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
/**
 * Context Commander — action-oriented triage view for context management.
 * Progressive UX: simple default, power mode on-demand.
 */

function api() {
  return window.LctxApi && window.LctxApi.apiFetch ? window.LctxApi.apiFetch : null;
}
function fmtLib() { return window.LctxFmt || {}; }
function tip(k) { return window.LctxShared && window.LctxShared.tip ? window.LctxShared.tip(k) : ''; }
function sparklineSvg(values, w, h) {
  return window.LctxShared && window.LctxShared.sparklineSvg
    ? window.LctxShared.sparklineSvg(values, w, h) : '';
}

const BAND_CONFIG = {
  green:  { label: 'Optimal',  icon: '\u2713', cls: 'band-green',  desc: 'No action needed' },
  yellow: { label: 'Moderate', icon: '\u25b2', cls: 'band-yellow', desc: 'Consider compressed reads for new files' },
  orange: { label: 'High',     icon: '\u26a0', cls: 'band-orange', desc: 'Review top eviction candidates' },
  red:    { label: 'Critical', icon: '\u2718', cls: 'band-red',    desc: 'Compact or create handoff pack' },
};

const esc = s => String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');

function fmtTok(n) {
  if (n == null) return '0';
  if (n >= 1e6) return (n / 1e6).toFixed(1) + 'M';
  if (n >= 1000) return (n / 1000).toFixed(1) + 'k';
  return String(Math.round(n));
}

function shortenPath(p) {
  if (!p) return '';
  const parts = p.replace(/\\/g, '/').split('/');
  if (parts.length <= 3) return parts.join('/');
  return '\u2026/' + parts.slice(-3).join('/');
}

function timeAgo(ts) {
  if (!ts) return '\u2014';
  const secs = Math.floor(Date.now() / 1000) - ts;
  if (secs < 60) return 'just now';
  if (secs < 3600) return Math.floor(secs / 60) + 'm ago';
  if (secs < 86400) return Math.floor(secs / 3600) + 'h ago';
  return Math.floor(secs / 86400) + 'd ago';
}

function toast(msg, kind) {
  if (typeof window.showToast === 'function') window.showToast(msg, kind);
}

class CockpitCommander extends HTMLElement {
  constructor() {
    super();
    this._data = null;
    this._risk = null;
    this._loading = true;
    this._error = null;
    this._powerMode = false;
    this._sortKey = 'eviction_score';
    this._sortDir = 'desc';
    this._modeFilter = 'all';
    this._expandedTrails = new Set();
  }

  connectedCallback() {
    if (this._ready) return;
    this._ready = true;
    this._onRefresh = this._onRefresh || (() => {
      const v = document.getElementById('view-commander');
      if (v && v.classList.contains('active')) this.loadData();
    });
    document.addEventListener('lctx:refresh', this._onRefresh);
    // Lazy-load (#452): the router loads this view's data on activation.
  }

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

  async loadData() {
    const fetchJson = api();
    if (!fetchJson) { this._error = 'API not loaded'; this._loading = false; this.render(); return; }
    this._loading = true;
    this._error = null;
    this.render();

    const [triage, risk, signals] = await Promise.all([
      fetchJson('/api/context-triage', { timeoutMs: 12000 }).catch(e => ({ __error: String(e?.error || e) })),
      fetchJson('/api/context-risk', { timeoutMs: 12000 }).catch(e => ({ __error: String(e?.error || e) })),
      fetchJson('/api/signals', { timeoutMs: 12000 }).catch(e => ({ __error: String(e?.error || e) })),
    ]);

    if (triage?.__error) this._error = triage.__error;
    this._data = triage?.__error ? null : triage;
    this._risk = risk?.__error ? null : risk;
    this._signals = signals?.__error ? null : signals;
    this._loading = false;
    this.render();
  }

  render() {
    if (this._loading) {
      this.innerHTML = '<div class="loading-pulse" style="padding:40px;text-align:center">Loading triage data\u2026</div>';
      return;
    }
    if (this._error || !this._data) {
      this.innerHTML = '<div class="card" style="padding:20px;color:var(--red)">\u26a0 ' + esc(this._error || 'No data') + '</div>';
      return;
    }

    let h = '';
    h += this._renderBudgetHero();
    h += this._renderLiveSignals();
    h += this._renderActionCards();
    h += this._renderRiskAlerts();
    h += this._renderPressureTable();
    // Sibling view: Triage says what to do, Contents shows what is loaded.
    h += '<p class="hs" style="margin-top:4px;color:var(--muted)">Want the full inventory? ' +
      '<a href="#context/contents" style="color:var(--accent)">Context Contents \u2192</a></p>';
    this.innerHTML = h;
    this._bind();
  }

  // === BUDGET HERO ===

  _renderBudgetHero() {
    const b = this._data.budget;
    const s = this._data.summary;
    const band = BAND_CONFIG[b.band] || BAND_CONFIG.green;
    const pct = Math.round((b.utilization || 0) * 100);

    let h = '<div class="cmdr-budget-hero ' + band.cls + '">';

    h += '<div class="cmdr-gauge-wrap">';
    h += '<div class="cmdr-gauge-ring">';
    h += '<svg viewBox="0 0 36 36" width="120" height="120">';
    h += '<circle class="cmdr-gauge-bg" cx="18" cy="18" r="15.91549430918954" />';
    const dashLen = Math.min(100, pct);
    const gap = 100 - dashLen;
    h += '<circle class="cmdr-gauge-fg" cx="18" cy="18" r="15.91549430918954" stroke-dasharray="' + dashLen + ' ' + gap + '" stroke-dashoffset="' + gap + '" />';
    h += '</svg>';
    h += '<div class="cmdr-gauge-label">' + pct + '%</div>';
    h += '</div>';

    h += '<div class="cmdr-gauge-info">';
    h += '<div class="cmdr-band-badge" title="Health bands: \u2713 Optimal (<50% used) \u00b7 \u25b2 Moderate (50\u201375%) \u00b7 \u26a0 High (75\u201390%) \u00b7 \u2718 Critical (>90%)">' +
      band.icon + ' ' + esc(band.label) + '</div>';
    h += '<div class="cmdr-band-desc">' + esc(b.recommendation) + '</div>';
    h += '<div class="cmdr-band-desc" style="opacity:.7;font-size:11px">Live value \u2014 changes as your agents read and write context.</div>';
    h += '</div>';
    h += '</div>';

    h += '<div class="cmdr-stats-row">';
    h += this._statCell('Files', s.total_files, '', '');
    h += this._statCell('Tokens Used', fmtTok(s.total_tokens_sent), fmtTok(b.window_size) + ' window', '');
    h += this._statCell('Tokens Saved', fmtTok(s.total_tokens_saved), '', 'var(--green)');
    h += this._statCell('Remaining', fmtTok(b.remaining_tokens), '', b.band === 'red' ? 'var(--red)' : '');
    h += this._statCell('Pinned', String(s.pinned_count), '', '');
    h += this._statCell('At Risk', String(s.risk_count), '', s.risk_count > 0 ? 'var(--yellow)' : '');
    h += '</div>';

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

  _statCell(label, value, sub, color) {
    let c = '<div class="cmdr-stat-cell">';
    c += '<div class="cmdr-stat-label">' + label + '</div>';
    c += '<div class="cmdr-stat-value"' + (color ? ' style="color:' + color + '"' : '') + '>' + esc(value) + '</div>';
    if (sub) c += '<div class="cmdr-stat-sub">' + esc(sub) + '</div>';
    return c + '</div>';
  }

  // === LIVE SIGNALS (#505/#507) ===

  /**
   * What the closed-loop signal stores know right now: editor focus, build
   * diagnostics, git working set, bounce memory, auto-mode decision sources,
   * plus the bounce-rate learning trend. Honest empty states — a tile says
   * "no signal" rather than pretending a zero is knowledge.
   */
  _renderLiveSignals() {
    const sig = this._signals;
    if (!sig) return '';

    const tile = (icon, label, value, detail, tone) => {
      const color = tone === 'on' ? 'var(--accent)' : tone === 'warn' ? 'var(--red)' : 'var(--muted)';
      return '<div class="cmdr-stat-cell" style="min-width:130px"' + (detail ? ' title="' + esc(detail) + '"' : '') + '>' +
        '<div class="cmdr-stat-label">' + icon + ' ' + esc(label) + '</div>' +
        '<div class="cmdr-stat-value" style="font-size:14px;color:' + color + '">' + value + '</div>' +
        '</div>';
    };

    let tiles = '';

    const ed = sig.editor || {};
    if (ed.active_file && ed.fresh) {
      const base = String(ed.active_file).split('/').pop();
      tiles += tile('\ud83d\udc41', 'Editor focus', esc(base),
        ed.active_file + ' \u2014 ranked up while you look at it', 'on');
    } else if (ed.active_file) {
      tiles += tile('\ud83d\udc41', 'Editor focus', 'stale',
        'Last focus signal is older than 2 min \u2014 not steering ranking. Needs the VS Code extension.', 'off');
    } else {
      tiles += tile('\ud83d\udc41', 'Editor focus', 'no signal',
        'Sent by the lean-ctx VS Code extension on tab change (path only, never content).', 'off');
    }

    const dg = sig.diagnostics || {};
    if (dg.errors > 0) {
      tiles += tile('\u2716', 'Build errors', dg.errors + ' active',
        'Files with active compiler/linter errors: ' + (dg.files || []).join(', ') + ' \u2014 forced to full reads + ranked up.', 'warn');
    } else {
      tiles += tile('\u2713', 'Build errors', 'none',
        'Failing cargo/tsc/eslint runs mark their files as context priority; passing runs clear them.', 'off');
    }

    const git = sig.git || {};
    tiles += tile('\u25cf', 'Git working set',
      git.uncommitted > 0 ? git.uncommitted + ' uncommitted' : 'clean',
      'Uncommitted files are the active task \u2014 they rank up and resist eviction.',
      git.uncommitted > 0 ? 'on' : 'off');

    const bm = sig.bounce_memory || {};
    tiles += tile('\u21ba', 'Bounce memory',
      bm.tracked_paths > 0
        ? bm.tracked_paths + ' tracked' + (bm.forced_full_paths > 0 ? ' \u00b7 ' + bm.forced_full_paths + ' forced full' : '')
        : 'empty',
      'Files where compressed reads kept getting re-read in full. After 2+ bounces auto-mode stops compressing them.',
      bm.forced_full_paths > 0 ? 'on' : 'off');

    const srcs = sig.auto_mode_sources || [];
    const learnedSrcs = srcs.filter((s) =>
      s[0] === 'path_bounce_memory' || s[0] === 'heatmap_conservative' || s[0] === 'active_diagnostic');
    if (learnedSrcs.length > 0) {
      const top = learnedSrcs.map((s) => s[0].replace(/_/g, ' ') + ' \u00d7' + s[1]).join(' \u00b7 ');
      tiles += tile('\u2699', 'Learned decisions', esc(top),
        'How often the learning loops (not static heuristics) decided the read mode, cumulative.', 'on');
    } else {
      tiles += tile('\u2699', 'Learned decisions', 'none yet',
        'Counts how often bounce memory, heatmap or diagnostics override the default mode choice.', 'off');
    }

    let trend = '';
    const bt = sig.bounce_trend || [];
    if (bt.length >= 2) {
      const rates = bt.map((d) => {
        const reads = Math.max(1, d[2]);
        return Math.min(1, d[1] / reads);
      });
      const spark = sparklineSvg(rates, 120, 26);
      const last = bt[bt.length - 1];
      const lastPct = Math.round(Math.min(1, last[1] / Math.max(1, last[2])) * 100);
      trend = '<div style="display:flex;align-items:center;gap:10px;margin-left:auto" ' +
        'title="Bounce rate per day = bounces / compressed reads. Falling = the mode policy is learning which files not to compress.">' +
        '<div style="text-align:right"><div class="cmdr-stat-label">Bounce-rate trend (' + bt.length + 'd)</div>' +
        '<div class="cmdr-stat-sub">today ' + lastPct + '%</div></div>' + spark + '</div>';
    } else {
      trend = '<div class="cmdr-stat-sub" style="margin-left:auto;align-self:center">' +
        'Learning trend: collecting data \u2014 needs 2+ days of usage</div>';
    }

    return '<div class="cmdr-section"><div class="cmdr-section-header"><h3>Live Signals</h3>' +
      '<span class="badge" title="What lean-ctx currently knows about your working context, and the loops it learned from. Updates with every agent action.">closed loop</span></div>' +
      '<div style="display:flex;gap:8px;flex-wrap:wrap;align-items:stretch">' + tiles + trend + '</div></div>';
  }

  // === ACTION CARDS ===

  _renderActionCards() {
    const actions = this._data.actions || [];
    if (actions.length === 0) return '';

    let h = '<div class="cmdr-section">';
    h += '<div class="cmdr-section-header"><h3>Recommended Actions</h3>';
    h += '<span class="badge">' + actions.length + '</span></div>';
    h += '<div class="cmdr-actions-grid">';

    for (const a of actions) {
      const icon = a.type === 'evict' ? '\u232b' : a.type === 'compress' ? '\u21e9' : '\u21bb';
      const typeLabel = a.type === 'evict' ? 'Evict' : a.type === 'compress' ? 'Compress' : 'Full Read';
      const savingsText = a.estimated_savings > 0 ? 'Save ' + fmtTok(a.estimated_savings) + ' tokens' : '';

      h += '<div class="cmdr-action-card" data-action-type="' + esc(a.type) + '" data-action-path="' + esc(a.path) + '"';
      if (a.to_mode) h += ' data-action-mode="' + esc(a.to_mode) + '"';
      h += '>';
      h += '<div class="cmdr-action-icon">' + icon + '</div>';
      h += '<div class="cmdr-action-body">';
      h += '<div class="cmdr-action-type">' + typeLabel + '</div>';
      h += '<div class="cmdr-action-path" title="' + esc(a.path) + '">' + esc(shortenPath(a.path)) + '</div>';
      h += '<div class="cmdr-action-reason">' + esc(a.reason) + '</div>';
      if (savingsText) h += '<div class="cmdr-action-savings">' + savingsText + '</div>';
      h += '</div>';
      h += '<button type="button" class="cmdr-action-btn" title="Execute">Apply</button>';
      h += '</div>';
    }

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

  // === RISK ALERTS ===

  _renderRiskAlerts() {
    const warnings = this._risk?.warnings || [];
    if (warnings.length === 0) return '';

    let h = '<div class="cmdr-section">';
    for (const w of warnings) {
      const sev = w.severity === 'high' ? 'cmdr-risk-high' : 'cmdr-risk-medium';
      h += '<div class="cmdr-risk-banner ' + sev + '">';
      h += '<div class="cmdr-risk-icon">' + (w.severity === 'high' ? '\u26a0' : '\u24d8') + '</div>';
      h += '<div class="cmdr-risk-body">';
      h += '<div class="cmdr-risk-path">' + esc(shortenPath(w.path)) + ' <span class="tag tg">' + esc(w.mode) + '</span></div>';
      h += '<div class="cmdr-risk-msg">' + esc(w.message) + '</div>';
      h += '<div class="cmdr-risk-suggest">' + esc(w.suggestion) + '</div>';
      h += '</div>';
      h += '<button type="button" class="cmdr-action-btn" data-action-type="full_read" data-action-path="' + esc(w.path) + '">Read Full</button>';
      h += '</div>';
    }
    h += '</div>';
    return h;
  }

  // === PRESSURE TABLE ===

  _renderPressureTable() {
    const items = this._data.items || [];
    if (items.length === 0) return '<div class="card" style="padding:20px;text-align:center;color:var(--muted)">No files in context yet.</div>';

    const modes = ['all', ...new Set(items.map(i => i.mode).filter(Boolean))];

    let filtered = this._modeFilter !== 'all' ? items.filter(i => i.mode === this._modeFilter) : items;

    const sk = this._sortKey;
    const dir = this._sortDir === 'desc' ? -1 : 1;
    filtered = [...filtered].sort((a, b) => {
      let av = a[sk], bv = b[sk];
      if (typeof av === 'string') av = av.toLowerCase();
      if (typeof bv === 'string') bv = bv.toLowerCase();
      if (av == null) av = 0;
      if (bv == null) bv = 0;
      return av < bv ? -1 * dir : av > bv ? dir : 0;
    });

    const th = (key, label, cls) => {
      const active = sk === key;
      const ind = active ? (this._sortDir === 'asc' ? ' \u25b2' : ' \u25bc') : ' \u25c7';
      return '<th class="' + (cls || '') + (active ? ' th-sort-active' : '') + '" data-sort="' + key + '" style="cursor:pointer;user-select:none">' + label + '<span class="sort-ind">' + ind + '</span></th>';
    };

    const modeOpts = modes.map(m =>
      '<option value="' + esc(m) + '"' + (m === this._modeFilter ? ' selected' : '') + '>' + (m === 'all' ? 'All modes' : esc(m)) + '</option>'
    ).join('');

    let h = '<div class="cmdr-section">';
    h += '<div class="cmdr-section-header">';
    h += '<h3>Context Pressure Table</h3>';
    h += '<div style="display:flex;align-items:center;gap:8px">';
    h += '<span class="badge">' + filtered.length + '/' + items.length + '</span>';
    h += '<select id="cmdrModeFilter" class="btn" style="padding:4px 8px;font-size:11px">' + modeOpts + '</select>';
    h += '<button type="button" class="btn cmdr-power-toggle" id="cmdrPowerToggle">' + (this._powerMode ? 'Simple' : 'Detailed') + '</button>';
    h += '</div></div>';

    h += '<div class="table-scroll"><table>';
    h += '<thead><tr>';
    h += th('path', 'Path');
    h += th('tokens_sent', 'Tokens', 'r');
    h += th('mode', 'Mode');

    if (this._powerMode) {
      h += th('tokens_original', 'Original', 'r');
      h += th('compression_pct', 'Saved %', 'r');
      h += th('phi', '\u03a6', 'r');
      h += th('last_accessed_ts', 'Last Access');
      h += th('access_count', 'Reads', 'r');
      h += th('eviction_score', 'Eviction', 'r');
    }

    h += '<th>Status</th>';
    h += '<th>Actions</th>';
    h += '</tr></thead><tbody>';

    for (let idx = 0; idx < filtered.length; idx++) {
      const r = filtered[idx];
      const pd = encodeURIComponent(r.path);
      const hasRisk = r.risk_flags && r.risk_flags.length > 0;
      const rowCls = r.state === 'excluded' ? ' cmdr-row-excluded'
        : hasRisk ? ' cmdr-row-risk' : r.pinned ? ' cmdr-row-pinned' : '';

      h += '<tr class="cmdr-table-row' + rowCls + '">';
      h += '<td class="ctx-path-cell" title="' + esc(r.path) + '">' + esc(shortenPath(r.path)) + '</td>';
      h += '<td class="r">' + fmtTok(r.tokens_sent) + '</td>';
      h += '<td><span class="tag tg">' + esc(r.mode) + '</span></td>';

      if (this._powerMode) {
        h += '<td class="r">' + fmtTok(r.tokens_original) + '</td>';
        h += '<td class="r">' + (r.compression_pct || 0) + '%</td>';
        h += '<td class="r">' + (r.phi != null ? Number(r.phi).toFixed(3) : '\u2014') + '</td>';
        h += '<td>' + timeAgo(r.last_accessed_ts) + '</td>';
        h += '<td class="r">' + (r.access_count || 0) + '</td>';
        const evScore = r.eviction_score || 0;
        const evColor = evScore > 0.7 ? 'var(--red)' : evScore > 0.4 ? 'var(--yellow)' : 'var(--green)';
        h += '<td class="r" style="color:' + evColor + '">' + evScore.toFixed(2) + '</td>';
      }

      // Status
      h += '<td>';
      if (r.pinned) h += '<span class="cmdr-pin-badge">\ud83d\udccc</span> ';
      if (hasRisk) h += '<span class="cmdr-risk-dot" title="Risk detected">\u26a0</span>';
      // Active compiler/linter errors from the diagnostics store (#499).
      if (r.diagnostics && r.diagnostics.length > 0) {
        var errCount = r.diagnostics.filter(function (d) { return d.severity === 'error'; }).length;
        if (errCount > 0) {
          var firstErr = r.diagnostics.find(function (d) { return d.severity === 'error'; });
          var diagTip = 'Active build error' + (errCount > 1 ? 's (' + errCount + ')' : '') +
            (firstErr && firstErr.message ? ': ' + firstErr.message : '');
          h += ' <span style="color:var(--red);font-weight:600" title="' + esc(diagTip) + '">\u2716 ' +
            errCount + ' error' + (errCount > 1 ? 's' : '') + '</span>';
        }
      }
      if (r.git_recency >= 1) {
        h += ' <span style="color:var(--accent)" title="Uncommitted changes \u2014 active working set">\u25cf</span>';
      }
      if (r.editor_active) {
        h += ' <span title="Currently open in the editor">\ud83d\udc41</span>';
      }
      if (r.state === 'excluded') {
        h += ' <span class="tag td">Excluded</span>';
      }
      h += '</td>';

      // Actions
      h += '<td style="white-space:nowrap">';
      if (!r.pinned) {
        h += '<button type="button" class="action-btn" data-act="pin" data-path="' + pd + '">Pin</button> ';
      } else {
        h += '<button type="button" class="action-btn" data-act="unpin" data-path="' + pd + '">Unpin</button> ';
      }
      if (r.state === 'excluded') {
        h += '<span class="tag td" style="font-size:10px">Excluded</span>';
      } else {
        h += '<button type="button" class="action-btn danger" data-act="evict" data-path="' + pd + '">Evict</button>';
      }
      h += '</td></tr>';

      // Expandable trail row (power mode)
      if (this._powerMode && r.source_trail && r.source_trail.length > 0) {
        const expanded = this._expandedTrails.has(idx);
        h += '<tr class="cmdr-trail-toggle" data-trail-idx="' + idx + '">';
        h += '<td colspan="' + (this._powerMode ? 12 : 6) + '" style="padding:2px 12px;font-size:10px;cursor:pointer;color:var(--muted)">';
        h += (expanded ? '\u25bc' : '\u25b6') + ' Why in context? (' + r.source_trail.length + ')';
        h += '</td></tr>';

        if (expanded) {
          h += '<tr class="cmdr-trail-content"><td colspan="' + (this._powerMode ? 12 : 6) + '">';
          h += '<div class="cmdr-trail-items">';
          for (const t of r.source_trail) {
            h += '<div class="cmdr-trail-item">';
            h += '<span class="cmdr-trail-type">' + esc(t.type) + '</span>';
            if (t.tool) h += ' <span class="tag tg">' + esc(t.tool) + '</span>';
            if (t.detail) h += ' ' + esc(t.detail);
            if (t.ts) h += ' <span class="cmdr-trail-time">' + timeAgo(t.ts) + '</span>';
            h += '</div>';
          }
          h += '</div></td></tr>';
        }
      }
    }

    h += '</tbody></table></div></div>';
    return h;
  }

  // === EVENT BINDING ===

  _bind() {
    this.querySelectorAll('th[data-sort]').forEach(th => {
      th.addEventListener('click', () => {
        const k = th.getAttribute('data-sort');
        if (this._sortKey === k) {
          this._sortDir = this._sortDir === 'asc' ? 'desc' : 'asc';
        } else {
          this._sortKey = k;
          this._sortDir = 'desc';
        }
        this.render();
      });
    });

    const modeFilter = this.querySelector('#cmdrModeFilter');
    if (modeFilter) {
      modeFilter.addEventListener('change', () => {
        this._modeFilter = modeFilter.value;
        this.render();
      });
    }

    const toggle = this.querySelector('#cmdrPowerToggle');
    if (toggle) {
      toggle.addEventListener('click', () => {
        this._powerMode = !this._powerMode;
        this.render();
      });
    }

    this.querySelectorAll('.cmdr-trail-toggle').forEach(row => {
      row.addEventListener('click', () => {
        const idx = parseInt(row.getAttribute('data-trail-idx'), 10);
        if (this._expandedTrails.has(idx)) {
          this._expandedTrails.delete(idx);
        } else {
          this._expandedTrails.add(idx);
        }
        this.render();
      });
    });

    this.querySelectorAll('.cmdr-action-card .cmdr-action-btn').forEach(btn => {
      btn.addEventListener('click', () => {
        const card = btn.closest('.cmdr-action-card');
        const type = card.getAttribute('data-action-type');
        const path = card.getAttribute('data-action-path');
        const mode = card.getAttribute('data-action-mode');
        this._executeAction(type, path, mode);
      });
    });

    this.querySelectorAll('.cmdr-risk-banner .cmdr-action-btn').forEach(btn => {
      btn.addEventListener('click', () => {
        const type = btn.getAttribute('data-action-type');
        const path = btn.getAttribute('data-action-path');
        this._executeAction(type, path);
      });
    });

    this.querySelectorAll('.action-btn[data-act]').forEach(btn => {
      btn.addEventListener('click', () => {
        const act = btn.getAttribute('data-act');
        const path = decodeURIComponent(btn.getAttribute('data-path'));
        this._executeOverlay(act, path);
      });
    });
  }

  async _executeAction(type, path, mode) {
    const fetchJson = api();
    if (!fetchJson) return;

    if (type === 'evict') {
      // #715: real ledger eviction (drops pressure), not just an exclude overlay.
      await this._executeOverlay('evict', path);
    } else if (type === 'compress' && mode) {
      await this._executeOverlay('set_view', path, mode);
    } else if (type === 'full_read') {
      await this._executeOverlay('set_view', path, 'full');
    }
  }

  async _executeOverlay(action, path, value) {
    const fetchJson = api();
    if (!fetchJson) return;

    const body = { action, path };
    if (value !== undefined) body.value = value;

    try {
      await fetchJson('/api/context-overlay', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
        timeoutMs: 15000,
      });
      const msg = action === 'set_view'
        ? 'View → ' + (value || 'default') + ': ' + shortenPath(path) + ' (next read)'
        : action === 'evict'
          ? 'Evicted: ' + shortenPath(path)
          : action + ': ' + shortenPath(path);
      toast(msg, 'success');
      await this.loadData();
    } catch (e) {
      toast('Failed: ' + (e?.error || String(e)), 'error');
    }
  }
}

(function register() {
  var R = window.LctxRouter;
  if (R && R.registerLoader) {
    R.registerLoader('commander', function () {
      var el = document.querySelector('cockpit-commander');
      if (el && typeof el.loadData === 'function') return el.loadData();
    });
  }
})();

customElements.define('cockpit-commander', CockpitCommander);

export { CockpitCommander };