tix-tracker 0.12.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
//! Confirmed, idempotent occurrence generation (mission
//! `recurring-issues-01M3C7G7`, WP04; `data-model.md` §6/§8 and
//! `contracts/series-generator.md`).
//!
//! # Only a confirmed action generates
//!
//! [`generate`] is the **only** writer in the recurrence boundary, and it writes
//! only when the caller says so: [`GenerationRequest::confirmed`] must be set, and
//! an unconfirmed request is rejected before anything is read or written. That is
//! C-003's "detection is read-only, every mutation is explicit" as a type, not as a
//! convention — [`crate::recurrence::detect`] has no way to reach this function,
//! because it is given no store.
//!
//! # Idempotency is a lookup, not a lock
//!
//! The occurrence key (`<series-id>@<YYYY-MM-DD>`, WP02) is checked against the
//! caller's index *before* anything is created. A key that already has an
//! occurrence is a **no-op**, and so is one the series recorded as skipped: the
//! second attempt reports what it found and touches nothing (C-006/NFR-002).
//!
//! # One transaction, or nothing
//!
//! An occurrence is three writes: the issue itself (through the normal
//! `commands::create::create` core, so no field parsing or date validation is
//! duplicated), the typed `related` link to the series issue, and the series'
//! generation cursor. They run inside [`Store::transaction`], so a failure at any
//! point leaves no partial occurrence, no dangling link and no event — the
//! property T022 tests by asserting byte-identical files after a failure.
//!
//! # What the occurrence records, and what it does not
//!
//! The occurrence carries the `series:` table (identity: series id, date, key) and
//! one `relationship_added` History entry naming the series and the key. That
//! entry **is** the generation event: the crate's History vocabulary has one kind
//! per applied decision, and the generation's decision is the link between the
//! occurrence and the series. The series' `next_cursor` moves to the generated
//! date in the same transaction — it is bookkeeping for the next detection pass,
//! not a decision, so it appends nothing and the series' history stays append-only
//! as it was.
//!
//! Occurrence state is independent (C-005): once created, the occurrence is an
//! ordinary issue. Nothing here ever rewrites it again, and the series holds no
//! per-occurrence state beyond the cursor and the skipped dates.

use crate::commands::create;
use crate::config::Config;
use crate::error::render_diagnostics;
use crate::model::{HistoryEventKind, SeriesRef};
use crate::recurrence::rule::DateKey;
use crate::recurrence::series::{KeyState, OccurrenceKey, SeriesId, SeriesIndex};
use crate::relationships::RelationKind;
use crate::relationships::Relationship;
use crate::storage::Store;

/// The explicit, confirmed intent to generate one occurrence (T017).
///
/// Every field is required and none is inferred: the series, the exact key, who
/// asked, and *that they confirmed*. A surface builds this from a due warning it
/// showed the user; nothing constructs one on the user's behalf.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GenerationRequest {
    /// The series to generate for.
    pub series_id: SeriesId,
    /// The occurrence key to generate — the warning's key, not a re-derived one.
    pub occurrence_key: OccurrenceKey,
    /// Who asked; lands in the occurrence's History.
    pub actor: String,
    /// Whether the caller confirmed the action. An unconfirmed request is inert.
    pub confirmed: bool,
}

impl GenerationRequest {
    /// A request that is **not** yet confirmed: reading the two ids is not
    /// consent, so a caller has to say so explicitly.
    pub fn new(
        series_id: SeriesId,
        occurrence_key: OccurrenceKey,
        actor: impl Into<String>,
    ) -> Self {
        Self {
            series_id,
            occurrence_key,
            actor: actor.into(),
            confirmed: false,
        }
    }

    /// Record the confirmation.
    pub fn confirm(mut self) -> Self {
        self.confirmed = true;
        self
    }
}

/// Why a generation was refused.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum GenerationDiagnosticKind {
    /// The request was not confirmed, so nothing was even read.
    NotConfirmed,
    /// `occurrence_key` is not `<series-id>@<YYYY-MM-DD>`.
    MalformedKey,
    /// The key names a different series than `series_id`.
    KeySeriesMismatch,
    /// No series with that id is defined.
    UnknownSeries,
    /// The series is paused or ended, so generation is not allowed.
    SeriesNotActive,
    /// The issue that defines the series could not be read.
    DefinitionUnreadable,
    /// The create core refused the occurrence (the request's fields).
    Refused,
}

impl GenerationDiagnosticKind {
    /// The stable spelling the CLI and the MCP tools print.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::NotConfirmed => "not_confirmed",
            Self::MalformedKey => "malformed_occurrence_key",
            Self::KeySeriesMismatch => "occurrence_key_series_mismatch",
            Self::UnknownSeries => "unknown_series",
            Self::SeriesNotActive => "series_not_active",
            Self::DefinitionUnreadable => "definition_unreadable",
            Self::Refused => "refused",
        }
    }
}

/// One actionable reason a generation was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GenerationDiagnostic {
    /// What was wrong.
    pub kind: GenerationDiagnosticKind,
    /// One sentence saying what to do about it.
    pub message: String,
}

impl GenerationDiagnostic {
    fn new(kind: GenerationDiagnosticKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            message: message.into(),
        }
    }

    /// Render through the crate's one diagnostic renderer, so every surface
    /// spells a refusal the same way.
    pub fn render(&self) -> String {
        render_diagnostics(
            "E-tix-series",
            std::iter::once((self.kind.as_str(), self.message.as_str())),
        )
    }
}

/// The result of one confirmed generation attempt (`data-model.md` §8, T021).
///
/// Exactly one of three shapes, and each is a *result*, not an error: a surface
/// reports one outcome per candidate, so a refusal is data the caller shows
/// rather than an exception it has to catch.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GenerationOutcome {
    /// The occurrence was created, linked and recorded.
    Created {
        /// The series it belongs to.
        series_id: SeriesId,
        /// Its occurrence key.
        key: OccurrenceKey,
        /// The date it was generated for.
        date: DateKey,
        /// The new issue's number.
        issue_number: u32,
        /// The new issue's filename.
        filename: String,
    },
    /// The key was already taken: an occurrence exists, or the series skipped it.
    /// Nothing was written.
    NoOp {
        /// The series.
        series_id: SeriesId,
        /// The key that was already taken.
        key: OccurrenceKey,
        /// Which of the two it was.
        state: KeyState,
        /// One sentence saying which.
        message: String,
    },
    /// The action was refused. Nothing was written.
    Rejected {
        /// Every reason, in the order they were found.
        diagnostics: Vec<GenerationDiagnostic>,
    },
}

impl GenerationOutcome {
    /// Whether an occurrence was created.
    pub fn is_created(&self) -> bool {
        matches!(self, Self::Created { .. })
    }

    /// Whether the key was already taken.
    pub fn is_noop(&self) -> bool {
        matches!(self, Self::NoOp { .. })
    }

    /// Whether the action was refused.
    pub fn is_rejected(&self) -> bool {
        matches!(self, Self::Rejected { .. })
    }

    /// The stable word a surface prints: `created`, `no-op` or `rejected`.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Created { .. } => "created",
            Self::NoOp { .. } => "no-op",
            Self::Rejected { .. } => "rejected",
        }
    }

    /// One line for a surface: what happened, and to what.
    pub fn render(&self) -> String {
        match self {
            Self::Created {
                key,
                issue_number,
                filename,
                ..
            } => format!("created #{issue_number} for `{key}` ({filename})"),
            Self::NoOp { key, message, .. } => format!("no-op for `{key}`: {message}"),
            Self::Rejected { diagnostics } => {
                let first = diagnostics
                    .first()
                    .map(GenerationDiagnostic::render)
                    .unwrap_or_else(|| "rejected".to_string());
                if diagnostics.len() > 1 {
                    format!("{first} (and {} more)", diagnostics.len() - 1)
                } else {
                    first
                }
            }
        }
    }
}

/// Generate the occurrence `request` names, if it is confirmed and still free.
///
/// Returns an outcome rather than an error for every *decision* the operation
/// makes; only a genuine I/O failure while reading the store propagates. The
/// three writes (occurrence, link, cursor) are one transaction: either all three
/// land or none do.
#[allow(clippy::too_many_lines)]
pub fn generate(
    config: &Config,
    store: &Store,
    index: &SeriesIndex,
    request: &GenerationRequest,
) -> crate::error::Result<GenerationOutcome> {
    // T017: consent first. An unconfirmed request touches nothing — not even the
    // store — so there is no state to roll back.
    if !request.confirmed {
        return Ok(rejected(GenerationDiagnostic::new(
            GenerationDiagnosticKind::NotConfirmed,
            "generation must be confirmed: detection reports, a person or a caller \
             decides",
        )));
    }
    let (key_series, date) = match OccurrenceKey::parse(request.occurrence_key.as_str()) {
        Ok(parts) => parts,
        Err(error) => {
            return Ok(rejected(GenerationDiagnostic::new(
                GenerationDiagnosticKind::MalformedKey,
                error.first().message.clone(),
            )));
        }
    };
    if key_series != request.series_id {
        return Ok(rejected(GenerationDiagnostic::new(
            GenerationDiagnosticKind::KeySeriesMismatch,
            format!(
                "key `{}` names series `{key_series}` but the request names `{}`",
                request.occurrence_key, request.series_id
            ),
        )));
    }
    // T018: the stable key decides, before anything is created. A generated key
    // and a skipped key are both no-ops, and they say which they are: the caller
    // asked twice, and "already created" and "you skipped this one" are different
    // answers to that.
    let Some(series) = index.series_by_id(&request.series_id) else {
        return Ok(rejected(GenerationDiagnostic::new(
            GenerationDiagnosticKind::UnknownSeries,
            format!("no series `{}` is defined", request.series_id),
        )));
    };
    match index.key_state(&request.occurrence_key) {
        KeyState::Generated => {
            return Ok(GenerationOutcome::NoOp {
                series_id: series.id.clone(),
                key: request.occurrence_key.clone(),
                state: KeyState::Generated,
                message: format!(
                    "occurrence `{}` already exists ({})",
                    request.occurrence_key,
                    index
                        .occurrence(&request.occurrence_key)
                        .map(|record| record.filename.clone())
                        .unwrap_or_else(|| "in the index".to_string())
                ),
            });
        }
        KeyState::Skipped => {
            return Ok(GenerationOutcome::NoOp {
                series_id: series.id.clone(),
                key: request.occurrence_key.clone(),
                state: KeyState::Skipped,
                message: "the series recorded this date as skipped, and a skipped \
                          key is never regenerated"
                    .to_string(),
            });
        }
        KeyState::Free => {}
    }
    if !series.allows_generation() {
        return Ok(rejected(GenerationDiagnostic::new(
            GenerationDiagnosticKind::SeriesNotActive,
            format!(
                "series `{}` is {}; resume or restart it before generating",
                series.id,
                series.state.as_str()
            ),
        )));
    }

    // The definition issue is the template: its own create fields are what an
    // occurrence is made of, which is what "series defaults" means in this model
    // (the definition *is* the normal issue that carries them).
    let issues = store.list()?;
    let Some(definition) = issues
        .iter()
        .find(|issue| issue.number == series.issue_number)
    else {
        return Ok(rejected(GenerationDiagnostic::new(
            GenerationDiagnosticKind::DefinitionUnreadable,
            format!(
                "series `{}` is defined by issue #{} ({}) but that issue could not be read",
                series.id, series.issue_number, series.filename
            ),
        )));
    };

    // T019 + T020 + T021 in one transaction. The comma-separated list arguments
    // are the create core's own grammar, so the occurrence goes through exactly
    // the parsing and validation a hand-typed `tix create` does.
    let title = occurrence_title(&definition.title, &date);
    let labels = definition.labels.join(",");
    let files = definition.files.join(",");
    let cycles = definition
        .cycles
        .as_ref()
        .map(|cycles| cycles.join(","))
        .unwrap_or_default();
    let milestones = definition
        .milestones
        .as_ref()
        .map(|milestones| milestones.join(","))
        .unwrap_or_default();
    let created = store.transaction(|| {
        let mut occurrence = create::create(
            config,
            store,
            &title,
            Some(&definition.body),
            Some(definition.status.clone()),
            Some(definition.priority.clone()),
            definition.assignee.as_deref(),
            Some(labels.as_str()),
            Some(files.as_str()),
            definition.estimate.as_deref(),
            Some(cycles.as_str()),
            Some(milestones.as_str()),
            definition.reviewer.as_deref(),
            definition.start_date.as_deref(),
            definition.due_date.as_deref(),
            None,
            None,
            definition.type_.as_deref(),
        )?;
        // The identity: series id, canonical date, and the stored key.
        occurrence.series = Some(SeriesRef {
            id: series.id.as_str().to_string(),
            name: Some(series.name.clone()),
            date: Some(date.as_str().to_string()),
            key: Some(request.occurrence_key.as_str().to_string()),
            rule: None,
            state: None,
            next_cursor: None,
            skipped: Vec::new(),
        });
        // The typed link, and the one event that records the generation.
        occurrence.relationships.push(Relationship::new(
            occurrence.number,
            definition.number,
            RelationKind::Related,
            &definition.title,
        ));
        occurrence.history.append_now(
            &request.actor,
            HistoryEventKind::RelationshipAdded,
            &format!(
                "generated occurrence `{}` of series `{}` ({})",
                request.occurrence_key, series.id, series.name
            ),
        );
        let filename = store.update(&occurrence.filename, &occurrence)?;

        // The cursor is bookkeeping for the next detection pass: it moves to the
        // date this generation consumed, so the next candidate becomes due. The
        // series' history is untouched — a cursor is not a decision.
        let mut definition = definition.clone();
        if let Some(reference) = definition.series.as_mut() {
            reference.next_cursor = Some(date.as_str().to_string());
        }
        store.update(&definition.filename, &definition)?;
        Ok((occurrence, filename))
    });

    match created {
        Ok((occurrence, filename)) => Ok(GenerationOutcome::Created {
            series_id: series.id.clone(),
            key: request.occurrence_key.clone(),
            date,
            issue_number: occurrence.number,
            filename,
        }),
        // A refused create (a blank title, a date the calendar rejects, a status
        // the board does not configure) is a **rejected outcome**, not a crash:
        // the transaction has already rolled back, so the caller gets a reason and
        // no half-written occurrence.
        Err(error) => Ok(rejected(GenerationDiagnostic::new(
            GenerationDiagnosticKind::Refused,
            format!("the create core refused the occurrence: {error}"),
        ))),
    }
}

/// The occurrence's title: the series' title plus the date it is for, so two
/// occurrences of one series are distinguishable in a list without relying on the
/// key. The key, not the title, stays the identity.
fn occurrence_title(series_title: &str, date: &DateKey) -> String {
    format!("{series_title} ({date})")
}

/// One refusal, as an outcome.
fn rejected(diagnostic: GenerationDiagnostic) -> GenerationOutcome {
    GenerationOutcome::Rejected {
        diagnostics: vec![diagnostic],
    }
}

#[cfg(test)]
mod tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;

    /// The date and key every test uses, built through `time` rather than parsed:
    /// `DateKey` has no public parser (its own module's is private).
    fn date_and_key() -> (DateKey, OccurrenceKey) {
        let date = DateKey::from_date(
            time::Date::from_calendar_date(2026, time::Month::January, 1).expect("a real date"),
        );
        let id = SeriesId::parse("s-abc").expect("a valid id");
        let key = OccurrenceKey::new(&id, &date);
        (date, key)
    }

    #[test]
    fn a_request_is_unconfirmed_until_it_says_so() {
        let (_, key) = date_and_key();
        let request =
            GenerationRequest::new(SeriesId::parse("s-abc").unwrap(), key.clone(), "alice");
        assert!(!request.confirmed, "reading two ids is not consent");
        let confirmed = request.clone().confirm();
        assert!(confirmed.confirmed);
        assert_eq!(confirmed.actor, "alice");
        assert_eq!(confirmed.occurrence_key, key);
    }

    #[test]
    fn an_occurrence_title_names_the_date_after_the_series_title() {
        let (date, _) = date_and_key();
        assert_eq!(
            occurrence_title("Nightly close", &date),
            "Nightly close (2026-01-01)"
        );
    }

    #[test]
    fn every_outcome_has_one_stable_word() {
        let (date, key) = date_and_key();
        let series_id = SeriesId::parse("s-abc").unwrap();

        let created = GenerationOutcome::Created {
            series_id: series_id.clone(),
            key: key.clone(),
            date: date.clone(),
            issue_number: 7,
            filename: "a.md".to_string(),
        };
        assert_eq!(created.as_str(), "created");
        assert!(created.is_created());
        assert!(created.render().contains("#7"));

        let noop = GenerationOutcome::NoOp {
            series_id,
            key,
            state: KeyState::Generated,
            message: "already exists".to_string(),
        };
        assert_eq!(noop.as_str(), "no-op");
        assert!(noop.is_noop());
        assert!(noop.render().contains("already exists"));

        let rejected = GenerationOutcome::Rejected {
            diagnostics: vec![
                GenerationDiagnostic::new(
                    GenerationDiagnosticKind::NotConfirmed,
                    "generation must be confirmed",
                ),
                GenerationDiagnostic::new(GenerationDiagnosticKind::UnknownSeries, "no series"),
            ],
        };
        assert_eq!(rejected.as_str(), "rejected");
        assert!(rejected.is_rejected());
        assert!(
            rejected.render().contains("not_confirmed"),
            "{}",
            rejected.render()
        );
        assert!(
            rejected.render().contains("and 1 more"),
            "a second reason is counted, not hidden: {}",
            rejected.render()
        );
    }

    #[test]
    fn the_diagnostic_kinds_are_the_closed_set() {
        let spellings: Vec<&str> = [
            GenerationDiagnosticKind::NotConfirmed,
            GenerationDiagnosticKind::MalformedKey,
            GenerationDiagnosticKind::KeySeriesMismatch,
            GenerationDiagnosticKind::UnknownSeries,
            GenerationDiagnosticKind::SeriesNotActive,
            GenerationDiagnosticKind::DefinitionUnreadable,
            GenerationDiagnosticKind::Refused,
        ]
        .iter()
        .map(|kind| kind.as_str())
        .collect();
        assert_eq!(
            spellings,
            vec![
                "not_confirmed",
                "malformed_occurrence_key",
                "occurrence_key_series_mismatch",
                "unknown_series",
                "series_not_active",
                "definition_unreadable",
                "refused",
            ]
        );
    }
}