tokmd 1.13.0

Tokei-backed repo inventory receipts (Markdown/TSV/JSONL/CSV) for PRs, CI, and LLM workflows.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
use anyhow::Error;

pub(crate) fn format(err: &Error) -> String {
    let mut out = if let Some(token) = missing_path_as_unrecognized_subcommand(err) {
        format!("Error: Unrecognized subcommand '{token}'")
    } else {
        format!("Error: {err:#}")
    };
    let mut hints = suggestions(err);
    if out.starts_with("Error: Unrecognized subcommand ") {
        hints.retain(|h| {
            !h.contains("was intended as a subcommand")
                && !h.contains("was meant to be a subcommand")
        });
    }
    if !hints.is_empty() {
        out.push_str("\n\nHints:\n");
        for hint in hints {
            out.push_str("- ");
            out.push_str(&hint);
            out.push('\n');
        }
    }
    out
}

fn missing_path_as_unrecognized_subcommand(err: &Error) -> Option<String> {
    for entry in err.chain() {
        let message = entry.to_string();
        let token = message
            .strip_prefix("Path not found: ")
            .or_else(|| message.strip_prefix("Input path does not exist: "));

        if let Some(token) = token {
            let token = token.trim();
            if looks_like_bare_subcommand_token(token) {
                return Some(token.to_string());
            }
        }
    }

    None
}

fn looks_like_bare_subcommand_token(token: &str) -> bool {
    !token.is_empty()
        && !token.starts_with('-')
        && !token.contains('/')
        && !token.contains('\\')
        && !token.contains('.')
        && !token.contains(':')
}

fn suggestions(err: &Error) -> Vec<String> {
    let chain: Vec<String> = err.chain().map(|e| e.to_string()).collect();
    let haystack = chain.join(" | ").to_ascii_lowercase();
    let mut out: Vec<String> = Vec::new();

    if haystack.contains("git is not available on path")
        || haystack.contains("requires the 'git' feature")
    {
        push_hint(&mut out, "Install git and verify it with `git --version`.");
        push_hint(
            &mut out,
            "If git metrics are optional, disable them with `--no-git`.",
        );
    }

    if haystack.contains("not inside a git repository") {
        push_hint(
            &mut out,
            "Run the command from a git repository, or disable git-dependent behavior.",
        );
        push_hint(&mut out, "Initialize git first if needed: `git init`.");
    }

    if haystack.contains("rate limit")
        || haystack.contains("rate_limit")
        || haystack.contains("too many requests")
        || haystack.contains("http 429")
        || haystack.contains("status 429")
    {
        push_hint(
            &mut out,
            "The upstream service is limiting requests. Wait briefly, then retry.",
        );
        push_hint(
            &mut out,
            "Honor provider retry windows such as `Retry-After` when available.",
        );
        push_hint(
            &mut out,
            "Use a smaller input scope if this command contacts a remote service.",
        );
    }

    if haystack.contains("timed out")
        || haystack.contains("timeout")
        || haystack.contains("temporary")
        || haystack.contains("temporarily")
        || haystack.contains("connection reset")
        || haystack.contains("connection refused")
        || haystack.contains("broken pipe")
        || haystack.contains("dns")
        || haystack.contains("network error")
        || haystack.contains("service unavailable")
        || haystack.contains("http 503")
        || haystack.contains("status 503")
    {
        push_hint(
            &mut out,
            "This looks transient. Retry with backoff after network or service health recovers.",
        );
        push_hint(
            &mut out,
            "Check network, VPN, or proxy settings if retries keep failing.",
        );
    }

    if haystack.contains("parent traversal")
        || haystack.contains("must be relative")
        || haystack.contains("escapes scan root")
        || haystack.contains("scan root must not be empty")
        || haystack.contains("bounded path must not be empty")
    {
        push_hint(
            &mut out,
            "Pass paths inside the selected scan root; parent traversal (`..`) is rejected.",
        );
        push_hint(
            &mut out,
            "Use root-relative paths for scanned entries, or choose the containing directory as the root.",
        );

        if haystack.contains("escapes scan root") {
            push_hint(
                &mut out,
                "Avoid symlinked or redirected paths that resolve outside the scan root.",
            );
        }
    }

    if haystack.contains("path not found")
        || haystack.contains("input path does not exist")
        || haystack.contains("no such file or directory")
    {
        let mut did_you_mean = false;

        let mut extracted_bad_path = None;

        // Check for common typoed subcommands in "Path not found: <bad>"
        if haystack.contains("path not found") {
            // Find the original path string from the chain
            for e in err.chain() {
                let e_str = e.to_string();
                if e_str.starts_with("Path not found: ") {
                    let bad_path = e_str.trim_start_matches("Path not found: ").trim();
                    extracted_bad_path = Some(bad_path.to_string());
                    if looks_like_bare_subcommand_token(bad_path) {
                        let known = [
                            "lang",
                            "module",
                            "export",
                            "analyze",
                            "badge",
                            "init",
                            "completions",
                            "run",
                            "diff",
                            "context",
                            "check-ignore",
                            "tools",
                            "gate",
                            "cockpit",
                            "baseline",
                            "handoff",
                            "sensor",
                        ];

                        let mut best_match = None;
                        let mut best_dist = usize::MAX;

                        for k in known.iter() {
                            let d = levenshtein(bad_path, k);
                            if d < best_dist {
                                best_dist = d;
                                best_match = Some(*k);
                            }
                        }

                        if let Some(m) = best_match {
                            // Max distance 2 for a typo, or proportional to length
                            let threshold = std::cmp::max(2, m.len() / 3);
                            if best_dist <= threshold && best_dist > 0 {
                                push_hint(&mut out, &format!("Did you mean the subcommand `{m}`?"));
                                did_you_mean = true;
                            }
                        }
                    }
                    break;
                }
            }
        }

        if !did_you_mean {
            if let Some(bp) = extracted_bad_path {
                if looks_like_bare_subcommand_token(&bp) {
                    push_hint(
                        &mut out,
                        "Run `tokmd --help` to see a list of available subcommands.",
                    );
                    return out;
                }
            } else {
                push_hint(
                    &mut out,
                    "Run `tokmd --help` to see a list of available subcommands.",
                );
                return out;
            }
        }

        if did_you_mean {
            return out;
        }

        push_hint(&mut out, "Verify the input path exists and is readable.");
        push_hint(
            &mut out,
            "Use an absolute path to avoid working-directory confusion.",
        );
    }

    if haystack.contains("base ref") && haystack.contains("not found") {
        push_hint(
            &mut out,
            "Fetch refs (`git fetch --tags --prune`) and retry with `--base <ref>`.",
        );
        push_hint(
            &mut out,
            "You can also set `TOKMD_GIT_BASE_REF` to a valid default base ref.",
        );
    }

    if haystack.contains("failed to load diff source") || haystack.contains("invalid reference") {
        push_hint(
            &mut out,
            "If you meant to compare files, ensure they both exist locally.",
        );
        push_hint(
            &mut out,
            "If you meant to compare git refs, ensure the branch, tag, or commit exists.",
        );
    }

    if haystack.contains("unknown metric/finding key") {
        push_hint(
            &mut out,
            "Run `tokmd analyze --explain list` to see supported keys.",
        );
    }

    if haystack.contains("toml") && (haystack.contains("parse") || haystack.contains("invalid")) {
        push_hint(
            &mut out,
            "Check `tokmd.toml` syntax and key names, or regenerate with `tokmd init --force`.",
        );
    }

    out
}

fn push_hint(out: &mut Vec<String>, hint: &str) {
    if !out.iter().any(|h| h == hint) {
        out.push(hint.to_string());
    }
}

fn levenshtein(a: &str, b: &str) -> usize {
    let a_chars: Vec<char> = a.chars().collect();
    let b_chars: Vec<char> = b.chars().collect();

    if a_chars.is_empty() {
        return b_chars.len();
    }
    if b_chars.is_empty() {
        return a_chars.len();
    }

    let mut d = vec![vec![0; b_chars.len() + 1]; a_chars.len() + 1];

    for (i, row) in d.iter_mut().enumerate().take(a_chars.len() + 1) {
        row[0] = i;
    }
    for (j, item) in d[0].iter_mut().enumerate().take(b_chars.len() + 1) {
        *item = j;
    }

    for i in 1..=a_chars.len() {
        for j in 1..=b_chars.len() {
            let cost = if a_chars[i - 1] == b_chars[j - 1] {
                0
            } else {
                1
            };
            d[i][j] = std::cmp::min(
                std::cmp::min(d[i - 1][j] + 1, d[i][j - 1] + 1),
                d[i - 1][j - 1] + cost,
            );
        }
    }

    d[a_chars.len()][b_chars.len()]
}

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

    use super::{format, suggestions};

    #[test]
    fn suggests_for_missing_git() {
        let err = anyhow!("git is not available on PATH");
        let hints = suggestions(&err);
        assert!(hints.iter().any(|h| h.contains("git --version")));
        assert!(hints.iter().any(|h| h.contains("--no-git")));
    }

    #[test]
    fn suggests_for_typo_subcommand() {
        let err = anyhow!("Path not found: anolyze");
        let hints = suggestions(&err);
        assert!(
            hints
                .iter()
                .any(|h| h.contains("Did you mean the subcommand `analyze`?"))
        );
        assert!(!hints.iter().any(|h| h.contains("Run `tokmd --help`")));
        assert!(!hints.iter().any(|h| h.contains("input path exists")));
        assert!(
            !hints
                .iter()
                .any(|h| h.contains("subcommand, it is not recognized"))
        );
    }

    #[test]
    fn format_rewrites_bare_missing_path_as_unrecognized_subcommand() {
        let err = anyhow!("Path not found: frobnicate");
        let rendered = format(&err);
        assert!(rendered.contains("Error: Unrecognized subcommand 'frobnicate'"));
        assert!(!rendered.contains("Error: Path not found: frobnicate"));
        assert!(!rendered.contains("was intended as a subcommand"));
        assert!(rendered.contains("Run `tokmd --help` to see a list of available subcommands."));
        assert!(!rendered.contains("Verify the input path exists and is readable."));
    }

    #[test]
    fn format_preserves_path_shaped_missing_path_errors() {
        let err = anyhow!("Path not found: missing/file.rs");
        let rendered = format(&err);
        assert!(rendered.contains("Error: Path not found: missing/file.rs"));
        assert!(!rendered.contains("Unrecognized subcommand"));
    }

    #[test]
    fn suggests_for_missing_path() {
        let err = anyhow!("Path not found: missing/file.rs");
        let hints = suggestions(&err);
        assert!(hints.iter().any(|h| h.contains("input path exists")));
        assert!(hints.iter().any(|h| h.contains("absolute path")));
        assert!(!hints.iter().any(|h| h.contains("Run `tokmd --help`")));
    }

    #[test]
    fn suggests_help_for_unrecognized_bare_subcommand() {
        let err = anyhow!("Path not found: frobnicate");
        let hints = suggestions(&err);
        assert!(
            hints
                .iter()
                .any(|h| h.contains("Run `tokmd --help` to see a list of available subcommands."))
        );
        assert!(!hints.iter().any(|h| h.contains("input path exists")));
    }

    #[test]
    fn suggests_for_parent_traversal() {
        let err = anyhow!("Bounded path must not contain parent traversal: ../secret.txt");
        let hints = suggestions(&err);
        assert!(
            hints
                .iter()
                .any(|h| h.contains("inside the selected scan root"))
        );
        assert!(hints.iter().any(|h| h.contains("root-relative paths")));
    }

    #[test]
    fn suggests_for_root_escape() {
        let err = anyhow!("Bounded path escapes scan root C:/repo: C:/secret.txt");
        let rendered = format(&err);
        assert!(rendered.contains("Error:"));
        assert!(rendered.contains("Hints:"));
        assert!(rendered.contains("inside the selected scan root"));
        assert!(rendered.contains("resolve outside the scan root"));
    }

    #[test]
    fn resolve_failures_do_not_get_bounded_path_hints() {
        let err = anyhow!("Failed to resolve scan root C:/repo: permission denied");
        let hints = suggestions(&err);
        assert!(
            !hints
                .iter()
                .any(|h| h.contains("parent traversal") || h.contains("root-relative"))
        );
    }

    #[test]
    fn suggests_for_unknown_explain_key() {
        let err = anyhow!("Unknown metric/finding key 'foo'.");
        let hints = suggestions(&err);
        assert!(hints.iter().any(|h| h.contains("--explain list")));
    }

    #[test]
    fn suggests_for_missing_diff_source() {
        let err = anyhow!(
            "Failed to load diff source 'missing_file.json': Failed to create worktree for 'missing_file.json': git worktree add failed for 'missing_file.json'"
        );
        let hints = suggestions(&err);
        assert!(
            hints
                .iter()
                .any(|h| h.contains("ensure they both exist locally"))
        );
        assert!(
            hints
                .iter()
                .any(|h| h.contains("ensure the branch, tag, or commit exists"))
        );
    }

    #[test]
    fn format_includes_hints_section() {
        let err = anyhow!("Path not found: no-file");
        let rendered = format(&err);
        assert!(rendered.contains("Error:"));
        assert!(rendered.contains("Hints:"));
    }

    #[test]
    fn suggests_for_rate_limit_errors() {
        let err = anyhow!("GitHub returned HTTP 429 Too Many Requests");
        let hints = suggestions(&err);
        assert!(hints.iter().any(|h| h.contains("limiting requests")));
        assert!(hints.iter().any(|h| h.contains("Retry-After")));
        assert!(hints.iter().any(|h| h.contains("smaller input scope")));
    }

    #[test]
    fn suggests_for_transient_network_errors() {
        let err = anyhow!("request timed out while contacting remote service");
        let hints = suggestions(&err);
        assert!(hints.iter().any(|h| h.contains("looks transient")));
        assert!(hints.iter().any(|h| h.contains("VPN, or proxy")));
    }
}