-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
862 lines (758 loc) · 29.7 KB
/
Copy pathindex.html
File metadata and controls
862 lines (758 loc) · 29.7 KB
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custos — structural risk monitor</title>
<meta property="og:type" content="website">
<meta property="og:url" content="https://acevod.github.io/custos/">
<meta property="og:title" content="Custos — structural risk monitor">
<meta property="og:description" content="Structural risk monitor for Bitget stock rTokens. Watches wrapper liquidity, not price direction.">
<meta property="og:image" content="https://acevod.github.io/custos/og-image.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Custos — structural risk monitor">
<meta name="twitter:description" content="Structural risk monitor for Bitget stock rTokens. Watches wrapper liquidity, not price direction.">
<meta name="twitter:image" content="https://acevod.github.io/custos/og-image.png">
<meta name="description" content="Structural liquidity risk monitoring for Bitget rTokens.">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Barlow+Condensed:wght@400;500;600;700&family=Barlow:wght@400;500;600&family=IBM+Plex+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<style>
:root {
--bg: #0c111d;
--panel: #121829;
--line: #29314a;
--text: #e8e5dc;
--text-dim: #8890a4;
--healthy: #5fa88f;
--watch: #c9a24b;
--redflag: #bd5b45;
}
* { box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; }
body {
margin: 0;
background: var(--bg);
color: var(--text);
font-family: 'Barlow', sans-serif;
line-height: 1.5;
}
.mono { font-family: 'IBM Plex Mono', monospace; }
#app {
max-width: 840px;
margin: 0 auto;
padding: 48px 24px 80px;
}
header {
margin-bottom: 40px;
}
.brand {
display: flex;
align-items: baseline;
gap: 12px;
}
.brand h1 {
font-family: 'Barlow Condensed', sans-serif;
font-weight: 700;
font-size: 42px;
letter-spacing: 0.01em;
margin: 0;
}
.pulse {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--healthy);
flex-shrink: 0;
align-self: center;
animation: pulse 2.4s ease-in-out infinite;
}
/* Data is stale: stop implying "all good" with a cheerful green pulse. */
.pulse.is-stale {
background: var(--watch);
animation: none;
}
@keyframes pulse {
0%, 100% { opacity: 0.4; transform: scale(0.85); }
50% { opacity: 1; transform: scale(1); }
}
@media (prefers-reduced-motion: reduce) {
.pulse { animation: none; opacity: 1; }
}
.tagline {
color: var(--text-dim);
font-size: 16px;
margin: 10px 0 0;
max-width: 46ch;
}
.thesis {
margin: 28px 0 0;
padding: 18px 20px;
border: 1px solid var(--line);
border-left: 3px solid var(--healthy);
border-radius: 6px;
}
.thesis-label {
font-family: 'Barlow Condensed', sans-serif;
font-weight: 600;
font-size: 12.5px;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--healthy);
margin: 0 0 8px;
}
.thesis-body {
color: var(--text);
font-size: 16px;
line-height: 1.55;
margin: 0;
max-width: 58ch;
}
.freshness {
display: flex;
align-items: center;
gap: 6px;
font-size: 13px;
color: var(--text-dim);
margin: 14px 0 0;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 6px 20px;
font-size: 13px;
color: var(--text-dim);
margin: -6px 0 16px;
}
.legend-dot {
display: inline-block;
width: 9px;
height: 9px;
border-radius: 50%;
margin-right: 6px;
}
section {
margin-top: 48px;
}
h2 {
font-family: 'Barlow Condensed', sans-serif;
font-weight: 600;
font-size: 15px;
letter-spacing: 0.06em;
color: var(--text-dim);
margin: 0 0 16px;
padding-bottom: 10px;
border-bottom: 1px solid var(--line);
}
/* Hero stat row */
.stat-row {
display: flex;
gap: 0;
border: 1px solid var(--line);
border-radius: 6px;
overflow: hidden;
}
.stat {
flex: 1;
padding: 18px 20px;
border-right: 1px solid var(--line);
}
.stat:last-child { border-right: none; }
.stat-label {
font-size: 13px;
color: var(--text-dim);
margin-bottom: 6px;
}
.stat-num {
font-size: 24px;
font-weight: 500;
}
.hero .stat-num { font-size: 28px; }
/* Holdings ledger */
.row {
display: grid;
grid-template-columns: 64px 1fr 48px 124px 92px;
align-items: center;
gap: 14px;
padding: 11px 0;
border-bottom: 1px solid var(--line);
font-size: 14px;
}
.row:last-child { border-bottom: none; }
.row-ticker {
font-family: 'IBM Plex Mono', monospace;
font-weight: 600;
}
.meter {
height: 5px;
background: var(--line);
position: relative;
overflow: hidden;
}
.meter-fill {
height: 100%;
transition: width 0.6s ease;
}
.row-score {
text-align: right;
color: var(--text-dim);
}
.row-meter {
display: flex;
align-items: center;
gap: 8px;
}
.meter { flex: 1 1 auto; }
/* Last few composite scores for this token, oldest to newest. Purely a
trend cue (steady vs. jumpy) - the bar + number are still the reading
that matters. Hidden when there isn't enough recent history to plot. */
.spark {
flex: 0 0 auto;
width: 40px;
height: 16px;
opacity: 0.8;
}
.row-label {
font-size: 13px;
white-space: nowrap;
}
.row-status {
white-space: nowrap;
font-size: 12px;
color: var(--text-dim);
text-align: right;
}
.stat-sub {
font-size: 12.5px;
margin-top: 4px;
color: var(--text-dim);
}
/* Performance grid: hairlines in both directions, aligned values */
.perf-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
border-top: 1px solid var(--line);
border-left: 1px solid var(--line);
}
.perf-grid .stat {
border-right: 1px solid var(--line);
border-bottom: 1px solid var(--line);
padding: 14px 16px;
}
.perf-grid .stat-label { min-height: 2.6em; }
.perf-grid .stat-num { font-size: 20px; }
/* Decision log */
.log-scroll {
max-height: 420px;
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: var(--line) transparent;
}
.log-scroll::-webkit-scrollbar {
width: 8px;
}
.log-scroll::-webkit-scrollbar-track {
background: transparent;
}
.log-scroll::-webkit-scrollbar-thumb {
background: var(--line);
border-radius: 4px;
}
.raw-link {
color: var(--text-dim);
text-decoration: underline;
text-decoration-color: var(--line);
text-underline-offset: 3px;
}
.raw-link:hover {
color: var(--text);
}
.log-entry {
padding: 16px 0;
border-bottom: 1px solid var(--line);
}
.log-entry:last-child { border-bottom: none; }
.log-meta {
font-size: 12.5px;
color: var(--text-dim);
margin-bottom: 6px;
}
.log-ticker { color: var(--text); }
.badge {
display: inline-block;
font-size: 11.5px;
letter-spacing: 0.05em;
padding: 0 7px;
margin-right: 6px;
border: 1px solid currentColor;
border-radius: 3px;
}
.log-src { color: var(--text-dim); }
.log-detail {
margin: 0 0 4px;
font-size: 13.5px;
color: var(--text-dim);
max-width: 68ch;
}
.log-reasoning {
margin: 0;
font-size: 14.5px;
color: var(--text);
max-width: 68ch;
}
.log-why {
font-family: 'Barlow Condensed', sans-serif;
font-weight: 600;
font-size: 11px;
letter-spacing: 0.07em;
color: var(--text-dim);
margin-right: 6px;
}
.empty {
color: var(--text-dim);
font-size: 14.5px;
margin: 0;
}
.note {
color: var(--text-dim);
font-size: 12.5px;
margin: 10px 0 0;
}
footer {
margin-top: 56px;
padding-top: 20px;
border-top: 1px solid var(--line);
color: var(--text-dim);
font-size: 13px;
}
footer p { margin: 0; max-width: 62ch; }
.empty-state {
padding: 80px 0;
}
.empty-state h1 {
font-family: 'Barlow Condensed', sans-serif;
font-size: 42px;
margin: 0 0 16px;
}
.empty-state p {
color: var(--text-dim);
max-width: 46ch;
font-size: 15px;
}
@media (max-width: 620px) {
#app { padding: 32px 18px 64px; }
.thesis-body { font-size: 15px; }
.hide-sm { display: none; }
.stat-row.hero .stat { padding: 12px 10px; min-width: 0; }
.stat-sub { line-height: 1.5; margin-top: 6px; }
.stat-row.hero .stat-label { font-size: 12px; }
.stat-row.hero .stat-num { font-size: 17px; }
.stat-row.hero .stat-sub { font-size: 11px; }
.perf-grid { grid-template-columns: repeat(2, 1fr); }
.row {
padding: 9px 0;
grid-template-columns: 52px 1fr 48px;
grid-template-areas:
"ticker meter score"
"label label status";
row-gap: 4px;
}
.row-ticker { grid-area: ticker; }
.row-meter { grid-area: meter; }
.row-score { grid-area: score; }
.row-label { grid-area: label; }
.row-status { grid-area: status; text-align: left; }
}
</style>
</head>
<body>
<div id="app" class="loading">
<header>
<div class="brand">
<span class="pulse"></span>
<h1>Custos</h1>
</div>
<p class="tagline">Structural risk monitor for Bitget stock rTokens — watches wrapper liquidity, not price direction.</p>
</header>
<section class="thesis">
<p class="thesis-label">The problem</p>
<p class="thesis-body">A tokenized stock's price can look fine while the wrapper underneath it quietly becomes harder to trade — spread widens, depth thins. Custos watches that structure rather than betting on price direction, and decides whether to hold, act, or wait based on it alone.</p>
</section>
<p class="freshness mono" id="freshness">—</p>
<section class="stat-row hero">
<div class="stat">
<div class="stat-label">Portfolio value</div>
<div class="stat-num mono" id="stat-value">—</div>
<div class="stat-sub mono" id="stat-delta"></div>
</div>
<div class="stat">
<div class="stat-label">USDT held</div>
<div class="stat-num mono" id="stat-cash">—</div>
</div>
<div class="stat">
<div class="stat-label">Positions held</div>
<div class="stat-num mono" id="stat-held">—</div>
</div>
</section>
<section>
<h2>Holdings</h2>
<p class="note" style="margin-top:-8px; margin-bottom:16px;">An example paper-trading portfolio of 10 rTokens — no real funds move, but every price and spread reading is pulled live from Bitget. The same scoring method applies to any Bitget stock rToken.</p>
<p class="legend">
<span><span class="legend-dot" style="background:var(--healthy)"></span>healthy</span>
<span><span class="legend-dot" style="background:var(--watch)"></span>watch</span>
<span><span class="legend-dot" style="background:var(--redflag)"></span>red flag</span>
<span><span class="legend-dot" style="background:var(--text-dim)"></span>warming up</span>
<span><span class="legend-dot" style="background:var(--text-dim)"></span>no fresh signal</span>
</p>
<p class="note" style="margin:-4px 0 14px;">Score: 0 (worst) to 1 (best) wrapper health. A “warming up” bar shows progress toward a 48-hour baseline; “no fresh signal” means the feed is unchanged since the last cycle.</p>
<div id="holdings" class="holdings"></div>
</section>
<section>
<h2>Decision log</h2>
<p class="note" style="margin-top:-8px; margin-bottom:16px;">Every cycle, the agent evaluates the weakest holding and the strongest cash position and logs the outcome — whether or not it results in a trade. Most evaluations are settled by fixed safety rules; the model's own reasoning appears only when it was actually consulted.</p>
<div id="log" class="log log-scroll"></div>
<p class="note"><a href="https://github.com/acevod/custos/blob/main/data/event_log.jsonl" class="raw-link" target="_blank" rel="noopener noreferrer">View full decision history on GitHub →</a></p>
</section>
<section>
<h2>Performance</h2>
<p class="note" style="margin-top:-8px; margin-bottom:16px;">Two views, kept separate on purpose. <strong>Round trip</strong> = a sell followed by its buy-back, measured against simply holding through it (“gain vs holding”). <strong>Exit</strong> = the sell price against the original entry, which ignores what re-entering cost. Neither predicts price direction; the point is whether stepping aside from structural stress helped.</p>
<div id="perf"></div>
</section>
<section>
<h2>Run records</h2>
<p class="note" style="margin-top:-8px; margin-bottom:16px;">Every executed trade — timestamp, instrument, direction, price, quantity, and the resulting change to the USDT balance. Paper trading, no real funds involved.</p>
<div id="runrecords"></div>
<p class="note"><a href="https://github.com/acevod/custos/blob/main/data/transaction_log.jsonl" class="raw-link" target="_blank" rel="noopener noreferrer">View full transaction history on GitHub →</a></p>
</section>
<footer>
<p>Last updated <span id="updated" class="mono">—</span>. Paper trading only, no real funds. Not financial advice.</p>
</footer>
</div>
<script>
// Fix L-4: every value interpolated into HTML is escaped, JSONL
// parsing skips corrupt lines instead of killing the whole
// dashboard, and each dashboard section fails independently so one
// broken fetch can't blank sections that loaded fine.
const STATUS_COLOR = {
healthy: 'var(--healthy)',
watch: 'var(--watch)',
red_flag: 'var(--redflag)',
warming_up: 'var(--text-dim)',
no_fresh_signal: 'var(--text-dim)',
unknown: 'var(--text-dim)',
};
const STATUS_LABEL = {
healthy: 'healthy',
watch: 'watch',
red_flag: 'red flag',
warming_up: 'warming up',
no_fresh_signal: 'no fresh signal',
unknown: 'no data',
};
// A run is scheduled every 4 hours, but GitHub's scheduler is jittery:
// observed gaps between real runs were 3-8h. Only flag the dashboard as
// stale once the gap is clearly beyond that, or the banner cries wolf.
const STALE_AFTER_MS = 10 * 60 * 60 * 1000;
async function fetchJSON(path) {
const res = await fetch(path, { cache: 'no-store' });
if (!res.ok) throw new Error(path + ' not found');
return res.json();
}
async function fetchJSONL(path, limit) {
// event_log.jsonl and transaction_log.jsonl are both append-only
// and can grow indefinitely. main.py maintains a bounded JSON
// feed for the dashboard for each.
const dashboardPath = path.endsWith('event_log.jsonl')
? 'data/recent_events.json'
: path.endsWith('transaction_log.jsonl')
? 'data/recent_transactions.json'
: path;
const res = await fetch(dashboardPath, { cache: 'no-store' });
if (!res.ok) return [];
if (dashboardPath.endsWith('.json')) {
try {
const data = await res.json();
return Array.isArray(data) ? data.slice(0, limit || 20) : [];
} catch (e) {
return [];
}
}
const text = await res.text();
const lines = text.trim().split('\n').filter(Boolean).flatMap(l => {
try { return [JSON.parse(l)]; } catch (e) { return []; }
});
lines.reverse();
return limit ? lines.slice(0, limit) : lines;
}
const BASELINE_HOURS = 48; // mirrors MIN_HISTORY_HOURS in main.py
function fmtUsd(n) {
if (n === null || n === undefined || isNaN(n)) return '—';
const body = Math.abs(n).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
return (n < 0 ? '−' : '') + '$' + body;
}
const MONTHS = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
function fmtShort(iso) {
const d = new Date(iso);
if (isNaN(d.getTime())) return '—';
const pad = n => String(n).padStart(2, '0');
return d.getUTCDate() + ' ' + MONTHS[d.getUTCMonth()] + ' ' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ' UTC';
}
function fmtTime(iso) {
const d = new Date(iso);
// An invalid timestamp must not throw and blank the whole section.
if (isNaN(d.getTime())) return '—';
return d.toISOString().replace('T', ' ').slice(0, 16) + ' UTC';
}
function fmtAge(ms) {
const hours = Math.floor(ms / (60 * 60 * 1000));
if (hours < 1) return Math.round(ms / (60 * 1000)) + 'm';
const days = Math.floor(hours / 24);
if (days < 1) return hours + 'h';
return days + 'd ' + (hours % 24) + 'h';
}
function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = String(str);
return div.innerHTML;
}
// Last few composite scores as a tiny inline sparkline (SVG polyline,
// fixed 0-1 domain so steepness is comparable across tokens). `trend` is
// chronological oldest -> newest with `null` for runs where this token's
// score wasn't computed; those breaks are drawn as gaps, never bridged.
function sparkline(trend, color) {
if (!Array.isArray(trend) || trend.length < 2) return '';
const w = 40, h = 16, pad = 2, n = trend.length;
const x = i => (n === 1 ? w / 2 : pad + (i / (n - 1)) * (w - 2 * pad));
const y = v => h - pad - Math.max(0, Math.min(1, v)) * (h - 2 * pad);
const runs = [];
let current = [];
trend.forEach((v, i) => {
if (typeof v === 'number') {
current.push(`${x(i).toFixed(1)},${y(v).toFixed(1)}`);
} else if (current.length) {
runs.push(current);
current = [];
}
});
if (current.length) runs.push(current);
if (runs.every(r => r.length < 2) && runs.flat().length < 1) return '';
const lines = runs.filter(r => r.length >= 2)
.map(r => `<polyline points="${r.join(' ')}" fill="none" stroke="${color}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>`)
.join('');
if (!lines) return '';
let lastIdx = -1;
trend.forEach((v, i) => { if (typeof v === 'number') lastIdx = i; });
const dot = lastIdx >= 0 ? `<circle cx="${x(lastIdx).toFixed(1)}" cy="${y(trend[lastIdx]).toFixed(1)}" r="1.6" fill="${color}"/>` : '';
return `<svg class="spark" viewBox="0 0 ${w} ${h}" aria-hidden="true">${lines}${dot}</svg>`;
}
function renderHoldings(scores, positions, baseline) {
const tickers = Object.keys(scores);
return tickers.map(ticker => {
const s = scores[ticker] || {};
const pos = (positions && positions[ticker]) || {};
const b = (baseline && baseline[ticker]) || null;
const hasScore = typeof s.score === 'number';
const warming = s.label === 'warming_up';
const noFresh = s.label === 'no_fresh_signal';
const partial = warming || noFresh;
const color = STATUS_COLOR[s.label] || STATUS_COLOR.unknown;
let pct = 0, scoreText = '—', labelText = STATUS_LABEL[s.label] || 'no data', fillStyle = '', title = '';
if (!partial && hasScore) {
// Full-strength reading: all components present.
pct = Math.round(s.score * 100);
scoreText = s.score.toFixed(2);
} else if (warming) {
// A partial score would look confident (e.g. 0.95 from spread + calendar
// alone), so show progress toward the baseline instead of a score.
if (b && typeof b.span_hours === 'number' && b.span_hours < BASELINE_HOURS) {
pct = Math.min(100, Math.round(Math.max(0, b.span_hours) / BASELINE_HOURS * 100));
labelText = 'warming up ' + Math.floor(Math.max(0, b.span_hours)) + '/' + BASELINE_HOURS + 'h';
fillStyle = 'opacity:.55;';
}
title = 'Not enough history to score this token reliably yet. The bar shows progress toward a ' + BASELINE_HOURS + 'h baseline.';
} else if (noFresh) {
title = "Bitget's quote is unchanged since the last cycle, so there is no fresh signal to score.";
}
// Static markup only (no data interpolated): "· cash" is dropped on narrow screens.
const statusHtml = pos.status === 'held' ? 'held'
: (pos.status === 'sold' ? 'sold<span class="hide-sm"> · cash</span>' : '—');
const spark = sparkline(b && b.trend, color);
return `
<div class="row" ${title ? `title="${escapeHtml(title)}"` : ''}>
<div class="row-ticker">${escapeHtml(ticker)}</div>
<div class="row-meter">
<div class="meter"><div class="meter-fill" style="width:${pct}%; background:${color}; ${fillStyle}"></div></div>
${spark}
</div>
<div class="row-score mono">${escapeHtml(scoreText)}</div>
<div class="row-label" style="color:${color}">${escapeHtml(labelText)}</div>
<div class="row-status mono">${statusHtml}</div>
</div>`;
}).join('');
}
function parseAction(action) {
// "HOLD (awaiting confirmation - ...)" -> ["HOLD", "awaiting confirmation - ..."]
const m = /^([A-Za-z_ ]+?)\s*\((.*)\)\s*$/.exec(String(action || ''));
return m ? [m[1].trim(), m[2].trim()] : [String(action || '').trim(), ''];
}
function renderLog(events) {
if (!events.length) {
return '<p class="empty">No decisions logged yet — the agent evaluates every cycle once enough history builds up to score a token.</p>';
}
return events.map(e => { try {
let badge, color, detail = '', source;
if (e.type === 'sell') {
badge = 'SOLD'; color = 'var(--redflag)'; source = 'model';
detail = 'Proceeds ' + fmtUsd(e.proceeds_usd) + ' · P&L vs entry ' + fmtUsd(e.realized_pnl_usd) + ' · score ' + e.score_at_decision;
} else if (e.type === 'buy_back') {
badge = 'BOUGHT BACK'; color = 'var(--healthy)'; source = 'model';
detail = 'Cost ' + fmtUsd(e.cost_usd) + ' · score ' + e.score_at_decision;
} else {
const parsed = parseAction(e.action_taken);
badge = parsed[0].toUpperCase(); detail = parsed[1];
detail = detail ? detail.charAt(0).toUpperCase() + detail.slice(1) : '';
color = /SKIPPED|FROZEN/.test(badge) ? 'var(--watch)' : 'var(--text-dim)';
source = e.type === 'evaluation_skipped' ? 'data' : (e.llm_provider_used ? 'model' : 'rule');
}
// Reasoning is capped server-side; clip again defensively so an old
// long entry (e.g. raw chain-of-thought) can never flood the page.
let rawReason = String(e.llm_reasoning || '').replace(/\n+/g, ' ').trim();
if (rawReason.length > 400) rawReason = rawReason.slice(0, 399) + '…';
const ageMs = Date.now() - new Date(e.timestamp).getTime();
const age = isNaN(ageMs) ? '' : ' · ' + fmtAge(Math.max(0, ageMs)) + ' ago';
return `
<div class="log-entry">
<div class="log-meta mono"><span class="badge" style="color:${color}">${escapeHtml(badge)}</span><span class="log-ticker">${escapeHtml(e.instrument)}</span> · ${fmtShort(e.timestamp)}${age} · <span class="log-src" title="${source === 'model' ? 'The language model was consulted' : (source === 'rule' ? 'Settled by a fixed safety rule, no model call' : 'Market data was unavailable')}">${source}</span></div>
${detail ? `<p class="log-detail">${escapeHtml(detail)}</p>` : ''}
${rawReason ? `<p class="log-reasoning"><span class="log-why">WHY</span>${escapeHtml(rawReason)}</p>` : ''}
</div>`;
} catch (err) { return ''; } }).join('');
}
function renderPerformance(perf) {
const exits = perf ? (perf.exit_count ?? perf.trade_count ?? 0) : 0;
if (!perf || exits === 0) {
return '<p class="empty">No exits yet — no holding has been sold. A sell needs a mature baseline (12+ points over 48h+) and a low score confirmed on consecutive runs.</p>';
}
const pct = v => (v === null || v === undefined) ? '—' : v + '%';
const trips = perf.round_trips_completed || 0;
const rows = [
['Exits (sells)', exits],
['Round trips done', trips],
['Round-trip win rate', pct(perf.round_trip_win_rate_pct)],
['Gain vs holding', fmtUsd(perf.total_protection_gain_usd)],
['Exit win rate', pct(perf.win_rate_pct)],
['Exit P&L vs entry', fmtUsd(perf.total_realized_pnl_usd)],
['Max drawdown', fmtUsd(perf.max_drawdown_usd)],
];
return '<div class="perf-grid">' + rows.map(([label, val]) =>
`<div class="stat"><div class="stat-label">${escapeHtml(label)}</div><div class="stat-num mono">${escapeHtml(val)}</div></div>`
).join('') + '</div>';
}
function renderRunRecords(records) {
if (!records.length) {
return '<p class="empty">No trades executed yet — nothing has crossed the hard SELL/BUY_BACK thresholds so far. This section fills in as soon as the first trade happens.</p>';
}
return records.map(t => {
const directionColor = t.direction === 'SELL' ? 'var(--redflag)' : 'var(--healthy)';
const price = typeof t.price === 'number' ? t.price.toFixed(2) : '—';
const qty = typeof t.quantity === 'number' ? t.quantity.toFixed(4) : '—';
const change = typeof t.balance_change === 'number'
? (t.balance_change >= 0 ? '+' : '') + fmtUsd(t.balance_change)
: '—';
return `
<div class="log-entry">
<div class="log-meta mono">${fmtTime(t.timestamp)} · <span class="log-ticker">${escapeHtml(t.instrument)}</span> · <span style="color:${directionColor}">${escapeHtml(t.direction || '—')}</span> · price ${price} · qty ${qty} · balance ${change}</div>
</div>`;
}).join('');
}
function showEmptyState() {
document.getElementById('app').innerHTML = `
<div class="empty-state">
<div class="brand"><span class="pulse"></span><h1>Custos</h1></div>
<p>Monitoring hasn't started yet. This dashboard populates once the first automated run completes — check back in a few hours, or trigger the workflow manually from the Actions tab.</p>
</div>`;
}
// L-4 fix: each section renders independently - a failure in one
// section leaves the other sections intact instead of falling into
// the global "hasn't started" state.
async function renderStats(latest) {
const ps = latest.portfolio_summary;
document.getElementById('stat-value').textContent = fmtUsd(ps.total_portfolio_value_market_usd);
const cost = ps.total_portfolio_value_cost_basis_usd, mkt = ps.total_portfolio_value_market_usd;
const delta = document.getElementById('stat-delta');
if (typeof cost === 'number' && typeof mkt === 'number' && cost > 0) {
const diff = mkt - cost, sign = diff >= 0 ? '+' : '−';
delta.innerHTML = escapeHtml(sign + fmtUsd(Math.abs(diff)) + ' (' + sign + Math.abs(diff / cost * 100).toFixed(2) + '%)') + '<span class="hide-sm"> vs cost</span>';
delta.style.color = diff >= 0 ? 'var(--healthy)' : 'var(--redflag)';
}
// These are two different problems and get two different
// messages - conflating them under one generic "stale" warning
// previously blamed "prices unavailable" even when the real
// cause was simply that the workflow hadn't run again in a
// while, which sent people chasing a fetch-failure bug that
// wasn't there.
const fetchFailed = ps.valuation_status === 'stale';
const ageMs = Date.now() - new Date(latest.timestamp).getTime();
const tooOld = ageMs > STALE_AFTER_MS;
// One freshness signal, not three: the header's pulse dot (color-coded)
// plus a single line of text that folds in the reason when something's
// actually wrong, instead of a separate dot + a separate stale banner
// repeating the same "stale" word.
const stale = fetchFailed || tooOld;
const pulseDot = document.querySelector('.pulse');
if (pulseDot) pulseDot.classList.toggle('is-stale', stale);
const freshness = document.getElementById('freshness');
let freshText = (stale ? 'updated' : 'live · updated') + ' ' + fmtAge(ageMs) + ' ago';
if (fetchFailed && tooOld) {
freshText += ' — some prices failed to fetch last cycle, still no update since';
} else if (fetchFailed) {
freshText += ' — some live prices were unavailable during the last run';
} else if (tooOld) {
freshText += ' — check whether the scheduled workflow is still running';
}
freshness.textContent = freshText;
freshness.style.color = stale ? 'var(--watch)' : 'var(--text-dim)';
document.getElementById('stat-cash').textContent = fmtUsd(ps.total_usdt_cash);
document.getElementById('stat-held').textContent = ps.held_stocks.length + ' / 10';
}
async function renderHoldingsSection(latest) {
document.getElementById('holdings').innerHTML = renderHoldings(latest.scores, latest.positions, latest.baseline);
}
async function renderLogSection() {
const events = await fetchJSONL('data/event_log.jsonl', 20);
document.getElementById('log').innerHTML = renderLog(events);
}
async function renderPerfSection(latest) {
document.getElementById('perf').innerHTML = renderPerformance(latest.performance_summary);
}
async function renderRunRecordsSection() {
const records = await fetchJSONL('data/transaction_log.jsonl', 20);
document.getElementById('runrecords').innerHTML = renderRunRecords(records);
}
async function init() {
let latest;
try {
latest = await fetchJSON('data/latest.json');
} catch (err) {
showEmptyState();
return;
}
const sections = [
() => renderStats(latest),
() => renderHoldingsSection(latest),
renderLogSection,
() => renderPerfSection(latest),
renderRunRecordsSection,
];
const results = await Promise.allSettled(sections.map(render => render()));
results.forEach((r, i) => {
if (r.status === 'rejected') console.error('Section ' + i + ' failed to render:', r.reason);
});
document.getElementById('updated').textContent = fmtTime(latest.timestamp);
}
init();
</script>
</body>
</html>