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
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
//! Linear adapter: shells out to the canonical `linear-cli` CLI
//! (nesszer/linear-cli, the `cargo:linear-cli` crate pinned in `mise.toml`).
//!
//! The grammar is the real **0.3.28** surface, checked against the installed
//! binary on 2026-10-09. Four argv shapes parse — they fail only with
//! `No workspace selected` (exit 1, because no workspace is configured here):
//! `issues create -t=ENG -d=D -p=2 -s=Todo -o json -- "T"`,
//! `issues update -T=T -d=D -s=Done -- ENG-1`,
//! `issues list -t=ENG -o json`, and
//! `relations add -r blocks ENG-1 ENG-2`; two clap errors confirm the shape —
//! `linear-cli issue create "T"` (exit 2, `unrecognized subcommand 'issue'`)
//! and `linear-cli issues create --title T` (exit 2,
//! `unexpected argument '--title'`). The plural `issues` is the subcommand; the
//! title is **positional** on create; the workflow flag is `--state`, not
//! `--status`. The **API path is unverified**: no workspace is configured here,
//! so nothing past argument parsing was exercised.
//!
//! ## Values are attached; positionals follow `--`
//!
//! Every user-controlled option value is attached with `=` (`-d=<body>`,
//! `-T=<title>`, `-l=<label>`, `-s=<state>`, `-t=<team>`, `-p=<n>`) and the
//! positional title/id follows the flags behind `--`. This is not cosmetic: tix
//! bodies are markdown, and a body whose first line is `- item` — or a title
//! starting with `-` — is rejected by clap when it is a separate argv element
//! (`error: unexpected argument '- ' found`, exit 2). Separating them would abort
//! an export mid-run on ordinary data.
//!
//! ## The import reads two payloads
//!
//! `issues list` enumerates with only `id, identifier, title, priority,
//! state{name}, assignee{name}, project{name}` — no body, labels, or timestamp —
//! so an import is **one `issues list` call plus one `issues get <ID>` per open
//! issue**, the latter returning the full issue object (`description`,
//! `updatedAt`, `labels.nodes`, `parent`, `project`, …). The two shapes are
//! modelled separately, exactly as the verbs carry them.
//!
//! The tool reads **`LINEAR_API_KEY`** (its own help shows
//! `printf '%s\n' "$LINEAR_API_KEY" | linear config set-key`); it does not read
//! `LINEAR_TOKEN`, so that is what [`LinearAdapter::child_env`] injects.
//!
//! Linear conveys workflow stage through `-s <state>` (done → `Done`, otherwise
//! the first work column), so this adapter sets `done_via_status` and never
//! issues a separate close.

use serde::Deserialize;

use crate::error::{Result, TixError};
use crate::sync::{CommandOutcome, CommandRunner, RemoteIssue, Tool, TrackerAdapter, scrub_secret};

/// The `linear-cli` adapter. Spawns `linear-cli issues <list|get|create|update>`
/// with the configured team and, when a secret is configured, the
/// `LINEAR_API_KEY` env pair.
pub struct LinearAdapter {
    runner: Box<dyn CommandRunner>,
    token: Option<String>,
    team: String,
}

impl LinearAdapter {
    pub fn new(runner: impl CommandRunner + 'static, token: Option<String>, team: String) -> Self {
        LinearAdapter {
            runner: Box::new(runner),
            token,
            team,
        }
    }

    fn child_env(&self) -> Vec<(String, String)> {
        match &self.token {
            Some(token) => vec![("LINEAR_API_KEY".to_string(), token.clone())],
            None => Vec::new(),
        }
    }

    fn run(&self, args: &[String]) -> Result<CommandOutcome> {
        self.runner
            .run(Tool::Linear.binary(), args, &self.child_env())
    }

    fn external(&self, context: &str, outcome: &CommandOutcome) -> TixError {
        let mut message = format!("{context}: {}", outcome.text().trim());
        if let Some(secret) = &self.token {
            message = scrub_secret(&message, secret);
        }
        TixError::External(message)
    }

    /// Parse `linear-cli issues create` stdout for the `identifier`.
    fn parse_identifier(&self, outcome: &CommandOutcome) -> Result<String> {
        serde_json::from_str::<serde_json::Value>(&outcome.stdout)
            .ok()
            .and_then(|value| {
                value
                    .get("identifier")
                    .and_then(serde_json::Value::as_str)
                    .map(str::to_string)
            })
            .ok_or_else(|| {
                TixError::External(format!(
                    "`linear-cli issues create` did not return JSON with an `identifier` field (expected {{\"identifier\":…}}): {}",
                    scrub_secret(outcome.stdout.trim(), self.token.as_deref().unwrap_or(""))
                ))
            })
    }

    /// Fetch one issue's **detail** payload (`issues get <ID> -o json`).
    fn fetch_issue(&self, identifier: &str) -> Result<RemoteIssue> {
        let args: Vec<String> = vec![
            "issues".into(),
            "get".into(),
            "-o".into(),
            "json".into(),
            identifier.to_string(),
        ];
        let outcome = self.run(&args)?;
        if !outcome.success {
            return Err(self.external("`linear-cli issues get` failed", &outcome));
        }
        let detail: LinearDetailIssue = serde_json::from_str(&outcome.stdout).map_err(|e| {
            TixError::External(format!(
                "`linear-cli issues get` did not return a JSON object: {e}\n{}",
                scrub_secret(&outcome.stdout, self.token.as_deref().unwrap_or(""))
            ))
        })?;
        Ok(RemoteIssue::from(detail))
    }
}

impl TrackerAdapter for LinearAdapter {
    fn tool(&self) -> Tool {
        Tool::Linear
    }

    fn create_issue(
        &mut self,
        title: &str,
        body: &str,
        labels: &[String],
        _assignee: Option<&str>,
        priority: Option<&str>,
        status: &str,
    ) -> Result<String> {
        let mut args: Vec<String> = vec![
            "issues".into(),
            "create".into(),
            format!("-t={}", self.team),
            format!("-d={body}"),
        ];
        for label in labels {
            args.push(format!("-l={label}"));
        }
        if let Some(p) = priority.and_then(linear_priority) {
            args.push(format!("-p={p}"));
        }
        args.push(format!("-s={status}"));
        args.push("-o".into());
        args.push("json".into());
        // `--` so a title starting with `-` is a positional, not a flag.
        args.push("--".into());
        args.push(title.to_string());
        let outcome = self.run(&args)?;
        if !outcome.success {
            return Err(self.external("`linear-cli issues create` failed", &outcome));
        }
        self.parse_identifier(&outcome)
    }

    fn update_issue(
        &mut self,
        remote_ref: &str,
        title: &str,
        body: &str,
        labels: &[String],
        _assignee: Option<&str>,
        priority: Option<&str>,
        status: &str,
    ) -> Result<()> {
        let mut args: Vec<String> = vec![
            "issues".into(),
            "update".into(),
            format!("-T={title}"),
            format!("-d={body}"),
        ];
        for label in labels {
            args.push(format!("-l={label}"));
        }
        if let Some(p) = priority.and_then(linear_priority) {
            args.push(format!("-p={p}"));
        }
        args.push(format!("-s={status}"));
        // `--` so an id/ref starting with `-` is a positional, not a flag.
        args.push("--".into());
        args.push(remote_ref.to_string());
        let outcome = self.run(&args)?;
        if !outcome.success {
            return Err(self.external("`linear-cli issues update` failed", &outcome));
        }
        Ok(())
    }

    /// Linear conveys done via `-s Done`; there is no close command.
    fn mark_done(&mut self, _remote_ref: &str) -> Result<()> {
        Ok(())
    }

    /// Enumerate open issues with `issues list`, then fetch each one's detail.
    ///
    /// The list payload carries only `id, identifier, title, priority,
    /// state{name}, assignee{name}, project{name}` — never a body, labels, or
    /// timestamp — so the fields an import needs come from a per-issue
    /// `issues get`. Cost: **one list call plus one get per open issue**.
    fn list_open(&mut self) -> Result<Vec<RemoteIssue>> {
        let args: Vec<String> = vec![
            "issues".into(),
            "list".into(),
            format!("-t={}", self.team),
            "-o".into(),
            "json".into(),
        ];
        let outcome = self.run(&args)?;
        if !outcome.success {
            return Err(self.external("`linear-cli issues list` failed", &outcome));
        }
        let listed: Vec<LinearListIssue> = serde_json::from_str(&outcome.stdout).map_err(|e| {
            TixError::External(format!(
                "`linear-cli issues list` did not return a JSON array: {e}\n{}",
                scrub_secret(&outcome.stdout, self.token.as_deref().unwrap_or(""))
            ))
        })?;
        let mut issues = Vec::new();
        for item in listed {
            if item.state_name() == "Done" {
                continue;
            }
            issues.push(self.fetch_issue(&item.identifier)?);
        }
        Ok(issues)
    }

    fn done_via_status(&self) -> bool {
        true
    }

    /// Linear's `relations add`, the relation affordance the 0.3.28 CLI exposes.
    ///
    /// One call per relation, because `relations add` is **additive and creates a
    /// single edge**: `-r <RELATION> <FROM> <TO>` with the relation kind and the
    /// two issues' **remote identifiers** (`ENG-123`); the target identifier is
    /// what [`crate::sync::map_relation_to_remote`] resolved and carried in
    /// `value`. The first failure stops the run: a partially-created relation set
    /// is worse than a loud stop, and `export` is not transactional across issues
    /// either, so a diagnostic-free partial state is exactly what a reader cannot
    /// detect.
    fn set_relations(
        &mut self,
        remote_ref: &str,
        relations: &[super::MappedRelation],
    ) -> Result<()> {
        for relation in relations {
            let super::MappedRelation::Remote { field, value } = relation else {
                continue;
            };
            let args: Vec<String> = vec![
                "relations".into(),
                "add".into(),
                "-r".into(),
                field.clone(),
                remote_ref.to_string(),
                value.clone(),
            ];
            let outcome = self.run(&args)?;
            if !outcome.success {
                return Err(self.external("`linear-cli relations add` failed", &outcome));
            }
        }
        Ok(())
    }

    /// Linear's side of the project-association seam — and its answer is "nothing"
    /// (WP08 T036).
    ///
    /// Linear's issue carries **one** `project`, so a second membership has nowhere
    /// to go: there is no list field and therefore no command line that could carry
    /// one. Sending the first association and diagnosing the rest would split one
    /// membership rule across two places and quietly drop data; C-005's answer for
    /// all of them is the diagnostic, and the local list stays whole.
    ///
    /// The `debug_assert` pins the same invariant as GitLab's: a value cannot arrive
    /// while `PROJECT_WIRE_VERIFIED` is empty, and a table flipped without an
    /// implementation here fails loudly in every test build rather than dropping an
    /// association in silence.
    fn set_projects(&mut self, _remote_ref: &str, projects: &[super::MappedProject]) -> Result<()> {
        debug_assert!(
            projects.is_empty(),
            "Linear's issue carries one `project`, so no membership list can be \
             sent: flip `PROJECT_WIRE_VERIFIED` only together with an \
             implementation here"
        );
        Ok(())
    }

    /// Linear's side of the epic-reference seam — and its answer is "nothing" (WP08,
    /// mission `epics-work-items-01M3BYW4`).
    ///
    /// Linear has no epic level at all: its issues carry one `project`, and the
    /// nearest concept above a project is an initiative. Neither `issues list` nor
    /// `issues get` returns an epic field, so there is nothing to read and no field
    /// to send.
    ///
    /// The `debug_assert` pins the same invariant as GitLab's: a value cannot arrive
    /// while `EPIC_WIRE_VERIFIED` is empty, and a table flipped without an
    /// implementation here fails loudly in every test build rather than dropping a
    /// reference in silence.
    fn set_epics(&mut self, _remote_ref: &str, epics: &[super::MappedEpic]) -> Result<()> {
        debug_assert!(
            epics.is_empty(),
            "Linear has no epic level, so no epic reference list can be sent: flip \
             `EPIC_WIRE_VERIFIED` only together with an implementation here"
        );
        Ok(())
    }
}

/// Map a local priority word to `linear-cli`'s **numeric** `-p` value, or `None`
/// when it cannot be expressed.
///
/// `linear-cli` takes a number (0 = none, 1 = urgent, 2 = high, 3 = normal,
/// 4 = low), so the words tix stores need translating: `low`→4, `medium`→3,
/// `high`→2, and the empty string (tix's "explicitly no priority") →0. Anything
/// else — a custom or unknown string — yields `None`, and the caller **omits the
/// flag** rather than coercing it. This mirrors the GitLab adapter, which ignores
/// a priority it cannot map; a wrong priority written silently is worse than none
/// written at all.
#[must_use]
fn linear_priority(priority: &str) -> Option<&'static str> {
    match priority {
        "low" => Some("4"),
        "medium" => Some("3"),
        "high" => Some("2"),
        "" => Some("0"),
        _ => None,
    }
}

/// One entry from `linear-cli issues list -o json`, which returns only
/// `id, identifier, title, priority, state{name}, assignee{name}, project{name}`.
#[derive(Debug, Deserialize)]
struct LinearListIssue {
    identifier: String,
    #[serde(default, alias = "state")]
    state: Option<LinearStatus>,
}

impl LinearListIssue {
    /// The state name, or the empty string when the payload omitted it.
    fn state_name(&self) -> &str {
        self.state.as_ref().map(LinearStatus::name).unwrap_or("")
    }
}

/// The full issue object `linear-cli issues get <ID> -o json` prints (the subset
/// this adapter reads):
/// `identifier, title, description, updatedAt, state{name}, assignee{name,email},
/// labels{nodes{name,color}}, parent{identifier,title}, project{name}`.
#[derive(Debug, Deserialize)]
struct LinearDetailIssue {
    identifier: String,
    #[serde(default)]
    title: String,
    #[serde(default)]
    description: Option<String>,
    #[serde(default, alias = "state")]
    state: Option<LinearStatus>,
    #[serde(default, alias = "updatedAt")]
    updated_at: Option<String>,
    #[serde(default)]
    assignee: Option<LinearAssignee>,
    #[serde(default)]
    labels: Option<LinearLabels>,
    /// The parent issue, reported as `{identifier, title}` (or null).
    #[serde(default)]
    parent: Option<serde_json::Value>,
    /// Linear's single `project`, reported as `{name}`.
    #[serde(default, alias = "projects")]
    project: Option<serde_json::Value>,
}

/// Linear's assignee object: `{name, email}`. Only the name is used (the local
/// field is a bare handle).
#[derive(Debug, Deserialize)]
struct LinearAssignee {
    #[serde(default)]
    name: Option<String>,
}

/// Linear's labels connection: `{nodes: [{name, color}]}`.
#[derive(Debug, Deserialize)]
struct LinearLabels {
    #[serde(default)]
    nodes: Vec<LinearLabelNode>,
}

#[derive(Debug, Deserialize)]
struct LinearLabelNode {
    #[serde(default)]
    name: String,
}

/// `state` arrives either as a plain string or as `{"name":..}`.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum LinearStatus {
    Name(String),
    Named { name: String },
}

impl LinearStatus {
    fn name(&self) -> &str {
        match self {
            LinearStatus::Name(name) | LinearStatus::Named { name } => name,
        }
    }
}

impl From<LinearDetailIssue> for RemoteIssue {
    fn from(issue: LinearDetailIssue) -> Self {
        RemoteIssue {
            id: issue.identifier,
            title: issue.title,
            description: issue.description.unwrap_or_default(),
            labels: issue
                .labels
                .map(|labels| labels.nodes.into_iter().map(|n| n.name).collect())
                .unwrap_or_default(),
            state: issue
                .state
                .as_ref()
                .map(LinearStatus::name)
                .unwrap_or("")
                .to_string(),
            updated_at: issue.updated_at,
            assignee: issue.assignee.and_then(|a| a.name),
            // Linear sends the parent as an object (`{identifier, title}`), an id
            // string, or a list of either. All are accepted so a payload shape
            // change surfaces as "no parent" rather than as a deserialisation
            // failure that aborts the whole import. The first entry is taken,
            // because tix holds one reference and the contract is single-parent.
            parent: linear_parent_id(issue.parent.as_ref()),
            projects: crate::sync::remote_projects(issue.project.as_ref()),
            // Linear has no epic level and neither verb returns an epic field, so
            // there is never an epic reference to read.
            epics: Vec::new(),
        }
    }
}

/// The first parent identifier from Linear's parent field, in any of the shapes
/// it is known to arrive in.
///
/// Pure and total: an unrecognised shape yields `None`, which the import treats
/// as "no parent reported" and reports as a diagnostic. It never panics and
/// never guesses.
fn linear_parent_id(value: Option<&serde_json::Value>) -> Option<String> {
    fn one(value: &serde_json::Value) -> Option<String> {
        match value {
            serde_json::Value::String(s) => Some(s.clone()),
            serde_json::Value::Object(map) => map
                .get("id")
                .or_else(|| map.get("identifier"))
                .and_then(|v| v.as_str())
                .map(str::to_string),
            _ => None,
        }
    }
    match value? {
        serde_json::Value::Array(items) => items.first().and_then(one),
        other => one(other),
    }
}

/// Response helpers shaped like `linear-cli issues ... -o json` output.
impl CommandOutcome {
    #[must_use]
    pub fn linear_created(identifier: &str) -> CommandOutcome {
        CommandOutcome {
            success: true,
            status: Some(0),
            stdout: format!(
                "{{\"identifier\": \"{identifier}\", \"url\": \"https://linear.app/acme/issue/{identifier}\"}}"
            ),
            stderr: String::new(),
        }
    }

    #[must_use]
    pub fn linear_list(payload: &str) -> CommandOutcome {
        CommandOutcome {
            success: true,
            status: Some(0),
            stdout: payload.to_string(),
            stderr: String::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;
    use crate::sync::MappedRelation;
    use crate::sync::glab::{FakeRunner, RecordedCall};

    fn adapter_with(runner: FakeRunner, token: Option<&str>) -> LinearAdapter {
        LinearAdapter::new(runner, token.map(String::from), "Eng".into())
    }

    fn recorded(adapter: &LinearAdapter) -> Vec<RecordedCall> {
        adapter
            .runner
            .as_any()
            .downcast_ref::<FakeRunner>()
            .expect("adapter must hold a FakeRunner")
            .take_calls()
    }

    #[test]
    fn create_attaches_values_and_puts_the_positional_title_behind_double_dash() {
        let runner = FakeRunner::new(vec![CommandOutcome::linear_created("TIX-7")]);
        let mut adapter = adapter_with(runner, Some("lin-token"));
        let id = adapter
            .create_issue("Fix", "body", &["bug".into()], None, Some("high"), "Done")
            .unwrap();
        assert_eq!(id, "TIX-7");
        let (argv, env) = &recorded(&adapter)[0];
        assert_eq!(
            argv.join(" "),
            "linear-cli issues create -t=Eng -d=body -l=bug -p=2 -s=Done -o json -- Fix"
        );
        assert_eq!(
            env,
            &[("LINEAR_API_KEY".to_string(), "lin-token".to_string())]
        );
    }

    /// A markdown body whose first line is `- item`, and a title starting with
    /// `-`, are the ordinary case this argv has to survive: attached values and
    /// the `--` terminator are what keep clap from reading them as flags.
    #[test]
    fn create_survives_a_hyphen_leading_body_and_title() {
        let runner = FakeRunner::new(vec![CommandOutcome::linear_created("TIX-7")]);
        let mut adapter = adapter_with(runner, None);
        adapter
            .create_issue(
                "-leading title",
                "- bullet one\n- bullet two",
                &["bug".into()],
                None,
                None,
                "Todo",
            )
            .unwrap();
        let argv = &recorded(&adapter)[0].0;
        assert_eq!(
            argv.join(" "),
            "linear-cli issues create -t=Eng -d=- bullet one\n- bullet two -l=bug -s=Todo -o json -- -leading title"
        );
        assert_eq!(
            argv.last().unwrap(),
            "-leading title",
            "the title is the positional"
        );
    }

    #[test]
    fn update_survives_a_hyphen_leading_title_and_body() {
        let runner = FakeRunner::new(vec![]);
        let mut adapter = adapter_with(runner, None);
        adapter
            .update_issue("TIX-7", "-tricky title", "- body", &[], None, None, "Done")
            .unwrap();
        let argv = &recorded(&adapter)[0].0;
        assert_eq!(
            argv.join(" "),
            "linear-cli issues update -T=-tricky title -d=- body -s=Done -- TIX-7"
        );
    }

    /// The injected name is the one the tool actually reads — `LINEAR_API_KEY`,
    /// not the `LINEAR_TOKEN` this adapter used to send (which never reached it).
    #[test]
    fn the_token_is_injected_under_the_name_the_tool_reads() {
        let runner = FakeRunner::new(vec![CommandOutcome::linear_created("TIX-1")]);
        let mut adapter = adapter_with(runner, Some("lin-token"));
        adapter
            .create_issue("T", "b", &[], None, None, "Todo")
            .unwrap();
        assert_eq!(
            &recorded(&adapter)[0].1,
            &[("LINEAR_API_KEY".to_string(), "lin-token".to_string())]
        );
    }

    #[test]
    fn create_without_labels_omits_label_flag() {
        let runner = FakeRunner::new(vec![CommandOutcome::linear_created("TIX-8")]);
        let mut adapter = adapter_with(runner, None);
        adapter
            .create_issue("T", "b", &[], None, None, "todo")
            .unwrap();
        let joined = recorded(&adapter)[0].0.join(" ");
        assert!(!joined.contains("-l="), "{joined}");
    }

    #[test]
    fn priority_maps_to_linear_numbers_and_unknown_is_omitted() {
        assert_eq!(linear_priority("low"), Some("4"));
        assert_eq!(linear_priority("medium"), Some("3"));
        assert_eq!(linear_priority("high"), Some("2"));
        assert_eq!(linear_priority(""), Some("0"), "the empty string is `none`");
        for unknown in ["urgent", "none", "MEDIUM", "custom-word"] {
            assert_eq!(
                linear_priority(unknown),
                None,
                "{unknown} must not be coerced to a number"
            );
        }
    }

    #[test]
    fn an_unmappable_priority_omits_the_priority_flag() {
        let runner = FakeRunner::new(vec![CommandOutcome::linear_created("TIX-9")]);
        let mut adapter = adapter_with(runner, None);
        adapter
            .create_issue("T", "b", &[], None, Some("urgent"), "Todo")
            .unwrap();
        let joined = recorded(&adapter)[0].0.join(" ");
        assert!(
            !joined.contains("-p="),
            "unknown priority must be omitted: {joined}"
        );
    }

    #[test]
    fn update_passes_identifier_title_body_labels_priority_and_state() {
        let runner = FakeRunner::new(vec![]);
        let mut adapter = adapter_with(runner, None);
        adapter
            .update_issue(
                "TIX-7",
                "New title",
                "new body",
                &["bug".into()],
                None,
                Some("low"),
                "Done",
            )
            .unwrap();
        let joined = recorded(&adapter)[0].0.join(" ");
        assert_eq!(
            joined,
            "linear-cli issues update -T=New title -d=new body -l=bug -p=4 -s=Done -- TIX-7"
        );
    }

    #[test]
    fn done_via_status_is_true_and_mark_done_is_a_noop() {
        let runner = FakeRunner::new(vec![]);
        let mut adapter = adapter_with(runner, None);
        assert!(adapter.done_via_status());
        adapter.mark_done("TIX-7").unwrap();
        assert!(recorded(&adapter).is_empty(), "no close call for linear");
    }

    #[test]
    fn set_relations_adds_one_edge_per_relation_with_remote_identifiers() {
        let runner = FakeRunner::new(vec![
            CommandOutcome::linear_list(""),
            CommandOutcome::linear_list(""),
        ]);
        let mut adapter = adapter_with(runner, None);
        adapter
            .set_relations(
                "TIX-1",
                &[
                    MappedRelation::Remote {
                        field: "blocks".into(),
                        value: "TIX-2".into(),
                    },
                    MappedRelation::Remote {
                        field: "blocks".into(),
                        value: "TIX-3".into(),
                    },
                ],
            )
            .unwrap();
        let calls = recorded(&adapter);
        assert_eq!(
            calls[0].0.join(" "),
            "linear-cli relations add -r blocks TIX-1 TIX-2"
        );
        assert_eq!(
            calls[1].0.join(" "),
            "linear-cli relations add -r blocks TIX-1 TIX-3"
        );
    }

    /// The list payload carries only the enumeration fields; each open issue's
    /// body/labels/timestamp come from a per-issue `issues get`. A `Done` issue is
    /// filtered from the list and never fetched.
    #[test]
    fn list_open_enumerates_then_fetches_each_open_issues_detail() {
        let list = r#"[
          {"id":"u1","identifier":"TIX-1","title":"T1","priority":3,"state":{"name":"In Progress"}},
          {"id":"u2","identifier":"TIX-2","title":"T2","state":{"name":"Done"}}
        ]"#;
        let detail = r##"{"id":"u1","identifier":"TIX-1","title":"T1","description":"full body",
          "updatedAt":"2026-05-11T10:00:00Z","state":{"name":"In Progress"},
          "assignee":{"name":"Al","email":"al@example.com"},
          "labels":{"nodes":[{"name":"bug","color":"#f00"},{"name":"api","color":"#0f0"}]}}"##;
        // FakeRunner pops a response per call, from the back: the list call is the
        // last element pushed, so it is popped first.
        let runner = FakeRunner::new(vec![
            CommandOutcome::linear_list(detail),
            CommandOutcome::linear_list(list),
        ]);
        let mut adapter = adapter_with(runner, None);
        let issues = adapter.list_open().unwrap();
        assert_eq!(issues.len(), 1, "the Done issue is filtered before the get");
        assert_eq!(issues[0].id, "TIX-1");
        assert_eq!(issues[0].title, "T1");
        assert_eq!(issues[0].description, "full body");
        assert_eq!(issues[0].labels, ["bug", "api"]);
        assert_eq!(issues[0].state, "In Progress");
        assert_eq!(issues[0].assignee.as_deref(), Some("Al"));
        assert_eq!(
            issues[0].updated_at.as_deref(),
            Some("2026-05-11T10:00:00Z")
        );
        let calls = recorded(&adapter);
        assert_eq!(
            calls.len(),
            2,
            "one list call and one get — never a get for the Done issue"
        );
        assert_eq!(
            calls[0].0.join(" "),
            "linear-cli issues list -t=Eng -o json"
        );
        assert_eq!(calls[1].0.join(" "), "linear-cli issues get -o json TIX-1");
    }

    /// A real list payload has no body/labels/timestamp, so nothing on the list
    /// side may pretend to read them.
    #[test]
    fn a_list_payload_without_detail_fields_does_not_fail_the_import() {
        let list = r#"[{"id":"u1","identifier":"TIX-1","title":"T1","state":{"name":"Todo"}}]"#;
        let detail = r#"{"identifier":"TIX-1","title":"T1","state":{"name":"Todo"}}"#;
        let runner = FakeRunner::new(vec![
            CommandOutcome::linear_list(detail),
            CommandOutcome::linear_list(list),
        ]);
        let mut adapter = adapter_with(runner, None);
        let issues = adapter.list_open().unwrap();
        assert_eq!(issues.len(), 1);
        assert_eq!(issues[0].description, "");
        assert_eq!(issues[0].labels, [] as [std::string::String; 0]);
        assert_eq!(issues[0].updated_at, None);
    }

    #[test]
    fn create_json_without_identifier_is_a_parse_error() {
        let runner = FakeRunner::new(vec![CommandOutcome::linear_list("{}")]);
        let mut adapter = adapter_with(runner, None);
        let err = adapter
            .create_issue("T", "b", &[], None, None, "todo")
            .unwrap_err();
        assert!(matches!(err, TixError::External(_)));
        assert!(err.to_string().contains("identifier"));
        assert!(
            err.to_string().contains("linear-cli issues create"),
            "the error must name the real subcommand: {err}"
        );
    }

    #[test]
    fn a_detail_without_the_identifier_is_a_parse_error() {
        let list = r#"[{"identifier":"TIX-1","title":"T1","state":{"name":"Todo"}}]"#;
        let runner = FakeRunner::new(vec![
            CommandOutcome::linear_list("{}"),
            CommandOutcome::linear_list(list),
        ]);
        let mut adapter = adapter_with(runner, None);
        let err = adapter.list_open().unwrap_err();
        assert!(matches!(err, TixError::External(_)));
        assert!(
            err.to_string().contains("linear-cli issues get"),
            "the error names the failing verb: {err}"
        );
    }

    #[test]
    fn failure_message_scrubs_token_from_tool_output() {
        let runner = FakeRunner::new(vec![CommandOutcome {
            success: false,
            status: Some(1),
            stdout: String::new(),
            stderr: "LINEAR_API_KEY=lin-token leaked".into(),
        }]);
        let mut adapter = adapter_with(runner, Some("lin-token"));
        let err = adapter
            .create_issue("T", "b", &[], None, None, "todo")
            .unwrap_err();
        let text = err.to_string();
        assert!(text.contains("<token>"), "expected redaction, got: {text}");
        assert!(!text.contains("lin-token"), "secret leaked: {text}");
    }

    /// WP08 T036: Linear's single `project` is read from the **detail** payload,
    /// and nothing is sent for it, because Linear's issue carries one project and
    /// no list.
    #[test]
    fn t036_project_reference_is_read_from_detail_and_never_sent() {
        let list = r#"[{"identifier":"TIX-1","title":"T","state":{"name":"Todo"}}]"#;
        let detail = r#"{"identifier":"TIX-1","title":"T","state":{"name":"Todo"},
          "project":{"name":"One"}}"#;
        let runner = FakeRunner::new(vec![
            CommandOutcome::linear_list(detail),
            CommandOutcome::linear_list(list),
        ]);
        let mut adapter = adapter_with(runner, None);
        let issues = adapter.list_open().unwrap();
        assert_eq!(
            issues[0].projects,
            vec![crate::sync::RemoteProject {
                id: String::new(),
                name: Some("One".into()),
            }],
            "the real query selects `project{{name}}`, so the id is empty and the name kept"
        );

        let calls_before = recorded(&adapter).len();
        adapter.set_projects("TIX-1", &[]).unwrap();
        assert_eq!(
            recorded(&adapter).len(),
            calls_before,
            "an empty membership set must not spawn any command"
        );
    }

    /// WP08 T038: Linear has no epic level, and neither verb returns an epic
    /// field, so a payload key this adapter does not model yields no reference —
    /// and nothing is ever sent for it.
    #[test]
    fn t038_no_epic_reference_is_read_or_sent() {
        let list = r#"[{"identifier":"TIX-1","title":"T","state":{"name":"Todo"}}]"#;
        // An unmodelled key is ignored, never mistaken for an epic list.
        let detail = r#"{"identifier":"TIX-1","title":"T","state":{"name":"Todo"},
          "epics":["e-1"]}"#;
        let runner = FakeRunner::new(vec![
            CommandOutcome::linear_list(detail),
            CommandOutcome::linear_list(list),
        ]);
        let mut adapter = adapter_with(runner, None);
        let issues = adapter.list_open().unwrap();
        assert_eq!(issues[0].epics, [] as [crate::sync::RemoteEpic; 0]);

        let calls_before = recorded(&adapter).len();
        adapter.set_epics("TIX-1", &[]).unwrap();
        assert_eq!(
            recorded(&adapter).len(),
            calls_before,
            "an empty reference set must not spawn any command"
        );
    }
}