lean-ctx 3.10.5

Local context engine, CLI, MCP server, and proxy for AI agents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
/**
 * Leaderboard (#466 items 1+2) — submit your tokens saved to the community
 * board and flip auto-submit, right from the dashboard.
 *
 * Phase B (this file): your current standing + a Submit button (optional handle)
 * + an auto-submit on/off toggle. All three talk to the authenticated, CSRF-
 * protected /api/leaderboard/* endpoints; a submit sends only the minimal
 * aggregate numbers (tokens saved, est. USD, compression rate) and your chosen
 * handle — never code, paths or prompts. Phase C adds the public rankings table
 * above the standing card via a server-side /api/leaderboard proxy.
 */

// Public rankings are Research and intentionally unavailable in the default
// dashboard. Keep the implementation behind an explicit local development
// flag so it cannot become an implicit public product claim.
function experimentalLeaderboardEnabled() {
  return window.LEAN_CTX_EXPERIMENTAL_LEADERBOARD === true;
}

function api() {
  return window.LctxApi && window.LctxApi.apiFetch ? window.LctxApi.apiFetch : null;
}

function fmtLib() {
  return window.LctxFmt || {};
}

function shared() {
  return window.LctxShared || {};
}

class CockpitLeaderboard extends HTMLElement {
  constructor() {
    super();
    this._status = null;
    this._loading = true;
    this._error = null;
    this._busy = null; // 'submit' | 'auto' while a write is in flight
    // Feedback is rendered *inline* at the control that produced it, never at the
    // top of the card: the card is long (standing + full board + submit), so a
    // top banner is off-screen when you act on the submit/auto controls at the
    // bottom — a failed write then looks like "nothing happened" (#466 follow-up).
    this._submitNotice = null;
    this._autoNotice = null;
    this._name = '';
    // Public board (#466 item 2) — loaded independently so a board outage never
    // blocks the submit/auto controls.
    this._board = null;
    this._boardLoading = true;
    this._boardError = null;
    this._onRefresh = this._onRefresh.bind(this);
    // Machine linking (GH #736)
    this._linkCode = null;
    this._linkExpiry = null;
    this._linkInput = '';
    this._linkBusy = null; // 'start' | 'complete'
    this._linkNotice = null;
    // Recovery phrase state
    this._phrase = null;
    this._phraseVisible = false;
    this._phraseLoaded = false;
    this._rejoinInput = '';
    this._rejoinBusy = false;
    this._rejoinNotice = null;
  }

  connectedCallback() {
    if (this._ready) return;
    this._ready = true;
    this.style.display = 'block';
    document.addEventListener('lctx:refresh', this._onRefresh);
    this.render();
    // Lazy-load (#452): the router calls loadData() when this view activates.
  }

  disconnectedCallback() {
    document.removeEventListener('lctx:refresh', this._onRefresh);
  }

  _onRefresh() {
    var v = document.getElementById('view-leaderboard');
    if (v && v.classList.contains('active')) this.loadData();
  }

  async loadData() {
    if (!experimentalLeaderboardEnabled()) {
      this._loading = false;
      this.render();
      return;
    }
    var fetchJson = api();
    if (!fetchJson) {
      this._error = 'API client not loaded';
      this._loading = false;
      this.render();
      return;
    }
    this._loading = !this._status;
    this._error = null;
    if (!this._phraseLoaded) this._loadPhrase();
    if (this._loading) this.render();
    try {
      var resp = await fetchJson('/api/leaderboard/status', { timeoutMs: 8000 });
      this._status = resp || {};
      // Seed the handle input from the saved display name on first load only,
      // so we never clobber what the user is mid-typing on a refresh.
      if (this._name === '' && this._status.display_name) {
        this._name = String(this._status.display_name);
      }
      this._loading = false;
      this.render();
      this._bind();
    } catch (e) {
      this._loading = false;
      this._error = e && e.error ? String(e.error) : 'failed to load leaderboard status';
      this.render();
    }
    // Load the public board in parallel — never gates the controls above.
    this._loadBoard();
  }

  async _loadBoard() {
    var fetchJson = api();
    if (!fetchJson) return;
    this._boardError = null;
    try {
      // The public board is paginated now; pull a generous first page for the
      // in-app view and link out to the full board for everyone beyond it.
      var resp = await fetchJson('/api/leaderboard?per_page=100', { timeoutMs: 12000 });
      var entries = (resp && resp.entries) || [];
      // Drop entries the server flagged for review (anomalous / under audit).
      this._board = entries.filter(function (e) {
        return e && e.flagged !== true;
      });
      this._boardLoading = false;
    } catch (e) {
      this._boardLoading = false;
      this._boardError = e && e.error ? String(e.error) : 'could not load the board';
    }
    this.render();
    this._bind();
  }

  async _submit() {
    var fetchJson = api();
    if (!fetchJson || this._busy) return;
    this._busy = 'submit';
    this._submitNotice = null;
    this.render();
    this._bind();
    var name = (this._name || '').trim();
    try {
      var resp = await fetchJson('/api/leaderboard/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(name ? { name: name } : {}),
        timeoutMs: 20000,
      });
      var url = resp && resp.url ? String(resp.url) : null;
      this._submitNotice = {
        kind: 'ok',
        msg: 'Submitted to the community leaderboard.',
        url: url,
      };
      await this.loadData();
      this.render();
      this._bind();
      return;
    } catch (e) {
      this._submitNotice = {
        kind: 'err',
        msg: e && e.error ? String(e.error) : 'Submit failed.',
      };
    }
    this._busy = null;
    this.render();
    this._bind();
  }

  async _setAuto(on) {
    var fetchJson = api();
    if (!fetchJson || this._busy) return;
    this._busy = 'auto';
    this._autoNotice = null;
    this.render();
    this._bind();
    try {
      var resp = await fetchJson('/api/leaderboard/auto', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ on: !!on }),
        timeoutMs: 12000,
      });
      this._status = resp || this._status;
      this._autoNotice = {
        kind: 'ok',
        msg: on ? 'Auto-submit is on.' : 'Auto-submit is off.',
      };
    } catch (e) {
      this._autoNotice = {
        kind: 'err',
        msg: e && e.error ? String(e.error) : 'Could not change auto-submit.',
      };
    }
    this._busy = null;
    this.render();
    this._bind();
  }

  render() {
    if (!experimentalLeaderboardEnabled()) {
      this.innerHTML =
        '<div class="card"><div class="card-header"><h3>Public rankings are unavailable</h3></div>' +
        '<p class="hs" style="margin:0">Benchmark publication and the Agent Performance Index are Research. ' +
        'Use local Receipts and offline verification for evidence today.</p></div>';
      return;
    }
    var F = fmtLib();
    var esc =
      F.esc ||
      function (s) {
        return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {
          return '&#' + c.charCodeAt(0) + ';';
        });
      };

    if (this._loading) {
      this.innerHTML = '<div class="card"><div class="loading-state">Loading leaderboard\u2026</div></div>';
      return;
    }
    if (this._error) {
      this.innerHTML =
        '<div class="card"><h3>Error</h3><p class="hs" style="color:var(--red)">' +
        esc(this._error) +
        '</p></div>';
      return;
    }

    this.innerHTML =
      '<div style="display:grid;gap:14px">' +
      this._renderStanding(esc) +
      this._renderBoard(esc) +
      this._renderLink(esc) +
      this._renderRecovery(esc) +
      this._renderSubmit(esc) +
      this._renderAuto(esc) +
      '</div>' +
      this._renderFooter(shared());
  }

  /**
   * Inline feedback shown directly under the control that triggered a write.
   * `notice` is `{ kind: 'ok' | 'err', msg, url? }` or null. Errors wrap rather
   * than truncate so an actionable message (e.g. "run lean-ctx doctor --fix")
   * is always fully readable at the point of action.
   */
  _renderInlineNotice(esc, notice) {
    if (!notice) return '';
    var ok = notice.kind === 'ok';
    var color = ok ? 'var(--green)' : 'var(--red)';
    var bg = ok ? 'rgba(34,197,94,.08)' : 'rgba(239,68,68,.08)';
    var link = notice.url
      ? ' <a href="' +
        esc(notice.url) +
        '" target="_blank" rel="noopener noreferrer" style="color:' +
        color +
        '">View your card \u2192</a>'
      : '';
    return (
      '<p class="hs" role="status" style="margin:10px 0 0;padding:8px 10px;' +
      'border-left:2px solid ' +
      color +
      ';background:' +
      bg +
      ';border-radius:6px;color:' +
      color +
      ';font-size:12px;line-height:1.5;word-break:break-word">' +
      esc(notice.msg) +
      link +
      '</p>'
    );
  }

  _renderStanding(esc) {
    var s = this._status || {};
    var pill = function (bg, fg, text) {
      return (
        '<span style="display:inline-block;padding:3px 10px;border-radius:999px;' +
        'font-size:12px;font-weight:600;background:' +
        bg +
        ';color:' +
        fg +
        '">' +
        text +
        '</span>'
      );
    };
    var badge;
    if (s.on_leaderboard) {
      badge = pill('rgba(34,197,94,.15)', 'var(--green)', 'On the leaderboard');
    } else if (s.published) {
      badge = pill(
        'rgba(234,179,8,.15)',
        'var(--yellow)',
        'Published privately \u2014 not on the board'
      );
    } else {
      badge = pill('rgba(148,163,184,.15)', 'var(--muted,#94a3b8)', 'Not submitted yet');
    }

    var rows = '';
    if (s.display_name) {
      rows +=
        '<p class="hs" style="margin:6px 0 0;font-size:12px;opacity:.85">Handle: <strong>' +
        esc(s.display_name) +
        '</strong></p>';
    }
    if (s.last_published_at) {
      rows +=
        '<p class="hs" style="margin:6px 0 0;font-size:12px;opacity:.7">Last submitted: ' +
        esc(this._fmtDate(s.last_published_at)) +
        '</p>';
    }
    if (s.url) {
      rows +=
        '<p class="hs" style="margin:6px 0 0;font-size:12px"><a href="' +
        esc(s.url) +
        '" target="_blank" rel="noopener noreferrer">Your public card \u2192</a></p>';
    }

    return (
      '<div class="card">' +
      '<div class="card-header"><h3>Your standing</h3></div>' +
      '<div style="margin:4px 0 0">' +
      badge +
      '</div>' +
      rows +
      '</div>'
    );
  }

  _renderBoard(esc) {
    var F = fmtLib();
    var head =
      '<div class="card-header"><h3>Community leaderboard</h3></div>' +
      '<p class="hs" style="margin:0 0 10px;font-size:12px;opacity:.8">' +
      'Top contributors by all-time tokens saved \u2014 the opt-in public board at ' +
      '<code>leanctx.com/metrics</code>.</p>';

    var inner;
    if (this._boardLoading && !this._board) {
      inner = '<div class="loading-state">Loading the board\u2026</div>';
    } else if (this._boardError && !this._board) {
      inner =
        '<p class="hs" style="margin:0;color:var(--yellow);font-size:12px">' +
        'Couldn\u2019t load the board: ' +
        esc(this._boardError) +
        '</p>';
    } else if (!this._board || this._board.length === 0) {
      inner = '<p class="hs" style="margin:0;opacity:.7;font-size:12px">No entries yet \u2014 be the first to submit.</p>';
    } else {
      inner =
        this._boardTable(esc, F) +
        '<p class="hs" style="margin:12px 0 0;font-size:12px">' +
        '<a href="https://leanctx.com/metrics" target="_blank" rel="noopener noreferrer">' +
        'See the full leaderboard \u2192</a></p>';
    }
    return '<div class="card">' + head + inner + '</div>';
  }

  _boardTable(esc, F) {
    var myUrl = this._status && this._status.url ? String(this._status.url) : null;
    var fmtNum = F.fmt || function (n) { return String(n); };
    var self = this;
    var rows = this._board
      .slice(0, 100)
      .map(function (e) {
        var mine = myUrl && e.url === myUrl;
        var name = e.display_name ? esc(String(e.display_name)) : '<span style="opacity:.6">anonymous</span>';
        var nameCell = e.url
          ? '<a href="' + esc(String(e.url)) + '" target="_blank" rel="noopener noreferrer" style="color:inherit;text-decoration:none">' + name + '</a>'
          : name;
        var youTag = mine
          ? ' <span style="font-size:10px;font-weight:700;color:var(--green);border:1px solid var(--green);border-radius:4px;padding:0 4px;margin-left:4px">YOU</span>'
          : '';
        var rowStyle =
          'border-top:1px solid var(--border,#222)' +
          (mine ? ';background:rgba(34,197,94,.08)' : '');
        var td = 'padding:7px 8px;font-size:12px';
        return (
          '<tr style="' + rowStyle + '">' +
          '<td style="' + td + ';opacity:.6;width:38px">' + esc(String(e.rank != null ? e.rank : '')) + '</td>' +
          '<td style="' + td + ';font-weight:600">' + nameCell + youTag + '</td>' +
          '<td style="' + td + ';text-align:right;font-variant-numeric:tabular-nums">' + esc(fmtNum(Number(e.tokens_saved) || 0)) + '</td>' +
          '<td style="' + td + ';text-align:right;font-variant-numeric:tabular-nums;opacity:.85">' + esc(self._fmtUsd(Number(e.cost_avoided_usd) || 0)) + '</td>' +
          '<td style="' + td + ';text-align:right;opacity:.75">' + esc(String(Math.round(Number(e.compression_rate_pct) || 0))) + '%</td>' +
          '</tr>'
        );
      })
      .join('');

    var th = 'padding:6px 8px;font-size:10px;text-transform:uppercase;letter-spacing:.04em;opacity:.55;font-weight:600';
    return (
      '<div style="overflow-x:auto"><table style="width:100%;border-collapse:collapse">' +
      '<thead><tr>' +
      '<th style="' + th + ';text-align:left">#</th>' +
      '<th style="' + th + ';text-align:left">Name</th>' +
      '<th style="' + th + ';text-align:right">Tokens saved</th>' +
      '<th style="' + th + ';text-align:right">Saved</th>' +
      '<th style="' + th + ';text-align:right">Net %</th>' +
      '</tr></thead><tbody>' +
      rows +
      '</tbody></table></div>'
    );
  }

  /** Compact USD: whole-dollar with separators above $100, cents below. */
  _fmtUsd(a) {
    if (!Number.isFinite(a)) return '$0';
    if (a >= 100) return '$' + Math.round(a).toLocaleString('en-US');
    return '$' + a.toFixed(2);
  }

  _renderSubmit(esc) {
    var submitting = this._busy === 'submit';
    var label = submitting ? 'Submitting\u2026' : 'Submit tokens saved';
    return (
      '<div class="card">' +
      '<div class="card-header"><h3>Submit to the leaderboard</h3></div>' +
      '<p class="hs" style="margin:0 0 10px;font-size:12px;opacity:.8">' +
      'Publish your all-time tokens saved to the community board at ' +
      '<code>leanctx.com/metrics</code>. Pick a handle so you\u2019re not listed as ' +
      '\u201Canonymous\u201D.</p>' +
      '<div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">' +
      '<input type="text" id="lbName" maxlength="60" placeholder="your handle (optional)" ' +
      'value="' +
      esc(this._name || '') +
      '" ' +
      (submitting ? 'disabled ' : '') +
      'style="flex:1 1 220px;min-width:180px;padding:8px 10px;border-radius:8px;' +
      'border:1px solid var(--border,#2a2a2a);background:var(--bg-2,#111);color:inherit;font:inherit">' +
      '<button type="button" class="filter-btn active" id="lbSubmit"' +
      (submitting ? ' disabled style="opacity:.5;cursor:not-allowed"' : '') +
      '>' +
      esc(label) +
      '</button>' +
      '</div>' +
      '<p class="hs" style="margin:10px 0 0;font-size:11px;opacity:.7">' +
      '<strong>Shared (aggregate only):</strong> tokens saved, estimated USD, compression rate' +
      (this._name && this._name.trim() ? ', and the handle you chose' : '') +
      '.<br><strong>Never shared:</strong> your code, file contents, paths, repo names, prompts or messages.</p>' +
      this._renderInlineNotice(esc, this._submitNotice) +
      '</div>'
    );
  }

  _renderAuto(esc) {
    var s = this._status || {};
    var on = !!s.auto_submit;
    var busy = this._busy === 'auto';
    var btn = function (val, text) {
      var active = val === on;
      return (
        '<button type="button" class="filter-btn' +
        (active ? ' active' : '') +
        '" data-auto="' +
        (val ? 'on' : 'off') +
        '"' +
        (busy ? ' disabled style="opacity:.5;cursor:not-allowed"' : '') +
        '>' +
        esc(text) +
        '</button>'
      );
    };
    return (
      '<div class="card">' +
      '<div class="card-header"><h3>Auto-submit</h3></div>' +
      '<p class="hs" style="margin:0 0 10px;font-size:12px;opacity:.8">' +
      'Keep your entry fresh automatically: when on, lean-ctx re-submits your ' +
      'recap in the background (at most once a day) so you don\u2019t have to ' +
      'remember to click. Mirrors <code>[gain] auto_publish</code>.</p>' +
      '<div class="filter-row" style="display:flex;gap:6px">' +
      btn(true, 'On') +
      btn(false, 'Off') +
      '</div>' +
      (busy
        ? '<p class="hs" role="status" style="margin:10px 0 0;font-size:12px;opacity:.7">Saving\u2026</p>'
        : this._renderInlineNotice(esc, this._autoNotice)) +
      '</div>'
    );
  }

  // ─── Machine linking (GH #736) ──────────────────────────────────────────────

  async _linkStart() {
    var fetchJson = api();
    if (!fetchJson || this._linkBusy) return;
    this._linkBusy = 'start';
    this._linkNotice = null;
    this._linkCode = null;
    this.render();
    this._bind();
    try {
      var resp = await fetchJson('/api/leaderboard/link/start', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: '{}',
        timeoutMs: 15000,
      });
      this._linkCode = resp && resp.code ? String(resp.code) : null;
      this._linkExpiry = resp && resp.expires_in_secs ? Number(resp.expires_in_secs) : 600;
      if (this._linkCode) {
        this._linkNotice = { kind: 'ok', msg: 'Pairing code generated. Enter it on your other machine within ' + Math.ceil(this._linkExpiry / 60) + ' minutes.' };
      }
    } catch (e) {
      this._linkNotice = { kind: 'err', msg: e && e.error ? String(e.error) : 'Could not generate pairing code.' };
    }
    this._linkBusy = null;
    this.render();
    this._bind();
  }

  async _linkComplete() {
    var fetchJson = api();
    if (!fetchJson || this._linkBusy) return;
    var code = (this._linkInput || '').trim();
    if (!code) {
      this._linkNotice = { kind: 'err', msg: 'Enter the pairing code from your other machine.' };
      this.render();
      this._bind();
      return;
    }
    this._linkBusy = 'complete';
    this._linkNotice = null;
    this.render();
    this._bind();
    try {
      await fetchJson('/api/leaderboard/link/complete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ code: code }),
        timeoutMs: 15000,
      });
      this._linkNotice = { kind: 'ok', msg: 'Linked! Both machines now appear as one leaderboard entry.' };
      this._linkInput = '';
      this._linkCode = null;
    } catch (e) {
      var msg = e && e.error ? String(e.error) : 'Link failed.';
      if (msg.indexOf('invalid or expired') !== -1) {
        msg = 'Code invalid or expired \u2014 generate a fresh one on the other machine.';
      }
      this._linkNotice = { kind: 'err', msg: msg };
    }
    this._linkBusy = null;
    this.render();
    this._bind();
  }

  _renderLink(esc) {
    var s = this._status || {};
    if (!s.published) return '';

    var startBusy = this._linkBusy === 'start';
    var completeBusy = this._linkBusy === 'complete';

    var codeDisplay = '';
    if (this._linkCode) {
      codeDisplay =
        '<div style="margin:12px 0;padding:16px;background:var(--bg-2,#111);' +
        'border:1px solid var(--border,#2a2a2a);border-radius:10px;text-align:center">' +
        '<p class="hs" style="margin:0 0 6px;font-size:11px;opacity:.7;text-transform:uppercase;' +
        'letter-spacing:.05em">Your pairing code</p>' +
        '<p style="margin:0;font-size:28px;font-weight:700;font-family:monospace;' +
        'letter-spacing:.15em;color:var(--green)">' + esc(this._linkCode) + '</p>' +
        '<p class="hs" style="margin:8px 0 0;font-size:11px;opacity:.6">' +
        'Enter this on your other machine within ' +
        Math.ceil((this._linkExpiry || 600) / 60) + ' minutes</p>' +
        '</div>';
    }

    return (
      '<div class="card">' +
      '<div class="card-header"><h3>Link machines</h3></div>' +
      '<p class="hs" style="margin:0 0 12px;font-size:12px;opacity:.8">' +
      'Combine multiple computers into one leaderboard entry. ' +
      'Tokens saved are summed \u2014 no account needed.</p>' +

      '<div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-bottom:8px">' +
      '<button type="button" class="filter-btn" id="lbLinkStart"' +
      (startBusy ? ' disabled style="opacity:.5;cursor:not-allowed"' : '') +
      '>' + (startBusy ? 'Generating\u2026' : 'Generate pairing code') + '</button>' +
      '<span class="hs" style="font-size:12px;opacity:.6">or</span>' +
      '</div>' +

      codeDisplay +

      '<div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">' +
      '<input type="text" id="lbLinkCode" maxlength="16" placeholder="Enter code from other machine" ' +
      'value="' + esc(this._linkInput || '') + '" ' +
      (completeBusy ? 'disabled ' : '') +
      'style="flex:1 1 200px;min-width:160px;padding:8px 10px;border-radius:8px;' +
      'border:1px solid var(--border,#2a2a2a);background:var(--bg-2,#111);' +
      'color:inherit;font:inherit;font-family:monospace;letter-spacing:.08em;text-transform:uppercase">' +
      '<button type="button" class="filter-btn active" id="lbLinkComplete"' +
      (completeBusy ? ' disabled style="opacity:.5;cursor:not-allowed"' : '') +
      '>' + (completeBusy ? 'Linking\u2026' : 'Link') + '</button>' +
      '</div>' +

      this._renderInlineNotice(esc, this._linkNotice) +
      '</div>'
    );
  }

  _renderRecovery(esc) {
    var html = '<div class="card" style="border:1px solid var(--border);border-radius:8px;padding:16px">';
    html += '<h4 style="margin:0 0 10px">\u{1F511} Recovery Phrase</h4>';
    html += '<p class="hs" style="font-size:12px;color:var(--muted);margin:0 0 12px">';
    html += 'Save your recovery phrase to rejoin the leaderboard after a reinstall or on another machine.</p>';

    if (this._phrase) {
      if (this._phraseVisible) {
        html += '<div style="background:var(--bg);border:1px solid var(--accent);border-radius:6px;padding:12px 16px;margin:0 0 10px;font-family:monospace;font-size:16px;letter-spacing:2px;text-align:center">';
        html += esc(this._phrase.toUpperCase());
        html += '</div>';
        html += '<p class="hs" style="font-size:11px;color:var(--muted);margin:0 0 8px">';
        html += 'Rejoin: <code>lean-ctx gain --rejoin ' + esc(this._phrase.toUpperCase()) + '</code></p>';
        html += '<button id="lbHidePhrase" style="font-size:12px;padding:4px 12px;cursor:pointer">Hide</button>';
      } else {
        html += '<button id="lbShowPhrase" style="font-size:12px;padding:6px 14px;cursor:pointer">Show recovery phrase</button>';
      }
    } else if (this._phraseLoaded) {
      html += '<p class="hs" style="font-size:12px;color:var(--muted);margin:0 0 10px">';
      html += 'No recovery phrase stored. Submit to the leaderboard to generate one, ';
      html += 'or enter an existing phrase below to rejoin.</p>';
    }

    html += '<div style="margin-top:12px;border-top:1px solid var(--border);padding-top:12px">';
    html += '<p class="hs" style="font-size:12px;font-weight:600;margin:0 0 8px">Rejoin with existing phrase</p>';
    html += '<div style="display:flex;gap:8px;align-items:center">';
    html += '<input id="lbRejoinInput" type="text" placeholder="WORD1 WORD2 WORD3 WORD4" ';
    html += 'value="' + esc(this._rejoinInput) + '" ';
    html += 'style="flex:1;padding:6px 10px;font-family:monospace;font-size:13px;border:1px solid var(--border);border-radius:4px;background:var(--bg);color:var(--fg)" />';
    html += '<button id="lbRejoinBtn" ' + (this._rejoinBusy ? 'disabled' : '') + ' ';
    html += 'style="padding:6px 14px;cursor:pointer;font-size:12px;white-space:nowrap">';
    html += this._rejoinBusy ? 'Restoring\u2026' : 'Rejoin';
    html += '</button>';
    html += '</div>';
    html += this._renderInlineNotice(esc, this._rejoinNotice);
    html += '</div>';

    html += '</div>';
    return html;
  }

  async _loadPhrase() {
    var fetchJson = api();
    if (!fetchJson) return;
    try {
      var data = await fetchJson('/api/leaderboard/phrase');
      this._phrase = data.phrase || null;
      this._phraseLoaded = true;
      this.render();
    } catch (e) {
      this._phraseLoaded = true;
    }
  }

  async _rejoin() {
    var phrase = this._rejoinInput.trim();
    if (!phrase) return;
    var fetchJson = api();
    if (!fetchJson) return;
    this._rejoinBusy = true;
    this._rejoinNotice = null;
    this.render();
    try {
      var res = await fetchJson('/api/leaderboard/rejoin', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ phrase: phrase })
      });
      this._rejoinBusy = false;
      this._rejoinNotice = {
        kind: 'ok',
        msg: 'Identity restored! Publisher: ' + (res.publisher_id_prefix || '') + '\u2026'
      };
      this._rejoinInput = '';
      await this._loadPhrase();
      this.loadData();
    } catch (e) {
      this._rejoinBusy = false;
      this._rejoinNotice = { kind: 'err', msg: e.message || String(e) };
      this.render();
    }
  }

    _renderFooter(S) {
    if (!S.howItWorks) {
      return (
        '<p class="hs" style="margin-top:14px;font-size:11px;opacity:.7">' +
        'Submitting publishes a signed, login-less card. Remove it anytime with ' +
        '<code>lean-ctx gain --unpublish</code>.</p>' +
        '<p class="hs" style="margin-top:6px;font-size:11px;opacity:.7">' +
        'Multiple machines? Use the \u201CLink machines\u201D card above or run ' +
        '<code>lean-ctx gain --link</code> on each machine to combine them into one entry.</p>' +
        '<p class="hs" style="margin-top:6px;font-size:11px;opacity:.7">' +
        'Reinstalled? Use <code>lean-ctx gain --rejoin WORD1 WORD2 WORD3 WORD4</code> to restore your ' +
        'identity from your recovery phrase. Or use the Recovery Phrase card above.</p>'
      );
    }
    return S.howItWorks(
      'Leaderboard',
      '<strong>Share what you save.</strong> Submit publishes your all-time ' +
        'tokens saved to the community board at <code>leanctx.com/metrics</code> ' +
        'as a signed, login-less card (one per machine — re-submitting refreshes ' +
        'the same card, never duplicates). <strong>Multiple machines?</strong> ' +
        'Use the \u201CLink machines\u201D card or <code>lean-ctx gain --link</code> ' +
        'to combine them into one entry (no account needed).<br><br>' +
        'The payload is a fixed, minimal set of <strong>aggregate numbers</strong> ' +
        '(tokens saved, estimated USD, compression rate) plus the optional handle ' +
        'you choose — enforced by the same whitelist the CLI uses. Your code, file ' +
        'contents, paths, repo names and prompts are <strong>never</strong> sent.<br><br>' +
        '<strong>Auto-submit</strong> flips <code>[gain] auto_publish</code>: when ' +
        'on, the recap is re-submitted in the background at most once a day. Turn it ' +
        'off here or with <code>lean-ctx config set gain.auto_publish false</code>.<br><br>' +
        'Writes go through the authenticated, CSRF-protected ' +
        '<code>/api/leaderboard/*</code> endpoints.'
    );
  }

  /** Format an RFC3339 timestamp as a short local date, falling back to raw. */
  _fmtDate(iso) {
    try {
      var d = new Date(iso);
      if (isNaN(d.getTime())) return iso;
      return d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
    } catch (e) {
      return iso;
    }
  }

  _bind() {
    var self = this;
    var nameEl = this.querySelector('#lbName');
    if (nameEl) {
      nameEl.addEventListener('input', function () {
        self._name = nameEl.value;
      });
    }
    var submitEl = this.querySelector('#lbSubmit');
    if (submitEl && !submitEl.disabled) {
      submitEl.addEventListener('click', function () {
        self._submit();
      });
    }
    this.querySelectorAll('[data-auto]').forEach(function (btn) {
      if (btn.disabled) return;
      btn.addEventListener('click', function () {
        var want = btn.getAttribute('data-auto') === 'on';
        var cur = !!(self._status && self._status.auto_submit);
        if (want === cur) return;
        self._setAuto(want);
      });
    });
    // Link machine bindings
    var linkStartBtn = this.querySelector('#lbLinkStart');
    if (linkStartBtn && !linkStartBtn.disabled) {
      linkStartBtn.addEventListener('click', function () { self._linkStart(); });
    }
    var linkCodeInput = this.querySelector('#lbLinkCode');
    if (linkCodeInput) {
      linkCodeInput.addEventListener('input', function () { self._linkInput = linkCodeInput.value; });
    }
    var linkCompleteBtn = this.querySelector('#lbLinkComplete');
    if (linkCompleteBtn && !linkCompleteBtn.disabled) {
      linkCompleteBtn.addEventListener('click', function () { self._linkComplete(); });
    }
    // Recovery phrase bindings
    var showPhraseBtn = this.querySelector('#lbShowPhrase');
    if (showPhraseBtn) {
      showPhraseBtn.addEventListener('click', function () {
        self._phraseVisible = true;
        self.render();
      });
    }
    var hidePhraseBtn = this.querySelector('#lbHidePhrase');
    if (hidePhraseBtn) {
      hidePhraseBtn.addEventListener('click', function () {
        self._phraseVisible = false;
        self.render();
      });
    }
    var rejoinInput = this.querySelector('#lbRejoinInput');
    if (rejoinInput) {
      rejoinInput.addEventListener('input', function () {
        self._rejoinInput = rejoinInput.value;
      });
    }
    var rejoinBtn = this.querySelector('#lbRejoinBtn');
    if (rejoinBtn && !rejoinBtn.disabled) {
      rejoinBtn.addEventListener('click', function () { self._rejoin(); });
    }
    var S = shared();
    if (S.bindHowItWorks) S.bindHowItWorks(this);
  }
}

customElements.define('cockpit-leaderboard', CockpitLeaderboard);

window.LctxRouter && window.LctxRouter.registerLoader
  ? window.LctxRouter.registerLoader('leaderboard', function () {
      var el = document.querySelector('cockpit-leaderboard');
      if (el && typeof el.loadData === 'function') el.loadData();
    })
  : document.addEventListener('DOMContentLoaded', function () {
      if (window.LctxRouter && window.LctxRouter.registerLoader) {
        window.LctxRouter.registerLoader('leaderboard', function () {
          var el = document.querySelector('cockpit-leaderboard');
          if (el && typeof el.loadData === 'function') el.loadData();
        });
      }
    });

export { CockpitLeaderboard };