yandex-tracker-cli 1.0.0

Token-efficient Yandex Tracker CLI for humans and AI agents
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
//! Turning Tracker's payloads into our models.
//!
//! Tracker returns most human-readable values as objects with `display`, `key`,
//! `id` and `self` members, and the useful part is not always in the same one.
//! Rather than deriving `Deserialize` against a moving target, we pull out what
//! we render and keep everything else in `extra`, so an upstream addition is
//! carried through instead of breaking the parse (ADR 4).

use serde_json::{Map, Value};

use crate::api::models::{
    Attachment, Change, ChecklistItem, Comment, DictEntry, Entity, FieldChange, Issue, Link,
    LinkKind, Person, RemoteLink, User, Worklog,
};

/// System fields we map explicitly. Anything outside this set is treated as a
/// custom field and lands in `extra`.
const KNOWN: &[&str] = &[
    "key",
    // Counters and bookkeeping Tracker returns on every issue. They are not
    // custom fields, and counting them as such made every issue look like it had
    // several — which is exactly the noise the summary exists to avoid.
    "commentWithExternalMessageCount",
    "votes",
    "votedBy",
    "unique",
    "boards",
    "access",
    "followers",
    "checklistDone",
    "checklistTotal",
    "checklistItems",
    "emailCreatedBy",
    "emailTo",
    "emailFrom",
    "summary",
    "status",
    "type",
    "priority",
    "queue",
    "assignee",
    "createdBy",
    "createdAt",
    "updatedAt",
    "description",
    "commentWithoutExternalMessageCount",
    "id",
    "self",
    "version",
    "aliases",
    "lastCommentUpdatedAt",
    "statusStartTime",
    "updatedBy",
    "previousStatus",
    "previousStatusLastAssignee",
    "favorite",
    "pendingReplyFrom",
];

/// The label of a Tracker reference object: `display` if present, else `key`,
/// else `id`, else the value itself when it is a bare string.
fn label(value: Option<&Value>) -> Option<String> {
    let value = value?;
    if let Some(text) = value.as_str() {
        return Some(text.to_owned());
    }
    for member in ["display", "key", "id"] {
        if let Some(text) = value.get(member).and_then(Value::as_str) {
            return Some(text.to_owned());
        }
    }
    None
}

/// The key of a reference object, falling back to its label.
///
/// Queues are addressed by key everywhere — it is the `PROJ` in `PROJ-1` — so
/// showing the prettier `display` name would print something the caller cannot
/// then type back into another command.
/// The stable key of a referenced object, and nothing else.
///
/// Unlike [`key_label`] this does not fall back to a display name: half a
/// vocabulary is worse than none, since a caller matching on `closed` would
/// silently start matching a localised word that happens to be there.
fn key_of(value: Option<&Value>) -> Option<String> {
    value?
        .get("key")
        .and_then(Value::as_str)
        .map(ToOwned::to_owned)
}

fn key_label(value: Option<&Value>) -> Option<String> {
    let value = value?;
    if let Some(key) = value.get("key").and_then(Value::as_str) {
        return Some(key.to_owned());
    }
    label(Some(value))
}

fn user(value: Option<&Value>) -> Option<User> {
    let value = value?;
    Some(User {
        id: value
            .get("id")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_owned(),
        login: value
            .get("login")
            .and_then(Value::as_str)
            .map(ToOwned::to_owned),
        display: value
            .get("display")
            .and_then(Value::as_str)
            .map(ToOwned::to_owned),
    })
}

/// Parse a Tracker timestamp.
///
/// The API emits offsets as `+0300` rather than `+03:00`, which is valid ISO 8601
/// but not what a strict RFC 3339 parser accepts, so the compact form is widened
/// before parsing. An unparseable date is dropped rather than failing the whole
/// issue: a missing `updated` line is a much smaller problem than a command that
/// refuses to show an issue at all.
fn timestamp(value: Option<&Value>) -> Option<jiff::Timestamp> {
    let text = value?.as_str()?;

    if let Ok(parsed) = text.parse::<jiff::Timestamp>() {
        return Some(parsed);
    }

    let widened = widen_offset(text);
    match widened.parse::<jiff::Timestamp>() {
        Ok(parsed) => Some(parsed),
        Err(error) => {
            tracing::debug!(%text, %error, "unparseable timestamp, omitted");
            None
        }
    }
}

/// `2026-08-27T10:00:00.000+0300` -> `2026-08-27T10:00:00.000+03:00`.
fn widen_offset(text: &str) -> String {
    let bytes = text.as_bytes();
    let Some(sign_at) = bytes
        .iter()
        .rposition(|byte| *byte == b'+' || *byte == b'-')
    else {
        return text.to_owned();
    };

    // Only the trailing `±HHMM` form needs widening, and only when it really is
    // a four-digit offset rather than part of the date.
    let offset = &text[sign_at + 1..];
    if offset.len() != 4 || !offset.bytes().all(|byte| byte.is_ascii_digit()) {
        return text.to_owned();
    }

    format!("{}{}:{}", &text[..=sign_at], &offset[..2], &offset[2..])
}

/// Map a link type id and our side of it onto our vocabulary.
///
/// Keyed on `type.id`, which is stable and English, rather than on the
/// `inward`/`outward` labels, which come back in the organisation's language —
/// a Russian-locale organisation answers "Связана", and an English word list
/// silently turns every link into "links".
///
/// `direction` says which end we are on, and the rule is one rule: the kind has
/// to mean what Tracker's own label for *our* side means. `subtask` outward is
/// labelled "родительская задача" — we are the parent, so the other issue is
/// the subtask; `depends` outward is labelled "зависит от" — we are the one
/// that depends.
///
/// The `depends` pair was the wrong way round until a round trip against a real
/// organisation caught it, and nothing else could have: written from one end
/// the wrong mapping is self-consistent, and the fixtures were written from the
/// same belief as the code. Both ends, or it proves nothing.
fn link_kind(type_id: &str, inward: bool) -> LinkKind {
    match (type_id, inward) {
        ("subtask", true) => LinkKind::Parent,
        ("subtask", false) => LinkKind::Subtask,
        ("depends", true) => LinkKind::IsDependentBy,
        ("depends", false) => LinkKind::Depends,
        ("duplicates" | "duplicate", true) => LinkKind::Duplicates,
        ("duplicates" | "duplicate", false) => LinkKind::IsDuplicatedBy,
        ("epic", true) => LinkKind::HasEpic,
        ("epic", false) => LinkKind::Epic,
        ("relates", _) => LinkKind::Relates,
        _ => LinkKind::Other,
    }
}

/// Parse one entry of `GET /v3/issues/{key}/links`.
#[must_use]
pub fn link(value: &Value) -> Option<Link> {
    let object = value.get("object")?;
    let kind_object = value.get("type");
    let inward = value.get("direction").and_then(Value::as_str) == Some("inward");

    let type_id = kind_object
        .and_then(|kind| kind.get("id"))
        .and_then(Value::as_str)
        .unwrap_or_default();

    // Tracker's own wording for our side of the link, kept for the types we do
    // not recognise so the output still says something true.
    let relation = kind_object
        .and_then(|kind| kind.get(if inward { "inward" } else { "outward" }))
        .and_then(Value::as_str)
        .map(str::to_lowercase);

    Some(Link {
        // A number on the wire in some organisations, a string in others, and
        // absent only in a payload we have never seen. A link with no id is
        // still a link: dropping the row would make it invisible, and this
        // command exists so that invisible and absent are not the same thing.
        id: match value.get("id") {
            Some(Value::String(id)) => id.clone(),
            Some(other) => other.to_string(),
            None => String::new(),
        },
        kind: link_kind(type_id, inward),
        relation,
        key: object.get("key").and_then(Value::as_str)?.to_owned(),
        summary: label(object.get("display")),
        status: label(object.get("status")),
    })
}

/// One link out of Tracker.
///
/// Everything but the id is optional on purpose: the object at the far end is
/// described by an application we know nothing about, and a link whose payload
/// is thinner than the documented shape is still a link worth printing.
#[must_use]
pub fn remote_link(value: &Value) -> Option<RemoteLink> {
    let object = value.get("object");
    let inward = value.get("direction").and_then(Value::as_str) == Some("inward");

    Some(RemoteLink {
        id: match value.get("id")? {
            Value::String(id) => id.clone(),
            other => other.to_string(),
        },
        relation: value
            .get("type")
            .and_then(|kind| {
                kind.get(if inward { "inward" } else { "outward" })
                    .or_else(|| kind.get("id"))
            })
            .and_then(Value::as_str)
            .map(str::to_lowercase),
        application: object
            .and_then(|object| object.get("application"))
            .and_then(|app| app.get("name").or_else(|| app.get("id")))
            .and_then(Value::as_str)
            .map(ToOwned::to_owned),
        key: object
            .and_then(|object| object.get("key"))
            .and_then(Value::as_str)
            .map(ToOwned::to_owned),
        title: label(object.and_then(|object| object.get("display"))),
    })
}

/// Parse one project, portfolio or goal.
///
/// Everything worth showing sits under `fields`; the envelope carries only
/// identity.
#[must_use]
pub fn entity(value: &Value) -> Option<Entity> {
    let fields = value.get("fields");
    let field = |name: &str| fields.and_then(|fields| fields.get(name));

    Some(Entity {
        id: value.get("id").and_then(Value::as_str)?.to_owned(),
        short_id: value.get("shortId").and_then(Value::as_i64),
        entity_type: value
            .get("entityType")
            .and_then(Value::as_str)
            .map(ToOwned::to_owned),
        summary: field("summary")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_owned(),
        status: label(field("entityStatus")),
        lead: user(field("lead")),
        start: field("start")
            .and_then(Value::as_str)
            .map(ToOwned::to_owned),
        end: field("end").and_then(Value::as_str).map(ToOwned::to_owned),
        description: field("description")
            .and_then(Value::as_str)
            .map(ToOwned::to_owned),
        parent: parent_entity(field("parentEntity")),
        version: value.get("version").and_then(Value::as_u64),
    })
}

/// The id out of `parentEntity`, in whichever shape it arrives.
///
/// Writes take an object (`{"primary": id, "secondary": [...]}`), and reads have
/// been seen to answer with the bare id. Both are accepted rather than guessed
/// at, because an entity whose parent silently reads as absent is worse than one
/// that costs a few lines here.
fn parent_entity(value: Option<&Value>) -> Option<String> {
    fn id_of(value: &Value) -> Option<String> {
        match value {
            Value::String(id) => Some(id.clone()),
            Value::Number(id) => Some(id.to_string()),
            // A read answers `{"primary": {"id": …, "display": …}}`; a write
            // takes `{"primary": "<id>"}`. Both arrive here.
            Value::Object(map) => map.get("id").and_then(id_of),
            _ => None,
        }
    }

    match value? {
        Value::Object(map) => map.get("primary").and_then(id_of),
        other => id_of(other),
    }
}

/// Parse one entry of `GET /v3/issues/{key}/attachments`.
#[must_use]
pub fn attachment(value: &Value) -> Option<Attachment> {
    Some(Attachment {
        id: match value.get("id")? {
            Value::String(text) => text.clone(),
            other => other.to_string(),
        },
        name: value
            .get("name")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_owned(),
        size: value.get("size").and_then(Value::as_u64),
        mimetype: value
            .get("mimetype")
            .and_then(Value::as_str)
            .map(ToOwned::to_owned),
        author: user(value.get("createdBy")),
        created_at: timestamp(value.get("createdAt")),
        content: value
            .get("content")
            .and_then(Value::as_str)
            .map(ToOwned::to_owned),
    })
}

/// Parse one entry of `GET /v3/issues/{key}/comments`.
#[must_use]
pub fn comment(value: &Value) -> Option<Comment> {
    Some(Comment {
        id: value
            .get("id")
            .map(|id| match id {
                Value::String(text) => text.clone(),
                other => other.to_string(),
            })
            .unwrap_or_default(),
        text: value
            .get("text")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_owned(),
        author: user(value.get("createdBy")),
        created_at: timestamp(value.get("createdAt")),
    })
}

/// Parse one entry of `GET /v3/issues/{key}/worklog`.
#[must_use]
pub fn worklog(value: &Value) -> Option<Worklog> {
    Some(Worklog {
        id: identifier(value.get("id"))?,
        duration: value
            .get("duration")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_owned(),
        author: user(value.get("createdBy")),
        start: timestamp(value.get("start")),
        comment: value
            .get("comment")
            .and_then(Value::as_str)
            .map(str::to_owned),
        issue: key_label(value.get("issue")),
    })
}

/// Parse one entry of `GET /v3/issues/{key}/checklistItems`.
#[must_use]
pub fn checklist_item(value: &Value) -> Option<ChecklistItem> {
    Some(ChecklistItem {
        id: identifier(value.get("id"))?,
        text: value
            .get("text")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_owned(),
        checked: value
            .get("checked")
            .and_then(Value::as_bool)
            .unwrap_or(false),
        assignee: user(value.get("assignee")),
        deadline: value
            .get("deadline")
            .and_then(|deadline| deadline.get("date").or(Some(deadline)))
            .and_then(Value::as_str)
            .map(str::to_owned),
    })
}

/// An id, whether Tracker sent it as a string or a number.
///
/// Worklog and checklist ids come back as numbers on some endpoints and strings
/// on others, and a caller passes whichever they were given straight back.
fn identifier(value: Option<&Value>) -> Option<String> {
    match value? {
        Value::String(text) => Some(text.clone()),
        Value::Number(number) => Some(number.to_string()),
        _ => None,
    }
}

/// The name a caller can actually type for a custom field.
///
/// Tracker returns them prefixed with the queue's opaque id —
/// `603bd9b6cdc7ba0d2f4b1a55--component` — and accepts the trailing segment
/// back. `queue fields` has always printed the short form; the issue view
/// printed the raw one, which meant the line whose whole purpose is to say what
/// to ask for next named a key `--fields` would not take.
fn custom_field_key(key: &str) -> String {
    key.rsplit("--").next().unwrap_or(key).to_owned()
}

/// Parse `GET /v3/issues/{key}` (or one element of a search result).
///
/// Returns `None` only when the payload has no key, which means it is not an
/// issue at all.
#[must_use]
pub fn issue(value: &Value) -> Option<Issue> {
    let object = value.as_object()?;

    let mut extra = Map::new();
    for (key, member) in object {
        if KNOWN.contains(&key.as_str()) {
            continue;
        }
        // A custom field that is set to nothing is not worth counting: it would
        // inflate the "N set" summary with fields nobody filled in.
        if member.is_null() {
            continue;
        }
        let key = custom_field_key(key);
        if let Some(text) = label(Some(member)) {
            extra.insert(key, Value::String(text));
        } else {
            extra.insert(key, member.clone());
        }
    }

    Some(Issue {
        key: object.get("key")?.as_str()?.to_owned(),
        summary: object
            .get("summary")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_owned(),
        status: label(object.get("status")),
        status_key: key_of(object.get("status")),
        issue_type: label(object.get("type")),
        priority: label(object.get("priority")),
        priority_key: key_of(object.get("priority")),
        queue: key_label(object.get("queue")),
        assignee: user(object.get("assignee")),
        author: user(object.get("createdBy")),
        created_at: timestamp(object.get("createdAt")),
        updated_at: timestamp(object.get("updatedAt")),
        description: object
            .get("description")
            .and_then(Value::as_str)
            .map(ToOwned::to_owned),
        links: Vec::new(),
        comment_count: object
            .get("commentWithoutExternalMessageCount")
            .and_then(Value::as_u64)
            .and_then(|count| u32::try_from(count).ok()),
        extra,
    })
}

/// One entry of the changelog.
#[must_use]
pub fn change(value: &Value) -> Option<Change> {
    let fields = value
        .get("fields")
        .and_then(Value::as_array)
        .map(|entries| entries.iter().filter_map(field_change).collect())
        .unwrap_or_default();

    Some(Change {
        id: identifier(value.get("id"))?,
        at: timestamp(value.get("updatedAt")),
        by: user(value.get("updatedBy")),
        kind: value
            .get("type")
            .and_then(Value::as_str)
            .unwrap_or("change")
            .to_owned(),
        fields,
    })
}

fn field_change(value: &Value) -> Option<FieldChange> {
    // The field's id, not its display name, and for the same reason `dict list`
    // prints keys: `Статус` is what a Russian organisation calls it, `status` is
    // what `--set` and `--fields` take. Custom fields arrive prefixed with the
    // queue id, and the trailing segment is the part a caller can type.
    let field = value
        .get("field")
        .and_then(|field| field.get("id"))
        .and_then(Value::as_str)
        .map(custom_field_key)
        .or_else(|| label(value.get("field")))?;

    Some(FieldChange {
        field,
        from: changed_value(value.get("from")),
        to: changed_value(value.get("to")),
    })
}

/// One side of a change, as one line of text.
///
/// A field's value can be a reference object, a bare scalar or a list of either
/// — tags and followers arrive as arrays — and all three have to render as
/// something a person can compare against the other side. `null` becomes
/// `None`: on a creation there is no before, and that is not the same as a
/// field whose value is the word "null".
fn changed_value(value: Option<&Value>) -> Option<String> {
    match value? {
        Value::Null => None,
        Value::Bool(flag) => Some(flag.to_string()),
        Value::Number(number) => Some(number.to_string()),
        Value::Array(entries) => {
            let joined: Vec<String> = entries
                .iter()
                .filter_map(|entry| changed_value(Some(entry)))
                .collect();
            (!joined.is_empty()).then(|| joined.join(", "))
        }
        // A reference whose only member is a numeric id — board membership
        // arrives as `[{"id": 1}]` — still has to render as something, or the
        // line claims nothing changed when something did.
        other => label(Some(other)).or_else(|| identifier(other.get("id"))),
    }
}

/// One entry of an issue type, priority, status or resolution listing.
///
/// Without a `key` the entry is useless for the purpose it is listed for — a
/// write quotes the key — so an entry that has none is dropped rather than
/// printed as a row nobody can act on.
#[must_use]
pub fn dict_entry(value: &Value) -> Option<DictEntry> {
    Some(DictEntry {
        key: value.get("key").and_then(Value::as_str)?.to_owned(),
        name: value
            .get("name")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_owned(),
        description: value
            .get("description")
            .and_then(Value::as_str)
            .filter(|text| !text.is_empty())
            .map(ToOwned::to_owned),
        order: value.get("order").and_then(Value::as_i64),
        category: value
            .get("type")
            .and_then(Value::as_str)
            .map(ToOwned::to_owned),
    })
}

/// One directory record.
///
/// `display` is assembled by Tracker from the first and last name and is what
/// a person is called in every other answer, so it is preferred over
/// re-assembling it here. An account with neither falls back to its login,
/// because a blank column reads as a bug.
#[must_use]
pub fn person(value: &Value) -> Option<Person> {
    let login = value.get("login").and_then(Value::as_str)?.to_owned();
    let display = value
        .get("display")
        .and_then(Value::as_str)
        .filter(|text| !text.trim().is_empty())
        .unwrap_or(&login)
        .to_owned();

    Some(Person {
        uid: identifier(value.get("uid")).unwrap_or_default(),
        display,
        email: value
            .get("email")
            .and_then(Value::as_str)
            .filter(|text| !text.is_empty())
            .map(ToOwned::to_owned),
        dismissed: value
            .get("dismissed")
            .and_then(Value::as_bool)
            .unwrap_or(false),
        external: value
            .get("external")
            .and_then(Value::as_bool)
            .unwrap_or(false),
        login,
    })
}

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

    #[test]
    fn reference_objects_collapse_to_their_display_name() {
        let value = serde_json::json!({"display": "In Progress", "key": "inProgress"});
        assert_eq!(label(Some(&value)).as_deref(), Some("In Progress"));
    }

    #[test]
    fn a_reference_without_a_display_falls_back_to_its_key() {
        let value = serde_json::json!({"key": "PROJ", "id": "7"});
        assert_eq!(label(Some(&value)).as_deref(), Some("PROJ"));
    }

    /// Tracker writes offsets as `+0300`; a strict RFC 3339 parser wants `+03:00`.
    #[test]
    fn compact_offsets_are_widened_before_parsing() {
        let value = serde_json::json!("2026-08-27T10:00:00.000+0300");
        let parsed = timestamp(Some(&value)).expect("parsed");
        assert_eq!(parsed.to_string(), "2026-08-27T07:00:00Z");
    }

    #[test]
    fn utc_timestamps_parse_unchanged() {
        let value = serde_json::json!("2026-08-27T10:00:00Z");
        assert!(timestamp(Some(&value)).is_some());
    }

    /// A date we cannot read costs one line of output. Refusing to show the
    /// issue would cost the whole command.
    #[test]
    fn an_unparseable_date_is_dropped_not_fatal() {
        let value = serde_json::json!("yesterday");
        assert!(timestamp(Some(&value)).is_none());
    }

    #[test]
    fn unknown_members_become_custom_fields_and_nulls_are_skipped() {
        let value = serde_json::json!({
            "key": "PROJ-1",
            "summary": "s",
            "storyPoints": 3,
            "sprint": {"display": "S-12", "id": "9"},
            "emptyField": null,
        });
        let parsed = issue(&value).expect("parsed");

        assert_eq!(parsed.extra.len(), 2);
        assert_eq!(parsed.extra.get("sprint"), Some(&serde_json::json!("S-12")));
        assert!(!parsed.extra.contains_key("emptyField"));
    }

    #[test]
    fn a_payload_without_a_key_is_not_an_issue() {
        assert!(issue(&serde_json::json!({"summary": "s"})).is_none());
    }

    fn subtask_link(direction: &str, key: &str) -> Value {
        serde_json::json!({
            "type": {"id": "subtask", "inward": "Is subtask for", "outward": "Is parent task for"},
            "direction": direction,
            "object": {"key": key, "display": "some issue"},
        })
    }

    /// Tracker answers in the organisation's language. Reading the relationship
    /// from the localised label turned every link in a Russian organisation into
    /// the fallback, so the type id decides.
    #[test]
    fn a_russian_organisation_still_gets_real_link_types() {
        let value = serde_json::json!({
            "type": {"id": "relates", "inward": "Связана", "outward": "Связана"},
            "direction": "outward",
            "object": {"key": "LMS-1", "display": "какая-то задача"},
        });

        assert_eq!(link(&value).expect("link").kind, LinkKind::Relates);
    }

    /// An unfamiliar link type keeps Tracker's own wording rather than being
    /// rendered as the word "link".
    #[test]
    fn an_unknown_link_type_keeps_what_tracker_called_it() {
        let value = serde_json::json!({
            "type": {"id": "somethingNew", "inward": "Blocks release of", "outward": "x"},
            "direction": "inward",
            "object": {"key": "PROJ-5"},
        });

        let parsed = link(&value).expect("link");
        assert_eq!(parsed.kind, LinkKind::Other);
        assert_eq!(parsed.relation.as_deref(), Some("blocks release of"));
    }

    /// Bookkeeping counters are not custom fields; counting them made every
    /// issue look like it had several.
    #[test]
    fn tracker_bookkeeping_is_not_mistaken_for_custom_fields() {
        let value = serde_json::json!({
            "key": "PROJ-1",
            "summary": "s",
            "commentWithExternalMessageCount": 0,
            "votes": 3,
            "followers": [],
            "storyPoints": 5,
        });

        let parsed = issue(&value).expect("parsed");
        assert_eq!(parsed.extra.keys().collect::<Vec<_>>(), ["storyPoints"]);
    }

    #[test]
    fn link_direction_decides_parent_from_subtask() {
        assert_eq!(
            link(&subtask_link("inward", "PROJ-9")).expect("link").kind,
            LinkKind::Parent
        );
        assert_eq!(
            link(&subtask_link("outward", "PROJ-12"))
                .expect("link")
                .kind,
            LinkKind::Subtask
        );
    }

    /// The labels here are Tracker's own, and they are the way round a real
    /// organisation sends them: `depends` **inward** is "блокирующая задача",
    /// the blocking task, so the issue on that end is the one being depended
    /// on. This was asserted backwards for months, by a test written from the
    /// same guess as the code, with a fixture that invented the labels the
    /// other way round.
    ///
    /// A live round trip is what settles it, and there is one in the live
    /// suite: write the link, read it from both ends.
    #[test]
    fn the_end_that_depends_is_the_outward_one() {
        let kind = |direction: &str| {
            let value = serde_json::json!({
                "id": 10,
                "type": {
                    "id": "depends",
                    "inward": "блокирующая задача",
                    "outward": "зависит от",
                },
                "direction": direction,
                "object": {"key": "PROJ-3", "display": "blocker"},
            });
            link(&value).expect("link").kind
        };

        assert_eq!(kind("outward"), LinkKind::Depends);
        assert_eq!(kind("inward"), LinkKind::IsDependentBy);
    }

    /// A payload with no id is still a link. Dropping it would hide it, and a
    /// hidden link is indistinguishable from one that is not there.
    #[test]
    fn a_link_without_an_id_is_still_shown() {
        let value = serde_json::json!({
            "type": {"id": "relates", "inward": "Связана", "outward": "Связана"},
            "direction": "outward",
            "object": {"key": "PROJ-2"},
        });

        let parsed = link(&value).expect("link");
        assert!(parsed.id.is_empty());
        assert_eq!(parsed.key, "PROJ-2");
    }

    #[test]
    fn a_queue_renders_as_its_key_not_its_display_name() {
        let value = serde_json::json!({
            "key": "PROJ-1",
            "summary": "s",
            "queue": {"key": "PROJ", "display": "Product"},
        });
        assert_eq!(
            issue(&value).expect("parsed").queue.as_deref(),
            Some("PROJ")
        );
    }

    /// The line whose whole purpose is to say what to ask for next has to name
    /// a key `--fields` accepts. Tracker prefixes custom fields with the
    /// queue's opaque id and takes the trailing segment back.
    #[test]
    fn a_custom_field_is_keyed_by_the_name_a_caller_can_type() {
        let value = serde_json::json!({
            "key": "PROJ-1",
            "summary": "x",
            "603bd9b6cdc7ba0d2f4b1a55--component": "backend",
            "sprint": "S-12",
        });

        let parsed = issue(&value).expect("parses");

        assert_eq!(
            parsed.extra.get("component"),
            Some(&serde_json::json!("backend"))
        );
        assert!(!parsed.extra.keys().any(|key| key.contains("--")));
        // A field with no prefix is left exactly as it came.
        assert_eq!(parsed.extra.get("sprint"), Some(&serde_json::json!("S-12")));
    }
}