compactlab 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.
Files changed (67) hide show
  1. compactlab/__init__.py +3 -0
  2. compactlab/adapters/__init__.py +2 -0
  3. compactlab/adapters/base.py +212 -0
  4. compactlab/adapters/cache.py +396 -0
  5. compactlab/adapters/claude_code.py +226 -0
  6. compactlab/adapters/codex.py +298 -0
  7. compactlab/adapters/dsh.py +287 -0
  8. compactlab/adapters/gemini_cli.py +259 -0
  9. compactlab/adapters/opencode.py +375 -0
  10. compactlab/apply/__init__.py +582 -0
  11. compactlab/cli/__init__.py +5 -0
  12. compactlab/cli/main.py +2436 -0
  13. compactlab/data/config_knobs.json +158 -0
  14. compactlab/data/harness_defaults.json +72 -0
  15. compactlab/data/harness_formats.json +300 -0
  16. compactlab/data/pricing.json +51 -0
  17. compactlab/engine/__init__.py +138 -0
  18. compactlab/engine/live.py +306 -0
  19. compactlab/engine/settings.py +175 -0
  20. compactlab/engine/watch.py +82 -0
  21. compactlab/eval/__init__.py +1 -0
  22. compactlab/eval/deep.py +390 -0
  23. compactlab/eval/executors.py +84 -0
  24. compactlab/eval/factcheck.py +75 -0
  25. compactlab/lens.py +80 -0
  26. compactlab/model/__init__.py +285 -0
  27. compactlab/pricing/__init__.py +211 -0
  28. compactlab/pricing/auto.py +118 -0
  29. compactlab/pricing/ids.py +148 -0
  30. compactlab/pricing/refresh.py +299 -0
  31. compactlab/publish.py +125 -0
  32. compactlab/py.typed +0 -0
  33. compactlab/recommend/__init__.py +201 -0
  34. compactlab/recommend/claude_code.py +172 -0
  35. compactlab/recommend/codex.py +104 -0
  36. compactlab/recommend/dsh.py +89 -0
  37. compactlab/recommend/gemini_cli.py +85 -0
  38. compactlab/recommend/opencode.py +117 -0
  39. compactlab/recommend/units.py +63 -0
  40. compactlab/report/__init__.py +3 -0
  41. compactlab/report/html.py +27 -0
  42. compactlab/report/template.html +1189 -0
  43. compactlab/service/__init__.py +1 -0
  44. compactlab/service/core.py +220 -0
  45. compactlab/service/http.py +133 -0
  46. compactlab/service/lock.py +92 -0
  47. compactlab/service/policy.py +258 -0
  48. compactlab/service/schedule.py +212 -0
  49. compactlab/share.py +553 -0
  50. compactlab/sim/__init__.py +1 -0
  51. compactlab/sim/baseline.py +214 -0
  52. compactlab/sim/calibrate.py +108 -0
  53. compactlab/sim/engine.py +1130 -0
  54. compactlab/sim/select.py +238 -0
  55. compactlab/sim/timing.py +134 -0
  56. compactlab/synth.py +416 -0
  57. compactlab/term/__init__.py +0 -0
  58. compactlab/term/style.py +134 -0
  59. compactlab/term/top.py +531 -0
  60. compactlab/term/views.py +598 -0
  61. compactlab/term/widgets.py +238 -0
  62. compactlab/verify.py +462 -0
  63. compactlab-0.2.0.dist-info/METADATA +243 -0
  64. compactlab-0.2.0.dist-info/RECORD +67 -0
  65. compactlab-0.2.0.dist-info/WHEEL +4 -0
  66. compactlab-0.2.0.dist-info/entry_points.txt +2 -0
  67. compactlab-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1189 @@
1
+ <!doctype html>
2
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
3
+ <meta name="color-scheme" content="light dark">
4
+ <title>compactlab report</title>
5
+ <style>
6
+ :root{
7
+ --bg:#f6f5f0;--bg2:#efede6;--card:#fdfcf9;--ink:#1f1e1b;--ink2:#56544d;--ink3:#77746c;--line:#e3e0d6;--line2:#cfcbbf;
8
+ --acc:#c15f3c;--acc-soft:#c15f3c17;--good:#2f7a4f;--good-soft:#2f7a4f14;--amber:#a26412;--amber-soft:#a2641216;--bad:#b42318;--bad-soft:#b4231812;
9
+ --serif:ui-serif,"New York","Iowan Old Style","Charter","Palatino Linotype",Georgia,"Songti SC","Noto Serif CJK SC",serif;
10
+ --sans:-apple-system,BlinkMacSystemFont,"SF Pro Text","Segoe UI",system-ui,"PingFang SC","Hiragino Sans GB",sans-serif;
11
+ --mono:ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
12
+ --r:14px;--rs:10px;--pk:.07;--ht:.32;--mp:.45;--ba-was:#d9d5ca
13
+ }
14
+ @media (prefers-color-scheme:dark){:root:not([data-theme=light]){
15
+ --bg:#1a1915;--bg2:#211f1b;--card:#24221e;--ink:#ecebe4;--ink2:#bab7ad;--ink3:#8f8c83;--line:#35332d;--line2:#4a4740;
16
+ --acc:#d97757;--acc-soft:#d9775722;--good:#6cc08e;--good-soft:#6cc08e1c;--amber:#e3a548;--amber-soft:#e3a5481c;--bad:#f2867a;--bad-soft:#f2867a1c;--pk:.16;--ht:.6;--mp:.8;--ba-was:#4d4a43}}
17
+ :root[data-theme=dark]{
18
+ --bg:#1a1915;--bg2:#211f1b;--card:#24221e;--ink:#ecebe4;--ink2:#bab7ad;--ink3:#8f8c83;--line:#35332d;--line2:#4a4740;
19
+ --acc:#d97757;--acc-soft:#d9775722;--good:#6cc08e;--good-soft:#6cc08e1c;--amber:#e3a548;--amber-soft:#e3a5481c;--bad:#f2867a;--bad-soft:#f2867a1c;--pk:.16;--ht:.6;--mp:.8;--ba-was:#4d4a43}
20
+ *{box-sizing:border-box}
21
+ html{background:var(--bg)}
22
+ body{margin:0;background:var(--bg);color:var(--ink);font:14px/1.5 var(--sans);-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}
23
+ td,.kpi .v,.tval,.chip,#tip{font-variant-numeric:tabular-nums}
24
+ code{font:12px var(--mono);background:var(--bg2);border:1px solid var(--line);border-radius:5px;padding:0 4px}
25
+ svg.ic{display:inline-block;width:16px;height:16px;flex:none;vertical-align:-3px;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round}
26
+ .app{display:grid;grid-template-columns:272px minmax(0,1fr);min-height:100vh}
27
+ /* ---------- sidebar: harness > family > model, role chips on the model row ---------- */
28
+ .side{position:sticky;top:0;align-self:start;height:100vh;overflow:auto;border-right:1px solid var(--line);padding:20px 12px 16px;display:flex;flex-direction:column;gap:14px;background:var(--bg)}
29
+ .brand{display:flex;gap:10px;align-items:center;padding:0 8px}
30
+ .brand svg.ic{width:24px;height:24px;stroke-width:1.4}
31
+ .wm{font:600 19px/1.1 var(--serif);letter-spacing:-.01em}
32
+ .drw{display:none}
33
+ .treebox{display:flex;flex-direction:column;gap:12px;flex:1;min-height:0}
34
+ .sbox{position:relative;padding:0 4px}.sbox .ic{position:absolute;left:14px;top:9px;color:var(--ink3);width:14px;height:14px;pointer-events:none}
35
+ .sbox input.tq{width:100%;padding-left:30px;min-height:32px;font-size:12.5px}
36
+ #tree{display:flex;flex-direction:column;gap:1px;font-size:13px}
37
+ .ovr,.fold,.mn{display:flex;align-items:center;gap:6px;width:100%;font:inherit;color:var(--ink2);background:transparent;border:0;border-radius:8px;padding:4px 8px;min-height:32px;cursor:pointer;text-align:left}
38
+ .ovr:hover,.fold:hover,.mn:hover{background:var(--bg2)}
39
+ .ovr{color:var(--ink);font-weight:500;margin-bottom:6px}.ovr[aria-current=page]{background:var(--card);box-shadow:inset 2px 0 0 var(--acc),0 0 0 1px var(--line)}
40
+ .fold>svg.ic:first-child{width:12px;height:12px;transition:transform .15s;color:var(--ink3)}
41
+ .fold[aria-expanded=true]>svg.ic:first-child{transform:rotate(90deg)}
42
+ #tree .nm{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
43
+ .har>.fold{font-weight:600;color:var(--ink);margin-top:4px}
44
+ .fam>.fold{font-size:12.5px}
45
+ .kids{padding-left:12px}
46
+ .mrow{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;column-gap:4px;border-radius:9px;padding:0 6px 4px 0;margin:1px 0 1px 4px}
47
+ .mrow.cur{background:var(--card);box-shadow:inset 2px 0 0 var(--acc),0 0 0 1px var(--line)}
48
+ .mn{color:var(--ink);font-weight:500;flex-direction:column;align-items:flex-start;gap:0;padding-bottom:0}
49
+ .mn .why{font-size:11px;color:var(--ink3);font-weight:400;white-space:normal;line-height:1.35}
50
+ .roles{grid-column:1/-1;display:flex;gap:3px;padding-left:8px}
51
+ .rc,.rt{font:11px/1 var(--sans);border:1px solid var(--line);background:transparent;color:var(--ink3);border-radius:6px;padding:4px 7px;min-height:22px;display:inline-flex;align-items:center;gap:3px}
52
+ .rc{cursor:pointer}.rc:hover{color:var(--ink)}.rc[aria-pressed=true]{background:var(--ink);color:var(--bg);border-color:var(--ink)}
53
+ .rc svg.ic,.rt svg.ic{width:11px;height:11px;vertical-align:0}
54
+ .bdg{font:500 11px/1 var(--mono);white-space:nowrap;color:var(--ink3);display:inline-flex;gap:6px;align-items:center;margin-left:auto}
55
+ .bdg.good{color:var(--good)}.bdg.warn{color:var(--amber)}.bdg i{font-style:normal;color:var(--ink3);font-weight:400}
56
+ .nc>.fold{color:var(--ink3);margin-top:10px}.nc>.fold .ic:nth-child(2){color:var(--good)}
57
+ .sidefoot{margin-top:auto;display:flex;gap:6px;flex-wrap:wrap;padding:0 8px}
58
+ /* views: overview, a model that needs tuning, a model that never compacts */
59
+ [data-view=overview] .vg,[data-view=noop] .vg,[data-view=group] .vo,[data-view=noop] .vo,[data-view=group] .vn,[data-view=overview] .vn,[data-view=noop] .vgo{display:none!important}
60
+ /* ---------- main ---------- */
61
+ main{min-width:0;padding:26px 36px 64px;max-width:1180px;width:100%}
62
+ .eyebrow{font-size:11.5px;letter-spacing:.06em;text-transform:uppercase;color:var(--ink3)}
63
+ h1{font:500 30px/1.15 var(--serif);letter-spacing:-.015em;margin:2px 0 0;overflow-wrap:anywhere}
64
+ h1 .rl{color:var(--ink3)}
65
+ h2{font:500 20px/1.25 var(--serif);letter-spacing:-.01em;margin:40px 0 12px;display:flex;align-items:center;gap:6px}
66
+ h3{font:600 13px/1.35 var(--sans);margin:0 0 8px;display:flex;align-items:center;gap:6px}
67
+ .meta{display:flex;flex-wrap:wrap;gap:6px 18px;margin:12px 0 0;font-size:12.5px;color:var(--ink2);align-items:center}
68
+ .mi{display:inline-flex;align-items:center;gap:6px;min-height:28px}.mi .ic{color:var(--ink3)}.mi.warn,.mi.warn .ic{color:var(--amber)}
69
+ .badge{display:inline-block;font-size:11px;border:1px solid var(--acc);color:var(--acc);border-radius:999px;padding:0 8px}
70
+ .cap{font-size:11.5px;color:var(--ink3);line-height:1.4}
71
+ .card{background:var(--card);border:1px solid var(--line);border-radius:var(--r);padding:16px 18px}
72
+ .grid2{display:grid;grid-template-columns:1fr 1fr;gap:16px}
73
+ /* info / warning icon buttons (tooltips) */
74
+ .ib{display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;padding:0;border:0;border-radius:50%;background:transparent;color:var(--ink3);cursor:help;flex:none}
75
+ .ib:hover{color:var(--ink);background:var(--bg2)}
76
+ .ib.low{color:var(--amber)}.ib.bad{color:var(--bad)}.ib.ok{color:var(--good)}
77
+ /* segmented controls */
78
+ .seg{display:inline-flex;flex-wrap:wrap;gap:2px;background:var(--bg2);border:1px solid var(--line);border-radius:12px;padding:3px;max-width:100%}
79
+ .seg button{font:inherit;font-size:13px;color:var(--ink2);background:transparent;border:1px solid transparent;border-radius:9px;padding:4px 12px;cursor:pointer;white-space:nowrap;min-height:32px;display:inline-flex;align-items:center;gap:6px;transition:color .15s,background .15s,border-color .15s}
80
+ .seg button:hover{color:var(--ink)}
81
+ .seg button[aria-pressed=true]{background:var(--card);color:var(--ink);border-color:var(--line);box-shadow:0 1px 1px #0000000a;font-weight:600}
82
+ .seg.sm button{padding:3px 10px;font-size:12px;min-height:28px}
83
+ /* sticky control bar */
84
+ .bar{position:sticky;top:0;z-index:5;margin:18px -36px 0;padding:10px 36px 6px;background:color-mix(in srgb,var(--bg) 88%,transparent);-webkit-backdrop-filter:saturate(1.2) blur(10px);backdrop-filter:saturate(1.2) blur(10px);border-bottom:1px solid var(--line)}
85
+ .gearrow{display:flex;flex-wrap:wrap;align-items:center;gap:8px 14px}
86
+ #flags{display:inline-flex;gap:2px;margin-left:auto;align-items:center}
87
+ .vot{font-size:11.5px;color:var(--ink3)}
88
+ .slider{display:grid;grid-template-columns:auto 1fr auto;align-items:start;gap:4px 14px;font-size:13px;color:var(--ink2);flex:1 1 100%;min-width:0}
89
+ .slider label{line-height:28px;display:inline-flex;align-items:center;height:28px}
90
+ .track{position:relative;min-width:0;padding-bottom:46px}
91
+ input[type=range]{width:100%;height:28px;margin:0;accent-color:var(--acc);cursor:pointer;touch-action:pan-y;background:transparent}
92
+ .tval{font:600 20px/28px var(--mono);color:var(--ink);min-width:60px;text-align:right}
93
+ .mk{position:absolute;transform:translateX(-50%);font:inherit;font-size:11px;line-height:1.2;white-space:nowrap;background:transparent;border:0;padding:4px 2px 2px;color:var(--ink3);cursor:pointer;min-height:18px;display:inline-flex;align-items:center;gap:3px}
94
+ .mk svg.ic{width:12px;height:12px;vertical-align:-2px}
95
+ .mk::before{content:"";position:absolute;left:50%;top:-4px;width:1px;height:7px;background:currentColor;transform:translateX(-50%)}
96
+ .mk.r1{top:26px}.mk.r2{top:50px;color:var(--ink2)}.mk.r2::before{height:5px;top:-2px}
97
+ .mk.l1{margin-top:14px}.mk.l2{margin-top:28px}.mk.er{transform:translateX(calc(-100% + 4px))}.mk.er::before{left:auto;right:3px}.mk.el{transform:translateX(-4px)}.mk.el::before{left:3px}
98
+ .mk.on{color:var(--acc);font-weight:600}.mk:hover{color:var(--ink)}
99
+ /* KPI cards */
100
+ #ctl{margin-top:16px}
101
+ .kpis{display:grid;grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:12px}
102
+ .kpi{background:var(--card);border:1px solid var(--line);border-radius:var(--r);padding:12px 16px;min-width:0}
103
+ .kh{display:flex;align-items:center;gap:7px;font-size:12px;color:var(--ink2)}.kh .ic{color:var(--ink3)}
104
+ .kpi .v{font:500 26px/1.25 var(--mono);letter-spacing:-.02em;margin-top:6px}
105
+ .kr{display:flex;align-items:center;gap:8px;margin-top:6px;min-width:0;flex-wrap:wrap}
106
+ .good{color:var(--good)}.warn{color:var(--amber)}.bad{color:var(--bad)}
107
+ /* delta chips */
108
+ .chip{display:inline-flex;align-items:center;gap:4px;font:500 12px/1 var(--mono);border-radius:999px;padding:4px 8px;background:var(--bg2);color:var(--ink2);white-space:nowrap}
109
+ .chip svg.ic{width:13px;height:13px;vertical-align:0}
110
+ .chip.good{background:var(--good-soft);color:var(--good)}.chip.warn{background:var(--amber-soft);color:var(--amber)}.chip.bad{background:var(--bad-soft);color:var(--bad)}
111
+ .chip[tabindex]{cursor:help}
112
+ .act{font:11px var(--sans);border:1px solid var(--line2);color:var(--ink2);border-radius:999px;padding:1px 8px;white-space:nowrap}
113
+ .act.set{border-color:var(--acc);color:var(--acc)}
114
+ /* mini gauges */
115
+ .gauge{position:relative;height:6px;border-radius:3px;background:var(--bg2);flex:1 1 60px;min-width:50px}
116
+ .gauge i{position:absolute;left:0;top:0;bottom:0;border-radius:3px;background:var(--ink3)}
117
+ .gauge b{position:absolute;top:-3px;width:2px;height:12px;background:var(--amber);border-radius:1px}
118
+ .pc.sel .gauge i,.kpi .gauge i{background:var(--acc)}
119
+ /* profiles: per-day impact */
120
+ .ihead{display:flex;flex-wrap:wrap;gap:8px 12px;align-items:center;margin-bottom:12px}
121
+ .pcs{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}
122
+ .pc{background:var(--card);border:1px solid var(--line);border-radius:var(--r);padding:12px 14px;min-width:0;display:grid;gap:10px;align-content:start}
123
+ .pc.sel{border-color:color-mix(in srgb,var(--acc) 55%,var(--line));box-shadow:inset 0 2px 0 var(--acc)}
124
+ .pc header{display:flex;align-items:center;gap:7px;min-width:0}
125
+ .pc header>svg.ic{width:18px;height:18px;color:var(--ink2)}.pc.sel header>.ic{color:var(--acc)}
126
+ .pc .pn{font:500 17px/1.2 var(--serif)}
127
+ .pc .act{margin-left:auto}
128
+ .tb{display:flex;align-items:center;gap:8px}.tb .pt{font:500 13px var(--mono);min-width:44px;text-align:right}
129
+ .irow{display:grid;gap:5px;padding-top:8px;border-top:1px solid var(--line)}
130
+ .irow .chips{display:flex;flex-wrap:wrap;gap:5px}
131
+ /* charts */
132
+ svg{width:100%;height:auto;display:block}
133
+ text{fill:var(--ink3);font-size:10.5px;font-family:var(--sans)}
134
+ .ax{stroke:var(--line2)}.grid{stroke:var(--line);stroke-dasharray:1 3}
135
+ .dl{font-size:10.5px;paint-order:stroke;stroke:var(--card);stroke-width:3.5px;stroke-linejoin:round}
136
+ .hov{cursor:crosshair}
137
+ #tip{position:fixed;z-index:20;pointer-events:none;background:var(--card);color:var(--ink);border:1px solid var(--line2);border-radius:10px;padding:8px 11px;font-size:12px;line-height:1.5;box-shadow:0 8px 28px #00000014;min-width:150px;max-width:min(340px,calc(100vw - 16px))}
138
+ #tip b{font:600 13px var(--mono)}#tip .r{display:flex;justify-content:space-between;gap:16px}#tip .r span:first-child{color:var(--ink2)}#tip .r span:last-child{font-family:var(--mono)}
139
+ /* main chart: cost and time panels sharing the threshold axis */
140
+ #fMain{padding:14px 18px 6px}
141
+ #fMain .mh{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:4px}
142
+ svg.mainc{touch-action:pan-y;user-select:none;-webkit-user-select:none}
143
+ .peaks rect{fill:var(--ink);opacity:var(--pk)}
144
+ .unsafe{fill:url(#hatch)}.hatch{stroke:var(--bad);stroke-width:1.2;opacity:var(--ht)}
145
+ .dl.uz{fill:var(--bad)}
146
+ .zero{stroke:var(--ink3);stroke-width:.9}
147
+ .mdef{stroke:var(--ink2);stroke-dasharray:4 3;stroke-width:1}.mcur{stroke:var(--ink2);stroke-dasharray:1 3;stroke-width:1.5}
148
+ .mprof{stroke:var(--acc);opacity:var(--mp);stroke-width:1}
149
+ .pico{fill:none;stroke:currentColor;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round;color:var(--ink2)}
150
+ .cursor .cl{stroke:var(--acc);stroke-width:1.6}.cursor circle{fill:var(--acc);stroke:var(--card);stroke-width:2}
151
+ .cursor .ch{fill:var(--acc)}.cursor .chl{fill:var(--card);font:600 11px var(--mono)}
152
+ .dl.good{fill:var(--good)}.dl.warn{fill:var(--amber)}.dl.b{font-weight:600;font-size:11.5px}
153
+ .drag{cursor:ew-resize}
154
+ #fMain .track{margin-top:2px}
155
+ .dl.b{stroke-width:5px}.ptl{fill:var(--ink2);font-size:11px}.pic{color:var(--acc)}.tk.good{fill:var(--good)}.tk.warn{fill:var(--amber)}
156
+ .key{display:flex;flex-wrap:wrap;gap:4px 14px;font-size:11.5px;color:var(--ink2);margin:0 0 4px}
157
+ .ky{display:inline-flex;align-items:center;gap:5px}.ky b{font-weight:600}.sw{display:inline-block;width:12px;height:10px;border-radius:2px}
158
+ .swp{background:var(--ink);opacity:calc(var(--pk) * 2.5)}.swh{background:repeating-linear-gradient(45deg,var(--bad) 0 1.3px,transparent 1.3px 4px);opacity:.8}
159
+ .swd{width:0;height:12px;border-left:1.5px dashed var(--ink2);border-radius:0}.swc{width:0;height:12px;border-left:2px dotted var(--ink2);border-radius:0}
160
+ .est{display:inline-block;font:500 10.5px/1.5 var(--sans);color:var(--ink3);border:1px solid var(--line2);border-radius:5px;padding:0 5px;margin-left:6px;letter-spacing:0;text-transform:none;vertical-align:1px}
161
+ .ansrow{display:flex;flex-wrap:wrap;align-items:center;gap:4px 12px;margin-top:8px}
162
+ .ans{font-size:14px;font-weight:500}.ans2{font-size:12.5px;font-weight:400}.ans2::before{content:'·';margin:0 8px;color:var(--ink3)}
163
+ .btn.sm{display:inline-flex;align-items:center;gap:6px;font-size:12.5px;padding:3px 12px;min-height:30px}.btn:disabled{opacity:.4;cursor:not-allowed}
164
+ .btn svg.ic{width:14px;height:14px}
165
+ .mute,td.mute{color:var(--ink3)!important}tspan.mute{fill:var(--ink3)}tspan.good{fill:var(--good)}tspan.warn{fill:var(--amber)}
166
+ .smk{fill:var(--line2)}.ovrow.keep .ovname{fill:var(--ink3)}
167
+ .bdg i{display:inline-flex;align-items:center;gap:2px}.bdg i svg.ic{width:10px;height:10px;vertical-align:0}.bdg.mute{opacity:.85}
168
+ .kw{font-size:11.5px;line-height:1.35;color:var(--ink2);background:var(--bg2);border-radius:6px;padding:3px 7px;margin-top:4px;white-space:normal;text-align:left;max-width:340px;margin-left:auto}
169
+ .pc .kw{margin:0;max-width:none}.ans2.kw{margin:0;padding:1px 7px}.ans2.kw::before{content:none}
170
+ .kpi .v .nw{white-space:nowrap}.kpi .v .sc{display:block;font:500 12.5px/1.4 var(--mono);margin:2px 0 0;opacity:.85}#ovw .kpi .v{font-size:23px}
171
+ .hrow{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:8px}.hrow .indep{margin:0 auto 0 0}
172
+ .ld{font-weight:600}.sc{font-size:.85em;opacity:.8;margin-left:5px;font-weight:400}.chip .sc{margin-left:4px}tspan.sc2{font-weight:400;font-size:10px;opacity:.85}
173
+ .ovctl{display:flex;flex-wrap:wrap;gap:8px 14px;align-items:center;margin-bottom:8px}.ovctl .seg button{font-size:12.5px;padding:3px 10px}
174
+ .olg{display:flex;flex-wrap:wrap;gap:4px 14px;font-size:11.5px;color:var(--ink2);margin:0 0 4px}.olg span{display:inline-flex;align-items:center;gap:5px}
175
+ .olg i{display:inline-block;width:16px;height:9px;border-radius:2px}.olg .lw{background:var(--ba-was)}.olg .ln{background:var(--acc)}
176
+ .olg .ls{background:repeating-linear-gradient(45deg,var(--good) 0 1.4px,var(--good-soft) 1.4px 4px)}.olg .la{background:var(--amber)}
177
+ h3.ovh{margin:14px 0 2px;color:var(--ink2);font-weight:500}
178
+ .baw{fill:var(--ba-was)}.ban{fill:var(--acc)}.baa{fill:var(--amber)}.bash{fill:var(--good-soft)}.bahl{stroke:var(--good);stroke-width:1.4}
179
+ .babr{fill:none;stroke:var(--good);stroke-width:1}
180
+ .dtrack{stroke:var(--line);stroke-width:1}.dline{stroke-width:3.5;stroke-linecap:round}.dline.sv{stroke:var(--good)}.dline.ad{stroke:var(--amber)}
181
+ .dwas{fill:var(--card);stroke:var(--ink3);stroke-width:2.5}.dnow{fill:var(--acc);stroke:var(--card);stroke-width:1.5}
182
+ #fOv.dots .olg .lw{background:none;border:2.5px solid var(--ink3);border-radius:50%;width:10px;height:10px}#fOv.dots .olg .ln{border-radius:50%;width:10px;height:10px}
183
+ #fOv.dots .olg .ls{background:var(--good);height:3px}#fOv.dots .olg .la{height:3px}.lead{stroke:var(--line2);stroke-dasharray:1 3}.axt{font-size:10px}
184
+ tspan.big{font-size:13px;font-weight:700}.barow{cursor:pointer}.barow:hover .ovbg{fill:var(--bg2)}.barow.tot .ovname{font-weight:600}.barow.keep .ovname{fill:var(--ink3)}
185
+ .sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
186
+ .minib{display:inline-flex;align-items:center;cursor:help}.mini{display:block}
187
+ .indep{font-size:11px;color:var(--ink3);margin-bottom:8px}
188
+ #marks.compact .mk.r1 .tx{display:none}
189
+ .live{display:inline-flex;align-items:center;gap:6px;flex-wrap:wrap}.live .tval{min-width:0;font-size:18px}
190
+ /* no-change view */
191
+ .nohead{display:flex;gap:12px;align-items:flex-start;margin-top:18px}.nohead>svg.ic{width:22px;height:22px;color:var(--good);margin-top:2px}
192
+ .nohead .nt{font:500 18px/1.3 var(--serif)}.nohead .chips{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}
193
+ .nzone{fill:var(--acc-soft)}.nbar{fill:var(--line2)}.nbar:hover{fill:var(--ink3)}
194
+ /* overview */
195
+ .ovbar{display:flex;flex-wrap:wrap;gap:8px 14px;align-items:center;margin-top:18px}
196
+ #ovw .kpis{margin-top:16px}
197
+ .ovrow{cursor:pointer}.ovrow:hover .ovbg{fill:var(--bg2)}.ovbg{fill:transparent}
198
+ .sm1{fill:var(--acc)}.sm2{fill:var(--acc);opacity:.5}.sma{fill:var(--amber)}
199
+ .seglab{fill:var(--card);font-size:10px;font-weight:600;pointer-events:none}
200
+ .ovname{fill:var(--ink);font-size:12px}.ovsub{fill:var(--ink3);font-size:10.5px}
201
+ #ovT td button{font:inherit;color:var(--ink);background:none;border:0;padding:0;cursor:pointer;text-align:left;min-height:28px}
202
+ #ovT td button:hover{color:var(--acc)}
203
+ #ovT th .srt{font:inherit;color:inherit;background:none;border:0;padding:0;cursor:pointer;min-height:24px}#ovT th .srt:hover{color:var(--ink)}
204
+ /* tables */
205
+ select,input[type=search]{font:inherit;font-size:13px;background:var(--card);color:var(--ink);border:1px solid var(--line2);border-radius:9px;padding:6px 10px;min-height:34px;max-width:100%}
206
+ input[type=search]{width:260px}
207
+ table{width:100%;border-collapse:collapse;font-size:12.5px}
208
+ th,td{padding:7px 8px;border-bottom:1px solid var(--line);text-align:right;white-space:nowrap}
209
+ th:first-child,td:first-child{text-align:left}
210
+ th{color:var(--ink3);font-weight:500;font-size:11.5px}
211
+ #st th[data-k]{cursor:pointer}
212
+ .scroll{overflow:auto;max-height:440px}
213
+ #fCmp{max-height:none}#fCmp th{white-space:normal;vertical-align:bottom}#fCmp th,#fCmp td{padding:7px 6px}
214
+ #fCmp td{font-family:var(--mono);font-size:12px}#fCmp td:first-child{font-family:var(--sans)}
215
+ tr.sel td{background:var(--acc-soft)}tr.sel td:first-child{box-shadow:inset 2px 0 0 var(--acc);font-weight:600}
216
+ .ctlrow{display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin:0 0 10px}
217
+ pre.snip{background:var(--bg2);border:1px solid var(--line);border-radius:var(--rs);padding:12px 14px;overflow:auto;font:12px/1.55 var(--mono);white-space:pre;max-height:420px;margin:12px 0 0}
218
+ .copyrow{display:flex;gap:8px 10px;flex-wrap:wrap;align-items:center}
219
+ .btn{font:inherit;font-size:13px;border:1px solid var(--ink);background:var(--ink);color:var(--bg);border-radius:9px;padding:5px 14px;cursor:pointer;min-height:32px}
220
+ details.more{margin-top:40px;font-size:12.5px;color:var(--ink2)}details.more summary{cursor:pointer;min-height:32px;display:flex;align-items:center;gap:6px;color:var(--ink2)}
221
+ ul.n{margin:6px 0 0;padding-left:18px}ul.n li{margin:3px 0}
222
+ .foot{margin-top:28px;padding-top:12px;border-top:1px solid var(--line);font-size:11.5px;color:var(--ink3);display:flex;align-items:center;gap:4px;flex-wrap:wrap}
223
+ :focus-visible{outline:2px solid var(--acc);outline-offset:2px;border-radius:6px}
224
+ /* ---------- responsive ---------- */
225
+ @media (max-width:1100px){.pcs{grid-template-columns:1fr 1fr}}
226
+ @media (max-width:900px){
227
+ .app{display:block}
228
+ /* the tree becomes a drawer that opens below the top bar */
229
+ .side{position:relative;z-index:8;height:auto;overflow:visible;border-right:0;border-bottom:1px solid var(--line);padding:8px 16px;display:block}
230
+ .brand{padding:0}
231
+ .drw{display:inline-flex;align-items:center;gap:6px;margin-left:auto;font:inherit;font-size:13px;color:var(--ink);background:var(--card);border:1px solid var(--line);border-radius:999px;padding:4px 12px;min-height:44px;max-width:62vw;cursor:pointer}
232
+ .drw .nm{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
233
+ .drw>svg.ic:last-child{transition:transform .15s}.side.open .drw>svg.ic:last-child{transform:rotate(180deg)}
234
+ .treebox{display:none}
235
+ .side.open .treebox{display:flex;position:absolute;left:0;right:0;top:100%;background:var(--bg);border-bottom:1px solid var(--line);padding:12px 12px 16px;max-height:78vh;overflow:auto;box-shadow:0 14px 30px #00000024}
236
+ .ovr,.fold,.mn{min-height:44px}.rc{min-height:32px;padding:6px 10px}
237
+ main{padding:20px 16px 56px}
238
+ .bar{margin:16px -16px 0;padding:8px 16px 4px}
239
+ .grid2{grid-template-columns:1fr}
240
+ h1{font-size:26px}
241
+ }
242
+ @media (max-width:768px),(pointer:coarse){.seg button,.btn{min-height:44px}.rc{min-height:32px}.seg.sm button{min-height:40px}.ib{width:44px;height:44px}.mk{min-height:24px}input[type=range]{height:44px}.mk.r1{top:38px}.mk.r2{top:64px}.track{padding-bottom:62px}.slider label,.tval{line-height:44px;height:44px}}
243
+ @media (max-width:640px){.pcs{grid-template-columns:1fr}.kpis{grid-template-columns:1fr 1fr}.kpi .v{font-size:21px}}
244
+ @media (max-width:520px){
245
+ .mi.opt{display:none}#flags{margin-left:auto}.ans{font-size:13.5px}
246
+ /* on a phone the bar is tall: let it scroll away instead of covering the chart */
247
+ .bar{position:static}
248
+ #gears{display:grid;grid-template-columns:repeat(4,1fr);flex:1 1 100%}
249
+ #gears button{padding:4px 2px;justify-content:center;font-size:11.5px;gap:3px}#gears button svg.ic{width:13px;height:13px}
250
+ .slider{grid-template-columns:1fr auto;width:100%}.slider label{grid-row:1}.tval{grid-row:1;grid-column:2}.track{grid-column:1/-1}
251
+ .card{padding:14px}
252
+ }
253
+ @media (max-width:380px){.kpis{grid-template-columns:1fr}}
254
+ @media (prefers-reduced-motion:reduce){*{transition:none!important;animation:none!important;scroll-behavior:auto!important}}
255
+ </style></head><body>
256
+ <svg width="0" height="0" style="position:absolute" aria-hidden="true"><defs>
257
+ <symbol id="i-logo" viewBox="0 0 24 24"><rect x="2.5" y="2.5" width="19" height="19" rx="5"/><path d="M7 8.5h10M7 12h7M7 15.5h4"/></symbol>
258
+ <symbol id="i-coin" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M14.6 9.6c-.5-.9-1.5-1.4-2.6-1.4-1.4 0-2.5.8-2.5 1.9s1 1.6 2.5 1.9 2.5.9 2.5 2-1.1 1.9-2.5 1.9c-1.1 0-2.1-.5-2.6-1.4M12 6.6v1.6M12 15.8v1.6"/></symbol>
259
+ <symbol id="i-scale" viewBox="0 0 24 24"><path d="M12 4v16M8 20h8M4.5 7h15M6.5 7l-3 6.5h6zM17.5 7l-3 6.5h6z"/></symbol>
260
+ <symbol id="i-clock" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M12 7.5V12l3 2"/></symbol>
261
+ <symbol id="i-refresh" viewBox="0 0 24 24"><path d="M19.5 11A7.5 7.5 0 0 0 6 6.8M4.5 13A7.5 7.5 0 0 0 18 17.2M5.5 3.5v3.6h3.6M18.5 20.5v-3.6h-3.6"/></symbol>
262
+ <symbol id="i-shield" viewBox="0 0 24 24"><path d="M12 3.5l7 2.8v5.2c0 4.3-2.9 7.6-7 9-4.1-1.4-7-4.7-7-9V6.3z"/><path d="M9 12l2.2 2.2L15 10.4"/></symbol>
263
+ <symbol id="i-info" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M12 11v5M12 8h.01"/></symbol>
264
+ <symbol id="i-warn" viewBox="0 0 24 24"><path d="M12 4.5 3 19.5h18z"/><path d="M12 10v4.5M12 17h.01"/></symbol>
265
+ <symbol id="i-check" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M8.5 12.2l2.4 2.4 4.6-4.8"/></symbol>
266
+ <symbol id="i-cal" viewBox="0 0 24 24"><rect x="4" y="5.5" width="16" height="14.5" rx="2"/><path d="M4 10h16M8.5 3.5v4M15.5 3.5v4"/></symbol>
267
+ <symbol id="i-db" viewBox="0 0 24 24"><ellipse cx="12" cy="6" rx="7" ry="2.5"/><path d="M5 6v12c0 1.4 3.1 2.5 7 2.5s7-1.1 7-2.5V6M5 12c0 1.4 3.1 2.5 7 2.5s7-1.1 7-2.5"/></symbol>
268
+ <symbol id="i-layers" viewBox="0 0 24 24"><path d="M12 4l8.5 4.5L12 13 3.5 8.5z"/><path d="M3.5 13 12 17.5l8.5-4.5"/></symbol>
269
+ <symbol id="i-sliders" viewBox="0 0 24 24"><path d="M4 7h9M17 7h3M4 17h3M11 17h9"/><circle cx="15" cy="7" r="2"/><circle cx="9" cy="17" r="2"/></symbol>
270
+ <symbol id="i-flag" viewBox="0 0 24 24"><path d="M6 20.5V4M6 4.5h11l-2 4 2 4H6"/></symbol>
271
+ <symbol id="i-sun" viewBox="0 0 24 24"><circle cx="12" cy="12" r="4"/><path d="M12 2.5v2M12 19.5v2M4.6 4.6 6 6M18 18l1.4 1.4M2.5 12h2M19.5 12h2M4.6 19.4 6 18M18 6l1.4-1.4"/></symbol>
272
+ <symbol id="i-moon" viewBox="0 0 24 24"><path d="M19.5 14.5A8 8 0 0 1 9.5 4.5a8 8 0 1 0 10 10z"/></symbol>
273
+ <symbol id="i-copy" viewBox="0 0 24 24"><rect x="8.5" y="8.5" width="11" height="11" rx="2"/><path d="M15.5 8.5V6a1.5 1.5 0 0 0-1.5-1.5H6A1.5 1.5 0 0 0 4.5 6v8A1.5 1.5 0 0 0 6 15.5h2.5"/></symbol>
274
+ <symbol id="i-bars" viewBox="0 0 24 24"><path d="M4 6.5h13M4 12h16M4 17.5h9" stroke-width="3"/></symbol>
275
+ <symbol id="i-dots" viewBox="0 0 24 24"><path d="M7 6.5h10M9 12h9M5 17.5h8"/><circle cx="7" cy="6.5" r="2"/><circle cx="17" cy="6.5" r="2"/><circle cx="9" cy="12" r="2"/><circle cx="18" cy="12" r="2"/><circle cx="5" cy="17.5" r="2"/><circle cx="13" cy="17.5" r="2"/></symbol>
276
+ <symbol id="i-chev" viewBox="0 0 24 24"><path d="M9 5.5l6.5 6.5L9 18.5"/></symbol>
277
+ <symbol id="i-down" viewBox="0 0 24 24"><path d="M6 9.5l6 6 6-6"/></symbol>
278
+ <symbol id="i-grid" viewBox="0 0 24 24"><path d="M4 19.5h16M6.5 16V11M11 16V6M15.5 16v-3.5M20 16V8.5"/></symbol>
279
+ <symbol id="i-search" viewBox="0 0 24 24"><circle cx="10.5" cy="10.5" r="6"/><path d="M15 15l5 5"/></symbol>
280
+ <symbol id="i-bot" viewBox="0 0 24 24"><rect x="5" y="8" width="14" height="11" rx="3"/><path d="M12 4.5V8M9.5 13h.01M14.5 13h.01"/></symbol>
281
+ <symbol id="i-user" viewBox="0 0 24 24"><circle cx="12" cy="8.5" r="3.5"/><path d="M5 19.5c1-3.6 3.8-5.5 7-5.5s6 1.9 7 5.5"/></symbol>
282
+ <symbol id="i-auto" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M12 3.5v17A8.5 8.5 0 0 0 12 3.5z" fill="currentColor"/></symbol>
283
+ </defs></svg>
284
+ <div class="app">
285
+ <aside class="side" id="side">
286
+ <div class="brand"><svg class="ic" aria-hidden="true"><use href="#i-logo"/></svg><span class="wm">compactlab</span>
287
+ <button type="button" class="drw" id="drawer" aria-expanded="false" aria-controls="treebox"><span class="nm" id="drwL"></span><svg class="ic" aria-hidden="true"><use href="#i-down"/></svg></button></div>
288
+ <div class="treebox" id="treebox">
289
+ <div class="sbox"><svg class="ic" aria-hidden="true"><use href="#i-search"/></svg><input type="search" class="tq" id="tq" autocomplete="off"></div>
290
+ <nav id="tree"></nav>
291
+ <div class="sidefoot"><div class="seg sm" role="group" aria-label="Language" id="langs"></div><div class="seg sm" role="group" aria-label="Theme" id="themes"></div></div>
292
+ </div>
293
+ </aside>
294
+ <main id="main">
295
+ <header>
296
+ <div class="hrow"><div class="indep" id="indep"></div><div class="seg sm" role="group" id="units"></div><span id="unitI"></span></div>
297
+ <div class="eyebrow" id="eyebrow"></div>
298
+ <h1 id="title">compactlab</h1>
299
+ <div class="meta" id="meta"></div>
300
+ </header>
301
+ <div class="bar vg" id="bar"></div>
302
+ <section class="vo" id="ovw"></section>
303
+ <section class="vn" id="noop"></section>
304
+ <div class="card vg" id="fMain" style="margin-top:16px"></div>
305
+ <h2 class="vg"><span id="hImpact"></span><span id="iImpact"></span></h2>
306
+ <div class="vg" id="fImpact"></div>
307
+ <section class="vg" id="ctl" style="margin-top:16px"><div class="kpis" id="kpis"></div></section>
308
+ <h2 class="vg"><span id="hCmp"></span><span id="iCmp"></span></h2>
309
+ <div class="card scroll vg" id="fCmp"></div>
310
+ <h2 class="vgo"><span id="hCopy"></span><span id="iCopy"></span></h2>
311
+ <div class="card vgo" id="fCopy"></div>
312
+ <h2 class="vg"><span id="hTrade"></span></h2>
313
+ <div class="grid2 vg"><div class="card fig" id="fPareto"></div><div class="card fig" id="fCost"></div></div>
314
+ <h2 class="vg"><span id="hTime"></span></h2>
315
+ <div class="card fig vg" id="fTime"></div>
316
+ <h2 class="vg"><span id="hHist"></span></h2>
317
+ <div class="grid2 vg"><div class="card fig" id="fHist"></div><div class="card fig" id="fSess"></div></div>
318
+ <h2 class="vg"><span id="hDeep"></span></h2>
319
+ <div class="card vg" id="fDeep"></div>
320
+ <h2><span id="hSess"></span></h2>
321
+ <div class="ctlrow"><input type="search" id="q"> <span class="cap" id="cnt"></span></div>
322
+ <div class="card scroll"><table id="st"></table></div>
323
+ <details class="more vg"><summary id="hNotes"></summary><ul class="n" id="notes"></ul></details>
324
+ <footer class="foot" id="foot"></footer>
325
+ </main>
326
+ </div>
327
+ <div id="tip" role="tooltip" hidden></div>
328
+ <script id="data" type="application/json">__DATA__</script>
329
+ <script>
330
+ const D=JSON.parse(document.getElementById('data').textContent);
331
+ const $=s=>document.querySelector(s),NS='http://www.w3.org/2000/svg';
332
+ const fk=v=>v==null?'–':v===0?'0':v>=1e6?(v/1e6)+'M':Math.round(v/1e3)+'k';
333
+ const MINUS='−';
334
+ const fd=v=>(v<0?MINUS:'')+'$'+(Math.abs(v)>=100?Math.round(Math.abs(v)).toLocaleString('en-US'):Math.abs(v).toFixed(2));
335
+ const fds=v=>(v>=0?'+':MINUS)+'$'+(Math.abs(v)>=100?Math.round(Math.abs(v)).toLocaleString('en-US'):Math.abs(v).toFixed(2));
336
+ // per-day money: one decimal below $1,000 ('−$204.8' = saves $204.8)
337
+ const fusd=v=>v==null?'–':Math.abs(v)<.05?'$0':(v<0?MINUS:'+')+'$'+(Math.abs(v)<1000?Math.abs(v).toFixed(1):Math.round(Math.abs(v)).toLocaleString('en-US'));
338
+ const pc=v=>(v>=0?'+':MINUS)+Math.abs(v*100).toFixed(0)+'%';
339
+ const fh=s=>{const a=Math.abs(s),sg=s>=0?'+':MINUS;return a>=3600?sg+(a/3600).toFixed(1)+'h':sg+Math.round(a/60)+'m'};
340
+ const fha=s=>s>=3600?(s/3600).toFixed(1)+'h':Math.round(s/60)+'m';
341
+ const fm=s=>{const a=Math.abs(s)/60;return (s>=0?'+':MINUS)+(a>=10?Math.round(a):a.toFixed(1))+'m'};
342
+ // minutes on a basis; months switch to hours
343
+ const fmin=(v,basis)=>{if(v==null)return '–';if(Math.abs(v)<.05)return '0 min';const sg=v<0?MINUS:'+',a=Math.abs(v);
344
+ if(basis==='per_month'&&a>=120)return sg+(a/60).toFixed(1)+' h';return sg+(a>=100?Math.round(a):a.toFixed(1))+' min'};
345
+ // sign convention for deltas (vs default or current): arrow AND sign, '▼ −$429.3' saves (green), '▲ +$1.2' adds
346
+ // (amber). Absolute figures (a window's total cost, a level per day) carry neither, so the two never look alike.
347
+ const fsv=v=>v==null?'–':Math.abs(v)<.05?'$0':(v<0?'▼ −':'▲ +')+'$'+(Math.abs(v)<1000?Math.abs(v).toFixed(1):Math.round(Math.abs(v)).toLocaleString('en-US'));
348
+ const fmv=(v,basis)=>{if(v==null)return '–';const a=Math.abs(v);if(a<.05)return '0 min';const sg=v<0?'▼ −':'▲ +';
349
+ if(basis==='per_month'&&a>=120)return sg+(a/60).toFixed(1)+' h';return sg+(a>=100?Math.round(a):a.toFixed(1))+' min'};
350
+ // percent of the reference: cost vs its window cost, time vs its total wall-clock (the engine's d_cost_pct and
351
+ // d_time_pct); null when the reference is zero, and callers then lead with the amount
352
+ const pabs=v=>{const a=Math.abs(v*100);return a<10?a.toFixed(1):String(Math.round(a))};
353
+ const fpct=v=>v==null?'–':Math.abs(v*100)<.05?'0%':(v<0?'▼ −':'▲ +')+pabs(v)+'%';
354
+ const fpn=v=>v==null?'':Math.abs(v*100)<.05?'0%':(v<0?'−':'+')+pabs(v)+'%';
355
+ const fsn=v=>Math.abs(v)<.05?'$0':(v<0?'−':'+')+'$'+(Math.abs(v)<1000?Math.abs(v).toFixed(1):Math.round(Math.abs(v)).toLocaleString('en-US'));
356
+ const fmn=(v,basis)=>{const a=Math.abs(v);if(a<.05)return '0 min';const sg=v<0?'−':'+';if(basis==='per_month'&&a>=120)return sg+(a/60).toFixed(1)+' h';return sg+(a>=100?Math.round(a):a.toFixed(1))+' min'};
357
+ const ratio=(num,den)=>den>0?num/den:null;
358
+ function pctAt(g,thr,ref){const i=g.grid.indexOf(thr);if(i<0||!ref)return {c:null,t:null};
359
+ return {c:ratio(g.combined_cost[i]-ref.combined_cost,ref.combined_cost),t:ratio(g.time_s[i]-ref.time_s,ref.time_s)}}
360
+ // a delta led by the chosen unit with the other one small: '▼ −61% −$429.3' or '▼ −$429.3 −61%'
361
+ function dual(pv,lead,sec){const p=S.unit==='pct'&&pv!=null;return `<b class="ld">${p?fpct(pv):lead}</b><small class="sc">${p?sec:fpn(pv)}</small>`}
362
+ // per-day amounts of the default, the denominators for aggregated percents (summed amounts, never averaged percents)
363
+ const defUsd=g=>g.default.combined_cost/Math.max(g.days||1,1),defMin=g=>g.default.time_s/60/Math.max(g.days||1,1);
364
+ // One base for every aggregated percent (Overview cards, the chart's Total row, sidebar badges): the summed default
365
+ // per-day amount of the models with at least one "set" group (all their groups, as the chart's grey bars).
366
+ const setModel=(g,k=S.op)=>D.groups.some(x=>x.harness===g.harness&&x.model===g.model&&isSet(x,k));
367
+ const baseUsd=(gs,k=S.op)=>gs.reduce((a,g)=>a+(setModel(g,k)?defUsd(g):0),0),baseMin=(gs,k=S.op)=>gs.reduce((a,g)=>a+(setModel(g,k)?defMin(g):0),0);
368
+ const fdays=v=>(+v).toFixed(Math.abs(v-Math.round(v))<.05?0:1);
369
+ const day=ts=>new Date(ts*1000).toISOString().slice(0,10);
370
+ const dur=s=>{s=Math.max(0,s);return s<3600?Math.round(s/60)+'m':s<86400?(s/3600).toFixed(s<36000?1:0)+'h':(s/86400).toFixed(s<864000?1:0)+'d'};
371
+ const esc=t=>String(t).replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
372
+ const strip=h=>String(h).replace(/<[^>]*>/g,'');
373
+ // green saves, amber adds; arrows carry the direction
374
+ const tone=v=>v==null||Math.abs(v)<.05?'':v<0?'good':'warn';
375
+ const arrow=v=>v==null||Math.abs(v)<.05?'':v<0?'▼ ':'▲ ';
376
+ // ---------- i18n: English and Chinese, one language shown at a time ----------
377
+ const I={
378
+ tag:['Independent open-source tool. Not made or endorsed by any model or harness vendor; names only identify your own sessions. Computed locally, works offline.','独立开源工具,不是任何模型或工具厂商的产品,也未获其背书;名称只用来标识你自己的会话。在本机计算,可离线打开。'],
379
+ disclaimer:['Independent open-source tool · list-price estimates · recall is a lite-mode proxy','独立开源工具 · 按公开标价估算 · 召回率为 lite 模式代理值'],
380
+ thAuto:['Theme: follow system','主题:跟随系统'], thLight:['Theme: light','主题:浅色'], thDark:['Theme: dark','主题:深色'],
381
+ synthetic:['synthetic demo','合成演示'],
382
+ mRange:['History','历史范围'], mCal:['Calibration','校准'],
383
+ ago:[x=>'calibrated '+x+' ago',x=>x+'前校准'], nextIn:[x=>'next in '+x,x=>x+'后下次校准'], calOff:['manual only','仅手动'],
384
+ calStale:['stale: older than twice the interval','已过期:超过两倍校准间隔'], recal:['Recalibrate now','立即重新校准'],
385
+ recalBusy:['Recalibrating…','正在校准…'], recalFail:['Recalibration could not start','无法开始校准'],
386
+ drift:[(a,b)=>'drift: last applied '+a+', now recommends '+b,(a,b)=>'漂移:上次应用 '+a+',现在推荐 '+b], mSource:['Data source','数据来源'], mMode:['Mode','模式'], mSize:['Sample','样本'],
387
+ rangeTxt:[(a,b,d,ad)=>a+' → '+b+' · '+d+' d · '+ad+' active',(a,b,d,ad)=>a+' → '+b+' · '+d+' 天 · '+ad+' 活跃'],
388
+ rangeNo:[(d,ad)=>d+' d · '+ad+' active',(d,ad)=>d+' 天 · '+ad+' 活跃'],
389
+ srcLocal:[h=>'local '+h+' logs',h=>'本机 '+h+' 日志'],
390
+ modeLite:['lite','lite'], modeDeep:['deep','deep'],
391
+ sizeTxt:[(s,n)=>s+' sessions · '+n+' turns',(s,n)=>s+' 会话 · '+n+' 轮'],
392
+ caveat:['Costs are list-price estimates from replaying your own history against a public price table (no discounts, plans or credits). Time comes from your own timestamps; thin fits fall back to pooled data or a pessimistic prior. Recall is a lite-mode proxy (context-rot table × summary retention), only used as a floor. Profiles price your time at $10/h (cost), $250/h (balanced) and $600/h (time). Deltas are against the harness default unless marked “current”.',
393
+ '成本是按公开标价回放你自己历史得到的估算(不含折扣、套餐或额度)。时间来自你自己的时间戳;样本太少时改用同工具汇总数据或偏保守的先验值。召回率是 lite 模式的代理值(上下文衰减表 × 摘要保留率),只用作下限。三个方案给时间的价格:省钱 $10/小时,均衡 $250/小时,省时 $600/小时。除标明“当前”外,差值都相对 harness 默认值。'],
394
+ gear:['Profile','方案'], cost:['Cost','省钱'], balanced:['Balanced','均衡'], time:['Time','省时'], custom:['Custom','自定义'],
395
+ vot:[v=>'$'+v+'/h',v=>'$'+v+'/小时'], votL:[v=>'time valued at $'+v+' per hour',v=>'时间按每小时 $'+v+' 计'],
396
+ threshold:['Threshold','阈值'],
397
+ kMoney:['Money / day','费用 / 天'], kTimeD:['Wall-clock / day','耗时 / 天'], kRecall:['Recall (proxy)','召回(代理)'], kComp:['Compactions / day','压缩 / 天'],
398
+ uDay:['/day','/天'],
399
+ cVsDef:[x=>'vs default '+x,x=>'对默认 '+x], cVsCur:[x=>'vs current '+x,x=>'对当前 '+x],
400
+ cSplit:[(w,g)=>'wait '+w+' · turns '+g,(w,g)=>'等待 '+w+' · 每轮 '+g],
401
+ cFloor:[(f,d)=>'floor '+f+' · default '+d,(f,d)=>'下限 '+f+' · 默认 '+d],
402
+ cCompSub:[(d,m)=>'default '+d+' · '+m+'/mo',(d,m)=>'默认 '+d+' · '+m+'/月'],
403
+ pctTotal:['change in total cost','总成本变化'],
404
+ noAction:['No change needed: with the harness default these sessions never compact.','无需调整:按 harness 默认设置,这些会话从未触发压缩。'],
405
+ lowTime:[(a,b)=>'Rough time estimate: turn latency from '+a+', compaction latency from '+b+' (too few timed samples here).',(a,b)=>'时间估算较粗:每轮耗时来自'+a+',压缩耗时来自'+b+'(本组可计时样本太少)。'],
406
+ lowThin:[n=>'Thin data: '+n+' sessions. Treat as a rough guide.',n=>'数据偏少:'+n+' 个会话,仅供粗略参考。'],
407
+ lowDays:[d=>'Short history: '+d+' days; per-day and per-month figures extrapolate.',d=>'历史较短:'+d+' 天;每天和每月数字是外推的。'],
408
+ lowPen:[n=>'Re-discovery penalty uses a prior ('+n+' observed compactions; 5 needed).',n=>'找回惩罚用的是先验值(观察到 '+n+' 次压缩,需要 5 次)。'],
409
+ hImpact:['Per-day impact','每日影响'],
410
+ bDay:['Per day','每天'], bActive:['Per active day','每活跃天'], bMonth:['Per month','每月'], bLabel:['Basis','口径'],
411
+ uB_per_day:['day','天'], uB_per_active_day:['active day','活跃天'], uB_per_month:['month','月'],
412
+ iMoney:['money','费用'], iTime:['wall-clock','耗时'], iComp:['compactions','压缩次数'],
413
+ iFrac:[(p,w)=>p+'% of '+w,(p,w)=>w+' 的 '+p+'%'],
414
+ iCap:[(d,a)=>'▼ − saves · ▲ + adds · '+d+' d, '+a+' active',(d,a)=>'▼ − 节省 · ▲ + 增加 · '+d+' 天,'+a+' 活跃'],
415
+ iCapNo:[d=>'▼ − saves · ▲ + adds · '+d+' d',d=>'▼ − 节省 · ▲ + 增加 · '+d+' 天'],
416
+ iHelp:['For each profile vs the harness default and vs your current setting. Per day = total ÷ calendar days in the history; per active day = total ÷ days with at least one turn (closer to a heavy day of use); per month = per day × 30. Green saves, amber adds; red marks a broken guardrail. Time splits into compaction wait and faster turns from a smaller context. List-price estimates; recall is a lite-mode proxy.',
417
+ '每个方案分别对比 harness 默认值和你当前的设置。每天 = 总量 ÷ 历史覆盖的自然日;每活跃天 = 总量 ÷ 至少有一轮的天数(更接近重度使用的一天);每月 = 每天 × 30。绿色节省,琥珀色增加,红色表示护栏被突破。耗时拆成压缩等待和上下文变小带来的每轮提速。按公开标价估算;召回率是 lite 模式代理值。'],
418
+ iNoActive:['Active days are missing from this result; re-run compactlab simulate.','这份结果没有活跃天数;重新运行 compactlab simulate。'],
419
+ iSplitTip:[(w,g)=>'compaction wait '+w+' · faster turns '+g,(w,g)=>'压缩等待 '+w+' · 每轮提速 '+g],
420
+ saves:['saves','节省'], adds:['adds','增加'],
421
+ hCmp:['Compared with the default','与默认对比'], sCmp:['Whole-history totals for each profile, your current setting and the slider position.','各方案、当前设置和滑块位置在整段历史上的总量。'],
422
+ hTrade:['Trade-off','取舍'], hTime:['Time','时间'], hDeep:['Lite vs deep','lite 与 deep'], hHist:['Your history','你的历史'], hSess:['Sessions','会话'], hNotes:['Assumptions','假设'],
423
+ cTier:['profile','方案'], cWin:['window','阈值'], cAct:['action','建议'], cDc:['Δcost','成本差'], cDt:['Δwall-clock (/day)','耗时差(/天)'], cWait:['wait / day','等待/天'], cComp:['compactions / day','压缩/天'], cRec:['recall','召回'], cCur:['vs current','对当前'], cFlags:['',''],
424
+ rDefault:['default','默认'], rCurrent:['current','当前'], rSel:['slider','滑块'],
425
+ aSet:['change','建议改'], aKeep:['keep default','保持默认'], aCur:['keep current','保持当前'], aNo:['no change','无需调整'],
426
+ cmpNote:[(n,c)=>'Default: '+n+(c?' Current: '+c+'.':''),(n,c)=>'默认依据:'+n+(c?' 当前:'+c+'。':'')],
427
+ pTitle:['Pareto frontier','帕累托前沿'], pSub:['Each dot is a threshold; up and left is cheaper and safer (assumed recall). Profiles are ringed, the default is a square.','每个点是一个阈值;越靠左上越省钱、越安全(假设召回率)。圆圈是方案,方块是默认值。'],
428
+ pFloor:['recall floor','召回下限'],
429
+ coTitle:['Cost by threshold','各阈值成本'], coSub:['Replay cost (list price), re-discovery penalty and the profile score (cost + value of time × wall-clock). The band is the recommended range.','回放成本(标价)、找回惩罚和方案评分(成本 + 时间价值 × 耗时)。色带是推荐区间。'],
430
+ lCost:['cost','成本'], lPen:['penalty','惩罚'], lScore:['score','评分'], lDefault:['default','默认'],
431
+ tTitle:['Wall-clock vs default','耗时(对默认)'],
432
+ tSub:['Time saved by smaller contexts minus time added by compactions and re-discovery, from your own timestamps.','更小上下文省下的时间减去压缩和找回增加的时间,基于你自己的时间戳。'],
433
+ tSaved:['saved by smaller context','小上下文省下'], tAdded:['added by compactions','压缩增加'], tNet:['net','净变化'],
434
+ tConf:[(c,n,cc,cn,ts,cs)=>'Turn latency: '+c+' ('+n+' timed turns), using '+ts+'. Compaction latency: '+cc+' ('+cn+' samples), using '+cs+'.',(c,n,cc,cn,ts,cs)=>'每轮耗时:'+c+'('+n+' 个可计时轮次),采用'+ts+'。压缩耗时:'+cc+'('+cn+' 个样本),采用'+cs+'。'],
435
+ conf_ok:['ok','可信'], conf_low:['low confidence','置信度低'], conf_prior:['no usable data','无可用数据'],
436
+ src_own:['this group\'s fit','本组拟合'], src_pooled:['the pooled fit of this harness','同工具汇总拟合'], src_prior:['a pessimistic prior','偏保守的先验值'],
437
+ dLiteShort:['Lite only: recall is assumed.','只有 lite 结果:召回率为假设值。'],
438
+ dLite:['Run compactlab simulate --mode deep --budget N to measure recall at candidate thresholds (costs money; estimate shown first).','运行 compactlab simulate --mode deep --budget N 可在候选阈值实测召回(会花钱,先显示预估)。'],
439
+ dNone:['No deep samples for this group.','这个分组没有 deep 样本。'],
440
+ dHead:[(m,j,r,s,b)=>m+' summarizes, '+j+' judges ('+r+' votes). Spent '+s+' of '+b+'.',(m,j,r,s,b)=>m+' 生成摘要,'+j+' 评审('+r+' 票)。已花 '+s+',预算 '+b+'。'],
441
+ dAssumed:['assumed (lite)','假设(lite)'], dMeasured:['measured (deep)','实测(deep)'], dSamples:['samples','样本'], dDis:['lite and deep disagree by more than 0.1','lite 与 deep 相差超过 0.1'],
442
+ dLowered:[(p,t)=>'Measured recall at the lite '+p+' threshold fell below the floor; lowered to '+t+'.',(p,t)=>'lite '+p+' 方案阈值处的实测召回低于下限,已降到 '+t+'。'],
443
+ hTitle:['Where your tokens sit','token 分布'], hSub:['Share of turns (bars) and of read tokens (line) by context size. Right of the dashed line is what a lower threshold would cut.','按上下文大小统计的轮次占比(柱)和读取 token 占比(线)。虚线右侧是更低阈值会砍掉的部分。'],
444
+ hTurns:['turns','轮次'], hRead:['read tokens','读取 token'], hAbove:[(p,t)=>p+'% above '+t,(p,t)=>p+'% 高于 '+t],
445
+ sTitle:['History vs replay','历史与回放'], sSub:[t=>'Actual context (grey) and the same session replayed at '+t+' (colour).',t=>'真实上下文(灰)和同一会话在 '+t+' 下的回放(彩色)。'],
446
+ sAct:[n=>'actual · '+n,n=>'实际 · '+n], sRep:[n=>'replay · '+n,n=>'回放 · '+n],
447
+ filter:['Filter sessions','筛选会话'], of:[(a,b)=>a+' / '+b,(a,b)=>a+' / '+b],
448
+ colSession:['session','会话'], colHarness:['harness','工具'], colRole:['role','角色'], colModel:['model','模型'], colTurns:['turns','轮次'], colPeak:['peak','峰值'], colComp:['compactions','压缩'], colCtx:['context','上下文'],
449
+ nObs:[n=>'Penalty calibrated from '+n+' observed compactions.',n=>'惩罚参数由 '+n+' 次已观察到的压缩校准。'],
450
+ nPrice:[(k,s)=>'Prices: row “'+k+'” from '+s+'.',(k,s)=>'价格:“'+k+'” 这一行,来源 '+s+'。'],
451
+ nTtl:[(m,s)=>'Prompt cache: '+m+' ('+s+'); cache writes priced at that tier.',(m,s)=>'提示缓存:'+m+'('+s+'),缓存写入按该档计价。'],
452
+ nAssume:[(b,s,w)=>'Assumed base '+b+', summary '+s+', window '+w+'. Each profile = largest threshold within 2% of its lowest score, above the recall floor and inside its guardrails.',(b,s,w)=>'假设基础上下文 '+b+',摘要 '+s+',窗口 '+w+'。每个方案 = 在其最低评分 2% 以内、不低于召回下限且符合护栏的最大阈值。'],
453
+ f_below_quarter_window:['below 25% of the max window: frequent lossy compactions','低于最大窗口 25%:会频繁有损压缩'],
454
+ f_wait_over_cap:[c=>'adds more than '+c+' min/day of compaction wait',c=>'每天多等压缩超过 '+c+' 分钟'],
455
+ f_guardrail_applied:[(u,t)=>'guardrail moved the pick from '+u+' to '+t,(u,t)=>'护栏把选择从 '+u+' 调到 '+t],
456
+ f_recall_floor_not_met:['no threshold met the recall floor','没有阈值达到召回下限'],
457
+ f_wait_cap_unreachable:[c=>'no threshold keeps added wait under '+c+' min/day',c=>'没有阈值能把额外等待压到每天 '+c+' 分钟内'],
458
+ f_min_window_unreachable:['grid does not reach the minimum window','网格达不到最小窗口'],
459
+ f_deep_recall_below_floor:['deep: measured recall below floor, lowered','deep:实测召回低于下限,已下调'],
460
+ nEdge:['Optimum is at the lowest grid value; widen the grid or revisit the penalty assumptions.','最优值落在网格最低点,可以放宽网格或检查惩罚假设。'],
461
+ none:['No sessions found.','没有找到会话。'],
462
+ hCopy:['Copy settings','复制推荐设置'],
463
+ cpSub:['Ready-to-paste config per harness and scope. The report never writes files; use the merge line or compactlab apply.','按工具和作用范围生成的可粘贴配置。报告不会写文件;用合并命令或 compactlab apply。'],
464
+ cpHarness:['Harness','工具'], cpScope:['Scope','范围'], cpTier:['Profile','方案'], cpFormat:['Format','格式'],
465
+ global:['Global','全局'], project:['Project','项目'], agent:['Agent','agent'],
466
+ cpCopy:['Copy','复制'], cpCopied:['Copied','已复制'], cpFail:['Select the text and copy manually','请手动选中复制'],
467
+ cpNone:['Nothing to set for this choice:','这个选择下无需设置:'],
468
+ overview:['Overview','概览'], allModels:['All models','全部模型'], models:['Models','模型'], search:['Search models','搜索模型'],
469
+ rMain:['main','主'], rSub:['subagent','子 agent'], rMainS:['main','主'], rSubS:['sub','子'],
470
+ noChange:['No change needed','无需调整'], ncWhy:[(p,d)=>'peak '+p+' < '+d,(p,d)=>'峰值 '+p+' < '+d],
471
+ bTip:[u=>u+' per day vs default if the “set” groups are applied (est.; % of the default cost of the models marked “set”)',u=>'应用“设置”分组后每天 '+u+'(对默认,估算;% 为占“设置”模型默认费用的比例)'],
472
+ mTitle:['Cost and time by auto-compact threshold','各自动压缩阈值下的成本和时间'],
473
+ mHelp:['Top: money per day against the harness default; bottom: wall-clock minutes per day against the default. Both share the threshold axis. The grey bars behind are where your sessions actually peak; the hatched zone is below the recall floor (recall is a lite-mode proxy). Drag the chart or the slider (or focus the slider and use the arrow keys); ▼ saves, ▲ adds. List-price estimates.','上:每天费用相对 harness 默认值的变化;下:每天耗时(分钟)相对默认值的变化,两者共用阈值轴。背后的灰色柱是你的会话实际达到的峰值;斜线区域低于召回下限。拖动图表或滑块;▼ 节省,▲ 增加。'],
474
+ dUsd:['$ / day vs default','美元 / 天(对默认)'], dMin:['minutes / day vs default','分钟 / 天(对默认)'],
475
+ peaksL:['session peaks','会话峰值'], peaksTip:[(a,b,n)=>n+' sessions peak at '+a+'–'+b,(a,b,n)=>n+' 个会话峰值在 '+a+'–'+b],
476
+ unsafeL:[f=>'recall < '+f+' (proxy)',f=>'召回 < '+f+'(代理)'],
477
+ noopT:['Never reaches the threshold: nothing to tune.','从未达到压缩阈值:没有可调的。'],
478
+ noopSub:['Every session peaks below the default auto-compact threshold, so no threshold in range changes cost or time.','每个会话的峰值都低于默认自动压缩阈值,范围内的任何阈值都不会改变成本或时间。'],
479
+ mPeak:['peak','峰值'], zoneL:['auto-compacts here','此区间会自动压缩'],
480
+ kTotUsd:['Δ cost vs default','较默认费用'], kTotMin:['Δ time vs default','较默认耗时'], kToSet:['To change','需要调整'], kNoCh:['No change needed','无需调整'],
481
+ ovChart:['Before and after, per day','前后对比(每天)'],
482
+ ovCostT:['Cost per day (list price)','每日费用(按公开标价)'], ovTimeT:['Wall-clock per day (agent minutes)','每日耗时(agent 分钟)'],
483
+ scL:['Scale','比例'], stL:['Chart style','图表样式'], stBars:['bars: was and now overlaid','条形:原来与现在叠加'], stDots:['dots: was → now joined by a line','点线:原来 → 现在用线连接'], scAbs:['absolute','绝对值'], scNorm:['each row = 100%','每行 = 100%'], byL:['Sort','排序'], byUsd:['by amount saved','按节省金额'], byPct:['by % saved','按节省比例'],
484
+ axUsd:['$ per day, shared axis','美元/天,共用坐标'], axMin:['minutes per day, shared axis','分钟/天,共用坐标'], axNorm:['share of the original, each row = 100%','占原值比例,每行 = 100%'],
485
+ lgWas:['was (default)','原来(默认)'], lgNow:['now (profile)','现在(方案)'], lgSaved:['saved','节省'], lgAdded:['added','增加'],
486
+ lgLine:['grey = was (default), accent = now, green = saved, amber = added','灰色 = 原来(默认),强调色 = 现在,绿色 = 节省,琥珀色 = 增加'],
487
+ wasNow:[(a,b)=>'was '+a+' → now '+b,(a,b)=>'原来 '+a+' → 现在 '+b], totalSet:['Total','合计'], totalSub:[n=>n+' “set” models',n=>n+' 个“设置”模型'],
488
+ tWait:['compaction wait','压缩等待'], tTurn:['turn time','每轮耗时'],
489
+ srRow:[(n,w,c,v,p,tw,tn)=>n+': was '+w+' per day, now '+c+', '+v+' '+p+' percent; wall-clock was '+tw+', now '+tn,(n,w,c,v,p,tw,tn)=>n+':原来每天 '+w+',现在 '+c+','+v+' '+p+'%;耗时原来 '+tw+',现在 '+tn],
490
+ srKeep:[(n,w)=>n+': keep default, '+w+' per day',(n,w)=>n+':保持默认,每天 '+w], ovHelp:['Per model: the grey bar is the cost (or wall-clock) per day with the harness default, the accent bar the same with the chosen profile applied to its “set” groups; the green hatch between them is the saving, amber an addition. “Keep default” models show only the grey bar. The total sums the “set” models. Absolute shares one axis; “each row = 100%” makes every grey bar the same length. List-price estimates; hover a row for main / subagent and, for time, wait vs turn time.','所选方案相对 harness 默认值的每天费用估算,分为主会话和子 agent;每条右侧是每天分钟数。点击一行打开该模型。'],
491
+ ovTable:['Recommended settings','推荐设置'], cModel:['model','模型'], cRole:['role','角色'], cDef:['default','默认'], cUsd:['Δ $ / day','Δ 美元 / 天'], cMin:['Δ min / day','Δ 分钟 / 天'], cUsdP:['Δ cost %','Δ 费用 %'], cMinP:['Δ wall-clock %','Δ 总耗时 %'], sortBy:['Sort by','排序:'],
492
+ kTotPct:['% of the default cost (or wall-clock) per day of the models marked “set”: their summed change divided by their summed default, the same base as the chart\'s Total row and the sidebar badges; group percents are never averaged.','占“设置”模型默认每日费用(或耗时)的百分比:它们的变化之和除以它们的默认值之和,与图表合计行和侧栏徽标同一基数;不对分组百分比取平均。'],
493
+ tWin:['Window cost (total)','窗口总成本'], tDUsd:['Δ cost vs default','较默认费用'], tDMin:['Δ time vs default','较默认耗时'],
494
+ unitL:['Show changes as','变化显示为'], unit_pct:['percent of the default','占默认值的百分比'], unit_usd:['amount per day','每日金额'],
495
+ unitHelp:['% = change against the harness default for the same history: cost as a share of the default\'s window cost (list price) for that group, time as a share of the default\'s total wall-clock. Totals divide summed amounts by summed defaults, never average percents. $ = the change per calendar day. Toggle % | $ to lead with either; the other is shown small.','% = 同一段历史下相对 harness 默认值的变化:费用占该分组默认窗口成本(按公开标价)的比例,时间占默认总耗时的比例。汇总值是加总金额除以加总默认值,不对百分比取平均。$ = 每个自然日的变化。用 % | $ 切换主显示,另一个以小字显示。'],
496
+ wCost:['cost','费用'], wTime:['time','耗时'], perDayS:['per day','每天'], pcCost:['of the default\'s cost','占默认费用'], pcTime:['of the default\'s wall-clock','占默认耗时'],
497
+ dPct:['cost vs default (%)','费用(对默认,%)'], dPctT:['wall-clock vs default (%)','耗时(对默认,%)'], tComp:['Compactions / day','每日压缩次数'],
498
+ votS:[v=>'time @ $'+v+'/h',v=>'时间 @ $'+v+'/小时'], est:['est.','估算'],
499
+ indepL:['Independent open-source tool · not affiliated with any model vendor · list-price estimates','独立开源工具 · 与任何模型厂商无关 · 按公开标价估算'],
500
+ bKeep:[u=>'keep default: '+u+' per day if set anyway (est.)',u=>'保持默认:若仍设置,每天 '+u+'(估算)'], bSess:[n=>n+' sessions',n=>n+' 个会话'],
501
+ vsDefL:[d=>'per day vs default '+d,d=>'每天,对默认 '+d], vsCurL:[c=>'vs current '+c,c=>'对当前 '+c], noDiff:['no difference','没有差别'],
502
+ noCur:['no current setting found · compared with the default','没有找到当前设置 · 与默认值比较'], noCurS:['no current setting','无当前设置'],
503
+ cpKeep:['keep default: nothing to set here','保持默认:这里无需设置'], cpOneTip:[x=>'Copy: '+x,x=>'复制:'+x],
504
+ cmpS:['/d','/天'], compAtDef:[n=>n+' compactions at default',n=>'默认下压缩 '+n+' 次'],
505
+ peaksK:[n=>'session peaks (tallest '+n+')',n=>'会话峰值(最高 '+n+')'], unsafeK:[f=>'recall < '+f+' (lite proxy)',f=>'召回 < '+f+'(lite 代理值)'],
506
+ kTotSub:[n=>'if the '+n+' “set” models are applied',n=>'应用 '+n+' 个“设置”模型时'], kKeep:['Keep default','保持默认'], mUnit:['models','个模型'],
507
+ kwAbove:[(a,b)=>'keep default: '+a+' is not below the default '+b,(a,b)=>'保持默认:'+a+' 不低于默认值 '+b],
508
+ kwScore:[(v,n)=>'keep default: no net gain at $'+v+'/h (net '+n+' per day)',(v,n)=>'保持默认:按 $'+v+'/小时 没有净收益(每天净 '+n+')'],
509
+ kwCur:[(p,c,tl,v,n)=>'keep current: '+p+' would not beat your '+c+' by more than '+tl+'% at $'+v+'/h (net '+n+' per day)',(p,c,tl,v,n)=>'保持当前:按 $'+v+'/小时,'+p+' 比你现在的 '+c+' 好不到 '+tl+'%(每天净 '+n+')'],
510
+ kwSmall:[(v,n,p)=>'keep default: net gain under '+p+'% at $'+v+'/h ('+n+' per day)',(v,n,p)=>'保持默认:按 $'+v+'/小时 净收益不到 '+p+'%(每天 '+n+')'],
511
+ kwWorth:[(v,u,m,tv)=>'keep default: not worth it at $'+v+'/h · saves '+u+'/day but adds '+m+'/day of wall-clock (= '+tv+')',(v,u,m,tv)=>'保持默认:按 $'+v+'/小时 不划算 · 每天省 '+u+',但总耗时每天多 '+m+'(折合 '+tv+')'],
512
+ hSessG:[x=>'Sessions · '+x,x=>'会话 · '+x], hSessAll:['All sessions','全部会话'],
513
+ ovRange:[(a,b,n)=>a+' → '+b+' · '+n+' models',(a,b,n)=>a+' → '+b+' · '+n+' 个模型']
514
+ };
515
+ const S={gi:0,gear:'balanced',T:null,vot:100,lang:'en',sid:null,basis:'per_day',theme:'auto',view:'group',op:'balanced',fold:{},unit:'pct',ovSort:null,ovScale:'abs',ovBy:'usd',ovStyle:null};
516
+ let sortK='peak',asc=false;
517
+ const PROF=['cost','balanced','time'],PICON={cost:'coin',balanced:'scale',time:'clock',custom:'sliders'};
518
+ // a broken guardrail is red, a warning amber (cost below a quarter of the window, more wait than the cap),
519
+ // and a plain note (a guardrail moved the pick, deep lowered it) an info icon, not a warning
520
+ const VIOL=f=>['recall_floor_not_met','wait_cap_unreachable','min_window_unreachable'].includes(f);
521
+ const NOTE=f=>['guardrail_applied','deep_recall_below_floor'].includes(f);
522
+ const flagKind=f=>VIOL(f)?'bad':NOTE(f)?'':'low';
523
+ S.lang=/^zh/i.test(navigator.language||'')?'zh':'en';
524
+ try{const l=localStorage.getItem('compactlab.lang');if(l==='en'||l==='zh')S.lang=l;const th=localStorage.getItem('compactlab.theme');if(th)S.theme=th;
525
+ const un=localStorage.getItem('compactlab.unit');if(un==='pct'||un==='usd')S.unit=un;
526
+ const sc=localStorage.getItem('compactlab.ovScale');if(sc==='abs'||sc==='norm')S.ovScale=sc;const ob=localStorage.getItem('compactlab.ovBy');if(ob==='usd'||ob==='pct')S.ovBy=ob;
527
+ const os=localStorage.getItem('compactlab.ovStyle');if(os==='bars'||os==='dots')S.ovStyle=os;
528
+ const fo=JSON.parse(localStorage.getItem('compactlab.fold')||'{}');if(fo&&typeof fo==='object')S.fold=fo}catch(e){}
529
+ function applyTheme(){if(S.theme==='auto')delete document.documentElement.dataset.theme;else document.documentElement.dataset.theme=S.theme}
530
+ applyTheme();
531
+ function t(k,...a){const v=I[k];if(!v)return k;const x=v[S.lang==='zh'?1:0];return typeof x==='function'?x(...a):x}
532
+ function el(n,a,x){const e=document.createElementNS(NS,n);for(const k in a)e.setAttribute(k,a[k]);if(x!=null)e.textContent=x;return e}
533
+ // inline SVG icon; with a label it is announced, otherwise hidden from assistive tech
534
+ function ic(n,label){return `<svg class="ic" ${label?`role="img" aria-label="${esc(label)}"`:'aria-hidden="true"'}><use href="#i-${n}"/></svg>`}
535
+ // icon button with a hover/focus/tap tooltip; the tooltip text is also its accessible name
536
+ function ib(text,icon='info',cls=''){const s=strip(text);return `<button type="button" class="ib ${cls}" data-tip="${esc(s)}" aria-label="${esc(s)}">${ic(icon)}</button>`}
537
+ function chip(text,cls,icon,tip,attrs=''){return `<span class="chip ${cls||''}"${attrs}${tip?` tabindex="0" data-tip="${esc(tip)}" aria-label="${esc(tip)}"`:''}>${icon?ic(icon):''}${text}</span>`}
538
+ const G=()=>D.groups[S.gi];
539
+ const SC=g=>g.grid.map((_,i)=>g.combined_cost[i]+g.time_s[i]/3600*S.vot);
540
+ const SCp=(g,p)=>p.combined_cost+p.time_s/3600*S.vot;
541
+ function pt(g,i){return {threshold:g.grid[i],combined_cost:g.combined_cost[i],time_s:g.time_s[i],time_turns_s:g.time_turns_s[i],time_compact_s:g.time_compact_s[i],time_redisc_s:g.time_redisc_s[i],compactions:g.compactions[i],recall:g.recall[i]}}
542
+ function cmp(a,r,g=G()){const days=Math.max(g.days||1,1);return {dc:a.combined_cost-r.combined_cost,dcp:r.combined_cost?(a.combined_cost-r.combined_cost)/r.combined_cost:0,dt:a.time_s-r.time_s,dtd:(a.time_s-r.time_s)/days,
543
+ saved:r.time_turns_s-a.time_turns_s,added:(a.time_compact_s+a.time_redisc_s)-(r.time_compact_s+r.time_redisc_s),addd:((a.time_compact_s+a.time_redisc_s)-(r.time_compact_s+r.time_redisc_s))/days,cpd:a.compactions/days,dr:a.recall-r.recall}}
544
+ // same arithmetic as compactlab.sim.select.impact (used for the slider position; profiles use the stored numbers)
545
+ function impJS(a,r,g=G()){const days=Math.max(g.days||1,1),act=g.active_days?Math.max(g.active_days,1):null,c=cmp(a,r,g);
546
+ const per=(x,s=1)=>({per_day:x*s/days,per_active_day:act?x*s/act:null,per_month:x*s/days*30});
547
+ return {days,active_days:act,usd:per(c.dc),minutes:per(c.dt,1/60),wait_minutes:per(c.added,1/60),turn_gain_minutes:per(c.saved,1/60),compactions:per(a.compactions),ref_compactions:per(r.compactions)}}
548
+ function impOf(g,k,ref){const c=g.comparison[k][ref];if(!c)return null;if(c.impact)return c.impact;
549
+ return impJS(pt(g,g.grid.indexOf(g.profiles[k].threshold)),ref==='vs_default'?g.default:g.current,g)}
550
+ // a group's headline: per-day money and minutes of a profile against the default (0 when nothing compacts)
551
+ const usdOf=(g,k=S.op)=>{if(g.no_action_needed)return 0;const im=impOf(g,k,'vs_default');return im?im.usd.per_day:0};
552
+ const minOf=(g,k=S.op)=>{if(g.no_action_needed)return 0;const im=impOf(g,k,'vs_default');return im?im.minutes.per_day:0};
553
+ // ---------- model names: family from the id, date suffixes only in the tooltip ----------
554
+ const cap=s=>s.charAt(0).toUpperCase()+s.slice(1);
555
+ const baseId=m=>String(m).replace(/-\d{8}$/,'');
556
+ function family(m){const b=baseId(m),x=/^claude-([a-z]+)/.exec(b);if(x)return cap(x[1]);if(/^gpt/i.test(b))return 'GPT';return cap(b.split(/[-_./:]/)[0]||b)}
557
+ function label(m){const b=baseId(m);let x=/^claude-[a-z]+-(\d+(?:-\d+)*)$/.exec(b);if(x)return family(m)+' '+x[1].replace(/-/g,'.');
558
+ x=/^gpt-(.+)$/i.exec(b);if(x)return 'GPT-'+x[1];return b}
559
+ const roleS=r=>r==='main'?t('rMainS'):r==='subagent'?t('rSubS'):r,roleL=r=>r==='main'?t('rMain'):r==='subagent'?t('rSub'):r;
560
+ const roleIc=r=>r==='subagent'?'bot':'user';
561
+ // compact signed money for badges: '−$12.9', '−$140'
562
+ const fus=v=>Math.abs(v)<.05?'':(v<0?'▼−':'▲+')+'$'+(Math.abs(v)>=100?Math.round(Math.abs(v)):Math.abs(v).toFixed(1));
563
+ // totals count only groups whose action is "set": a "keep default" group would not be changed
564
+ const isSet=(g,k=S.op)=>!g.no_action_needed&&action(g,g.profiles[k].threshold,g.profiles[k].value_of_time)==='aSet';
565
+ const setUsd=(g,k=S.op)=>isSet(g,k)?usdOf(g,k):0,setMin=(g,k=S.op)=>isSet(g,k)?minOf(g,k):0;
566
+ // the group with the largest per-day money impact, never one that needs no change; ties by turns
567
+ function best(){const key=g=>[isSet(g)?1:0,Math.abs(usdOf(g)),g.n_turns];let b=-1,bk=null;
568
+ D.groups.forEach((g,i)=>{if(g.no_action_needed)return;const k=key(g);if(!bk||k[0]>bk[0]||(k[0]===bk[0]&&(k[1]>bk[1]+1e-9||(Math.abs(k[1]-bk[1])<=1e-9&&k[2]>bk[2])))){b=i;bk=k}});return b}
569
+ function tolOf(){return (D.options&&D.options.tolerance!=null)?D.options.tolerance:0.02}
570
+ function action(g,thr,vot){if(g.no_action_needed)return 'aNo';const d=g.default,i=g.grid.indexOf(thr),p=pt(g,i),c=g.current;
571
+ if(c&&c.combined_cost+c.time_s/3600*vot<=(p.combined_cost+p.time_s/3600*vot)*(1+tolOf()))return 'aCur';
572
+ return (thr>=d.threshold||d.combined_cost+d.time_s/3600*vot<=(p.combined_cost+p.time_s/3600*vot)*(1+tolOf()))?'aKeep':'aSet'}
573
+ // why a threshold keeps the default: the same tests as action() and compactlab.sim.engine._comparison
574
+ function actOf(g,k=S.op){return action(g,g.profiles[k].threshold,g.profiles[k].value_of_time)}
575
+ function keepWhy(g,thr,vot){const d=g.default;if(g.no_action_needed)return '';
576
+ if(action(g,thr,vot)==='aCur'){const im=impJS(pt(g,g.grid.indexOf(thr)),g.current,g),n=im.usd.per_day+im.minutes.per_day/60*vot;
577
+ return t('kwCur',fk(thr),fk(g.current.configured??g.current.threshold),+(tolOf()*100).toFixed(1),vot,fsv(n))}
578
+ if(thr>=d.threshold)return t('kwAbove',fk(thr),fk(d.threshold));
579
+ const im=impJS(pt(g,g.grid.indexOf(thr)),d,g),u=im.usd.per_day,m=im.minutes.per_day,tv=m/60*vot;
580
+ if(u+tv<0)return t('kwSmall',vot,fsv(u+tv),+(tolOf()*100).toFixed(1));
581
+ if(u<0&&m>0)return t('kwWorth',vot,'$'+(-u).toFixed(1),m.toFixed(1)+' min','$'+tv.toFixed(1));
582
+ return t('kwScore',vot,fsv(u+tv))}
583
+ function paretoIdx(sc,rc){return sc.map((_,i)=>i).filter(i=>!sc.some((_,j)=>sc[j]<=sc[i]&&rc[j]>=rc[i]&&(sc[j]<sc[i]||rc[j]>rc[i])))}
584
+ function setGear(k){S.gear=k;if(k!=='custom'){S.T=G().profiles[k].threshold;S.vot=G().profiles[k].value_of_time}update()}
585
+ function setT(T){S.gear=PROF.find(k=>G().profiles[k].threshold===T&&k===S.gear)||'custom';S.T=T;update()}
586
+ function nearest(g,v){let b=0;g.grid.forEach((x,i)=>{if(Math.abs(x-v)<Math.abs(g.grid[b]-v))b=i});return b}
587
+ // re-render a box without losing keyboard focus or scroll position
588
+ function keep(fn){const a=document.activeElement,key=a&&a.dataset?Object.entries(a.dataset).filter(([k])=>k!=='tip').map(([k,v])=>`[data-${k}="${v}"]`).join(''):'',y=scrollY;fn();
589
+ if(key){const n=document.querySelector(key);if(n&&n!==a)n.focus({preventScroll:true})}if(scrollY!==y)scrollTo(0,y)}
590
+ function flagText(f,p){const k='f_'+f;return I[k]?t(k,f==='guardrail_applied'?fk(p.unconstrained_threshold):p.wait_cap_min_per_day,fk(p.threshold)):f}
591
+ function flagIcons(P){return P?P.flags.map(f=>ib(flagText(f,P),NOTE(f)?'info':'warn',flagKind(f))).join(''):''}
592
+ function frame(W,H,m){const svg=el('svg',{viewBox:`0 0 ${W} ${H}`,role:'img'});return {svg,x0:m.l,x1:W-m.r,y0:H-m.b,y1:m.t}}
593
+ function axes(f,X,Y,xt,yt,xf,yf){for(const v of yt){f.svg.append(el('line',{x1:f.x0,x2:f.x1,y1:Y(v),y2:Y(v),class:'grid'}));f.svg.append(el('text',{x:f.x0-6,y:Y(v)+3.5,'text-anchor':'end'},yf(v)))}
594
+ for(const v of xt)f.svg.append(el('text',{x:X(v),y:f.y0+16,'text-anchor':'middle'},xf(v)));f.svg.append(el('line',{x1:f.x0,x2:f.x1,y1:f.y0,y2:f.y0,class:'ax'}))}
595
+ const ticks=(lo,hi,n)=>Array.from({length:n+1},(_,i)=>lo+(hi-lo)*i/n);
596
+ // direct labels: [{x,y,text,color,anchor}] nudged apart vertically so they never overlap
597
+ function dlabels(f,items,gap=12){items.sort((a,b)=>a.y-b.y);for(let i=1;i<items.length;i++)if(items[i].y-items[i-1].y<gap)items[i].y=items[i-1].y+gap;
598
+ const over=items.length?items[items.length-1].y-(f.y0-4):0;if(over>0)items.forEach(it=>it.y-=over);
599
+ for(const it of items)f.svg.append(el('text',{x:it.x,y:it.y,'text-anchor':it.anchor||'end',class:'dl',style:'fill:'+it.color+(it.bold?';font-weight:600':'')},it.text))}
600
+ function line(f,X,Y,xs,v,c,w,d){f.svg.append(el('polyline',{points:xs.map((x,i)=>X(x)+','+Y(v[i])).join(' '),fill:'none',stroke:c,'stroke-width':w,'stroke-dasharray':d||'','stroke-linejoin':'round','stroke-linecap':'round'}))}
601
+ function figHead(box,title,sub,extra=''){box.innerHTML=`<h3>${title}${ib(sub)}${extra}</h3>`}
602
+ // ---------- tooltips for every [data-tip] element: hover, keyboard focus, tap ----------
603
+ const tipNode=e=>e.target&&e.target.closest?e.target.closest('[data-tip]'):null;
604
+ function tipAt(n){const r=n.getBoundingClientRect();showTip(esc(n.dataset.tip),r.left,r.bottom+4,true)}
605
+ document.addEventListener('pointerover',e=>{const n=tipNode(e);if(n)tipAt(n)});
606
+ document.addEventListener('pointerout',e=>{if(tipNode(e))hideTip()});
607
+ document.addEventListener('focusin',e=>{const n=tipNode(e);if(n)tipAt(n)});
608
+ document.addEventListener('focusout',e=>{if(tipNode(e))hideTip()});
609
+ document.addEventListener('click',e=>{const n=tipNode(e);if(n&&n.classList.contains('ib'))tipAt(n)});
610
+ document.addEventListener('keydown',e=>{if(e.key==='Escape')hideTip()});
611
+ function statics(){
612
+ document.documentElement.lang=S.lang;
613
+ for(const k of ['hImpact','hCmp','hCopy','hTrade','hTime','hDeep','hHist','hSess'])$('#'+k).textContent=t(k);
614
+ $('#hNotes').innerHTML=ic('info')+'<span>'+t('hNotes')+'</span>';
615
+ $('#iImpact').innerHTML=ib(t('iHelp'));$('#iCmp').innerHTML=ib(t('sCmp'));$('#iCopy').innerHTML=ib(t('cpSub'));
616
+ $('#foot').innerHTML='<span>'+esc(t('disclaimer'))+'</span>'+ib(t('tag'));$('#indep').textContent=t('indepL');
617
+ $('#q').placeholder=t('filter');$('#q').setAttribute('aria-label',t('filter'));
618
+ $('#langs').innerHTML=[['en','EN','English'],['zh','中','中文']].map(([k,l,a])=>`<button data-l="${k}" aria-pressed="${S.lang===k}" aria-label="${a}">${l}</button>`).join('');
619
+ $('#units').setAttribute('aria-label',t('unitL'));
620
+ $('#units').innerHTML=[['pct','%'],['usd','$']].map(([k,l])=>`<button data-unit="${k}" aria-pressed="${S.unit===k}" aria-label="${t('unit_'+k)}">${l}</button>`).join('');
621
+ $('#unitI').innerHTML=ib(t('unitHelp'));
622
+ document.querySelectorAll('#units button').forEach(b=>b.onclick=()=>{S.unit=b.dataset.unit;try{localStorage.setItem('compactlab.unit',S.unit)}catch(e){}S.tree=null;keep(()=>{statics();render()})});
623
+ document.querySelectorAll('#langs button').forEach(b=>b.onclick=()=>{S.lang=b.dataset.l;try{localStorage.setItem('compactlab.lang',S.lang)}catch(e){}keep(()=>{statics();render();renderS()})});
624
+ $('#themes').innerHTML=[['auto','auto','thAuto'],['light','sun','thLight'],['dark','moon','thDark']].map(([k,i,l])=>`<button data-th="${k}" aria-pressed="${S.theme===k}" aria-label="${t(l)}" title="${t(l)}">${ic(i)}</button>`).join('');
625
+ document.querySelectorAll('#themes button').forEach(b=>b.onclick=()=>{S.theme=b.dataset.th;try{localStorage.setItem('compactlab.theme',S.theme)}catch(e){}applyTheme();keep(statics)});
626
+ $('#tq').placeholder=t('search');$('#tq').setAttribute('aria-label',t('search'));$('#tree').setAttribute('aria-label',t('models'));
627
+ tree()}
628
+ // ---------- sidebar tree: harness > family > model (role chips on the row), sorted by impact ----------
629
+ // Models whose every role needs no change go to a collapsed bucket at the bottom with a one-line reason.
630
+ function buildTree(){const H=new Map(),nc=[];
631
+ D.groups.forEach((g,i)=>{const fam=family(g.model);if(!H.has(g.harness))H.set(g.harness,{key:'h:'+g.harness,name:g.harness,fams:new Map()});
632
+ const h=H.get(g.harness);if(!h.fams.has(fam))h.fams.set(fam,{key:'f:'+g.harness+'/'+fam,name:fam,models:new Map()});
633
+ const f=h.fams.get(fam);if(!f.models.has(g.model))f.models.set(g.model,{id:g.model,harness:g.harness,name:label(g.model),gs:[]});f.models.get(g.model).gs.push(i)});
634
+ const agg=(o,gs)=>{const G_=gs.map(i=>D.groups[i]);o.usd=G_.reduce((a,g)=>a+setUsd(g),0);o.keep=G_.reduce((a,g)=>a+(isSet(g)?0:usdOf(g)),0);
635
+ o.w=G_.reduce((a,g)=>a+Math.abs(setUsd(g)),0)+1e-6*G_.reduce((a,g)=>a+Math.abs(usdOf(g)),0);
636
+ o.den=baseUsd(G_);o.keepDen=G_.reduce((a,g)=>a+defUsd(g),0);o.n=G_.reduce((a,g)=>a+g.n_sessions,0);o.turns=G_.reduce((a,g)=>a+g.n_turns,0);return o};
637
+ const byW=(a,b)=>b.w-a.w||b.turns-a.turns,hs=[];
638
+ for(const h of H.values()){const fams=[];
639
+ for(const f of h.fams.values()){const ms=[...f.models.values()];
640
+ // two ids with the same display name (a dated and an undated id) keep the suffix visible
641
+ ms.forEach(m=>{if(m.id!==baseId(m.id)&&ms.some(o=>o!==m&&o.name===m.name))m.name+=' · '+m.id.slice(baseId(m.id).length+1)});
642
+ for(const m of ms){m.gs.sort((a,b)=>Math.abs(usdOf(D.groups[b]))-Math.abs(usdOf(D.groups[a]))||(D.groups[a].role==='main'?-1:1));agg(m,m.gs);
643
+ m.noop=m.gs.every(i=>D.groups[i].no_action_needed);m.fam=f.name;if(m.noop)nc.push(m)}
644
+ f.models=ms.filter(m=>!m.noop).sort(byW);if(f.models.length)fams.push(agg(f,f.models.flatMap(m=>m.gs)))}
645
+ h.fams=fams.sort(byW);if(fams.length)hs.push(agg(h,fams.flatMap(f=>f.models.flatMap(m=>m.gs))))}
646
+ return {hs:hs.sort(byW),nc:nc.sort((a,b)=>b.turns-a.turns)}}
647
+ // per role, so the reason matches the page it opens: 'peak main 416k · sub 506k < 967k'
648
+ function ncWhy(m){const gs=m.gs.map(i=>D.groups[i]);return t('ncWhy',gs.map(g=>(gs.length>1?roleS(g.role)+' ':'')+fk(g.peak_max||0)).join(' · '),fk(gs[0].default.threshold))}
649
+ // money per day of the groups that would be set (muted: only "keep default" figures), and the session count
650
+ function badge(o){const muted=Math.abs(o.usd)<.05&&Math.abs(o.keep||0)>=.05,v=muted?o.keep:o.usd,pv=ratio(v,muted?o.keepDen:o.den);
651
+ const both=fsv(v)+(pv!=null?' ('+fpn(pv)+')':''),tip=(muted?t('bKeep',both):t('bTip',both))+' · '+t('bSess',o.n);
652
+ const txt=S.unit==='pct'&&pv!=null?(Math.abs(pv*100)<.05?'':(v<0?'▼−':'▲+')+pabs(pv)+'%'):fus(v);
653
+ return `<span class="bdg ${muted?'mute':tone(v)}" data-tip="${esc(tip)}">${txt}<i>${ic('flag')}${o.n}</i></span>`}
654
+ function tree(){const T=S.tree||(S.tree=buildTree()),q=$('#tq').value.trim().toLowerCase(),box=$('#tree'),sel=S.view==='overview'?null:G();
655
+ const hit=m=>!q||(m.id+' '+m.name+' '+m.harness+' '+m.fam).toLowerCase().includes(q);
656
+ const isSel=m=>sel&&m.id===sel.model&&m.harness===sel.harness;
657
+ const open=(key,inside)=>q?true:key in S.fold?S.fold[key]:inside;
658
+ const fold=(key,cls,head,inner,inside)=>{const o=open(key,inside);return `<div class="node ${cls}"><button type="button" class="fold" data-fold="${esc(key)}" aria-expanded="${o}">${ic('chev')}${head}</button><div class="kids"${o?'':' hidden'}>${inner}</div></div>`};
659
+ const mrow=(m,why)=>{const cur=isSel(m),g0=D.groups[m.gs[0]];
660
+ const roles=m.gs.length>1?m.gs.map(i=>{const g=D.groups[i];return `<button type="button" class="rc" data-tab="${i}" aria-pressed="${cur&&i===S.gi}" aria-label="${esc(m.name+' · '+roleL(g.role))}" data-tip="${esc(roleL(g.role)+' · '+(g.no_action_needed?t('noChange'):fsv(usdOf(g))+t('uDay')+(isSet(g)?'':' · '+t(actOf(g))))+' · '+g.n_sessions)}">${ic(roleIc(g.role))}${esc(roleS(g.role))}</button>`}).join('')
661
+ :`<span class="rt">${ic(roleIc(g0.role))}${esc(roleS(g0.role))}</span>`;
662
+ return `<div class="mrow${cur?' cur':''}"><button type="button" class="mn" data-tab="${m.gs[0]}" title="${esc(m.id)}" aria-label="${esc(m.name)}"${cur?' aria-current="page"':''}><span class="nm">${esc(m.name)}</span>${why?`<span class="why">${esc(why)}</span>`:''}</button>${why?'':badge(m)}<span class="roles">${roles}</span></div>`};
663
+ const all=T.hs.flatMap(h=>h.fams.flatMap(f=>f.models.flatMap(m=>m.gs)));
664
+ let h=`<button type="button" class="ovr" data-ov="1"${S.view==='overview'?' aria-current="page"':''}>${ic('grid')}<span class="nm">${t('overview')}</span>${badge({usd:all.reduce((a,i)=>a+setUsd(D.groups[i]),0),den:baseUsd(D.groups),n:D.groups.reduce((a,g)=>a+g.n_sessions,0)})}</button>`;
665
+ for(const H_ of T.hs){const inner=H_.fams.map(f=>{const ms=f.models.filter(hit);if(!ms.length)return '';
666
+ return fold(f.key,'fam',`<span class="nm">${esc(f.name)}</span>${badge(f)}`,ms.map(m=>mrow(m)).join(''),ms.some(isSel))}).join('');
667
+ if(inner)h+=fold(H_.key,'har',`<span class="nm">${esc(H_.name)}</span>${badge(H_)}`,inner,H_.fams.some(f=>f.models.some(isSel)))}
668
+ const nc=T.nc.filter(hit);
669
+ if(nc.length)h+=fold('nc','nc',ic('check')+`<span class="nm">${t('noChange')}</span><span class="bdg"><i>${nc.length}</i></span>`,nc.map(m=>mrow(m,m.harness+' · '+ncWhy(m))).join(''),nc.some(isSel));
670
+ box.innerHTML=h;
671
+ box.querySelectorAll('[data-fold]').forEach(b=>b.onclick=()=>{const k=b.dataset.fold,o=b.getAttribute('aria-expanded')!=='true';S.fold[k]=o;
672
+ try{localStorage.setItem('compactlab.fold',JSON.stringify(S.fold))}catch(e){}b.setAttribute('aria-expanded',o);b.nextElementSibling.hidden=!o});
673
+ box.querySelectorAll('[data-tab]').forEach(b=>b.onclick=()=>pick(+b.dataset.tab));
674
+ box.querySelector('[data-ov]').onclick=overview;
675
+ $('#drwL').textContent=sel?label(sel.model)+' · '+roleS(sel.role):t('overview');$('#drawer').setAttribute('aria-label',t('models')+': '+$('#drwL').textContent)}
676
+ function closeDrawer(){$('#side').classList.remove('open');$('#drawer').setAttribute('aria-expanded','false')}
677
+ $('#drawer').onclick=()=>{const o=!$('#side').classList.contains('open');$('#side').classList.toggle('open',o);$('#drawer').setAttribute('aria-expanded',o)};
678
+ $('#tq').oninput=()=>tree();
679
+ function header(){const g=G(),d=fdays(Math.max(g.days,1)),ad=g.active_days!=null?fdays(g.active_days):'?';
680
+ $('#eyebrow').textContent=g.harness+' · '+family(g.model);$('#title').innerHTML=esc(label(g.model))+' <span class="rl">· '+esc(roleL(g.role))+'</span>';$('#title').title=g.model;
681
+ const range=g.span?t('rangeTxt',day(g.span[0]),day(g.span[1]),d,ad):t('rangeNo',d,ad);
682
+ const src=D.demo?'<span class="badge">'+t('synthetic')+'</span>':esc(t('srcLocal',g.harness));
683
+ $('#meta').innerHTML=mi('cal','mRange',esc(range))+mi('db','mSource',src)+mi('layers','mMode',t(D.mode==='deep'?'modeDeep':'modeLite')+(D.generated?' · '+esc(D.generated.replace('data through ','≤ ')):''))+
684
+ mi('flag','mSize',esc(t('sizeTxt',g.n_sessions,g.n_turns.toLocaleString('en-US'))))+calMeta(g)+ib(t('caveat'))}
685
+ const mi=(icon,lab,v)=>`<span class="mi${lab==='mSource'||lab==='mMode'?' opt':''}">${ic(icon,t(lab))}${v}</span>`;
686
+ // calibration age, next run, drift since the last auto-apply, and (when served) a recalibrate button
687
+ function calMeta(g){const sv=D.service,c=D.calibration||{},at=sv?sv.last_calibrated:c.at;if(!at&&!sv)return '';
688
+ const now=Date.now()/1000,every=sv?sv.every_s:c.every_s,stale=!at||now-at>2*(every||86400);
689
+ let h=at?esc(t('ago',dur(now-at))):'–';if(sv)h+=' · '+esc(sv.next_calibration?t('nextIn',dur(sv.next_calibration-now)):t('calOff'));
690
+ let out=`<span class="mi${stale?' warn':''}">${ic('clock',t('mCal'))}${h}</span>`;if(stale)out+=ib(t('calStale'),'warn','low');
691
+ if(sv)out+=`<button type="button" class="ib" id="recal" aria-label="${t('recal')}" data-tip="${t('recal')}">${ic('refresh')}</button>`;
692
+ const ap=g&&sv&&sv.applied&&sv.applied[g.model],rec=g&&g.profiles[g.profile].threshold;
693
+ if(ap&&ap.value!==rec)out+=ib(t('drift',fk(ap.value),fk(rec)),'warn','low');
694
+ return out}
695
+ async function recalibrate(){const b=$('#recal');if(!b)return;b.disabled=true;b.dataset.tip=t('recalBusy');b.setAttribute('aria-label',t('recalBusy'));
696
+ try{const r=await fetch('/api/recalibrate',{method:'POST',headers:{Authorization:'Bearer '+D.service.token}});
697
+ if(r.status!==202&&r.status!==409)throw new Error(r.status);
698
+ for(;;){await new Promise(z=>setTimeout(z,2000));const h=await (await fetch('/api/health')).json();if(!h.running){location.reload();return}}}
699
+ catch(e){b.disabled=false;b.dataset.tip=t('recalFail');b.setAttribute('aria-label',t('recalFail'));b.classList.add('bad')}}
700
+ document.addEventListener('click',e=>{if(e.target.closest&&e.target.closest('#recal'))recalibrate()});
701
+ // The sticky bar (profile buttons, live readout, status icons) and the main chart with its slider are built once
702
+ // per group/language and then only updated in place, so dragging never replaces the node under the pointer.
703
+ function buildBar(){const g=G();
704
+ $('#bar').innerHTML=`<div class="gearrow"><div class="seg" id="gears" role="group" aria-label="${t('gear')}">${[...PROF,'custom'].map(k=>`<button data-gear="${k}" aria-pressed="false" aria-label="${t(k)}${k===g.profile?' ★':''}">${ic(PICON[k])}<span class="gt">${t(k)}${k===g.profile?'&nbsp;★':''}</span></button>`).join('')}</div>
705
+ <span class="vot" id="vot"></span></div>
706
+ <div class="ansrow"><b class="tval" id="tval" aria-live="polite"></b><span id="mini"></span><span class="ans" id="ans"></span><button type="button" class="btn sm" id="cpOne">${ic('copy')}<span>${t('cpCopy')}</span></button><span id="flags"></span></div>`;
707
+ document.querySelectorAll('#gears button').forEach(b=>b.onclick=()=>setGear(b.dataset.gear));
708
+ $('#cpOne').onclick=async()=>{const b=$('#cpOne'),ok=await copyStr(snippet(G(),S.T));b.querySelector('span').textContent=ok?t('cpCopied'):t('cpFail');
709
+ clearTimeout(b.tm);b.tm=setTimeout(()=>{b.querySelector('span').textContent=t('cpCopy')},2200)}}
710
+ // one answer line: 'saves $44.9 + 14.7 min per day vs default 967k', each part coloured by its own sign
711
+ function answer(u,m,vs,pc,pt){const zu=Math.abs(u)<.05,zm=Math.abs(m)<.05;if(zu&&zm)return `<span>${t('noDiff')}</span> <span class="cap">${esc(vs)}</span>`;
712
+ const p=S.unit==='pct'&&pc!=null&&pt!=null;
713
+ const a=p?[zu?'':`<span class="${tone(u)}">${fpct(pc)} ${t('wCost')}</span>`,zm?'':`<span class="${tone(m)}">${fpct(pt)} ${t('wTime')}</span>`]
714
+ :[zu?'':`<span class="${tone(u)}">${fsv(u)}</span>`,zm?'':`<span class="${tone(m)}">${fmv(m)}</span>`];
715
+ const sec=p?[zu?'':fsn(u),zm?'':fmn(m)].filter(Boolean).join(' · '):[zu?'':fpn(pc)+' '+t('wCost'),zm?'':fpn(pt)+' '+t('wTime')].filter(Boolean).join(' · ');
716
+ return a.filter(Boolean).join(' · ')+` <small class="sc">${esc(sec)}</small> <span class="cap">${esc(vs)}</span>`}
717
+ // the setting for this one model at threshold T, in the harness's own config syntax
718
+ function snippet(g,T){return (g.settings||[])[g.grid.indexOf(T)]||''}
719
+ async function copyStr(txt){try{if(navigator.clipboard&&window.isSecureContext){await navigator.clipboard.writeText(txt);return true}}catch(e){}
720
+ try{const ta=document.createElement('textarea');ta.value=txt;ta.setAttribute('readonly','');ta.style.cssText='position:fixed;top:0;left:0;opacity:0';document.body.append(ta);ta.select();const ok=document.execCommand('copy');ta.remove();return ok}catch(e){return false}}
721
+ // "nice" round ticks covering [lo, hi]; ticksN keeps at least `min` of them
722
+ function ticksN(lo,hi,min){let n=min,o=nice(lo,hi,n);while(o.length<min&&n<12)o=nice(lo,hi,++n);return o}
723
+ // "nice" round ticks covering [lo, hi]
724
+ function nice(lo,hi,n=4){const st0=(hi-lo||1)/n,mag=10**Math.floor(Math.log10(st0)),f=st0/mag,st=(f<1.5?1:f<3?2:f<7?5:10)*mag,out=[];
725
+ for(let v=Math.ceil(lo/st)*st;v<=hi+st*1e-6;v+=st)out.push(Math.abs(v)<st*1e-6?0:+v.toPrecision(12));return out}
726
+ // axis ticks: ▼ below the default line saves, ▲ above adds
727
+ const fpctT=v=>v===0?'0':(v<0?'▼−':'▲+')+(+Math.abs(v).toFixed(1))+'%';
728
+ const fusdT=v=>v===0?'0':(v<0?'▼−':'▲+')+'$'+(Math.abs(v)>=100?Math.round(Math.abs(v)):+Math.abs(v).toFixed(1));
729
+ const fminT=v=>v===0?'0':(v<0?'▼−':'▲+')+(Math.abs(v)>=100?Math.round(Math.abs(v)):+Math.abs(v).toFixed(1))+'m';
730
+ // charts drawn at the box's own width keep their text at its real size on a phone
731
+ const boxW=(box,pad=36)=>{const w=box.clientWidth;return w>0?Math.max(300,Math.round(w-pad)):940};
732
+ function peaksOf(g){return D.sessions.filter(s=>s.model===g.model&&s.role===g.role&&(!s.harness||s.harness===g.harness)).map(s=>s.peak)}
733
+ // Main chart: x = auto-compact threshold over the grid. Top panel: $/day vs default; bottom panel: min/day vs
734
+ // default (0 = the default). Behind both: where this group's sessions peak. Hatched: recall below the floor.
735
+ // Vertical marks: default (dashed), current (dotted), profiles (thin, icon on top). The cursor follows S.T.
736
+ function buildMain(){const g=G(),box=$('#fMain'),xs=g.grid,n=xs.length,d=g.default,im=xs.map((_,i)=>impJS(pt(g,i),d,g));
737
+ const U=im.map(x=>x.usd.per_day),M=im.map(x=>x.minutes.per_day),PC=xs.map((_,i)=>ratio(g.combined_cost[i]-d.combined_cost,d.combined_cost)),PT=xs.map((_,i)=>ratio(g.time_s[i]-d.time_s,d.time_s));
738
+ const usePct=S.unit==='pct'&&PC.every(v=>v!=null)&&PT.every(v=>v!=null),u=usePct?PC.map(v=>v*100):U,m=usePct?PT.map(v=>v*100):M;
739
+ // rows from the top: threshold pill (cursor), profile icons, panel title, panel; then the time panel the same way
740
+ const W=boxW(box),L=W<600?50:62,R=W<600?10:18,top={y1:58,y0:198},bot={y1:240,y0:364},H=bot.y0+24,x0=L,x1=W-R;
741
+ const X=v=>x0+(v-xs[0])/((xs[n-1]-xs[0])||1)*(x1-x0);
742
+ const scale=(p,v)=>{let lo=Math.min(0,...v),hi=Math.max(0,...v);const pad=(hi-lo||1)*.14;lo-=pad;hi+=pad;return {lo,hi,Y:y=>p.y0-(y-lo)/(hi-lo)*(p.y0-p.y1)}};
743
+ const su=scale(top,u),sm=scale(bot,m);
744
+ const svg=el('svg',{viewBox:`0 0 ${W} ${H}`,role:'img','aria-label':t('mTitle')+': '+t('threshold')+' '+fk(xs[0])+'–'+fk(xs[n-1])});svg.classList.add('mainc');
745
+ const defs=el('defs');const pat=el('pattern',{id:'hatch',width:6,height:6,patternUnits:'userSpaceOnUse',patternTransform:'rotate(45)'});pat.append(el('line',{x1:0,y1:0,x2:0,y2:6,class:'hatch'}));defs.append(pat);svg.append(defs);
746
+ // where sessions peak (bins of two grid steps), faint, across both panels; counts in the tooltip and the key
747
+ const step=2*((xs[1]-xs[0])||25000),nb=Math.max(1,Math.ceil((xs[n-1]-xs[0])/step)),cnt=new Array(nb).fill(0);
748
+ peaksOf(g).forEach(p=>{cnt[Math.min(nb-1,Math.max(0,Math.floor((p-xs[0])/step)))]++});
749
+ const cm=Math.max(...cnt,1),bg=el('g',{class:'peaks'});
750
+ cnt.forEach((c,b)=>{if(!c)return;const a=X(xs[0]+b*step),z=X(Math.min(xs[0]+(b+1)*step,xs[n-1])),hh=(bot.y0-top.y1)*.92*c/cm;
751
+ bg.append(el('rect',{x:a+1,y:bot.y0-hh,width:Math.max(z-a-2,1),height:hh,rx:2}))});
752
+ svg.append(bg);
753
+ // recall below the floor: hatched, labelled at the top of the zone
754
+ const fl=g.recommendation.recall_floor,mid=i=>i<=0?x0:i>=n?x1:(X(xs[i-1])+X(xs[i]))/2;
755
+ for(let i=0;i<n;){if(!(g.recall[i]<fl)){i++;continue}let j=i;while(j<n&&g.recall[j]<fl)j++;const a=mid(i),z=mid(j);
756
+ svg.append(el('rect',{x:a,y:top.y1,width:z-a,height:bot.y0-top.y1,class:'unsafe'}));
757
+ if(z-a>70)svg.append(el('text',{x:z-6,y:top.y1+13,'text-anchor':'end',class:'dl uz'},t('unsafeL',fl)));i=j}
758
+ // panels: ticks (at least four), zero line (= default), title above the panel starting at the left edge
759
+ for(const [p,s,v,f,lab,icn] of [[top,su,u,usePct?fpctT:fusdT,usePct?'dPct':'dUsd','coin'],[bot,sm,m,usePct?fpctT:fminT,usePct?'dPctT':'dMin','clock']]){
760
+ for(const y of ticksN(s.lo,s.hi,3)){svg.append(el('line',{x1:x0,x2:x1,y1:s.Y(y),y2:s.Y(y),class:'grid'}));svg.append(el('text',{x:x0-7,y:s.Y(y)+3.5,'text-anchor':'end',class:y<0?'tk good':y>0?'tk warn':'tk'},f(y)))}
761
+ svg.append(el('line',{x1:x0,x2:x1,y1:s.Y(0),y2:s.Y(0),class:'zero'}));
762
+ svg.append(el('use',{href:'#i-'+icn,x:4,y:p.y1-17,width:13,height:13,class:'pico'}));svg.append(el('text',{x:21,y:p.y1-7,class:'dl ptl'},t(lab)));
763
+ svg.append(el('polyline',{points:xs.map((x,i)=>X(x)+','+s.Y(v[i])).join(' '),fill:'none',stroke:p===top?'var(--acc)':'var(--ink2)','stroke-width':p===top?2.2:1.8,'stroke-linejoin':'round','stroke-linecap':'round'}))}
764
+ for(const x of ticksN(xs[0],xs[n-1],4))if(x>=xs[0]&&x<=xs[n-1])svg.append(el('text',{x:X(x),y:bot.y0+16,'text-anchor':'middle'},fk(x)));
765
+ svg.append(el('line',{x1:x0,x2:x1,y1:bot.y0,y2:bot.y0,class:'ax'}));
766
+ // reference marks; profile icons pushed apart when they would touch
767
+ const vl=(v,cls)=>svg.append(el('line',{x1:X(v),x2:X(v),y1:top.y1,y2:bot.y0,class:cls}));
768
+ vl(d.threshold,'mdef');if(g.current)vl(g.current.threshold,'mcur');
769
+ const icons=PROF.map(k=>({k,x:X(g.profiles[k].threshold)})).sort((a,b)=>a.x-b.x);
770
+ icons.forEach((o,j)=>{if(j&&o.x-icons[j-1].x<15)o.x=icons[j-1].x+15});const over=Math.max(0,icons[icons.length-1].x-(x1-2));icons.forEach(o=>o.x-=over);
771
+ PROF.forEach(k=>vl(g.profiles[k].threshold,'mprof'));
772
+ icons.forEach(o=>svg.append(el('use',{href:'#i-'+PICON[o.k],x:o.x-6.5,y:top.y1-38,width:13,height:13,class:'pico pic'})));
773
+ // cursor (moved by moveCursor) and hover crosshair
774
+ const guide=el('line',{y1:top.y1,y2:bot.y0,stroke:'var(--ink3)','stroke-width':.8,'stroke-dasharray':'2 2',visibility:'hidden','pointer-events':'none'});
775
+ const cur=el('g',{class:'cursor','pointer-events':'none'});
776
+ cur.append(el('line',{y1:top.y1-40,y2:bot.y0,class:'cl'}),el('circle',{r:4.5}),el('circle',{r:4.5}),el('text',{class:'dl b'}),el('text',{class:'dl b'}),el('rect',{class:'ch',rx:4,height:17,y:2}),el('text',{class:'chl','text-anchor':'middle',y:14.5}));
777
+ const ov=el('rect',{x:x0-8,y:top.y1-40,width:x1-x0+16,height:bot.y0-top.y1+40,fill:'transparent',class:'hov drag'});
778
+ svg.append(guide,cur,ov);
779
+ const loc=e=>{const mm=svg.getScreenCTM();if(!mm)return -1;const q=new DOMPoint(e.clientX,e.clientY).matrixTransform(mm.inverse());if(q.x<x0-10||q.x>x1+10)return -1;
780
+ let b=0;xs.forEach((v,i)=>{if(Math.abs(X(v)-q.x)<Math.abs(X(xs[b])-q.x))b=i});return b};
781
+ const pk=i=>{const b=Math.min(nb-1,Math.max(0,Math.floor((xs[i]-xs[0])/step)));return t('peaksTip',fk(xs[0]+b*step),fk(Math.min(xs[0]+(b+1)*step,xs[n-1])),cnt[b])};
782
+ let drag=null;
783
+ ov.addEventListener('pointerdown',e=>{const i=loc(e);if(i<0)return;drag=e.pointerId;try{ov.setPointerCapture(e.pointerId)}catch(_){}if(xs[i]!==S.T)setT(xs[i])});
784
+ ov.addEventListener('pointermove',e=>{const i=loc(e);if(i<0){hideTip();guide.setAttribute('visibility','hidden');return}
785
+ if(drag!=null&&xs[i]!==S.T)setT(xs[i]);guide.setAttribute('x1',X(xs[i]));guide.setAttribute('x2',X(xs[i]));guide.setAttribute('visibility','visible');
786
+ showTip(tipHTML(g,i)+'<div class="cap">'+esc(pk(i))+'</div>',e.clientX,e.clientY)});
787
+ const end=e=>{if(drag!=null){try{ov.releasePointerCapture(drag)}catch(_){}}drag=null};
788
+ ov.addEventListener('pointerup',end);ov.addEventListener('pointercancel',end);
789
+ ov.addEventListener('pointerleave',()=>{if(drag==null){hideTip();guide.setAttribute('visibility','hidden')}});
790
+ S.mc={X,su,sm,u,m,U,M,PC,PT,usePct,top,bot,cur,x0,x1};
791
+ // slider directly under the plot: its thumb centre lines up with the chart's x (the thumb is inset 8px)
792
+ const pos=v=>Math.min(Math.max((v-xs[0])/((xs[n-1]-xs[0])||1),0),1),at=v=>`left:calc(8px + (100% - 16px) * ${pos(v).toFixed(4)})`;
793
+ const byT={};PROF.forEach(k=>{(byT[g.profiles[k].threshold]=byT[g.profiles[k].threshold]||[]).push(k)});
794
+ const marks=Object.entries(byT).map(([T,ks])=>`<button class="mk r1" data-mk="${T}" data-g="${ks[0]}" style="${at(+T)}" aria-label="${t('threshold')} ${fk(+T)}: ${ks.map(k=>t(k)).join(', ')}">${ks.map(k=>ic(PICON[k])).join('')}<span class="tx">${ks.map(k=>t(k)).join(' · ')}</span></button>`);
795
+ const refs=[[d.threshold,'rDefault']].concat(g.current?[[g.current.threshold,'rCurrent']]:[]);
796
+ refs.forEach(([T,k])=>marks.push(`<button class="mk r2" data-mk="${T}" data-ref="${k}" style="${at(T)}" aria-label="${t(k)} ${fk(T)}">${t(k)} ${fk(T)}</button>`));
797
+ // on-chart key: what the background, hatching and marks mean, and the sign convention
798
+ const key=[`<span class="ky"><i class="sw swp"></i>${esc(t('peaksK',Math.max(...cnt)))}</span>`,`<span class="ky"><i class="sw swh"></i>${esc(t('unsafeK',fl))}</span>`,
799
+ `<span class="ky"><i class="sw swd"></i>${esc(t('rDefault')+' '+fk(d.threshold))}</span>`,
800
+ g.current?`<span class="ky"><i class="sw swc"></i>${esc(t('rCurrent')+' '+fk(g.current.configured??g.current.threshold))}</span>`:`<span class="ky cap">${esc(t('noCurS'))}</span>`,
801
+ `<span class="ky"><b class="good">▼ −</b>${t('saves')} <b class="warn">▲ +</b>${t('adds')}</span>`];
802
+ box.innerHTML=`<h3 class="mh">${t('mTitle')}${ib(t('mHelp'))}<span class="est">${t('est')}</span></h3><div class="key">${key.join('')}</div>`;box.append(svg);
803
+ const tr=document.createElement('div');tr.className='track';tr.style.margin=`0 calc(${(R/W*100).toFixed(3)}% - 8px) 0 calc(${(L/W*100).toFixed(3)}% - 8px)`;
804
+ tr.innerHTML=`<input type="range" min="0" max="${n-1}" step="1" id="rng" aria-label="${t('threshold')}"><div id="marks">${marks.join('')}</div>`;box.append(tr);
805
+ document.querySelectorAll('#marks .mk').forEach(b=>b.onclick=()=>{if(b.dataset.g)setGear(b.dataset.g);else setT(g.grid[nearest(g,+b.dataset.mk)])});
806
+ $('#rng').addEventListener('input',e=>{S.gear='custom';S.T=g.grid[+e.target.value];update()});
807
+ requestAnimationFrame(spreadMarks)}
808
+ // value labels sit on the side of the dot away from the curve: below it where the curve rises to the right
809
+ function moveCursor(){const c=S.mc,g=G();if(!c)return;const i=g.grid.indexOf(S.T),n=g.grid.length,x=c.X(S.T),[ln,d1,d2,t1,t2,hd,hl]=c.cur.children;
810
+ ln.setAttribute('x1',x);ln.setAttribute('x2',x);const right=x<c.x1-130;
811
+ const L1=c.usePct?[fpct(c.PC[i]),fsn(c.U[i])+t('uDay')]:[fsv(c.U[i])+t('uDay'),fpn(c.PC[i])],L2=c.usePct?[fpct(c.PT[i]),fmn(c.M[i])+t('uDay')]:[fmv(c.M[i])+t('uDay'),fpn(c.PT[i])];
812
+ for(const [dot,lab,s,v,L,p] of [[d1,t1,c.su,c.u,L1,c.top],[d2,t2,c.sm,c.m,L2,c.bot]]){const y=s.Y(v[i]);dot.setAttribute('cx',x);dot.setAttribute('cy',y);
813
+ const j=Math.min(n-1,Math.max(0,i+(right?2:-2))),ny=s.Y(v[j]),below=right?ny<y:ny>y;
814
+ let ly=below?y+17:y-9;ly=Math.min(Math.max(ly,p.y1+11),p.y0-4);
815
+ lab.setAttribute('x',x+(right?9:-9));lab.setAttribute('y',ly);lab.setAttribute('text-anchor',right?'start':'end');lab.setAttribute('class','dl b '+tone(v[i]));lab.textContent=L[0];if(L[1])lab.append(el('tspan',{class:'sc2',dx:5},L[1]))}
816
+ hl.textContent=fk(S.T);hl.setAttribute('x',x);const w=8*fk(S.T).length+12;hd.setAttribute('width',w);hd.setAttribute('x',Math.min(Math.max(x-w/2,0),c.x1+16-w))}
817
+ // push mark labels down a line when they would overlap a neighbour in the same row
818
+ function spreadMarks(){const tb=document.querySelector('.track');if(!tb)return;const T=tb.getBoundingClientRect();
819
+ // a narrow track shows the profile marks as icons only (their names are on the profile switch)
820
+ const mk=document.getElementById('marks');if(mk)mk.classList.toggle('compact',T.width<520);
821
+ document.querySelectorAll('#marks .mk').forEach(m=>{m.classList.remove('er','el');const r=m.getBoundingClientRect();if(r.right>T.right+4)m.classList.add('er');else if(r.left<T.left-4)m.classList.add('el')});
822
+ for(const row of ['r1','r2']){const ms=[...document.querySelectorAll('#marks .mk.'+row)];ms.forEach(m=>m.classList.remove('l1','l2'));
823
+ ms.sort((a,b)=>a.getBoundingClientRect().left-b.getBoundingClientRect().left);const ends=[-1e9,-1e9,-1e9];
824
+ for(const m of ms){const r=m.getBoundingClientRect();let lv=ends.findIndex(e=>r.left>e+4);if(lv<0)lv=2;if(lv)m.classList.add('l'+lv);ends[lv]=r.right}}
825
+ const tr=document.querySelector('.track');if(tr){const extra=[...document.querySelectorAll('#marks .mk')].reduce((a,m)=>Math.max(a,m.classList.contains('l2')?28:m.classList.contains('l1')?14:0),0);tr.style.paddingBottom='';tr.style.paddingBottom=(parseFloat(getComputedStyle(tr).paddingBottom)+extra)+'px'}}
826
+ // charts follow their box width: rebuild them when it changes (a ResizeObserver also sees a pane that was hidden
827
+ // or narrow at load, which a window resize event does not), keeping the slider position
828
+ function refit(){clearTimeout(refit.tm);refit.tm=setTimeout(()=>{
829
+ const box=S.view==='group'?$('#fMain'):S.view==='noop'?$('#fNoop'):$('#fOv'),svg=box&&box.querySelector('svg.mainc,svg[viewBox]:not(.ic)'),w=box?boxW(box):0;
830
+ if(svg&&box.clientWidth>0&&Math.abs(+svg.getAttribute('viewBox').split(' ')[2]-w)>24){if(S.view==='group'){buildMain();update()}else if(S.view==='noop')keep(noopPanel);else keep(renderOverview)}
831
+ spreadMarks()},120)}
832
+ addEventListener('resize',refit);
833
+ if(window.ResizeObserver){const ro=new ResizeObserver(refit);['#fMain','#noop','#ovw'].forEach(q=>ro.observe($(q)))}
834
+ function controls(){const g=G(),i=g.grid.indexOf(S.T),r=g.recommendation,p=pt(g,i),d=g.default,c=cmp(p,d),rng=$('#rng');
835
+ if(+rng.value!==i)rng.value=i;rng.setAttribute('aria-valuetext',fk(S.T));$('#tval').textContent=fk(S.T);
836
+ document.querySelectorAll('#gears button').forEach(b=>b.setAttribute('aria-pressed',b.dataset.gear===S.gear));
837
+ document.querySelectorAll('#marks .mk').forEach(b=>b.classList.toggle('on',+b.dataset.mk===S.T));
838
+ $('#vot').textContent=t('votS',S.vot);$('#vot').title=t('votL',S.vot);
839
+ $('#flags').innerHTML=flags(g).map(([k,h,icn])=>ib(h,k==='note'?icn||'info':'warn',k==='note'?'':k)).join('');
840
+ const im=impJS(p,d),icur=g.current?impJS(p,g.current):null,def=fk(d.threshold);
841
+ const cur=(v,f)=>icur?' · '+t('rCurrent')+' '+f(v):'';
842
+ const fl=r.recall_floor,lo=Math.min(fl,p.recall,d.recall)-.02,gp=v=>((v-lo)/(1-lo)*100).toFixed(1)+'%';
843
+ const dcp=im.compactions.per_day-im.ref_compactions.per_day;
844
+ const pd=pctAt(g,S.T,d),pcu=g.current?pctAt(g,S.T,g.current):null;
845
+ $('#ans').innerHTML=answer(im.usd.per_day,im.minutes.per_day,t('vsDefL',def),pd.c,pd.t)+(icur?'<span class="ans2">'+answer(icur.usd.per_day,icur.minutes.per_day,t('vsCurL',fk(g.current.configured??g.current.threshold)),pcu.c,pcu.t)+'</span>':'<span class="ans2 cap">'+esc(t('noCur'))+'</span>');
846
+ $('#mini').innerHTML=miniBA(g,im);
847
+ const cb=$('#cpOne'),keepIt=action(g,S.T,S.vot)!=='aSet';if(keepIt)$('#ans').insertAdjacentHTML('beforeend','<span class="ans2 kw">'+esc(keepWhy(g,S.T,S.vot))+'</span>');cb.disabled=keepIt;cb.dataset.tip=keepIt?t('cpKeep'):t('cpOneTip',snippet(g,S.T));cb.setAttribute('aria-label',t('cpCopy')+': '+(keepIt?t('cpKeep'):snippet(g,S.T)));
848
+ $('#kpis').innerHTML=`
849
+ <div class="kpi"><div class="kh">${ic('refresh')}<span>${t('kComp')}</span></div><div class="v">${im.compactions.per_day.toFixed(1)}</div>
850
+ <div class="kr">${chip(arrow(dcp)+(dcp>=0?'+':MINUS)+Math.abs(dcp).toFixed(1),'')}<span class="cap">${esc(t('cCompSub',im.ref_compactions.per_day.toFixed(1),Math.round(im.compactions.per_month)))}</span></div></div>
851
+ <div class="kpi"><div class="kh">${ic('shield')}<span>${t('kRecall')}</span></div><div class="v ${p.recall>=fl?'':'bad'}">${p.recall.toFixed(3)}</div>
852
+ <div class="kr"><span class="gauge" role="img" aria-label="${esc(t('kRecall')+' '+p.recall.toFixed(3)+', '+t('cFloor',fl,d.recall.toFixed(3)))}"><i style="width:${gp(p.recall)}"></i><b style="left:${gp(fl)}"></b></span><span class="cap">${esc(t('cFloor',fl,d.recall.toFixed(3)))}</span></div></div>`;
853
+ $('#notes').innerHTML=notes(g).map(n=>'<li>'+n+'</li>').join('')}
854
+ // status icons in the control bar. A warning triangle only for the selected profile's guardrail flags (red when
855
+ // broken, amber for a guardrail warning); data-confidence notes and guardrail moves are info icons.
856
+ function flags(g){const out=[],tm=g.time_model||{},P=g.profiles[S.gear];
857
+ if(P)for(const f of P.flags)out.push([flagKind(f)||'note',flagText(f,P),'shield']);
858
+ if(S.T===g.grid[0])out.push(['note',t('nEdge'),'sliders']);
859
+ if((tm.turn_source||'prior')!=='own'||(tm.compact_source||'prior')!=='own')out.push(['note',t('lowTime',t('src_'+(tm.turn_source||'prior')),t('src_'+(tm.compact_source||'prior'))),'clock']);
860
+ if(g.n_sessions<5)out.push(['note',t('lowThin',g.n_sessions),'db']);
861
+ if(g.days<3)out.push(['note',t('lowDays',fdays(g.days)),'cal']);
862
+ if(g.penalty_params.source==='prior')out.push(['note',t('lowPen',g.penalty_params.n_observed),'refresh']);
863
+ return out}
864
+ function notes(g){const n=[],pp=g.penalty_params,d=g.default,cur=g.current;
865
+ n.push(esc(t('caveat')));
866
+ if(pp.source!=='prior')n.push(t('nObs',pp.n_observed));
867
+ n.push(esc(t('nPrice',g.price_key,g.price_source)));
868
+ if(g.cache_ttl)n.push(esc(t('nTtl',g.cache_ttl>=3600?(g.cache_ttl/3600)+' h':Math.round(g.cache_ttl/60)+' min',g.cache_ttl_source)));
869
+ n.push(t('nAssume',fk(g.base_tokens),fk(g.summary_tokens),fk(g.max_window)));
870
+ n.push(esc(S.lang==='zh'?I.cmpNote[1](d.note_zh||d.note,cur?cur.source:(g.current_note||'')):I.cmpNote[0](d.note,cur?cur.source:(g.current_note||''))));return n}
871
+ // ---------- per-day impact: every profile vs default and vs current ----------
872
+ function impactPanel(){const g=G(),box=$('#fImpact');
873
+ if(g.no_action_needed){box.innerHTML='<div class="card mi good">'+ic('check')+'<span>'+esc(t('noAction'))+'</span></div>';return}
874
+ const hasAct=g.active_days!=null,difAct=hasAct&&Math.abs(g.active_days-Math.max(g.days,1))>=.05;if(S.basis==='per_active_day'&&!difAct)S.basis='per_day';const B=S.basis;
875
+ const refs=[['vs_default','cVsDef',fk(g.default.threshold),'rDefault']].concat(g.current?[['vs_current','cVsCur',fk(g.current.configured??g.current.threshold),'rCurrent']]:[]);
876
+ const bases=[['per_day','bDay'],['per_active_day','bActive'],['per_month','bMonth']].filter(([k])=>k!=='per_active_day'||difAct);
877
+ const emax=g.effective_max||g.grid[g.grid.length-1],unit=' / '+t('uB_'+B);
878
+ const cf=x=>B==='per_month'?String(Math.round(x)):x.toFixed(1);
879
+ const cards=PROF.map(k=>{const P=g.profiles[k],act=action(g,P.threshold,P.value_of_time),frac=Math.min(P.threshold/emax,1);
880
+ const rows=refs.map(([r,lab,thr,rk])=>{const im=impOf(g,k,r);if(!im)return '';const pr=pctAt(g,P.threshold,r==='vs_default'?g.default:g.current);const u=im.usd[B],m=im.minutes[B],w=im.wait_minutes[B],tg=-im.turn_gain_minutes[B],cc=im.compactions[B],rc=im.ref_compactions[B];
881
+ return `<div class="irow" data-ref="${r}"><span class="cap">${esc(t(lab,thr))}</span><div class="chips">`+
882
+ chip(dual(pr.c,fsv(u),fsn(u)),tone(u),'coin',t('iMoney')+' '+fsv(u)+unit+(pr.c!=null?' · '+fpn(pr.c)+' '+t('pcCost'):'')+' ('+(u<0?t('saves'):t('adds'))+', '+t('est')+')',` data-m="usd-${r}"`)+
883
+ chip(dual(pr.t,fmv(m,B),fmn(m,B)),tone(m),'clock',t('iTime')+' '+fmv(m,B)+unit+(pr.t!=null?' · '+fpn(pr.t)+' '+t('pcTime'):'')+' · '+t('iSplitTip',fmv(w,B),fmv(tg,B)),` data-m="min-${r}"`)+
884
+ chip(cf(cc)+' '+t('cmpS'),'','refresh',t('iComp')+' '+cf(cc)+unit+' · '+t(rk)+' '+cf(rc))+
885
+ `</div><span class="cap">${esc(t('cSplit',fmv(w,B),fmv(tg,B)))}</span></div>`}).join('');
886
+ return `<article class="pc ${k===S.gear?'sel':''}" data-pc="${k}"><header>${ic(PICON[k],t(k))}<span class="pn">${t(k)}${k===g.profile?'&nbsp;★':''}</span>${flagIcons(P)}<span class="act ${act==='aSet'?'set':''}">${t(act)}</span></header>
887
+ <div class="tb"><span class="cap">${t('threshold')}</span><span class="pt" title="${esc(t('iFrac',Math.round(frac*100),fk(emax)))}">${fk(P.threshold)}</span></div>
888
+ ${(act==='aKeep'||act==='aCur')?`<div class="kw">${esc(keepWhy(g,P.threshold,P.value_of_time))}</div>`:''}${rows}</article>`}).join('');
889
+ const cap=hasAct?t('iCap',fdays(Math.max(g.days,1)),fdays(g.active_days)):t('iCapNo',fdays(Math.max(g.days,1)));
890
+ box.innerHTML=`<div class="ihead"><div class="seg sm" data-k="basis" role="group" aria-label="${t('bLabel')}">${bases.map(([k,l])=>`<button data-basis="${k}" aria-pressed="${B===k}">${t(l)}</button>`).join('')}</div><span class="cap">${esc(cap)}</span>${hasAct?'':ib(t('iNoActive'),'info')}<span class="est">${t('est')}</span></div>
891
+ <div class="pcs">${cards}</div>`;
892
+ box.querySelectorAll('[data-basis]').forEach(b=>b.onclick=()=>{S.basis=b.dataset.basis;keep(impactPanel)})}
893
+ // ---------- chart tooltips ----------
894
+ function tipRow(k,v){return `<div class="r"><span>${k}</span><span>${v}</span></div>`}
895
+ function tipHTML(g,i){const p=pt(g,i),d=g.default,c=cmp(p,d),im=impJS(p,d);return `<b>${fk(p.threshold)}</b>`+tipRow(t('tWin'),fd(p.combined_cost))+
896
+ tipRow(t('tDUsd'),S.unit==='pct'?fpct(ratio(c.dc,d.combined_cost))+' · '+fsn(im.usd.per_day)+t('uDay'):fsv(im.usd.per_day)+t('uDay')+' · '+fpn(ratio(c.dc,d.combined_cost)))+
897
+ tipRow(t('tDMin'),S.unit==='pct'?fpct(ratio(c.dt,d.time_s))+' · '+fmn(im.minutes.per_day)+t('uDay'):fmv(im.minutes.per_day)+t('uDay')+' · '+fpn(ratio(c.dt,d.time_s)))+tipRow(t('tComp'),c.cpd.toFixed(1))+tipRow(t('kRecall'),p.recall.toFixed(3))}
898
+ function showTip(html,x,y,below){const tp_=$('#tip');tp_.innerHTML=html;tp_.hidden=false;const w=tp_.offsetWidth,h=tp_.offsetHeight;
899
+ tp_.style.left=Math.max(8,Math.min(x+(below?0:14),innerWidth-w-8))+'px';
900
+ tp_.style.top=(below?(y+h>innerHeight-8?Math.max(8,y-h-34):y):Math.max(8,(y-h-12<8?y+16:y-h-12)))+'px'}
901
+ function hideTip(){$('#tip').hidden=true}
902
+ // idxAt(svgX, svgY) -> grid index or -1. Hover shows the tooltip; click/tap selects that threshold.
903
+ function hover(f,idxAt){const g=G(),r=el('rect',{x:f.x0,y:f.y1,width:f.x1-f.x0,height:f.y0-f.y1,fill:'transparent',class:'hov'});
904
+ const guide=el('line',{y1:f.y1,y2:f.y0,stroke:'var(--ink3)','stroke-width':.8,'stroke-dasharray':'2 2',visibility:'hidden','pointer-events':'none'});
905
+ f.svg.append(guide,r);const loc=e=>{const m=f.svg.getScreenCTM();if(!m)return -1;const q=new DOMPoint(e.clientX,e.clientY).matrixTransform(m.inverse());return idxAt(q.x,q.y)};
906
+ const move=e=>{const i=loc(e);if(i<0){hideTip();return}showTip(tipHTML(g,i),e.clientX,e.clientY);const gx=f.gx?f.gx(i):null;if(gx!=null){guide.setAttribute('x1',gx);guide.setAttribute('x2',gx);guide.setAttribute('visibility','visible')}};
907
+ r.addEventListener('pointermove',move);r.addEventListener('pointerdown',move);
908
+ r.addEventListener('pointerleave',()=>{hideTip();guide.setAttribute('visibility','hidden')});
909
+ r.addEventListener('click',e=>{const i=loc(e);if(i>=0)setT(g.grid[i])})}
910
+ function byX(f,X,xs){f.gx=i=>X(xs[i]);return x=>{if(x<f.x0-4||x>f.x1+4)return -1;let b=0;xs.forEach((v,i)=>{if(Math.abs(X(v)-x)<Math.abs(X(xs[b])-x))b=i});return b}}
911
+ function comparison(){const g=G(),d=g.default,box=$('#fCmp'),cur=g.current;
912
+ const rows=[[t('rDefault'),d,'',null]];
913
+ if(cur)rows.push([t('rCurrent'),cur,'',null]);
914
+ for(const k of PROF){const P=g.profiles[k];rows.push([ic(PICON[k])+' '+t(k)+(k===g.profile?'&nbsp;★':''),pt(g,g.grid.indexOf(P.threshold)),action(g,P.threshold,P.value_of_time),P])}
915
+ if(S.gear==='custom')rows.push([ic('sliders')+' '+t('rSel'),pt(g,g.grid.indexOf(S.T)),action(g,S.T,S.vot),null]);
916
+ const cols=['cTier','cWin','cAct','cDc','cDt','cWait','cComp','cRec'].concat(cur?['cCur']:[]).concat(['cFlags']);
917
+ box.innerHTML='<table><tr>'+cols.map(k=>'<th>'+t(k)+'</th>').join('')+'</tr>'+rows.map(([name,p,act,P],ri)=>{const isDef=ri===0,c=isDef?null:cmp(p,d);const no=act==='aNo';
918
+ const sel=!isDef&&(P?S.gear===P.profile:S.gear==='custom'&&p.threshold===S.T);
919
+ const vc=cur&&c&&p!==cur?cmp(p,cur):null;
920
+ return `<tr class="${sel?'sel':''}"><td>${name}</td><td>${no?'–':fk(p.threshold??p.configured)}</td><td>${act?`<span class="act ${act==='aSet'?'set':''}">${t(act)}</span>`:'–'}</td>`+
921
+ (c?`<td class="${tone(c.dc)}">${arrow(c.dc)}${fds(c.dc)} (${pc(c.dcp)})</td><td class="${tone(c.dt)}">${arrow(c.dt)}${fh(c.dt)} (${fm(c.dtd)})</td><td>${arrow(c.addd)}${fm(c.addd)}</td><td>${c.cpd.toFixed(1)}</td><td>${p.recall.toFixed(3)}</td>`
922
+ :`<td>${fd(p.combined_cost)}</td><td>${fha(p.time_s)}</td><td>–</td><td>${(p.compactions/Math.max(g.days,1)).toFixed(1)}</td><td>${p.recall.toFixed(3)}</td>`)+
923
+ (cur?`<td>${vc?arrow(vc.dcp)+pc(vc.dcp)+' · '+arrow(vc.dt)+fh(vc.dt):'–'}</td>`:'')+`<td>${P&&!no?flagIcons(P):''}</td></tr>`}).join('')+'</table>'}
924
+ function pareto(){const g=G(),box=$('#fPareto'),sc=SC(g);figHead(box,t('pTitle'),t('pSub'));
925
+ const f=frame(460,300,{l:50,r:14,t:12,b:30}),xs=sc,ys=g.recall,dx=SCp(g,g.default);f.svg.setAttribute('aria-label',t('pTitle'));
926
+ let x0=Math.min(...xs,dx),x1=Math.max(...xs,dx),y0=Math.min(...ys,g.default.recall),y1=Math.max(...ys,g.default.recall);
927
+ const px=(x1-x0||1)*.08,py=(y1-y0||.01)*.14;x0-=px;x1+=px;y0-=py;y1+=py;
928
+ const X=v=>f.x0+(v-x0)/(x1-x0)*(f.x1-f.x0),Y=v=>f.y0-(v-y0)/(y1-y0)*(f.y0-f.y1);
929
+ axes(f,X,Y,ticks(x0,x1,4),ticks(y0,y1,4),fd,v=>v.toFixed(3));
930
+ const fr=paretoIdx(xs,ys).sort((a,b)=>xs[a]-xs[b]),fl=g.recommendation.recall_floor,L=[];
931
+ if(fl>=y0&&fl<=y1){f.svg.append(el('line',{x1:f.x0,x2:f.x1,y1:Y(fl),y2:Y(fl),stroke:'var(--amber)','stroke-dasharray':'3 4','stroke-width':.9}));
932
+ f.svg.append(el('text',{x:f.x0+4,y:Y(fl)-4,class:'dl',style:'fill:var(--amber)'},t('pFloor')+' '+fl))}
933
+ g.grid.forEach((_,i)=>{if(!fr.includes(i))f.svg.append(el('circle',{cx:X(xs[i]),cy:Y(ys[i]),r:2.4,fill:'var(--line2)'}))});
934
+ f.svg.append(el('polyline',{points:fr.map(i=>X(xs[i])+','+Y(ys[i])).join(' '),fill:'none',stroke:'var(--ink3)','stroke-width':1.1}));
935
+ fr.forEach(i=>f.svg.append(el('circle',{cx:X(xs[i]),cy:Y(ys[i]),r:2.8,fill:'var(--ink3)'})));
936
+ const hy=deepOf(g);if(hy)hy.points.forEach(p=>{const i=g.grid.indexOf(p.threshold);if(i<0)return;f.svg.append(el('rect',{x:X(xs[i])-3.5,y:Y(p.measured_recall)-3.5,width:7,height:7,fill:'none',stroke:'var(--ink)','stroke-width':1.2}));f.svg.append(el('line',{x1:X(xs[i]),x2:X(xs[i]),y1:Y(ys[i]),y2:Y(p.measured_recall),stroke:'var(--ink)','stroke-dasharray':'2 2','stroke-width':.8}))});
937
+ PROF.forEach(k=>{const i=g.grid.indexOf(g.profiles[k].threshold);if(i>=0&&k!==S.gear){f.svg.append(el('circle',{cx:X(xs[i]),cy:Y(ys[i]),r:6,fill:'none',stroke:'var(--ink2)','stroke-width':1}));L.push({x:X(xs[i])+9,y:Y(ys[i])+13,text:t(k)+' '+fk(g.profiles[k].threshold),color:'var(--ink2)',anchor:'start'})}});
938
+ f.svg.append(el('rect',{x:X(dx)-3.5,y:Y(g.default.recall)-3.5,width:7,height:7,fill:'var(--ink2)'}));
939
+ L.push({x:X(dx)-8,y:Y(g.default.recall)+15,text:t('rDefault')+' '+fk(g.default.threshold),color:'var(--ink2)',anchor:'end'});
940
+ const si=g.grid.indexOf(S.T);f.svg.append(el('circle',{cx:X(xs[si]),cy:Y(ys[si]),r:9,fill:'var(--acc-soft)',stroke:'var(--acc)','stroke-width':1.2}));f.svg.append(el('circle',{cx:X(xs[si]),cy:Y(ys[si]),r:4,fill:'var(--acc)'}));
941
+ L.push({x:X(xs[si])+12,y:Y(ys[si])-8,text:fk(S.T),color:'var(--acc)',anchor:'start',bold:1});
942
+ for(const l of L){if(l.anchor==='start'&&l.x>f.x1-50){l.anchor='end';l.x-=24}if(l.anchor==='end'&&l.x<f.x0+50){l.anchor='start';l.x+=16}}
943
+ dlabels(f,L,11);
944
+ f.svg.append(el('text',{x:f.x1,y:f.y1+2,'text-anchor':'end'},t('lScore')+' @ '+t('vot',S.vot)));
945
+ hover(f,(x,y)=>{let b=-1,bd=24*24;xs.forEach((v,i)=>{const d=(X(v)-x)**2+(Y(ys[i])-y)**2;if(d<bd){bd=d;b=i}});return b});
946
+ box.append(f.svg)}
947
+ function deepOf(g){return D.deep&&D.deep.groups.find(x=>x.model===g.model&&x.role===g.role&&(!x.harness||x.harness===g.harness))}
948
+ function deepPanel(){const g=G(),b=$('#fDeep'),hy=deepOf(g);
949
+ if(!D.deep){b.innerHTML='<div class="mi">'+ic('layers')+'<span>'+esc(t('dLiteShort'))+'</span>'+ib(t('dLite'))+'</div>';return}
950
+ if(!hy){b.innerHTML='<p class="cap" style="margin:0">'+t('dNone')+'</p>';return}
951
+ b.innerHTML='<p class="cap" style="margin:0 0 8px">'+esc(t('dHead',D.deep.model,D.deep.judge_model,D.deep.repeats,fd(D.deep.spent_usd),fd(D.deep.budget_usd)))+(D.deep.stopped?' '+esc(D.deep.stopped):'')+'</p><table><tr><th>'+t('threshold')+'</th><th>'+t('dAssumed')+'</th><th>'+t('dMeasured')+'</th><th>'+t('dSamples')+'</th><th></th></tr>'+hy.points.map(p=>`<tr><td>${fk(p.threshold)}</td><td>${p.assumed_recall==null?'–':p.assumed_recall.toFixed(3)}</td><td>${p.measured_recall.toFixed(3)}</td><td>${p.samples}</td><td>${p.assumed_recall!=null&&Math.abs(p.measured_recall-p.assumed_recall)>.1?ib(t('dDis'),'warn','low'):''}</td></tr>`).join('')+'</table>'+Object.entries(hy.adjusted||{}).map(([k,v])=>'<p class="mi warn">'+ic('warn')+' '+t('dLowered',t(k),fk(v))+'</p>').join('')}
952
+ function costs(){const g=G(),box=$('#fCost'),sc=SC(g);figHead(box,t('coTitle'),t('coSub'));
953
+ const f=frame(460,300,{l:50,r:14,t:12,b:30}),xs=g.grid,hi=Math.max(...sc,SCp(g,g.default))*1.08;f.svg.setAttribute('aria-label',t('coTitle'));
954
+ const X=v=>f.x0+(v-xs[0])/((xs[xs.length-1]-xs[0])||1)*(f.x1-f.x0),Y=v=>f.y0-v/hi*(f.y0-f.y1);
955
+ const P=g.profiles[S.gear];if(P){const r=P.recommendation;f.svg.append(el('rect',{x:X(r.range[0]),y:f.y1,width:Math.max(X(r.range[1])-X(r.range[0]),3),height:f.y0-f.y1,fill:'var(--acc-soft)'}))}
956
+ const st=Math.ceil(xs.length/6);axes(f,X,Y,xs.filter((_,i)=>i%st===0),ticks(0,hi,4),fk,fd);
957
+ const dv=SCp(g,g.default);f.svg.append(el('line',{x1:f.x0,x2:f.x1,y1:Y(dv),y2:Y(dv),stroke:'var(--ink3)','stroke-dasharray':'2 3','stroke-width':.9}));
958
+ line(f,X,Y,xs,g.cost,'var(--ink3)',1.1);line(f,X,Y,xs,g.penalty,'var(--amber)',1.1,'3 3');line(f,X,Y,xs,sc,'var(--acc)',2);
959
+ const si=xs.indexOf(S.T);f.svg.append(el('line',{x1:X(S.T),x2:X(S.T),y1:f.y1,y2:f.y0,stroke:'var(--acc)','stroke-width':1,opacity:.6}));f.svg.append(el('circle',{cx:X(S.T),cy:Y(sc[si]),r:4,fill:'var(--acc)'}));
960
+ const e=xs.length-1,xe=f.x1-2;
961
+ dlabels(f,[{x:xe,y:Y(sc[e])-6,text:t('lScore'),color:'var(--acc)',bold:1},{x:xe,y:Y(g.cost[e])-6,text:t('lCost'),color:'var(--ink2)'},{x:xe,y:Y(g.penalty[e])-6,text:t('lPen'),color:'var(--amber)'},{x:f.x0+4,y:Y(dv)-5,text:t('lDefault')+' '+fk(g.default.threshold),color:'var(--ink2)',anchor:'start'}]);
962
+ hover(f,byX(f,X,xs));
963
+ box.append(f.svg)}
964
+ function timeChart(){const g=G(),d=g.default,box=$('#fTime'),tm=g.time_model,xs=g.grid;
965
+ const saved=xs.map((_,i)=>d.time_turns_s-g.time_turns_s[i]),added=xs.map((_,i)=>(g.time_compact_s[i]+g.time_redisc_s[i])-(d.time_compact_s+d.time_redisc_s)),net=xs.map((_,i)=>g.time_s[i]-d.time_s);
966
+ const L=S.lang==='zh'?1:0,conf=I.tConf[L](I['conf_'+tm.turn_confidence][L],tm.n_turn_samples,I['conf_'+tm.compact_confidence][L],tm.n_compact_samples,I['src_'+(tm.turn_source||'prior')][L],I['src_'+(tm.compact_source||'prior')][L]);
967
+ const own=tm.turn_source==='own'&&tm.compact_source==='own';
968
+ figHead(box,t('tTitle'),t('tSub'),ib(conf,own?'clock':'warn',own?'':'low'));
969
+ const f=frame(940,260,{l:54,r:14,t:12,b:30}),all=[...saved,...added,...net,0],lo=Math.min(...all),hi=Math.max(...all),pad=(hi-lo||1)*.1;f.svg.setAttribute('aria-label',t('tTitle'));
970
+ const X=v=>f.x0+(v-xs[0])/((xs[xs.length-1]-xs[0])||1)*(f.x1-f.x0),Y=v=>f.y0-(v-(lo-pad))/((hi+pad)-(lo-pad))*(f.y0-f.y1);
971
+ const st=Math.ceil(xs.length/10);axes(f,X,Y,xs.filter((_,i)=>i%st===0),ticks(lo-pad,hi+pad,4),fk,v=>Math.abs(v)<30?'0':arrow(v)+fh(v));
972
+ f.svg.append(el('line',{x1:f.x0,x2:f.x1,y1:Y(0),y2:Y(0),stroke:'var(--ink3)','stroke-width':.8}));
973
+ line(f,X,Y,xs,saved,'var(--good)',1.1);line(f,X,Y,xs,added,'var(--amber)',1.1);line(f,X,Y,xs,net,'var(--acc)',2);
974
+ f.svg.append(el('line',{x1:X(S.T),x2:X(S.T),y1:f.y1,y2:f.y0,stroke:'var(--acc)','stroke-dasharray':'3 3',opacity:.7}));
975
+ const Ls=[[saved,'tSaved','var(--good)'],[added,'tAdded','var(--amber)'],[net,'tNet','var(--acc)']].map(([v,k,c])=>{const i=v.reduce((b,x,j)=>Math.abs(x)>Math.abs(v[b])?j:b,0);return {x:Math.min(X(xs[i])+6,f.x1-130),y:Y(v[i])+(v[i]>=0?-6:14),text:t(k),color:c,anchor:'start',bold:k==='tNet'}});
976
+ dlabels(f,Ls);
977
+ hover(f,byX(f,X,xs));
978
+ box.append(f.svg)}
979
+ function hist(){const g=G(),box=$('#fHist'),h=g.hist;figHead(box,t('hTitle'),t('hSub'));
980
+ const f=frame(460,300,{l:42,r:14,t:12,b:30}),n=h.turns.length,mx=Math.max(...h.turns,...h.share)*1.15||1,bw=(f.x1-f.x0)/n;f.svg.setAttribute('aria-label',t('hTitle'));
981
+ const Y=v=>f.y0-v/mx*(f.y0-f.y1),X=v=>f.x0+v/(n*h.bin)*(f.x1-f.x0);
982
+ axes(f,X,Y,Array.from({length:Math.min(n,8)+1},(_,i)=>Math.round(i*n/Math.min(n,8))*h.bin),ticks(0,mx,4),fk,v=>Math.round(v*100)+'%');
983
+ h.turns.forEach((v,i)=>f.svg.append(el('rect',{x:f.x0+i*bw+1,y:Y(v),width:Math.max(bw-2,1),height:f.y0-Y(v),fill:'var(--line2)',rx:2})));
984
+ f.svg.append(el('polyline',{points:h.share.map((v,i)=>(f.x0+(i+.5)*bw)+','+Y(v)).join(' '),fill:'none',stroke:'var(--acc)','stroke-width':1.8,'stroke-linejoin':'round'}));
985
+ f.svg.append(el('line',{x1:X(S.T),x2:X(S.T),y1:f.y1,y2:f.y0,stroke:'var(--ink)','stroke-width':1,'stroke-dasharray':'3 3'}));
986
+ const over=h.share.reduce((a,v,i)=>a+((i+1)*h.bin>S.T?v:0),0);
987
+ const ti=h.turns.reduce((b,x,j)=>x>h.turns[b]?j:b,0),ri=h.share.reduce((b,x,j)=>x>h.share[b]?j:b,0);
988
+ dlabels(f,[{x:Math.min(X(S.T)+6,f.x1-110),y:f.y1+10,text:t('hAbove',Math.round(over*100),fk(S.T)),color:'var(--ink)',anchor:'start'},
989
+ {x:Math.min(f.x0+(ri+.5)*bw+6,f.x1-80),y:Y(h.share[ri])-6,text:t('hRead'),color:'var(--acc)',anchor:'start',bold:1},
990
+ {x:Math.min(f.x0+(ti+.5)*bw+6,f.x1-80),y:Y(h.turns[ti])-6,text:t('hTurns'),color:'var(--ink2)',anchor:'start'}]);
991
+ box.append(f.svg)}
992
+ // replay at full resolution (growth has one entry per turn), then thin the line to the length of the actual curve
993
+ function simulate(sess,g,T){const full=[];let c=g.base_tokens,k=0;const pp=g.penalty_params;
994
+ const man=sess.manual||{};sess.growth.forEach((x,i)=>{c+=x;if(c>T||(man[i+1]!==undefined&&c>=0.7*man[i+1])){k++;const d=Math.max(c-g.base_tokens-g.summary_tokens,0);c=g.base_tokens+g.summary_tokens+Math.floor(pp.rho*d+pp.fixed_tokens)}full.push(c)});
995
+ const n=sess.curve.length,st=full.length/n;return {out:full.length<=n?full:Array.from({length:n},(_,i)=>full[Math.floor(i*st)]),k}}
996
+ function sessList(){const g=G();return D.sessions.filter(s=>s.model===g.model&&s.role===g.role&&(!s.harness||s.harness===g.harness)).sort((a,b)=>b.peak-a.peak).slice(0,30)}
997
+ function sessPick(){const box=$('#fSess'),ss=sessList();
998
+ const cur=S.sid&&ss.find(s=>s.id===S.sid)?S.sid:(ss[0]||{}).id;S.sid=cur;
999
+ box.innerHTML=`<h3>${t('sTitle')}<span id="sInfo"></span></h3><select id="sp" aria-label="${t('colSession')}">${ss.map(s=>`<option value="${esc(s.id)}"${s.id===cur?' selected':''}>${esc(s.id.slice(0,24))} · ${fk(s.peak)} · ${s.turns}</option>`).join('')}</select><div id="sChart"></div>`;
1000
+ $('#sp').onchange=e=>{S.sid=e.target.value;sessChart()};sessChart()}
1001
+ function sessChart(){const g=G(),box=$('#sChart'),s=sessList().find(x=>x.id===S.sid);$('#sInfo').innerHTML=ib(t('sSub',fk(S.T)));box.innerHTML='';if(!s)return;
1002
+ const sim=simulate(s,g,S.T),n=s.curve.length;
1003
+ const f=frame(460,260,{l:42,r:14,t:14,b:26}),hi=Math.max(...s.curve,...sim.out,S.T)*1.1;f.svg.setAttribute('aria-label',t('sTitle'));
1004
+ const X=i=>f.x0+i/((n-1)||1)*(f.x1-f.x0),Y=v=>f.y0-v/hi*(f.y0-f.y1);
1005
+ axes(f,X,Y,[0,Math.round((n-1)/2),n-1],ticks(0,hi,4),i=>Math.round(i/(n-1||1)*100)+'%',fk);
1006
+ f.svg.append(el('line',{x1:f.x0,x2:f.x1,y1:Y(S.T),y2:Y(S.T),stroke:'var(--ink3)','stroke-dasharray':'3 3','stroke-width':.9}));
1007
+ f.svg.append(el('polyline',{points:s.curve.map((v,i)=>X(i)+','+Y(v)).join(' '),fill:'none',stroke:'var(--line2)','stroke-width':1.6,'stroke-linejoin':'round'}));
1008
+ f.svg.append(el('polyline',{points:sim.out.map((v,i)=>X(i)+','+Y(v)).join(' '),fill:'none',stroke:'var(--acc)','stroke-width':1.6,'stroke-linejoin':'round'}));
1009
+ dlabels(f,[{x:f.x0+4,y:Y(S.T)-5,text:fk(S.T),color:'var(--ink2)',anchor:'start'},
1010
+ {x:f.x1-2,y:Y(s.curve[n-1])-6,text:t('sAct',s.compactions),color:'var(--ink2)'},{x:f.x1-2,y:Y(sim.out[sim.out.length-1])-6,text:t('sRep',sim.k),color:'var(--acc)',bold:1}]);
1011
+ box.append(f.svg)}
1012
+ function copyPanel(){const b=$('#fCopy'),R=D.recommendations||[];
1013
+ const hs=[...new Set(R.map(r=>r.harness))];if(!hs.length){b.innerHTML='<p class="cap">–</p>';return}
1014
+ S.cp=S.cp||{harness:G().harness,scope:'global',profile:G().profile||'balanced',format:null};if(!hs.includes(S.cp.harness))S.cp.harness=hs[0];
1015
+ const fmts=[...new Set(R.filter(r=>r.harness===S.cp.harness&&r.scope===S.cp.scope).map(r=>r.format))];if(!fmts.includes(S.cp.format))S.cp.format=fmts[0];
1016
+ const seg=(key,vals,lab)=>`<div class="seg sm" data-k="${key}" role="group" aria-label="${t(lab)}">${vals.map(v=>`<button data-v="${v}" aria-pressed="${S.cp[key]===v}">${PICON[v]?ic(PICON[v]):''}${I[v]?t(v):v}</button>`).join('')}</div>`;
1017
+ const rows=R.filter(r=>r.harness===S.cp.harness&&r.scope===S.cp.scope&&r.profile===S.cp.profile&&r.format===S.cp.format);
1018
+ const snips=rows.filter(r=>!r.omitted),om=rows.filter(r=>r.omitted);
1019
+ const txt=snips.map(r=>r.text).join('\n');
1020
+ b.innerHTML='<div class="copyrow">'+seg('harness',hs,'cpHarness')+seg('scope',['global','project','agent'],'cpScope')+seg('profile',PROF,'cpTier')+seg('format',fmts,'cpFormat')+'</div>'+
1021
+ (snips.length?'<div class="copyrow" style="margin-top:12px"><button class="btn" id="cpBtn">'+t('cpCopy')+'</button><span class="cap" id="cpMsg" role="status" aria-live="polite"></span></div><pre class="snip" id="cpPre"></pre>':'')+
1022
+ (om.length?'<ul class="n cap" style="margin-top:12px">'+om.map(o=>'<li>'+(snips.length?'':t('cpNone')+' ')+esc(o.omitted)+'</li>').join('')+'</ul>':'');
1023
+ if(snips.length){$('#cpPre').textContent=txt;$('#cpBtn').onclick=()=>copyText(txt)}
1024
+ b.querySelectorAll('.seg[data-k]').forEach(sg=>sg.querySelectorAll('button').forEach(bt=>bt.onclick=()=>{S.cp[sg.dataset.k]=bt.dataset.v;if(sg.dataset.k!=='format')S.cp.format=null;keep(copyPanel)}))}
1025
+ // navigator.clipboard needs a secure context (not file://); fall back to execCommand, then to selecting the text
1026
+ async function copyText(txt){let ok=false;
1027
+ try{if(navigator.clipboard&&window.isSecureContext){await navigator.clipboard.writeText(txt);ok=true}}catch(e){}
1028
+ if(!ok){try{const ta=document.createElement('textarea');ta.value=txt;ta.setAttribute('readonly','');ta.style.cssText='position:fixed;top:0;left:0;opacity:0';document.body.append(ta);ta.select();ok=document.execCommand('copy');ta.remove()}catch(e){}}
1029
+ const msg=$('#cpMsg'),btn=$('#cpBtn');
1030
+ if(ok){msg.textContent='✓ '+t('cpCopied');msg.className='cap good';btn.textContent=t('cpCopied')}
1031
+ else{msg.textContent=t('cpFail');msg.className='cap warn';const r=document.createRange();r.selectNodeContents($('#cpPre'));const sel=getSelection();sel.removeAllRanges();sel.addRange(r)}
1032
+ clearTimeout(copyText.tm);copyText.tm=setTimeout(()=>{if($('#cpBtn')){$('#cpBtn').textContent=t('cpCopy');$('#cpMsg').textContent=''}},2200)}
1033
+ // ---------- a model that never compacts: say so, and show where its sessions peak against the default ----------
1034
+ function noopPanel(){const g=G(),box=$('#noop'),dt=g.default.threshold,mx=Math.max(g.max_window||0,dt,g.peak_max||0),pk=peaksOf(g);
1035
+ box.innerHTML=`<div class="card nohead">${ic('check')}<div><div class="nt">${esc(t('noopT'))}${ib(t('noopSub'))}</div><div class="chips">`+
1036
+ chip(t('mPeak')+' '+fk(g.peak_max),'','flag')+chip('p50 '+fk(g.peak_p50),'','flag')+chip(t('rDefault')+' '+fk(dt),'','sliders')+
1037
+ chip(t('compAtDef',g.default.compactions),'','refresh')+`</div></div></div><div class="card fig" id="fNoop" style="margin-top:16px"></div>`;
1038
+ const nf=$('#fNoop'),W=boxW(nf),f=frame(W,230,{l:34,r:W<600?10:18,t:22,b:28}),nb=W<600?12:20,bw=mx/nb,cnt=new Array(nb).fill(0);pk.forEach(p=>cnt[Math.min(nb-1,Math.floor(p/bw))]++);
1039
+ const cmx=Math.max(...cnt,1),X=v=>f.x0+v/mx*(f.x1-f.x0),Y=v=>f.y0-v/cmx*(f.y0-f.y1);f.svg.setAttribute('aria-label',t('peaksL')+' · '+t('rDefault')+' '+fk(dt));
1040
+ f.svg.append(el('rect',{x:X(dt),y:f.y1,width:f.x1-X(dt),height:f.y0-f.y1,class:'nzone'}));
1041
+ if(f.x1-X(dt)>130)f.svg.append(el('text',{x:X(dt)+8,y:f.y1+14,class:'dl',style:'fill:var(--acc)'},t('zoneL')));
1042
+ axes(f,X,Y,nice(0,mx,Math.max(3,Math.floor(W/100))).filter(v=>v<=mx),nice(0,cmx,Math.min(cmx,4)).filter(v=>Number.isInteger(v)),fk,v=>String(v));
1043
+ cnt.forEach((c,b)=>{if(!c)return;const r=el('rect',{x:X(b*bw)+1,y:Y(c),width:Math.max(X(bw)-X(0)-2,1),height:f.y0-Y(c),rx:2,class:'nbar','data-tip':t('peaksTip',fk(b*bw),fk((b+1)*bw),c)});f.svg.append(r)});
1044
+ f.svg.append(el('line',{x1:X(dt),x2:X(dt),y1:f.y1-8,y2:f.y0,class:'mdef'}));
1045
+ dlabels(f,[{x:X(dt)-6,y:f.y1-2,text:t('rDefault')+' '+fk(dt),color:'var(--ink2)',anchor:'end',bold:1},{x:X(g.peak_max)+6,y:f.y1+30,text:t('mPeak')+' '+fk(g.peak_max),color:'var(--ink)',anchor:'start'}]);
1046
+ f.svg.append(el('line',{x1:X(g.peak_max),x2:X(g.peak_max),y1:f.y1+20,y2:f.y0,stroke:'var(--ink)','stroke-width':1}));
1047
+ f.svg.append(el('text',{x:f.x0,y:f.y1-8,class:'dl',style:'fill:var(--ink2)'},t('peaksL')));
1048
+ nf.append(f.svg)}
1049
+ // ---------- overview: every model's per-day impact for one profile, plus the recommended settings ----------
1050
+ function overviewHeader(){const sp=D.groups.filter(g=>g.span),a=sp.length?Math.min(...sp.map(g=>g.span[0])):null,b=sp.length?Math.max(...sp.map(g=>g.span[1])):null;
1051
+ const nm=new Set(D.groups.map(g=>g.harness+'|'+g.model)).size,ns=D.groups.reduce((x,g)=>x+g.n_sessions,0),nt=D.groups.reduce((x,g)=>x+g.n_turns,0);
1052
+ $('#eyebrow').textContent=t('allModels');$('#title').textContent=t('overview');$('#title').title='';
1053
+ const src=D.demo?'<span class="badge">'+t('synthetic')+'</span>':esc([...new Set(D.groups.map(g=>g.harness))].map(h=>t('srcLocal',h)).join(' · '));
1054
+ $('#meta').innerHTML=(a?mi('cal','mRange',esc(t('ovRange',day(a),day(b),nm))):'')+mi('db','mSource',src)+mi('layers','mMode',t(D.mode==='deep'?'modeDeep':'modeLite')+(D.generated?' · '+esc(D.generated.replace('data through ','≤ ')):''))+
1055
+ mi('flag','mSize',esc(t('sizeTxt',ns,nt.toLocaleString('en-US'))))+calMeta(null)+ib(t('caveat'))}
1056
+ function renderOverview(){overviewHeader();const box=$('#ovw'),k=S.op;
1057
+ // per model (harness + id): its groups, what applying the "set" ones would change, and its status
1058
+ const models=[];D.groups.forEach((g,i)=>{let m=models.find(x=>x.h===g.harness&&x.id===g.model);if(!m)models.push(m={h:g.harness,id:g.model,gs:[]});m.gs.push(i)});
1059
+ models.forEach(m=>{const G_=m.gs.map(i=>D.groups[i]);m.usd=G_.reduce((a,g)=>a+setUsd(g,k),0);m.min=G_.reduce((a,g)=>a+setMin(g,k),0);
1060
+ m.keep=G_.filter(g=>!g.no_action_needed&&!isSet(g,k));m.st=G_.some(g=>isSet(g,k))?'set':m.keep.length?'keep':'noop';m.kl=m.keep.some(g=>actOf(g,k)==='aCur')?'aCur':'aKeep';
1061
+ m.den=G_.reduce((a,g)=>a+defUsd(g),0);m.mden=G_.reduce((a,g)=>a+defMin(g),0);
1062
+ m.w=Math.abs(m.usd)+1e-6*G_.reduce((a,g)=>a+Math.abs(usdOf(g,k)),0);m.gs.sort((a,b)=>(D.groups[a].role==='main'?0:1)-(D.groups[b].role==='main'?0:1))});
1063
+ const tu=models.reduce((a,m)=>a+m.usd,0),tm=models.reduce((a,m)=>a+m.min,0),cnt=st=>models.filter(m=>m.st===st).length;
1064
+ // percents of the whole: summed changes over summed defaults (all groups), never an average of group percents
1065
+ const tpu=ratio(tu,baseUsd(D.groups,k)),tpm=ratio(tm,baseMin(D.groups,k));
1066
+ const kpi=(icn,lab,v,cls,sub)=>`<div class="kpi"><div class="kh">${ic(icn)}<span>${t(lab)}</span></div><div class="v ${cls||''}">${v}</div>${sub?`<div class="cap">${sub}</div>`:''}</div>`;
1067
+ box.innerHTML=`<div class="ovbar"><div class="seg" role="group" aria-label="${t('gear')}">${PROF.map(p=>`<button data-op="${p}" aria-pressed="${p===k}" aria-label="${t(p)}">${ic(PICON[p])}<span class="gt">${t(p)}</span></button>`).join('')}</div><span class="vot">${esc(t('votS',D.groups[0]?D.groups[0].profiles[k].value_of_time:0))}</span></div>
1068
+ <div class="kpis">${kpi('coin','kTotUsd','<span class="nw">'+dual(tpu,fsv(tu)+t('uDay'),fsn(tu)+t('uDay'))+'</span>',tone(tu),esc(t('kTotSub',cnt('set')))+' <span class="est">'+t('est')+'</span>'+ib(t('kTotPct')))+kpi('clock','kTotMin','<span class="nw">'+dual(tpm,fmv(tm)+t('uDay'),fmn(tm)+t('uDay'))+'</span>',tone(tm),esc(t('kTotSub',cnt('set'))))+
1069
+ kpi('sliders','kToSet',String(cnt('set')),'',esc(t('mUnit')))+kpi('scale','kKeep',String(cnt('keep')),'',esc(t('mUnit')))+kpi('check','kNoCh',String(cnt('noop')),'',esc(t('mUnit')))}</div>
1070
+ <h2>${t('ovChart')}${ib(t('ovHelp'))}</h2><div class="card fig" id="fOv">
1071
+ <div class="ovctl"><div class="seg" role="group" aria-label="${t('scL')}">${[['abs','scAbs'],['norm','scNorm']].map(([k_,l])=>`<button data-ovs="${k_}" aria-pressed="${S.ovScale===k_}">${t(l)}</button>`).join('')}</div>
1072
+ <div class="seg" role="group" aria-label="${t('stL')}" id="ovst"></div>
1073
+ <div class="seg" role="group" aria-label="${t('byL')}">${[['usd','byUsd'],['pct','byPct']].map(([k_,l])=>`<button data-ovb="${k_}" aria-pressed="${S.ovBy===k_}">${t(l)}</button>`).join('')}</div></div>
1074
+ ${legendBA()}<h3 class="ovh">${ic('coin')}${t('ovCostT')}</h3><div id="ovC"></div><h3 class="ovh">${ic('clock')}${t('ovTimeT')}</h3><div id="ovM"></div><ul class="sr" id="ovSR"></ul></div>
1075
+ <h2>${t('ovTable')}</h2><div class="card scroll" id="ovT"></div>`;
1076
+ box.querySelectorAll('[data-op]').forEach(b=>b.onclick=()=>{S.op=b.dataset.op;S.tree=null;keep(()=>{renderOverview();tree()})});
1077
+ box.querySelectorAll('[data-ovs]').forEach(b=>b.onclick=()=>{S.ovScale=b.dataset.ovs;try{localStorage.setItem('compactlab.ovScale',S.ovScale)}catch(e){}keep(renderOverview)});
1078
+ box.querySelectorAll('[data-ovb]').forEach(b=>b.onclick=()=>{S.ovBy=b.dataset.ovb;try{localStorage.setItem('compactlab.ovBy',S.ovBy)}catch(e){}keep(renderOverview)});
1079
+ // before / after per model: was = the default's summed per-day amount, now = was + the change of its "set" groups
1080
+ const rows=models.filter(m=>m.st!=='noop').map(m=>{const G_=m.gs.map(i=>D.groups[i]),sg=G_.filter(g=>isSet(g,k)),im=sg.map(g=>impOf(g,k,'vs_default')).filter(Boolean);
1081
+ return {m,name:label(m.id),sub:m.h+' · '+m.gs.map(i=>roleS(D.groups[i].role)).join(' + '),keep:m.st==='keep',kl:m.kl,gi:m.gs[0],
1082
+ c:{was:m.den,now:m.den+m.usd},t:{was:m.mden,now:m.mden+m.min},
1083
+ wait:im.reduce((a,x)=>a+x.wait_minutes.per_day,0),turn:im.reduce((a,x)=>a-x.turn_gain_minutes.per_day,0),
1084
+ roles:m.gs.map(i=>{const g=D.groups[i];return [roleL(g.role),g.no_action_needed?t('noChange'):fsv(usdOf(g,k))+t('uDay')+(isSet(g,k)?'':' · '+t(actOf(g,k)))]})}});
1085
+ const sv=r=>r.keep?Infinity:S.ovBy==='pct'?(ratio(r.c.now-r.c.was,r.c.was)??0):r.c.now-r.c.was;
1086
+ rows.sort((a,b)=>(a.keep-b.keep)||sv(a)-sv(b)||b.c.was-a.c.was);
1087
+ const setR=rows.filter(r=>!r.keep),tot={name:t('totalSet'),sub:t('totalSub',setR.length),total:true,keep:false,gi:null,
1088
+ c:{was:setR.reduce((a,r)=>a+r.c.was,0),now:setR.reduce((a,r)=>a+r.c.now,0)},t:{was:setR.reduce((a,r)=>a+r.t.was,0),now:setR.reduce((a,r)=>a+r.t.now,0)},
1089
+ wait:setR.reduce((a,r)=>a+r.wait,0),turn:setR.reduce((a,r)=>a+r.turn,0),roles:[]};
1090
+ const items=(setR.length?[tot]:[]).concat(rows),style=ovStyleFor(items.length);
1091
+ $('#ovst').innerHTML=[['bars','stBars'],['dots','stDots']].map(([k_,l])=>`<button data-ovst="${k_}" aria-pressed="${style===k_}" aria-label="${t(l)}" data-tip="${t(l)}">${ic(k_)}</button>`).join('');
1092
+ $('#ovst').querySelectorAll('[data-ovst]').forEach(b=>b.onclick=()=>{S.ovStyle=b.dataset.ovst;try{localStorage.setItem('compactlab.ovStyle',S.ovStyle)}catch(e){}keep(renderOverview)});
1093
+ $('#fOv').classList.toggle('dots',style==='dots');beforeAfter($('#ovC'),items,'c',style);beforeAfter($('#ovM'),items,'t',style);
1094
+ $('#ovSR').innerHTML=items.map(r=>'<li>'+esc(srRow(r))+'</li>').join('');
1095
+ // roll-up table, every group: set first, then keep default, then no change
1096
+ const rk=g=>g.no_action_needed?2:isSet(g,k)?0:1;
1097
+ const pcOf=g=>g.no_action_needed?{c:null,t:null}:pctAt(g,g.profiles[k].threshold,g.default);
1098
+ const key={cModel:g=>label(g.model),cUsd:g=>S.unit==='pct'&&pcOf(g).c!=null?pcOf(g).c:usdOf(g,k),cMin:g=>S.unit==='pct'&&pcOf(g).t!=null?pcOf(g).t:minOf(g,k)};
1099
+ const so=S.ovSort,tr=D.groups.map((g,i)=>[g,i]).sort((a,b)=>so?(so.k==='cModel'?key.cModel(a[0]).localeCompare(key.cModel(b[0])):key[so.k](a[0])-key[so.k](b[0]))*(so.asc?1:-1):rk(a[0])-rk(b[0])||Math.abs(usdOf(b[0],k))-Math.abs(usdOf(a[0],k)));
1100
+ $('#ovT').innerHTML='<table><tr>'+['cModel','cRole','cTier','cDef','cAct','cUsd','cMin'].map(c=>key[c]?`<th><button type="button" class="srt" data-sort="${c}" aria-label="${t('sortBy')} ${t(c)}">${t(c==='cUsd'?(S.unit==='pct'?'cUsdP':'cUsd'):c==='cMin'?(S.unit==='pct'?'cMinP':'cMin'):c)}${so&&so.k===c?(so.asc?' ↑':' ↓'):''}</button></th>`:'<th>'+t(c)+'</th>').join('')+'</tr>'+tr.map(([g,i])=>{const P=g.profiles[k],a=action(g,P.threshold,P.value_of_time),u=usdOf(g,k),mn=minOf(g,k),mu=a==='aSet'?'':' mute',pr=pcOf(g);
1101
+ return `<tr><td><button type="button" data-tab="${i}" title="${esc(g.model)}">${esc(label(g.model))}</button></td><td>${ic(roleIc(g.role))} ${esc(roleS(g.role))}</td><td>${g.no_action_needed?'–':ic(PICON[k])+' '+fk(P.threshold)}</td><td>${fk(g.default.threshold)}</td><td><span class="act ${a==='aSet'?'set':''}">${t(a)}</span>${(a==='aKeep'||a==='aCur')?`<div class="kw">${esc(keepWhy(g,P.threshold,P.value_of_time))}</div>`:''}</td><td class="${tone(u)}${mu}" data-v="usd">${g.no_action_needed?'–':dual(pr.c,fsv(u),fsn(u))}</td><td class="${tone(mn)}${mu}">${g.no_action_needed?'–':dual(pr.t,fmv(mn),fmn(mn))}</td></tr>`}).join('')+'</table>';
1102
+ $('#ovT').querySelectorAll('[data-tab]').forEach(b=>b.onclick=()=>pick(+b.dataset.tab));
1103
+ $('#ovT').querySelectorAll('[data-sort]').forEach(b=>b.onclick=()=>{const c=b.dataset.sort;S.ovSort=S.ovSort&&S.ovSort.k===c?{k:c,asc:!S.ovSort.asc}:{k:c,asc:true};keep(renderOverview)}); // first click: A→Z, or the biggest saving first
1104
+ copyPanel();renderS()}
1105
+ // ---------- before / after bars: grey = was (default), accent = now (profile), green hatch = saved, amber = added ----------
1106
+ const fabs=(v,kind)=>kind==='c'?'$'+(v>=100?Math.round(v).toLocaleString('en-US'):v.toFixed(1)):(v>=100?Math.round(v):v.toFixed(1))+' min';
1107
+ function legendBA(){return `<div class="olg"><span><i class="lw"></i>${t('lgWas')}</span><span><i class="ln"></i>${t('lgNow')}</span><span><i class="ls"></i>${t('lgSaved')}</span><span><i class="la"></i>${t('lgAdded')}</span></div>`}
1108
+ // the legend's swatches follow the chart style (bars: blocks and hatch; dots: dots and lines)
1109
+ function baLabel(o,kind){const d=o.now-o.was,pv=ratio(d,o.was),p=S.unit==='pct'&&pv!=null;
1110
+ return {lead:p?fpct(pv):(kind==='c'?fsv(d)+t('uDay'):fmv(d)+t('uDay')),sec:p?(kind==='c'?fsn(d)+t('uDay'):fmn(d)+t('uDay')):fpn(pv),tone:tone(kind==='c'?d:d),wn:t('wasNow',fabs(o.was,kind),fabs(o.now,kind))}}
1111
+ function srRow(r){const d=r.c.now-r.c.was,pv=ratio(d,r.c.was);
1112
+ return r.keep?t('srKeep',r.name,fabs(r.c.was,'c')):t('srRow',r.name,fabs(r.c.was,'c'),fabs(r.c.now,'c'),d<0?t('saves'):t('adds'),pv==null?'–':pabs(pv),fabs(r.t.was,'t'),fabs(r.t.now,'t'))}
1113
+ function hatchDef(svg,id){const defs=el('defs'),p=el('pattern',{id,width:5,height:5,patternUnits:'userSpaceOnUse',patternTransform:'rotate(45)'});
1114
+ p.append(el('rect',{width:5,height:5,class:'bash'}),el('line',{x1:0,y1:0,x2:0,y2:5,class:'bahl'}));defs.append(p);svg.append(defs)}
1115
+ // bars (overlay) or dumbbells (dot and line); without a choice, dumbbells from nine rows up
1116
+ const ovStyleFor=n=>S.ovStyle||(n>8?'dots':'bars');
1117
+ function beforeAfter(box,items,kind,style='bars'){box.innerHTML='';if(!items.length)return;
1118
+ const W=boxW(box.parentElement,36),wide=W>=600,rowH=wide?44:62,L=wide?180:8,R=wide?300:8,T=4,norm=S.ovScale==='norm';
1119
+ const v=r=>r[kind],pw=W-L-R,mx=Math.max(...items.map(r=>Math.max(v(r).was,v(r).now)),1e-9);
1120
+ // absolute: one shared axis; normalised: every row's "was" is the same length (80% of the plot, room for amber)
1121
+ const len=(r,x)=>norm?(v(r).was>0?x/v(r).was:0)*pw*.8:x/mx*pw;
1122
+ const H=T+items.length*rowH+30,svg=el('svg',{viewBox:`0 0 ${W} ${H}`,role:'img','aria-label':t(kind==='c'?'ovCostT':'ovTimeT')});svg.classList.add('bac',style);
1123
+ const hid='hs-'+kind;hatchDef(svg,hid);
1124
+ const ticks=norm?[0,.5,1].map(f=>[f*pw*.8,Math.round(f*100)+'%']):ticksN(0,mx,Math.max(3,Math.floor(pw/110))).filter(x=>x<=mx).map(x=>[x/mx*pw,kind==='c'?'$'+(+x.toFixed(1)):(+x.toFixed(1))+'']);
1125
+ for(const [x,l] of ticks){svg.append(el('line',{x1:L+x,x2:L+x,y1:T,y2:H-26,class:'grid'}));svg.append(el('text',{x:L+x,y:H-12,'text-anchor':'middle'},l))}
1126
+ svg.append(el('text',{x:L+pw,y:H-1,'text-anchor':'end',class:'axt'},t(norm?'axNorm':kind==='c'?'axUsd':'axMin')));
1127
+ items.forEach((r,n)=>{const y=T+n*rowH,o=v(r),gr=el('g',{class:'barow'+(r.total?' tot':'')+(r.keep?' keep':'')});if(r.gi!=null)gr.dataset.tab=r.gi;
1128
+ gr.append(el('rect',{x:0,y,width:W,height:rowH-2,rx:6,class:'ovbg'}));
1129
+ if(r.total)svg.append(el('line',{x1:0,x2:W,y1:y+rowH-1,y2:y+rowH-1,class:'ax'}));
1130
+ const by=wide?y+9:y+24,ww=Math.max(len(r,o.was),3),nw=r.keep?0:Math.max(len(r,o.now),o.now>0?2:0);
1131
+ gr.append(el('text',{x:8,y:wide?y+17:y+14,class:'ovname'+(r.total?' b':'')},r.name));if(wide)gr.append(el('text',{x:8,y:y+31,class:'ovsub'},r.sub));
1132
+ if(style==='dots'){const cy=by+11,xw=L+ww,xn=L+nw;
1133
+ gr.append(el('line',{x1:L,x2:L+pw*(norm?.8:1),y1:cy,y2:cy,class:'dtrack'}));
1134
+ if(!r.keep&&Math.abs(xn-xw)>.5)gr.append(el('line',{x1:xw,x2:xn,y1:cy,y2:cy,class:'dline '+(xn<xw?'sv':'ad')}));
1135
+ gr.append(el('circle',{cx:xw,cy,r:5.5,class:'dwas'}));if(!r.keep)gr.append(el('circle',{cx:xn,cy,r:5.5,class:'dnow'}))}
1136
+ else gr.append(el('rect',{x:L,y:by,width:ww,height:22,rx:3,class:'baw'}));
1137
+ if(style!=='dots'&&!r.keep){gr.append(el('rect',{x:L,y:by+5,width:nw,height:12,rx:2,class:'ban'}));
1138
+ if(nw<ww-.5){gr.append(el('rect',{x:L+nw,y:by+5,width:ww-nw,height:12,fill:`url(#${hid})`}));
1139
+ gr.append(el('path',{d:`M${L+nw},${by-2}v-3h${ww-nw}v3`,class:'babr'}))} // bracket over the saving
1140
+ else if(nw>ww+.5)gr.append(el('rect',{x:L+ww,y:by+5,width:nw-ww,height:12,rx:2,class:'baa'}))}
1141
+ // labels: a fixed column on the right (a leader joins tiny bars to it); on a phone, above and below the bar
1142
+ const lb=baLabel(o,kind),end=L+Math.max(ww,nw)+(style==='dots'?6:0);
1143
+ if(wide){const lx=L+pw+14;if(lx-end>10)gr.append(el('line',{x1:end+4,x2:lx-4,y1:by+11,y2:by+11,class:'lead'}));
1144
+ const tx=el('text',{x:lx,y:y+17,class:'dl b'});
1145
+ if(r.keep)tx.append(el('tspan',{class:'mute'},t(r.kl||'aKeep')+' · '+fabs(o.was,kind)+t('uDay')));
1146
+ else tx.append(el('tspan',{class:'big '+lb.tone},lb.lead+' '),el('tspan',{class:lb.tone+' sc2'},lb.sec));
1147
+ gr.append(tx);if(!r.keep)gr.append(el('text',{x:lx,y:y+32,class:'ovsub'},lb.wn))}
1148
+ else{const tx=el('text',{x:W-8,y:y+14,'text-anchor':'end',class:'dl b'});
1149
+ if(r.keep)tx.append(el('tspan',{class:'mute'},t(r.kl||'aKeep')));else tx.append(el('tspan',{class:'big '+lb.tone},lb.lead+' '),el('tspan',{class:lb.tone+' sc2'},lb.sec));
1150
+ gr.append(tx);gr.append(el('text',{x:8,y:y+58,class:'ovsub'},r.keep?fabs(o.was,kind)+t('uDay'):lb.wn))}
1151
+ const tip=()=>'<b>'+esc(r.name)+'</b>'+tipRow(t('lgWas'),fabs(o.was,kind)+t('uDay'))+(r.keep?tipRow(t(r.kl||'aKeep'),''):tipRow(t('lgNow'),fabs(o.now,kind)+t('uDay'))+tipRow(o.now<=o.was?t('lgSaved'):t('lgAdded'),fpct(ratio(o.now-o.was,o.was))+' · '+(kind==='c'?fsn(o.now-o.was):fmn(o.now-o.was))+t('uDay')))+
1152
+ (kind==='t'&&!r.keep?tipRow(t('tWait'),fmv(r.wait)+t('uDay'))+tipRow(t('tTurn'),fmv(r.turn)+t('uDay')):'')+r.roles.map(([a,b])=>tipRow(a,b)).join('');
1153
+ gr.addEventListener('pointermove',e=>showTip(tip(),e.clientX,e.clientY));gr.addEventListener('pointerleave',hideTip);
1154
+ if(r.gi!=null)gr.addEventListener('click',()=>pick(r.gi));svg.append(gr)});
1155
+ box.append(svg)}
1156
+ // compact pair on the model page: cost and time at the cursor against the default, in the same visual language
1157
+ function miniBA(g,im){const rows=[['c',defUsd(g),defUsd(g)+im.usd.per_day],['t',defMin(g),defMin(g)+im.minutes.per_day]],W=150,H=30,svg=el('svg',{viewBox:`0 0 ${W} ${H}`,width:W,height:H,class:'mini'});
1158
+ hatchDef(svg,'hs-mini');const txt=[];
1159
+ rows.forEach(([kind,was,now],n)=>{const mx=Math.max(was,now,1e-9),y=2+n*15,ww=Math.max(was/mx*(W-4),2),nw=Math.max(now/mx*(W-4),now>0?1:0);
1160
+ svg.append(el('rect',{x:2,y,width:ww,height:12,rx:2,class:'baw'}),el('rect',{x:2,y:y+3,width:nw,height:6,rx:1,class:'ban'}));
1161
+ if(nw<ww)svg.append(el('rect',{x:2+nw,y:y+3,width:ww-nw,height:6,fill:'url(#hs-mini)'}));else if(nw>ww)svg.append(el('rect',{x:2+ww,y:y+3,width:nw-ww,height:6,class:'baa'}));
1162
+ txt.push(t(kind==='c'?'wCost':'wTime')+': '+t('wasNow',fabs(was,kind),fabs(now,kind))+' ('+fpct(ratio(now-was,was))+')')});
1163
+ const s_=txt.join(' · ')+' — '+t('lgLine');svg.setAttribute('role','img');svg.setAttribute('aria-label',s_);return `<span class="minib" tabindex="0" data-tip="${esc(s_)}">${svg.outerHTML}</span>`}
1164
+ // update(): everything that depends on the selected threshold/profile; render(): full rebuild (group or language change)
1165
+ function update(){if(S.view!=='group')return;controls();impactPanel();comparison();pareto();costs();timeChart();hist();sessChart();moveCursor();hideTip()}
1166
+ function render(){keep(()=>{if(S.view==='overview'){renderOverview();return}header();renderS();
1167
+ if(S.view==='noop'){noopPanel();return}buildBar();buildMain();sessPick();update();copyPanel();deepPanel()})}
1168
+ function setView(v){S.view=v;document.body.dataset.view=v}
1169
+ function hashOf(){return S.view==='overview'?'#overview':'#g='+encodeURIComponent([G().harness,G().model,G().role].join('|'))}
1170
+ function setHash(){try{history.replaceState(null,'',hashOf())}catch(e){}}
1171
+ function pick(i){S.gi=i;const g=G();setView(g.no_action_needed?'noop':'group');S.gear=g.profile||'balanced';S.T=g.profiles[S.gear].threshold;S.vot=g.profiles[S.gear].value_of_time;S.sid=null;S.mc=null;
1172
+ render();tree();setHash();closeDrawer()}
1173
+ function overview(){setView('overview');S.mc=null;render();tree();setHash();closeDrawer()}
1174
+ function fromHash(){const h=decodeURIComponent(location.hash||'');if(h==='#overview')return 'ov';
1175
+ if(h.startsWith('#g=')){const [hh,m,r]=h.slice(3).split('|'),i=D.groups.findIndex(g=>g.harness===hh&&g.model===m&&g.role===r);if(i>=0)return i}return null}
1176
+ if(D.groups.length){const h=fromHash(),b=best();S.gi=Math.max(b,0);statics();if(h==='ov'||(h==null&&b<0))overview();else pick(h!=null?h:b)}
1177
+ else{statics();$('#ctl').textContent=t('none')}
1178
+ addEventListener('scroll',hideTip,{passive:true});
1179
+ function spark(c){if(c.length<2)return'';const w=110,h=20,mx=Math.max(...c);return `<svg viewBox="0 0 ${w} ${h}" width="${w}" height="${h}" aria-hidden="true"><polyline fill="none" stroke="var(--acc)" stroke-width="1.1" points="${c.map((v,i)=>(i/(c.length-1)*w).toFixed(1)+','+(h-1-v/mx*(h-2)).toFixed(1)).join(' ')}"/></svg>`}
1180
+ function renderS(){const q=$('#q').value.toLowerCase(),g=S.view==='overview'?null:G();
1181
+ $('#hSess').textContent=g?t('hSessG',label(g.model)+' · '+roleS(g.role)):t('hSessAll');
1182
+ const pool=g?D.sessions.filter(s=>s.model===g.model&&s.role===g.role&&(!s.harness||s.harness===g.harness)):D.sessions;
1183
+ const rows=pool.filter(s=>(s.id+s.model+s.role+s.harness).toLowerCase().includes(q));
1184
+ rows.sort((a,b)=>(a[sortK]>b[sortK]?1:-1)*(asc?1:-1));$('#cnt').textContent=t('of',rows.length,pool.length);
1185
+ const cols=[['id','colSession'],['harness','colHarness'],['role','colRole'],['model','colModel'],['turns','colTurns'],['peak','colPeak'],['compactions','colComp']];
1186
+ $('#st').innerHTML='<tr>'+cols.map(c=>`<th data-k="${c[0]}">${t(c[1])}</th>`).join('')+'<th>'+t('colCtx')+'</th></tr>'+rows.slice(0,500).map(s=>`<tr><td>${esc(s.id.slice(0,28))}</td><td>${s.harness}</td><td>${s.role}</td><td>${esc(s.model)}</td><td>${s.turns}</td><td>${fk(s.peak)}</td><td>${s.compactions}</td><td>${spark(s.curve)}</td></tr>`).join('');
1187
+ document.querySelectorAll('#st th[data-k]').forEach(th=>th.onclick=()=>{const k=th.dataset.k;asc=sortK===k?!asc:false;sortK=k;renderS()})}
1188
+ $('#q').oninput=renderS;renderS();
1189
+ </script></body></html>