Skip to main content

lean_ctx_cli/cli/
gotchas_cmd.rs

1// SPDX-License-Identifier: Apache-2.0
2//! `lean-ctx gotchas`, plus the `upgrade` stub that points at the renamed
3//! command.
4
5use lean_ctx::core;
6
7const ACTIONS: &[&str] = &[
8    "list", "ls", "clear", "export", "stats", "reflect", "ledger",
9];
10const USAGE: &str = "Usage: lean-ctx gotchas [list|clear|export|stats|reflect]";
11
12pub fn cmd_gotchas(args: &[String]) {
13    let code = run(args);
14    if code != 0 {
15        std::process::exit(code);
16    }
17}
18
19/// Exit status: 0 on success, 2 for an unknown action, 1 when the store
20/// cannot be resolved, saved or exported (F9c: an error never exits 0).
21fn run(args: &[String]) -> i32 {
22    let action = args.first().map_or("list", std::string::String::as_str);
23    if matches!(action, "help" | "--help" | "-h") {
24        println!("{USAGE}");
25        return 0;
26    }
27    if !ACTIONS.contains(&action) {
28        eprintln!("lean-ctx gotchas: unknown action '{action}'");
29        eprintln!("{USAGE}");
30        return 2;
31    }
32    let project_root = match super::common::require_project_root() {
33        Ok(root) => root,
34        Err(error) => {
35            eprintln!("{error}");
36            return 1;
37        }
38    };
39
40    let report = match action {
41        "list" | "ls" => {
42            let store = core::gotcha_tracker::GotchaStore::load(&project_root);
43            store.format_list()
44        }
45        "clear" => {
46            let mut store = core::gotcha_tracker::GotchaStore::load(&project_root);
47            let count = store.gotchas.len();
48            store.clear();
49            if let Err(error) = store.save(&project_root) {
50                eprintln!("Clear failed: {error}");
51                return 1;
52            }
53            format!("Cleared {count} gotchas.")
54        }
55        "export" => {
56            let store = core::gotcha_tracker::GotchaStore::load(&project_root);
57            return match serde_json::to_string_pretty(&store.gotchas) {
58                Ok(json) => match released_export(&project_root, json) {
59                    Ok(document) => {
60                        super::common::print_released(&document);
61                        0
62                    }
63                    Err(reason) => super::common::exit_withheld(&reason),
64                },
65                Err(e) => {
66                    eprintln!("Export failed: {e}");
67                    1
68                }
69            };
70        }
71        "stats" => {
72            let store = core::gotcha_tracker::GotchaStore::load(&project_root);
73            [
74                "Bug Memory Stats:".to_string(),
75                format!("  Active gotchas:      {}", store.gotchas.len()),
76                format!(
77                    "  Errors detected:     {}",
78                    store.stats.total_errors_detected
79                ),
80                format!(
81                    "  Fixes correlated:    {}",
82                    store.stats.total_fixes_correlated
83                ),
84                format!("  Bugs prevented:      {}", store.stats.total_prevented),
85                format!("  Promoted to knowledge: {}", store.stats.gotchas_promoted),
86                format!("  Decayed/archived:    {}", store.stats.gotchas_decayed),
87                format!("  Session logs:        {}", store.error_log.len()),
88            ]
89            .join("\n")
90        }
91        // `ACTIONS` admitted only the reflect/ledger alias by this point.
92        _ => {
93            let store = core::gotcha_tracker::GotchaStore::load(&project_root);
94            core::gotcha_tracker::format_ledger(&store)
95        }
96    };
97    super::common::print_released(&released_report(&project_root, report));
98    0
99}
100
101/// Gotchas are distilled from error output and may quote it: every report is
102/// released like other CLI output and, as text for the person at the
103/// terminal, never recorded as a delivery.
104fn released_report(project_root: &str, report: String) -> String {
105    super::common::CliToolRun::new("ctx_knowledge", project_root, None)
106        .human_facing()
107        .deliver_text(|| report)
108}
109
110/// `export`: the JSON document, released without breaking it (a masked value
111/// stands in its place); `Err` is the content-free reason it was withheld.
112fn released_export(project_root: &str, json: String) -> Result<String, String> {
113    super::common::CliToolRun::new("ctx_knowledge", project_root, None).deliver_json(|| json)
114}
115
116/// Deprecated alias for `update`. Arguments are forwarded, so `upgrade --check`
117/// only checks instead of silently installing the latest release (#1906).
118pub fn cmd_upgrade(args: &[String]) {
119    println!("'upgrade' has been renamed to 'update'. Running 'lean-ctx update' instead.\n");
120    core::updater::run(args, &crate::setup::UpdateRefresh);
121}
122
123#[cfg(test)]
124mod tests {
125    /// F9c: an unknown action exits non-zero instead of printing the usage
126    /// and exiting 0.
127    #[test]
128    fn an_unknown_action_exits_non_zero() {
129        let args = |list: &[&str]| list.iter().map(ToString::to_string).collect::<Vec<_>>();
130        assert_eq!(super::run(&args(&["bogus"])), 2);
131        assert_eq!(super::run(&args(&["help"])), 0);
132    }
133
134    /// The reports and the export printed gotchas (quoted error output)
135    /// directly; they now pass the release point.
136    #[test]
137    fn gotcha_output_is_released() {
138        use crate::cli::common::carrier_tests_support::{AWS_KEY, governed, lineage, project};
139        let _data = lean_ctx::core::data_dir::isolated_data_dir();
140        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
141        governed();
142        let (_project, root) = project();
143        let list = "1 gotcha: cargo build fails on missing feature";
144        let printed = super::released_report(&root, list.to_string());
145        assert_eq!(printed, list, "admitted text keeps its bytes");
146        assert_eq!(lineage(&root, &printed), None);
147        let leaked = super::released_report(&root, format!("error: token {AWS_KEY}"));
148        assert!(!leaked.contains(AWS_KEY), "{leaked}");
149
150        let keyed = serde_json::json!([{ "trigger": format!("key {AWS_KEY}") }]).to_string();
151        let document = super::released_export(&root, keyed).expect("masked, not withheld");
152        assert!(!document.contains(AWS_KEY), "{document}");
153        assert!(serde_json::from_str::<serde_json::Value>(&document).is_ok());
154    }
155}