tix-tracker 0.3.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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
//! External tracker sync: orchestration for `tix export` / `tix import`,
//! the [`Tool`] selector, the [`CommandRunner`] spawn seam, and the pure
//! mapping / conflict-resolution rules.
//!
//! WP05 wires the CLI to `glab` (GitLab) and `linear-cli` (Linear) under
//! `contracts/external-tools.md`. Tokens are resolved through
//! [`token::resolve`] with env precedence, injected only as an env pair (never
//! argv), and every error/report surface scrubs the secret as `<token>`.
//!
//! The orchestration lives here so it is testable at module granularity by
//! pointing PATH at fake tool scripts; [`export`] / [`import`] are pure in the
//! sense that they take the store, tool, config and an output sink, and the
//! only externally visible side effects are local issue files, `tix.toml`,
//! the tool subprocesses, and what is written to `out`.

use std::io::Write;

use crate::config::{BoardConfiguration, Config};
use crate::error::{Result, TixError};
use crate::model::{Issue, Status};
use crate::storage::Store;

pub mod glab;
pub mod linear;
pub mod token;

/// The supported external tracker, selected via `--target gitlab|linear`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tool {
    GitLab,
    Linear,
}

impl Tool {
    #[must_use]
    pub fn from_target(target: &str) -> Result<Tool> {
        match target {
            "gitlab" => Ok(Tool::GitLab),
            "linear" => Ok(Tool::Linear),
            other => Err(TixError::InvalidInput(format!(
                "unknown --target '{other}' — use gitlab or linear"
            ))),
        }
    }

    /// The token env var that wins over any `tix.toml` token.
    #[must_use]
    pub fn token_var(self) -> &'static str {
        match self {
            Tool::GitLab => "GITLAB_TOKEN",
            Tool::Linear => "LINEAR_TOKEN",
        }
    }

    /// The binary shelled out to.
    #[must_use]
    pub fn binary(self) -> &'static str {
        match self {
            Tool::GitLab => "glab",
            Tool::Linear => "linear-cli",
        }
    }

    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Tool::GitLab => "gitlab",
            Tool::Linear => "linear",
        }
    }
}

impl std::fmt::Display for Tool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The captured result of a spawned external tool.
///
/// `ProcessRunner` waits synchronously on the child (never kills it), so a
/// blocking tool blocks the sync — the contract's supported "wait" model for
/// `glab`/`linear-cli`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandOutcome {
    pub success: bool,
    pub status: Option<i32>,
    pub stdout: String,
    pub stderr: String,
}

impl CommandOutcome {
    /// The human-readable output chosen for error reporting: stderr when the
    /// tool failed and produced any, otherwise stdout.
    #[must_use]
    pub fn text(&self) -> &str {
        if self.success {
            &self.stdout
        } else if !self.stderr.trim().is_empty() {
            &self.stderr
        } else {
            &self.stdout
        }
    }
}

/// Spawn seam: production uses [`ProcessRunner`]; tests inject a
/// `FakeRunner` that records argv/env without spawning anything.
pub trait CommandRunner: Send {
    fn run(
        &self,
        program: &str,
        args: &[String],
        env: &[(String, String)],
    ) -> Result<CommandOutcome>;

    /// Downcasting hook so tests can inspect recorded calls on a fake.
    fn as_any(&self) -> &dyn std::any::Any;
}

/// Production runner: `std::process::Command` with a synchronous output wait.
///
/// A missing binary surfaces as [`TixError::External`] with the contract's
/// exit-3 wording (`contracts/external-tools.md`: "missing binary ... exit 3").
pub struct ProcessRunner;

impl CommandRunner for ProcessRunner {
    fn run(
        &self,
        program: &str,
        args: &[String],
        env: &[(String, String)],
    ) -> Result<CommandOutcome> {
        use std::process::Command;
        let mut cmd = Command::new(program);
        cmd.args(args);
        for (key, value) in env {
            cmd.env(key, value);
        }
        let output = cmd.output().map_err(|e| {
            if e.kind() == std::io::ErrorKind::NotFound {
                TixError::External(not_found_message(program))
            } else {
                TixError::External(format!("`{program}` failed to start: {e}"))
            }
        })?;
        Ok(CommandOutcome {
            success: output.status.success(),
            status: output.status.code(),
            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Common surface both tracker adapters implement so the orchestration is
/// tool-agnostic.
///
/// `status` is the *remote* state/label already computed by the pure mapping
/// helpers (e.g. `closed`, `Done`, or the first work column). GitLab conveys
/// "done" via a separate close call ([`TrackerAdapter::mark_done`]); Linear
/// sends `--status Done` directly ([`TrackerAdapter::done_via_status`]).
pub trait TrackerAdapter {
    fn tool(&self) -> Tool;

    /// Create a remote issue and return its remote id (GitLab `iid`, Linear
    /// `identifier`).
    fn create_issue(
        &mut self,
        title: &str,
        body: &str,
        labels: &[String],
        assignee: Option<&str>,
        priority: Option<&str>,
        status: &str,
    ) -> Result<String>;

    /// Update an existing remote issue in place.
    #[allow(clippy::too_many_arguments)]
    fn update_issue(
        &mut self,
        remote_ref: &str,
        title: &str,
        body: &str,
        labels: &[String],
        assignee: Option<&str>,
        priority: Option<&str>,
        status: &str,
    ) -> Result<()>;

    /// Convey "done" (GitLab: `issue close <id>`). Only invoked when
    /// `done_via_status` is false.
    fn mark_done(&mut self, remote_ref: &str) -> Result<()>;

    /// List open remote issues (the import source). Closed/done issues are
    /// excluded.
    fn list_open(&mut self) -> Result<Vec<RemoteIssue>>;

    /// Linear sets done through the status flag; GitLab needs a separate
    /// close call.
    fn done_via_status(&self) -> bool;
}

/// A remote issue parsed from the tracker's JSON list output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteIssue {
    /// Remote id (GitLab `iid`, Linear `identifier`).
    pub id: String,
    pub title: String,
    pub description: String,
    pub labels: Vec<String>,
    /// Remote state (`closed` / `Done` / a column label, ...).
    pub state: String,
    /// ISO-8601 `updated_at`; `None` when the tool omitted it.
    pub updated_at: Option<String>,
    /// Best-effort single assignee (bare name, no `@`).
    pub assignee: Option<String>,
}

/// Map a local column to the remote state/label sent to the tracker
/// (`contracts/external-tools.md` mapping table).
///
/// - GitLab: done → `closed`, anything else → `opened`.
/// - Linear: done → `Done`, otherwise the first non-done column label.
#[must_use]
pub fn local_to_remote_status(tool: Tool, local_status: &str, config: &Config) -> String {
    let board = config.default_config();
    match tool {
        Tool::GitLab => {
            if is_done_column(board, local_status) {
                "closed".into()
            } else {
                "opened".into()
            }
        }
        Tool::Linear => {
            if is_done_column(board, local_status) {
                "Done".into()
            } else {
                first_work_column(board).to_string()
            }
        }
    }
}

/// Map a remote state/label back onto a local column. Closed/Done maps to
/// the effective done column; anything else lands in the column whose name
/// matches (case-insensitive), else the first column — per the contract's
/// "whose name matches, else into the first column".
#[must_use]
pub fn remote_to_local_status(tool: Tool, remote_status: &str, config: &Config) -> String {
    let board = config.default_config();
    let done = board.effective_done_column().unwrap_or("done").to_string();
    match tool {
        Tool::GitLab => {
            if remote_status == "closed" {
                done
            } else {
                board
                    .columns
                    .first()
                    .cloned()
                    .unwrap_or_else(|| "todo".into())
            }
        }
        Tool::Linear => {
            if remote_status == "Done" {
                done
            } else {
                board
                    .columns
                    .iter()
                    .find(|c| c.eq_ignore_ascii_case(remote_status))
                    .cloned()
                    .unwrap_or_else(|| {
                        board
                            .columns
                            .first()
                            .cloned()
                            .unwrap_or_else(|| "todo".into())
                    })
            }
        }
    }
}

fn is_done_column(board: &BoardConfiguration, local_status: &str) -> bool {
    board.effective_done_column() == Some(local_status)
}

fn first_work_column(board: &BoardConfiguration) -> &str {
    let done = board.effective_done_column().unwrap_or("done");
    board
        .columns
        .iter()
        .find(|c| c.as_str() != done)
        .map_or(done, String::as_str)
}

/// The inverse of `model::civil_from_days` (Howard Hinnant's
/// `days_from_civil`): calendar date → days since the Unix epoch.
#[must_use]
pub fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
    let y = if m <= 2 { y - 1 } else { y };
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400; // [0, 399]
    let mp = (m + 9) % 12; // [0, 11]
    let doy = i64::from((153 * mp + 2) / 5 + d - 1); // [0, 365]
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096]
    era * 146_097 + doe - 719_468
}

/// Parse `YYYY-MM-DD` into days since the Unix epoch.
#[must_use]
pub fn date_to_epoch_days(ymd: &str) -> Option<i64> {
    let mut parts = ymd.trim().split('-');
    let y: i64 = parts.next()?.parse().ok()?;
    let m: u32 = parts.next()?.parse().ok()?;
    let d: u32 = parts.next()?.parse().ok()?;
    if parts.next().is_some() {
        return None;
    }
    if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
        return None;
    }
    Some(days_from_civil(y, m, d))
}

/// Parse an ISO-8601 remote timestamp into epoch seconds. Accepts
/// `YYYY-MM-DDTHH:MM:SS` (the `T` may be a space) with optional fractional
/// seconds and a `Z` or `±HH:MM` zone.
#[must_use]
pub fn iso_to_epoch_secs(input: &str) -> Option<i64> {
    let (date, time) = input.trim().split_once(['T', ' '])?;
    let days = date_to_epoch_days(date)?;
    let (time, zone) = split_zone(time);
    let mut hms = time.split(':');
    let hh: i64 = hms.next()?.parse().ok()?;
    let mm: i64 = hms.next()?.parse().ok()?;
    let ss_part = hms.next()?;
    let whole: i64 = ss_part.split('.').next()?.parse().ok()?;
    if !(0..=23).contains(&hh) || !(0..=59).contains(&mm) || !(0..=59).contains(&whole) {
        return None;
    }
    let mut secs = days * 86_400 + hh * 3600 + mm * 60 + whole;
    if let Some((zh, zm)) = zone {
        secs -= zh * 3600 + zm * 60;
    }
    Some(secs)
}

/// Split `HH:MM:SS[.frac][zone]` into the bare time and an optional
/// `(hours, minutes)` zone offset (already sign-adjusted).
fn split_zone(time: &str) -> (&str, Option<(i64, i64)>) {
    if time.ends_with('Z') || time.ends_with('z') {
        return (&time[..time.len() - 1], Some((0, 0)));
    }
    match time.rfind(['+', '-']) {
        Some(i) if i > 0 => {
            let (bare, zone) = time.split_at(i);
            let sign = if zone.starts_with('-') { -1i64 } else { 1i64 };
            let digits = &zone[1..];
            let (zh, zm) = if let Some((h, m)) = digits.split_once(':') {
                (h.parse::<i64>().ok(), m.parse::<i64>().ok())
            } else if digits.len() == 2 {
                (digits.parse::<i64>().ok(), Some(0))
            } else if digits.len() >= 3 {
                let (h, m) = digits.split_at(digits.len() - 2);
                (h.parse::<i64>().ok(), m.parse::<i64>().ok())
            } else {
                (None, None)
            };
            match (zh, zm) {
                (Some(zh), Some(zm)) => (bare, Some((sign * zh, sign * zm))),
                _ => (bare, None),
            }
        }
        Some(_) | None => (time, None),
    }
}

/// The conflict rule: the remote wins when its `updated_at` is strictly later
/// than the local issue's `updated` (a `YYYY-MM-DD` interpreted as end of
/// day). A remote timestamp that cannot be parsed counts as *not newer*, so
/// the local issue is kept.
#[must_use]
pub fn is_remote_newer(remote_updated_at: &str, local_updated: &str) -> bool {
    let Some(remote) = iso_to_epoch_secs(remote_updated_at) else {
        return false;
    };
    let local_end_of_day = date_to_epoch_days(local_updated).map_or(0, |d| d * 86_400 + 86_399);
    remote > local_end_of_day
}

/// Redact a resolved secret from text flowing through error/report surfaces.
#[must_use]
pub fn scrub_secret(text: &str, secret: &str) -> String {
    if secret.is_empty() {
        return text.to_string();
    }
    text.replace(secret, "<token>")
}

/// The contract's missing-binary wording (`contracts/external-tools.md`):
/// exit code 3 with `required tool not found: <tool> — install from <source>`.
fn not_found_message(program: &str) -> String {
    match program {
        "glab" => "required tool not found: glab — install from https://gitlab.com/gitlab-org/cli"
            .to_string(),
        _ => format!("required tool not found: {program} — install it and retry"),
    }
}

/// `tix export`: mirror local issues to the remote tracker, recording the
/// remote id back into the local `gitlab_id`/`linear_id` so a re-run updates
/// instead of creating duplicates (idempotency, FR-Remote-sync).
///
/// Returns the number of issues handled (created or updated — `close` on an
/// updated GitLab done issue is not counted separately).
pub fn export(
    store: &Store,
    tool: Tool,
    config: &Config,
    dry_run: bool,
    out: &mut dyn Write,
) -> Result<usize> {
    let mut adapter = adapter_for(store, tool, config)?;

    if dry_run {
        for issue in store.list()? {
            match remote_ref(tool, &issue) {
                Some(r) => {
                    writeln!(out, "would update {tool} issue {r} \"{}\"", issue.title)?;
                }
                None => {
                    writeln!(out, "would create {tool} issue \"{}\"", issue.title)?;
                }
            }
        }
        writeln!(out, "dry run — {tool} CLI was not invoked")?;
        return Ok(store.list()?.len());
    }

    let mut handled = 0;
    for mut issue in store.list()? {
        let remote_status = local_to_remote_status(tool, issue.status.display(), config);
        let labels: Vec<String> = issue.labels.clone();
        let assignee = issue.assignee.as_deref();
        let priority = issue.priority.to_string();
        match remote_ref(tool, &issue) {
            Some(r) => {
                let r = r.to_string();
                adapter.update_issue(
                    &r,
                    &issue.title,
                    &issue.body,
                    &labels,
                    assignee,
                    Some(&priority),
                    &remote_status,
                )?;
                if !adapter.done_via_status() && remote_status_is_done(&remote_status) {
                    adapter.mark_done(&r)?;
                }
                writeln!(out, "updated {tool} issue {r} \"{}\"", issue.title)?;
            }
            None => {
                let id = adapter.create_issue(
                    &issue.title,
                    &issue.body,
                    &labels,
                    assignee,
                    Some(&priority),
                    &remote_status,
                )?;
                if !adapter.done_via_status() && remote_status_is_done(&remote_status) {
                    adapter.mark_done(&id)?;
                }
                match tool {
                    Tool::GitLab => issue.gitlab_id = Some(id.clone()),
                    Tool::Linear => issue.linear_id = Some(id.clone()),
                }
                store.update(&issue.filename, &issue)?;
                writeln!(
                    out,
                    "created {tool} issue {id} \"{}\" (remote id recorded)",
                    issue.title
                )?;
            }
        }
        handled += 1;
    }
    writeln!(out, "exported {handled} issue(s) to {tool}")?;
    Ok(handled)
}

/// `tix import`: pull open remote issues into local files.
///
/// Conflict resolution: a remote issue that already tracks a local one skips
/// the local file when the local `updated` is later or equal; when the remote
/// `updated_at` is newer the local file is overwritten (fields + body, keeping
/// `created`), with the previous file first copied to `<filename>.bak`.
///
/// Returns the number of local files created or overwritten.
pub fn import(store: &Store, tool: Tool, config: &Config, out: &mut dyn Write) -> Result<usize> {
    let mut adapter = adapter_for(store, tool, config)?;
    let remote_issues = adapter.list_open()?;
    let mut handled = 0;
    for remote in remote_issues {
        let tracked = store
            .list()?
            .into_iter()
            .find(|i| remote_ref(tool, i) == Some(remote.id.as_str()));
        match tracked {
            None => {
                let mut issue = Issue {
                    number: 0,
                    title: remote.title.clone(),
                    status: Status::new(remote_to_local_status(tool, &remote.state, config)),
                    labels: remote.labels.clone(),
                    priority: crate::model::Priority::Medium,
                    assignee: remote.assignee.clone(),
                    estimate: None,
                    commit: None,
                    gitlab_id: None,
                    linear_id: None,
                    mission: None,
                    task: None,
                    links: vec![],
                    files: vec![],
                    created: crate::model::today(),
                    updated: crate::model::today(),
                    filename: String::new(),
                    body: String::new(),
                };
                match tool {
                    Tool::GitLab => issue.gitlab_id = Some(remote.id.clone()),
                    Tool::Linear => issue.linear_id = Some(remote.id.clone()),
                }
                let path = store.create(&mut issue, &remote.description, None)?;
                let name = path
                    .file_name()
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_default();
                writeln!(
                    out,
                    "imported {tool} issue {} \"{}\" as #{} ({}) [{name}]",
                    remote.id, remote.title, issue.number, issue.status
                )?;
                handled += 1;
            }
            Some(local) => {
                if is_remote_newer(remote.updated_at.as_deref().unwrap_or(""), &local.updated) {
                    let backup = format!("{}.bak", local.filename);
                    std::fs::copy(
                        store.issues_dir.join(&local.filename),
                        store.issues_dir.join(&backup),
                    )?;
                    let mut overwritten = local;
                    let keep_created = overwritten.created.clone();
                    overwritten.title = remote.title.clone();
                    overwritten.body = remote.description.clone();
                    overwritten.labels = remote.labels.clone();
                    overwritten.status =
                        Status::new(remote_to_local_status(tool, &remote.state, config));
                    if let Some(a) = &remote.assignee {
                        overwritten.assignee = Some(a.clone());
                    }
                    overwritten.created = keep_created;
                    overwritten.bump_updated();
                    let filename = overwritten.filename.clone();
                    store.update(&filename, &overwritten)?;
                    writeln!(
                        out,
                        "overwrote {tool} issue {} \"{}\" (remote newer; backup at {backup})",
                        remote.id, overwritten.title
                    )?;
                    handled += 1;
                } else {
                    writeln!(
                        out,
                        "kept {tool} issue {} \"{}\" (local updated later or equal)",
                        remote.id, remote.title
                    )?;
                }
            }
        }
    }
    writeln!(out, "imported {handled} {tool} issue(s)")?;
    Ok(handled)
}

/// Whether the computed remote status conveys "done".
pub fn remote_status_is_done(status: &str) -> bool {
    status == "closed" || status == "Done"
}

fn remote_ref(tool: Tool, issue: &Issue) -> Option<&str> {
    match tool {
        Tool::GitLab => issue.gitlab_id.as_deref(),
        Tool::Linear => issue.linear_id.as_deref(),
    }
}

/// Build and configure the adapter for `tool`: resolves the token with env
/// precedence, validates the `[export]` target section, and returns the
/// tool-specific adapter wired to a [`ProcessRunner`].
fn adapter_for(store: &Store, tool: Tool, config: &Config) -> Result<Box<dyn TrackerAdapter>> {
    let _ = store;
    // The contract's warning starts with "warning:" — no `tix:` prefix.
    let mut warn = |w: &str| eprintln!("{w}");
    let resolution = token::resolve(tool, config, &token::RealEnv, &mut warn);
    let secret = resolution.secret().map(str::to_string);
    match tool {
        Tool::GitLab => {
            let rc = config.export.gitlab.as_ref().ok_or_else(|| {
                TixError::Config("no `[export.gitlab]` section in tix.toml — run `tix init --with gitlab` or edit tix.toml".to_string())
            })?;
            let project = rc.project.clone().ok_or_else(|| {
                TixError::Config("`[export.gitlab].project` is not set — add `project = \"acme/tix\"` to tix.toml".to_string())
            })?;
            Ok(Box::new(glab::GitLabAdapter::new(
                ProcessRunner,
                secret,
                rc.base_url.clone(),
                project,
            )))
        }
        Tool::Linear => {
            let rc = config.export.linear.as_ref().ok_or_else(|| {
                TixError::Config("no `[export.linear]` section in tix.toml — run `tix init --with linear` or edit tix.toml".to_string())
            })?;
            let team = rc.team.clone().ok_or_else(|| {
                TixError::Config(
                    "`[export.linear].team` is not set — add `team = \"Eng\"` to tix.toml"
                        .to_string(),
                )
            })?;
            Ok(Box::new(linear::LinearAdapter::new(
                ProcessRunner,
                secret,
                team,
            )))
        }
    }
}

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

    #[test]
    fn target_parsing_accepts_only_the_two_contract_targets() {
        assert_eq!(Tool::from_target("gitlab").unwrap(), Tool::GitLab);
        assert_eq!(Tool::from_target("linear").unwrap(), Tool::Linear);
        assert!(Tool::from_target("github").is_err());
        assert_eq!(Tool::GitLab.token_var(), "GITLAB_TOKEN");
        assert_eq!(Tool::Linear.token_var(), "LINEAR_TOKEN");
        assert_eq!(Tool::GitLab.binary(), "glab");
        assert_eq!(Tool::Linear.binary(), "linear-cli");
    }

    #[test]
    fn gitlab_status_mapping() {
        let config = Config::default();
        assert_eq!(
            local_to_remote_status(Tool::GitLab, "todo", &config),
            "opened"
        );
        assert_eq!(
            local_to_remote_status(Tool::GitLab, "done", &config),
            "closed"
        );
        assert_eq!(
            remote_to_local_status(Tool::GitLab, "opened", &config),
            "todo"
        );
        assert_eq!(
            remote_to_local_status(Tool::GitLab, "closed", &config),
            "done"
        );
        assert_eq!(
            remote_to_local_status(Tool::GitLab, "anything-else", &config),
            "todo"
        );
    }

    #[test]
    fn linear_status_mapping() {
        let config = Config::default();
        assert_eq!(
            local_to_remote_status(Tool::Linear, "todo", &config),
            "todo"
        );
        assert_eq!(
            local_to_remote_status(Tool::Linear, "in review", &config),
            "todo"
        );
        assert_eq!(
            local_to_remote_status(Tool::Linear, "done", &config),
            "Done"
        );
        assert_eq!(
            remote_to_local_status(Tool::Linear, "In Progress", &config),
            "in progress"
        );
        assert_eq!(
            remote_to_local_status(Tool::Linear, "Done", &config),
            "done"
        );
        assert_eq!(
            remote_to_local_status(Tool::Linear, "Unknown", &config),
            "todo"
        );
    }

    #[test]
    fn days_from_civil_roundtrips_civil_from_days() {
        // spot-check independent epoch anchors (known values)
        assert_eq!(days_from_civil(1970, 1, 1), 0);
        assert_eq!(days_from_civil(2000, 1, 1), 10957);
        assert_eq!(days_from_civil(1970, 1, 2), 1);
        assert_eq!(days_from_civil(2026, 5, 11), 20584);
    }

    #[test]
    fn date_to_epoch_days_parses_only_yyyymmdd() {
        assert_eq!(date_to_epoch_days("1970-01-01"), Some(0));
        assert_eq!(date_to_epoch_days("2026-05-11"), Some(20_584));
        assert_eq!(date_to_epoch_days("not-a-date"), None);
        assert_eq!(date_to_epoch_days("2026-13-01"), None);
        assert_eq!(date_to_epoch_days("2026-05-11T10:00:00"), None);
    }

    #[test]
    fn iso_to_epoch_secs_accepts_contract_timestamp_shapes() {
        let day = days_from_civil(2026, 5, 11) * 86_400;
        assert_eq!(iso_to_epoch_secs("2026-05-11T00:00:00Z"), Some(day));
        assert_eq!(iso_to_epoch_secs("2026-05-11 00:00:00"), Some(day));
        assert_eq!(iso_to_epoch_secs("2026-05-11T00:00:00.123Z"), Some(day));
        assert_eq!(
            iso_to_epoch_secs("2026-05-11T00:00:00+02:00"),
            Some(day - 7200)
        );
        assert_eq!(
            iso_to_epoch_secs("2026-05-11T00:00:00-05:30"),
            Some(day + 19_800)
        );
        assert_eq!(
            iso_to_epoch_secs("2026-05-11T10:30:00Z"),
            Some(day + 37_800)
        );
        assert_eq!(iso_to_epoch_secs("garbage"), None);
    }

    #[test]
    fn remote_newer_wins_only_when_strictly_after_local_end_of_day() {
        // local `updated` = 2026-05-11 is interpreted as end of day.
        assert!(is_remote_newer("2026-05-12T00:00:00Z", "2026-05-11"));
        assert!(!is_remote_newer("2026-05-11 13:00:00", "2026-05-11"));
        assert!(!is_remote_newer("2026-05-11T23:59:59Z", "2026-05-11"));
        assert!(!is_remote_newer("2026-05-10T23:59:59Z", "2026-05-11"));
        // unparseable remote timestamp keeps the local issue
        assert!(!is_remote_newer("not-a-time", "2026-05-11"));
    }

    #[test]
    fn scrub_replaces_secret_everywhere_and_preserves_text() {
        assert_eq!(
            scrub_secret("token=sekrit end", "sekrit"),
            "token=<token> end"
        );
        assert_eq!(
            scrub_secret("token=sekrit token=sekrit", "sekrit"),
            "token=<token> token=<token>"
        );
        assert_eq!(scrub_secret("no secret here", "sekrit"), "no secret here");
        assert_eq!(scrub_secret("empty secret", ""), "empty secret");
    }

    #[test]
    fn remote_status_is_done_matches_both_tools() {
        assert!(remote_status_is_done("closed"));
        assert!(remote_status_is_done("Done"));
        assert!(!remote_status_is_done("opened"));
        assert!(!remote_status_is_done("In Progress"));
    }
}