frame 0.2.0

A markdown task tracker with a terminal UI for humans and a CLI for agents
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
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
//! What a `ref:` or `spec:` value points at, and whether it is there.
//!
//! The two metadata keys mean different things — a spec is the document a task
//! implements, a ref is a file it touches — but they are written identically and
//! carry the same kind of value: a path relative to the project root, optionally
//! followed by a `#anchor`, a `:line` or `:line:col`. So they resolve
//! identically, and this module is the one place that says how.
//!
//! It exists because they did not. `spec:` stripped the anchor before looking on
//! disk and `ref:` did not, so `doc/design.md#rationale` was a valid spec and a
//! broken ref — the same string, the same file, two answers, in two copies of
//! the rule that had drifted apart in `check` and in `clean`. Neither knew about
//! `src/parser.rs:807` at all, which is how most refs to code get written.
//!
//! **Only the file is validated.** An anchor may name a heading that moved and a
//! line number goes stale on the next edit above it; neither is a broken
//! reference in the sense worth reporting, and frame does not read the target to
//! find out.
//!
//! It also says how a value is **spelled** ([`normalize`]). One file has many
//! spellings — `real.md`, `./real.md`, `sub/../real.md` — and every one of them
//! resolves, so a stored list could carry the same file twice and `rm` could
//! fail to find what was plainly there. Storing the normal form and comparing by
//! it is what makes the list behave like a set of files rather than a set of
//! strings.

use std::path::Path;

/// Every reading of a `ref:`/`spec:` value, most literal first.
///
/// The whole value comes first so a filename that genuinely contains `#` or `:`
/// is reachable — the suffixes are stripped only when the literal path is not
/// there, which makes this strictly more permissive than checking either form
/// alone.
fn candidates(value: &str) -> Vec<&str> {
    let mut out = vec![value];
    let anchorless = strip_anchor(value);
    let lineless = strip_line_ref(value);
    for c in [anchorless, lineless, strip_line_ref(anchorless)] {
        if !c.is_empty() && !out.contains(&c) {
            out.push(c);
        }
    }
    out
}

/// The path part of a value carrying an anchor: everything before the first `#`.
pub fn strip_anchor(value: &str) -> &str {
    value.split('#').next().unwrap_or(value)
}

/// The path part of a value carrying a line reference: `:N`, `:N-M`, or a
/// second such segment for a column (`:N:C`).
///
/// Bounded to two strippings so a path of the shape `a:1:2:3` cannot be eaten
/// down to `a` — beyond a line and a column, the colon is part of the name.
pub fn strip_line_ref(value: &str) -> &str {
    let mut out = value;
    for _ in 0..2 {
        match out.rsplit_once(':') {
            Some((head, tail)) if !head.is_empty() && is_line_segment(tail) => out = head,
            _ => break,
        }
    }
    out
}

/// `807` or `807-820` — a line, or a range of them.
fn is_line_segment(s: &str) -> bool {
    let (start, end) = match s.split_once('-') {
        Some((a, b)) => (a, Some(b)),
        None => (s, None),
    };
    let digits = |x: &str| !x.is_empty() && x.bytes().all(|b| b.is_ascii_digit());
    digits(start) && end.is_none_or(digits)
}

/// The value with `.` and `..` segments folded away, so that every spelling of
/// one file gives one string.
///
/// **Lexical, and over the whole value.** Nothing is read from disk, so a
/// symlink cannot change the answer and a path that does not exist normalizes
/// just as well as one that does. Folding runs over `/`-separated segments of
/// the entire value rather than a stripped path part, which is what keeps the
/// suffix safe: neither a `#anchor` nor a `:line` can contain a `/`, so
/// `./sub/../real.md:807` folds to `real.md:807` while `doc/issue#3.md` and
/// `src/odd:9.rs` are left exactly as they are. Doing it the other way round
/// would mean choosing a candidate first — and `candidates` tries the literal
/// value ahead of the stripped ones precisely because that choice cannot be made
/// reliably.
///
/// Two things survive folding on purpose: a leading `/`, so the value stays
/// absolute, and a leading `..` with nothing to pop, so it still escapes.
/// Whether either is *allowed* is a separate question from how it is spelled.
pub fn normalize(value: &str) -> String {
    let value = value.trim();
    // An empty value stays empty. Folding it to `.` would name the project root,
    // which exists — turning a value `exists` refuses into one it accepts.
    if value.is_empty() {
        return String::new();
    }
    let absolute = value.starts_with('/');
    let mut out: Vec<&str> = Vec::new();
    for segment in value.split('/') {
        match segment {
            // `.` and the empty segment from `//` (or a trailing slash) carry no
            // information; an absolute path's leading empty segment is already
            // recorded in `absolute`.
            "." | "" => {}
            ".." => match out.last() {
                // Nothing to cancel: at the root of an absolute path `..` is
                // itself, and a leading `..` is kept so containment can see it.
                None | Some(&"..") => out.push(segment),
                Some(_) => {
                    out.pop();
                }
            },
            _ => out.push(segment),
        }
    }
    let joined = out.join("/");
    match (absolute, joined.is_empty()) {
        (true, _) => format!("/{joined}"),
        // Everything folded away — `./` or `sub/..` — which names the project
        // root itself.
        (false, true) => ".".to_string(),
        (false, false) => joined,
    }
}

/// Why a value cannot be stored, beyond the file not being there.
///
/// Each of these resolves perfectly well *here* — that is what makes them worth
/// refusing rather than reporting broken. What they do not do is survive the
/// trip to another clone, where the project lives at a different absolute path
/// and whatever sits outside it is not the same.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathRejection {
    /// An absolute path: `/etc/hosts`, or even the project's own files spelled
    /// from the filesystem root.
    Absolute,
    /// Escapes the project root after folding: `../outside.md`.
    Escapes,
    /// Inside the project, but git is ignoring it: `scratch/notes.md`.
    Ignored,
}

impl PathRejection {
    /// The clause a message puts after the path, in the shape "<path> …".
    pub fn reason(self) -> &'static str {
        match self {
            PathRejection::Absolute => {
                "is absolute — a ref is relative to the project root, so this one \
                 means nothing on another machine"
            }
            PathRejection::Escapes => {
                "leaves the project root — nothing outside it travels with the project"
            }
            PathRejection::Ignored => {
                "is ignored by git — it is in this working copy and will not be in \
                 anyone else's"
            }
        }
    }
}

/// Whether a value names something the project can actually point at, or `None`
/// when it is fine.
///
/// Pure: no disk, no git, no `project_root` argument. A path that escapes does
/// so by its own spelling, and asking the filesystem could only weaken the
/// answer — `../outside.md` resolving to something real is the problem, not a
/// mitigation.
pub fn containment(value: &str) -> Option<PathRejection> {
    let normalized = normalize(value);
    if normalized.is_empty() {
        return None; // Not a containment question; `exists` refuses it already.
    }
    if Path::new(&normalized).is_absolute() {
        return Some(PathRejection::Absolute);
    }
    if normalized == ".." || normalized.starts_with("../") {
        return Some(PathRejection::Escapes);
    }
    None
}

/// Whether two values name the same file, whatever spelling each uses.
///
/// The suffix is part of the identity: `real.md` and `real.md:807` are different
/// references, and removing one must not take the other with it.
pub fn same_path(a: &str, b: &str) -> bool {
    normalize(a) == normalize(b)
}

/// The reading of a value that actually finds a file — the path it points at,
/// with any suffix already accounted for. `None` when nothing resolves.
///
/// Anything that has to hand the path to something else (git, say) wants this
/// rather than the raw value: `src/parser.rs:807` is not a filename.
pub fn resolved(project_root: &Path, value: &str) -> Option<String> {
    let value = value.trim();
    if value.is_empty() {
        return None;
    }
    candidates(value)
        .into_iter()
        .find(|c| project_root.join(c).exists())
        .map(|c| c.to_string())
}

/// Whether a `ref:`/`spec:` value resolves to a file in the project.
pub fn exists(project_root: &Path, value: &str) -> bool {
    resolved(project_root, value).is_some()
}

/// Which of `values` point at a file git is ignoring, in the order given.
///
/// **Batched.** One `git check-ignore` for the whole list rather than one per
/// path — the same call `fr check`'s local-file leak guard already makes. Paths
/// are passed relative to the project root and git resolves them against it, so
/// a project living in a subdirectory of its repo needs no special handling.
///
/// **Asks about the resolved path, not the raw value.** A value carrying a
/// suffix is not a filename, and `scratch/notes.md:12` would miss a `*.md` rule
/// that `scratch/notes.md` matches. Values that resolve to nothing are left out
/// entirely: a broken ref is already reported as one, and asking git about a
/// file that is not there would answer a different question.
///
/// **Empty when frame cannot tell** — outside a repo, or with `git`
/// unavailable. Callers read that as "allow", because a guess either way would
/// be worse than the silence.
///
/// A *tracked* path is never reported, which is `io::git::ignored_paths`'
/// deliberate behaviour: ignore rules do not apply to files already in the
/// index, so a tracked one does travel, whatever `.gitignore` says about it.
pub fn ignored(project_root: &Path, values: &[String]) -> Vec<String> {
    let (probes, owners): (Vec<String>, Vec<usize>) = values
        .iter()
        .enumerate()
        .filter_map(|(i, v)| resolved(project_root, v).map(|p| (p, i)))
        .unzip();
    if probes.is_empty() {
        return Vec::new();
    }
    let Some(matched) = crate::io::git::ignored_paths(project_root, &probes) else {
        return Vec::new();
    };
    probes
        .iter()
        .zip(owners)
        .filter(|(probe, _)| matched.contains(probe))
        .map(|(_, i)| values[i].clone())
        .collect()
}

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

    fn project() -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        fs::create_dir_all(dir.path().join("doc")).unwrap();
        fs::create_dir_all(dir.path().join("src")).unwrap();
        fs::write(dir.path().join("doc/design.md"), "x").unwrap();
        fs::write(dir.path().join("doc/issue#3.md"), "x").unwrap();
        fs::write(dir.path().join("src/parser.rs"), "x").unwrap();
        fs::write(dir.path().join("src/odd:9.rs"), "x").unwrap();
        dir
    }

    #[test]
    fn a_plain_path_resolves() {
        let dir = project();
        assert!(exists(dir.path(), "doc/design.md"));
        assert!(!exists(dir.path(), "doc/missing.md"));
    }

    #[test]
    fn an_anchor_is_ignored() {
        let dir = project();
        assert!(exists(dir.path(), "doc/design.md#rationale"));
        assert!(!exists(dir.path(), "doc/missing.md#rationale"));
    }

    #[test]
    fn a_line_reference_is_ignored() {
        let dir = project();
        assert!(exists(dir.path(), "src/parser.rs:807"));
        assert!(exists(dir.path(), "src/parser.rs:807-820"));
        assert!(exists(dir.path(), "src/parser.rs:807:12"));
        assert!(!exists(dir.path(), "src/missing.rs:807"));
        assert!(!exists(dir.path(), "src/missing.rs:807-820"));
    }

    /// The literal value wins, so a `#` or a `:` in a filename is not mistaken
    /// for a suffix.
    #[test]
    fn a_hash_or_colon_in_the_filename_still_resolves() {
        let dir = project();
        assert!(exists(dir.path(), "doc/issue#3.md"));
        assert!(exists(dir.path(), "src/odd:9.rs"));
    }

    #[test]
    fn an_empty_or_suffix_only_value_resolves_to_nothing() {
        let dir = project();
        assert!(!exists(dir.path(), ""));
        assert!(!exists(dir.path(), "   "));
        assert!(!exists(dir.path(), "#anchor"));
        assert!(!exists(dir.path(), ":807"));
    }

    #[test]
    fn a_colon_run_is_not_eaten_past_a_column() {
        assert_eq!(strip_line_ref("a:1:2:3"), "a:1");
        assert_eq!(strip_line_ref("src/parser.rs"), "src/parser.rs");
        assert_eq!(strip_line_ref("src/parser.rs:807"), "src/parser.rs");
        assert_eq!(strip_line_ref("src/parser.rs:807-820"), "src/parser.rs");
    }

    #[test]
    fn normalize_folds_dot_and_dotdot() {
        assert_eq!(normalize("./sub/../real.md"), "real.md");
        assert_eq!(normalize("doc/../src/parser.rs"), "src/parser.rs");
        assert_eq!(normalize("./real.md"), "real.md");
        assert_eq!(normalize("a//b"), "a/b");
        assert_eq!(normalize("doc/"), "doc");
        assert_eq!(normalize("  real.md  "), "real.md");
        // Already normal: folding is idempotent, which is what lets a stored
        // value be compared against a fresh one without re-deriving either.
        assert_eq!(normalize("src/parser.rs"), "src/parser.rs");
        assert_eq!(normalize(normalize("./sub/../real.md").as_str()), "real.md");
    }

    /// The suffix rides along untouched — folding whole `/`-separated segments
    /// cannot see inside one, which is the entire reason it is done that way.
    #[test]
    fn normalize_leaves_the_suffix_alone() {
        assert_eq!(normalize("./sub/../real.md:807"), "real.md:807");
        assert_eq!(normalize("./doc/../design.md#why"), "design.md#why");
        assert_eq!(normalize("doc/issue#3.md"), "doc/issue#3.md");
        assert_eq!(normalize("src/odd:9.rs"), "src/odd:9.rs");
        assert_eq!(normalize("src/parser.rs:807-820"), "src/parser.rs:807-820");
    }

    /// Absoluteness and an unpoppable `..` are the two things a later
    /// containment check needs to still be able to see.
    #[test]
    fn normalize_keeps_what_makes_a_path_escape() {
        assert_eq!(normalize("../outside.md"), "../outside.md");
        assert_eq!(normalize("a/../../b.md"), "../b.md");
        assert_eq!(normalize("../../b.md"), "../../b.md");
        assert_eq!(normalize("/etc/hosts"), "/etc/hosts");
        assert_eq!(normalize("/etc/../etc/hosts"), "/etc/hosts");
        // `..` above the root of an absolute path has nowhere to go.
        assert_eq!(normalize("/../etc/hosts"), "/../etc/hosts");
    }

    /// A value that folds to the project root becomes `.` — but an *empty* one
    /// stays empty, because `.` exists and empty does not, and normalization
    /// must never turn a value `exists` refuses into one it accepts.
    #[test]
    fn normalize_handles_values_that_fold_to_nothing() {
        assert_eq!(normalize("."), ".");
        assert_eq!(normalize("./"), ".");
        assert_eq!(normalize("sub/.."), ".");
        assert_eq!(normalize(""), "");
        assert_eq!(normalize("   "), "");
        assert!(!exists(project().path(), &normalize("")));
    }

    /// A file with a name of its own that happens to contain `..` is not a
    /// traversal — only a whole segment counts.
    #[test]
    fn normalize_does_not_fold_inside_a_segment() {
        assert_eq!(normalize("doc/..hidden.md"), "doc/..hidden.md");
        assert_eq!(normalize("doc/a..b.md"), "doc/a..b.md");
        assert_eq!(normalize("...md"), "...md");
    }

    /// A git repo whose `.gitignore` covers `scratch/`, alongside the ordinary
    /// files. Returns `None` when git is unavailable, as `io::git`'s own tests
    /// do — every caller skips rather than failing.
    fn ignoring_project(dir: &Path) -> Option<()> {
        let git = |args: &[&str]| {
            std::process::Command::new("git")
                .current_dir(dir)
                .args(args)
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .status()
                .map(|s| s.success())
                .unwrap_or(false)
        };
        fs::create_dir_all(dir.join("scratch")).ok()?;
        fs::create_dir_all(dir.join("doc")).ok()?;
        fs::write(dir.join(".gitignore"), "scratch/\n*.tmp\n").ok()?;
        fs::write(dir.join("scratch/notes.md"), "x").ok()?;
        fs::write(dir.join("doc/design.md"), "x").ok()?;
        fs::write(dir.join("doc/draft.tmp"), "x").ok()?;
        git(&["init", "-q"]).then_some(())
    }

    #[test]
    fn ignored_reports_what_git_covers_and_nothing_else() {
        let dir = tempfile::tempdir().unwrap();
        if ignoring_project(dir.path()).is_none() {
            return; // git unavailable
        }
        let values: Vec<String> = ["scratch/notes.md", "doc/design.md", "doc/draft.tmp"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        assert_eq!(
            ignored(dir.path(), &values),
            vec!["scratch/notes.md".to_string(), "doc/draft.tmp".to_string()]
        );
    }

    /// The suffix is stripped before git is asked. `doc/draft.tmp:12` is not a
    /// filename, and the `*.tmp` rule would miss it.
    #[test]
    fn ignored_asks_about_the_resolved_path_not_the_raw_value() {
        let dir = tempfile::tempdir().unwrap();
        if ignoring_project(dir.path()).is_none() {
            return;
        }
        let values = vec!["doc/draft.tmp:12".to_string()];
        assert_eq!(ignored(dir.path(), &values), values);
    }

    /// A path with nothing behind it is left out: it is already reported as a
    /// broken ref, and git would be answering a different question.
    #[test]
    fn ignored_says_nothing_about_a_path_that_does_not_resolve() {
        let dir = tempfile::tempdir().unwrap();
        if ignoring_project(dir.path()).is_none() {
            return;
        }
        let values = vec!["scratch/gone.md".to_string()];
        assert!(ignored(dir.path(), &values).is_empty());
    }

    /// Outside a repo frame cannot tell, so it allows rather than guessing.
    #[test]
    fn ignored_is_silent_outside_a_repository() {
        let dir = tempfile::tempdir().unwrap();
        fs::create_dir_all(dir.path().join("scratch")).unwrap();
        fs::write(dir.path().join("scratch/notes.md"), "x").unwrap();
        // Guard against the tempdir itself sitting inside a repo, which would
        // make this pass for the wrong reason.
        if crate::io::git::ignored_paths(dir.path(), &["scratch/notes.md".to_string()]).is_some() {
            return;
        }
        let values = vec!["scratch/notes.md".to_string()];
        assert!(ignored(dir.path(), &values).is_empty());
    }

    #[test]
    fn resolved_returns_the_path_without_its_suffix() {
        let dir = project();
        assert_eq!(
            resolved(dir.path(), "src/parser.rs:807").as_deref(),
            Some("src/parser.rs")
        );
        assert_eq!(
            resolved(dir.path(), "doc/design.md#why").as_deref(),
            Some("doc/design.md")
        );
        // The literal value wins, so a `#` or `:` in the name survives.
        assert_eq!(
            resolved(dir.path(), "doc/issue#3.md").as_deref(),
            Some("doc/issue#3.md")
        );
        assert_eq!(resolved(dir.path(), "doc/missing.md"), None);
    }

    #[test]
    fn containment_refuses_what_will_not_travel() {
        assert_eq!(containment("../outside.md"), Some(PathRejection::Escapes));
        assert_eq!(containment("a/../../b.md"), Some(PathRejection::Escapes));
        assert_eq!(containment(".."), Some(PathRejection::Escapes));
        assert_eq!(containment("/etc/hosts"), Some(PathRejection::Absolute));
        assert_eq!(
            containment("/etc/../etc/hosts"),
            Some(PathRejection::Absolute)
        );
        // Absolute *into* the project is still absolute: it names this machine.
        assert_eq!(
            containment("/Users/x/proj/doc/design.md"),
            Some(PathRejection::Absolute)
        );
    }

    /// A path that dips out and comes back stays inside, and the awkward
    /// spellings that fold to something contained are fine.
    #[test]
    fn containment_allows_everything_that_stays_inside() {
        assert_eq!(containment("doc/design.md"), None);
        assert_eq!(containment("./sub/../real.md"), None);
        assert_eq!(containment("doc/../src/parser.rs:807"), None);
        assert_eq!(containment("."), None);
        assert_eq!(containment("doc/..hidden.md"), None);
        // Empty is not a containment question — `exists` refuses it on its own,
        // and answering here would give it two different error messages.
        assert_eq!(containment(""), None);
    }

    #[test]
    fn same_path_sees_through_spelling_but_not_through_the_suffix() {
        assert!(same_path("real.md", "./sub/../real.md"));
        assert!(same_path("./sub/../real.md", "real.md"));
        assert!(same_path("./sub/../real.md", "./sub/../real.md"));
        assert!(same_path("doc/design.md#why", "./doc/design.md#why"));
        // Different references to the same file, and `rm` must keep them apart.
        assert!(!same_path("real.md", "real.md:807"));
        assert!(!same_path("doc/design.md", "doc/design.md#why"));
        assert!(!same_path("real.md", "other.md"));
    }

    /// Only a line, a range, or a column follows the colon. Anything else is
    /// part of the path — a stray suffix must not make a missing file look
    /// present by resolving to its parent directory.
    #[test]
    fn a_non_numeric_suffix_is_part_of_the_path() {
        assert_eq!(strip_line_ref("src/parser.rs:main"), "src/parser.rs:main");
        assert_eq!(strip_line_ref("src/parser.rs:8a"), "src/parser.rs:8a");
        assert_eq!(strip_line_ref("src/parser.rs:-8"), "src/parser.rs:-8");
        assert_eq!(strip_line_ref("src/parser.rs:8-"), "src/parser.rs:8-");
    }
}