lean-ctx 3.9.8

Context Runtime for AI Agents with CCP. 71 MCP tools, 10 read modes, 95+ compression patterns, cross-session memory (CCP), persistent AI knowledge with temporal facts + contradiction detection, multi-agent context sharing, LITM-aware positioning, AAAK compact format, adaptive compression with Thompson Sampling bandits. Supports 24+ AI tools. Reduces LLM token consumption by up to 99%.
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
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>LeanCTX Context Cockpit</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<link rel="stylesheet" href="/static/fonts/fonts.css">
<link rel="stylesheet" href="/static/style.css">
<style>
/* Cockpit shell — works with tokens in style.css */
.cockpit-shell-styles .topbar{
  display:flex;align-items:center;gap:16px;
  padding:12px 24px;
  background:var(--surface);
  border-bottom:1px solid var(--border);
  backdrop-filter:blur(16px);
  -webkit-backdrop-filter:blur(16px);
}
.topbar-breadcrumb{
  display:flex;align-items:center;gap:0;min-width:0;flex-shrink:0;
}
.breadcrumb-row{
  font-size:13px;color:var(--muted);
  display:flex;align-items:center;gap:6px;
}
.breadcrumb-row .bc-root{color:var(--muted);font-weight:400;font-size:13px}
.breadcrumb-row .bc-sep{opacity:0.3;font-size:12px}
.breadcrumb-row .bc-current{color:var(--text-bright);font-weight:600;font-size:14px}
.topbar-center{
  flex:1 1 200px;max-width:480px;margin:0 auto;
}
.global-search-wrap{position:relative;width:100%}
.global-search-wrap kbd{
  position:absolute;right:10px;top:50%;transform:translateY(-50%);
  font-size:9px;font-family:var(--mono);color:var(--muted);
  border:1px solid var(--border);border-radius:4px;padding:2px 6px;pointer-events:none;
  background:var(--surface-2);opacity:0.7;
}
.global-search{
  width:100%;padding:8px 52px 8px 14px;
  background:var(--bg);border:1px solid var(--border);
  border-radius:var(--rs);color:var(--text);font-family:var(--mono);font-size:12px;
  outline:none;transition:all .2s;
}
.global-search:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-dim);background:var(--surface)}
.global-search::placeholder{color:var(--muted);font-size:12px}
.topbar-right-cluster{
  display:flex;align-items:center;gap:8px;flex-shrink:0;
}
.topbar-status{
  display:flex;align-items:center;gap:8px;font-size:11px;color:var(--muted);
  padding:5px 12px;background:var(--bg);border-radius:var(--rs);border:1px solid var(--border);
}
.topbar-status .ts-item{display:flex;align-items:center;gap:5px;white-space:nowrap}
.topbar-status .ts-ascii{font-family:var(--mono);font-size:9px;font-weight:700;flex-shrink:0}
.topbar-status .ts-ascii.on{color:var(--green)}
.topbar-status .ts-ascii.off{color:var(--red)}
.topbar-status .agent-badge{
  font-size:10px;font-weight:600;font-family:var(--mono);
  background:var(--surface-2);color:var(--muted);
  padding:1px 7px;border-radius:4px;border:1px solid var(--border);
}
.topbar-status .session-pill{
  max-width:140px;overflow:hidden;text-overflow:ellipsis;
  font-size:10px;color:var(--text);opacity:0.8;
}
.topbar-status .ts-sep{width:1px;height:14px;background:var(--border);flex-shrink:0}
/* Doctor health signal (#466) — three-level badge + one-click fix popover */
.doctor-signal{position:relative;flex-shrink:0}
.doctor-badge{
  display:flex;align-items:center;gap:6px;cursor:pointer;
  font-size:11px;color:var(--muted);font-family:var(--font);
  padding:6px 10px;background:var(--bg);border-radius:var(--rs);border:1px solid var(--border);
  transition:.15s;
}
.doctor-badge:hover{border-color:var(--border-light);color:var(--text)}
.doctor-badge .doctor-dot{font-family:var(--mono);font-size:9px;font-weight:700;flex-shrink:0;color:var(--muted)}
.doctor-badge.doctor-ok .doctor-dot{color:var(--green)}
.doctor-badge.doctor-warn .doctor-dot{color:var(--yellow)}
.doctor-badge.doctor-crit .doctor-dot{color:var(--red)}
.doctor-badge.doctor-warn{border-color:rgba(251,191,36,0.35)}
.doctor-badge.doctor-crit{border-color:rgba(248,113,113,0.35)}
.doctor-badge-label{font-weight:600}
.doctor-panel{
  position:fixed;top:64px;right:16px;z-index:var(--z-dropdown);
  width:340px;max-width:calc(100vw - 16px);
  background:var(--surface);border:1px solid var(--border-light);border-radius:var(--r);
  box-shadow:var(--shadow-md);padding:12px;font-size:12px;color:var(--text);
}
.doctor-panel-head{
  display:flex;align-items:center;justify-content:space-between;
  padding-bottom:8px;margin-bottom:8px;border-bottom:1px solid var(--border);
}
.doctor-panel-title{font-weight:600;color:var(--text-bright)}
.doctor-panel-score{font-family:var(--mono);font-size:11px;font-weight:700;color:var(--muted)}
.doctor-panel-head.doctor-ok .doctor-panel-score{color:var(--green)}
.doctor-panel-head.doctor-warn .doctor-panel-score{color:var(--yellow)}
.doctor-panel-head.doctor-crit .doctor-panel-score{color:var(--red)}
.doctor-checks{list-style:none;display:flex;flex-direction:column;gap:5px;margin:0;padding:0}
.doctor-check{display:flex;align-items:flex-start;gap:7px;line-height:1.35}
.doctor-check-mark{font-family:var(--mono);font-weight:700;flex-shrink:0}
.doctor-check.ok .doctor-check-mark{color:var(--green)}
.doctor-check.bad .doctor-check-mark{color:var(--red)}
.doctor-check.bad .doctor-check-text{color:var(--text-bright)}
.doctor-warnings{list-style:none;margin:8px 0 0;padding:8px 0 0;display:flex;flex-direction:column;gap:4px;
  border-top:1px solid var(--border);color:var(--yellow);font-size:11px}
.doctor-panel-actions{display:flex;gap:8px;margin-top:12px}
.doctor-fix-btn,.doctor-recheck-btn{
  flex:1;padding:7px 10px;border-radius:var(--rs);cursor:pointer;font-size:11px;font-weight:600;
  border:1px solid var(--border);background:var(--surface-2);color:var(--text);transition:.15s;
}
.doctor-fix-btn{background:var(--accent-dim);border-color:var(--accent);color:var(--accent)}
.doctor-fix-btn:hover:not(:disabled){background:var(--accent);color:var(--bg)}
.doctor-fix-btn:disabled{opacity:.5;cursor:default}
.doctor-recheck-btn:hover{border-color:var(--border-light);color:var(--text-bright)}
.doctor-fix-status{margin-top:8px;font-size:11px;min-height:0;line-height:1.4}
.doctor-fix-status.running{color:var(--muted)}
.doctor-fix-status.ok{color:var(--green)}
.doctor-fix-status.warn{color:var(--yellow)}
.doctor-fix-status.err{color:var(--red)}
.theme-toggle{
  display:flex;align-items:center;justify-content:center;
  width:32px;height:32px;border-radius:var(--rs);border:1px solid var(--border);
  background:var(--bg);color:var(--muted);cursor:pointer;transition:.15s;
}
.theme-toggle:hover{border-color:var(--border-light);color:var(--text)}
.cockpit-status-bar{
  position:fixed;bottom:0;left:var(--sidebar-w);right:0;height:32px;z-index:250;
  display:flex;align-items:center;justify-content:space-between;gap:12px;
  padding:0 16px 0 20px;
  font-size:11px;font-family:var(--mono);color:var(--muted);
  background:var(--surface);border-top:1px solid var(--border);
  box-shadow:0 -2px 12px rgba(0,0,0,0.12);
  transition:left .25s var(--ease-out);
}
.cockpit-status-bar .sb-l,.cockpit-status-bar .sb-c,.cockpit-status-bar .sb-r{
  display:flex;align-items:center;gap:10px;min-width:0;white-space:nowrap;overflow:hidden;
}
.cockpit-status-bar .sb-l{flex:0 0 auto}
.cockpit-status-bar .sb-c{flex:1 1 auto;justify-content:center;text-align:center}
.cockpit-status-bar .sb-r{flex:0 1 auto;justify-content:flex-end}
.cockpit-status-bar .sb-r #sbSession{overflow:hidden;text-overflow:ellipsis;max-width:30vw}
.cockpit-status-bar .sb-strong{color:var(--text-bright);font-weight:600}
.cockpit-status-bar .sb-sep{opacity:0.35}
.toast-host{
  position:fixed;right:16px;bottom:40px;z-index:var(--z-modal);
  display:flex;flex-direction:column;gap:8px;align-items:flex-end;pointer-events:none;
  max-width:min(360px, calc(100vw - 32px));
}
.cockpit-toast{
  pointer-events:auto;
  padding:10px 14px;border-radius:4px;font-size:12px;line-height:1.4;
  border:1px solid var(--border);background:var(--surface);
  color:var(--text);box-shadow:var(--shadow-md);
  opacity:0;transform:translateX(12px);transition:opacity .25s var(--ease-out), transform .25s var(--ease-out);
}
.cockpit-toast.show{opacity:1;transform:translateX(0)}
.cockpit-toast.toast-success{border-color:rgba(52,211,153,0.35);background:var(--green-dim);color:var(--green)}
[data-theme="light"] .cockpit-toast.toast-success{border-color:rgba(5,150,105,0.35)}
.cockpit-toast.toast-error{border-color:rgba(248,113,113,0.35);background:var(--red-dim);color:var(--red)}
[data-theme="light"] .cockpit-toast.toast-error{border-color:rgba(220,38,38,0.35)}
.cockpit-toast.toast-info{border-color:var(--border-light)}
.detail-panel{
  transform:translateX(8px);
  transition:transform .35s var(--ease-out), right .35s var(--ease-out), box-shadow .35s ease;
}
.detail-panel.open{transform:translateX(0)}
@media(max-width:860px){
  .topbar-status{display:none}
  .seg-toggle-label{display:none}
}
@media(max-width:768px){
  .cockpit-status-bar{left:0;padding-left:12px}
  .topbar-center{max-width:100%;order:3;flex-basis:100%}
}
/* Narrow windows: the three status segments no longer fit side by side.
   Drop the center (tokens repeat on Home anyway) so left/right never overlap. */
@media(max-width:620px){
  .cockpit-status-bar .sb-c{display:none}
  .cockpit-status-bar .sb-r #sbSession{display:none}
}
</style>
<script src="/static/vendor/chart.umd.min.js" defer></script>
<script src="/static/vendor/d3.min.js" defer></script>
<script>
(function(){
  if (window.__LEAN_CTX_TOKEN__) {
    try { sessionStorage.setItem('lctx_token', window.__LEAN_CTX_TOKEN__); } catch(e) {}
  } else {
    try { var st = sessionStorage.getItem('lctx_token'); if (st) window.__LEAN_CTX_TOKEN__ = st; } catch(e) {}
  }
  var _origFetch = window.fetch;
  window.fetch = function(url, opts) {
    if (window.__LEAN_CTX_TOKEN__ && typeof url === 'string' && url.startsWith('/api/')) {
      opts = opts || {};
      opts.headers = opts.headers || {};
      opts.headers['Authorization'] = 'Bearer ' + window.__LEAN_CTX_TOKEN__;
    }
    return _origFetch.call(this, url, opts);
  };
  /* Token gate (GL #456): when auth is on and this browser has no (valid)
     token, every card would surface a raw "unauthorized". Instead, the first
     401 raises lctx:unauthorized and we swap the page for one centered token
     prompt. Stored in sessionStorage only; reload re-runs all loaders. */
  window.addEventListener('lctx:unauthorized', function () {
    if (document.getElementById('lctxTokenGate')) return;
    var wrap = document.createElement('div');
    wrap.id = 'lctxTokenGate';
    wrap.setAttribute('role', 'dialog');
    wrap.setAttribute('aria-modal', 'true');
    wrap.setAttribute('aria-label', 'Dashboard token required');
    wrap.style.cssText = 'position:fixed;inset:0;z-index:10000;display:flex;align-items:center;justify-content:center;background:var(--bg,#0d0d12)';
    wrap.innerHTML =
      '<div style="max-width:380px;width:90%;padding:28px;border:1px solid var(--border,#2a2a35);border-radius:12px;background:var(--surface,#16161d);font-family:inherit">' +
      '<h2 style="margin:0 0 8px;font-size:16px;color:var(--text-bright,#fff)">Token required</h2>' +
      '<p style="margin:0 0 16px;font-size:12.5px;line-height:1.55;color:var(--muted,#9a9aa5)">' +
      'This dashboard runs with <code>LEAN_CTX_HTTP_TOKEN</code> auth. Paste the token ' +
      '(or reopen via the <code>?token=\u2026</code> URL printed by <code>lean-ctx dashboard</code>).</p>' +
      '<form id="lctxTokenForm" style="display:flex;gap:8px">' +
      '<input id="lctxTokenInput" type="password" autocomplete="off" spellcheck="false" aria-label="Dashboard token" ' +
      'style="flex:1;padding:8px 10px;border-radius:8px;border:1px solid var(--border,#2a2a35);background:var(--bg,#0d0d12);color:var(--text,#ddd);font-family:monospace;font-size:12px">' +
      '<button type="submit" style="padding:8px 14px;border-radius:8px;border:0;background:var(--accent,#4ade80);color:#08080c;font-weight:600;cursor:pointer">Unlock</button>' +
      '</form>' +
      '<p id="lctxTokenErr" style="margin:10px 0 0;font-size:11.5px;color:var(--red,#f87171);display:none">Token rejected \u2014 please check and try again.</p>' +
      '</div>';
    document.body.appendChild(wrap);
    var input = document.getElementById('lctxTokenInput');
    input.focus();
    document.getElementById('lctxTokenForm').addEventListener('submit', function (ev) {
      ev.preventDefault();
      var tok = input.value.trim();
      if (!tok) return;
      /* Validate before reloading so a wrong token shows feedback instead of looping. */
      _origFetch('/api/health', { headers: { Authorization: 'Bearer ' + tok }, cache: 'no-store' })
        .then(function (r) {
          if (r.status === 401) {
            document.getElementById('lctxTokenErr').style.display = 'block';
            return;
          }
          try { sessionStorage.setItem('lctx_token', tok); } catch (e) {}
          location.reload();
        })
        .catch(function () {
          document.getElementById('lctxTokenErr').style.display = 'block';
        });
    });
  });
})();
</script>
<script src="/static/lib/format.js" defer></script>
<script src="/static/lib/shared.js" defer></script>
<script src="/static/lib/doctor.js" defer></script>
<script type="module" src="/static/lib/api.js"></script>
<script type="module" src="/static/lib/charts.js"></script>
<script type="module" src="/static/lib/router.js"></script>
<script type="module" src="/static/components/cockpit-nav.js"></script>
<script type="module" src="/static/components/cockpit-context.js"></script>
<script type="module" src="/static/components/cockpit-overview.js"></script>
<script type="module" src="/static/components/cockpit-live.js"></script>
<script type="module" src="/static/components/cockpit-knowledge.js"></script>
<script type="module" src="/static/components/cockpit-agents.js"></script>
<script type="module" src="/static/components/cockpit-memory.js"></script>
<script type="module" src="/static/components/cockpit-search.js"></script>
<script type="module" src="/static/components/cockpit-compression.js"></script>
<script src="/static/components/cockpit-tour.js"></script>
<script type="module" src="/static/components/cockpit-graph.js"></script>
<script type="module" src="/static/components/cockpit-architecture.js"></script>
<script type="module" src="/static/components/cockpit-explorer.js"></script>
<script type="module" src="/static/components/cockpit-health.js"></script>
<script type="module" src="/static/components/cockpit-remaining.js"></script>
<script type="module" src="/static/components/cockpit-commander.js"></script>
<script type="module" src="/static/components/cockpit-palette.js"></script>
<script type="module" src="/static/components/cockpit-roi.js"></script>
<script type="module" src="/static/components/cockpit-replay.js"></script>
<script type="module" src="/static/components/cockpit-leaderboard.js"></script>
<script type="module" src="/static/components/cockpit-area-tabs.js"></script>
<script type="module" src="/static/components/cockpit-protection.js"></script>
<script type="module" src="/static/components/cockpit-settings.js"></script>
</head>
<body class="cockpit-shell-styles">
<div class="support-bar" id="supportBar" role="region" aria-label="Support lean-ctx">
  <span class="support-bar-heart" aria-hidden="true">&#9829;</span>
  <span class="support-bar-msg">
    <b>lean-ctx is free &amp; independent.</b>
    <span class="support-bar-sub">Help keep it that way — back development for the price of a coffee.</span>
  </span>
  <a class="support-bar-cta" href="https://leanctx.com/support" target="_blank" rel="noopener noreferrer">Become a supporter &rarr;</a>
  <button type="button" class="support-bar-x" id="supportBarX" aria-label="Dismiss support banner" title="Dismiss">&times;</button>
</div>
<script>
(function(){
  var x=document.getElementById('supportBarX');
  if(!x)return;
  /* Dismiss for the current view only — intentionally NOT persisted, so the
     support nudge reappears every time the dashboard is opened (a fresh page
     load), while still letting a reader clear it out of the way right now. */
  x.addEventListener('click',function(){
    document.documentElement.classList.add('support-bar-off');
  });
  /* Supporter badge (GL #393): if this machine is linked to a paying/supporting
     account, swap the ask for a thank-you. Cosmetic only — errors keep the CTA. */
  try{
    var h={};
    if(window.__LEAN_CTX_TOKEN__)h['Authorization']='Bearer '+window.__LEAN_CTX_TOKEN__;
    fetch('/api/billing-badge',{headers:h}).then(function(r){return r.ok?r.json():null;}).then(function(b){
      if(!b||!b.supporter)return;
      var bar=document.getElementById('supportBar');
      if(!bar)return;
      bar.classList.add('support-bar-thanks');
      var msg=bar.querySelector('.support-bar-msg');
      if(msg)msg.innerHTML='<b>You are a supporter — thank you.</b> <span class="support-bar-sub">Your backing keeps lean-ctx free &amp; independent.</span>';
      var cta=bar.querySelector('.support-bar-cta');
      if(cta){cta.textContent='Supporter \u2665';cta.setAttribute('aria-label','You are a supporter');}
    }).catch(function(){});
  }catch(e){}
})();
</script>
<cockpit-palette></cockpit-palette>
<div class="ascii-global-bg" aria-hidden="true"><pre id="asciiBgPre"></pre></div>
<script>
(function(){
  const art = [
    '                                    \u256D\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256E',
    '                                    \u2502  >>>>>>>>>>>>>>>  ctx_read  >>>>>>>>>>>>  \u2502',
    '         \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510           \u2502  >>>>>>>>>>>>>>>  compress  >>>>>>>>>>>>  \u2502           \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510',
    '         \u2502  100K tokens \u2502 =========>\u2502  >>>  AST  >>>  cache  >>>  signal  >>> \u2502 =========> \u2502  ~5K tok \u2502',
    '         \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518           \u2502  >>>>>>>>>>>>>>>  filter   >>>>>>>>>>>>  \u2502           \u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518',
    '                                    \u2502  >>>>>>>>>>>>>>>  dedupe   >>>>>>>>>>>>  \u2502',
    '        \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557            \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256F           \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557',
    '        \u2551   raw input  \u2551     \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500  lean-ctx  \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500 \u2500            \u2551  output  \u2551',
    '        \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D                                                                   \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D',
    '     \u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504\u2504',
    '       \u250C\u2500\u2500\u2510  \u250C\u2500\u2500\u2510  \u250C\u2500\u2500\u2510  \u250C\u2500\u2500\u2510       \u250C\u2500\u2500\u2510  \u250C\u2500\u2500\u2510  \u250C\u2500\u2500\u2510       \u250C\u2500\u2500\u2510  \u250C\u2500\u2500\u2510  \u250C\u2500\u2500\u2510  \u250C\u2500\u2500\u2510  \u250C\u2500\u2500\u2510  \u250C\u2500\u2500\u2510',
    '       \u2502\u2591\u2591\u2502  \u2502\u2591\u2591\u2502  \u2502\u2591\u2591\u2502  \u2502\u2591\u2591\u2502       \u2502\u2593\u2593\u2502  \u2502\u2593\u2593\u2502  \u2502\u2593\u2593\u2502       \u2502\u2591\u2591\u2502  \u2502\u2591\u2591\u2502  \u2502\u2591\u2591\u2502  \u2502\u2591\u2591\u2502  \u2502\u2591\u2591\u2502  \u2502\u2591\u2591\u2502',
    '       \u2502\u2591\u2591\u2502  \u2502\u2591\u2591\u2502  \u2502\u2591\u2591\u2502  \u2502\u2591\u2591\u2502  \u2500\u2500\u2500> \u2502\u2593\u2593\u2502  \u2502\u2593\u2593\u2502  \u2502\u2593\u2593\u2502  \u2500\u2500\u2500> \u2502\u2591\u2591\u2502  \u2502\u2591\u2591\u2502  \u2502\u2591\u2591\u2502  \u2502\u2591\u2591\u2502  \u2502\u2591\u2591\u2502  \u2502\u2591\u2591\u2502',
    '       \u2514\u2500\u2500\u2518  \u2514\u2500\u2500\u2518  \u2514\u2500\u2500\u2518  \u2514\u2500\u2500\u2518       \u2514\u2500\u2500\u2518  \u2514\u2500\u2500\u2518  \u2514\u2500\u2500\u2518       \u2514\u2500\u2500\u2518  \u2514\u2500\u2500\u2518  \u2514\u2500\u2500\u2518  \u2514\u2500\u2500\u2518  \u2514\u2500\u2500\u2518  \u2514\u2500\u2500\u2518',
    '        file  file  file  file       read  cache  send       tok   tok   tok   tok   tok   tok'
  ];
  const maxLen = Math.max(...art.map(l => l.length));
  const padded = art.map(l => l.padEnd(maxLen));
  const tiled = padded.map(l => l + '  ' + l + '  ' + l).join('\n');
  document.getElementById('asciiBgPre').textContent = Array(5).fill(tiled).join('\n');
})();
</script>
<div class="app-layout">
  <cockpit-nav id="cockpitNav"></cockpit-nav>

  <main class="main" id="mainContent">
    <div class="content-container">
    <div class="topbar" id="topbar">
      <div class="topbar-breadcrumb">
        <div class="breadcrumb-row" aria-label="Breadcrumb">
          <span class="bc-root">Context Cockpit</span>
          <span class="bc-sep">/</span>
          <span class="bc-current" id="breadcrumbCurrent">Overview</span>
        </div>
      </div>
      <div class="topbar-center">
        <div class="global-search-wrap">
          <input type="search" class="global-search" id="globalSearch" placeholder="Search… (Enter for Search Explorer)" autocomplete="off" aria-label="Global search">
          <kbd>⌘K</kbd>
        </div>
      </div>
      <div class="topbar-right-cluster">
        <div class="topbar-status" id="topbarStatus" aria-live="polite">
          <span class="ts-item" id="daemonItemTop" title="lean-ctx daemon: [*] green = connected — reads, search and shell calls are served from the warm in-memory cache. [x] red = offline — the dashboard still works, but tools fall back to slower cold starts and live stats pause. Start it with: lean-ctx serve -d">
            <span class="ts-ascii on" id="daemonDotTop" aria-hidden="true">[*]</span>
            <span id="daemonLabelTop">Daemon</span>
          </span>
          <span class="ts-sep"></span>
          <span class="agent-badge" id="agentCountBadge" title="Active agents">0</span>
        </div>
        <div id="doctorSignal" class="doctor-signal"></div>
        <div class="seg-toggle" id="modeToggle" role="group" aria-label="View detail level">
          <span class="seg-toggle-label" aria-hidden="true">View</span>
          <button type="button" class="seg" data-mode="simple" aria-pressed="true" title="Essential views only">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><rect x="4" y="4" width="16" height="16" rx="3"/></svg>
            <span>Simple</span>
          </button>
          <button type="button" class="seg" data-mode="pro" aria-pressed="false" title="All advanced developer views">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><rect x="3" y="3" width="7.5" height="7.5" rx="1.5"/><rect x="13.5" y="3" width="7.5" height="7.5" rx="1.5"/><rect x="3" y="13.5" width="7.5" height="7.5" rx="1.5"/><rect x="13.5" y="13.5" width="7.5" height="7.5" rx="1.5"/></svg>
            <span>Advanced</span>
          </button>
        </div>
        <button type="button" class="theme-toggle" id="themeToggle" aria-label="Toggle light and dark theme" title="Theme">
          <svg id="themeIconSun" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" style="display:none"><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"/></svg>
          <svg id="themeIconMoon" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"/></svg>
        </button>
        <button class="theme-toggle" id="refreshBtn" type="button" title="Refresh data">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="16" height="16"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0114.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0020.49 15"/></svg>
        </button>
      </div>
    </div>

    <cockpit-area-tabs id="areaTabs" hidden></cockpit-area-tabs>

    <div class="view-hint" id="viewHint" hidden>
      <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.3" aria-hidden="true"><circle cx="8" cy="8" r="6.5"/><line x1="8" y1="7.2" x2="8" y2="11.5"/><circle cx="8" cy="4.7" r="0.6" fill="currentColor"/></svg>
      <span id="viewHintText"></span>
    </div>

    <section id="view-overview" class="view active">
      <cockpit-overview id="overviewView"></cockpit-overview>
    </section>
    <section id="view-commander" class="view">
      <cockpit-commander id="commanderView"></cockpit-commander>
    </section>
    <section id="view-context" class="view">
      <cockpit-context id="contextView"></cockpit-context>
    </section>
    <section id="view-live" class="view">
      <cockpit-live id="liveView"></cockpit-live>
    </section>
    <section id="view-knowledge" class="view">
      <cockpit-knowledge id="knowledgeView"></cockpit-knowledge>
    </section>
    <section id="view-deps" class="view">
      <cockpit-graph id="depsView" data-tab="deps"></cockpit-graph>
    </section>
    <section id="view-compression" class="view">
      <cockpit-compression id="compressionView"></cockpit-compression>
    </section>
    <section id="view-settings" class="view">
      <cockpit-settings id="settingsView"></cockpit-settings>
    </section>
    <section id="view-roi" class="view">
      <cockpit-roi id="roiView"></cockpit-roi>
    </section>
    <section id="view-replay" class="view">
      <cockpit-replay id="replayView"></cockpit-replay>
    </section>
    <section id="view-learning" class="view">
      <cockpit-learning id="learningView"></cockpit-learning>
    </section>
    <section id="view-leaderboard" class="view">
      <cockpit-leaderboard id="leaderboardView"></cockpit-leaderboard>
    </section>
    <section id="view-agents" class="view">
      <cockpit-agents id="agentsView"></cockpit-agents>
    </section>
    <section id="view-memory" class="view">
      <cockpit-memory id="memoryView"></cockpit-memory>
    </section>
    <section id="view-search" class="view">
      <cockpit-search id="searchView"></cockpit-search>
    </section>
    <section id="view-symbols" class="view">
      <cockpit-graph id="symbolsView" data-tab="symbols"></cockpit-graph>
    </section>
    <section id="view-callgraph" class="view">
      <cockpit-graph id="callgraphView" data-tab="callgraph"></cockpit-graph>
    </section>
    <section id="view-routes" class="view">
      <cockpit-routes id="routesView"></cockpit-routes>
    </section>
    <section id="view-architecture" class="view">
      <cockpit-architecture id="architectureView"></cockpit-architecture>
    </section>
    <section id="view-explorer" class="view">
      <cockpit-explorer id="explorerView"></cockpit-explorer>
    </section>
    <section id="view-health" class="view">
      <cockpit-health id="healthView"></cockpit-health>
    </section>
    <section id="view-protection" class="view">
      <cockpit-protection id="protectionView"></cockpit-protection>
    </section>
    </div>
  </main>
</div>

<footer class="cockpit-status-bar" id="cockpitStatusBar" role="status" aria-live="polite">
  <div class="sb-l" id="sbDaemonItem"
       title="Connection between this dashboard and the lean-ctx engine on your machine. [*] green = live; [x] red = engine unreachable (data frozen until it reconnects). Start with: lean-ctx serve -d">

    <span class="ts-ascii on" id="daemonDotBar" aria-hidden="true">[*]</span>
    <span id="sbDaemonText">Connected</span>
    <span class="sb-sep">·</span>
    <span id="sbVersion">v---</span>
  </div>
  <div class="sb-c" title="Your receipt: estimated tokens saved all-time — same figure as the Home hero. The strictly verified, Ed25519-signed count lives in Proof → ROI & Plan.">
    <span>Tokens saved</span>
    <span class="sb-strong" id="sbTokensSaved">—</span>
  </div>
  <div class="sb-r">
    <span id="sbCompression" title="Share of estimated input tokens removed before sending, all-time.">Compression —</span>
    <span class="sb-sep">·</span>
    <span id="sbSession" title="The task your most recent agent session is working on.">No session</span>
  </div>
</footer>

<div class="toast-host" id="toastHost" aria-live="polite" aria-relevant="additions"></div>

<div class="onboard-overlay" id="onboardOverlay" hidden>
  <div class="onboard-card" role="dialog" aria-modal="true" aria-labelledby="onboardTitle">
    <div class="onboard-logo"><span>&lt;|&gt;</span> Lean<b>CTX</b></div>
    <h2 class="onboard-title" id="onboardTitle">Welcome to your cockpit</h2>
    <p class="onboard-sub">lean-ctx does four jobs for your AI agents — token savings are the receipt:</p>
    <div class="onboard-stats" id="onboardStats"></div>
    <ul class="onboard-points">
      <li><b>Home</b> shows your receipt — that's all most people need.</li>
      <li><b>Context</b> decides what agents read, <b>Memory</b> remembers what they learn, <b>Protection</b> guards what they touch, <b>Proof</b> signs what you save — flip <b>Simple → Advanced</b> for one tabbed page per job.</li>
      <li>The <b>Project Map</b> shows what lean-ctx understands about your codebase.</li>
      <li>Hover any <span class="onboard-i">i</span> for a plain-language explanation.</li>
    </ul>
    <button type="button" class="onboard-btn" id="onboardBtn">Got it — show me</button>
  </div>
</div>

<div class="detail-panel" id="detailPanel">
  <button type="button" class="detail-panel-close" id="detailPanelClose" aria-label="Close panel">&times;</button>
  <h3 class="detail-panel-title" id="detailPanelTitle"></h3>
  <div id="detailPanelBody"></div>
</div>

<script type="module">
function bootCockpit() {
  var THEME_KEY = 'lctx_theme';

  function getStoredTheme() {
    try { return localStorage.getItem(THEME_KEY); } catch (e) { return null; }
  }

  function systemPrefersLight() {
    return window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches;
  }

  function resolveTheme() {
    var s = getStoredTheme();
    if (s === 'light' || s === 'dark') return s;
    return systemPrefersLight() ? 'light' : 'dark';
  }

  function applyTheme(theme) {
    document.documentElement.setAttribute('data-theme', theme);
    var sun = document.getElementById('themeIconSun');
    var moon = document.getElementById('themeIconMoon');
    var btn = document.getElementById('themeToggle');
    if (theme === 'light') {
      if (sun) sun.style.display = '';
      if (moon) moon.style.display = 'none';
      if (btn) btn.setAttribute('title', 'Switch to dark theme');
    } else {
      if (sun) sun.style.display = 'none';
      if (moon) moon.style.display = '';
      if (btn) btn.setAttribute('title', 'Switch to light theme');
    }
  }

  applyTheme(resolveTheme());

  try {
    window.matchMedia('(prefers-color-scheme: light)').addEventListener('change', function () {
      if (getStoredTheme()) return;
      applyTheme(resolveTheme());
    });
  } catch (e) {}

  var themeToggle = document.getElementById('themeToggle');
  if (themeToggle) {
    themeToggle.addEventListener('click', function () {
      var cur = document.documentElement.getAttribute('data-theme') || resolveTheme();
      var next = cur === 'light' ? 'dark' : 'light';
      try { localStorage.setItem(THEME_KEY, next); } catch (e) {}
      applyTheme(next);
    });
  }

  // Sync CLI theme tokens to CSS custom properties
  fetch('/api/theme-tokens')
    .then(function (r) { return r.ok ? r.json() : null; })
    .then(function (data) {
      if (!data || !data.tokens) return;
      var t = data.tokens;
      var root = document.documentElement.style;
      root.setProperty('--lctx-primary', t.primary);
      root.setProperty('--lctx-secondary', t.secondary);
      root.setProperty('--lctx-accent', t.accent);
      root.setProperty('--lctx-success', t.success);
      root.setProperty('--lctx-warning', t.warning);
      root.setProperty('--lctx-danger', t.danger);
      root.setProperty('--lctx-muted', t.muted);
      root.setProperty('--lctx-text', t.text);
      root.setProperty('--lctx-surface', t.surface);
      root.setProperty('--lctx-background', t.background);
      root.setProperty('--lctx-bar-start', t.barStart);
      root.setProperty('--lctx-bar-end', t.barEnd);
      root.setProperty('--lctx-border', t.border);
    })
    .catch(function () {});

  var nav = document.getElementById('cockpitNav');
  if (nav) {
    nav.addEventListener('navigate', function (e) {
      if (window.LctxRouter && e.detail && e.detail.viewId) {
        window.LctxRouter.navigateTo(e.detail.viewId);
      }
    });
  }

  function escTitle(s) {
    if (window.LctxFmt && typeof window.LctxFmt.esc === 'function') return window.LctxFmt.esc(String(s));
    var d = document.createElement('div');
    d.textContent = s;
    return d.innerHTML;
  }

  window.showDetail = function (title, html) {
    var panel = document.getElementById('detailPanel');
    var ht = document.getElementById('detailPanelTitle');
    var body = document.getElementById('detailPanelBody');
    if (ht) ht.innerHTML = escTitle(title || '');
    if (body) body.innerHTML = html || '';
    if (panel) panel.classList.add('open');
  };

  window.closeDetail = function () {
    var panel = document.getElementById('detailPanel');
    if (panel) panel.classList.remove('open');
  };

  window.showToast = function (message, type) {
    var host = document.getElementById('toastHost');
    if (!host) return;
    var t = document.createElement('div');
    t.className = 'cockpit-toast toast-' + String(type || 'info');
    t.textContent = String(message || '');
    host.appendChild(t);
    requestAnimationFrame(function () { t.classList.add('show'); });
    setTimeout(function () {
      t.classList.remove('show');
      setTimeout(function () { if (t.parentNode) t.parentNode.removeChild(t); }, 280);
    }, 3000);
  };

  var closeBtn = document.getElementById('detailPanelClose');
  if (closeBtn) closeBtn.addEventListener('click', window.closeDetail);

  document.addEventListener('lctx:view', function (e) {
    var label = e.detail && e.detail.label;
    var desc = e.detail && e.detail.desc;
    var areaLabel = e.detail && e.detail.areaLabel;
    var el = document.getElementById('breadcrumbCurrent');
    // Inside an area page the breadcrumb shows "Area / Tab" (GL #487).
    if (el && label) el.textContent = areaLabel ? areaLabel + ' / ' + label : label;
    var hint = document.getElementById('viewHint');
    var hintText = document.getElementById('viewHintText');
    if (hint && hintText) {
      if (desc) {
        hintText.textContent = desc;
        hint.hidden = false;
      } else {
        hint.hidden = true;
      }
    }
  });

  // Simple ⇄ Advanced navigation mode (persisted; drives cockpit-nav).
  // Four-jobs IA (GL #486): Simple is the 5-second answer — Home only.
  var NAV_MODE_KEY = 'lctx_nav_mode';
  var SIMPLE_VIEWS = { overview: 1 };
  function getNavMode() {
    try { return localStorage.getItem(NAV_MODE_KEY) === 'pro' ? 'pro' : 'simple'; } catch (e) { return 'simple'; }
  }
  function applyNavMode(mode) {
    var segs = document.querySelectorAll('#modeToggle .seg');
    for (var i = 0; i < segs.length; i++) {
      var on = segs[i].getAttribute('data-mode') === mode;
      segs[i].setAttribute('aria-pressed', on ? 'true' : 'false');
    }
    document.dispatchEvent(new CustomEvent('lctx:navmode', { detail: { mode: mode } }));
  }
  function setNavMode(next) {
    try { localStorage.setItem(NAV_MODE_KEY, next); } catch (e) {}
    applyNavMode(next);
    if (next === 'simple' && window.LctxRouter) {
      var cur = window.LctxRouter.getActiveViewId();
      if (!SIMPLE_VIEWS[cur]) window.LctxRouter.navigateTo('overview');
    }
  }
  applyNavMode(getNavMode());
  var segButtons = document.querySelectorAll('#modeToggle .seg');
  for (var si = 0; si < segButtons.length; si++) {
    segButtons[si].addEventListener('click', function () {
      setNavMode(this.getAttribute('data-mode'));
    });
  }

  var globalSearch = document.getElementById('globalSearch');
  var searchKbd = document.querySelector('.global-search-wrap kbd');
  if (searchKbd) {
    searchKbd.textContent =
      typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/i.test(navigator.platform || '')
        ? '⌘K'
        : 'Ctrl+K';
  }
  if (globalSearch) {
    globalSearch.addEventListener('keydown', function (e) {
      if (e.key === 'Enter') {
        e.preventDefault();
        var q = globalSearch.value.trim();
        try { sessionStorage.setItem('lctx_search_query', q); } catch (err) {}
        document.dispatchEvent(new CustomEvent('lctx:search-submit', { detail: { query: q } }));
        if (window.LctxRouter) window.LctxRouter.navigateTo('search');
      }
    });
  }

  document.addEventListener('keydown', function (e) {
    var isK = e.key === 'k' || e.key === 'K';
    if ((e.metaKey || e.ctrlKey) && isK) {
      var gs = document.getElementById('globalSearch');
      if (gs) {
        e.preventDefault();
        gs.focus();
        gs.select();
      }
    }
  });

  var pulseHash = null;
  var daemonUp = false;

  function setDaemonConnected(up) {
    daemonUp = !!up;
    var dotTop = document.getElementById('daemonDotTop');
    var dotBar = document.getElementById('daemonDotBar');
    var lblTop = document.getElementById('daemonLabelTop');
    var sbTxt = document.getElementById('sbDaemonText');
    [dotTop, dotBar].forEach(function (d) {
      if (!d) return;
      d.classList.toggle('on', daemonUp);
      d.classList.toggle('off', !daemonUp);
      d.textContent = daemonUp ? '[*]' : '[x]';
    });
    if (lblTop) lblTop.textContent = daemonUp ? 'Daemon' : 'Offline';
    if (sbTxt) sbTxt.textContent = daemonUp ? 'Connected' : 'Offline';
    /* State-aware tooltip (GL #478): explain what the indicator means and how
       to recover, instead of a bare "Daemon" title. */
    var tipText = daemonUp
      ? 'lean-ctx daemon connected: reads, search and shell calls are served from the warm in-memory cache; stats update live.'
      : 'lean-ctx daemon offline: the dashboard keeps working, but tools fall back to slower cold starts and live stats pause. Start it with: lean-ctx serve -d';
    var itemTop = document.getElementById('daemonItemTop');
    var itemBar = document.getElementById('sbDaemonItem');
    if (itemTop) itemTop.title = tipText;
    if (itemBar) itemBar.title = tipText;
  }

  function formatTok(n) {
    if (window.LctxFmt && typeof window.LctxFmt.ff === 'function') return window.LctxFmt.ff(n);
    return String(n);
  }

  function applyStatsToStatusBar(stats) {
    var sbTok = document.getElementById('sbTokensSaved');
    var sbComp = document.getElementById('sbCompression');
    if (!stats) {
      if (sbTok) sbTok.textContent = '—';
      if (sbComp) sbComp.textContent = 'Compression —';
      return;
    }
    var inp = Number(stats.total_input_tokens || 0);
    var out = Number(stats.total_output_tokens || 0);
    var saved = Math.max(0, inp - out);
    var pct = inp > 0 ? Math.round(Math.min(100, (saved / inp) * 100)) : 0;
    if (sbTok) sbTok.textContent = formatTok(saved);
    if (sbComp) sbComp.textContent = 'Compression ' + pct + '%';
  }

  function applyAgentsToTop(agentsPayload) {
    var badge = document.getElementById('agentCountBadge');
    var n = agentsPayload && typeof agentsPayload.total_active === 'number' ? agentsPayload.total_active : 0;
    if (badge) {
      // A bare number next to "Daemon" reads as noise — say what it counts.
      badge.textContent = n === 1 ? '1 agent' : n + ' agents';
      badge.title = (n === 1 ? '1 AI agent is' : n + ' AI agents are') + ' currently connected through lean-ctx';
    }
  }

  function hasMeaningfulSession(sess) {
    if (!sess) return false;
    if (sess.task && sess.task.description) return true;
    if (sess.files_touched && sess.files_touched.length) return true;
    if (sess.findings && sess.findings.length) return true;
    return false;
  }

  function sessionTopSummary(sess) {
    if (!hasMeaningfulSession(sess)) return '—';
    var t = sess.task && sess.task.description ? String(sess.task.description) : '';
    if (t) return t.length > 48 ? t.slice(0, 45) + '…' : t;
    var root = sess.project_root || sess.shell_cwd || '';
    if (root) {
      var parts = root.replace(/\/$/, '').split('/');
      var leaf = parts[parts.length - 1] || root;
      return leaf.length > 48 ? leaf.slice(0, 45) + '…' : leaf;
    }
    return 'Session';
  }

  function sessionBarLabel(sess) {
    if (!hasMeaningfulSession(sess)) return 'No session';
    var t = sessionTopSummary(sess);
    return t === '—' ? 'No session' : 'Active · ' + t;
  }

  function applySessionUI(sess) {
    var sb = document.getElementById('sbSession');
    if (sb) sb.textContent = sessionBarLabel(sess);
  }

  window.checkPulse = async function checkPulse() {
    var refreshBtn = document.getElementById('refreshBtn');
    try {
      var res = await fetch('/api/pulse', { cache: 'no-store' });
      if (!res.ok) throw new Error('pulse http');
      var data = await res.json();
      setDaemonConnected(true);
      if (pulseHash !== null && data.hash !== pulseHash) {
        // Content changed since the last pulse. When the tab is visible, refresh
        // the active view's data in place (#425) so live stats update on their
        // own — previously the poll only flagged the manual button, so panels
        // stayed static until a reload. When hidden, just flag the button; the
        // visibilitychange handler catches up the moment the tab is focused.
        if (document.visibilityState === 'visible') {
          document.dispatchEvent(new CustomEvent('lctx:refresh'));
          if (refreshBtn) refreshBtn.classList.remove('has-update');
        } else if (refreshBtn) {
          refreshBtn.classList.add('has-update');
        }
      }
      pulseHash = data.hash;
    } catch (e) {
      setDaemonConnected(false);
    }
  };

  async function refreshMetrics() {
    var stats = null;
    var agents = null;
    var sess = null;
    var cached = window.LctxApi && window.LctxApi.cachedFetch ? window.LctxApi.cachedFetch : null;
    try {
      stats = cached
        ? await cached('/api/stats', { timeoutMs: 5000 })
        : await fetch('/api/stats', { cache: 'no-store' }).then(function (r) { return r.ok ? r.json() : null; });
    } catch (e) { stats = null; }
    try {
      agents = await fetch('/api/agents', { cache: 'no-store' }).then(function (r) { return r.ok ? r.json() : null; });
    } catch (e) { agents = null; }
    try {
      sess = cached
        ? await cached('/api/session', { timeoutMs: 5000 })
        : await fetch('/api/session', { cache: 'no-store' }).then(function (r) { return r.ok ? r.json() : null; });
    } catch (e) { sess = null; }

    if (!daemonUp) {
      /* keep last stats if pulse failed; do not pretend zeros are fresh */
    }
    applyStatsToStatusBar(stats);
    applyAgentsToTop(agents || {});
    applySessionUI(sess);

    if (stats) document.dispatchEvent(new CustomEvent('lctx:stats-data', { detail: stats }));
    if (sess) document.dispatchEvent(new CustomEvent('lctx:session-data', { detail: sess }));
  }

  async function pollCockpit() {
    await window.checkPulse();
    if (daemonUp) await refreshMetrics();
    else {
      applyStatsToStatusBar(null);
      applyAgentsToTop({});
      applySessionUI(null);
    }
  }

  var refreshBtn = document.getElementById('refreshBtn');
  if (refreshBtn) {
    refreshBtn.addEventListener('click', function () {
      refreshBtn.classList.add('spinning');
      refreshBtn.classList.remove('has-update');
      setTimeout(function () { refreshBtn.classList.remove('spinning'); }, 600);
      document.dispatchEvent(new CustomEvent('lctx:refresh'));
      pollCockpit();
      if (window.LctxRouter && window.LctxRouter.getActiveViewId) {
        window.LctxRouter.navigateTo(window.LctxRouter.getActiveViewId());
      }
    });
  }

  function syncVersionBadge(ver) {
    var sbVer = document.getElementById('sbVersion');
    var t = ver || 'v---';
    if (sbVer) sbVer.textContent = t;
    if (nav && typeof nav.setVersion === 'function') nav.setVersion(t);
  }
  fetch('/api/version', { cache: 'no-store' }).then(function (r) { return r.ok ? r.json() : null; }).then(function (j) {
    var ver = j && (j.version || j.current);
    if (ver) syncVersionBadge('v' + ver);
  }).catch(function () {});

  pollCockpit();
  setInterval(pollCockpit, 10000);

  // Auto-refresh the active view the moment the tab regains focus, so returning
  // to the dashboard never shows stale data (#425). Browsers throttle the 10s
  // poll while hidden; this guarantees an immediate catch-up on return.
  document.addEventListener('visibilitychange', function () {
    if (document.visibilityState !== 'visible') return;
    var rb = document.getElementById('refreshBtn');
    if (rb) rb.classList.remove('has-update');
    document.dispatchEvent(new CustomEvent('lctx:refresh'));
    pollCockpit();
  });

  if (window.LctxRouter && window.LctxRouter.init) window.LctxRouter.init();

  maybeShowOnboarding();

  function onboardStatCard(value, label) {
    return '<div class="onboard-stat"><div class="onboard-stat-v">' + value +
      '</div><div class="onboard-stat-l">' + label + '</div></div>';
  }

  function maybeShowOnboarding() {
    var seen = false;
    try { seen = localStorage.getItem('lctx_onboarded') === '1'; } catch (e) {}
    if (seen) return;
    var overlay = document.getElementById('onboardOverlay');
    if (!overlay) return;
    overlay.hidden = false;
    requestAnimationFrame(function () { overlay.classList.add('show'); });

    fetch('/api/stats', { cache: 'no-store' })
      .then(function (r) { return r.ok ? r.json() : null; })
      .then(function (s) {
        var host = document.getElementById('onboardStats');
        if (!host || !s) return;
        var inp = Number(s.total_input_tokens || 0);
        var out = Number(s.total_output_tokens || 0);
        var saved = Math.max(0, inp - out);
        var pct = inp > 0 ? Math.round(Math.min(100, (saved / inp) * 100)) : 0;
        host.innerHTML =
          onboardStatCard(formatTok(saved), 'tokens saved') +
          onboardStatCard(pct + '%', 'compression');
      })
      .catch(function () {});

    var btn = document.getElementById('onboardBtn');
    function dismiss() {
      try { localStorage.setItem('lctx_onboarded', '1'); } catch (e) {}
      overlay.classList.remove('show');
      setTimeout(function () { overlay.hidden = true; }, 300);
    }
    if (btn) btn.addEventListener('click', dismiss);
    overlay.addEventListener('click', function (e) { if (e.target === overlay) dismiss(); });
  }
}
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', bootCockpit);
} else {
  bootCockpit();
}
</script>
</body>
</html>