-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
3707 lines (3607 loc) · 215 KB
/
Copy pathserver.py
File metadata and controls
3707 lines (3607 loc) · 215 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
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
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import argparse
import json
import socket
import socketserver
from dataclasses import asdict, is_dataclass
from datetime import datetime, timezone
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler
from pathlib import Path
from urllib.parse import parse_qs, unquote, urlparse
from equity_research import config
from equity_research.budget import available_budget_modes, budget_allows_paid_data, load_budget_mode_definitions
from equity_research.consensus_import import import_consensus_csv
from equity_research.global_coverage import (
build_canonical_metric_ontology,
build_metric_resolution_audit,
coverage_case_for,
source_coverage_matrix_for,
)
from equity_research.global_peers import GlobalPeerFinancialProvider
from equity_research.management_sources import (
build_management_source_package,
transcript_document_from_payload,
)
from equity_research.models import CompanyIdentity, ConsensusPackage, ResearchSourcePlan, ResearchSourceRequest, ResearchSourceOutcome
from equity_research.pipeline import run_us_equity_research
from equity_research.peers import peer_universe_for
from equity_research.external_evidence import external_evidence_stack_from_config
from equity_research.historical_references import build_historical_references_for_ticker
from equity_research.local_secrets import (
LocalSecretsManager,
save_validated_keys,
validate_provider_keys,
)
from equity_research.llm_vault import (
build_llm_profile,
delete_llm_profile_with_secret,
list_llm_presets,
profile_to_provider,
save_llm_profile_with_secret,
test_llm_profile,
)
from equity_research.network_diagnostics import run_network_diagnostics
from equity_research.news_intelligence import (
build_corroboration_results,
claim_from_observation,
enrich_source_plan_with_news,
news_claim_from_payload,
observation_from_payload,
source_needs_for_claim,
)
from equity_research.providers import StooqPriceClient, build_consensus_provider
from equity_research.research_store import ResearchStore
from equity_research.research_profiles import event_identifier, research_profiles
from equity_research.rigor import build_calibration_report
from equity_research.sample_data import demo_result
from equity_research.sec_client import SecClient
from equity_research.storytelling import demo_cases
from equity_research.thesis_synthesis import UnavailableLlmProvider, provider_from_config
HTML = r"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>US Equity Research Radar</title>
<style>
:root {
--bg: #f6f7f9;
--ink: #20242a;
--muted: #667085;
--line: #d8dde6;
--panel: #ffffff;
--accent: #116a59;
--accent-2: #244c8f;
--warn: #9a5b00;
--bad: #9b1c31;
}
* { box-sizing: border-box; }
body {
margin: 0;
font-family: Inter, Segoe UI, Arial, sans-serif;
color: var(--ink);
background: var(--bg);
}
header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 18px 28px;
border-bottom: 1px solid var(--line);
background: var(--panel);
position: sticky;
top: 0;
z-index: 5;
}
h1 { font-size: 20px; margin: 0; font-weight: 700; }
h2 { font-size: 18px; margin: 22px 0 12px; }
h3 { font-size: 15px; margin: 0 0 8px; }
.controls {
display: flex;
gap: 8px;
align-items: center;
flex-wrap: wrap;
}
input, select, textarea {
height: 38px;
border: 1px solid var(--line);
border-radius: 6px;
padding: 0 10px;
font-size: 14px;
background: #fff;
}
textarea {
height: auto;
min-height: 72px;
padding: 9px 10px;
resize: vertical;
}
button {
height: 38px;
border: 1px solid var(--line);
border-radius: 6px;
padding: 0 12px;
background: #fff;
color: var(--ink);
cursor: pointer;
font-weight: 600;
}
button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
details.sources { position: relative; }
details.sources summary {
list-style: none;
height: 38px;
border: 1px solid var(--line);
border-radius: 6px;
padding: 9px 12px;
background: #fff;
cursor: pointer;
font-size: 14px;
font-weight: 600;
}
.source-menu {
position: absolute;
right: 0;
top: 44px;
width: min(360px, calc(100vw - 32px));
padding: 12px;
border: 1px solid var(--line);
border-radius: 8px;
background: var(--panel);
box-shadow: 0 10px 30px rgba(32, 36, 42, .14);
display: grid;
gap: 9px;
z-index: 9;
}
.source-menu label { color: var(--muted); font-size: 12px; display: grid; gap: 4px; }
.source-menu label.check { grid-template-columns: 18px 1fr; align-items: center; font-size: 13px; }
.source-menu input[type="checkbox"] { width: 16px; height: 16px; }
main { padding: 20px 28px 36px; max-width: 1440px; margin: 0 auto; }
.status {
border: 1px solid var(--line);
background: var(--panel);
padding: 12px;
border-radius: 8px;
margin-bottom: 14px;
color: var(--muted);
}
.summary {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
margin-bottom: 14px;
}
.metric, .idea, .monitor, .source {
background: var(--panel);
border: 1px solid var(--line);
border-radius: 8px;
padding: 12px;
}
.metric span { color: var(--muted); font-size: 12px; display: block; }
.metric strong { font-size: 20px; display: block; margin-top: 6px; }
.tabs { display: flex; gap: 6px; flex-wrap: wrap; border-bottom: 1px solid var(--line); }
.tab {
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
border-bottom-color: transparent;
}
.tab.active { background: var(--accent-2); border-color: var(--accent-2); color: #fff; }
.panel { display: none; padding-top: 14px; }
.panel.active { display: block; }
.table-scroll {
width: 100%;
overflow-x: auto;
border: 1px solid var(--line);
border-radius: 8px;
margin-bottom: 16px;
background: var(--panel);
}
table {
width: 100%;
min-width: 640px;
border-collapse: collapse;
background: var(--panel);
}
th, td {
border-bottom: 1px solid var(--line);
text-align: left;
padding: 9px 10px;
font-size: 13px;
vertical-align: top;
}
th { color: var(--muted); font-weight: 700; background: #fbfcfe; }
tr:last-child td { border-bottom: 0; }
.grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
.demo-gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 12px;
margin-bottom: 14px;
}
.demo-card, .story-card, .judge-card {
background: var(--panel);
border: 1px solid var(--line);
border-radius: 8px;
padding: 12px;
}
.demo-card h3, .story-card h3, .judge-card h3 { margin: 0 0 6px; font-size: 15px; }
.progress-strip {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(92px, 1fr));
gap: 8px;
margin: 12px 0 16px;
}
.progress-stage {
background: var(--panel);
border: 1px solid var(--line);
border-radius: 8px;
padding: 9px;
min-height: 72px;
}
.progress-stage strong { display: block; font-size: 12px; }
.progress-stage span { color: var(--muted); font-size: 12px; }
.story-grid, .judge-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
.idea { margin-bottom: 12px; }
.idea-head { display: flex; justify-content: space-between; gap: 12px; }
.outcome-form {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 9px;
margin-top: 10px;
padding: 10px;
border: 1px solid var(--line);
border-radius: 8px;
background: #fbfcfe;
}
.outcome-form label {
display: grid;
gap: 4px;
color: var(--muted);
font-size: 12px;
font-weight: 600;
}
.outcome-form input, .outcome-form select, .outcome-form textarea { width: 100%; }
.outcome-form .full, .outcome-form .outcome-status { grid-column: 1 / -1; }
.pill {
display: inline-flex;
align-items: center;
min-height: 24px;
border-radius: 999px;
padding: 2px 9px;
background: #e8f3ef;
color: var(--accent);
font-size: 12px;
font-weight: 700;
white-space: nowrap;
}
.pill.warn { background: #fff4df; color: var(--warn); }
.pill.bad { background: #fde8ec; color: var(--bad); }
pre {
white-space: pre-wrap;
background: #101820;
color: #f2f5f8;
padding: 16px;
border-radius: 8px;
overflow: auto;
line-height: 1.45;
}
.muted { color: var(--muted); }
@media (max-width: 900px) {
header { align-items: stretch; flex-direction: column; }
.summary, .grid { grid-template-columns: 1fr; }
}
@media (max-width: 560px) {
header { padding: 14px 16px; }
main { padding: 16px; }
.controls { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); }
.controls #ticker, .controls details { grid-column: 1 / -1; width: 100%; }
.controls details summary { width: 100%; }
input { min-width: 0; width: 100%; }
button { padding: 0 10px; }
.metric strong { font-size: 18px; }
}
</style>
</head>
<body>
<header>
<h1>US Equity Research Radar</h1>
<div class="controls">
<input id="ticker" value="AAPL" aria-label="Ticker" />
<select id="research-profile" aria-label="Research profile">
<option value="fast_screening">Fast Screening</option>
<option value="adaptive_ic" selected>Adaptive IC Research</option>
<option value="deep_initiation">Deep Initiation</option>
</select>
<select id="event-investigation" aria-label="Event investigation"><option value="">Investigate event...</option></select>
<button id="investigate-event">Investigate This Event</button>
<details class="sources">
<summary>Data Sources</summary>
<div class="source-menu">
<label>Alpha Vantage API key<input id="alpha-key" type="password" autocomplete="off" /></label>
<label>Finnhub API key<input id="finnhub-key" type="password" autocomplete="off" /></label>
<label>FMP API key<input id="fmp-key" type="password" autocomplete="off" /></label>
<label>Tiingo API key<input id="tiingo-key" type="password" autocomplete="off" /></label>
<label>EODHD API key<input id="eodhd-key" type="password" autocomplete="off" title="Recent adjusted EOD prices, event windows, peer reactions, and market-implied expectations" /></label>
<label>FRED API key<input id="fred-key" type="password" autocomplete="off" /></label>
<label>BEA API key<input id="bea-key" type="password" autocomplete="off" /></label>
<label>Census API key<input id="census-key" type="password" autocomplete="off" /></label>
<label>Wisburg API key<input id="wisburg-key" type="password" autocomplete="off" /></label>
<label>SEC user agent<input id="sec-user-agent" autocomplete="off" /></label>
<label>Budget mode<select id="budget-mode"><option>Free</option><option selected>Lean</option><option>Stable</option><option>Premium</option></select></label>
<label>Primary LLM<select id="llm-primary"></select></label>
<label>Secondary reader<select id="llm-secondary"></select></label>
<label>Secondary minimum stage<select id="llm-secondary-min-stage"><option>Research-Ready</option><option>High-Conviction</option></select></label>
<label>Language policy<select id="llm-language-policy"><option value="bilingual_audit">Bilingual audit</option><option value="english_only">English only</option></select></label>
<label class="check"><input id="enable-llm" type="checkbox" />LLM thesis synthesis</label>
<label class="check"><input id="enable-secondary-llm" type="checkbox" checked />Secondary review for Research-Ready+</label>
<details>
<summary>LLM Provider Vault</summary>
<label>Provider preset<select id="llm-profile-preset"></select></label>
<label>Profile name<input id="llm-profile-name" value="DeepSeek primary" autocomplete="off" /></label>
<label>Model<input id="llm-profile-model" value="deepseek-v4-pro" autocomplete="off" /></label>
<label>Base URL<input id="llm-profile-base-url" value="https://api.deepseek.com" autocomplete="off" /></label>
<label>API key<input id="llm-profile-api-key" type="password" autocomplete="off" /></label>
<div class="grid">
<button type="button" id="save-llm-profile">Save LLM Profile</button>
<button type="button" id="test-llm-profile">Test Profile</button>
</div>
<button type="button" id="delete-llm-profile">Delete Selected LLM Profile</button>
<div id="llm-profile-status" class="muted">Loading LLM profiles...</div>
</details>
<label class="check"><input id="enable-nasdaq" type="checkbox" />Nasdaq estimates (unofficial)</label>
<label class="check"><input id="enable-tradingview" type="checkbox" />TradingView targets (unofficial)</label>
<label class="check"><input id="enable-default-macro" type="checkbox" checked />Default official macro sources</label>
<label class="check"><input id="global-macro-mode" type="checkbox" />Global macro mode</label>
<label class="check"><input id="enable-gdelt" type="checkbox" />GDELT narrative saturation</label>
<label class="check"><input id="enable-wisburg" type="checkbox" />Wisburg external research</label>
<label class="check"><input id="refresh-macro-cache" type="checkbox" />Refresh macro cache</label>
<div class="grid">
<button type="button" id="test-keys">Test Keys</button>
<button type="button" id="save-keys">Save Valid Keys</button>
</div>
<button type="button" id="clear-keys">Clear Saved Keys</button>
<div id="secret-status" class="muted">Checking saved key status...</div>
</div>
</details>
<button class="primary" id="run">Run Research</button>
<button id="demo">Demo</button>
</div>
</header>
<main>
<section id="demo-gallery" class="demo-gallery"></section>
<div id="status" class="status">Enter a US ticker and run the workflow.</div>
<section id="summary" class="summary"></section>
<nav class="tabs" id="tabs"></nav>
<section id="content"></section>
</main>
<script>
const tabs = [
"IC Story",
"Evidence Trail",
"Causal Bridge",
"Market & Expectations",
"Work Orders",
"Raw Data"
];
let activeTab = tabs[0];
let current = null;
let llmProfiles = [];
let llmPresets = [];
let llmSelection = {};
document.getElementById("run").addEventListener("click", () => load(false, false));
document.getElementById("investigate-event").addEventListener("click", () => load(false, true));
document.getElementById("demo").addEventListener("click", () => load(true));
document.getElementById("test-keys").addEventListener("click", testKeys);
document.getElementById("save-keys").addEventListener("click", saveKeys);
document.getElementById("clear-keys").addEventListener("click", clearKeys);
document.getElementById("save-llm-profile").addEventListener("click", saveLlmProfile);
document.getElementById("test-llm-profile").addEventListener("click", testLlmProfile);
document.getElementById("delete-llm-profile").addEventListener("click", deleteLlmProfile);
loadSecretStatus();
loadLlmProfiles();
loadBudgetModes();
loadDemoCases();
function esc(value) {
return String(value ?? "").replace(/[&<>"']/g, c => ({
"&": "&", "<": "<", ">": ">", '"': """, "'": "'"
}[c]));
}
async function load(demo, investigateEvent = false) {
const ticker = document.getElementById("ticker").value.trim().toUpperCase() || "AAPL";
if (investigateEvent && !document.getElementById("event-investigation").value) {
setStatus("Select a detected event before running an event investigation.");
return;
}
setStatus(demo ? "Loading demo workflow..." : `Running live workflow for ${ticker}...`);
try {
const response = demo
? await fetch(`/api/demo?ticker=${ticker}`)
: await fetch("/api/research", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({
ticker,
research_profile: investigateEvent ? "investigate_event" : document.getElementById("research-profile").value,
investigate_event_id: investigateEvent ? document.getElementById("event-investigation").value : "",
alpha_vantage_key: document.getElementById("alpha-key").value,
finnhub_key: document.getElementById("finnhub-key").value,
fmp_key: document.getElementById("fmp-key").value,
tiingo_key: document.getElementById("tiingo-key").value,
eodhd_key: document.getElementById("eodhd-key").value,
fred_key: document.getElementById("fred-key").value,
bea_key: document.getElementById("bea-key").value,
census_key: document.getElementById("census-key").value,
wisburg_key: document.getElementById("wisburg-key").value,
sec_user_agent: document.getElementById("sec-user-agent").value,
budget_mode: document.getElementById("budget-mode").value,
enable_llm: document.getElementById("enable-llm").checked,
primary_llm_profile_id: document.getElementById("llm-primary").value,
secondary_llm_profile_id: document.getElementById("llm-secondary").value,
enable_secondary_llm: document.getElementById("enable-secondary-llm").checked,
secondary_llm_min_stage: document.getElementById("llm-secondary-min-stage").value,
llm_language_policy: document.getElementById("llm-language-policy").value,
enable_nasdaq: document.getElementById("enable-nasdaq").checked,
enable_tradingview: document.getElementById("enable-tradingview").checked,
enable_default_macro: document.getElementById("enable-default-macro").checked,
global_macro_mode: document.getElementById("global-macro-mode").checked,
enable_gdelt: document.getElementById("enable-gdelt").checked,
enable_wisburg: document.getElementById("enable-wisburg").checked,
refresh_macro_cache: document.getElementById("refresh-macro-cache").checked,
fallback: true
})
});
const payload = await parseJsonResponse(response);
if (!response.ok && !payload.result) throw new Error(payload.error || "Research failed");
current = payload.result;
await hydrateDailySnapshotContext();
render(payload.warning || `Loaded ${current.identity.ticker}.`);
} catch (error) {
setStatus(error.message);
}
}
async function loadDemoCases() {
try {
const response = await fetch("/api/demo-cases");
const payload = await parseJsonResponse(response);
const target = document.getElementById("demo-gallery");
const cases = payload.demo_cases || [];
target.innerHTML = cases.map(item => `
<article class="demo-card">
<h3>${esc(item.title)}</h3>
<p class="muted">${esc(item.lesson)}</p>
<p><span class="pill">${esc(item.badge || "No API keys")}</span> <span class="pill warn">${esc(item.expected_runtime || "Instant")}</span> <span class="pill">${esc(item.content_version || "Current")}</span></p>
<p class="muted">${esc(item.research_profile || "Current profile")} · ${esc(item.budget_mode || "Current budget")}</p>
<p class="muted">${esc((item.enabled_layers || []).join(" · "))}</p>
<p class="muted">Refreshed ${esc(item.refreshed_at || "Unknown")}</p>
<button type="button" data-demo-ticker="${esc(item.ticker)}">Load demo</button>
</article>
`).join("");
target.querySelectorAll("[data-demo-ticker]").forEach(button => {
button.addEventListener("click", () => {
document.getElementById("ticker").value = button.dataset.demoTicker || "AAPL";
load(true);
});
});
} catch (error) {
document.getElementById("demo-gallery").innerHTML = "";
}
}
async function hydrateDailySnapshotContext() {
if (!current || !current.identity || !current.identity.ticker) return;
const ticker = encodeURIComponent(current.identity.ticker);
try {
const [snapshotResponse, deltaResponse] = await Promise.all([
fetch(`/api/snapshot-status?ticker=${ticker}`),
fetch(`/api/wisburg-delta?ticker=${ticker}`)
]);
if (snapshotResponse.ok) {
const payload = await snapshotResponse.json();
current.daily_snapshot_status = payload.snapshot_status;
}
if (deltaResponse.ok) {
const payload = await deltaResponse.json();
current.wisburg_snapshot_delta = payload.wisburg_delta;
}
} catch (_error) {
current.daily_snapshot_status = current.daily_snapshot_status || null;
current.wisburg_snapshot_delta = current.wisburg_snapshot_delta || null;
}
}
async function loadBudgetModes() {
try {
const response = await fetch("/api/budget-modes");
const payload = await parseJsonResponse(response);
const modes = payload.modes || ["Free", "Lean", "Stable", "Premium"];
const select = document.getElementById("budget-mode");
const currentValue = select.value || "Lean";
select.innerHTML = modes.map(mode => `<option ${mode === currentValue ? "selected" : ""}>${esc(mode)}</option>`).join("");
if (!modes.includes(currentValue) && modes.includes("Lean")) select.value = "Lean";
} catch (error) {
// Static fallback remains usable.
}
}
function enteredSecrets() {
return {
ALPHAVANTAGE_API_KEY: document.getElementById("alpha-key").value,
FINNHUB_API_KEY: document.getElementById("finnhub-key").value,
FMP_API_KEY: document.getElementById("fmp-key").value,
FRED_API_KEY: document.getElementById("fred-key").value,
BEA_API_KEY: document.getElementById("bea-key").value,
CENSUS_API_KEY: document.getElementById("census-key").value,
WISBURG_API_KEY: document.getElementById("wisburg-key").value,
TIINGO_API_KEY: document.getElementById("tiingo-key").value,
EODHD_API_KEY: document.getElementById("eodhd-key").value,
SEC_USER_AGENT: document.getElementById("sec-user-agent").value
};
}
async function loadLlmProfiles() {
try {
const response = await fetch("/api/llm-profiles");
const payload = await parseJsonResponse(response);
llmProfiles = payload.profiles || [];
llmPresets = payload.presets || [];
llmSelection = payload.selection || {};
renderLlmControls();
} catch (error) {
document.getElementById("llm-profile-status").textContent = error.message;
}
}
function renderLlmControls() {
const presetSelect = document.getElementById("llm-profile-preset");
presetSelect.innerHTML = llmPresets.map(preset => `<option value="${esc(preset.preset_id)}">${esc(preset.label)}</option>`).join("");
presetSelect.value = "deepseek";
presetSelect.onchange = () => {
const preset = llmPresets.find(item => item.preset_id === presetSelect.value) || {};
document.getElementById("llm-profile-name").value = `${preset.label || presetSelect.value} primary`;
document.getElementById("llm-profile-model").value = preset.default_model || "";
document.getElementById("llm-profile-base-url").value = preset.default_base_url || "";
};
const options = [`<option value="">None</option>`].concat(llmProfiles.map(profile =>
`<option value="${esc(profile.profile_id)}">${esc(profile.display_name)} (${esc(profile.provider_preset)}, ${esc(profile.model)})${profile.key_configured ? " - key saved" : " - no key"}</option>`
)).join("");
document.getElementById("llm-primary").innerHTML = options;
document.getElementById("llm-secondary").innerHTML = options;
const fallbackPrimary = (llmProfiles.find(profile => profile.key_configured) || llmProfiles[0] || {}).profile_id || "";
document.getElementById("llm-primary").value = llmSelection.primary_profile_id || fallbackPrimary;
document.getElementById("llm-secondary").value = llmSelection.secondary_profile_id || "";
document.getElementById("enable-secondary-llm").checked = llmSelection.enable_secondary !== false;
document.getElementById("llm-secondary-min-stage").value = llmSelection.secondary_min_stage || "Research-Ready";
document.getElementById("llm-language-policy").value = llmSelection.language_policy || "bilingual_audit";
document.getElementById("llm-profile-status").textContent = `${llmProfiles.length} saved LLM profile(s).`;
}
function llmProfilePayload() {
return {
display_name: document.getElementById("llm-profile-name").value,
provider_preset: document.getElementById("llm-profile-preset").value,
model: document.getElementById("llm-profile-model").value,
base_url: document.getElementById("llm-profile-base-url").value,
api_key: document.getElementById("llm-profile-api-key").value
};
}
async function saveLlmProfile() {
const response = await fetch("/api/llm-profiles", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(llmProfilePayload())
});
const payload = await parseJsonResponse(response);
if (!response.ok) throw new Error(payload.error || "Could not save profile");
document.getElementById("llm-profile-api-key").value = "";
await loadLlmProfiles();
}
async function testLlmProfile() {
const response = await fetch("/api/llm-profiles/test", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(llmProfilePayload())
});
const payload = await parseJsonResponse(response);
document.getElementById("llm-profile-status").textContent = `${payload.status?.status || "unknown"}: ${payload.status?.message || ""}`;
}
async function deleteLlmProfile() {
const profileId = document.getElementById("llm-primary").value || document.getElementById("llm-secondary").value;
if (!profileId) return;
await fetch(`/api/llm-profiles/${encodeURIComponent(profileId)}`, {method: "DELETE"});
await loadLlmProfiles();
}
async function loadSecretStatus() {
try {
const response = await fetch("/api/local-secrets/status");
const payload = await parseJsonResponse(response);
renderSecretStatus(payload.status || []);
} catch (error) {
document.getElementById("secret-status").textContent = error.message;
}
}
async function testKeys() {
setStatus("Testing provider keys...");
const response = await fetch("/api/local-secrets/test", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({keys: enteredSecrets()})
});
const payload = await parseJsonResponse(response);
document.getElementById("secret-status").textContent = (payload.results || [])
.map(item => `${item.label}: ${item.status}`)
.join(" | ") || "No keys entered.";
setStatus("Key test complete.");
}
async function saveKeys() {
setStatus("Testing and saving valid keys...");
const response = await fetch("/api/local-secrets/save", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({keys: enteredSecrets()})
});
const payload = await parseJsonResponse(response);
document.getElementById("secret-status").textContent =
`Saved ${payload.saved.length} key(s); skipped ${payload.skipped.length}.`;
await loadSecretStatus();
setStatus("Saved valid local keys. Restart if a running workflow captured old settings.");
}
async function clearKeys() {
const response = await fetch("/api/local-secrets", { method: "DELETE" });
await parseJsonResponse(response);
await loadSecretStatus();
setStatus("Cleared saved local keys.");
}
function renderSecretStatus(rows) {
const configured = rows.filter(item => item.configured && item.key !== "SEC_USER_AGENT").length;
const backend = rows.length
? (rows[0].backend_available ? `Secret storage ready (${rows[0].backend || "local"})` : "Secret storage unavailable")
: "No status";
document.getElementById("secret-status").textContent = `${configured} saved provider key(s). ${backend}.`;
}
async function parseJsonResponse(response) {
const contentType = response.headers.get("content-type") || "";
const text = await response.text();
if (!contentType.includes("application/json")) {
const preview = text.trim().slice(0, 80);
throw new Error(`Research API returned ${contentType || "unknown content"} instead of JSON. You may be connected to the Streamlit server or a stale port. Response starts: ${preview}`);
}
try {
return JSON.parse(text);
} catch (error) {
throw new Error(`Research API returned invalid JSON: ${error.message}`);
}
}
function setStatus(message) {
document.getElementById("status").textContent = message;
}
function render(message) {
setStatus(message);
renderEventInvestigationOptions();
renderSummary();
renderTabs();
renderContent();
}
function renderEventInvestigationOptions() {
const select = document.getElementById("event-investigation");
const rows = (current && current.events ? current.events : []).slice(0, 20);
select.innerHTML = '<option value="">Investigate event...</option>' + rows.map(item => {
const id = (item.metrics || {}).event_id || "";
const label = `${item.event_date || "Date unknown"} | ${item.title || "Untitled event"}`;
return `<option value="${esc(id)}">${esc(label)}</option>`;
}).join("");
}
function renderSummary() {
const identity = current.identity;
const top = current.ideas[0] || {};
const score = top.score ? `${top.score.total}/100` : "n/a";
const capture = top.market_capture ? top.market_capture.category : "Unknown";
const values = [
["Company", identity.name],
["Ticker / CIK", `${identity.ticker} / ${identity.cik}`],
["Top Idea Score", score],
["Market Capture", capture]
];
document.getElementById("summary").innerHTML = values.map(([label, value]) => `
<div class="metric"><span>${esc(label)}</span><strong>${esc(value)}</strong></div>
`).join("");
}
function renderTabs() {
document.getElementById("tabs").innerHTML = tabs.map(tab => `
<button class="tab ${tab === activeTab ? "active" : ""}" data-tab="${esc(tab)}">${esc(tab)}</button>
`).join("");
document.querySelectorAll(".tab").forEach(button => {
button.addEventListener("click", () => {
activeTab = button.dataset.tab;
renderTabs();
renderContent();
});
});
}
function renderContent() {
const target = document.getElementById("content");
if (activeTab === "IC Story") target.innerHTML = icCopilot();
if (activeTab === "Evidence Trail") target.innerHTML = researchRadar() + managementSources();
if (activeTab === "Causal Bridge") target.innerHTML = decisionModels() + ideaFactory() + ideaScorer();
if (activeTab === "Market & Expectations") target.innerHTML = earningsSurprisePanel() + marketImpliedPanel() + recentMarketContextPanel() + priceMoveAttribution();
if (activeTab === "Work Orders") target.innerHTML = evidenceClosurePanel() + thesisMonitor();
if (activeTab === "Raw Data") target.innerHTML = memoPack();
if (activeTab === "Causal Bridge") bindOutcomeForms();
if (activeTab === "Causal Bridge") bindPayoffAssumptionActions();
if (activeTab === "Work Orders") bindMonitorActions();
if (activeTab === "Market & Expectations") bindMarketImpliedActions();
}
function table(rows, columns) {
if (!rows.length) return `<p class="muted">No rows.</p>`;
return `<div class="table-scroll"><table><thead><tr>${columns.map(col => `<th>${esc(col[0])}</th>`).join("")}</tr></thead>
<tbody>${rows.map(row => `<tr>${columns.map(col => `<td>${esc(row[col[1]])}</td>`).join("")}</tr>`).join("")}</tbody></table></div>`;
}
function wisburgLensPanel() {
const lens = current.wisburg_lens || {};
const delta = current.wisburg_snapshot_delta || {};
const narrative = lens.narrative_score || {};
const debate = lens.debate_map || {};
const coverage = lens.coverage_audit || {};
const themes = (lens.themes || []).slice(0, 8).map(theme => ({
theme: theme.label,
stance: theme.stance,
driver: theme.driver,
evidence: theme.evidence_count,
language: (theme.source_language_mix || []).join(", ") || "n/a",
confidence: theme.confidence,
summary: theme.summary
}));
const suggestions = (lens.source_suggestions || []).slice(0, 8).map(item => ({
priority: item.priority,
type: item.source_type,
title: item.title,
reason: item.reason_to_inspect,
expected: item.expected_evidence_type,
checks: item.confirms_or_disproves
}));
const excerpts = (lens.excerpts || []).slice(0, 10).map(item => ({
title: item.title,
category: item.category,
language: item.source_language,
asof: item.source_as_of || "n/a",
themes: (item.theme_tags || []).join(", "),
target: item.mentions_target_or_rating ? item.non_consensus_label : "n/a",
excerpt: item.original_excerpt,
summary: item.translated_summary || item.generated_summary
}));
const caveats = (lens.caveats || []).map(item => ({ item }));
const entitlementRows = (coverage.tools || []).map(item => ({
tool: item.tool_name,
category: item.source_category,
entitlement: item.status,
queries: item.query_count,
items: item.item_count,
details: item.detail_success_count,
message: item.message
}));
const reports = (lens.reports || []).slice(0, 20).map(item => ({
report: item.title,
category: item.category,
publisher: item.publisher,
published: item.published_at || "Unknown",
language: item.source_language,
detail: item.detail_status,
scope: item.content_scope,
tier: item.source_tier
}));
const revisions = (lens.revisions || []).slice(0, 12).map(item => ({
asof: item.source_as_of || "Unknown",
type: item.revision_type,
metric: item.metric,
direction: item.direction,
prior: item.previous_value ?? "Unknown",
current: item.current_value ?? "Unknown",
change: item.change_pct ?? "Unknown",
period: item.fiscal_period || "Unknown",
eligibility: item.eligibility,
statement: item.statement
}));
const claims = (lens.structured_claims || []).slice(0, 20).map(item => ({
claim: item.statement,
type: item.claim_type,
driver: item.driver,
metric: item.metric || "Unknown",
period: item.fiscal_period || "Unknown",
tier: item.source_tier,
check: item.corroboration_status,
primary: (item.primary_evidence_ids || []).length,
stage: item.allowed_stage
}));
const tasks = (lens.research_tasks || []).slice(0, 16).map(item => ({
priority: item.priority,
type: item.source_type,
action: item.action,
expected: item.expected_evidence,
checks: item.confirms_or_disproves,
status: item.status
}));
return `<h3>Outside Analyst Debate</h3>
<p class="muted">Wisburg is used for outside-analyst debate, narrative crowding, and source suggestions. It cannot independently promote an idea to Research-Ready or High-Conviction.</p>
<div class="summary">
<div class="metric"><span>Wisburg Lens</span><strong>${esc(lens.status || "Unavailable")}</strong></div>
<div class="metric"><span>Research Excerpts</span><strong>${esc((lens.excerpts || []).length)}</strong></div>
<div class="metric"><span>Themes</span><strong>${esc((lens.themes || []).length)}</strong></div>
<div class="metric"><span>Narrative</span><strong>${esc(narrative.label || "Unknown")}</strong></div>
</div>
${coverage.status ? `<details><summary>Wisburg entitlement and coverage audit</summary>
<p>${esc(coverage.status)}. Authentication: ${esc(coverage.authentication_status || "Unknown")}; tool discovery: ${esc(coverage.tool_discovery_status || "Unknown")}; observed items: ${esc(coverage.total_items || 0)}; structured details: ${esc(coverage.detailed_items || 0)}.</p>
${table(entitlementRows, [["Tool", "tool"], ["Category", "category"], ["Entitlement", "entitlement"], ["Queries", "queries"], ["Items", "items"], ["Details", "details"], ["Message", "message"]])}
<h3>Normalized report coverage</h3>${table(reports, [["Report", "report"], ["Category", "category"], ["Publisher", "publisher"], ["Published", "published"], ["Language", "language"], ["Detail status", "detail"], ["Stored scope", "scope"], ["Tier", "tier"]])}</details>` : ""}
${delta.status ? `<h3>Point-in-Time Wisburg Change</h3><p>${esc(delta.summary || "")}</p>
<p class="muted">Status: ${esc(delta.status)}; current: ${esc(delta.observed_at || "Unknown")}; prior: ${esc(delta.prior_observed_at || "First baseline")}; newly observed reports: ${esc((delta.new_report_ids || []).length)}; stance changes: ${esc((delta.theme_stance_changes || []).length)}; external revisions: ${esc((delta.new_revision_ids || []).length)}; corroboration changes: ${esc((delta.corroboration_changes || []).length)}. This covers the capped result set only.</p>` : ""}
<p class="muted">Debate: ${esc(debate.status || "Unavailable")}; bull: ${esc(debate.strongest_bull_case || "n/a")}; bear: ${esc(debate.strongest_bear_case || "n/a")}. Narrative score: ${esc(narrative.score ?? "n/a")}; topics: ${esc((narrative.repeated_topics || []).join(", ") || "n/a")}.</p>
<h3>External Revision Observations</h3><p class="muted">Report-level analyst context only; never official consensus or standalone promotion evidence.</p>
${table(revisions, [["As of", "asof"], ["Type", "type"], ["Metric", "metric"], ["Direction", "direction"], ["Previous", "prior"], ["Current", "current"], ["Change %", "change"], ["Period", "period"], ["Eligibility", "eligibility"], ["Statement", "statement"]])}
<h3>Structured Claims and Primary-Source Cross-Check</h3>
${table(claims, [["Claim", "claim"], ["Type", "type"], ["Driver", "driver"], ["Metric", "metric"], ["Period", "period"], ["Tier", "tier"], ["Cross-check", "check"], ["Primary matches", "primary"], ["Allowed stage", "stage"]])}
<h3>Executable Wisburg Research Work Orders</h3>
${table(tasks, [["Priority", "priority"], ["Source type", "type"], ["Action", "action"], ["Expected evidence", "expected"], ["Confirm/disprove", "checks"], ["Status", "status"]])}
${table(themes, [["Theme", "theme"], ["Stance", "stance"], ["Driver", "driver"], ["Evidence", "evidence"], ["Language", "language"], ["Confidence", "confidence"], ["Summary", "summary"]])}
<h3>Wisburg Source Suggestions</h3>${table(suggestions, [["Priority", "priority"], ["Source type", "type"], ["Title", "title"], ["Why inspect", "reason"], ["Expected evidence", "expected"], ["Confirm/disprove", "checks"]])}
<h3>Capped Wisburg Excerpts</h3>${table(excerpts, [["Title", "title"], ["Category", "category"], ["Language", "language"], ["As of", "asof"], ["Themes", "themes"], ["Target/rating", "target"], ["Excerpt", "excerpt"], ["Summary", "summary"]])}
${table(caveats, [["External research caveat", "item"]])}`;
}
function storyFirstPanel() {
const brief = current.thesis_brief || {};
const onePager = current.ic_one_pager || {};
const demo = current.demo_case || {};
const progress = current.run_progress || {};
const judge = current.bull_bear_judge || {};
const cards = current.story_cards || [];
const traces = current.formula_traces || [];
const profile = current.research_profile || {};
const historyPack = current.historical_research || {};
const profilePanel = profile.label ? `<h3>Research Profile</h3><div class="summary">
<div class="metric"><span>Profile</span><strong>${esc(profile.label)}</strong></div>
<div class="metric"><span>Quarter History</span><strong>${esc(historyPack.analyzed_quarters || 0)}/${esc(historyPack.requested_quarters || profile.quarter_depth || 0)}</strong></div>
<div class="metric"><span>Annual History</span><strong>${esc(historyPack.analyzed_annual_reports || 0)}/${esc(historyPack.requested_annual_reports || profile.annual_depth || 0)}</strong></div>
<div class="metric"><span>Call History</span><strong>${esc(historyPack.analyzed_calls || 0)}/${esc(historyPack.requested_calls || profile.call_depth || 0)}</strong></div>
</div><p class="muted">Adaptive deepening: ${esc((historyPack.adaptive_deepening_reasons || []).join(", ") || "not triggered")}.</p>` : "";
const demoBanner = demo.title ? `<div class="status"><strong>Demo:</strong> ${esc(demo.title)}. ${esc(demo.lesson || "")} Runtime: ${esc(demo.expected_runtime || "Instant")}; network: ${demo.network_required ? "yes" : "no"}.</div>` : "";
const pipeline = progress.stages ? `<h3>Research Pipeline</h3><p class="muted">${esc(progress.summary || "")}</p><div class="progress-strip">${progress.stages.map(stage => `
<details class="progress-stage">
<summary><strong>${esc(stage.label)}</strong><span>${esc(stage.status)}</span></summary>
<p>${esc(stage.summary || "")}</p>
${table((stage.blockers || []).map(item => ({item})), [["Blocker", "item"]])}
${stage.next_action ? `<p class="muted">Next: ${esc(stage.next_action)}</p>` : ""}
</details>
`).join("")}</div>` : "";
const storyCards = `<h3>Story Cards</h3><div class="story-grid">${cards.map(card => `
<article class="story-card">
<h3>${esc(card.title)}</h3>
<p class="muted">${esc(card.status || "")}</p>
<p>${esc(card.body || card.summary || "")}</p>
${card.next_action ? `<p class="muted"><strong>Next:</strong> ${esc(card.next_action)}</p>` : ""}
${(card.evidence || []).length ? `<details><summary>Show evidence</summary>${table((card.evidence || []).map(item => ({
claim: item.claim,
source: item.source || "Unknown",
section: item.section || "Unknown",
metric: item.metric || "n/a",
value: item.value || "n/a",
formula: item.formula || "n/a",
period: item.period || "Unknown",
confidence: item.confidence || "Unknown",
excerpt: item.excerpt || ""
})), [["Claim", "claim"], ["Source", "source"], ["Section", "section"], ["Metric", "metric"], ["Value", "value"], ["Formula", "formula"], ["Period", "period"], ["Confidence", "confidence"], ["Excerpt", "excerpt"]])}</details>` : ""}
</article>
`).join("")}</div>`;
const judgePanel = `<h3>Bull / Bear / Judge</h3><div class="judge-grid">
<article class="judge-card"><h3>Bull case</h3><p>${esc(judge.bull_case || "n/a")}</p></article>
<article class="judge-card"><h3>Bear case</h3><p>${esc(judge.bear_case || "n/a")}</p></article>
<article class="judge-card"><h3>Judge accepts</h3>${table((judge.judge_accepts || []).slice(0, 6).map(item => ({item})), [["Accepted claim", "item"]])}</article>
<article class="judge-card"><h3>Still unproven</h3>${table((judge.still_unproven || []).slice(0, 8).map(item => ({item})), [["Open item", "item"]])}</article>
</div>${(judge.resolution_plan || []).length ? `<h3>Resolution Plan</h3>${table((judge.resolution_plan || []).map(item => ({
type: item.issue_type,
status: item.status,
issue: item.issue,
evidence: item.evidence,
app: item.app_action,
user: item.user_action,
blocks: item.blocking_scope,
automatic: item.auto_resolvable ? "Yes" : "No"
})), [["Type", "type"], ["Status", "status"], ["What it means", "issue"], ["Triggering evidence", "evidence"], ["App action", "app"], ["User action", "user"], ["Blocks", "blocks"], ["Automatic", "automatic"]])}` : ""}`;
const formulas = `<details><summary>Formula transparency</summary>${table(traces.slice(0, 30).map(item => ({
label: item.label,
value: item.value,
sourceField: item.source_field,
formula: item.formula,
period: item.period || "Unknown",
currency: item.currency || "Unknown",
confidence: item.confidence,
source: item.source
})), [["Label", "label"], ["Value", "value"], ["Source field", "sourceField"], ["Formula", "formula"], ["Period", "period"], ["Currency", "currency"], ["Confidence", "confidence"], ["Source", "source"]])}</details>`;
const playbook = ((current.company_economics || {}).industry_playbook || {});
const missingMetrics = ((current.metric_resolution_audit || {}).items || []).filter(item => item.status === "metric missing");
const sourceGaps = ((current.source_coverage_matrix || {}).entries || []).filter(item => ["source unavailable", "source not attempted", "parse failed"].includes(item.status));
const contributorRows = [
{item: "Sector playbook", status: playbook.playbook_source ? "Existing / reviewable" : "Draft needed", app: `Prefill ${(playbook.key_kpis || []).length} KPI(s), ${(playbook.leading_indicators || []).length} indicator(s), valuation methods, catalysts, and a fixture specification.`},
{item: "ADR profile", status: ((current.entity_resolution || {}).reporting_forms || []).some(form => ["20-F", "40-F", "6-K"].includes(form)) ? "Applicable" : "Not currently indicated", app: "Prefill identity, reporting forms, currency, exchange, and source priorities from resolved entity metadata."},
{item: "Metric aliases", status: `${missingMetrics.length} unresolved metric(s)`, app: "Draft canonical alias rows with source tag, period, unit, and required expected-value fixture."},
{item: "Source adapters", status: `${sourceGaps.length} source gap(s)`, app: "Draft provider-health, citation, licensing, deterministic-validation, and no-network fixture contracts."},
{item: "Demo case", status: "Draft ready", app: `Prefill a sanitized ${current.identity ? current.identity.ticker : "ticker"} lesson and no-network regression requirement.`}
];
const contributor = `<details><summary>Improve this project</summary>
<p class="muted">The app pre-diagnoses contribution opportunities from this run. Authoritative configs and executable adapters still require review and fixture coverage.</p>
${table(contributorRows, [["Contribution", "item"], ["Status", "status"], ["What the app can prepare", "app"]])}
</details>`;
const implied = current.market_implied_expectations || {};
const impliedRows = implied.expectations || [];
const reverseBase = impliedRows.find(item => item.metric === "Reverse DCF base FCF");
const reverseGrowth = impliedRows.find(item =>
(item.metric || "").startsWith("Reverse DCF: implied") &&
(item.metric || "").includes("FCF growth") &&
item.implied_value != null
) || impliedRows.find(item =>
(item.metric || "").startsWith("Reverse DCF: implied") &&
item.implied_value != null
);
const fcfYield = impliedRows.find(item => item.metric === "Current free-cash-flow yield");
const reverseLabel = reverseGrowth && (reverseGrowth.metric || "").toLowerCase().includes("margin")
? "Price-implied FCF margin"
: "Price-implied FCF growth";
const reverseSnapshot = implied.template === "Non-financial" ? `<h3>Reverse FCF / DCF Snapshot</h3>
<div class="summary">
<div class="metric"><span>FCF base</span><strong>${reverseBase && reverseBase.implied_value != null ? `${number(reverseBase.implied_value)} ${esc(reverseBase.unit)}` : "Unavailable"}</strong></div>
<div class="metric"><span>Current FCF yield</span><strong>${fcfYield && fcfYield.implied_value != null ? `${number(fcfYield.implied_value)} ${esc(fcfYield.unit)}` : "Unavailable"}</strong></div>
<div class="metric"><span>${reverseLabel}</span><strong>${reverseGrowth && reverseGrowth.implied_value != null ? `${number(reverseGrowth.implied_value)} ${esc(reverseGrowth.unit)}` : "Unavailable"}</strong></div>
<div class="metric"><span>Confidence</span><strong>${esc(reverseGrowth ? reverseGrowth.confidence : "Unavailable")}</strong></div>
</div>
<p class="muted">${esc(reverseGrowth ? reverseGrowth.interpretation : "Open Market & Expectations for exact missing reverse-DCF inputs.")}</p>
${reverseBase ? '<p class="muted"><strong>FCF basis:</strong> ' + esc(reverseBase.status) + '. ' + esc(reverseBase.formula) + '. ' + esc(reverseBase.interpretation) + '</p>' : ""}` : "";
return `${demoBanner}<h2>IC Story</h2>
<div class="summary">
<div class="metric"><span>Verdict</span><strong>${esc(onePager.verdict || brief.verdict || "n/a")}</strong></div>
<div class="metric"><span>Stage</span><strong>${esc(onePager.stage || brief.stage || "n/a")}</strong></div>
<div class="metric"><span>Direction</span><strong>${esc(onePager.direction || brief.direction || "n/a")}</strong></div>
<div class="metric"><span>Decision</span><strong>${esc(onePager.decision || "Research next")}</strong></div>
</div>
<p>${esc(onePager.thesis || brief.thesis || "No thesis generated.")}</p>
${onePager.next_best_action ? `<div class="status"><strong>Next action:</strong> ${esc(onePager.next_best_action)}</div>` : ""}
${reverseSnapshot}${profilePanel}${pipeline}${storyCards}${judgePanel}${formulas}${contributor}`;
}
function icCopilot() {
const brief = current.thesis_brief || {};
const onePager = current.ic_one_pager || {};
const critique = current.thesis_critique || {};
const sufficiency = current.evidence_sufficiency || {};
const manifest = current.llm_run_manifest || {};