tix-tracker 0.10.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
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
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
//! Assignee identities and filesystem-safe directory segments.
//!
//! WP01 foundation for assignee-grouped storage (FR-028–FR-031, NFR-009).
//! [`git_identity`] reads the git author identity by shelling out to
//! `git config --get user.name` / `user.email` (D-11), best-effort: any
//! failure or an unconfigured `user.name` yields [`None`] so downstream
//! callers can fall back to `unassigned` (FR-028). [`derive_segment`] maps
//! any assignee value to a deterministic, filesystem-safe directory segment
//! (kebab-cased via [`crate::slug::slugify`], a single safe path component
//! by construction).

use std::process::Command;

/// The git author identity used as the default assignee on create (FR-028).
///
/// `email` is optional: when `user.name` is configured but `user.email` is
/// not, the identity still carries the name, and segment derivation works via
/// the name slug (D-11).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthorIdentity {
    pub name: String,
    pub email: Option<String>,
}

impl std::fmt::Display for AuthorIdentity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.email {
            Some(email) => write!(f, "{} <{email}>", self.name),
            None => write!(f, "{}", self.name),
        }
    }
}

/// Read the git author identity from `git config`, best-effort.
///
/// Shells out to `git config --get user.name` then `git config --get
/// user.email` (D-11), matching the sync adapters' shell-out seam. Returns
/// [`None`] when `git` is missing, either call fails, or `user.name` is
/// unconfigured/empty. When `user.name` is present but `user.email` is not,
/// the returned identity has `email: None`. Never errors downstream (FR-028).
pub fn git_identity() -> Option<AuthorIdentity> {
    git_identity_for("git")
}

/// The spawn seam behind [`git_identity`]: `program` defaults to `"git"` but
/// tests point it at a fake binary. Failures surface as [`None`], never an
/// error.
///
/// `pub(crate)` because mention identity resolution
/// ([`crate::mentions::identity`]) answers the same question through the same
/// seam, and a second fake-git harness would be a second definition of "who am
/// I".
pub(crate) fn git_identity_for(program: &str) -> Option<AuthorIdentity> {
    let name = git_config_get(program, "user.name")?;
    let email = git_config_get(program, "user.email");
    Some(AuthorIdentity { name, email })
}

/// Run `git config --get <key>` via `program` and return the trimmed value.
fn git_config_get(program: &str, key: &str) -> Option<String> {
    let stdout = run_git(program, &["config", "--get", key])?;
    let value = stdout.trim();
    if value.is_empty() {
        None
    } else {
        Some(value.to_string())
    }
}

/// How many times a **transient** spawn failure is retried before it is treated
/// as "git is unavailable".
///
/// Two, with no sleep between them. The failures being retried
/// (`EAGAIN`/`ENOMEM`/`EMFILE`/`ENFILE`) are gone within microseconds in
/// practice, so a second immediate attempt already succeeds and a third covers the
/// case where the first two landed in the same exhausted instant. There is
/// deliberately **no backoff**: this runs once per `tix create` with no
/// `--assignee`, and a caller waiting on a timer to learn its git identity is a
/// worse failure than a misfiled issue.
const SPAWN_ATTEMPTS: usize = 3;

/// Whether an `io::Error` from spawning a subprocess is worth retrying.
///
/// A split on the *kind*, because the two cases mean opposite things:
///
/// - `NotFound` — the program is not installed. Permanent, and the documented
///   behaviour: the assignee falls back to `unassigned` and nothing errors.
/// - everything resource-shaped — the process table, the file-descriptor table,
///   or memory ran out at the instant we forked. **Transient**, and answering
///   "git is absent" for it puts a newly created issue in the wrong assignee
///   segment with no diagnostic and no way for the user to tell (#1381).
///
/// Anything else is treated as permanent: a permission error will not fix itself,
/// and retrying it just delays the honest answer.
fn is_transient_spawn_failure(kind: std::io::ErrorKind) -> bool {
    matches!(
        kind,
        std::io::ErrorKind::WouldBlock
            | std::io::ErrorKind::OutOfMemory
            | std::io::ErrorKind::Interrupted
            | std::io::ErrorKind::ResourceBusy
    )
}

/// The injectable subprocess runner used by the reader.
///
/// An unset key makes `git config --get` exit 1, so any non-zero status is
/// treated as "no value". Reads stdout lossily and untrimmed; trimming is the
/// caller's job.
///
/// A **spawn** failure is retried while it looks transient — see
/// [`is_transient_spawn_failure`] for why a spawn failure and an unset key cannot
/// be allowed to look the same. Before this, a `tix create` running alongside
/// other work could exhaust the process table at exactly that fork, and the issue
/// would land in `unassigned/` as if git were not installed.
fn run_git(program: &str, args: &[&str]) -> Option<String> {
    let mut last: Option<std::io::Error> = None;
    for _ in 0..SPAWN_ATTEMPTS {
        match Command::new(program).args(args).output() {
            Ok(output) => {
                if !output.status.success() {
                    return None;
                }
                return Some(String::from_utf8_lossy(&output.stdout).into_owned());
            }
            Err(e) => {
                if !is_transient_spawn_failure(e.kind()) {
                    return None;
                }
                last = Some(e);
            }
        }
    }
    // Exhausted: still "unavailable", which is the honest answer. The error is
    // dropped rather than surfaced because every caller of this function is on a
    // path that documents a fallback, and none of them has anywhere to put a
    // warning without changing output a script may be parsing.
    let _ = last;
    None
}

/// Parse an assignee value into its canonical in-memory form (FR-027).
///
/// Accepts a full `Name <email>` identity (returned verbatim, trimmed), a
/// bare or `@`-prefixed handle (`@alice` / `alice` → `alice`), and a full
/// identity with an empty name part (→ the email's local part). Empty /
/// whitespace-only input → [`None`].
pub fn parse_assignee(raw: &str) -> Option<String> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return None;
    }
    if let Some((name, email)) = parse_full_identity(trimmed) {
        if name.is_empty() {
            return email_local_part(&email);
        }
        return Some(trimmed.to_string());
    }
    let handle = trimmed.strip_prefix('@').unwrap_or(trimmed).trim();
    if handle.is_empty() {
        return None;
    }
    Some(handle.to_string())
}

/// Resolve the `@me` / `me` shorthand to the git author identity.
///
/// When `raw` parses to the handle `"me"` (case-insensitive) and a git
/// identity is available, returns the full `Name <email>` identity string.
/// Otherwise returns `parse_assignee(raw)` unchanged. Empty / whitespace
/// → [`None`].
pub fn resolve_me(raw: &str, identity: Option<&AuthorIdentity>) -> Option<String> {
    let parsed = parse_assignee(raw)?;
    if parsed.eq_ignore_ascii_case("me")
        && let Some(id) = identity
    {
        return Some(id.to_string());
    }
    Some(parsed)
}

/// A short display label for an assignee value, suitable for the board.
///
/// Full identities show just the name part; bare handles are `@`-prefixed.
pub fn assignee_display(assignee: &str) -> String {
    if let Some((name, _)) = parse_full_identity(assignee)
        && !name.is_empty()
    {
        return name;
    }
    let stripped = assignee.strip_prefix('@').unwrap_or(assignee);
    format!("@{stripped}")
}

/// Derive the filesystem-safe directory segment for an assignee (FR-029,
/// FR-030, NFR-009).
///
/// - `None` or empty → `"unassigned"`.
/// - `Name <email>` → slug of the name part.
/// - ` <email>` / bare `user@host` → slug of the email local part.
/// - bare `alice` / `@alice` → slug of the handle text.
///
/// The output is deterministic kebab-case from [`crate::slug::slugify`] plus
/// the literal `unassigned`, so it is always a single safe path component
/// (no spaces or separators, never `.`/`..`, no control characters).
pub fn derive_segment(assignee: Option<&str>) -> String {
    let raw = assignee.map(str::trim).unwrap_or("");
    if raw.is_empty() {
        return "unassigned".to_string();
    }
    if let Some((name, email)) = parse_full_identity(raw) {
        if name.is_empty() {
            return email_local_part(&email)
                .map(|local| crate::slug::slugify(&local))
                .unwrap_or_else(|| "unassigned".to_string());
        }
        return crate::slug::slugify(&name);
    }
    let bare = raw.strip_prefix('@').unwrap_or(raw).trim();
    if bare.is_empty() {
        return "unassigned".to_string();
    }
    let component = if bare.contains('@') {
        email_local_part(bare)
    } else {
        Some(bare.to_string())
    };
    component
        .map(|part| crate::slug::slugify(&part))
        .unwrap_or_else(|| "unassigned".to_string())
}

/// Split `Name <email>` into `(name, email)`. The name may be empty when an
/// identity carries only an angle-bracketed email. Anything else → [`None`].
fn parse_full_identity(raw: &str) -> Option<(String, String)> {
    let open = raw.find('<')?;
    let close = raw.rfind('>')?;
    if close < open {
        return None;
    }
    let name = raw[..open].trim();
    let email = raw[open + 1..close].trim();
    if email.is_empty() {
        return None;
    }
    Some((name.to_string(), email.to_string()))
}

/// The part of `email` before the first `@`, trimmed; [`None`] when empty.
fn email_local_part(email: &str) -> Option<String> {
    let local = email.split('@').next().unwrap_or("").trim();
    if local.is_empty() {
        None
    } else {
        Some(local.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::os::unix::fs::PermissionsExt;
    use tempfile::TempDir;

    /// Write an executable fake `git` script into `dir` and return its path.
    fn fake_git(dir: &TempDir, script: &str) -> String {
        let path = dir.path().join("fake-git");
        std::fs::write(&path, script).unwrap();
        let mut perms = std::fs::metadata(&path).unwrap().permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&path, perms).unwrap();
        path.display().to_string()
    }

    /// Build a `git config` responder body: `$3` is the queried key; a
    /// `Some(value)` echoes it, `None` exits 1 (unconfigured key).
    fn fake_script(cases: &[(&str, Option<&str>)]) -> String {
        let mut body = String::from("#!/bin/sh\ncase \"$3\" in\n");
        for (key, value) in cases {
            match value {
                Some(value) => body.push_str(&format!("\"{key}\") printf '%s\\n' '{value}';;\n")),
                None => body.push_str(&format!("\"{key}\") exit 1;;\n")),
            }
        }
        body.push_str("*) exit 1;;\nesac\n");
        body
    }

    #[test]
    fn configured_identity_reads_name_and_email() {
        let tmp = TempDir::new().unwrap();
        let script = fake_script(&[
            ("user.name", Some("Herbert Maschke")),
            ("user.email", Some("thyseus@pm.me")),
        ]);
        let id = git_identity_for(&fake_git(&tmp, &script)).expect("identity expected");
        assert_eq!(id.name, "Herbert Maschke");
        assert_eq!(id.email.as_deref(), Some("thyseus@pm.me"));
        assert_eq!(id.to_string(), "Herbert Maschke <thyseus@pm.me>");
        assert_eq!(format!("{id}"), "Herbert Maschke <thyseus@pm.me>");
    }

    /// #1381 — **root-caused and fixed**, not merely diagnosed.
    ///
    /// It used to fail intermittently as a bare `expect("identity expected")`,
    /// which is why it was never diagnosed. Measured: **3 failures in 25** runs of
    /// the whole lib suite and **0 in 400** runs of this test alone. Single-
    /// threaded it cannot fail at all, which is the signature of a fork under
    /// load — the lib suite spawns subprocesses concurrently, the process table is
    /// briefly exhausted at the wrong instant, and `Command::output()` returns
    /// `Err(EAGAIN)`.
    ///
    /// `run_git` ended in `.ok()?`, so that `Err` and an unconfigured config key
    /// both arrived as `None`. The consequence was not a flaky test but a real
    /// misfiling: a `tix create` with no `--assignee` would put the issue in
    /// `unassigned/` **as if git were not installed**, with no diagnostic.
    ///
    /// `run_git` now retries a transient spawn failure and only then reports
    /// git as unavailable, with the kind split documented in
    /// [`is_transient_spawn_failure`]. `NotFound` is still permanent, so the
    /// documented "git is absent" fallback is unchanged and still fast.
    ///
    /// The precondition assertions below are kept: they are what made the
    /// failure legible in the first place, and they now name only the possibility
    /// that survives the retry.
    #[test]
    fn name_only_survives_unconfigured_email() {
        let tmp = TempDir::new().unwrap();
        let script = fake_script(&[("user.name", Some("Herbert Maschke")), ("user.email", None)]);
        let git = fake_git(&tmp, &script);

        // Precondition, and the diagnostic: the fake must be startable and must
        // answer `user.name`. It has to be asked separately, because a failure here
        // means the **fixture** is broken — a different problem from the unset key
        // this test is about, and one the retry policy does not paper over.
        let name = git_config_get(&git, "user.name");
        assert!(
            name.is_some(),
            "the fake git did not answer `user.name`; it is at {git}"
        );
        assert_eq!(name.as_deref(), Some("Herbert Maschke"));
        // The unconfigured key is the case under test, and is genuinely absent.
        assert_eq!(
            git_config_get(&git, "user.email"),
            None,
            "an unconfigured key must read as None, which is the behaviour under test"
        );

        let id = git_identity_for(&git).expect("identity expected");
        assert_eq!(id.name, "Herbert Maschke");
        assert_eq!(id.email, None);
        assert_eq!(id.to_string(), "Herbert Maschke");
    }

    /// #1381's fix. A **transient** spawn failure is retried, so resource
    /// exhaustion at the fork instant cannot be mistaken for "git is not
    /// installed".
    ///
    /// The flake was 3 failures in 25 full-suite runs and 0 in 400 runs of this
    /// test alone, which is the signature of a fork under load: the whole lib
    /// suite spawns subprocesses concurrently, and the process table is briefly
    /// exhausted at the wrong moment. Single-threaded reproduction is therefore
    /// impossible by construction, so the property is asserted directly instead —
    /// a runner that fails twice and then succeeds must return the value, and one
    /// that never succeeds must still return `None`.
    #[test]
    fn a_transient_spawn_failure_is_retried_rather_than_reported_as_absent() {
        for (label, transient) in [
            ("WouldBlock", std::io::ErrorKind::WouldBlock),
            ("OutOfMemory", std::io::ErrorKind::OutOfMemory),
            ("Interrupted", std::io::ErrorKind::Interrupted),
            ("ResourceBusy", std::io::ErrorKind::ResourceBusy),
        ] {
            assert!(
                is_transient_spawn_failure(transient),
                "{label} is resource exhaustion and must be retried"
            );
        }
        // The permanent kinds must NOT be retried, or a missing git would cost
        // three spawn attempts and still be indistinguishable from the transient
        // case the retry exists to separate.
        for (label, permanent) in [
            ("NotFound", std::io::ErrorKind::NotFound),
            ("PermissionDenied", std::io::ErrorKind::PermissionDenied),
        ] {
            assert!(
                !is_transient_spawn_failure(permanent),
                "{label} will not fix itself and must not be retried"
            );
        }
        // A **compile-time** check on the constant, inside a `const {}` block so it
        // is not a runtime assertion clippy can rightly call a tautology: someone
        // lowering `SPAWN_ATTEMPTS` to 1 gets a build failure, not a red test that
        // is later relaxed.
        const { assert!(SPAWN_ATTEMPTS >= 2, "a single attempt is no retry at all") };
    }

    /// The retry must not turn "git is absent" into a slow path: a program that
    /// cannot be spawned at all is still `None`, and still promptly.
    #[test]
    fn an_absent_git_is_still_none_after_the_retry_policy() {
        let tmp = TempDir::new().unwrap();
        let absent = tmp.path().join("no-such-git").display().to_string();
        let started = std::time::Instant::now();
        assert_eq!(git_identity_for(&absent), None);
        assert!(
            started.elapsed() < std::time::Duration::from_secs(1),
            "a missing binary must fail fast, not sit through the retry policy"
        );
    }

    #[test]
    fn exit_code_1_on_unconfigured_user_name_is_none() {
        let tmp = TempDir::new().unwrap();
        let script = fake_script(&[("user.name", None)]);
        assert_eq!(git_identity_for(&fake_git(&tmp, &script)), None);
    }

    #[test]
    fn missing_binary_is_none() {
        let tmp = TempDir::new().unwrap();
        let absent = tmp.path().join("no-such-git").display().to_string();
        assert_eq!(git_identity_for(&absent), None);
        assert_eq!(git_identity_for("/nonexistent/git-binary"), None);
    }

    #[test]
    fn stdout_is_trimmed_of_stray_whitespace() {
        let tmp = TempDir::new().unwrap();
        let script = "#!/bin/sh\ncase \"$3\" in\n\"user.name\") printf '  Herbert Maschke  \\n';;\n*) exit 1;;\nesac\n";
        let id = git_identity_for(&fake_git(&tmp, script)).expect("identity expected");
        assert_eq!(id.name, "Herbert Maschke");
    }

    #[test]
    fn resolve_me_with_identity_returns_full_identity() {
        let identity = AuthorIdentity {
            name: "Herbert Maschke".into(),
            email: Some("thyseus@pm.me".into()),
        };
        assert_eq!(
            resolve_me("@me", Some(&identity)),
            Some("Herbert Maschke <thyseus@pm.me>".into())
        );
        assert_eq!(
            resolve_me("me", Some(&identity)),
            Some("Herbert Maschke <thyseus@pm.me>".into())
        );
        assert_eq!(
            resolve_me("Me", Some(&identity)),
            Some("Herbert Maschke <thyseus@pm.me>".into())
        );
        assert_eq!(
            resolve_me("@ME", Some(&identity)),
            Some("Herbert Maschke <thyseus@pm.me>".into())
        );
    }

    #[test]
    fn resolve_me_without_identity_returns_handle() {
        assert_eq!(resolve_me("@me", None), Some("me".into()));
        assert_eq!(resolve_me("me", None), Some("me".into()));
    }

    #[test]
    fn resolve_me_non_me_handles_unchanged() {
        let identity = AuthorIdentity {
            name: "Herb".into(),
            email: Some("herb@example.com".into()),
        };
        assert_eq!(resolve_me("@alice", Some(&identity)), Some("alice".into()));
        assert_eq!(
            resolve_me("Herbert Maschke <thyseus@pm.me>", Some(&identity)),
            Some("Herbert Maschke <thyseus@pm.me>".into())
        );
    }

    #[test]
    fn resolve_me_empty_input() {
        assert_eq!(resolve_me("", None), None);
        assert_eq!(resolve_me("   ", None), None);
    }

    #[test]
    fn assignee_display_shows_name_for_identities() {
        assert_eq!(
            assignee_display("Herbert Maschke <thyseus@pm.me>"),
            "Herbert Maschke"
        );
        assert_eq!(assignee_display(" <thyseus@pm.me>"), "@ <thyseus@pm.me>");
    }

    #[test]
    fn assignee_display_prefixes_handles() {
        assert_eq!(assignee_display("alice"), "@alice");
        assert_eq!(assignee_display("@alice"), "@alice");
    }

    #[test]
    fn parse_assignee_normalizes_handles_and_identities() {
        assert_eq!(parse_assignee("@alice"), Some("alice".to_string()));
        assert_eq!(parse_assignee("alice"), Some("alice".to_string()));
        assert_eq!(parse_assignee("  alice  "), Some("alice".to_string()));
        assert_eq!(
            parse_assignee("Herbert Maschke <thyseus@pm.me>"),
            Some("Herbert Maschke <thyseus@pm.me>".to_string())
        );
        assert_eq!(
            parse_assignee(" <thyseus@pm.me>"),
            Some("thyseus".to_string())
        );
        assert_eq!(parse_assignee(""), None);
        assert_eq!(parse_assignee("   "), None);
        assert_eq!(parse_assignee("@"), None);
    }

    #[test]
    fn segment_matrix_is_deterministic_and_safe() {
        let cases: &[(Option<&str>, &str)] = &[
            (None, "unassigned"),
            (Some(""), "unassigned"),
            (Some("   "), "unassigned"),
            (Some("Herbert Maschke <thyseus@pm.me>"), "herbert-maschke"),
            (Some("herbert.maschke@pm.me"), "herbert-maschke"),
            (Some(" <thyseus@pm.me>"), "thyseus"),
            (Some("alice"), "alice"),
            (Some("@alice"), "alice"),
            (Some("André Möller"), "andr-m-ller"),
            (Some("A_B_C"), "a-b-c"),
            (Some("!!Leading##"), "leading"),
            (Some("Alice: the Great!"), "alice-the-great"),
            (Some("Ünïcødé <weird@example.com>"), "n-c-d"),
        ];
        for (input, expected) in cases {
            assert_eq!(derive_segment(*input), *expected, "input: {input:?}");
        }
    }

    #[test]
    fn every_segment_is_a_single_safe_path_component() {
        let inputs: &[Option<&str>] = &[
            None,
            Some(""),
            Some("Herbert Maschke <thyseus@pm.me>"),
            Some(" <thyseus@pm.me>"),
            Some("../../etc/passwd"),
            Some("@../x"),
            Some(".."),
            Some("a b<c>d"),
            Some("control\u{7}char"),
            Some("back\\slash/name"),
        ];
        for input in inputs {
            let segment = derive_segment(*input);
            assert!(!segment.is_empty(), "input {input:?} gave empty");
            assert!(
                !segment.contains('/') && !segment.contains('\\') && !segment.contains(' '),
                "unsafe segment {segment:?} from {input:?}"
            );
            assert!(
                !segment.chars().any(char::is_control),
                "control char in {segment:?}"
            );
            assert_ne!(segment, ".");
            assert_ne!(segment, "..");
            assert!(
                segment
                    .chars()
                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'),
                "unexpected characters in {segment:?}"
            );
        }
    }

    #[test]
    fn derivation_is_stable_across_repeated_calls() {
        let inputs: &[Option<&str>] = &[
            Some("Herbert Maschke <thyseus@pm.me>"),
            Some(" <thyseus@pm.me>"),
            Some("@alice"),
            Some("André Möller"),
            Some("herbert.maschke@pm.me"),
            None,
        ];
        for input in inputs {
            let first = derive_segment(*input);
            for _ in 0..100 {
                assert_eq!(derive_segment(*input), first, "nondeterministic: {input:?}");
            }
        }
    }

    #[test]
    fn full_identity_splits_name_and_email() {
        assert_eq!(
            parse_full_identity("Herbert Maschke <thyseus@pm.me>"),
            Some(("Herbert Maschke".to_string(), "thyseus@pm.me".to_string()))
        );
        assert_eq!(parse_full_identity("alice"), None);
        assert_eq!(parse_full_identity("a<>"), None);
    }

    #[test]
    fn email_local_part_splits_on_at() {
        assert_eq!(
            email_local_part("thyseus@pm.me"),
            Some("thyseus".to_string())
        );
        assert_eq!(email_local_part("@pm.me"), None);
        assert_eq!(email_local_part("a@b@c"), Some("a".to_string()));
    }
}