polydyno 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
telemetry.py ADDED
@@ -0,0 +1,1531 @@
1
+ """Rich live dashboard and JSON export for polycracker-dyno runs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime, timezone
6
+ from pathlib import Path
7
+ from textwrap import dedent
8
+ from typing import Any
9
+
10
+ from autopsy import BlackBoxAutopsy, autopsy_diff_to_html, parse_retention_fraction
11
+ from workload import (
12
+ CANONICAL_WORKLOAD_VERIFICATION_HASH,
13
+ TURN_SPECS,
14
+ short_workload_verification_hash,
15
+ )
16
+ from pydantic import BaseModel, Field
17
+ from rich import box
18
+ from rich.console import Console, Group, RenderableType
19
+ from rich.live import Live
20
+ from rich.panel import Panel
21
+ from rich.table import Table
22
+ from rich.text import Text
23
+
24
+ DYNO_HEADER = "🏎️ POLYCRACKER DYNO — 50-TURN CONTEXT DRIFT & INVARIANT BENCHMARK"
25
+
26
+ LOAD_TORQUE_MULTIPLIER: dict[str, float] = {
27
+ "stage1": 0.4,
28
+ "stage2": 0.7,
29
+ "outlaw": 1.0,
30
+ }
31
+
32
+ THERMAL_GRADE_MULTIPLIER: dict[str, float] = {
33
+ "A+": 1.05,
34
+ "A": 1.00,
35
+ "B": 0.90,
36
+ "C": 0.75,
37
+ "D": 0.55,
38
+ "F": 0.30,
39
+ }
40
+
41
+ # BSFC / context runaway thresholds (scoring only — workload hash unchanged)
42
+ LEAN_RUN_INPUT_BUDGET = 250_000
43
+ CONTEXT_RUNAWAY_INPUT_CAP = 1_100_000
44
+ PRE_FAILURE_TOKEN_CAP = 100_000
45
+ QUADRATIC_BLOAT_INPUT_MIN = 22_000
46
+ QUADRATIC_BLOAT_IO_RATIO = 22.0
47
+ RECOVERY_PENALTY_COEFFICIENT = 1.25
48
+ EFFECTIVE_THERMAL_FLOOR = 0.45
49
+
50
+
51
+ class TurnRecord(BaseModel):
52
+ turn: int
53
+ latency_ms: float
54
+ input_tokens: int
55
+ output_tokens: int
56
+ cached_input_tokens: int = 0
57
+ cumulative_cost_usd: float
58
+ retention_score: str = "—"
59
+ invariant_intact: bool
60
+ thermal_efficiency_ratio: float = 0.0
61
+ token_multiplier: float = 0.0
62
+ thermal_bloat: bool = False
63
+ status: str | None = None
64
+ notes: str = ""
65
+ initial_failed_invariants: list[str] = Field(default_factory=list)
66
+ repair_attempts: int = 0
67
+ recovery_tokens: int = 0
68
+ cascading_regressions: int = 0
69
+ recovered_cleanly: bool = False
70
+ lines_added: int = 0
71
+ lines_removed: int = 0
72
+ net_diff_lines: int = 0
73
+ collateral_churn_chars: int = 0
74
+
75
+
76
+ class DynoRunSheet(BaseModel):
77
+ started_at: str
78
+ finished_at: str | None = None
79
+ provider: str
80
+ model: str
81
+ total_turns: int = 50
82
+ turns: list[TurnRecord] = Field(default_factory=list)
83
+ autopsy: BlackBoxAutopsy | None = None
84
+ workload_verification_hash: str | None = None
85
+ structural_torque: int | None = None
86
+ thermal_grade: str | None = None
87
+ polyscore: int | None = None
88
+ metadata: dict[str, Any] = Field(default_factory=dict)
89
+
90
+
91
+ class DynoDashboard:
92
+ """Live terminal dashboard for turn-by-turn dyno telemetry."""
93
+
94
+ def __init__(self, console: Console | None = None, total_turns: int = 50) -> None:
95
+ self.console = console or Console()
96
+ self.total_turns = total_turns
97
+ self.turns: list[TurnRecord] = []
98
+ self._live: Live | None = None
99
+
100
+ def _status_label(self, row: TurnRecord) -> str:
101
+ if row.status == "API_ERROR":
102
+ return "API ERROR"
103
+ if not row.invariant_intact:
104
+ if row.repair_attempts > 0:
105
+ return f"🔴 DRIFT ({row.repair_attempts}R)"
106
+ return "🔴 DRIFT"
107
+ if row.repair_attempts > 0:
108
+ if row.cascading_regressions > 0:
109
+ return f"🟠 REPAIRED ({row.repair_attempts}R/{row.cascading_regressions}C)"
110
+ return f"🟢 REPAIRED ({row.repair_attempts}R)"
111
+ if row.thermal_bloat:
112
+ return "🟡 BLOAT"
113
+ return "🟢 INTACT"
114
+
115
+ def _format_cost(self, cumulative_cost_usd: float) -> str:
116
+ return f"${cumulative_cost_usd:.4f}"
117
+
118
+ def _build_table(self) -> Table:
119
+ table = Table(
120
+ title=DYNO_HEADER,
121
+ box=box.ROUNDED,
122
+ show_lines=False,
123
+ expand=False,
124
+ pad_edge=False,
125
+ )
126
+ table.add_column("Turn", justify="center", style="bold cyan", no_wrap=True)
127
+ table.add_column("Tokens (In / Out)", justify="right", no_wrap=True)
128
+ table.add_column("Retention", justify="center", no_wrap=True)
129
+ table.add_column("Cost", justify="right", style="green", no_wrap=True)
130
+ table.add_column("Status", justify="center", no_wrap=True)
131
+
132
+ for row in self.turns:
133
+ table.add_row(
134
+ f"{row.turn:02d}/{self.total_turns}",
135
+ f"{row.input_tokens:,} / {row.output_tokens:,}",
136
+ row.retention_score,
137
+ self._format_cost(row.cumulative_cost_usd),
138
+ self._status_label(row),
139
+ )
140
+ if not self.turns:
141
+ table.add_row("—", "—", "—", "—", "—")
142
+ return table
143
+
144
+ def _drift_panel(self) -> Panel | None:
145
+ drift_rows = [row for row in self.turns if not row.invariant_intact]
146
+ if not drift_rows:
147
+ return None
148
+ drift = drift_rows[-1]
149
+ body = Text(drift.notes or "Invariant violation detected.", style="bold red")
150
+ return Panel(
151
+ body,
152
+ title=f"[bold red]Critical drift — turn {drift.turn:02d}/{self.total_turns}[/bold red]",
153
+ border_style="red",
154
+ padding=(1, 2),
155
+ )
156
+
157
+ def render(self) -> RenderableType:
158
+ table = self._build_table()
159
+ drift = self._drift_panel()
160
+ if drift is None:
161
+ return Panel(table, border_style="bright_blue")
162
+ return Panel(Group(table, drift), border_style="bright_blue")
163
+
164
+ def start(self) -> Live:
165
+ self._live = Live(self.render(), console=self.console, refresh_per_second=8)
166
+ self._live.start()
167
+ return self._live
168
+
169
+ def stop(self) -> None:
170
+ if self._live is not None:
171
+ self._live.stop()
172
+ self._live = None
173
+
174
+ def record_turn(self, row: TurnRecord) -> None:
175
+ self.turns.append(row)
176
+ if self._live is not None:
177
+ self._live.update(self.render())
178
+
179
+
180
+ def load_dyno_sheet(path: str | Path) -> DynoRunSheet:
181
+ return DynoRunSheet.model_validate_json(Path(path).read_text(encoding="utf-8"))
182
+
183
+
184
+ def export_dyno_sheet(sheet: DynoRunSheet, results_dir: str | Path = "results") -> Path:
185
+ out_dir = Path(results_dir)
186
+ out_dir.mkdir(parents=True, exist_ok=True)
187
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
188
+ path = out_dir / f"dyno_sheet_{stamp}.json"
189
+ path.write_text(sheet.model_dump_json(indent=2), encoding="utf-8")
190
+ return path
191
+
192
+
193
+ def _avg_retention_fraction(turns: list[TurnRecord]) -> float:
194
+ fractions: list[float] = []
195
+ for row in turns:
196
+ frac = parse_retention_fraction(row.retention_score)
197
+ if frac is not None:
198
+ fractions.append(frac)
199
+ if not fractions:
200
+ return 0.0
201
+ return sum(fractions) / len(fractions)
202
+
203
+
204
+ def _turn_bsfc_bloat(input_tokens: int, output_tokens: int, *, schema_sql: str | None = None) -> bool:
205
+ artifact_chars = max(len(schema_sql or ""), max(output_tokens, 0) * 4, 1)
206
+ io_ratio = input_tokens / max(output_tokens, 1)
207
+ char_bloat = input_tokens > (50 * artifact_chars)
208
+ return char_bloat or (
209
+ input_tokens > QUADRATIC_BLOAT_INPUT_MIN and io_ratio > QUADRATIC_BLOAT_IO_RATIO
210
+ )
211
+
212
+
213
+ def _refresh_turn_bsfc_flags(sheet: DynoRunSheet) -> None:
214
+ """Recompute per-turn BSFC multiplier and bloat flags (for rescoring saved sheets)."""
215
+ for row in sheet.turns:
216
+ out = max(row.output_tokens, 0)
217
+ artifact_tokens = max(out, 1)
218
+ row.token_multiplier = row.input_tokens / artifact_tokens
219
+ row.thermal_bloat = _turn_bsfc_bloat(row.input_tokens, row.output_tokens)
220
+
221
+
222
+ def _compute_bsfc_aggregate(sheet: DynoRunSheet) -> dict[str, float | int]:
223
+ turns = sheet.turns
224
+ if not turns:
225
+ return {
226
+ "total_input_tokens": 0,
227
+ "total_output_tokens": 0,
228
+ "yield_ratio": 0.0,
229
+ "avg_bsfc": 0.0,
230
+ "peak_bsfc": 0.0,
231
+ "bloat_turns": 0,
232
+ "bloat_frac": 0.0,
233
+ }
234
+ total_in = sum(t.input_tokens for t in turns)
235
+ total_out = sum(t.output_tokens for t in turns)
236
+ bsfc_values = [t.input_tokens / max(t.output_tokens, 1) for t in turns]
237
+ bloat_turns = sum(1 for t in turns if t.thermal_bloat)
238
+ return {
239
+ "total_input_tokens": total_in,
240
+ "total_output_tokens": total_out,
241
+ "yield_ratio": total_out / max(total_in, 1),
242
+ "avg_bsfc": sum(bsfc_values) / len(bsfc_values),
243
+ "peak_bsfc": max(bsfc_values),
244
+ "bloat_turns": bloat_turns,
245
+ "bloat_frac": bloat_turns / len(turns),
246
+ }
247
+
248
+
249
+ def _pre_failure_token_base(sheet: DynoRunSheet) -> int:
250
+ """Tokens burned before first unassisted drop (attempt 0 only on drop turn)."""
251
+ _, _, _, _, _, first_drop = _recovery_totals(sheet)
252
+ if first_drop is None:
253
+ return sum(t.input_tokens + t.output_tokens for t in sheet.turns)
254
+ total = 0
255
+ for row in sheet.turns:
256
+ if row.turn < first_drop:
257
+ total += row.input_tokens + row.output_tokens
258
+ elif row.turn == first_drop:
259
+ total += row.input_tokens + row.output_tokens - row.recovery_tokens
260
+ break
261
+ return max(total, 1)
262
+
263
+
264
+ def _post_failure_runaway_tokens(sheet: DynoRunSheet) -> int:
265
+ """All tokens burned on/after first drop, excluding explicit recovery overhead tally."""
266
+ _, _, total_recovery, _, _, first_drop = _recovery_totals(sheet)
267
+ if first_drop is None:
268
+ return 0
269
+ post = 0
270
+ for row in sheet.turns:
271
+ if row.turn >= first_drop:
272
+ post += row.input_tokens + row.output_tokens
273
+ return max(0, post - total_recovery)
274
+
275
+
276
+ def _recovery_totals(sheet: DynoRunSheet) -> tuple[int, int, int, int, int, int | None]:
277
+ """Return (total_retries, total_cascading, total_recovery_tokens, clean_recoveries, turns_with_failures, first_unassisted_drop)."""
278
+ turns = sheet.turns
279
+ total_retries = sum(t.repair_attempts for t in turns)
280
+ total_cascading = sum(t.cascading_regressions for t in turns)
281
+ total_recovery_tokens = sum(t.recovery_tokens for t in turns)
282
+ clean_recoveries = sum(1 for t in turns if t.recovered_cleanly)
283
+ turns_with_failures = sum(
284
+ 1 for t in turns if t.repair_attempts > 0 or not t.invariant_intact or t.initial_failed_invariants
285
+ )
286
+ first_unassisted_drop: int | None = None
287
+ for t in turns:
288
+ if t.repair_attempts > 0 or not t.invariant_intact or t.initial_failed_invariants:
289
+ first_unassisted_drop = t.turn
290
+ break
291
+ return (
292
+ total_retries,
293
+ total_cascading,
294
+ total_recovery_tokens,
295
+ clean_recoveries,
296
+ turns_with_failures,
297
+ first_unassisted_drop,
298
+ )
299
+
300
+
301
+ def _multiplier_to_thermal_grade(mult: float) -> str:
302
+ if mult >= 1.03:
303
+ return "A+"
304
+ if mult >= 0.95:
305
+ return "A"
306
+ if mult >= 0.82:
307
+ return "B"
308
+ if mult >= 0.65:
309
+ return "C"
310
+ if mult >= 0.45:
311
+ return "D"
312
+ return "F"
313
+
314
+
315
+ def compute_structural_torque(sheet: DynoRunSheet) -> int:
316
+ """PolyScore structural torque (0–1000), scaled by Eddy-Current load stage and anti-dilution penalties."""
317
+ turns = sheet.turns
318
+ if not turns:
319
+ return 0
320
+ load = str(sheet.metadata.get("load", sheet.metadata.get("profile", "stage2")))
321
+ if load in ("standard", "adversarial"):
322
+ load = "stage1" if load == "standard" else "stage2"
323
+ multiplier = LOAD_TORQUE_MULTIPLIER.get(load, 0.7)
324
+ benchmark_turns = max(len(TURN_SPECS), 1)
325
+ retention = _avg_retention_fraction(turns)
326
+
327
+ total_retries, total_cascading, total_recovery_tokens, _, _, _ = _recovery_totals(sheet)
328
+ # Zero-Retry Guard: 100% untouched formula when no retries/regressions/recovery tokens
329
+ if total_retries == 0 and total_cascading == 0 and total_recovery_tokens == 0:
330
+ intact = sum(1 for row in turns if row.invariant_intact)
331
+ turn_factor = intact / benchmark_turns
332
+ score = 1000.0 * multiplier * turn_factor * retention
333
+ return max(0, min(1000, int(round(score))))
334
+
335
+ # Anti-Dilution Scoring: turns requiring repair or completed after the first repair earn 25% gross structural weight
336
+ first_repair_turn = next(
337
+ (row.turn for row in turns if row.repair_attempts > 0 or row.initial_failed_invariants),
338
+ None,
339
+ )
340
+ weighted_intact = 0.0
341
+ for row in turns:
342
+ if not row.invariant_intact:
343
+ continue
344
+ if first_repair_turn is not None and row.turn >= first_repair_turn:
345
+ weighted_intact += 0.25
346
+ else:
347
+ weighted_intact += 1.0
348
+
349
+ total_input = sum(row.input_tokens for row in turns)
350
+ strict_context_runaway = total_input > LEAN_RUN_INPUT_BUDGET
351
+
352
+ if strict_context_runaway:
353
+ run_benchmark = max(min(len(turns), benchmark_turns), 1)
354
+ gross_torque = int(
355
+ round(1000.0 * multiplier * (weighted_intact / run_benchmark) * retention)
356
+ )
357
+ else:
358
+ intact_count = sum(1 for row in turns if row.invariant_intact)
359
+ unassisted_equiv_torque = 1000.0 * (weighted_intact / benchmark_turns) * retention
360
+ full_track_gross_torque = 1000.0 * multiplier * (intact_count / benchmark_turns) * retention
361
+ gross_torque = int(round((full_track_gross_torque * 0.5) + (unassisted_equiv_torque * 0.6)))
362
+
363
+ retry_tax = total_retries * 15
364
+ regression_penalty = total_cascading * 45
365
+ net_torque = max(0, gross_torque - retry_tax - regression_penalty)
366
+ return max(0, min(1000, net_torque))
367
+
368
+
369
+ def compute_effective_thermal(sheet: DynoRunSheet) -> tuple[str, float]:
370
+ """Return (thermal_grade, effective_thermal_multiplier) with recovery token overhead penalty."""
371
+ base_grade = compute_thermal_grade(sheet)
372
+ base_mult = thermal_grade_multiplier(base_grade)
373
+ total_retries, total_cascading, total_recovery_tokens, _, _, _ = _recovery_totals(sheet)
374
+ if total_retries == 0 and total_cascading == 0 and total_recovery_tokens == 0:
375
+ return base_grade, base_mult
376
+
377
+ total_in = sum(row.input_tokens for row in sheet.turns)
378
+ if total_in > LEAN_RUN_INPUT_BUDGET:
379
+ pre_failure_base = min(_pre_failure_token_base(sheet), PRE_FAILURE_TOKEN_CAP)
380
+ recovery_overhead_ratio = total_recovery_tokens / max(pre_failure_base, 1)
381
+ else:
382
+ turns = sheet.turns
383
+ total_tokens = sum(row.input_tokens + row.output_tokens for row in turns)
384
+ base_turn_tokens = max(1, total_tokens - total_recovery_tokens)
385
+ recovery_overhead_ratio = total_recovery_tokens / base_turn_tokens
386
+ penalized_mult = max(
387
+ EFFECTIVE_THERMAL_FLOOR,
388
+ base_mult - (recovery_overhead_ratio * RECOVERY_PENALTY_COEFFICIENT),
389
+ )
390
+ penalized_grade = _multiplier_to_thermal_grade(penalized_mult)
391
+ return penalized_grade, penalized_mult
392
+
393
+
394
+ def compute_thermal_grade(sheet: DynoRunSheet) -> str:
395
+ """PolyScore thermal letter grade from BSFC / cumulative token burn."""
396
+ turns = sheet.turns
397
+ if not turns:
398
+ return "F"
399
+ agg = _compute_bsfc_aggregate(sheet)
400
+ total_in = int(agg["total_input_tokens"])
401
+ yield_ratio = float(agg["yield_ratio"])
402
+ bloat_frac = float(agg["bloat_frac"])
403
+ avg_eff = sum(row.thermal_efficiency_ratio for row in turns) / len(turns)
404
+
405
+ if yield_ratio < 0.025 or bloat_frac >= 0.55:
406
+ return "F"
407
+ if total_in > CONTEXT_RUNAWAY_INPUT_CAP or yield_ratio < 0.035 or bloat_frac >= 0.45:
408
+ return "D"
409
+ if total_in > LEAN_RUN_INPUT_BUDGET or yield_ratio < 0.042 or bloat_frac >= 0.30:
410
+ return "C"
411
+ if total_in > 450_000 or yield_ratio < 0.05 or bloat_frac >= 0.15:
412
+ return "B"
413
+ if total_in <= 150_000 and bloat_frac < 0.05 and yield_ratio >= 0.06 and avg_eff >= 0.06:
414
+ return "A+"
415
+ if total_in <= LEAN_RUN_INPUT_BUDGET and yield_ratio >= 0.05:
416
+ return "A"
417
+ return "B"
418
+
419
+
420
+ def thermal_grade_multiplier(thermal_grade: str) -> float:
421
+ return THERMAL_GRADE_MULTIPLIER.get(thermal_grade, THERMAL_GRADE_MULTIPLIER["F"])
422
+
423
+
424
+ def calculate_polyscore(
425
+ structural_torque: int,
426
+ thermal_grade: str,
427
+ *,
428
+ thermal_multiplier_override: float | None = None,
429
+ ) -> int:
430
+ """Headline PolyScore (0–1000): structural torque adjusted by thermal grade."""
431
+ multiplier = (
432
+ thermal_multiplier_override
433
+ if thermal_multiplier_override is not None
434
+ else thermal_grade_multiplier(thermal_grade)
435
+ )
436
+ raw = round(structural_torque * multiplier)
437
+ return max(0, min(1000, raw))
438
+
439
+
440
+ def _output_efficiency_totals(sheet: DynoRunSheet) -> dict[str, Any]:
441
+ """Aggregate isolated Output Efficiency metrics without touching PolyScore or Torque."""
442
+ turns = sheet.turns
443
+ n = max(len(turns), 1)
444
+ total_added = sum(t.lines_added for t in turns)
445
+ total_removed = sum(t.lines_removed for t in turns)
446
+ total_net_diff = sum(t.net_diff_lines for t in turns)
447
+ total_churn = sum(t.collateral_churn_chars for t in turns)
448
+ peak_turn = max(turns, key=lambda t: t.collateral_churn_chars, default=None)
449
+ return {
450
+ "total_lines_added": total_added,
451
+ "total_lines_removed": total_removed,
452
+ "total_net_diff_lines": total_net_diff,
453
+ "avg_lines_added": round(total_added / n, 2),
454
+ "avg_lines_removed": round(total_removed / n, 2),
455
+ "avg_net_diff_lines": round(total_net_diff / n, 2),
456
+ "total_collateral_churn_chars": total_churn,
457
+ "avg_collateral_churn_chars": round(total_churn / n, 1),
458
+ "peak_churn_turn": peak_turn.turn if peak_turn is not None else None,
459
+ "peak_churn_chars": peak_turn.collateral_churn_chars if peak_turn is not None else 0,
460
+ }
461
+
462
+
463
+ def finalize_polyscore(sheet: DynoRunSheet) -> None:
464
+ _refresh_turn_bsfc_flags(sheet)
465
+ agg = _compute_bsfc_aggregate(sheet)
466
+ pre_failure = _pre_failure_token_base(sheet)
467
+ post_failure = _post_failure_runaway_tokens(sheet)
468
+ total_retries, _, total_recovery, _, _, first_drop = _recovery_totals(sheet)
469
+ sheet.metadata["bsfc_avg"] = round(float(agg["avg_bsfc"]), 2)
470
+ sheet.metadata["bsfc_peak"] = round(float(agg["peak_bsfc"]), 2)
471
+ sheet.metadata["yield_ratio"] = round(float(agg["yield_ratio"]), 4)
472
+ sheet.metadata["bloat_turns"] = int(agg["bloat_turns"])
473
+ sheet.metadata["pre_failure_tokens"] = pre_failure
474
+ sheet.metadata["post_failure_runaway_tokens"] = post_failure
475
+ sheet.metadata["output_efficiency"] = _output_efficiency_totals(sheet)
476
+ if first_drop is not None and pre_failure > 0:
477
+ sheet.metadata["context_runaway_factor"] = round(
478
+ int(agg["total_input_tokens"]) / pre_failure,
479
+ 2,
480
+ )
481
+ recovery_anchor = min(pre_failure, PRE_FAILURE_TOKEN_CAP)
482
+ if total_recovery > 0 and recovery_anchor > 0:
483
+ sheet.metadata["recovery_overhead_vs_predrop_pct"] = round(
484
+ 100.0 * total_recovery / recovery_anchor,
485
+ 1,
486
+ )
487
+
488
+ sheet.structural_torque = compute_structural_torque(sheet)
489
+ base_grade = compute_thermal_grade(sheet)
490
+ grade, effective_mult = compute_effective_thermal(sheet)
491
+ sheet.thermal_grade = grade
492
+ sheet.metadata["base_thermal_grade"] = base_grade
493
+ sheet.metadata["effective_thermal_multiplier"] = round(effective_mult, 4)
494
+ sheet.polyscore = calculate_polyscore(
495
+ sheet.structural_torque,
496
+ sheet.thermal_grade,
497
+ thermal_multiplier_override=effective_mult,
498
+ )
499
+
500
+
501
+ def workload_verification_badge(sheet: DynoRunSheet) -> str:
502
+ full = sheet.workload_verification_hash or ""
503
+ short = short_workload_verification_hash(full) if full else "unknown"
504
+ if full and full == CANONICAL_WORKLOAD_VERIFICATION_HASH:
505
+ return f"🔒 VERIFIED CANONICAL WORKLOAD [{short}]"
506
+ if full:
507
+ return f"🔒 CUSTOM WORKLOAD [{short}]"
508
+ return "🔒 WORKLOAD UNVERIFIED"
509
+
510
+
511
+ def _first_drift_turn(sheet: DynoRunSheet) -> int | None:
512
+ for row in sheet.turns:
513
+ if not row.invariant_intact:
514
+ return row.turn
515
+ return None
516
+
517
+
518
+ def _ascii_token_curve(values: list[int], width: int = 48) -> str:
519
+ if not values:
520
+ return "(no data)"
521
+ blocks = "▁▂▃▄▅▆▇█"
522
+ lo = min(values)
523
+ hi = max(values)
524
+ if hi == lo:
525
+ return blocks[0] * min(len(values), width)
526
+ step = max(len(values) // width, 1)
527
+ sampled = values[::step][:width]
528
+ lines: list[str] = []
529
+ for value in sampled:
530
+ idx = int((value - lo) / (hi - lo) * (len(blocks) - 1))
531
+ lines.append(blocks[idx])
532
+ return "".join(lines)
533
+
534
+
535
+ def _sheet_summary_row(label: str, sheet: DynoRunSheet) -> dict[str, str]:
536
+ turns = sheet.turns
537
+ total_in = sum(t.input_tokens for t in turns)
538
+ total_cached = sum(t.cached_input_tokens for t in turns)
539
+ total_out = sum(t.output_tokens for t in turns)
540
+ drift = _first_drift_turn(sheet)
541
+ load_stage = sheet.metadata.get("load", sheet.metadata.get("profile", "n/a"))
542
+ intact = sum(1 for t in turns if t.invariant_intact)
543
+ avg_eff = sum(t.thermal_efficiency_ratio for t in turns) / len(turns) if turns else 0.0
544
+ avg_mult = sum(t.token_multiplier for t in turns) / len(turns) if turns else 0.0
545
+ bloat_turns = sum(1 for t in turns if t.thermal_bloat)
546
+ torque = sheet.structural_torque
547
+ if torque is None:
548
+ torque = compute_structural_torque(sheet)
549
+ eff_grade, eff_mult = compute_effective_thermal(sheet)
550
+ grade = sheet.thermal_grade or eff_grade
551
+ thermal_mult = float(sheet.metadata.get("effective_thermal_multiplier", eff_mult))
552
+ score = sheet.polyscore
553
+ if score is None:
554
+ score = calculate_polyscore(torque, grade, thermal_multiplier_override=thermal_mult)
555
+ w_hash = sheet.workload_verification_hash or "n/a"
556
+ invariant_mode = str(sheet.metadata.get("invariant_mode", "baseline"))
557
+ total_retries, total_cascading, total_recovery_tokens, clean_recoveries, turns_with_failures, first_drop = _recovery_totals(sheet)
558
+ base_tokens = max(1, (total_in + total_out) - total_recovery_tokens)
559
+ overhead_pct = (total_recovery_tokens / base_tokens) * 100.0 if total_recovery_tokens > 0 else 0.0
560
+ return {
561
+ "label": label,
562
+ "model": f"{sheet.provider}/{sheet.model}",
563
+ "polyscore": str(score),
564
+ "structural_torque": str(torque),
565
+ "thermal_grade": grade,
566
+ "thermal_multiplier": f"{thermal_mult:.2f}",
567
+ "workload_hash": short_workload_verification_hash(w_hash)
568
+ if w_hash not in ("", "n/a")
569
+ else "n/a",
570
+ "turns": str(len(turns)),
571
+ "load": str(load_stage),
572
+ "profile": str(load_stage),
573
+ "invariant_mode": invariant_mode,
574
+ "drift_turn": str(drift) if drift else "none",
575
+ "first_unassisted_drop": str(first_drop) if first_drop else "none",
576
+ "total_retries": str(total_retries),
577
+ "recovery_tokens": f"+{total_recovery_tokens:,} ({overhead_pct:.1f}%)",
578
+ "clean_recoveries": f"{clean_recoveries}/{turns_with_failures}",
579
+ "cascading_regressions": str(total_cascading),
580
+ "pass_rate": f"{intact}/{len(turns)}" if turns else "0/0",
581
+ "input_tokens": f"{total_in:,}",
582
+ "cached_input_tokens": f"{total_cached:,}",
583
+ "output_tokens": f"{total_out:,}",
584
+ "final_cost": f"${turns[-1].cumulative_cost_usd:.4f}" if turns else "$0.0000",
585
+ "thermal_efficiency": f"{avg_eff:.4f}",
586
+ "token_multiplier": f"{avg_mult:.1f}x",
587
+ "thermal_bloat_turns": str(bloat_turns),
588
+ }
589
+
590
+
591
+ def _readme_badge_snippet(sheet: DynoRunSheet) -> str:
592
+ drift = _first_drift_turn(sheet)
593
+ intact = all(t.invariant_intact for t in sheet.turns) if sheet.turns else False
594
+ if intact and drift is None:
595
+ badge = "![Polycracker Dyno](https://img.shields.io/badge/dyno-invariants%20intact-brightgreen)"
596
+ status = "passing"
597
+ else:
598
+ turn = drift if drift is not None else "?"
599
+ badge = (
600
+ f"![Polycracker Dyno]"
601
+ f"(https://img.shields.io/badge/dyno-drift%20turn%20{turn}-red)"
602
+ )
603
+ status = "drift"
604
+ return f"""### README badge snippet ({status})
605
+
606
+ ```markdown
607
+ {badge}
608
+ ```
609
+ """
610
+
611
+
612
+ def _cta_footer_markdown() -> str:
613
+ return dedent(
614
+ """
615
+ ---
616
+
617
+ ## Polycracker
618
+
619
+ > **Stop Context Detonation.** Eliminate multi-turn drift and cut token overhead with the
620
+ > **Polycracker MCP Server** → [polycracker.dev](https://polycracker.dev)
621
+ """
622
+ ).strip()
623
+
624
+
625
+ def _telemetry_table_markdown(sheet: DynoRunSheet) -> str:
626
+ header = (
627
+ "| Turn | Input | Output | Cached In | Retries | Recov Tok | Cascading | Retention | Cost | Status |\n"
628
+ "| ---: | ---: | ---: | ---: | ---: | ---: | ---: | :---: | ---: | :---: |"
629
+ )
630
+ rows: list[str] = []
631
+ for t in sheet.turns:
632
+ if t.status == "API_ERROR":
633
+ status = "API_ERROR"
634
+ elif not t.invariant_intact:
635
+ status = f"DRIFT ({t.repair_attempts}R)" if t.repair_attempts > 0 else "DRIFT"
636
+ elif t.repair_attempts > 0:
637
+ status = (
638
+ f"REPAIRED ({t.repair_attempts}R/{t.cascading_regressions}C)"
639
+ if t.cascading_regressions > 0
640
+ else f"REPAIRED ({t.repair_attempts}R)"
641
+ )
642
+ elif t.thermal_bloat:
643
+ status = "BLOAT"
644
+ else:
645
+ status = "INTACT"
646
+ rows.append(
647
+ f"| {t.turn} | {t.input_tokens:,} | {t.output_tokens:,} | {t.cached_input_tokens:,} "
648
+ f"| {t.repair_attempts} | {t.recovery_tokens:,} | {t.cascading_regressions} "
649
+ f"| {t.retention_score} | ${t.cumulative_cost_usd:.4f} | {status} |"
650
+ )
651
+ return header + "\n" + "\n".join(rows)
652
+
653
+
654
+ def _kpi_block_markdown(row: dict[str, str]) -> str:
655
+ return dedent(
656
+ f"""
657
+ ### PolyScore — {row["label"]}
658
+
659
+ - **PolyScore:** **{row["polyscore"]}** / 1000
660
+ - **Breakdown:** Torque {row["structural_torque"]}/1000 · Thermal {row["thermal_grade"]} (×{row["thermal_multiplier"]}) · Load `{row["load"]}` · Mode `{row["invariant_mode"]}`
661
+ - **Workload verification:** `{row["workload_hash"]}`
662
+
663
+ ### KPI summary — {row["label"]}
664
+
665
+ - **Model:** `{row["model"]}`
666
+ - **Eddy-Current load:** `{row["load"]}`
667
+ - **Invariant mode:** `{row["invariant_mode"]}`
668
+ - **Turns completed:** {row["turns"]}
669
+ - **Invariant pass rate:** {row["pass_rate"]}
670
+ - **First unassisted drop:** {row["first_unassisted_drop"]}
671
+ - **Terminal drift turn:** {row["drift_turn"]}
672
+ - **Total repair retries:** {row["total_retries"]}
673
+ - **Recovery token overhead:** {row["recovery_tokens"]}
674
+ - **Clean recoveries:** {row["clean_recoveries"]}
675
+ - **Cascading regressions:** {row["cascading_regressions"]}
676
+ - **Total input tokens:** {row["input_tokens"]}
677
+ - **Cached input tokens:** {row["cached_input_tokens"]}
678
+ - **Total output tokens:** {row["output_tokens"]}
679
+ - **Final cost (USD):** {row["final_cost"]}
680
+ - **Avg thermal efficiency:** {row["thermal_efficiency"]}
681
+ - **Avg token multiplier:** {row["token_multiplier"]}
682
+ - **Thermal bloat turns:** {row["thermal_bloat_turns"]}
683
+ """
684
+ ).strip()
685
+
686
+
687
+ def _autopsy_markdown(sheet: DynoRunSheet) -> str:
688
+ if sheet.autopsy is None:
689
+ return "_No Black Box Autopsy recorded (run completed without invariant drift)._"
690
+ autopsy = sheet.autopsy
691
+ noise = autopsy.adversarial_context_noise or "(no context noise captured)"
692
+ diff = autopsy.unified_diff or "(empty diff)"
693
+ return dedent(
694
+ f"""
695
+ ## Black Box Autopsy (turn {autopsy.previous_turn:02d} → {autopsy.drift_turn:02d})
696
+
697
+ ### Adversarial context at drift
698
+
699
+ ```
700
+ {noise.strip()}
701
+ ```
702
+
703
+ ### Unified SQL diff
704
+
705
+ ```diff
706
+ {diff.strip()}
707
+ ```
708
+ """
709
+ ).strip()
710
+
711
+
712
+ def export_markdown_report(
713
+ sheet: DynoRunSheet,
714
+ results_dir: str | Path = "results",
715
+ *,
716
+ compare_sheet: DynoRunSheet | None = None,
717
+ ) -> Path:
718
+ """Export GitHub-flavored Markdown dyno report for one run (optional head-to-head compare)."""
719
+ out_root = Path(results_dir)
720
+ if out_root.suffix.lower() == ".md":
721
+ out_path = out_root
722
+ else:
723
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
724
+ out_path = out_root / f"dyno_report_{stamp}.md"
725
+ out_path.parent.mkdir(parents=True, exist_ok=True)
726
+
727
+ row = _sheet_summary_row("Run", sheet)
728
+ sparkline = _ascii_token_curve([t.input_tokens for t in sheet.turns])
729
+ title = (
730
+ "# Polycracker Dyno — Head-to-Head Report"
731
+ if compare_sheet is not None
732
+ else "# Polycracker Dyno — Run Report"
733
+ )
734
+
735
+ sections = [
736
+ title,
737
+ "",
738
+ f"Generated: `{datetime.now(timezone.utc).isoformat()}` ",
739
+ f"Run window: `{sheet.started_at}` → `{sheet.finished_at or 'n/a'}`",
740
+ "",
741
+ f"> {workload_verification_badge(sheet)}",
742
+ "",
743
+ _readme_badge_snippet(sheet),
744
+ "",
745
+ _kpi_block_markdown(row),
746
+ "",
747
+ "### Input token growth (ASCII)",
748
+ "",
749
+ "```text",
750
+ sparkline,
751
+ "```",
752
+ "",
753
+ "## Turn telemetry",
754
+ "",
755
+ _telemetry_table_markdown(sheet),
756
+ "",
757
+ _autopsy_markdown(sheet),
758
+ ]
759
+
760
+ if compare_sheet is not None:
761
+ row_b = _sheet_summary_row("Run B", compare_sheet)
762
+ curve_a = _ascii_token_curve([t.input_tokens for t in sheet.turns])
763
+ curve_b = _ascii_token_curve([t.input_tokens for t in compare_sheet.turns])
764
+ sections.extend(
765
+ [
766
+ "",
767
+ "## Head-to-head comparison",
768
+ "",
769
+ "| Metric | Run A | Run B |",
770
+ "| --- | --- | --- |",
771
+ f"| Model | `{row['model']}` | `{row_b['model']}` |",
772
+ f"| Load | `{row['load']}` | `{row_b['load']}` |",
773
+ f"| Invariant mode | `{row['invariant_mode']}` | `{row_b['invariant_mode']}` |",
774
+ f"| PolyScore | **{row['polyscore']}** | **{row_b['polyscore']}** |",
775
+ f"| Turns | {row['turns']} | {row_b['turns']} |",
776
+ f"| First unassisted drop | {row['first_unassisted_drop']} | {row_b['first_unassisted_drop']} |",
777
+ f"| Terminal drift turn | {row['drift_turn']} | {row_b['drift_turn']} |",
778
+ f"| Repair retries | {row['total_retries']} | {row_b['total_retries']} |",
779
+ f"| Cascading regressions | {row['cascading_regressions']} | {row_b['cascading_regressions']} |",
780
+ f"| Recovery overhead | {row['recovery_tokens']} | {row_b['recovery_tokens']} |",
781
+ f"| Input tokens | {row['input_tokens']} | {row_b['input_tokens']} |",
782
+ f"| Final cost | {row['final_cost']} | {row_b['final_cost']} |",
783
+ "",
784
+ "```text",
785
+ f"A: {curve_a}",
786
+ f"B: {curve_b}",
787
+ "```",
788
+ ]
789
+ )
790
+
791
+ sections.extend(["", _cta_footer_markdown(), ""])
792
+ out_path.write_text("\n".join(sections), encoding="utf-8")
793
+ return out_path
794
+
795
+
796
+ def export_markdown_report_from_paths(
797
+ sheet_a_path: str | Path,
798
+ sheet_b_path: str | Path,
799
+ results_dir: str | Path = "results",
800
+ ) -> Path:
801
+ """Compare two dyno sheet JSON files in a Markdown report."""
802
+ return export_markdown_report(
803
+ load_dyno_sheet(sheet_a_path),
804
+ results_dir,
805
+ compare_sheet=load_dyno_sheet(sheet_b_path),
806
+ )
807
+
808
+
809
+ def render_summary(sheet: DynoRunSheet, console: Console | None = None) -> None:
810
+ console = console or Console()
811
+ turns = sheet.turns
812
+ if not turns:
813
+ console.print("[yellow]No turn data to summarize.[/yellow]")
814
+ return
815
+
816
+ total_input = sum(t.input_tokens for t in turns)
817
+ total_cached = sum(t.cached_input_tokens for t in turns)
818
+ total_output = sum(t.output_tokens for t in turns)
819
+ total_latency = sum(t.latency_ms for t in turns)
820
+ final_cost = turns[-1].cumulative_cost_usd
821
+ intact_count = sum(1 for t in turns if t.invariant_intact)
822
+ drift_turns = [t.turn for t in turns if not t.invariant_intact]
823
+ first_drift = drift_turns[0] if drift_turns else None
824
+
825
+ summary = Table(title="Dyno Benchmark Summary", box=box.ROUNDED, expand=False)
826
+ summary.add_column("Metric", style="bold", no_wrap=True)
827
+ summary.add_column("Value", justify="right", no_wrap=True)
828
+ load_stage = sheet.metadata.get("load", sheet.metadata.get("profile", "n/a"))
829
+ avg_eff = sum(t.thermal_efficiency_ratio for t in turns) / len(turns)
830
+ _refresh_turn_bsfc_flags(sheet)
831
+ agg = _compute_bsfc_aggregate(sheet)
832
+ avg_bsfc = float(agg["avg_bsfc"])
833
+ peak_bsfc = float(agg["peak_bsfc"])
834
+ yield_ratio = float(agg["yield_ratio"])
835
+ bloat_turns = int(agg["bloat_turns"])
836
+ torque = sheet.structural_torque if sheet.structural_torque is not None else compute_structural_torque(sheet)
837
+ eff_grade, eff_mult = compute_effective_thermal(sheet)
838
+ grade = sheet.thermal_grade or eff_grade
839
+ thermal_mult = float(sheet.metadata.get("effective_thermal_multiplier", eff_mult))
840
+ score = (
841
+ sheet.polyscore
842
+ if sheet.polyscore is not None
843
+ else calculate_polyscore(torque, grade, thermal_multiplier_override=thermal_mult)
844
+ )
845
+ verify_badge = workload_verification_badge(sheet)
846
+
847
+ hero = Text()
848
+ hero.append("🏎️ POLYSCORE: ", style="bold")
849
+ hero.append(f"{score}", style="bold bright_green")
850
+ hero.append(" / 1000", style="bold")
851
+ hero.append("\n")
852
+ hero.append(
853
+ f"(Torque: {torque}/1000 | Thermal: {grade} [x{thermal_mult:.2f}] | Load: {load_stage})",
854
+ style="dim",
855
+ )
856
+ hero.append("\n")
857
+ hero.append(verify_badge, style="cyan")
858
+ polyscore_hero = Panel(hero, border_style="bright_green", padding=(1, 2))
859
+
860
+ summary.add_row("Eddy-Current load", str(load_stage))
861
+ summary.add_row("Provider / Model", f"{sheet.provider} / {sheet.model}")
862
+ summary.add_row("Turns completed", str(len(turns)))
863
+ summary.add_row("Effective yield (out/in)", f"{yield_ratio:.1%}")
864
+ summary.add_row("BSFC token bloat (in/out)", f"{avg_bsfc:.1f}x avg (peak {peak_bsfc:.1f}x)")
865
+ summary.add_row("Avg thermal efficiency", f"{avg_eff:.4f}")
866
+ summary.add_row("Thermal bloat turns", str(bloat_turns))
867
+ runaway = sheet.metadata.get("context_runaway_factor")
868
+ if runaway is not None:
869
+ summary.add_row("Context runaway vs pre-drop", f"{runaway:.1f}x total input")
870
+ post_fail = sheet.metadata.get("post_failure_runaway_tokens")
871
+ if post_fail:
872
+ summary.add_row("Post-failure token burn", f"{int(post_fail):,} tokens")
873
+ summary.add_row("Invariant intact rate", f"{intact_count}/{len(turns)}")
874
+ summary.add_row("First drift turn", str(first_drift) if first_drift else "none")
875
+ summary.add_row("Total input tokens", f"{total_input:,}")
876
+ summary.add_row("Cached input tokens", f"{total_cached:,}")
877
+ summary.add_row("Total output tokens", f"{total_output:,}")
878
+ summary.add_row("Total latency (ms)", f"{total_latency:,.1f}")
879
+ summary.add_row("Final cumulative cost (USD)", f"${final_cost:.4f}")
880
+
881
+ invariant_mode = str(sheet.metadata.get("invariant_mode", "baseline"))
882
+ max_retries_cfg = int(sheet.metadata.get("max_retries", 0) or 0)
883
+ (
884
+ total_retries,
885
+ total_cascading,
886
+ total_recovery_tokens,
887
+ clean_recoveries,
888
+ turns_with_failures,
889
+ first_unassisted_drop,
890
+ ) = _recovery_totals(sheet)
891
+ recovery_anchor = min(_pre_failure_token_base(sheet), PRE_FAILURE_TOKEN_CAP)
892
+ overhead_pct = (
893
+ (total_recovery_tokens / recovery_anchor) * 100.0
894
+ if total_recovery_tokens > 0 and recovery_anchor > 0
895
+ else 0.0
896
+ )
897
+ thermal_penalty_pct = overhead_pct * RECOVERY_PENALTY_COEFFICIENT
898
+ base_thermal = str(sheet.metadata.get("base_thermal_grade", grade))
899
+ retry_and_regression_tax = (total_retries * 15) + (total_cascading * 45)
900
+
901
+ containment = Table(
902
+ title="POST-FAILURE CONTAINMENT & RECOVERY",
903
+ box=box.ROUNDED,
904
+ expand=False,
905
+ )
906
+ containment.add_column("Metric", style="bold", no_wrap=True)
907
+ containment.add_column("Value", justify="right", no_wrap=True)
908
+ if invariant_mode == "baseline" and max_retries_cfg == 0 and total_retries == 0:
909
+ containment.add_row("Invariant Mode", "baseline")
910
+ containment.add_row("Self-Repair Status", "N/A (Unassisted Baseline)")
911
+ containment.add_row(
912
+ "First Unassisted Drop",
913
+ f"Turn {first_unassisted_drop}" if first_unassisted_drop else "none",
914
+ )
915
+ containment.add_row(
916
+ "Terminal Drift Turn",
917
+ f"Turn {first_drift}" if first_drift else "none",
918
+ )
919
+ else:
920
+ containment.add_row("Invariant Mode", invariant_mode)
921
+ containment.add_row(
922
+ "First Unassisted Drop",
923
+ f"Turn {first_unassisted_drop}" if first_unassisted_drop else "none",
924
+ )
925
+ containment.add_row(
926
+ "Terminal Drift Turn",
927
+ f"Turn {first_drift}" if first_drift else "none",
928
+ )
929
+ containment.add_row("Total Repair Retries", str(total_retries))
930
+ containment.add_row(
931
+ "Recovery Token Overhead",
932
+ f"+{total_recovery_tokens:,} tokens (+{overhead_pct:.1f}% vs pre-drop · -{thermal_penalty_pct:.1f}% thermal mult)",
933
+ )
934
+ containment.add_row(
935
+ "Thermal grade (base → effective)",
936
+ f"{base_thermal} → {grade} [x{thermal_mult:.2f}]",
937
+ )
938
+ containment.add_row(
939
+ "Clean Recoveries",
940
+ f"{clean_recoveries} / {turns_with_failures}",
941
+ )
942
+ containment.add_row(
943
+ "Cascading Regressions",
944
+ f"{total_cascading} (Secondary invariants broken)",
945
+ )
946
+ containment.add_row(
947
+ "Retry & Regression Tax",
948
+ f"-{retry_and_regression_tax} pts ({total_retries} retries, {total_cascading} cascading breaks)",
949
+ )
950
+
951
+ drift_line = Text()
952
+ if first_drift:
953
+ drift_line.append("Critical drift detected", style="bold red")
954
+ drift_line.append(f" starting at turn {first_drift}.")
955
+ else:
956
+ drift_line.append("All turns preserved fk_user_id.", style="bold green")
957
+
958
+ input_curve = [t.input_tokens for t in turns]
959
+ sparkline = _ascii_token_curve(input_curve)
960
+ spark_panel = Panel(
961
+ Text.from_markup(
962
+ f"[bold]Input token trend[/bold] [cyan]{sparkline}[/cyan]\n"
963
+ f"[dim]min {min(input_curve):,} → max {max(input_curve):,} tokens "
964
+ f"({len(turns)} turns)[/dim]"
965
+ ),
966
+ title="Context inflation sparkline",
967
+ border_style="cyan",
968
+ padding=(0, 1),
969
+ )
970
+
971
+ out_eff = _output_efficiency_totals(sheet)
972
+ output_efficiency_table = Table(
973
+ title="OUTPUT EFFICIENCY (ISOLATED)",
974
+ box=box.ROUNDED,
975
+ expand=False,
976
+ )
977
+ output_efficiency_table.add_column("Metric", style="bold", no_wrap=True)
978
+ output_efficiency_table.add_column("Value", justify="right", no_wrap=True)
979
+ output_efficiency_table.add_row(
980
+ "Net Diff (Cumulative)",
981
+ f"+{out_eff['total_lines_added']:,} / -{out_eff['total_lines_removed']:,} lines "
982
+ f"({out_eff['total_net_diff_lines']:,} lines touched)",
983
+ )
984
+ output_efficiency_table.add_row(
985
+ "Avg Net Diff / Turn",
986
+ f"+{out_eff['avg_lines_added']:.1f} / -{out_eff['avg_lines_removed']:.1f} lines "
987
+ f"({out_eff['avg_net_diff_lines']:.1f} avg)",
988
+ )
989
+ output_efficiency_table.add_row(
990
+ "Collateral Churn (Excess Edit Dist)",
991
+ f"{out_eff['total_collateral_churn_chars']:,} chars rewritten "
992
+ f"({out_eff['avg_collateral_churn_chars']:,.1f}/turn)",
993
+ )
994
+ peak_turn_label = (
995
+ f"Turn {out_eff['peak_churn_turn']} ({out_eff['peak_churn_chars']:,} chars)"
996
+ if out_eff["peak_churn_turn"] is not None
997
+ else "none"
998
+ )
999
+ output_efficiency_table.add_row("Peak Turn Churn", peak_turn_label)
1000
+
1001
+ parts: list[RenderableType] = [
1002
+ polyscore_hero,
1003
+ output_efficiency_table,
1004
+ summary,
1005
+ containment,
1006
+ spark_panel,
1007
+ drift_line,
1008
+ ]
1009
+ first_drift_row = next((t for t in turns if not t.invariant_intact), None)
1010
+ if first_drift_row is not None:
1011
+ parts.append(
1012
+ Panel(
1013
+ Text(first_drift_row.notes, style="bold red"),
1014
+ title=f"[bold red]Invariant dropped — turn {first_drift_row.turn:02d}[/bold red]",
1015
+ border_style="red",
1016
+ padding=(1, 2),
1017
+ )
1018
+ )
1019
+
1020
+ console.print()
1021
+ console.print(Panel(Group(*parts), border_style="green"))
1022
+
1023
+
1024
+ def _cumulative_torque_series(sheet: DynoRunSheet) -> list[int]:
1025
+ """Compute progressive Structural Torque at each turn 1..N for the Power Band chart."""
1026
+ turns = sheet.turns
1027
+ if not turns:
1028
+ return []
1029
+ series: list[int] = []
1030
+ for idx in range(1, len(turns) + 1):
1031
+ partial = DynoRunSheet(
1032
+ started_at=sheet.started_at,
1033
+ finished_at=sheet.finished_at,
1034
+ provider=sheet.provider,
1035
+ model=sheet.model,
1036
+ total_turns=sheet.total_turns,
1037
+ turns=turns[:idx],
1038
+ metadata=dict(sheet.metadata),
1039
+ )
1040
+ series.append(compute_structural_torque(partial))
1041
+ return series
1042
+
1043
+
1044
+ def export_html_dyno_chart(
1045
+ sheet: DynoRunSheet,
1046
+ results_dir: str | Path = "results",
1047
+ ) -> Path:
1048
+ """Self-contained dark-mode HTML dashboard with dual Chart.js dyno plots."""
1049
+ turns = sheet.turns
1050
+ labels = [str(t.turn) for t in turns]
1051
+ input_tokens = [t.input_tokens for t in turns]
1052
+ recovery_tokens_series = [t.recovery_tokens for t in turns]
1053
+ repair_attempts_series = [t.repair_attempts for t in turns]
1054
+ cascading_series = [t.cascading_regressions for t in turns]
1055
+ costs = [t.cumulative_cost_usd for t in turns]
1056
+ collateral_churn_series = [t.collateral_churn_chars for t in turns]
1057
+ net_diff_series = [t.net_diff_lines for t in turns]
1058
+ lines_added_series = [t.lines_added for t in turns]
1059
+ lines_removed_series = [t.lines_removed for t in turns]
1060
+ torque_series = _cumulative_torque_series(sheet)
1061
+ retention_pct = []
1062
+ for t in turns:
1063
+ frac = parse_retention_fraction(t.retention_score)
1064
+ retention_pct.append(round(frac * 100, 2) if frac is not None else None)
1065
+
1066
+ out_eff = _output_efficiency_totals(sheet)
1067
+ peak_churn_label = (
1068
+ f"Turn {out_eff['peak_churn_turn']} ({out_eff['peak_churn_chars']:,} chars)"
1069
+ if out_eff["peak_churn_turn"] is not None
1070
+ else "none"
1071
+ )
1072
+
1073
+ drift_turn = _first_drift_turn(sheet)
1074
+ total_input = sum(t.input_tokens for t in turns)
1075
+ total_output = sum(t.output_tokens for t in turns)
1076
+ intact = sum(1 for t in turns if t.invariant_intact)
1077
+ final_cost = turns[-1].cumulative_cost_usd if turns else 0.0
1078
+ pass_rate = f"{intact}/{len(turns)}" if turns else "0/0"
1079
+ load_stage = sheet.metadata.get("load", sheet.metadata.get("profile", "n/a"))
1080
+ invariant_mode = str(sheet.metadata.get("invariant_mode", "baseline"))
1081
+ (
1082
+ total_retries,
1083
+ total_cascading,
1084
+ total_recovery_tokens,
1085
+ clean_recoveries,
1086
+ turns_with_failures,
1087
+ first_unassisted_drop,
1088
+ ) = _recovery_totals(sheet)
1089
+ _refresh_turn_bsfc_flags(sheet)
1090
+ agg = _compute_bsfc_aggregate(sheet)
1091
+ recovery_anchor = min(_pre_failure_token_base(sheet), PRE_FAILURE_TOKEN_CAP)
1092
+ overhead_pct = (
1093
+ (total_recovery_tokens / recovery_anchor) * 100.0
1094
+ if total_recovery_tokens > 0 and recovery_anchor > 0
1095
+ else 0.0
1096
+ )
1097
+ thermal_penalty_pct = overhead_pct * RECOVERY_PENALTY_COEFFICIENT
1098
+ retry_and_regression_tax = (total_retries * 15) + (total_cascading * 45)
1099
+ avg_eff = sum(t.thermal_efficiency_ratio for t in turns) / len(turns) if turns else 0.0
1100
+ avg_bsfc = float(agg["avg_bsfc"])
1101
+ peak_bsfc = float(agg["peak_bsfc"])
1102
+ yield_ratio = float(agg["yield_ratio"])
1103
+ bloat_turns = int(agg["bloat_turns"])
1104
+ runaway = sheet.metadata.get("context_runaway_factor")
1105
+ post_fail_tokens = int(sheet.metadata.get("post_failure_runaway_tokens") or 0)
1106
+ torque = sheet.structural_torque if sheet.structural_torque is not None else compute_structural_torque(sheet)
1107
+ eff_grade, eff_mult = compute_effective_thermal(sheet)
1108
+ grade = sheet.thermal_grade or eff_grade
1109
+ base_thermal = str(sheet.metadata.get("base_thermal_grade", grade))
1110
+ thermal_mult = float(sheet.metadata.get("effective_thermal_multiplier", eff_mult))
1111
+ score = (
1112
+ sheet.polyscore
1113
+ if sheet.polyscore is not None
1114
+ else calculate_polyscore(torque, grade, thermal_multiplier_override=thermal_mult)
1115
+ )
1116
+ verify_badge = workload_verification_badge(sheet)
1117
+ hero_subtext = f"Torque {torque} · Thermal {grade} ({thermal_mult:.2f}x) · Load {load_stage} · Mode {invariant_mode}"
1118
+
1119
+ drift_turn_js = "null" if drift_turn is None else str(drift_turn)
1120
+
1121
+ diff_html = autopsy_diff_to_html(sheet.autopsy)
1122
+ noise_html = ""
1123
+ if sheet.autopsy and sheet.autopsy.adversarial_context_noise:
1124
+ from html import escape
1125
+
1126
+ noise_html = escape(sheet.autopsy.adversarial_context_noise)
1127
+
1128
+ out_root = Path(results_dir)
1129
+ if out_root.suffix.lower() == ".html":
1130
+ out_path = out_root
1131
+ else:
1132
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
1133
+ out_path = out_root / f"dyno_chart_{stamp}.html"
1134
+ out_path.parent.mkdir(parents=True, exist_ok=True)
1135
+
1136
+ html_doc = f"""<!DOCTYPE html>
1137
+ <html lang="en">
1138
+ <head>
1139
+ <meta charset="utf-8" />
1140
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
1141
+ <title>Polycracker Dyno — {sheet.provider}/{sheet.model}</title>
1142
+ <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
1143
+ <style>
1144
+ :root {{
1145
+ --bg: #0d1117;
1146
+ --panel: #161b22;
1147
+ --text: #e6edf3;
1148
+ --muted: #8b949e;
1149
+ --accent: #58a6ff;
1150
+ --good: #3fb950;
1151
+ --bad: #ff4d4f;
1152
+ --border: #30363d;
1153
+ }}
1154
+ * {{ box-sizing: border-box; }}
1155
+ body {{
1156
+ margin: 0;
1157
+ font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
1158
+ background: var(--bg);
1159
+ color: var(--text);
1160
+ line-height: 1.5;
1161
+ }}
1162
+ .wrap {{ max-width: 1100px; margin: 0 auto; padding: 24px 16px 48px; }}
1163
+ h1 {{ font-size: 1.35rem; margin: 0 0 8px; }}
1164
+ .sub {{ color: var(--muted); margin-bottom: 20px; font-size: 0.9rem; }}
1165
+ .kpis {{
1166
+ display: grid;
1167
+ grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
1168
+ gap: 12px;
1169
+ margin-bottom: 20px;
1170
+ }}
1171
+ .kpi {{
1172
+ background: var(--panel);
1173
+ border: 1px solid var(--border);
1174
+ border-radius: 10px;
1175
+ padding: 14px;
1176
+ }}
1177
+ .kpi label {{ display: block; font-size: 0.72rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.04em; }}
1178
+ .kpi strong {{ font-size: 1.15rem; }}
1179
+ .kpi.hero {{
1180
+ grid-column: 1 / -1;
1181
+ border-color: #388bfd;
1182
+ background: linear-gradient(135deg, #1c2333 0%, #161b22 100%);
1183
+ }}
1184
+ .kpi.hero .polyscore-value {{
1185
+ display: block;
1186
+ font-size: 2.75rem;
1187
+ font-weight: 700;
1188
+ line-height: 1.1;
1189
+ margin: 4px 0 8px;
1190
+ color: var(--good);
1191
+ }}
1192
+ .kpi.hero .poly-sub {{ font-size: 0.95rem; color: var(--muted); margin-top: 4px; }}
1193
+ .verify {{
1194
+ display: inline-block;
1195
+ margin-top: 8px;
1196
+ font-size: 0.82rem;
1197
+ color: var(--good);
1198
+ font-family: ui-monospace, monospace;
1199
+ }}
1200
+ .panel {{
1201
+ background: var(--panel);
1202
+ border: 1px solid var(--border);
1203
+ border-radius: 10px;
1204
+ padding: 16px;
1205
+ margin-bottom: 20px;
1206
+ }}
1207
+ canvas {{ max-height: 420px; }}
1208
+ .autopsy-noise {{
1209
+ white-space: pre-wrap;
1210
+ font-size: 0.85rem;
1211
+ color: var(--muted);
1212
+ border-left: 3px solid #d29922;
1213
+ padding-left: 12px;
1214
+ margin-bottom: 16px;
1215
+ }}
1216
+ .diff-wrap {{
1217
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
1218
+ font-size: 0.78rem;
1219
+ overflow-x: auto;
1220
+ border-radius: 8px;
1221
+ border: 1px solid var(--border);
1222
+ padding: 8px;
1223
+ background: #010409;
1224
+ }}
1225
+ .diff-add {{ color: #3fb950; }}
1226
+ .diff-del {{ color: #ff7b72; }}
1227
+ .diff-hunk {{ color: var(--accent); }}
1228
+ .diff-meta {{ color: var(--muted); }}
1229
+ .diff-ctx {{ color: var(--text); }}
1230
+ .cta {{
1231
+ margin-top: 28px;
1232
+ padding: 16px 18px;
1233
+ border-radius: 10px;
1234
+ border: 1px solid #238636;
1235
+ background: linear-gradient(90deg, #122117, #161b22);
1236
+ font-size: 0.95rem;
1237
+ }}
1238
+ .cta a {{ color: #58a6ff; }}
1239
+ </style>
1240
+ </head>
1241
+ <body>
1242
+ <div class="wrap">
1243
+ <h1>🏎️ Polycracker Dyno Chart</h1>
1244
+ <p class="sub">Run {sheet.started_at} → {sheet.finished_at or "in progress"} · profile {sheet.metadata.get("profile", "n/a")}</p>
1245
+ <div class="kpis">
1246
+ <div class="kpi hero">
1247
+ <label>PolyScore</label>
1248
+ <span class="polyscore-value">{score}</span>
1249
+ <div class="poly-sub">{hero_subtext}</div>
1250
+ <span class="verify">{verify_badge}</span>
1251
+ </div>
1252
+ <div class="kpi"><label>Load Stage</label><strong>{load_stage}</strong></div>
1253
+ <div class="kpi"><label>Invariant Mode</label><strong>{invariant_mode}</strong></div>
1254
+ <div class="kpi"><label>Model</label><strong>{sheet.provider}/{sheet.model}</strong></div>
1255
+ <div class="kpi"><label>First Unassisted Drop</label><strong>{f"Turn {first_unassisted_drop}" if first_unassisted_drop else "none"}</strong></div>
1256
+ <div class="kpi"><label>Terminal Drift Turn</label><strong>{f"Turn {drift_turn}" if drift_turn else "none"}</strong></div>
1257
+ <div class="kpi"><label>Total Repair Retries</label><strong>{total_retries} ({clean_recoveries}/{turns_with_failures} clean)</strong></div>
1258
+ <div class="kpi"><label>Cascading Regressions</label><strong>{total_cascading}</strong></div>
1259
+ <div class="kpi"><label>Retry &amp; Regression Tax</label><strong>-{retry_and_regression_tax} pts ({total_retries} retries, {total_cascading} cascading breaks)</strong></div>
1260
+ <div class="kpi"><label>BSFC Token Bloat (in/out)</label><strong>{avg_bsfc:.1f}x avg · peak {peak_bsfc:.1f}x · yield {yield_ratio:.1%}</strong></div>
1261
+ <div class="kpi"><label>Context Runaway</label><strong>{f"{runaway:.1f}x vs pre-drop" if runaway is not None else "n/a"} · {post_fail_tokens:,} post-failure tok</strong></div>
1262
+ <div class="kpi"><label>Recovery Token Overhead</label><strong>+{total_recovery_tokens:,} tok (+{overhead_pct:.1f}% vs pre-drop → {base_thermal}→{grade} x{thermal_mult:.2f})</strong></div>
1263
+ <div class="kpi"><label>Thermal Bloat Turns</label><strong>{bloat_turns}</strong></div>
1264
+ <div class="kpi"><label>Thermal Efficiency</label><strong>{avg_eff:.4f}</strong></div>
1265
+ <div class="kpi"><label>Net Diff (Cumulative)</label><strong>+{out_eff['total_lines_added']:,} / -{out_eff['total_lines_removed']:,} ({out_eff['total_net_diff_lines']:,} lines · {out_eff['avg_net_diff_lines']:.1f}/turn)</strong></div>
1266
+ <div class="kpi"><label>Collateral Churn (Excess Edit Dist)</label><strong>{out_eff['total_collateral_churn_chars']:,} chars ({out_eff['avg_collateral_churn_chars']:,.1f}/turn · Peak {peak_churn_label})</strong></div>
1267
+ <div class="kpi"><label>Total Tokens (in+out)</label><strong>{total_input + total_output:,}</strong></div>
1268
+ <div class="kpi"><label>Total Cost</label><strong>${final_cost:.4f}</strong></div>
1269
+ <div class="kpi"><label>Invariant Pass Rate</label><strong>{pass_rate}</strong></div>
1270
+ </div>
1271
+ <div class="panel">
1272
+ <h2 style="margin-top:0;margin-bottom:4px;font-size:1rem;">⚡ Power Band vs. Parasitic Output Churn (Dyno Crossover)</h2>
1273
+ <p style="margin:0 0 12px;font-size:0.82rem;color:var(--muted);">Left Y: Structural Torque (0–1000) &amp; Retention (%) · Right Y: Collateral Churn (excess edit chars) &amp; Net Diff (lines touched)</p>
1274
+ <canvas id="dynoPowerPlot"></canvas>
1275
+ </div>
1276
+ <div class="panel">
1277
+ <h2 style="margin-top:0;margin-bottom:4px;font-size:1rem;">🔥 Fuel Burn &amp; Context Telemetry (Tokens &amp; Cost)</h2>
1278
+ <p style="margin:0 0 12px;font-size:0.82rem;color:var(--muted);">Left Y: Input Tokens &amp; Self-Repair Recovery Tokens · Right Y: Cumulative API Cost (USD)</p>
1279
+ <canvas id="dynoTokenPlot"></canvas>
1280
+ </div>
1281
+ <div class="panel">
1282
+ <h2 style="margin-top:0;font-size:1rem;">Black Box Autopsy</h2>
1283
+ <div class="autopsy-noise">{noise_html or "No adversarial context captured."}</div>
1284
+ <div class="diff-wrap">{diff_html}</div>
1285
+ </div>
1286
+ <div class="cta">
1287
+ 🏎️ Stop Context Detonation. Eliminate multi-turn drift and cut token overhead with the Polycracker MCP Server →
1288
+ <a href="https://polycracker.dev" target="_blank" rel="noopener">polycracker.dev</a>
1289
+ </div>
1290
+ </div>
1291
+ <script>
1292
+ const labels = {labels!r};
1293
+ const inputTokens = {input_tokens!r};
1294
+ const recoveryTokens = {recovery_tokens_series!r};
1295
+ const repairAttempts = {repair_attempts_series!r};
1296
+ const cascadingBreaks = {cascading_series!r};
1297
+ const costs = {costs!r};
1298
+ const retentionPct = {retention_pct!r};
1299
+ const torqueSeries = {torque_series!r};
1300
+ const collateralChurn = {collateral_churn_series!r};
1301
+ const netDiffLines = {net_diff_series!r};
1302
+ const linesAdded = {lines_added_series!r};
1303
+ const linesRemoved = {lines_removed_series!r};
1304
+ const driftTurn = {drift_turn_js};
1305
+ const tokenPointColors = labels.map((_, idx) => {{
1306
+ if (cascadingBreaks[idx] > 0) return '#ff4d4f';
1307
+ if (repairAttempts[idx] > 0) return '#f0883e';
1308
+ return '#58a6ff';
1309
+ }});
1310
+ const powerPointColors = labels.map((_, idx) => {{
1311
+ if (driftTurn !== null && String(labels[idx]) === String(driftTurn)) return '#ff4d4f';
1312
+ if (cascadingBreaks[idx] > 0) return '#ff4d4f';
1313
+ if (repairAttempts[idx] > 0) return '#f0883e';
1314
+ return '#3fb950';
1315
+ }});
1316
+ const pointRadii = labels.map((_, idx) => (repairAttempts[idx] > 0 || cascadingBreaks[idx] > 0 ? 7 : 3));
1317
+ const driftCliffPlugin = {{
1318
+ id: 'driftCliff',
1319
+ afterDraw(chart) {{
1320
+ const {{ top, bottom }} = chart.chartArea;
1321
+ const ctx2 = chart.ctx;
1322
+ ctx2.save();
1323
+ labels.forEach((lbl, idx) => {{
1324
+ if (repairAttempts[idx] > 0) {{
1325
+ const rx = chart.scales.x.getPixelForValue(lbl);
1326
+ ctx2.strokeStyle = cascadingBreaks[idx] > 0 ? 'rgba(255,77,79,0.55)' : 'rgba(240,136,62,0.55)';
1327
+ ctx2.lineWidth = 2;
1328
+ ctx2.setLineDash([4, 4]);
1329
+ ctx2.beginPath();
1330
+ ctx2.moveTo(rx, top);
1331
+ ctx2.lineTo(rx, bottom);
1332
+ ctx2.stroke();
1333
+ ctx2.setLineDash([]);
1334
+ ctx2.fillStyle = cascadingBreaks[idx] > 0 ? '#ff7b72' : '#f0883e';
1335
+ ctx2.font = '11px sans-serif';
1336
+ const tag = cascadingBreaks[idx] > 0
1337
+ ? `T${{lbl}}: ${{repairAttempts[idx]}}R / ${{cascadingBreaks[idx]}}C`
1338
+ : `T${{lbl}}: ${{repairAttempts[idx]}}R clean`;
1339
+ ctx2.fillText(tag, rx + 4, top + 28);
1340
+ }}
1341
+ }});
1342
+ if (driftTurn !== null) {{
1343
+ const idx = labels.indexOf(String(driftTurn));
1344
+ if (idx >= 0) {{
1345
+ const x = chart.scales.x.getPixelForValue(labels[idx]);
1346
+ ctx2.strokeStyle = '#ff4d4f';
1347
+ ctx2.lineWidth = 3;
1348
+ ctx2.beginPath();
1349
+ ctx2.moveTo(x, top);
1350
+ ctx2.lineTo(x, bottom);
1351
+ ctx2.stroke();
1352
+ ctx2.fillStyle = '#ff4d4f';
1353
+ ctx2.font = '12px sans-serif';
1354
+ ctx2.fillText('Drift Cliff T' + driftTurn, x + 6, top + 14);
1355
+ }}
1356
+ }}
1357
+ ctx2.restore();
1358
+ }},
1359
+ }};
1360
+
1361
+ const powerCtx = document.getElementById('dynoPowerPlot');
1362
+ new Chart(powerCtx, {{
1363
+ plugins: [driftCliffPlugin],
1364
+ type: 'line',
1365
+ data: {{
1366
+ labels,
1367
+ datasets: [
1368
+ {{
1369
+ label: 'Structural Torque (Power Band)',
1370
+ data: torqueSeries,
1371
+ borderColor: '#3fb950',
1372
+ backgroundColor: 'rgba(63,185,80,0.14)',
1373
+ fill: true,
1374
+ pointBackgroundColor: powerPointColors,
1375
+ pointBorderColor: powerPointColors,
1376
+ pointRadius: pointRadii,
1377
+ borderWidth: 2.5,
1378
+ yAxisID: 'yPower',
1379
+ tension: 0.2,
1380
+ order: 1,
1381
+ }},
1382
+ {{
1383
+ label: 'Retention %',
1384
+ data: retentionPct,
1385
+ borderColor: '#58a6ff',
1386
+ backgroundColor: 'rgba(88,166,255,0.08)',
1387
+ borderDash: [5, 4],
1388
+ pointRadius: 2,
1389
+ borderWidth: 1.8,
1390
+ yAxisID: 'yPower',
1391
+ spanGaps: true,
1392
+ tension: 0.2,
1393
+ order: 2,
1394
+ }},
1395
+ {{
1396
+ type: 'bar',
1397
+ label: 'Collateral Churn (Excess Edit Chars)',
1398
+ data: collateralChurn,
1399
+ borderColor: '#ff4d4f',
1400
+ backgroundColor: 'rgba(255,77,79,0.55)',
1401
+ borderWidth: 1,
1402
+ yAxisID: 'yChurn',
1403
+ order: 3,
1404
+ }},
1405
+ {{
1406
+ label: 'Net Diff (Lines Touched)',
1407
+ data: netDiffLines,
1408
+ borderColor: '#f0883e',
1409
+ backgroundColor: 'rgba(240,136,62,0.20)',
1410
+ pointBackgroundColor: '#f0883e',
1411
+ pointRadius: 3,
1412
+ borderWidth: 2,
1413
+ yAxisID: 'yChurn',
1414
+ tension: 0.2,
1415
+ order: 2,
1416
+ }},
1417
+ ],
1418
+ }},
1419
+ options: {{
1420
+ responsive: true,
1421
+ interaction: {{ mode: 'index', intersect: false }},
1422
+ plugins: {{
1423
+ legend: {{ labels: {{ color: '#e6edf3' }} }},
1424
+ tooltip: {{
1425
+ callbacks: {{
1426
+ afterBody(items) {{
1427
+ if (!items || !items.length) return '';
1428
+ const idx = items[0].dataIndex;
1429
+ return `Line Diff Breakdown: +${{linesAdded[idx]}} / -${{linesRemoved[idx]}} lines`;
1430
+ }},
1431
+ }},
1432
+ }},
1433
+ }},
1434
+ scales: {{
1435
+ x: {{
1436
+ ticks: {{ color: '#8b949e' }},
1437
+ grid: {{ color: '#30363d' }},
1438
+ title: {{ display: true, text: 'Turn (RPM Sweep)', color: '#8b949e' }},
1439
+ }},
1440
+ yPower: {{
1441
+ type: 'linear',
1442
+ position: 'left',
1443
+ min: 0,
1444
+ suggestedMax: 400,
1445
+ ticks: {{ color: '#3fb950' }},
1446
+ grid: {{ color: '#30363d' }},
1447
+ title: {{ display: true, text: 'Structural Torque (0–1000) / Retention (%)', color: '#3fb950' }},
1448
+ }},
1449
+ yChurn: {{
1450
+ type: 'linear',
1451
+ position: 'right',
1452
+ min: 0,
1453
+ ticks: {{ color: '#ff7b72' }},
1454
+ grid: {{ drawOnChartArea: false }},
1455
+ title: {{ display: true, text: 'Parasitic Loss: Collateral Churn (chars) & Net Diff (lines)', color: '#ff7b72' }},
1456
+ }},
1457
+ }},
1458
+ }},
1459
+ }});
1460
+
1461
+ const tokenCtx = document.getElementById('dynoTokenPlot');
1462
+ new Chart(tokenCtx, {{
1463
+ plugins: [driftCliffPlugin],
1464
+ type: 'line',
1465
+ data: {{
1466
+ labels,
1467
+ datasets: [
1468
+ {{
1469
+ label: 'Input Tokens',
1470
+ data: inputTokens,
1471
+ borderColor: '#58a6ff',
1472
+ backgroundColor: 'rgba(88,166,255,0.15)',
1473
+ pointBackgroundColor: tokenPointColors,
1474
+ pointBorderColor: tokenPointColors,
1475
+ pointRadius: pointRadii,
1476
+ yAxisID: 'yTokens',
1477
+ tension: 0.2,
1478
+ }},
1479
+ {{
1480
+ type: 'bar',
1481
+ label: 'Recovery Tokens (Self-Repair)',
1482
+ data: recoveryTokens,
1483
+ borderColor: '#f0883e',
1484
+ backgroundColor: 'rgba(240,136,62,0.45)',
1485
+ yAxisID: 'yTokens',
1486
+ }},
1487
+ {{
1488
+ label: 'Cumulative Cost ($)',
1489
+ data: costs,
1490
+ borderColor: '#d2a8ff',
1491
+ backgroundColor: 'rgba(210,168,255,0.12)',
1492
+ yAxisID: 'yCost',
1493
+ tension: 0.2,
1494
+ }},
1495
+ ],
1496
+ }},
1497
+ options: {{
1498
+ responsive: true,
1499
+ interaction: {{ mode: 'index', intersect: false }},
1500
+ plugins: {{
1501
+ legend: {{ labels: {{ color: '#e6edf3' }} }},
1502
+ }},
1503
+ scales: {{
1504
+ x: {{
1505
+ ticks: {{ color: '#8b949e' }},
1506
+ grid: {{ color: '#30363d' }},
1507
+ title: {{ display: true, text: 'Turn (RPM Sweep)', color: '#8b949e' }},
1508
+ }},
1509
+ yTokens: {{
1510
+ type: 'linear',
1511
+ position: 'left',
1512
+ ticks: {{ color: '#58a6ff' }},
1513
+ grid: {{ color: '#30363d' }},
1514
+ title: {{ display: true, text: 'Input & Recovery Tokens', color: '#58a6ff' }},
1515
+ }},
1516
+ yCost: {{
1517
+ type: 'linear',
1518
+ position: 'right',
1519
+ min: 0,
1520
+ ticks: {{ color: '#d2a8ff' }},
1521
+ grid: {{ drawOnChartArea: false }},
1522
+ title: {{ display: true, text: 'Cumulative Cost ($)', color: '#d2a8ff' }},
1523
+ }},
1524
+ }},
1525
+ }},
1526
+ }});
1527
+ </script>
1528
+ </body>
1529
+ </html>"""
1530
+ out_path.write_text(html_doc, encoding="utf-8")
1531
+ return out_path