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
//! The per-target mention store: `docs/mentions/<slug>.toml` (design D4/D5).
//!
//! One file per mentioned target, keyed by the **slug of the mention body** — `@herbert-maschke`
//! lands in `herbert-maschke.toml`, `@thyseus@pm.me` in `thyseus-pm-me.toml`. The same person
//! mentioned by handle and by email therefore lands in two files: the writer knows only the
//! token, and it is the reader's identity resolution (see [`super::identity`]) that reads both
//! and pools them.
//!
//! Every write goes through [`crate::storage::atomic_write`], which records the target's
//! pre-image in the active write journal. That is what makes a mention write participate in
//! `Store::transaction`: a command that fails mid-way rolls its mention files back with its
//! issue files.
//!
//! ## Best-effort by contract
//!
//! Reconciliation is **never allowed to fail a write**. A malformed target file, an I/O error,
//! or a permissions problem is reported through the disclosure channel and that target is left
//! untouched — the issue edit the user asked for still succeeds, and no data is destroyed.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use crate::error::{Result, TixError};
use crate::mentions::{IssueContent, Mention, MentionFile, MentionState, collect, reconcile};
use crate::slug::slugify;

/// The mention store rooted at one `docs/mentions` directory.
#[derive(Debug, Clone)]
pub struct MentionStore {
    dir: PathBuf,
}

impl MentionStore {
    /// A store rooted at `dir`. Nothing is created here — the directory is made lazily, on the
    /// first write (design D4).
    #[must_use]
    pub fn new(dir: PathBuf) -> Self {
        MentionStore { dir }
    }

    /// The directory the store reads and writes.
    #[must_use]
    pub fn dir(&self) -> &Path {
        &self.dir
    }

    /// The file stem for a mention body: the slug of the handle or the email.
    #[must_use]
    pub fn slug(body: &str) -> String {
        slugify(body)
    }

    fn path(&self, slug: &str) -> PathBuf {
        self.dir.join(format!("{slug}.toml"))
    }

    /// Read one target's file. `Ok(None)` when it does not exist; an existing but unreadable or
    /// malformed file is an error, so a caller can decline to overwrite it rather than
    /// destroy it.
    pub fn read(&self, slug: &str) -> Result<Option<MentionFile>> {
        let path = self.path(slug);
        if !path.is_file() {
            return Ok(None);
        }
        let text = std::fs::read_to_string(&path)?;
        let file: MentionFile = toml::from_str(&text)
            .map_err(|e| TixError::Parse(format!("{}: {e}", path.display())))?;
        Ok(Some(file))
    }

    /// Write one target's file — or remove it when the document is empty.
    fn write(&self, slug: &str, file: &MentionFile) -> Result<()> {
        let path = self.path(slug);
        if file.is_empty() {
            if path.is_file() {
                crate::storage::journal_record_write(&path);
                std::fs::remove_file(&path)?;
            }
            return Ok(());
        }
        std::fs::create_dir_all(&self.dir)?;
        let text = toml::to_string(file)
            .map_err(|e| TixError::Parse(format!("serialize {}: {e}", path.display())))?;
        crate::storage::atomic_write(&self.dir, &path, text.as_bytes())
    }

    /// Every target slug that has a file in the store, sorted.
    pub fn targets(&self) -> Result<Vec<String>> {
        if !self.dir.is_dir() {
            return Ok(Vec::new());
        }
        let mut out = Vec::new();
        for entry in std::fs::read_dir(&self.dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.extension().is_some_and(|e| e == "toml") {
                if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
                    out.push(stem.to_string());
                }
            }
        }
        out.sort();
        Ok(out)
    }

    /// Reconcile an issue's mentions into the store, and report whether anything was written.
    ///
    /// Best-effort per target: a failure on one target raises a disclosure and leaves that
    /// target alone, and the remaining targets are still reconciled.
    pub fn reconcile(&self, content: IssueContent<'_>) -> bool {
        // Group the occurrences by the target file they belong to, once. The parsed list
        // is also what says which targets are *present* in this write, so the removal pass
        // below does not have to scan the content again per target.
        let mut groups: BTreeMap<String, Vec<reconcile::Parsed>> = BTreeMap::new();
        for located in collect(content) {
            let slug = Self::slug(&located.parsed.body);
            groups.entry(slug).or_default().push(located.parsed);
        }
        let now = crate::model::utc_now_rfc3339();
        let mut changed = false;

        for (slug, parsed) in &groups {
            match self.reconcile_target(slug, parsed, content, &now) {
                Ok(true) => changed = true,
                Ok(false) => {}
                Err(e) => {
                    crate::storage::mention_disclosure(format!("mentions: {e} (left untouched)"))
                }
            }
        }
        // An occurrence may have *moved* target (a mention rewritten from a handle to an
        // email), so a target that still holds records for this issue but is not in
        // `groups` also has to be reconciled — against an empty parse, which drops them.
        changed |= self.reconcile_removals(content, groups.keys().map(String::as_str).collect());
        changed
    }

    /// Reconcile every target that holds records for this issue but has no occurrence in the
    /// content, so mentions that were removed (or moved to another target) stop pending.
    ///
    /// `present` is the set of targets the written content names; a target in it has already
    /// been reconciled and is skipped.
    fn reconcile_removals(
        &self,
        content: IssueContent<'_>,
        present: std::collections::BTreeSet<&str>,
    ) -> bool {
        let Ok(targets) = self.targets() else {
            return false;
        };
        let mut changed = false;
        for slug in targets {
            if present.contains(slug.as_str()) {
                continue;
            }
            let holds_this_issue = match self.read(&slug) {
                Ok(Some(file)) => file.mentions.iter().any(|m| m.issue_id == content.id),
                Ok(None) => false,
                Err(e) => {
                    crate::storage::mention_disclosure(format!("mentions: {e} (left untouched)"));
                    continue;
                }
            };
            if !holds_this_issue {
                continue;
            }
            match self.reconcile_target(&slug, &[], content, "") {
                Ok(true) => changed = true,
                Ok(false) => {}
                Err(e) => {
                    crate::storage::mention_disclosure(format!("mentions: {e} (left untouched)"))
                }
            }
        }
        changed
    }

    /// Reconcile one target file against `parsed`, which holds only the occurrences that target
    /// the file's slug.
    fn reconcile_target(
        &self,
        slug: &str,
        parsed: &[reconcile::Parsed],
        content: IssueContent<'_>,
        now: &str,
    ) -> Result<bool> {
        let file = self.read(slug)?;
        let existing = file.clone().unwrap_or_default();
        let (mine, others): (Vec<Mention>, Vec<Mention>) = existing
            .mentions
            .into_iter()
            .partition(|m| m.issue_id == content.id);

        let reconciled = reconcile::reconcile(
            &mine,
            parsed,
            reconcile::IssueRef {
                id: content.id,
                number: content.number,
                file: content.file,
            },
            now,
        );
        if reconciled == mine {
            return Ok(false);
        }
        let mut next = MentionFile {
            mentions: others,
            extra: if let Some(file) = file {
                file.extra
            } else {
                BTreeMap::new()
            },
        };
        next.mentions.extend(reconciled);
        self.write(slug, &next)?;
        Ok(true)
    }

    /// Every unread mention pooled across `candidates` (the local user's own mention bodies),
    /// ordered for display: by issue number, then creation stamp, then id.
    #[must_use]
    pub fn pending_for(&self, candidates: &[String]) -> Vec<Mention> {
        self.pooled(candidates, |m| m.is_unread())
    }

    /// How many unread mentions `candidates` hold — the TUI indicator's count.
    #[must_use]
    pub fn unread_count(&self, candidates: &[String]) -> usize {
        self.pending_for(candidates).len()
    }

    /// The unread mentions `candidates` hold **on one issue**.
    #[must_use]
    pub fn pending_for_issue(&self, candidates: &[String], issue_number: u32) -> Vec<Mention> {
        self.pooled(candidates, |m| {
            m.is_unread() && m.issue_number == issue_number
        })
    }

    fn pooled(&self, candidates: &[String], keep: impl Fn(&Mention) -> bool) -> Vec<Mention> {
        let mut out = Vec::new();
        let mut seen = std::collections::BTreeSet::new();
        for candidate in candidates {
            let slug = Self::slug(candidate);
            if !seen.insert(slug.clone()) {
                continue;
            }
            if let Ok(Some(file)) = self.read(&slug) {
                out.extend(file.mentions.into_iter().filter(|m| keep(m)));
            }
        }
        out.sort_by(|a, b| {
            a.issue_number
                .cmp(&b.issue_number)
                .then(a.created.cmp(&b.created))
                .then(a.id.cmp(&b.id))
        });
        out
    }

    /// One record by id, among `candidates`, read or unread.
    ///
    /// `show` and `jump` accept a mention the user has already acknowledged; only
    /// `mark_read` cares about the state.
    #[must_use]
    pub fn find(&self, candidates: &[String], id: &str) -> Option<Mention> {
        let mut seen = std::collections::BTreeSet::new();
        for candidate in candidates {
            let slug = Self::slug(candidate);
            if !seen.insert(slug.clone()) {
                continue;
            }
            if let Ok(Some(file)) = self.read(&slug) {
                if let Some(found) = file.mentions.into_iter().find(|m| m.id == id) {
                    return Some(found);
                }
            }
        }
        None
    }

    /// Mark one mention read, by id, among `candidates`. `false` when no such record exists.
    pub fn mark_read(&self, candidates: &[String], id: &str) -> Result<bool> {
        for candidate in candidates {
            let slug = Self::slug(candidate);
            let Some(mut file) = self.read(&slug)? else {
                continue;
            };
            let mut changed = false;
            for mention in &mut file.mentions {
                if mention.id == id && mention.state != MentionState::Read {
                    mention.state = MentionState::Read;
                    changed = true;
                }
            }
            if changed {
                self.write(&slug, &file)?;
                return Ok(true);
            }
        }
        Ok(false)
    }

    /// Drop every record naming `issue_id`, across every target file, because the issue is
    /// gone. A file that becomes empty is removed.
    pub fn clear_issue(&self, issue_id: &str) -> Result<()> {
        for slug in self.targets()? {
            let Some(file) = self.read(&slug)? else {
                continue;
            };
            let before = file.mentions.len();
            let next = MentionFile {
                mentions: file
                    .mentions
                    .into_iter()
                    .filter(|m| m.issue_id != issue_id)
                    .collect(),
                extra: file.extra,
            };
            if next.mentions.len() != before {
                self.write(&slug, &next)?;
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn content<'a>(id: &'a str, title: &'a str, body: &'a str) -> IssueContent<'a> {
        IssueContent {
            id,
            number: 42,
            file: "herbert-maschke/task/todo/2026-10-09-fix.md",
            title,
            body,
        }
    }

    #[test]
    fn reading_a_project_with_no_mentions_creates_no_directory() {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("docs/mentions");
        let store = MentionStore::new(dir.clone());
        assert_eq!(
            store.pending_for(&["alice".to_string()]),
            [] as [crate::mentions::Mention; 0]
        );
        assert_eq!(store.targets().unwrap(), Vec::<String>::new());
        assert!(!dir.exists(), "a read must not create the directory");
    }

    #[test]
    fn a_handle_mention_creates_the_target_file() {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("docs/mentions");
        let store = MentionStore::new(dir);
        assert!(store.reconcile(content("1A2B3C4D", "", "blocked on @herbert-maschke")));
        let file = store.read("herbert-maschke").unwrap().expect("file");
        assert_eq!(file.mentions.len(), 1);
        assert_eq!(file.mentions[0].body, "herbert-maschke");
        assert_eq!(file.mentions[0].issue_number, 42);
    }

    #[test]
    fn an_email_mention_creates_its_own_file() {
        let tmp = TempDir::new().unwrap();
        let store = MentionStore::new(tmp.path().join("docs/mentions"));
        assert!(store.reconcile(content("1A2B3C4D", "ping @thyseus@pm.me", "")));
        let file = store.read("thyseus-pm-me").unwrap().expect("file");
        assert_eq!(file.mentions[0].body, "thyseus@pm.me");
    }

    #[test]
    fn a_second_reconcile_of_unchanged_content_writes_nothing() {
        let tmp = TempDir::new().unwrap();
        let store = MentionStore::new(tmp.path().join("docs/mentions"));
        let c = content("1A2B3C4D", "", "cc @alice");
        assert!(store.reconcile(c));
        assert!(!store.reconcile(c), "a no-op must not rewrite the file");
    }

    #[test]
    fn removing_the_mention_text_drops_the_record() {
        let tmp = TempDir::new().unwrap();
        let store = MentionStore::new(tmp.path().join("docs/mentions"));
        let _ = store.reconcile(content("1A2B3C4D", "", "cc @alice"));
        let _ = store.reconcile(content("1A2B3C4D", "", "nothing here"));
        assert_eq!(
            store.pending_for(&["alice".to_string()]),
            [] as [crate::mentions::Mention; 0]
        );
        assert_eq!(
            store.targets().unwrap(),
            Vec::<String>::new(),
            "empty file removed"
        );
    }

    #[test]
    fn another_issue_records_are_preserved_when_one_issue_is_reconciled() {
        let tmp = TempDir::new().unwrap();
        let store = MentionStore::new(tmp.path().join("docs/mentions"));
        let mut other = content("ZZZZZZZZ", "", "cc @alice");
        other.number = 7;
        other.file = "alice/task/todo/other.md";
        store.reconcile(other);
        store.reconcile(content("1A2B3C4D", "", "cc @alice"));
        let file = store.read("alice").unwrap().expect("file");
        assert_eq!(file.mentions.len(), 2);
        assert!(file.mentions.iter().any(|m| m.issue_id == "ZZZZZZZZ"));
    }

    #[test]
    fn mark_read_persists_and_stops_pending() {
        let tmp = TempDir::new().unwrap();
        let store = MentionStore::new(tmp.path().join("docs/mentions"));
        store.reconcile(content("1A2B3C4D", "", "cc @alice"));
        let candidates = vec!["alice".to_string()];
        let pending = store.pending_for(&candidates);
        assert_eq!(pending.len(), 1);
        assert!(store.mark_read(&candidates, &pending[0].id).unwrap());
        assert_eq!(
            store.pending_for(&candidates),
            [] as [crate::mentions::Mention; 0]
        );
        // The write is on disk, not just in memory.
        let file = store.read("alice").unwrap().expect("file");
        assert_eq!(file.mentions[0].state, MentionState::Read);
    }

    #[test]
    fn find_returns_a_record_whether_or_not_it_is_read() {
        let tmp = TempDir::new().unwrap();
        let store = MentionStore::new(tmp.path().join("docs/mentions"));
        store.reconcile(content("1A2B3C4D", "", "cc @alice"));
        let candidates = vec!["alice".to_string()];
        let id = store.pending_for(&candidates)[0].id.clone();
        assert!(store.find(&candidates, &id).is_some());
        store.mark_read(&candidates, &id).unwrap();
        assert!(
            store.find(&candidates, &id).is_some(),
            "still findable once read"
        );
        assert!(store.find(&candidates, "MNOPE1234").is_none());
    }

    #[test]
    fn marking_an_unknown_id_is_a_no_op() {
        let tmp = TempDir::new().unwrap();
        let store = MentionStore::new(tmp.path().join("docs/mentions"));
        store.reconcile(content("1A2B3C4D", "", "cc @alice"));
        assert!(
            !store
                .mark_read(&["alice".to_string()], "MNOPE1234")
                .unwrap()
        );
    }

    #[test]
    fn unread_count_pools_two_candidate_files_for_one_user() {
        let tmp = TempDir::new().unwrap();
        let store = MentionStore::new(tmp.path().join("docs/mentions"));
        store.reconcile(content("1A2B3C4D", "", "hi @herbert-maschke"));
        store.reconcile(content("5A6B7C8D", "", "hi @thyseus@pm.me"));
        let candidates = vec!["herbert-maschke".to_string(), "thyseus@pm.me".to_string()];
        assert_eq!(store.unread_count(&candidates), 2);
        // The same candidate listed twice is not counted twice.
        let doubled = vec!["herbert-maschke".to_string(), "herbert-maschke".to_string()];
        assert_eq!(store.unread_count(&doubled), 1);
    }

    #[test]
    fn pending_for_issue_filters_by_number() {
        let tmp = TempDir::new().unwrap();
        let store = MentionStore::new(tmp.path().join("docs/mentions"));
        store.reconcile(content("1A2B3C4D", "", "cc @alice"));
        let mut other = content("ZZZZZZZZ", "", "cc @alice");
        other.number = 7;
        store.reconcile(other);
        let candidates = vec!["alice".to_string()];
        assert_eq!(store.pending_for_issue(&candidates, 42).len(), 1);
        assert_eq!(
            store.pending_for_issue(&candidates, 99),
            [] as [crate::mentions::Mention; 0]
        );
    }

    #[test]
    fn clear_issue_drops_only_that_issue() {
        let tmp = TempDir::new().unwrap();
        let store = MentionStore::new(tmp.path().join("docs/mentions"));
        store.reconcile(content("1A2B3C4D", "", "cc @alice and @bob"));
        let mut other = content("ZZZZZZZZ", "", "cc @alice");
        other.number = 7;
        store.reconcile(other);
        store.clear_issue("1A2B3C4D").unwrap();
        assert_eq!(store.targets().unwrap(), vec!["alice".to_string()]);
        let left = store.pending_for(&["bob".to_string()]);
        assert_eq!(left, [] as [crate::mentions::Mention; 0]);
        let alice = store.pending_for(&["alice".to_string()]);
        assert_eq!(alice.len(), 1);
        assert_eq!(alice[0].issue_id, "ZZZZZZZZ");
    }

    #[test]
    fn a_malformed_target_file_is_left_untouched_and_reconciliation_continues() {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("docs/mentions");
        std::fs::create_dir_all(&dir).unwrap();
        let broken = dir.join("alice.toml");
        std::fs::write(&broken, "this is not = = toml").unwrap();
        let store = MentionStore::new(dir);
        // The write still succeeds overall…
        assert!(store.reconcile(content("1A2B3C4D", "", "cc @alice and @bob")));
        // …the broken file is untouched, and the other target was written.
        assert_eq!(
            std::fs::read_to_string(&broken).unwrap(),
            "this is not = = toml"
        );
        assert!(store.read("bob").unwrap().is_some());
    }

    #[test]
    fn a_mention_moved_from_a_handle_to_an_email_leaves_the_old_target() {
        let tmp = TempDir::new().unwrap();
        let store = MentionStore::new(tmp.path().join("docs/mentions"));
        store.reconcile(content("1A2B3C4D", "", "cc @thyseus"));
        assert_eq!(store.targets().unwrap(), vec!["thyseus".to_string()]);
        store.reconcile(content("1A2B3C4D", "", "cc @thyseus@pm.me"));
        assert_eq!(store.targets().unwrap(), vec!["thyseus-pm-me".to_string()]);
    }
}