fallow-cli 3.34.1

CLI for fallow, codebase intelligence for TypeScript and JavaScript
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
//! Finding identity keys and one normalizer per envelope shape.
//!
//! Every surface reduces its output to a [`KeySet`], so the invariants compare
//! identity and never presentation (actions, columns, prose, timings).

use std::collections::BTreeSet;
use std::fmt;

use serde_json::Value;

/// Identity of one finding: (issue kind, root-relative path, symbol or package, line).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FindingKey {
    pub kind: String,
    pub path: String,
    pub symbol: String,
    pub line: u64,
}

impl fmt::Display for FindingKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {}:{}", self.kind, self.path, self.line)?;
        if !self.symbol.is_empty() {
            write!(f, " {}", self.symbol)?;
        }
        Ok(())
    }
}

pub type KeySet = BTreeSet<FindingKey>;

/// Top-level arrays of a dead-code envelope that do not hold findings.
const DEAD_CODE_NON_FINDING_ARRAYS: &[&str] = &["workspace_diagnostics", "next_steps"];

/// Fields tried in order for the symbol of a dead-code finding.
const SYMBOL_FIELDS: &[&str] = &[
    "export_name",
    "package_name",
    "member_name",
    "name",
    "specifier",
    "entry_name",
    "catalog_name",
];

/// The issue kind the harness uses for every clone group.
pub const DUPLICATION_KIND: &str = "code-duplication";
/// The issue kind the harness uses for every health finding.
pub const COMPLEXITY_KIND: &str = "complexity";

/// Keys of every finding in a dead-code envelope (CLI `dead-code`, the typed
/// programmatic result, MCP `analyze` and `check_changed`, and the `check`
/// section of a combined report).
pub fn dead_code_keys(envelope: &Value) -> KeySet {
    dead_code_findings(envelope)
        .map(|(kind, item)| dead_code_key(kind, item))
        .collect()
}

/// Every finding object of a dead-code envelope, with its issue kind.
fn dead_code_findings(envelope: &Value) -> impl Iterator<Item = (&str, &Value)> {
    envelope
        .as_object()
        .into_iter()
        .flatten()
        .filter(|(kind, _)| !DEAD_CODE_NON_FINDING_ARRAYS.contains(&kind.as_str()))
        .filter_map(|(kind, value)| Some((kind.as_str(), value.as_array()?)))
        .flat_map(|(kind, items)| {
            items
                .iter()
                .filter(|item| item.is_object())
                .map(move |item| (kind, item))
        })
}

/// One dead-code finding with its `finding_id`, `None` when the finding
/// carries no id.
pub type IdentifiedFinding = (FindingKey, Option<String>);

/// Every dead-code finding of an envelope with its `finding_id`, sorted. A
/// list and not a set, so two findings with one key and one id stay two
/// entries and invariant I10 sees the duplicate id.
pub fn dead_code_finding_ids(envelope: &Value) -> Vec<IdentifiedFinding> {
    let mut findings: Vec<IdentifiedFinding> = dead_code_findings(envelope)
        .map(|(kind, item)| {
            (
                dead_code_key(kind, item),
                item["finding_id"].as_str().map(str::to_string),
            )
        })
        .collect();
    findings.sort();
    findings
}

/// Every security finding of an envelope with its `finding_id`, sorted. The
/// key is the rule (the category, or the kind without one), the path, the line
/// and the column: the parts of the security id.
pub fn security_finding_ids(envelope: &Value) -> Vec<IdentifiedFinding> {
    let mut findings: Vec<IdentifiedFinding> = envelope["security_findings"]
        .as_array()
        .into_iter()
        .flatten()
        .map(|item| {
            let rule = item["category"]
                .as_str()
                .or_else(|| item["kind"].as_str())
                .unwrap_or_default();
            (
                FindingKey {
                    kind: format!("security/{rule}"),
                    path: item["path"].as_str().unwrap_or_default().to_string(),
                    symbol: format!("col {}", item["col"].as_u64().unwrap_or(0)),
                    line: item["line"].as_u64().unwrap_or(0),
                },
                item["finding_id"]
                    .as_str()
                    .filter(|id| !id.is_empty())
                    .map(str::to_string),
            )
        })
        .collect();
    findings.sort();
    findings
}

fn dead_code_key(kind: &str, item: &Value) -> FindingKey {
    if let Some(key) = package_cycle_key(kind, item) {
        return key;
    }
    let path = item["path"]
        .as_str()
        .map_or_else(|| joined_strings(&item["files"]), str::to_string);
    let symbol = SYMBOL_FIELDS
        .iter()
        .find_map(|field| item[*field].as_str())
        .map(|symbol| match item["parent_name"].as_str() {
            Some(parent) => format!("{parent}.{symbol}"),
            None => symbol.to_string(),
        })
        .or_else(|| suppression_symbol(item))
        .unwrap_or_default();
    FindingKey {
        kind: kind.to_string(),
        path,
        symbol,
        line: item["line"].as_u64().unwrap_or(0),
    }
}

/// The key of a package cycle, `None` for every other finding. A package
/// cycle has no `path`, `files` or name field. Its path joins the files of
/// its example imports, sorted and without duplicates, so a scope check sees
/// real files. Its symbol joins the packages of the cycle in report order.
fn package_cycle_key(kind: &str, item: &Value) -> Option<FindingKey> {
    let packages = item["packages"].as_array()?;
    let mut files: Vec<&str> = item["edges"]
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|edge| edge["path"].as_str())
        .collect();
    files.sort_unstable();
    files.dedup();
    Some(FindingKey {
        kind: kind.to_string(),
        path: files.join(" -> "),
        symbol: packages
            .iter()
            .filter_map(Value::as_str)
            .collect::<Vec<_>>()
            .join(" -> "),
        line: 0,
    })
}

/// The symbol of a stale suppression: the directive and what it suppresses,
/// as in its audit key. Without it, two stale suppressions in one file would
/// share an identity.
fn suppression_symbol(item: &Value) -> Option<String> {
    let origin = item["origin"].as_object()?;
    let target = origin
        .get("issue_kind")
        .or_else(|| origin.get("export_name"))
        .and_then(Value::as_str)
        .unwrap_or_default();
    let scope = if origin.get("is_file_level").and_then(Value::as_bool) == Some(true) {
        "file"
    } else {
        "line"
    };
    let missing_reason = item["missing_reason"].as_bool() == Some(true);
    Some(format!(
        "{}:{scope}:{target}{}",
        origin
            .get("type")
            .and_then(Value::as_str)
            .unwrap_or_default(),
        if missing_reason {
            ":missing-reason"
        } else {
            ""
        }
    ))
}

fn joined_strings(value: &Value) -> String {
    value.as_array().map_or_else(String::new, |items| {
        items
            .iter()
            .filter_map(|item| item.as_str().or_else(|| item["path"].as_str()))
            .collect::<Vec<_>>()
            .join(" -> ")
    })
}

/// Keys of every clone group in a dupes envelope. One key per group: the path
/// joins the instance files with ` -> ` (as for a circular dependency) and the
/// symbol lists each instance as `path:start-end@start_col-end_col`, so a
/// surface that drops a single instance changes the key. A clone can start or
/// end inside a line, and the columns tell which part of the line it holds.
pub fn dupes_keys(envelope: &Value) -> KeySet {
    let mut keys = KeySet::new();
    for group in envelope["clone_groups"].as_array().into_iter().flatten() {
        let mut instances: Vec<(String, u64, u64, u64, u64)> = group["instances"]
            .as_array()
            .into_iter()
            .flatten()
            .map(|instance| {
                let number = |field: &str| instance[field].as_u64().unwrap_or(0);
                (
                    instance["file"].as_str().unwrap_or_default().to_string(),
                    number("start_line"),
                    number("end_line"),
                    number("start_col"),
                    number("end_col"),
                )
            })
            .collect();
        instances.sort();
        let Some(first) = instances.first() else {
            continue;
        };
        let mut files: Vec<&str> = instances.iter().map(|(file, ..)| file.as_str()).collect();
        files.dedup();
        keys.insert(FindingKey {
            kind: DUPLICATION_KIND.to_string(),
            path: files.join(" -> "),
            symbol: instances
                .iter()
                .map(|(file, start, end, start_col, end_col)| {
                    format!("{file}:{start}-{end}@{start_col}-{end_col}")
                })
                .collect::<Vec<_>>()
                .join(" | "),
            line: first.1,
        });
    }
    keys
}

/// One instance of a clone-group symbol (`path:start-end@start_col-end_col`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CloneInstance<'a> {
    pub path: &'a str,
    pub start_line: u64,
    pub end_line: u64,
    pub start_col: u64,
    pub end_col: u64,
}

/// The instances of a clone-group symbol. An instance that does not parse is
/// `None`.
pub fn clone_instances(symbol: &str) -> impl Iterator<Item = Option<CloneInstance<'_>>> {
    symbol.split(" | ").map(|instance| {
        let (location, columns) = instance.rsplit_once('@')?;
        let (path, lines) = location.rsplit_once(':')?;
        let (start_line, end_line) = lines.split_once('-')?;
        let (start_col, end_col) = columns.split_once('-')?;
        Some(CloneInstance {
            path,
            start_line: start_line.parse().ok()?,
            end_line: end_line.parse().ok()?,
            start_col: start_col.parse().ok()?,
            end_col: end_col.parse().ok()?,
        })
    })
}

/// Keys of every function finding in a health envelope.
pub fn health_keys(envelope: &Value) -> KeySet {
    envelope["findings"]
        .as_array()
        .into_iter()
        .flatten()
        .map(|finding| FindingKey {
            kind: COMPLEXITY_KIND.to_string(),
            path: finding["path"].as_str().unwrap_or_default().to_string(),
            symbol: finding["name"].as_str().unwrap_or_default().to_string(),
            line: finding["line"].as_u64().unwrap_or(0),
        })
        .collect()
}

/// Keys of the three sections of a combined (bare `fallow`) report.
pub fn combined_keys(envelope: &Value) -> SectionKeys {
    SectionKeys {
        dead_code: dead_code_keys(&envelope["check"]),
        dupes: dupes_keys(&envelope["dupes"]),
        health: health_keys(&envelope["health"]),
    }
}

/// Per-domain key sets of a report that carries several analyses.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SectionKeys {
    pub dead_code: KeySet,
    pub dupes: KeySet,
    pub health: KeySet,
}

impl SectionKeys {
    /// The union of all domains.
    pub fn all(&self) -> KeySet {
        self.dead_code
            .iter()
            .chain(&self.dupes)
            .chain(&self.health)
            .cloned()
            .collect()
    }
}

/// Keys of an audit report, split by attribution.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AuditKeys {
    pub introduced: KeySet,
    pub inherited: KeySet,
    pub verdict: String,
}

/// A function that reduces one envelope shape to keys.
type Normalizer = fn(&Value) -> KeySet;

/// Keys of an audit report (CLI `audit`, MCP `audit`, `fallow_api::run_audit`).
pub fn audit_keys(envelope: &Value) -> AuditKeys {
    let mut keys = AuditKeys {
        verdict: envelope["verdict"].as_str().unwrap_or_default().to_string(),
        ..AuditKeys::default()
    };
    let sections: [(&str, Normalizer); 3] = [
        ("dead_code", dead_code_keys),
        ("duplication", dupes_keys),
        ("complexity", health_keys),
    ];
    for (section, normalize) in sections {
        let Some(map) = envelope[section].as_object() else {
            continue;
        };
        for (field, value) in map {
            let Some(items) = value.as_array() else {
                continue;
            };
            for item in items {
                let mut single = serde_json::Map::new();
                single.insert(field.clone(), Value::Array(vec![item.clone()]));
                let target = if item["introduced"].as_bool() == Some(false) {
                    &mut keys.inherited
                } else {
                    &mut keys.introduced
                };
                target.extend(normalize(&Value::Object(single)));
            }
        }
    }
    keys
}

/// Keys of any machine envelope, dispatched on its `kind` member.
///
/// # Panics
///
/// Panics on an envelope kind the harness has no normalizer for, so a new
/// shape cannot pass as an empty key set.
pub fn envelope_keys(envelope: &Value) -> KeySet {
    match envelope["kind"].as_str() {
        Some("dead-code" | "architecture") => dead_code_keys(envelope),
        Some("dupes") => dupes_keys(envelope),
        Some("health") => health_keys(envelope),
        Some("combined") => combined_keys(envelope).all(),
        Some("audit") => {
            let keys = audit_keys(envelope);
            keys.introduced.union(&keys.inherited).cloned().collect()
        }
        other => panic!("no normalizer for envelope kind {other:?}: {envelope}"),
    }
}

/// Parse the text content of an MCP `tools/call` result into its envelope.
///
/// # Panics
///
/// Panics when the result is an error or carries no JSON text.
pub fn mcp_result_envelope(result: &Value) -> Value {
    assert_ne!(result["isError"], true, "MCP tool call failed: {result}");
    let text = result["content"][0]["text"]
        .as_str()
        .unwrap_or_else(|| panic!("MCP result has no text content: {result}"));
    serde_json::from_str(text)
        .unwrap_or_else(|err| panic!("MCP result text is not JSON ({err}): {text}"))
}

/// Render a key set, one key per line, for a failure message.
pub fn render(keys: &KeySet) -> String {
    if keys.is_empty() {
        return "    (none)".to_string();
    }
    keys.iter()
        .map(|key| format!("    {key}"))
        .collect::<Vec<_>>()
        .join("\n")
}