forklaunch 1.35.1

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
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
//! `forklaunch score` — Enterprise-Readiness Report Card for this workspace.
//!
//! Scores through the platform's analysis API, so the result is a real
//! five-rail agent-scored card and a shareable asset rather than a number that
//! disappears with the terminal scrollback.
//!
//! # Why it uploads
//!
//! `POST /analysis/repo` takes a `workspaceRoot` — a path on the orchestrator's
//! own disk. It cannot see a laptop. The only route from a local checkout is
//! `POST /analysis/zip`, so the workspace is packed and uploaded. What goes
//! into that archive is a privacy decision, handled in `workspace_archive`:
//! `.gitignore` is honoured, and `.git`/`node_modules` are dropped regardless.
//!
//! # What that costs
//!
//! Analysis is metered — a free tier per account, then credits — and returns a
//! job to poll rather than an answer. So this is a milestone action, not
//! something to run after every edit. `--offline` keeps the old behaviour for
//! the tight loop: deterministic checks only, no network, no auth, no cost, and
//! only the checklist items static analysis can actually decide (labelled with
//! the platform's criterion ids and labels, so they match the website).

use std::path::Path;
use std::time::{Duration, Instant};

use anyhow::{Context, Result};
use base64::Engine;
use clap::{Arg, ArgMatches, Command};
use serde_json::{Value, json};

use crate::{
    CliCommand,
    compliance::checks::run_local_checks,
    constants::{get_platform_ui_url, get_studio_orchestrator_api_url},
    core::{
        command::command,
        hmac::AuthMode,
        http_client::{get_with_auth, post_with_auth},
        report_card::{ReportCard, build_local_report_card, iso8601_now},
        validate::require_manifest,
        workspace_archive::pack_workspace,
    },
};

/// How long to wait for a job before giving up. Scoring runs several models;
/// minutes is normal, and a caller who hits this wants the job id rather than
/// a hang.
const POLL_TIMEOUT: Duration = Duration::from_secs(15 * 60);
const POLL_INTERVAL: Duration = Duration::from_secs(3);
/// Consecutive status requests that may fail with a dropped connection, a
/// timeout or a gateway error before the CLI gives up on a job that is still
/// running on the server.
const MAX_TRANSIENT_POLL_FAILURES: u32 = 10;

/// Gateway errors from the proxy in front of the analysis API: the request
/// never reached a handler, so asking again is safe.
fn is_transient_status(status: u16) -> bool {
    matches!(status, 502..=504)
}

#[derive(Debug)]
pub(crate) struct ScoreCommand;

impl ScoreCommand {
    pub(crate) fn new() -> Self {
        Self
    }
}

impl CliCommand for ScoreCommand {
    fn command(&self) -> Command {
        command(
            "score",
            "Score this workspace's enterprise readiness and get a shareable report card.",
        )
        .arg(
            Arg::new("base_path")
                .short('p')
                .long("path")
                .help("Application root path (defaults to the current directory's manifest)"),
        )
        .arg(
            Arg::new("offline")
                .long("offline")
                .help(
                    "Score from deterministic checks only — no upload, no auth, no cost. Covers \
                     the compliance, security and governance checklist items those checks \
                     decide; scalability and observability need an agent and come back \
                     unassessed.",
                )
                .action(clap::ArgAction::SetTrue),
        )
        .arg(
            Arg::new("no_share")
                .long("no-share")
                .help("Skip minting the share link (the card is still scored and printed)")
                .action(clap::ArgAction::SetTrue),
        )
        .arg(
            Arg::new("json")
                .long("json")
                .help("Emit the raw report card as JSON instead of a terminal summary")
                .action(clap::ArgAction::SetTrue),
        )
        .arg(
            Arg::new("pretty")
                .long("pretty")
                .help("Pretty-print the JSON output")
                .action(clap::ArgAction::SetTrue),
        )
        .arg(
            Arg::new("prompt")
                .long("prompt")
                .help(
                    "Print only the remediation prompt (the default output shows it after the summary): the \
                     same prompt the website's \"Generate prompt\" builds (every open finding \
                     with its evidence and fix, then the outstanding checklist items). \
                     --prompt-scope chooses what it covers. With --offline, a prompt built \
                     from the deterministic checks.",
                )
                .action(clap::ArgAction::SetTrue),
        )
        .arg(
            Arg::new("prompt_scope")
                .long("prompt-scope")
                .value_name("SCOPE")
                .help(
                    "What the remediation prompt covers: not-met (open findings and failed \
                     requirements), undecided (requirements the reviewers could not decide: the \
                     agent first checks whether each is already met, makes it demonstrable if so \
                     and implements it if not), or both (the default). Ignored with --offline.",
                )
                .value_parser(["not-met", "undecided", "both"])
                .default_value("both"),
        )
        .arg(
            Arg::new("min_score")
                .long("min-score")
                .help("Exit non-zero if the overall score is below this (0-100). For CI gating.")
                .value_parser(clap::value_parser!(u32).range(0..=100)),
        )
    }

    fn handler(&self, matches: &ArgMatches) -> Result<()> {
        let (app_root, manifest) = require_manifest(matches)?;
        let json_out = matches.get_flag("json");
        let pretty = matches.get_flag("pretty");

        let prompt_out = matches.get_flag("prompt");
        let offline = matches.get_flag("offline");
        let (card_json, share_url, remote_prompt) = if offline {
            (
                offline_card(&app_root, &manifest.app_name, &manifest.modules_path)?,
                None,
                None,
            )
        } else {
            score_via_api(
                &app_root,
                &manifest.app_name,
                manifest.platform_application_id.as_deref(),
                !matches.get_flag("no_share"),
                json_out || prompt_out,
                matches
                    .get_one::<String>("prompt_scope")
                    .map(String::as_str)
                    .unwrap_or("both"),
            )?
        };
        // The platform builds the prompt (the website's own builder); offline, or
        // from a platform that predates it, build one from the card.
        let prompt = remote_prompt.unwrap_or_else(|| offline_prompt(&card_json, offline));

        if json_out {
            let mut out = card_json.clone();
            if let Some(object) = out.as_object_mut() {
                object.insert(
                    "remediationPrompt".to_string(),
                    Value::String(prompt.clone()),
                );
            }
            let serialized = if pretty {
                serde_json::to_string_pretty(&out)?
            } else {
                serde_json::to_string(&out)?
            };
            println!("{}", serialized);
        } else if prompt_out {
            println!("{prompt}");
        } else {
            print_summary(&card_json);
            if let Some(url) = &share_url {
                println!("  {}", bold(&format!("Report card: {url}")));
                println!();
            }
            // The findings are the point of scoring: a person reads the summary
            // above, an agent works from the prompt below (every finding with its
            // evidence and fix, and the rescoring loop). `--prompt` prints it alone.
            println!("  {}", bold("Remediation prompt"));
            println!(
                "  {}",
                dim(
                    "(`forklaunch score --prompt` prints only this; `--json` carries it as remediationPrompt)"
                )
            );
            println!();
            println!("{prompt}");
        }

        if let Some(min) = matches.get_one::<u32>("min_score") {
            let overall = card_json
                .get("overall")
                .and_then(Value::as_u64)
                .unwrap_or(0) as u32;
            if overall < *min {
                anyhow::bail!(
                    "readiness score {} is below the required minimum of {}",
                    overall,
                    min
                );
            }
        }

        Ok(())
    }
}

/// Deterministic-only card, built locally. No network, no auth, no cost.
fn offline_card(app_root: &Path, app_name: &str, modules_path: &str) -> Result<Value> {
    let modules_root = app_root.join(modules_path);
    let mut findings = run_local_checks(&modules_root)?;
    // Cached advisory lookups only: the offline card makes no network calls, so an
    // uncached lockfile shows up as not checked rather than clean.
    findings.extend(crate::compliance::deps::scan(
        app_root,
        app_name,
        crate::compliance::deps::Lookup::CacheOnly,
    ));
    let module_count = std::fs::read_dir(&modules_root)
        .map(|entries| {
            entries
                .filter_map(|e| e.ok())
                .filter(|e| e.path().is_dir())
                .count()
        })
        .unwrap_or(0);

    let card: ReportCard =
        build_local_report_card(app_name, module_count, &findings, iso8601_now());
    Ok(json!(card))
}

fn studio_url(path: &str) -> String {
    format!(
        "{}/studio-orchestrator/analysis{}",
        get_studio_orchestrator_api_url(),
        path
    )
}

/// Pack → upload → poll → (optionally) share.
fn score_via_api(
    app_root: &Path,
    app_name: &str,
    // The platform application this project is bound to: its deployed instance
    // counts decide the card's hosting criteria (read server-side as the caller).
    application_id: Option<&str>,
    want_share: bool,
    quiet: bool,
    // What the platform's remediation prompt covers: not-met, undecided or both.
    prompt_scope: &str,
) -> Result<(Value, Option<String>, Option<String>)> {
    let auth = AuthMode::detect();

    if !quiet {
        println!();
        println!("  {} packing workspace…", dim("→"));
    }
    let (archive, summary) = pack_workspace(app_root)?;
    if !quiet {
        println!(
            "  {} {} files, {:.1} MB{}",
            dim("→"),
            summary.files,
            summary.bytes as f64 / (1024.0 * 1024.0),
            if summary.skipped_large > 0 {
                format!(" ({} large file(s) skipped)", summary.skipped_large)
            } else {
                String::new()
            }
        );
    }

    let zip_base64 = base64::engine::general_purpose::STANDARD.encode(&archive);
    let mut body = json!({ "appId": app_name, "zipBase64": zip_base64 });
    if let Some(id) = application_id {
        body["applicationId"] = Value::String(id.to_string());
    }

    if !quiet {
        println!("  {} uploading for analysis…", dim("→"));
    }
    let response = post_with_auth(&auth, &studio_url("/zip"), body)
        .context("could not reach the analysis API")?;
    let status = response.status();
    if !status.is_success() {
        let text = response.text().unwrap_or_default();
        return Err(api_error(status.as_u16(), &text));
    }

    let accepted: Value = response.json().context("analysis API returned no job id")?;
    let job_id = accepted
        .get("jobId")
        .and_then(Value::as_str)
        .context("analysis API returned no job id")?
        .to_string();

    let job = poll_job(&auth, &job_id, prompt_scope, quiet)?;
    let card = job
        .get("reportCard")
        .cloned()
        .context("the analysis finished without producing a report card")?;
    let prompt = job
        .get("remediationPrompt")
        .and_then(Value::as_str)
        .map(str::to_string);

    let share_url = if want_share {
        mint_share(&auth, &job_id).unwrap_or(None)
    } else {
        None
    };

    Ok((card, share_url, prompt))
}

/// A remediation prompt built from a card, for `--offline` (or a platform that
/// does not return one). Lists every finding with its evidence and fix and
/// every outstanding checklist item, then the loop an agent runs.
fn offline_prompt(card: &Value, offline: bool) -> String {
    use std::fmt::Write as _;
    let mut out = String::new();
    let overall = card.get("overall").and_then(Value::as_u64).unwrap_or(0);
    let _ = writeln!(
        out,
        "Harden this repository against its ForkLaunch report card{}.",
        if offline {
            " (offline: deterministic wiring checks only)"
        } else {
            ""
        }
    );
    let _ = writeln!(
        out,
        "Baseline: {overall}/100. {}",
        card.get("headline").and_then(Value::as_str).unwrap_or("")
    );
    if let Some(caveat) = card.get("caveat").and_then(Value::as_str) {
        let _ = writeln!(out, "Caveat: {caveat}");
    }
    let _ = writeln!(
        out,
        "\nLOOP\n\
         1. Fix the findings below in severity order. Inspect the code before accepting a finding, \
         fix every place a shared cause appears, and add a test for each fix.\n\
         2. After each batch run `forklaunch score --offline --json` (fast, free, deterministic) and \
         confirm the finding is gone. A score that does not move means the fix did not take effect.\n\
         3. When the offline checks are clean, run `forklaunch score --prompt --no-share` for the full \
         assessment (every category, judged criteria) and continue from the prompt it prints. The \
         offline score covers only the deterministic checks; do not stop at it.\n\
         4. Never weaken a control, suppress a finding or remove functionality to raise the score."
    );

    let severity_rank = |s: &str| match s {
        "critical" => 0,
        "high" => 1,
        "medium" => 2,
        "low" => 3,
        _ => 4,
    };
    let mut findings: Vec<(String, &Value)> = Vec::new();
    let mut outstanding: Vec<(String, &Value)> = Vec::new();
    if let Some(dimensions) = card.get("dimensions").and_then(Value::as_object) {
        for (rail, dim) in dimensions {
            for f in dim
                .get("findings")
                .and_then(Value::as_array)
                .into_iter()
                .flatten()
            {
                findings.push((rail.clone(), f));
            }
            for item in dim
                .get("items")
                .and_then(Value::as_array)
                .into_iter()
                .flatten()
            {
                if matches!(
                    item.get("status").and_then(Value::as_str),
                    Some("unmet" | "pending")
                ) {
                    outstanding.push((rail.clone(), item));
                }
            }
        }
    }
    findings.sort_by_key(|(_, f)| {
        severity_rank(f.get("severity").and_then(Value::as_str).unwrap_or(""))
    });

    let _ = writeln!(out, "\nFINDINGS");
    if findings.is_empty() {
        let _ = writeln!(out, "- None from these checks.");
    }
    let text = |v: &Value, key: &str| v.get(key).and_then(Value::as_str).unwrap_or("").to_string();
    // Identical findings (same rail, title, evidence) collapse into one line
    // with a count, so repeated per-field hits do not bury the rest.
    let mut grouped: Vec<(&String, &Value, usize)> = Vec::new();
    for (rail, f) in &findings {
        match grouped.iter_mut().find(|(r, g, _)| {
            *r == rail
                && text(g, "title") == text(f, "title")
                && text(g, "detail") == text(f, "detail")
        }) {
            Some(entry) => entry.2 += 1,
            None => grouped.push((rail, f, 1)),
        }
    }
    for (rail, f, count) in &grouped {
        let times = if *count > 1 {
            format!(" (x{count})")
        } else {
            String::new()
        };
        let _ = writeln!(
            out,
            "- [{rail}; {}] {}{times}",
            text(f, "severity"),
            text(f, "title")
        );
        let detail = text(f, "detail");
        if !detail.is_empty() {
            let _ = writeln!(out, "  Evidence: {detail}");
        }
        let fix = text(f, "fix");
        let _ = writeln!(
            out,
            "  Remediation: {}",
            if fix.is_empty() {
                "Inspect the cited code, find the root cause and repair it with a regression test."
            } else {
                &fix
            }
        );
    }

    let _ = writeln!(out, "\nOUTSTANDING CHECKLIST ITEMS");
    if outstanding.is_empty() {
        let _ = writeln!(out, "- None.");
    }
    for (rail, item) in &outstanding {
        let _ = writeln!(
            out,
            "- [{rail}] {}: {}",
            text(item, "label"),
            text(item, "status")
        );
        let detail = text(item, "detail");
        if !detail.is_empty() {
            let _ = writeln!(out, "  Evidence: {detail}");
        }
    }
    out
}

/// Poll until the job reaches a terminal state.
/// The job status path, asking for the prompt in a scope. The default scope sends no
/// parameter, so a platform that predates scopes is asked exactly what it was before.
fn job_path(job_id: &str, prompt_scope: &str) -> String {
    if prompt_scope == "not-met" {
        format!("/job/{job_id}")
    } else {
        format!("/job/{job_id}?promptScope={prompt_scope}")
    }
}

fn poll_job(auth: &AuthMode, job_id: &str, prompt_scope: &str, quiet: bool) -> Result<Value> {
    let started = Instant::now();
    let mut last_status = String::new();
    let mut transient_failures = 0u32;

    loop {
        if started.elapsed() > POLL_TIMEOUT {
            anyhow::bail!(
                "analysis did not finish within {} minutes. It may still complete — check the \
                 dashboard, or poll job {job_id} directly.",
                POLL_TIMEOUT.as_secs() / 60
            );
        }

        // The job keeps running on the server whatever happens to one status
        // request, so a dropped connection, a timeout or a proxy 502/503/504
        // (the service is busy while it scores, or restarting) is retried
        // rather than abandoning the run.
        let response = match get_with_auth(auth, &studio_url(&job_path(job_id, prompt_scope))) {
            Ok(response) if is_transient_status(response.status().as_u16()) => {
                transient_failures += 1;
                if transient_failures > MAX_TRANSIENT_POLL_FAILURES {
                    let status = response.status().as_u16();
                    let text = response.text().unwrap_or_default();
                    return Err(api_error(status, &text));
                }
                std::thread::sleep(POLL_INTERVAL);
                continue;
            }
            Ok(response) => response,
            Err(error) => {
                transient_failures += 1;
                if transient_failures > MAX_TRANSIENT_POLL_FAILURES {
                    return Err(error.context("lost contact with the analysis API"));
                }
                std::thread::sleep(POLL_INTERVAL);
                continue;
            }
        };
        transient_failures = 0;
        let http_status = response.status();
        if !http_status.is_success() {
            let text = response.text().unwrap_or_default();
            return Err(api_error(http_status.as_u16(), &text));
        }

        let job: Value = response.json().context("could not read the job status")?;
        let status = job.get("status").and_then(Value::as_str).unwrap_or("");

        match status {
            "done" => return Ok(job),
            "error" => {
                let message = job
                    .get("error")
                    .and_then(Value::as_str)
                    .unwrap_or("the analysis failed without a reason");
                anyhow::bail!("analysis failed: {message}");
            }
            other => {
                if !quiet && other != last_status {
                    println!("  {} {other}…", dim("→"));
                    last_status = other.to_string();
                }
            }
        }

        std::thread::sleep(POLL_INTERVAL);
    }
}

/// Mint a revocable share link. Best-effort: a scored card the caller can see
/// is worth more than an error because the link step failed.
fn mint_share(auth: &AuthMode, job_id: &str) -> Result<Option<String>> {
    let response = post_with_auth(auth, &studio_url("/share"), json!({ "jobId": job_id }))?;
    if !response.status().is_success() {
        return Ok(None);
    }
    let body: Value = response.json()?;
    Ok(body
        .get("sharePath")
        .and_then(Value::as_str)
        .map(|path| format!("{}{}", get_platform_ui_url(), path)))
}

/// Turn the API's status codes into something a person can act on. The tiering
/// (anonymous → sign in → free tier → credits) is invisible from a raw 401/402.
fn api_error(status: u16, body: &str) -> anyhow::Error {
    match status {
        401 => anyhow::anyhow!(
            "not signed in. Run `forklaunch login`, or use `forklaunch score --offline` for the \
             deterministic checks without an account."
        ),
        402 => anyhow::anyhow!(
            "analysis credits exhausted for this account. Add credits, or use \
             `forklaunch score --offline` for the deterministic checks."
        ),
        413 => anyhow::anyhow!(
            "the workspace archive was rejected as too large. Exclude generated directories or \
             score a narrower path with --path."
        ),
        _ => anyhow::anyhow!("analysis API returned {status} — {body}"),
    }
}

/// Terminal rendering. Default output, because a wall of JSON is not an answer
/// to "how ready is this" — the checklist and the unmet items are.
fn print_summary(card: &Value) {
    print!("{}", render_summary(card));
}

/// Built as a string rather than printed directly so the rendering rules below
/// — which are the whole point of this command's default output — can be
/// asserted rather than eyeballed.
/// A 0-100 score as the card stores it: a whole number or a decimal (a
/// category averages its items, e.g. 83.3). Rounded for display; `None` when
/// absent or not a number.
fn score_of(value: Option<&Value>) -> Option<u64> {
    value
        .and_then(Value::as_f64)
        .filter(|score| score.is_finite())
        .map(|score| score.clamp(0.0, 100.0).round() as u64)
}

fn render_summary(card: &Value) -> String {
    use std::fmt::Write as _;
    let mut out = String::new();

    let overall = score_of(card.get("overall")).unwrap_or(0);
    let _ = writeln!(out);
    let _ = writeln!(out, "  {}  {}/100", bold("Enterprise Readiness"), overall);
    if let Some(headline) = card.get("headline").and_then(Value::as_str) {
        let _ = writeln!(out, "  {}", dim(headline));
    }
    let _ = writeln!(out);

    if let Some(dimensions) = card.get("dimensions").and_then(Value::as_object) {
        let mut keys: Vec<&String> = dimensions.keys().collect();
        keys.sort();
        for key in keys {
            let rail = &dimensions[key];
            let label = {
                let mut c = key.chars();
                match c.next() {
                    Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
                    None => key.clone(),
                }
            };

            // `pending` marks a category with items still undecided. It can
            // still carry a score from the items that were decided (93.8);
            // a pending category whose score is missing or the 0 placeholder
            // was not assessed at all.
            let pending = rail
                .get("pending")
                .and_then(Value::as_bool)
                .unwrap_or(false);
            let score = match score_of(rail.get("score")) {
                Some(score) if !(pending && score == 0) => score,
                _ => {
                    let _ = writeln!(out, "  {:<16} {}", label, dim("not assessed"));
                    continue;
                }
            };
            let items = rail.get("items").and_then(Value::as_array);

            // A rail can score 100 and still have unmet items: only findings
            // cost points, and an `info` finding costs none. A bare "100/100"
            // therefore reads as "nothing left to do" on an app that has work
            // left — and it is the number a non-technical reader takes away.
            // So the outstanding count travels with the score, always.
            // `pending` counts too: an item a check flagged for review is not
            // done, whatever the score says.
            let outstanding = items
                .map(|items| {
                    items
                        .iter()
                        .filter(|item| {
                            matches!(
                                item.get("status").and_then(Value::as_str),
                                Some("unmet" | "pending")
                            )
                        })
                        .count()
                })
                .unwrap_or(0);
            if outstanding > 0 {
                let _ = writeln!(
                    out,
                    "  {:<16} {}/100  {}",
                    label,
                    score,
                    dim(&format!(
                        "({} item{} outstanding)",
                        outstanding,
                        if outstanding == 1 { "" } else { "s" }
                    ))
                );
            } else {
                let _ = writeln!(out, "  {:<16} {}/100", label, score);
            }

            if let Some(items) = items {
                for item in items.iter().take(8) {
                    let marker = match item.get("status").and_then(Value::as_str) {
                        Some("met") => "+",
                        Some("pending") => "?",
                        _ => "-",
                    };
                    let text = item.get("label").and_then(Value::as_str).unwrap_or("");
                    let _ = writeln!(out, "      {} {}", marker, text);
                }
            }
            if let Some(findings) = rail.get("findings").and_then(Value::as_array)
                && !findings.is_empty()
            {
                // The same check firing once per module produces N identical
                // titles. Listing "7 finding(s)" for one repeated problem
                // overstates the work; collapse them and say how many times.
                let mut unique: Vec<(&str, usize)> = Vec::new();
                for finding in findings {
                    let title = finding.get("title").and_then(Value::as_str).unwrap_or("");
                    match unique.iter_mut().find(|(seen, _)| *seen == title) {
                        Some((_, count)) => *count += 1,
                        None => unique.push((title, 1)),
                    }
                }
                let _ = writeln!(
                    out,
                    "      {}",
                    dim(&format!(
                        "{} finding(s){}",
                        unique.len(),
                        if unique.len() == findings.len() {
                            String::new()
                        } else {
                            format!(", {} total", findings.len())
                        }
                    ))
                );
                for (title, count) in unique.iter().take(5) {
                    if title.is_empty() {
                        continue;
                    }
                    let suffix = if *count > 1 {
                        format!(" (×{count})")
                    } else {
                        String::new()
                    };
                    let _ = writeln!(out, "        {}", dim(&format!("{title}{suffix}")));
                }
            }
            let _ = writeln!(out);
        }
    }

    if let Some(caveat) = card.get("caveat").and_then(Value::as_str) {
        let _ = writeln!(out, "  {}", dim(caveat));
        let _ = writeln!(out);
    }

    out
}

fn bold(s: &str) -> String {
    format!("\x1b[1m{s}\x1b[0m")
}

fn dim(s: &str) -> String {
    format!("\x1b[2m{s}\x1b[0m")
}

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

    #[test]
    fn summary_shows_decimal_scores_and_scores_of_incomplete_categories() {
        let card = serde_json::json!({
            "overall": 93,
            "dimensions": {
                "governance": { "score": 83.3, "pending": false, "items": [] },
                "compliance": { "score": 93.8, "pending": true, "items": [] },
                "security": { "pending": true, "items": [] }
            }
        });
        let text = render_summary(&card);
        assert!(text.contains("83/100"), "{text}");
        assert!(text.contains("94/100"), "{text}");
        assert!(!text.contains(" 0/100"), "{text}");
        assert!(text.contains("not assessed"), "{text}");
    }

    #[test]
    fn gateway_errors_are_transient_and_handler_errors_are_not() {
        for status in [502, 503, 504] {
            assert!(is_transient_status(status), "{status}");
        }
        for status in [400, 401, 402, 403, 404, 500] {
            assert!(!is_transient_status(status), "{status}");
        }
    }

    #[test]
    fn auth_failures_explain_the_tier_rather_than_the_status_code() {
        // A raw 401/402 tells the caller nothing about the anonymous → signed-in
        // → free-tier → credits ladder, and both have an offline escape hatch
        // worth naming at the point of failure.
        let unauthorised = api_error(401, "{}").to_string();
        assert!(unauthorised.contains("forklaunch login"), "{unauthorised}");
        assert!(unauthorised.contains("--offline"), "{unauthorised}");

        let payment = api_error(402, "{}").to_string();
        assert!(payment.contains("credits"), "{payment}");
        assert!(payment.contains("--offline"), "{payment}");
    }

    #[test]
    fn an_unexpected_status_keeps_the_body_rather_than_swallowing_it() {
        let err = api_error(500, "boom").to_string();
        assert!(err.contains("500"), "{err}");
        assert!(err.contains("boom"), "{err}");
    }

    #[test]
    fn the_studio_path_matches_what_the_dashboard_calls() {
        // The client hits `${STUDIO_API_URL}/studio-orchestrator/analysis/...`;
        // a mismatch here 404s against a service that is up and healthy.
        assert!(studio_url("/zip").ends_with("/studio-orchestrator/analysis/zip"));
        assert!(studio_url("/share").ends_with("/studio-orchestrator/analysis/share"));
    }

    #[test]
    fn the_prompt_scope_rides_on_the_job_poll_only_when_asked() {
        assert_eq!(job_path("j1", "not-met"), "/job/j1");
        assert_eq!(job_path("j1", "undecided"), "/job/j1?promptScope=undecided");
        assert_eq!(job_path("j1", "both"), "/job/j1?promptScope=both");
    }

    #[test]
    fn summary_renders_a_card_without_panicking_on_missing_fields() {
        // The API's response is untyped (`unknownSchema`), so the renderer has
        // to tolerate a card that omits anything.
        print_summary(&json!({}));
        print_summary(&json!({
            "overall": 72,
            "dimensions": { "security": { "score": 80, "items": [], "findings": [] } }
        }));
    }

    /// The scaffold case: a perfect rail with work still on it. Only findings
    /// cost points and an `info` finding costs none, so 100 alongside an unmet
    /// item is arithmetically correct and, unqualified, misleading.
    #[test]
    fn a_perfect_rail_still_reports_its_unmet_items() {
        let rendered = render_summary(&json!({
            "overall": 100,
            "dimensions": {
                "compliance": {
                    "score": 100,
                    "items": [
                        { "status": "met", "label": "Sensitive fields are encrypted at rest" },
                        { "status": "pending", "label": "Sensitive data is identified and handled according to its sensitivity" }
                    ],
                    "findings": []
                }
            }
        }));
        assert!(rendered.contains("100/100"), "{rendered}");
        assert!(rendered.contains("1 item outstanding"), "{rendered}");
        assert!(
            rendered.contains("? Sensitive data is identified"),
            "a review item must not render as met or failed: {rendered}"
        );
    }

    #[test]
    fn a_rail_with_nothing_outstanding_says_nothing_extra() {
        let rendered = render_summary(&json!({
            "overall": 100,
            "dimensions": {
                "security": {
                    "score": 100,
                    "items": [{ "status": "met", "label": "One customer cannot see or change another customer\u{2019}s data" }],
                    "findings": []
                }
            }
        }));
        assert!(!rendered.contains("outstanding"), "{rendered}");
    }

    /// One check firing once per module is one problem, not seven. Reporting
    /// the raw count overstates the work and buries what the problem is.
    #[test]
    fn repeated_findings_collapse_to_one_line_with_a_count() {
        let repeated: Vec<serde_json::Value> = (0..7)
            .map(|_| json!({ "title": "Sensitive fields are classified (iam)" }))
            .collect();
        let rendered = render_summary(&json!({
            "overall": 100,
            "dimensions": {
                "compliance": { "score": 100, "items": [], "findings": repeated }
            }
        }));
        assert!(rendered.contains("1 finding(s), 7 total"), "{rendered}");
        assert!(rendered.contains("(×7)"), "{rendered}");
    }

    #[test]
    fn distinct_findings_are_not_collapsed() {
        let rendered = render_summary(&json!({
            "overall": 60,
            "dimensions": {
                "compliance": {
                    "score": 60,
                    "items": [],
                    "findings": [
                        { "title": "Field encryptor is not registered" },
                        { "title": "Retention policies are missing" }
                    ]
                }
            }
        }));
        assert!(rendered.contains("2 finding(s)"), "{rendered}");
        // Nothing was collapsed, so there is no "of N" tail to add.
        assert!(!rendered.contains("total"), "{rendered}");
    }

    /// A rail the CLI cannot judge must stay "not assessed" — never 0/100, and
    /// never carry an outstanding count it did not compute.
    #[test]
    fn a_pending_rail_is_not_given_a_score() {
        let rendered = render_summary(&json!({
            "overall": 100,
            "dimensions": { "governance": { "score": 0, "pending": true } }
        }));
        assert!(rendered.contains("not assessed"), "{rendered}");
        // Asserted on the rail's own line: the overall header legitimately
        // reads "100/100", which contains "0/100" as a substring.
        let governance_line = rendered
            .lines()
            .find(|line| line.contains("Governance"))
            .expect("governance rail should render");
        assert!(!governance_line.contains("/100"), "{governance_line}");
        assert!(
            !governance_line.contains("outstanding"),
            "{governance_line}"
        );
    }
}

#[cfg(test)]
mod prompt_tests {
    use super::offline_prompt;
    use serde_json::json;

    fn card() -> serde_json::Value {
        json!({
            "overall": 72,
            "headline": "demo",
            "dimensions": {
                "security": {
                    "findings": [
                        {"severity": "high", "title": "Tenant filter", "detail": "worker.ts lacks setupTenantFilter", "fix": "Call setupTenantFilter."},
                        {"severity": "critical", "title": "Direct AI provider", "detail": "src/ai.ts imports openai", "fix": "Use createModelGatewayClient."}
                    ],
                    "items": [{"label": "Encryption at rest", "status": "unmet", "detail": "no key"}]
                },
                "compliance": {
                    "findings": [
                        {"severity": "info", "title": "Classify fields", "detail": "same"},
                        {"severity": "info", "title": "Classify fields", "detail": "same"}
                    ],
                    "items": [{"label": "Audit log", "status": "met"}]
                }
            }
        })
    }

    #[test]
    fn prompt_carries_loop_evidence_and_fixes_in_severity_order() {
        let p = offline_prompt(&card(), true);
        assert!(p.contains("Baseline: 72/100"));
        assert!(p.contains("forklaunch score --offline --json"));
        assert!(p.contains("forklaunch score --prompt --no-share"));
        assert!(p.contains("Remediation: Use createModelGatewayClient."));
        assert!(p.contains("Evidence: worker.ts lacks setupTenantFilter"));
        assert!(p.find("Direct AI provider").unwrap() < p.find("Tenant filter").unwrap());
        assert!(p.contains("Encryption at rest: unmet"));
        assert!(!p.contains("Audit log"));
    }

    #[test]
    fn identical_findings_collapse_with_a_count() {
        let p = offline_prompt(&card(), true);
        assert_eq!(p.matches("Classify fields").count(), 1);
        assert!(p.contains("Classify fields (x2)"));
        assert!(p.contains("Remediation: Inspect the cited code"));
    }
}