solwatch 0.1.18

Real-data Solana memecoin auditor โ€” rug/freeze/bundle scanner with a 0-100 risk score, plain-English flags, and a live dashboard. Sister tool to Hoodwatch.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
//! Report renderers (text / markdown / tweet / rokha_app / self-contained
//! HTML) + a durable report store (writes .md + .json artifacts and an
//! index; the .html sibling is opt-in).

use crate::types::{AuditResult, Verdict};
use anyhow::Result;
use serde_json::json;
use std::fs;
use std::path::{Path, PathBuf};

/// The live dashboard UI โ€” also the template for the static per-audit HTML
/// artifact (same pixels, data baked in, zero network).
pub const DASHBOARD_HTML: &str = include_str!("dashboard.html");

fn verdict_str(v: Verdict) -> &'static str {
    match v {
        Verdict::Avoid => "AVOID",
        Verdict::HighRisk => "HIGH RISK",
        Verdict::Caution => "CAUTION",
        Verdict::Fair => "FAIR",
        Verdict::LowRisk => "LOW RISK",
        Verdict::Unknown => "UNKNOWN",
    }
}

fn verdict_emoji(v: Verdict) -> &'static str {
    match v {
        Verdict::Avoid => "๐Ÿ”ด",
        Verdict::HighRisk => "๐ŸŸ ",
        Verdict::Caution => "๐ŸŸก",
        Verdict::Fair => "๐ŸŸข",
        Verdict::LowRisk => "โœ…",
        Verdict::Unknown => "โšช",
    }
}

fn sev_emoji(s: crate::types::Severity) -> &'static str {
    use crate::types::Severity::*;
    match s {
        Critical => "๐Ÿ›‘",
        Danger => "๐Ÿ”ด",
        Warning => "โš ๏ธ",
        Info => "โ„น๏ธ",
        Good => "โœ…",
    }
}

fn usd(n: Option<f64>) -> String {
    match n {
        None => "โ€”".into(),
        Some(v) => {
            let int = v.round() as i64;
            let digits = int.abs().to_string();
            let mut s = String::new();
            for (i, c) in digits.chars().enumerate() {
                if i > 0 && (digits.len() - i) % 3 == 0 {
                    s.push(',');
                }
                s.push(c);
            }
            format!("${s}")
        }
    }
}

pub fn render_text(r: &AuditResult) -> String {
    let mut l = vec![];
    l.push(format!(
        "Solwatch audit โ€” {} ({})",
        r.token.symbol.clone().unwrap_or_else(|| "?".into()),
        r.token.name.clone().unwrap_or_else(|| "unknown".into())
    ));
    l.push(format!("  {}  ยท  Solana", r.address));
    l.push(format!(
        "  {} {}   score {}/100",
        verdict_emoji(r.verdict),
        verdict_str(r.verdict),
        r.score
    ));
    l.push(format!(
        "  mcap {}  ยท  24h vol {}  ยท  holders {}{}",
        usd(r.token.market_cap_usd),
        usd(r.token.volume_24h_usd),
        r.token
            .holders_count
            .map(|h| h.to_string())
            .unwrap_or_else(|| "โ€”".into()),
        r.token
            .launchpad
            .as_ref()
            .map(|l| format!("  ยท  via {l}"))
            .unwrap_or_default()
    ));
    l.push(String::new());
    l.push("  Flags:".into());
    for f in &r.flags {
        l.push(format!(
            "    {} {} โ€” {}",
            sev_emoji(f.severity),
            f.title,
            f.detail
        ));
    }
    if !r.coverage_gaps.is_empty() {
        l.push(String::new());
        l.push(format!(
            "  โš  INCOMPLETE SCAN โ€” affected checks did NOT run; unknown โ‰  safe: {}",
            r.coverage_gaps.join("; ")
        ));
    }
    if !r.warnings.is_empty() {
        l.push(String::new());
        l.push(format!("  Notes: {}", r.warnings.join("; ")));
    }
    l.push(String::new());
    if let Some(u) = &r.rokha_url {
        l.push(format!("  View in Rokha: {u}"));
    }
    l.push(format!("  scanned {}", r.scanned_at));
    l.join("\n")
}

pub fn render_markdown(r: &AuditResult) -> String {
    let mut l = vec![];
    l.push(format!(
        "# {} {} โ€” {} ({}/100)",
        verdict_emoji(r.verdict),
        r.token.symbol.clone().unwrap_or_else(|| "?".into()),
        verdict_str(r.verdict),
        r.score
    ));
    l.push(String::new());
    l.push(format!(
        "**{}** ยท `{}` ยท Solana{}",
        r.token
            .name
            .clone()
            .unwrap_or_else(|| "Unknown token".into()),
        r.address,
        r.token
            .launchpad
            .as_ref()
            .map(|lp| format!(" ยท launched via {lp}"))
            .unwrap_or_default()
    ));
    l.push(String::new());
    l.push("| Market cap | 24h volume | Holders | Scanned |".into());
    l.push("|---|---|---|---|".into());
    l.push(format!(
        "| {} | {} | {} | {} |",
        usd(r.token.market_cap_usd),
        usd(r.token.volume_24h_usd),
        r.token
            .holders_count
            .map(|h| h.to_string())
            .unwrap_or_else(|| "โ€”".into()),
        r.scanned_at[..r.scanned_at.len().min(16)].replace('T', " ")
    ));
    l.push(String::new());
    l.push("## Findings".into());
    l.push(String::new());
    for f in &r.flags {
        l.push(format!(
            "- {} **{}** โ€” {}",
            sev_emoji(f.severity),
            f.title,
            f.detail
        ));
    }
    if let Some(bu) = r.sections.get("bundles") {
        if bu
            .get("analyzed")
            .and_then(|v| v.as_bool())
            .unwrap_or(false)
        {
            l.push(String::new());
            l.push("## Launch window".into());
            l.push(format!(
                "{}% of supply sniped by {} wallets ({} in the exact creation slot); snipers still hold {}%. Dev allocation {}%.",
                bu.get("pctSupplySniped").map(|v| v.to_string()).unwrap_or_else(|| "โ€”".into()),
                bu.get("snipers").map(|v| v.to_string()).unwrap_or_else(|| "โ€”".into()),
                bu.get("sameSlotBuyers").map(|v| v.to_string()).unwrap_or_else(|| "โ€”".into()),
                bu.get("pctSnipersStillHold").map(|v| v.to_string()).unwrap_or_else(|| "โ€”".into()),
                bu.get("pctDevAllocation").map(|v| v.to_string()).unwrap_or_else(|| "โ€”".into()),
            ));
        }
    }
    if let Some(cl) = r
        .sections
        .pointer("/cluster/findings")
        .and_then(|v| v.as_array())
        .filter(|c| !c.is_empty())
    {
        l.push(String::new());
        l.push("## Linked wallets".into());
        l.push(String::new());
        // Every row states the evidence that produced it and how far that
        // evidence goes. `proven` means we read the transaction; `lead` means
        // we did not, and the row is printed anyway so nobody mistakes our
        // silence for a clean bill of health.
        l.push("| # | wallets | holds now | bought | evidence | confidence |".into());
        l.push("|---|---|---|---|---|---|".into());
        for (i, c) in cl.iter().enumerate() {
            let conf = c.get("confidence").and_then(|v| v.as_str()).unwrap_or("");
            l.push(format!(
                "| {} | {} | {}% | {} | {} | {} |",
                c.get("id").and_then(|v| v.as_u64()).unwrap_or(i as u64 + 1),
                c.get("wallets")
                    .and_then(|w| w.as_array())
                    .map(|w| w.len())
                    .unwrap_or(0),
                c.get("pct_combined")
                    .and_then(|v| v.as_f64())
                    .unwrap_or(0.0),
                c.get("pct_bought")
                    .and_then(|v| v.as_f64())
                    .map(|v| format!("{v}%"))
                    .unwrap_or_else(|| "โ€”".into()),
                c.get("evidence")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .replace('_', " "),
                match conf {
                    "proven" =>
                        if c.get("proof").map(|p| !p.is_null()).unwrap_or(false) {
                            "**proven** โšก Jito"
                        } else {
                            "**proven**"
                        },
                    "probable" => "probable",
                    "lead" => "_lead only_",
                    other => other,
                },
            ));
        }
        for c in cl {
            if let Some(n) = c.get("note").and_then(|v| v.as_str()) {
                l.push(format!("- {n}"));
            }
        }
        if let Some(ec) = r.sections.pointer("/cluster/effective_concentration") {
            if !ec.is_null() {
                l.push(String::new());
                l.push(format!(
                    "Entity top-10 is **at least {}%** (raw per-wallet: {}%); the largest single entity at least {}%. These are floors โ€” every link we did not find can only raise them.",
                    ec.get("top10_entity_pct_floor")
                        .and_then(|v| v.as_f64())
                        .unwrap_or(0.0),
                    ec.get("top10_raw_pct")
                        .and_then(|v| v.as_f64())
                        .unwrap_or(0.0),
                    ec.get("largest_entity_pct_floor")
                        .and_then(|v| v.as_f64())
                        .unwrap_or(0.0),
                ));
            }
        }
        // What this pass structurally CANNOT see, printed on every report โ€”
        // including the clean ones, where it matters most. A reader who does
        // not know the holder set stops at 20 wallets will read "no clusters
        // found" as "no clusters exist".
        if let Some(scope) = r.sections.pointer("/cluster/scope") {
            l.push(String::new());
            l.push(format!(
                "**How far this went** โ€” {} wallets examined ({} holders, {} launch buyers), {} funding hop(s), {} transaction(s) sampled for direct transfers. Coverage: **{}**.",
                scope.get("wallets_analyzed").and_then(|v| v.as_u64()).unwrap_or(0),
                scope.get("holders_analyzed").and_then(|v| v.as_u64()).unwrap_or(0),
                scope.get("snipers_analyzed").and_then(|v| v.as_u64()).unwrap_or(0),
                scope.get("funder_hops").and_then(|v| v.as_u64()).unwrap_or(0),
                scope.get("transfer_txs_sampled").and_then(|v| v.as_u64()).unwrap_or(0),
                scope.get("coverage").and_then(|v| v.as_str()).unwrap_or("unknown"),
            ));
            if let Some(limits) = scope.get("limits").and_then(|v| v.as_array()) {
                l.push(String::new());
                for lim in limits {
                    if let Some(s) = lim.as_str() {
                        l.push(format!("- {s}"));
                    }
                }
            }
            if let Some(n) = scope.get("note").and_then(|v| v.as_str()) {
                if !n.is_empty() {
                    l.push(format!("- {n}"));
                }
            }
        }
    }
    if !r.coverage_gaps.is_empty() {
        l.push(String::new());
        l.push(format!(
            "> โš  **INCOMPLETE SCAN** โ€” the affected checks did NOT run, and unknown is not the same as safe: {}. Treat the score as a ceiling.",
            r.coverage_gaps.join("; ")
        ));
    }
    if !r.warnings.is_empty() {
        l.push(String::new());
        l.push(format!("> Notes: {}", r.warnings.join("; ")));
    }
    l.push(String::new());
    if let Some(u) = &r.rokha_url {
        l.push(format!("**[View in Rokha โ†’]({u})**"));
        l.push(String::new());
    }
    l.push(
        "_Solwatch ยท real on-chain data ยท a SNAPSHOT of the chain at scan time (flags \
         and score move as the chain moves โ€” compare `flags[]`, not bare scores) ยท \
         not financial advice._"
            .into(),
    );
    l.join("\n")
}

pub fn render_tweet(r: &AuditResult) -> String {
    let top: Vec<String> = r
        .flags
        .iter()
        .filter(|f| {
            matches!(
                f.severity,
                crate::types::Severity::Critical | crate::types::Severity::Danger
            )
        })
        .take(2)
        .map(|f| f.title.replace('๐Ÿฏ', "").trim().to_string())
        .collect();
    let flag_line = if top.is_empty() {
        String::new()
    } else {
        format!(" {}", top.join("; "))
    };
    // An UNKNOWN verdict means nothing could be read โ€” printing "0/100" beside
    // it reads as a catastrophic score rather than an absent one.
    let score_part = if r.verdict == crate::types::Verdict::Unknown {
        String::new()
    } else {
        format!(" ({}/100)", r.score)
    };
    let base = format!(
        "{} ${} on Solana โ€” {}{}.{}",
        verdict_emoji(r.verdict),
        r.token.symbol.clone().unwrap_or_else(|| "?".into()),
        verdict_str(r.verdict),
        score_part,
        flag_line
    );
    // Loud honesty on the most public surface. This marker used to be withheld
    // from risk verdicts on the reasoning that "risk verdicts already warn" โ€”
    // but they warn about RISK, not about COVERAGE. That is the reputational
    // landmine: a tweet accusing named wallets of dev-funded sniping, made on a
    // partial scan the code itself labels a floor, went out with no qualifier
    // while a CAUTION token got one. An accusation needs the hedge MORE than a
    // reassurance does, because compression already strips it: only `f.title`
    // survives into the post, and every "at least" / "treat this as a floor"
    // qualifier lives in `f.detail`.
    let coverage_full = r.coverage_gaps.is_empty()
        && r.sections
            .pointer("/cluster/scope/coverage")
            .and_then(|v| v.as_str())
            == Some("full");
    let base = if coverage_full {
        base
    } else {
        format!("{base} โš  partial scan โ€” figures are floors")
    };
    let tail = format!(
        " mcap {}. Audited by @Rokha_ai",
        usd(r.token.market_cap_usd)
    );
    let mut out = format!("{base}{tail}");
    if out.chars().count() > 280 {
        let keep = 280usize.saturating_sub(tail.chars().count() + 1);
        out = format!("{}โ€ฆ{}", base.chars().take(keep).collect::<String>(), tail);
    }
    out.chars().take(280).collect()
}

/// Build the Rokha APP-view block: the documented, repeatable contract for a
/// rig to get a native render in Rokha's output rail. A rig whose final step
/// outputs `{ "rokha_app": โ€ฆ }` (this JSON already carries it) is render-ready.
pub fn render_rokha_app(r: &AuditResult) -> serde_json::Value {
    let mut metrics = vec![];
    let mut push = |label: &str, value: String, tone: &str| {
        metrics.push(json!({"label": label, "value": value, "tone": tone}));
    };
    if let Some(m) = r.token.market_cap_usd {
        push("Market cap", usd(Some(m)), "neutral");
    }
    if let Some(v) = r.token.volume_24h_usd {
        push("24h volume", usd(Some(v)), "neutral");
    }
    if let Some(h) = r.token.holders_count {
        push("Holders", h.to_string(), "neutral");
    }
    if let Some(t) = r
        .sections
        .pointer("/liquidity/totalLiquidityUsd")
        .and_then(|v| v.as_f64())
        .filter(|t| *t > 0.0)
    {
        push(
            "Liquidity",
            usd(Some(t)),
            if t < 5000.0 { "warn" } else { "neutral" },
        );
    }
    if let Some(p) = r
        .sections
        .pointer("/bundles/pctSupplySniped")
        .and_then(|v| v.as_f64())
    {
        push(
            "Supply sniped",
            format!("{p}%"),
            if p >= 40.0 {
                "bad"
            } else if p >= 15.0 {
                "warn"
            } else {
                "ok"
            },
        );
    }
    if let Some(p) = r
        .sections
        .pointer("/holders/top10Pct")
        .and_then(|v| v.as_f64())
    {
        push(
            "Top-10 hold",
            format!("{p}%"),
            if p >= 60.0 {
                "bad"
            } else if p >= 30.0 {
                "warn"
            } else {
                "ok"
            },
        );
    }
    if let Some(p) = r
        .sections
        .pointer("/cluster/effective_concentration/largest_entity_pct_floor")
        .and_then(|v| v.as_f64())
        .filter(|p| *p > 0.0)
    {
        push(
            "Largest entity",
            format!("โ‰ฅ{p}%"),
            if p >= 20.0 {
                "bad"
            } else if p >= 10.0 {
                "warn"
            } else {
                "ok"
            },
        );
    }
    if let Some(p) = r
        .sections
        .pointer("/cluster/effective_concentration/top10_entity_pct_floor")
        .and_then(|v| v.as_f64())
        .filter(|p| *p > 0.0)
    {
        push(
            "Entity top-10",
            format!("โ‰ฅ{p}%"),
            if p >= 60.0 {
                "bad"
            } else if p >= 30.0 {
                "warn"
            } else {
                "ok"
            },
        );
    }
    if let Some(cl) = r
        .sections
        .pointer("/cluster/findings")
        .and_then(|v| v.as_array())
    {
        let proven = cl
            .iter()
            .any(|c| c.get("proof").map(|p| !p.is_null()).unwrap_or(false));
        // "no" would be evidence-of-absence framing when the proof API was
        // simply unreachable โ€” absence of evidence must read as unchecked.
        let jito_live = r
            .sections
            .pointer("/cluster/scope/jitoApiOk")
            .and_then(|v| v.as_bool())
            .unwrap_or(true);
        if !cl.is_empty() {
            push(
                "Jito-proven",
                if proven {
                    "yes".into()
                } else if jito_live {
                    "no".into()
                } else {
                    "unchecked".into()
                },
                if proven {
                    "bad"
                } else if jito_live {
                    "neutral"
                } else {
                    "warn"
                },
            );
        }
    }
    if let Some(s) = r
        .sections
        .pointer("/market/organicScore")
        .and_then(|v| v.as_f64())
    {
        let s = s.round();
        push(
            "Organic score",
            format!("{s}/100"),
            if s >= 60.0 {
                "ok"
            } else if s >= 25.0 {
                "warn"
            } else {
                "bad"
            },
        );
    }

    let findings: Vec<String> = r
        .flags
        .iter()
        .map(|f| format!("- {} **{}** โ€” {}", sev_emoji(f.severity), f.title, f.detail))
        .collect();
    let mut sections = vec![json!({"heading": "Findings", "markdown": findings.join("\n")})];
    if let Some(sn) = r
        .sections
        .pointer("/bundles/topSnipers")
        .and_then(|v| v.as_array())
    {
        if !sn.is_empty() {
            let rows: Vec<_> = sn
                .iter()
                .map(|s| {
                    json!([
                        s.get("owner").and_then(|v| v.as_str()).unwrap_or("?"),
                        // `null` here means the probe never resolved this
                        // wallet's balance. Rendering that as "0%" published
                        // "still holds 0%" next to a real address โ€” a specific
                        // public claim that a named trader dumped their bag,
                        // asserted from a measurement we never took.
                        match s.get("pct").and_then(|v| v.as_f64()) {
                            Some(p) => format!("{p}%"),
                            None => "โ€”".to_string(),
                        },
                        match s.get("heldPct").and_then(|v| v.as_f64()) {
                            Some(p) => format!("{p}%"),
                            None => "โ€” (not checked)".to_string(),
                        },
                        if s.get("sameSlot").and_then(|v| v.as_bool()).unwrap_or(false) {
                            "yes"
                        } else {
                            ""
                        },
                    ])
                })
                .collect();
            sections.push(json!({"heading": "Launch snipers", "table": {
                "columns": ["wallet", "bought at launch", "still holds", "same-slot"],
                "rows": rows,
            }}));
        }
    }
    if let Some(cl) = r
        .sections
        .pointer("/cluster/findings")
        .and_then(|v| v.as_array())
    {
        if !cl.is_empty() {
            let rows: Vec<_> = cl
                .iter()
                .enumerate()
                .map(|(i, c)| {
                    json!([
                        format!(
                            "#{}",
                            c.get("id").and_then(|v| v.as_u64()).unwrap_or(i as u64 + 1)
                        ),
                        c.get("wallets")
                            .and_then(|w| w.as_array())
                            .map(|w| w.len().to_string())
                            .unwrap_or_default(),
                        format!(
                            "{}%",
                            c.get("pct_combined")
                                .and_then(|v| v.as_f64())
                                .unwrap_or(0.0)
                        ),
                        c.get("pct_bought")
                            .and_then(|v| v.as_f64())
                            .map(|v| format!("{v}%"))
                            .unwrap_or_else(|| "โ€”".into()),
                        c.get("evidence")
                            .and_then(|v| v.as_str())
                            .unwrap_or("")
                            .replace('_', " "),
                        // The confidence tier IS the headline column โ€” a reader
                        // scanning this table must not have to infer how much
                        // any row is worth from the evidence name alone.
                        match c.get("confidence").and_then(|v| v.as_str()).unwrap_or("") {
                            "proven" =>
                                if c.get("proof").map(|p| !p.is_null()).unwrap_or(false) {
                                    "proven (Jito)".to_string()
                                } else {
                                    "proven".to_string()
                                },
                            other => other.to_string(),
                        },
                    ])
                })
                .collect();
            sections.push(json!({"heading": "Linked wallets", "table": {
                "columns": ["#", "wallets", "holds now", "bought at launch", "evidence", "confidence"],
                "rows": rows,
            }}));
        }
    }
    // The limits ride the app block too โ€” the rail renders this beside the
    // score, which is exactly where an over-read happens.
    if let Some(limits) = r
        .sections
        .pointer("/cluster/scope/limits")
        .and_then(|v| v.as_array())
        .filter(|l| !l.is_empty())
    {
        let md: Vec<String> = limits
            .iter()
            .filter_map(|v| v.as_str())
            .map(|s| format!("- {s}"))
            .collect();
        sections.push(json!({
            "heading": "What the wallet-link pass cannot see",
            "markdown": md.join("\n"),
        }));
    }
    json!({
        "title": format!("Solwatch audit โ€” ${}", r.token.symbol.clone().unwrap_or_else(|| "?".into())),
        "subject": r.address,
        "verdict": verdict_str(r.verdict).replace(' ', "_").to_lowercase(),
        "score": r.score,
        "metrics": metrics,
        "sections": sections,
        // The APP rail and public rig product pages render THIS block โ€” the
        // most-seen surface was previously the least disclosed, showing a clean
        // score card for a run with a degraded scan. Coverage travels with the
        // score everywhere the score goes.
        "coverage": if r.coverage_gaps.is_empty() { "full" } else { "partial" },
        "coverageGaps": r.coverage_gaps,
        "warnings": r.warnings,
    })
}

/// One self-contained HTML file โ€” the exact dashboard card with this audit's
/// data baked in (inlined CSS/JS, fetch stubbed, no network). This is how a
/// run inside an egress-only sandbox ships its "frontend" OUT as an artifact:
/// the file renders anywhere, including a hard-sandboxed srcdoc iframe.
pub fn render_html(r: &AuditResult) -> String {
    // `</` would close the script tag early inside embedded JSON.
    let data = serde_json::to_string(r)
        .unwrap_or_else(|_| "null".into())
        .replace("</", "<\\/");
    let stub = format!(
        "<script>\nconst __AUDIT = {data};\nwindow.fetch = async (u) => {{\n  const s = String(u);\n  if (s.includes('/api/audit')) {{\n    const m = s.match(/[?&]address=([^&]*)/);\n    const a = m ? decodeURIComponent(m[1]) : '';\n    const baked = (__AUDIT && __AUDIT.address) || '';\n    if (a && a.toLowerCase() !== baked.toLowerCase() && window.parent !== window) {{\n      window.parent.postMessage({{ rokha: 'app_action', action: 'run', input: a.slice(0, 4000) }}, '*');\n      return {{ json: async () => ({{ __rokha_pending: true }}) }};\n    }}\n    return {{ json: async () => __AUDIT }};\n  }}\n  return {{ json: async () => [] }};\n}};\n</script>\n<script>"
    );
    let html = DASHBOARD_HTML.replacen("<script>", &stub, 1);
    html.replacen(
        "</script>\n</body>",
        "if (__AUDIT && __AUDIT.address) audit(__AUDIT.address);</script>\n</body>",
        1,
    )
}

// ---- report store ----

pub fn default_report_dir() -> PathBuf {
    std::env::var("SOLWATCH_OUT")
        .map(PathBuf::from)
        .unwrap_or_else(|_| {
            std::env::current_dir()
                .unwrap_or_default()
                .join("solwatch-reports")
        })
}

fn safe(s: &str) -> String {
    let out: String = s
        .chars()
        .filter(|c| c.is_ascii_alphanumeric())
        .take(16)
        .collect();
    if out.is_empty() {
        "token".into()
    } else {
        out
    }
}

/// Write the durable report artifacts: `.md` + `.json` + the index, always;
/// the self-contained `.html` dashboard sibling only when `html` is true
/// (opt-in โ€” `--report-html` on the CLI; `--app-html` is the standalone
/// dashboard path and doesn't ride through here).
pub fn write_report(r: &AuditResult, dir: &Path, html: bool) -> Result<String> {
    fs::create_dir_all(dir)?;
    let ts = r.scanned_at.replace([':', '.'], "-");
    let base = format!(
        "{}-{}-{}",
        safe(r.token.symbol.as_deref().unwrap_or("token")),
        &r.address[..8.min(r.address.len())],
        ts
    );
    let md_file = format!("{base}.md");
    fs::write(dir.join(&md_file), render_markdown(r))?;
    fs::write(
        dir.join(format!("{base}.json")),
        serde_json::to_string_pretty(r)?,
    )?;
    if html {
        fs::write(dir.join(format!("{base}.html")), render_html(r))?;
    }

    let idx_path = dir.join("index.json");
    let mut index: Vec<serde_json::Value> = fs::read_to_string(&idx_path)
        .ok()
        .and_then(|s| serde_json::from_str(&s).ok())
        .unwrap_or_default();
    index.insert(0, json!({
        "file": md_file, "symbol": r.token.symbol, "address": r.address,
        "score": r.score, "verdict": verdict_str(r.verdict).replace(' ', "_"), "scannedAt": r.scanned_at,
    }));
    index.truncate(500);
    fs::write(&idx_path, serde_json::to_string_pretty(&index)?)?;
    Ok(md_file)
}

pub fn list_reports(dir: &Path) -> Vec<serde_json::Value> {
    fs::read_to_string(dir.join("index.json"))
        .ok()
        .and_then(|s| serde_json::from_str(&s).ok())
        .unwrap_or_default()
}