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
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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
//! `tix recurring`: the CLI adapter over the recurrence boundary (mission
//! `recurring-issues-01M3C7G7`, WP06).
//!
//! # A thin adapter, and nothing else
//!
//! Every subcommand here is `parse → call one service → print`. The rule grammar
//! and its arithmetic live in [`crate::recurrence::rule`], the identity and the
//! index in [`crate::recurrence::series`], detection in
//! [`crate::recurrence::detect`], creation in [`crate::recurrence::generate`], and
//! the lifecycle in [`crate::recurrence::lifecycle`]. This module owns no
//! schedule, no clock beyond resolving "today" at the boundary, no series writer
//! and no History grammar — the two ways a second, divergent implementation would
//! appear.
//!
//! # The one clock, and where it lives
//!
//! `--date` is explicit on every command that evaluates a schedule, and when it is
//! omitted the *boundary* resolves today (`crate::model::today`) and hands the
//! domain a [`RuleContext`]. Nothing below the CLI reads a clock, which is what
//! makes `tix recurring detect --date 2026-03-01` reproducible in a test and in a
//! cron job alike.
//!
//! # Confirmation
//!
//! A mutation needs `--yes`, exactly as `tix delete` and `tix move --yes` do. The
//! flag is the confirmation the services require; without it the service refuses
//! and this surface prints the refusal and exits non-zero, having written nothing.

use time::{Date, Month};

use crate::cli::{
    RecurringAction, RecurringCreateArgs, RecurringEditArgs, RecurringLifecycleArgs,
    RecurringRuleArgs,
};
use crate::config::Config;
use crate::error::{Result, TixError};
use crate::model::{SeriesRef, SeriesRule};
use crate::recurrence::detect::{Detection, detect};
use crate::recurrence::generate::{GenerationOutcome, GenerationRequest, generate};
use crate::recurrence::lifecycle::{LifecycleAction, LifecycleOutcome, LifecycleRequest, apply};
use crate::recurrence::rule::{DateKey, RuleContext, Timezone};
use crate::recurrence::series::{OccurrenceKey, Series, SeriesId, SeriesIndex};
use crate::storage::Store;

/// Run one `tix recurring` subcommand.
///
/// One read of the repository per invocation: the index every subcommand works
/// from is built here, once, from the files — never carried in from a caller.
pub fn run(config: &Config, store: &Store, action: &RecurringAction) -> Result<()> {
    let issues = store.list()?;
    let index = SeriesIndex::build(&issues);
    match action {
        RecurringAction::List => list(&index),
        RecurringAction::Show { series } => show(&index, series),
        RecurringAction::Create(args) => create(config, store, args),
        RecurringAction::Edit { series, args } => edit(store, &index, series, args),
        RecurringAction::Detect { date, timezone } => {
            detect_now(&index, date.as_deref(), timezone.as_deref())
        }
        RecurringAction::Generate {
            series,
            date,
            confirmation,
        } => generate_now(config, store, &index, series, date, confirmation),
        RecurringAction::Pause {
            series,
            confirmation,
        } => lifecycle(store, series, LifecycleAction::Pause, None, confirmation),
        RecurringAction::Resume {
            series,
            confirmation,
        } => lifecycle(store, series, LifecycleAction::Resume, None, confirmation),
        RecurringAction::End {
            series,
            confirmation,
        } => lifecycle(store, series, LifecycleAction::End, None, confirmation),
        RecurringAction::Skip {
            series,
            date,
            confirmation,
        } => lifecycle(
            store,
            series,
            LifecycleAction::Skip,
            Some(date),
            confirmation,
        ),
        RecurringAction::Defer {
            series,
            date,
            confirmation,
        } => lifecycle(
            store,
            series,
            LifecycleAction::Defer,
            Some(date),
            confirmation,
        ),
        RecurringAction::Ignore {
            series,
            date,
            confirmation,
        } => lifecycle(
            store,
            series,
            LifecycleAction::Ignore,
            Some(date),
            confirmation,
        ),
    }
}

// ---------------------------------------------------------------------------
// Read-only: list, show, detect
// ---------------------------------------------------------------------------

/// One tab-separated row per series, in id order.
fn list(index: &SeriesIndex) -> Result<()> {
    println!("id\tname\tstate\tnext_cursor\tskipped");
    for series in index.series() {
        println!(
            "{}\t{}\t{}\t{}\t{}",
            series.id,
            series.name,
            series.state.as_str(),
            series
                .next_cursor
                .as_ref()
                .map(DateKey::as_str)
                .unwrap_or("-"),
            series.skipped.len()
        );
    }
    Ok(())
}

/// Everything the definition holds and the index derived from it.
fn show(index: &SeriesIndex, selector: &str) -> Result<()> {
    let series = resolve(index, selector)?;
    println!("id: {}", series.id);
    println!("name: {}", series.name);
    println!("state: {}", series.state.as_str());
    println!("rule: {}", series.rule.summary());
    println!(
        "anchor: {}",
        series
            .rule
            .anchor_key()
            .map(|key| key.as_str().to_string())
            .unwrap_or_else(|_| "(invalid)".to_string())
    );
    println!(
        "next_cursor: {}",
        series
            .next_cursor
            .as_ref()
            .map(DateKey::as_str)
            .unwrap_or("-")
    );
    println!(
        "skipped: {}",
        if series.skipped.is_empty() {
            "-".to_string()
        } else {
            series
                .skipped
                .iter()
                .map(DateKey::as_str)
                .collect::<Vec<_>>()
                .join(",")
        }
    );
    println!("issue: #{} ({})", series.issue_number, series.filename);
    let occurrences: Vec<String> = index
        .occurrences()
        .filter(|record| record.series_id == series.id)
        .map(|record| record.date.as_str().to_string())
        .collect();
    println!(
        "occurrences: {}",
        if occurrences.is_empty() {
            "-".to_string()
        } else {
            occurrences.join(",")
        }
    );
    for diagnostic in index.diagnostics() {
        eprintln!("{}", diagnostic.render());
    }
    Ok(())
}

/// Detection, read-only, with the resolution of "today" kept at the boundary.
fn detect_now(index: &SeriesIndex, date: Option<&str>, timezone: Option<&str>) -> Result<()> {
    let context = context_for(date, timezone)?;
    let detection = detect(index, &context);
    print_detection(&detection);
    Ok(())
}

fn print_detection(detection: &Detection) {
    if detection.is_empty() {
        println!(
            "No occurrences due across {} series.",
            detection.series_examined()
        );
    } else {
        println!("series_id\toccurrence_key\tdue_date\trule");
        for warning in detection.warnings() {
            println!(
                "{}\t{}\t{}\t{}",
                warning.series_id, warning.occurrence_key, warning.due_date, warning.rule_summary
            );
        }
    }
    for note in detection.notes() {
        // The kind is the machine-readable half: a script branches on
        // `series_paused` / `series_ended` / `cursor_already_taken`, and a person
        // reads the sentence beside it.
        println!(
            "note: {}\t{}\t{}",
            note.kind.as_str(),
            note.series_id,
            note.message
        );
    }
}

// ---------------------------------------------------------------------------
// Series definition: create, edit
// ---------------------------------------------------------------------------

/// What [`create_series`] wrote, as the surface that asked for it reports it.
///
/// The CLI's `create` prints these three values; the F8 Schedule page's create form
/// shows them in its status line. Both go through [`create_series`], so the
/// validation order, the transaction, the issue's fields and the `series:` table
/// have one implementation (C-007) and a creation from the page is byte-identical to
/// the same input from the command line.
pub(crate) struct CreatedSeries {
    /// The series' stable id, as the validated definition carries it.
    pub id: String,
    /// The definition issue's number.
    pub issue_number: u32,
    /// The definition issue's filename within the store.
    pub filename: String,
    /// The rule, in the summary `tix recurring show` prints.
    pub rule: String,
}

/// Create the issue that *is* the series, validating the rule first, and return
/// what was written without printing anything.
///
/// No `stdout`: the F8 Schedule page's create form calls this from inside the TUI's
/// alternate screen, where a `println!` would corrupt the frame. The CLI's `create`
/// is the thin printer over it.
pub(crate) fn create_series(
    config: &Config,
    store: &Store,
    args: &RecurringCreateArgs,
) -> Result<CreatedSeries> {
    let id = match args.id.as_deref() {
        Some(raw) => SeriesId::parse(raw).map_err(|error| refusal(&error.first().render()))?,
        None => SeriesId::generate(),
    };
    let name = args.name.clone().unwrap_or_else(|| args.title.clone());
    let reference = SeriesRef {
        id: id.as_str().to_string(),
        name: Some(name.clone()),
        date: None,
        key: None,
        rule: Some(rule_from_args(&args.rule, SeriesRule::default())),
        state: None,
        next_cursor: None,
        skipped: Vec::new(),
    };
    // Rejected **before** persistence: a rule that does not validate must not
    // create an issue at all.
    let definition = Series::from_ref(&reference, 0, "")
        .and_then(|series| {
            series.ok_or_else(|| {
                crate::recurrence::series::SeriesError::single(
                    crate::recurrence::series::SeriesDiagnostic::new(
                        crate::recurrence::series::SeriesDiagnosticKind::MissingField,
                        "series.rule",
                        "a series definition needs a rule",
                    ),
                )
            })
        })
        .map_err(|error| refusal(&error.first().render()))?;

    let created = store.transaction(|| {
        let mut issue = crate::commands::create::create(
            config,
            store,
            &args.title,
            args.body.as_deref(),
            args.status.clone().map(crate::model::Status::new),
            args.priority
                .as_deref()
                .map(crate::commands::parse_priority)
                .transpose()?,
            args.assignee.as_deref(),
            args.labels.as_deref(),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        )?;
        issue.series = Some(reference.clone());
        let filename = store.update(&issue.filename, &issue)?;
        Ok((issue, filename))
    })?;

    let (issue, filename) = created;
    Ok(CreatedSeries {
        id: definition.id.to_string(),
        issue_number: issue.number,
        filename,
        rule: definition.rule.summary(),
    })
}

/// Create the issue that *is* the series, validating the rule first, and print what
/// was written — the CLI's own report of [`create_series`].
fn create(config: &Config, store: &Store, args: &RecurringCreateArgs) -> Result<()> {
    let created = create_series(config, store, args)?;
    println!("Created series {}", created.id);
    println!("  issue: #{} ({})", created.issue_number, created.filename);
    println!("  rule: {}", created.rule);
    Ok(())
}

/// Rename and/or re-rule an existing series, keeping its identity.
fn edit(
    store: &Store,
    index: &SeriesIndex,
    selector: &str,
    args: &RecurringEditArgs,
) -> Result<()> {
    let series = resolve(index, selector)?;
    let issues = store.list()?;
    let definition = issues
        .iter()
        .find(|issue| issue.number == series.issue_number)
        .ok_or_else(|| {
            TixError::NotFound(format!(
                "issue #{} defining series `{}`",
                series.issue_number, series.id
            ))
        })?;
    let mut updated = definition.clone();
    let mut reference = updated.series.clone().ok_or_else(|| {
        TixError::Refused(format!(
            "issue #{} no longer carries a series table",
            updated.number
        ))
    })?;
    if let Some(name) = args.name.as_deref() {
        reference.name = Some(name.to_string());
    }
    if args.rule.is_any() {
        let stored = reference.rule.clone().unwrap_or_default();
        reference.rule = Some(rule_from_args(&args.rule, stored));
        // Validate before the write, so a typo leaves the file untouched.
        let candidate = SeriesRef {
            id: reference.id.clone(),
            name: reference.name.clone().or_else(|| Some(series.name.clone())),
            ..reference.clone()
        };
        Series::from_ref(&candidate, updated.number, &updated.filename)
            .map_err(|error| refusal(&error.first().render()))?;
    }
    updated.series = Some(reference);
    let filename = store.transaction(|| store.update(&updated.filename, &updated))?;
    let name = updated
        .series
        .as_ref()
        .and_then(|reference| reference.name.clone())
        .unwrap_or_default();
    println!("Updated series {}", series.id);
    println!("  name: {name}");
    println!("  file: {filename}");
    Ok(())
}

// ---------------------------------------------------------------------------
// Actions
// ---------------------------------------------------------------------------

fn generate_now(
    config: &Config,
    store: &Store,
    index: &SeriesIndex,
    selector: &str,
    date: &str,
    confirmation: &RecurringLifecycleArgs,
) -> Result<()> {
    let series = resolve(index, selector)?;
    let context = context_for(Some(date), None)?;
    let key = OccurrenceKey::new(&series.id, &DateKey::from_date(context.today));
    let request = if confirmation.yes {
        GenerationRequest::new(series.id.clone(), key, actor()).confirm()
    } else {
        GenerationRequest::new(series.id.clone(), key, actor())
    };
    let outcome = generate(config, store, index, &request)?;
    match outcome {
        GenerationOutcome::Created {
            issue_number,
            filename,
            ref key,
            ..
        } => {
            println!("Created occurrence #{issue_number} for {key}");
            println!("  file: {filename}");
        }
        GenerationOutcome::NoOp {
            ref key, message, ..
        } => {
            println!("No-op for {key}: {message}");
        }
        GenerationOutcome::Rejected { .. } => {
            return Err(TixError::Refused(outcome.render()));
        }
    }
    Ok(())
}

fn lifecycle(
    store: &Store,
    selector: &str,
    action: LifecycleAction,
    date: Option<&str>,
    confirmation: &RecurringLifecycleArgs,
) -> Result<()> {
    let issues = store.list()?;
    let index = SeriesIndex::build(&issues);
    let series = resolve(&index, selector)?;
    let mut request = LifecycleRequest::new(series.id.clone(), action, actor());
    if let Some(date) = date {
        let context = context_for(Some(date), None)?;
        request = request.about(OccurrenceKey::new(
            &series.id,
            &DateKey::from_date(context.today),
        ));
    }
    if let Some(reason) = confirmation.reason.as_deref() {
        request = request.because(reason);
    }
    if confirmation.yes {
        request = request.confirm();
    }
    let outcome = apply(store, &request)?;
    match &outcome {
        LifecycleOutcome::Applied {
            action,
            state,
            detail,
            ..
        } => {
            println!(
                "{}: series {} is now {}",
                action.as_str(),
                series.id,
                state.as_str()
            );
            println!("  {detail}");
        }
        LifecycleOutcome::NoOp {
            action, message, ..
        } => {
            println!("{}: no-op: {message}", action.as_str());
        }
        LifecycleOutcome::Rejected { .. } => return Err(TixError::Refused(outcome.render())),
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------

/// Resolve a series selector: the stable id first, then a **unique** display name.
///
/// Identity is the id (C-002); the name is accepted only because a human types it,
/// and an ambiguous name is refused rather than guessed.
///
/// `pub(crate)` because the MCP tools (WP08) take the same selectors and must not
/// grow a second resolver: one place decides what a series reference means.
pub(crate) fn resolve(index: &SeriesIndex, selector: &str) -> Result<Series> {
    let trimmed = selector.trim();
    if let Ok(id) = SeriesId::parse(trimmed)
        && let Some(series) = index.series_by_id(&id)
    {
        return Ok(series.clone());
    }
    let matches: Vec<&Series> = index
        .series()
        .filter(|series| series.name == trimmed)
        .collect();
    match matches.as_slice() {
        [series] => Ok((*series).clone()),
        [] => Err(TixError::NotFound(format!("series `{trimmed}`"))),
        several => Err(TixError::InvalidInput(format!(
            "series name `{trimmed}` is ambiguous: {}",
            several
                .iter()
                .map(|series| series.id.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        ))),
    }
}

/// The date context a subcommand evaluates against.
///
/// `--date` wins when given; otherwise the **boundary** resolves today and hands
/// the domain a context, so no domain module ever reads a clock. `pub(crate)` for
/// the same reason [`resolve`] is: MCP takes a `date` argument, and the one place
/// that turns it into a [`RuleContext`] is here.
pub(crate) fn context_for(date: Option<&str>, timezone: Option<&str>) -> Result<RuleContext> {
    let today = match date {
        Some(raw) => parse_date(raw)?,
        None => parse_date(&crate::model::today())?,
    };
    let context = RuleContext::on(today);
    Ok(match timezone {
        Some(raw) => context.with_timezone(Timezone::parse(raw)),
        None => context,
    })
}

/// Parse a `YYYY-MM-DD` calendar date at the CLI boundary.
///
/// The domain modules validate dates through `crate::model::validate_date`; this
/// turns the validated text into the `time::Date` the rule context takes. It is a
/// boundary concern (the CLI is where user text becomes a value), not schedule
/// logic, and `DateKey` exposes no parser of its own.
fn parse_date(raw: &str) -> Result<Date> {
    let raw = raw.trim();
    if !crate::model::validate_date(raw) {
        return Err(TixError::InvalidInput(format!(
            "`{raw}` is not a `YYYY-MM-DD` calendar date"
        )));
    }
    let year: i32 = raw[0..4].parse().map_err(|_| date_error(raw))?;
    let month: u8 = raw[5..7].parse().map_err(|_| date_error(raw))?;
    let day: u8 = raw[8..10].parse().map_err(|_| date_error(raw))?;
    Date::from_calendar_date(
        year,
        Month::try_from(month).map_err(|_| date_error(raw))?,
        day,
    )
    .map_err(|_| date_error(raw))
}

fn date_error(raw: &str) -> TixError {
    TixError::InvalidInput(format!("`{raw}` is not a `YYYY-MM-DD` calendar date"))
}

/// Build a stored rule from the CLI's flags, keeping every field the caller did
/// not name (so `edit --interval 2` changes the cadence and nothing else).
fn rule_from_args(args: &RecurringRuleArgs, base: SeriesRule) -> SeriesRule {
    SeriesRule {
        kind: args.rule.clone().or(base.kind),
        interval: args.interval.or(base.interval),
        anchor: args.anchor.clone().or(base.anchor),
        timezone: args.timezone.clone().or(base.timezone),
        expression: args.expression.clone().or(base.expression),
        unit: args.unit.clone().or(base.unit),
        extensions: base.extensions,
    }
}

/// The actor recorded in History: the git identity when there is one, else the
/// environment's user, else a stable placeholder.
pub(crate) fn actor() -> String {
    crate::assignee::git_identity()
        .map(|identity| identity.to_string())
        .or_else(|| std::env::var("USER").ok())
        .or_else(|| std::env::var("USERNAME").ok())
        .unwrap_or_else(|| "tix".to_string())
}

/// A refusal whose payload is already a rendered diagnostic block.
fn refusal(rendered: &str) -> TixError {
    TixError::Refused(rendered.to_string())
}

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

    #[test]
    fn the_rule_flags_overlay_the_stored_rule_field_by_field() {
        let base = SeriesRule {
            kind: Some("interval".to_string()),
            interval: Some(3),
            anchor: Some("2026-01-01".to_string()),
            unit: Some("weeks".to_string()),
            ..SeriesRule::default()
        };
        let args = RecurringRuleArgs {
            rule: None,
            anchor: None,
            interval: Some(5),
            unit: None,
            expression: None,
            timezone: Some("+02:00".to_string()),
        };
        let merged = rule_from_args(&args, base);
        assert_eq!(
            merged.kind.as_deref(),
            Some("interval"),
            "unnamed fields stay"
        );
        assert_eq!(merged.interval, Some(5), "the named field changes");
        assert_eq!(merged.unit.as_deref(), Some("weeks"));
        assert_eq!(merged.timezone.as_deref(), Some("+02:00"));
    }

    #[test]
    fn a_date_that_is_not_a_calendar_date_is_refused_at_the_boundary() {
        for raw in ["", "2026-1-1", "2026-02-30", "yesterday"] {
            let error = parse_date(raw).unwrap_err().to_string();
            assert!(
                error.contains("YYYY-MM-DD"),
                "`{raw}` must be refused with the format: {error}"
            );
        }
        assert_eq!(
            parse_date("2026-02-28").unwrap(),
            Date::from_calendar_date(2026, Month::February, 28).unwrap()
        );
    }

    #[test]
    fn an_explicit_date_wins_over_today() {
        let context = context_for(Some("2026-03-01"), None).unwrap();
        assert_eq!(DateKey::from_date(context.today).as_str(), "2026-03-01");
        let tz = context_for(Some("2026-03-01"), Some("+02:00")).unwrap();
        assert!(tz.timezone.is_some(), "the timezone policy is carried");
    }
}