forklaunch 1.23.0

Launch faster with forklaunch
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
//! Build an Enterprise-Readiness Report Card from deterministic checks alone.
//!
//! The card contract (`REPORT_CARD_SCHEMA_VERSION` 2, five weighted rails) is
//! defined once in TypeScript and shared by every surface that produces one.
//! That file names this producer explicitly: "`forklaunch audit` repo analysis
//! (deterministic compliance findings → card)", reserves `phase: 'audit'` for
//! it, and tags findings `source: 'cli'` to separate them from AI assessment.
//! This module is the Rust side of that contract.
//!
//! # What this can and cannot score
//!
//! Every deterministic check bears on one platform checklist criterion (the
//! `LOCAL_CHECKS` table in the platform's `run-checks.ts`), and each item on
//! this card carries that criterion's id and its exact label, so the offline
//! card lists the same lines as the website's "Checked" half. A criterion's
//! rail decides where its item lands:
//!
//! | rail | scored here | criteria |
//! |---|---|---|
//! | compliance | yes | `cmp-encryption-at-rest`, `cmp-data-classification` |
//! | security | yes | `sec-tenant-isolation` |
//! | governance | yes | `gov-data-retention`, `gdpr-erasure` |
//! | scalability | no | needs load characteristics no source read reveals |
//! | observability | no | wiring is visible, but whether it covers what matters is not |
//!
//! Emitting 0 for the last two would read as failure rather than absence, so
//! they are marked `pending` and excluded from the weighted average, and the
//! card carries a `caveat` saying so. The online `score` replaces this with the
//! platform's full agent-scored card.

use serde::Serialize;

use crate::compliance::checks::{LocalFinding, Severity};

/// Bump only alongside the TypeScript `REPORT_CARD_SCHEMA_VERSION`.
const SCHEMA_VERSION: u32 = 2;

/// Rails this command can decide from source alone, with their contract weights.
const SCORED_RAILS: &[(&str, f64)] = &[
    ("compliance", 0.25),
    ("security", 0.25),
    ("governance", 0.15),
];

/// Rails that need an agent. Weights are carried for documentation only; they
/// are excluded from the average rather than counted as zero.
const PENDING_RAILS: &[(&str, f64, &str)] = &[
    (
        "scalability",
        0.15,
        "Load characteristics and data growth are not visible in source.",
    ),
    (
        "observability",
        0.2,
        "Instrumentation wiring is visible, but whether it covers what matters is a judgement.",
    ),
];

/// A platform checklist criterion (`BASELINE_CRITERIA` / `FRAMEWORK_CRITERIA`
/// in the platform's `report-card.ts`). Labels are the platform's exact
/// strings: the website matches checks to items by label, so a paraphrase here
/// would put the offline card and the website on different lines.
struct Criterion {
    id: &'static str,
    rail: &'static str,
    label: &'static str,
}

/// The criteria the offline checks bear on, in the order the card lists them.
const CRITERIA: &[Criterion] = &[
    Criterion {
        id: "cmp-encryption-at-rest",
        rail: "compliance",
        label: "Sensitive fields are encrypted at rest",
    },
    Criterion {
        id: "cmp-data-classification",
        rail: "compliance",
        label: "Sensitive data is identified and handled according to its sensitivity",
    },
    Criterion {
        id: "sec-tenant-isolation",
        rail: "security",
        label: "One customer cannot see or change another customer\u{2019}s data",
    },
    Criterion {
        id: "gov-data-retention",
        rail: "governance",
        label: "How long data is kept, and how it is deleted, is defined",
    },
    Criterion {
        id: "gdpr-erasure",
        rail: "governance",
        label: "Users can request data export and erasure",
    },
];

/// What a check's finding means for its criterion. Mirrors `onFinding` in the
/// platform's `LOCAL_CHECKS`.
#[derive(PartialEq)]
enum OnFinding {
    /// The item is unmet.
    Fail,
    /// A human should look; the item is neither met nor failed.
    Review,
}

/// Local check id -> (criterion id, what a finding means). Mirrors the
/// platform's `LOCAL_CHECKS` table.
fn criterion_for_check(check: &str) -> Option<(&'static str, OnFinding)> {
    Some(match check {
        "tenant-isolation-wiring" | "tenant-context-half-wired" => {
            ("sec-tenant-isolation", OnFinding::Fail)
        }
        "encryptor-registration" | "tenant-em-wiring" | "better-auth-encryption-context" => {
            ("cmp-encryption-at-rest", OnFinding::Fail)
        }
        "retention-wiring" => ("gov-data-retention", OnFinding::Fail),
        "erasure-wiring" => ("gdpr-erasure", OnFinding::Fail),
        "possible-misclassification" => ("cmp-data-classification", OnFinding::Review),
        _ => return None,
    })
}

fn criterion(id: &str) -> Option<&'static Criterion> {
    CRITERIA.iter().find(|c| c.id == id)
}

/// Which rail each deterministic check belongs to: its criterion's rail.
/// Unmapped checks fall back to compliance, as the platform's
/// `CATEGORY_DIMENSIONS` does for unknown categories.
fn rail_for_check(check: &str) -> &'static str {
    criterion_for_check(check)
        .and_then(|(id, _)| criterion(id))
        .map(|c| c.rail)
        .unwrap_or("compliance")
}

/// Contract severity for a local finding.
///
/// `tenant-context-half-wired` is promoted above the other warnings on
/// evidence: it is the one check whose failure mode is silent — rows filter
/// correctly, tests pass, and encrypted columns quietly use the wrong key until
/// a real tenant exists in production.
fn severity_for(finding: &LocalFinding) -> &'static str {
    match (&finding.severity, finding.check.as_str()) {
        (Severity::Warning, "tenant-context-half-wired") => "critical",
        (Severity::Warning, _) => "high",
        (Severity::Info, _) => "info",
    }
}

/// Points deducted per finding. Deductions accumulate but never drive a rail
/// below zero.
fn penalty_for(severity: &str) -> f64 {
    match severity {
        "critical" => 30.0,
        "high" => 15.0,
        "medium" => 8.0,
        "low" => 4.0,
        _ => 0.0,
    }
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct CardFinding {
    pub(crate) severity: String,
    pub(crate) title: String,
    pub(crate) detail: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) fix: Option<String>,
    /// Always `cli` here: these are deterministic, not model output.
    pub(crate) source: String,
    /// Platform criterion id the finding bears on, e.g. `sec-tenant-isolation`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) criterion: Option<String>,
}

/// One deterministic check's outcome on an item, as the platform's v3 item
/// `checks` records it (`pass` / `fail` / `review`).
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct CardItemCheck {
    pub(crate) id: String,
    pub(crate) status: String,
    pub(crate) detail: String,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct CardItem {
    /// The platform criterion's exact label.
    pub(crate) label: String,
    /// `met` (every check on it passed), `unmet` (a check failed) or `pending`
    /// (a check asks for review). Only `unmet` is settled by a check alone:
    /// the offline checks are partial, so a pass is evidence, not proof.
    pub(crate) status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) detail: Option<String>,
    /// Platform criterion id, e.g. `cmp-encryption-at-rest`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) criterion: Option<String>,
    /// The checks that bear on this item and how each came out.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub(crate) checks: Vec<CardItemCheck>,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct CardDimension {
    pub(crate) score: u32,
    pub(crate) summary: String,
    pub(crate) items: Vec<CardItem>,
    /// The CLI asks nothing; the field is required by the contract.
    pub(crate) questions: Vec<serde_json::Value>,
    pub(crate) findings: Vec<CardFinding>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) pending: Option<bool>,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ReportCard {
    pub(crate) schema_version: u32,
    pub(crate) overall: u32,
    pub(crate) headline: String,
    pub(crate) caveat: String,
    pub(crate) phase: String,
    pub(crate) step: String,
    /// Empty: deciding which frameworks apply to a domain is an agent's job,
    /// and guessing would be worse than saying nothing.
    pub(crate) frameworks: Vec<String>,
    pub(crate) dimensions: std::collections::BTreeMap<String, CardDimension>,
    pub(crate) generated_at: String,
}

/// One human-readable line per check, used for finding titles. Checklist
/// items use the criterion label instead (see `CRITERIA`).
fn item_label(check: &str) -> &'static str {
    match check {
        "encryptor-registration" => "Field encryptor is registered",
        "retention-wiring" => "Retention policies are wired",
        "erasure-wiring" => "GDPR erasure is wired",
        "possible-misclassification" => "Sensitive fields are classified",
        "better-auth-encryption-context" => "Better Auth reads bind an encryption context",
        "tenant-isolation-wiring" => "Tenant isolation filter is installed",
        "tenant-em-wiring" => "An encryption tenant is bound",
        "tenant-context-half-wired" => "Tenant filter and encryption context agree",
        _ => "Deterministic check",
    }
}

fn remedy(check: &str) -> Option<String> {
    let text = match check {
        "tenant-context-half-wired" => {
            "Replace the hand-rolled fork with \
             wrapEmWithTenantContext(Orm.em.fork(opts), context?.tenantId). setFilterParams \
             scopes rows only; it does not bind the encryption key."
        }
        "tenant-em-wiring" | "tenant-isolation-wiring" => {
            "Bind the tenant on the EntityManager before reading encrypted columns."
        }
        "encryptor-registration" => "Register a FieldEncryptor during bootstrap.",
        "retention-wiring" => "Declare retention on classified entities.",
        "erasure-wiring" => "Wire the erasure handler so subject-deletion requests are honoured.",
        "possible-misclassification" => {
            "Classify the field with .compliance('pii'|'phi'|'pci') or confirm 'none' is correct."
        }
        "better-auth-encryption-context" => {
            "Wrap Better Auth's EntityManager so its reads carry the tenant."
        }
        _ => return None,
    };
    Some(text.to_string())
}

/// Build a card from deterministic findings.
///
/// `generated_at` is passed in rather than read from the clock so the caller
/// owns time and this stays a pure function.
pub(crate) fn build_local_report_card(
    app_name: &str,
    module_count: usize,
    findings: &[LocalFinding],
    generated_at: String,
) -> ReportCard {
    let mut dimensions = std::collections::BTreeMap::new();
    let mut weighted_total = 0.0;
    let mut weight_used = 0.0;

    for (rail, weight) in SCORED_RAILS {
        let rail_findings: Vec<&LocalFinding> = findings
            .iter()
            .filter(|f| rail_for_check(&f.check) == *rail)
            .collect();

        let mut score = 100.0;
        let mut card_findings = Vec::new();
        for finding in &rail_findings {
            let severity = severity_for(finding);
            score -= penalty_for(severity);
            card_findings.push(CardFinding {
                severity: severity.to_string(),
                title: format!("{} ({})", item_label(&finding.check), finding.project),
                detail: finding.message.clone(),
                fix: remedy(&finding.check),
                source: "cli".to_string(),
                criterion: criterion_for_check(&finding.check).map(|(id, _)| id.to_string()),
            });
        }
        let score = score.max(0.0);

        // One item per criterion on this rail. A check that fired failed (or,
        // for a review check, asks for review); one that never fired passed
        // everywhere it was evaluated.
        let mut items: Vec<CardItem> = Vec::new();
        for crit in CRITERIA.iter().filter(|c| c.rail == *rail) {
            let mut checks = Vec::new();
            let mut failed = false;
            let mut review = false;
            let mut detail = None;
            for check in checks_for_criterion(crit.id) {
                let hits: Vec<&&LocalFinding> =
                    rail_findings.iter().filter(|f| f.check == *check).collect();
                let status = match hits.first() {
                    None => "pass",
                    Some(first) => {
                        detail.get_or_insert_with(|| first.message.clone());
                        match criterion_for_check(check).map(|(_, on)| on) {
                            Some(OnFinding::Review) => {
                                review = true;
                                "review"
                            }
                            _ => {
                                failed = true;
                                "fail"
                            }
                        }
                    }
                };
                checks.push(CardItemCheck {
                    id: (*check).to_string(),
                    status: status.to_string(),
                    detail: match hits.first() {
                        None => "No problems found by this check.".to_string(),
                        Some(first) => format!(
                            "{} finding{}: {}{}",
                            hits.len(),
                            if hits.len() > 1 { "s" } else { "" },
                            first.message,
                            if hits.len() > 1 {
                                format!(" (and {} more)", hits.len() - 1)
                            } else {
                                String::new()
                            }
                        ),
                    },
                });
            }
            items.push(CardItem {
                label: crit.label.to_string(),
                status: if failed {
                    "unmet"
                } else if review {
                    "pending"
                } else {
                    "met"
                }
                .to_string(),
                detail,
                criterion: Some(crit.id.to_string()),
                checks,
            });
        }

        let summary = if card_findings.is_empty() {
            format!("No deterministic {rail} findings across {module_count} module(s).")
        } else {
            format!(
                "{} deterministic finding(s) across {} module(s).",
                card_findings.len(),
                module_count
            )
        };

        dimensions.insert(
            (*rail).to_string(),
            CardDimension {
                score: score.round() as u32,
                summary,
                items,
                questions: Vec::new(),
                findings: card_findings,
                pending: None,
            },
        );

        weighted_total += score * weight;
        weight_used += weight;
    }

    for (rail, _weight, why) in PENDING_RAILS {
        dimensions.insert(
            (*rail).to_string(),
            CardDimension {
                score: 0,
                summary: format!("Not assessed. {why}"),
                items: Vec::new(),
                questions: Vec::new(),
                findings: Vec::new(),
                pending: Some(true),
            },
        );
    }

    // Renormalise over the rails actually scored. Counting the unassessed
    // three as zero would cap this card at 50 and read as failure rather than
    // absence.
    let overall = if weight_used > 0.0 {
        (weighted_total / weight_used).round() as u32
    } else {
        0
    };

    let total = findings.len();
    let headline = if total == 0 {
        format!(
            "{app_name}: no deterministic compliance or security findings across {module_count} module(s)."
        )
    } else {
        format!(
            "{app_name}: {total} deterministic finding(s) across {module_count} module(s), scored on compliance, security and governance."
        )
    };

    ReportCard {
        schema_version: SCHEMA_VERSION,
        overall,
        headline,
        caveat: "Deterministic checks only. Compliance, security and governance are scored \
                 from static analysis of the checklist items those checks cover; scalability \
                 and observability need judgement a source read cannot supply and are left \
                 unassessed rather than scored zero. The overall score is weighted across the \
                 scored rails only. All five rails need an agent's judgement, which the studio \
                 surface provides."
            .to_string(),
        phase: "audit".to_string(),
        step: "audit".to_string(),
        frameworks: Vec::new(),
        dimensions,
        generated_at,
    }
}

/// Every local check, so the checklist shows passes as well as failures.
const ALL_CHECKS: &[&str] = &[
    "encryptor-registration",
    "tenant-em-wiring",
    "better-auth-encryption-context",
    "possible-misclassification",
    "tenant-isolation-wiring",
    "tenant-context-half-wired",
    "retention-wiring",
    "erasure-wiring",
];

/// The local checks that bear on a criterion.
fn checks_for_criterion(id: &str) -> Vec<&'static str> {
    ALL_CHECKS
        .iter()
        .copied()
        .filter(|check| criterion_for_check(check).is_some_and(|(c, _)| c == id))
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn finding(check: &str, severity: Severity) -> LocalFinding {
        LocalFinding {
            severity,
            project: "iam".to_string(),
            check: check.to_string(),
            subject: "registrations.ts".to_string(),
            message: "example".to_string(),
        }
    }

    fn at() -> String {
        "2026-01-01T00:00:00Z".to_string()
    }

    #[test]
    fn a_clean_workspace_scores_full_marks_on_the_rails_it_can_judge() {
        let card = build_local_report_card("demo", 3, &[], at());
        assert_eq!(card.overall, 100);
        assert_eq!(card.dimensions["compliance"].score, 100);
        assert_eq!(card.dimensions["security"].score, 100);
        assert_eq!(card.dimensions["governance"].score, 100);
        assert_eq!(card.dimensions["governance"].pending, None);
    }

    /// Every item carries the platform criterion id and its exact label, so
    /// the offline card and the website's "Checked" half list the same lines.
    #[test]
    fn items_use_platform_criterion_ids_and_exact_labels() {
        let card = build_local_report_card("demo", 1, &[], at());
        let expected = [
            (
                "compliance",
                "cmp-encryption-at-rest",
                "Sensitive fields are encrypted at rest",
            ),
            (
                "compliance",
                "cmp-data-classification",
                "Sensitive data is identified and handled according to its sensitivity",
            ),
            (
                "security",
                "sec-tenant-isolation",
                "One customer cannot see or change another customer\u{2019}s data",
            ),
            (
                "governance",
                "gov-data-retention",
                "How long data is kept, and how it is deleted, is defined",
            ),
            (
                "governance",
                "gdpr-erasure",
                "Users can request data export and erasure",
            ),
        ];
        let total: usize = card.dimensions.values().map(|d| d.items.len()).sum();
        assert_eq!(total, expected.len());
        for (rail, id, label) in expected {
            let item = card.dimensions[rail]
                .items
                .iter()
                .find(|i| i.criterion.as_deref() == Some(id))
                .unwrap_or_else(|| panic!("{rail} has no {id} item"));
            assert_eq!(item.label, label);
        }
        let json = serde_json::to_value(&card).unwrap();
        assert_eq!(
            json["dimensions"]["security"]["items"][0]["criterion"],
            "sec-tenant-isolation"
        );
        assert!(
            json["dimensions"]["security"]["items"][0]["label"]
                .as_str()
                .unwrap()
                .contains('\u{2019}'),
            "the label must keep the typographic apostrophe"
        );
    }

    #[test]
    fn every_local_check_maps_to_its_platform_criterion() {
        for (check, id) in [
            ("tenant-isolation-wiring", "sec-tenant-isolation"),
            ("tenant-context-half-wired", "sec-tenant-isolation"),
            ("encryptor-registration", "cmp-encryption-at-rest"),
            ("tenant-em-wiring", "cmp-encryption-at-rest"),
            ("better-auth-encryption-context", "cmp-encryption-at-rest"),
            ("retention-wiring", "gov-data-retention"),
            ("erasure-wiring", "gdpr-erasure"),
            ("possible-misclassification", "cmp-data-classification"),
        ] {
            assert_eq!(
                criterion_for_check(check).map(|(c, _)| c),
                Some(id),
                "{check}"
            );
            assert!(
                ALL_CHECKS.contains(&check),
                "{check} missing from ALL_CHECKS"
            );
        }
    }

    #[test]
    fn a_failed_check_marks_its_criterion_unmet_and_names_itself() {
        let card = build_local_report_card(
            "demo",
            1,
            &[finding("tenant-em-wiring", Severity::Warning)],
            at(),
        );
        let item = card.dimensions["compliance"]
            .items
            .iter()
            .find(|i| i.criterion.as_deref() == Some("cmp-encryption-at-rest"))
            .unwrap();
        assert_eq!(item.status, "unmet");
        let em = item
            .checks
            .iter()
            .find(|c| c.id == "tenant-em-wiring")
            .unwrap();
        assert_eq!(em.status, "fail");
        assert!(
            item.checks
                .iter()
                .filter(|c| c.id != "tenant-em-wiring")
                .all(|c| c.status == "pass")
        );
        assert_eq!(
            card.dimensions["compliance"].findings[0]
                .criterion
                .as_deref(),
            Some("cmp-encryption-at-rest")
        );
    }

    /// Misclassification is a review, not a failure: the item is left pending.
    #[test]
    fn possible_misclassification_is_a_review_not_a_failure() {
        let card = build_local_report_card(
            "demo",
            1,
            &[finding("possible-misclassification", Severity::Info)],
            at(),
        );
        let item = card.dimensions["compliance"]
            .items
            .iter()
            .find(|i| i.criterion.as_deref() == Some("cmp-data-classification"))
            .unwrap();
        assert_eq!(item.status, "pending");
        assert_eq!(item.checks[0].status, "review");
    }

    #[test]
    fn unassessed_rails_are_pending_not_zero_scores() {
        // Scoring them 0 would cap every card at 50 and read as failure rather
        // than absence -- the distinction the `pending` flag exists to make.
        let card = build_local_report_card("demo", 1, &[], at());
        for rail in ["scalability", "observability"] {
            assert_eq!(card.dimensions[rail].pending, Some(true), "{rail}");
        }
        assert_eq!(
            card.overall, 100,
            "unassessed rails must not drag the average down"
        );
    }

    #[test]
    fn the_silent_failure_check_outweighs_the_others() {
        let half_wired = build_local_report_card(
            "demo",
            1,
            &[finding("tenant-context-half-wired", Severity::Warning)],
            at(),
        );
        // Same rail (sec-tenant-isolation), ordinary severity.
        let ordinary = build_local_report_card(
            "demo",
            1,
            &[finding("tenant-isolation-wiring", Severity::Warning)],
            at(),
        );

        assert!(
            half_wired.dimensions["security"].score < ordinary.dimensions["security"].score,
            "the check whose failure mode is silent must cost more"
        );
        assert_eq!(
            half_wired.dimensions["security"].findings[0].severity,
            "critical"
        );
    }

    #[test]
    fn findings_route_to_the_right_rail() {
        let card = build_local_report_card(
            "demo",
            1,
            &[
                finding("tenant-isolation-wiring", Severity::Warning),
                finding("tenant-em-wiring", Severity::Warning),
                finding("retention-wiring", Severity::Warning),
            ],
            at(),
        );
        // Rails follow the criterion: tenant-em-wiring binds the encryption
        // tenant, so it bears on encryption at rest (compliance), not isolation.
        assert_eq!(card.dimensions["security"].findings.len(), 1);
        assert_eq!(card.dimensions["compliance"].findings.len(), 1);
        assert_eq!(card.dimensions["governance"].findings.len(), 1);
    }

    #[test]
    fn a_rail_never_scores_below_zero() {
        let many: Vec<LocalFinding> = (0..20)
            .map(|_| finding("tenant-context-half-wired", Severity::Warning))
            .collect();
        let card = build_local_report_card("demo", 1, &many, at());
        assert_eq!(card.dimensions["security"].score, 0);
    }

    #[test]
    fn info_findings_are_reported_without_costing_points() {
        let card = build_local_report_card(
            "demo",
            1,
            &[finding("possible-misclassification", Severity::Info)],
            at(),
        );
        assert_eq!(card.dimensions["compliance"].score, 100);
        assert_eq!(card.dimensions["compliance"].findings.len(), 1);
        assert_eq!(card.dimensions["compliance"].findings[0].severity, "info");
    }

    #[test]
    fn passing_checks_are_listed_as_met_so_the_checklist_shows_work_done() {
        let card = build_local_report_card("demo", 1, &[], at());
        let security = &card.dimensions["security"];
        assert!(!security.items.is_empty());
        assert!(security.items.iter().all(|i| i.status == "met"));
    }

    #[test]
    fn every_finding_carries_a_remedy_and_is_marked_deterministic() {
        let card = build_local_report_card(
            "demo",
            1,
            &[finding("tenant-context-half-wired", Severity::Warning)],
            at(),
        );
        let f = &card.dimensions["security"].findings[0];
        assert_eq!(f.source, "cli");
        assert!(
            f.fix
                .as_ref()
                .is_some_and(|s| s.contains("wrapEmWithTenantContext"))
        );
    }

    #[test]
    fn the_card_declares_the_contract_version_and_audit_phase() {
        let card = build_local_report_card("demo", 1, &[], at());
        assert_eq!(card.schema_version, SCHEMA_VERSION);
        assert_eq!(card.phase, "audit");
        // The caveat is the only thing standing between a partial score and
        // someone quoting it as a full readiness number, so it must say both
        // that rails were skipped and where the rest come from -- without
        // naming a flag this command does not have.
        assert!(
            card.caveat.contains("unassessed"),
            "the caveat must say some rails were not scored: {}",
            card.caveat
        );
        assert!(
            card.caveat.contains("studio"),
            "the caveat must say where the remaining rails come from: {}",
            card.caveat
        );
        assert!(
            !card.caveat.contains("--upload"),
            "the caveat must not name a flag `score` does not accept"
        );
    }
}

/// UTC timestamp for the card's `generatedAt`, without pulling in a date crate.
pub(crate) fn iso8601_now() -> String {
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);

    // Days since epoch -> civil date (Howard Hinnant's algorithm).
    let days = (secs / 86_400) as i64;
    let rem = secs % 86_400;
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };

    format!(
        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
        y,
        m,
        d,
        rem / 3_600,
        (rem % 3_600) / 60,
        rem % 60
    )
}