tix-tracker 0.6.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
//! Linear adapter: shells out to the `linear-cli` CLI under
//! `contracts/external-tools.md` (Linear row).
//!
//! Linear conveys workflow stage through the `--status` flag (done → `Done`,
//! otherwise the first work column), so this adapter sets `done_via_status`
//! and never issues a separate close. Create/list use `--output json` to
//! recover the `identifier` / list payload.

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 issue <create|update|list>`
/// with the configured team and, when a secret is configured, the
/// `LINEAR_TOKEN` 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_TOKEN".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 issue 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 issue create` did not return JSON with an `identifier` field (expected {{\"identifier\":…}}): {}",
                    scrub_secret(outcome.stdout.trim(), self.token.as_deref().unwrap_or(""))
                ))
            })
    }
}

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![
            "issue".into(),
            "create".into(),
            "--team".into(),
            self.team.clone(),
            "--title".into(),
            title.to_string(),
            "--description".into(),
            body.to_string(),
        ];
        if !labels.is_empty() {
            args.push("--label".to_string());
            args.push(labels.join(","));
        }
        if let Some(p) = priority {
            args.push("--priority".to_string());
            args.push(p.to_string());
        }
        args.push("--status".to_string());
        args.push(status.to_string());
        args.push("--output".to_string());
        args.push("json".to_string());
        let outcome = self.run(&args)?;
        if !outcome.success {
            return Err(self.external("`linear-cli issue 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![
            "issue".into(),
            "update".into(),
            remote_ref.to_string(),
            "--title".into(),
            title.to_string(),
            "--description".into(),
            body.to_string(),
        ];
        args.push("--status".to_string());
        args.push(status.to_string());
        let outcome = self.run(&args)?;
        if !outcome.success {
            return Err(self.external("`linear-cli issue update` failed", &outcome));
        }
        Ok(())
    }

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

    fn list_open(&mut self) -> Result<Vec<RemoteIssue>> {
        let args: Vec<String> = vec![
            "issue".into(),
            "list".into(),
            "--team".into(),
            self.team.clone(),
            "--output".into(),
            "json".into(),
        ];
        let outcome = self.run(&args)?;
        if !outcome.success {
            return Err(self.external("`linear-cli issue list` failed", &outcome));
        }
        let issues: Vec<LinearIssue> = serde_json::from_str(&outcome.stdout).map_err(|e| {
            TixError::External(format!(
                "`linear-cli issue list` did not return a JSON array: {e}\n{}",
                scrub_secret(&outcome.stdout, self.token.as_deref().unwrap_or(""))
            ))
        })?;
        Ok(issues
            .into_iter()
            .map(RemoteIssue::from)
            .filter(|i| i.state != "Done")
            .collect())
    }

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

    /// Linear's `relations.create`, the one relation affordance its CLI exposes
    /// (WP07 T031) — same seam, same signature, different verb.
    ///
    /// One call per relation, because `relations.create` creates a single relation.
    /// 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 { value, .. } = relation else {
                continue;
            };
            let args: Vec<String> = vec![
                "relation".into(),
                "create".into(),
                "--issue".into(),
                remote_ref.to_string(),
                "--type".into(),
                value.clone(),
            ];
            let outcome = self.run(&args)?;
            if !outcome.success {
                return Err(self.external("`linear-cli relation create` failed", &outcome));
            }
        }
        Ok(())
    }
}

/// A single entry from `linear-cli issue list --output json`.
#[derive(Debug, Deserialize)]
struct LinearIssue {
    identifier: String,
    #[serde(default)]
    title: String,
    #[serde(default)]
    description: Option<String>,
    #[serde(default)]
    labels: Vec<LinearLabel>,
    #[serde(default, alias = "state")]
    status: Option<LinearStatus>,
    #[serde(default, alias = "updatedAt")]
    updated_at: Option<String>,
    /// The parent issue's identifier, when the remote reported one.
    ///
    /// Linear's hierarchy is a **list** (`parent` on an issue can hold more than
    /// one entry in the API), and this reads the first. Taking one and saying so
    /// is the conservative choice: silently dropping the rest would make a
    /// round trip lossy in a way nothing reports, and tix's contract is
    /// single-parent anyway, so there is exactly one reference to keep.
    #[serde(default)]
    parent: Option<serde_json::Value>,
}

/// Labels arrive either as plain strings or as `{"name":..}` / `{"value":..}`.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum LinearLabel {
    Name(String),
    Named { name: String },
}

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

impl From<LinearIssue> for RemoteIssue {
    fn from(issue: LinearIssue) -> Self {
        let state = match issue.status {
            Some(LinearStatus::Name(name)) | Some(LinearStatus::Named { name }) => name,
            None => String::new(),
        };
        RemoteIssue {
            id: issue.identifier,
            title: issue.title,
            description: issue.description.unwrap_or_default(),
            labels: issue
                .labels
                .into_iter()
                .map(|l| match l {
                    LinearLabel::Name(name) | LinearLabel::Named { name } => name,
                })
                .collect(),
            state,
            updated_at: issue.updated_at,
            assignee: None,
            // Linear sends the parent as an object, an id string, or a list of
            // either. All three 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()),
        }
    }
}

/// 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` 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 {
    use super::*;
    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_passes_team_title_body_labels_priority_status_and_token() {
        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[0], "linear-cli");
        let joined = argv.join(" ");
        assert!(joined.contains("issue create --team Eng --title Fix --description body --label bug --priority high --status Done --output json"));
        assert_eq!(
            env,
            &[("LINEAR_TOKEN".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("--label"));
    }

    #[test]
    fn update_passes_identifier_and_status() {
        let runner = FakeRunner::new(vec![]);
        let mut adapter = adapter_with(runner, None);
        adapter
            .update_issue("TIX-7", "New title", "new body", &[], None, None, "Done")
            .unwrap();
        let joined = recorded(&adapter)[0].0.join(" ");
        assert!(joined.starts_with("linear-cli issue update TIX-7 "));
        assert!(joined.contains("--title New title"));
        assert!(joined.contains("--description new body"));
        assert!(joined.contains("--status Done"));
    }

    #[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 list_open_parses_json_object_status_and_filters_done() {
        let payload = r#"[
          {"identifier":"TIX-1","title":"T1","description":"d","labels":["bug"],"status":{"name":"In Progress"},"updated_at":"2026-05-11T10:00:00Z"},
          {"identifier":"TIX-2","title":"T2","status":"Done"}
        ]"#;
        let runner = FakeRunner::new(vec![CommandOutcome::linear_list(payload)]);
        let mut adapter = adapter_with(runner, None);
        let issues = adapter.list_open().unwrap();
        assert_eq!(issues.len(), 1);
        assert_eq!(issues[0].id, "TIX-1");
        assert_eq!(issues[0].state, "In Progress");
        assert_eq!(issues[0].labels, ["bug"]);
        assert_eq!(
            issues[0].updated_at.as_deref(),
            Some("2026-05-11T10:00:00Z")
        );
    }

    #[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"));
    }

    #[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_TOKEN=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}");
    }
}