onetaskgraph-linear 0.8.0

A onetaskgraph source over the Linear API.
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
//! A Linear item's change token, `lin1`: what [`Task::version`](onetaskgraph_plugin_api::Task::version),
//! [`Project::version`](onetaskgraph_plugin_api::Project::version) and
//! [`Document::version`](onetaskgraph_plugin_api::Document::version) hold here, and the one
//! ordering of two of them.
//!
//! `docs/plugin-protocol.md` §4.13d is the specification. Every part is spelled from the response
//! the source already receives: the item's `updatedAt`, and the digest of its *facets* — what a
//! person can change about it without moving that time, which `spike-linear-coverage` measured
//! `updatedAt` alone missing: a label renamed or recoloured, a workflow state renamed, a
//! document's content and slot edited. With the store's cache attached a task's token also
//! carries digests of its first page of comments, relations and inverse relations, and a
//! project's of its first page of relations and inverse relations — the parts §4.13d says each
//! covers.
//!
//! An item whose labels came back as 50 nodes or more — Linear's default page, which the
//! documents here select without a `first` or a `pageInfo` — gives no token, and so does an item
//! whose comments, relations or inverse relations page reports another page or holds more than
//! [`PAGE`] rows: a part read from part of a connection vouches for nothing.

use std::cmp::Ordering;

use chrono::{DateTime, Utc};
use onetaskgraph_plugin_api::asset_sha256;
use serde::Serialize;
use serde_json::Value;

/// What every token this plugin gives starts with.
pub const PREFIX: &str = "lin1|";

/// The rows a comments, relations or inverse relations page a token is spelled from holds at
/// most: the `first` of the pages the cache's documents select.
pub const PAGE: usize = 10;

/// The labels Linear answers a `labels` connection with when it names no `first`: a response
/// holding this many may be a first page of more, so it gives no token.
pub const DEFAULT_LABEL_PAGE: usize = 50;

/// Which spelling of a token a response is read as: the one a source with no cache attached gives,
/// or the one the cache's widened reads let it give, carrying their first pages' digests.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Spelling {
    /// `lin1|<updatedAt>|<facets>`, from what every read selects.
    Plain,
    /// With the parts the cache's widened reads carry: a task's comments, relations and inverse
    /// relations, a project's relations and inverse relations.
    Attached,
}

/// One of the parts the cache's widened reads add to a token, each the digest of one first page.
///
/// Spelled in this order, which is the only order a token holds them in, so the part a later
/// page of one walk is held to — everything before [`Part::Relations`] — is a prefix of it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Part {
    /// A task's comments, as `[id, updatedAt]` rows.
    Comments,
    /// A task's or a project's relations, as `[id, type, far end]` rows.
    Relations,
    /// A task's or a project's inverse relations, as `[id, type, near end]` rows.
    Inverse,
}

impl Part {
    const ALL: [Self; 3] = [Self::Comments, Self::Relations, Self::Inverse];

    fn tag(self) -> &'static str {
        match self {
            Self::Comments => "c:",
            Self::Relations => "r:",
            Self::Inverse => "i:",
        }
    }
}

/// One label as a facet spells it: its id, its name and its colour, which Linear may leave null.
type LabelFacet<'a> = (&'a str, &'a str, Option<&'a str>);

/// A workflow state's or a project status's name and type.
type NamedType<'a> = (&'a str, &'a str);

/// A task's facets, as its token's digest spells them.
#[derive(Serialize)]
struct TaskFacets<'a> {
    key: &'a str,
    labels: Vec<LabelFacet<'a>>,
    project: Option<&'a str>,
    state: NamedType<'a>,
    url: Option<&'a str>,
}

/// A project's facets.
#[derive(Serialize)]
struct ProjectFacets<'a> {
    labels: Vec<LabelFacet<'a>>,
    status: NamedType<'a>,
}

/// A lowercase hex SHA-256 — of a document's content, of a facets part's canonical JSON, of a
/// first page — made only by hashing, or read back out of a token and refused when it is not
/// one.
#[derive(Debug, PartialEq, Eq, Serialize)]
#[serde(transparent)]
struct Sha256Hex(String);

impl Sha256Hex {
    fn of(bytes: &[u8]) -> Self {
        Self(asset_sha256(bytes))
    }

    fn parse(text: &str) -> Option<Self> {
        (text.len() == 64
            && text
                .bytes()
                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)))
        .then(|| Self(text.to_owned()))
    }
}

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

/// A document's facets.
#[derive(Serialize)]
struct DocumentFacets<'a> {
    content: Sha256Hex,
    project: Option<&'a str>,
    title: &'a str,
    url: &'a str,
}

/// The lowercase hex SHA-256 of `facets`' canonical JSON.
fn digest(facets: &impl Serialize) -> Option<Sha256Hex> {
    Some(Sha256Hex::of(
        serde_json::to_string(facets).ok()?.as_bytes(),
    ))
}

/// `key` of `item` when it is a string — and `None`, so no token, when it is missing or anything
/// else: a part read as something Linear's schema does not give vouches for nothing.
fn text<'a>(item: &'a Value, key: &str) -> Option<&'a str> {
    item.get(key)?.as_str()
}

/// `key` of `item` when it is a string or null, `None` within when null — and `None` when it is
/// missing or anything else.
fn nullable_text<'a>(item: &'a Value, key: &str) -> Option<Option<&'a str>> {
    match item.get(key)? {
        Value::Null => Some(None),
        Value::String(text) => Some(Some(text)),
        _ => None,
    }
}

/// Every label of `item`, as `[id, name, color]` sorted by id — or `None` when the connection is
/// missing, may be only a first page, or holds a label without a string id and name and a
/// string or null colour.
fn labels(item: &Value) -> Option<Vec<LabelFacet<'_>>> {
    let nodes = item.pointer("/labels/nodes")?.as_array()?;
    if nodes.len() >= DEFAULT_LABEL_PAGE {
        return None;
    }
    let mut labels = nodes
        .iter()
        .map(|label| {
            Some((
                text(label, "id")?,
                text(label, "name")?,
                nullable_text(label, "color")?,
            ))
        })
        .collect::<Option<Vec<_>>>()?;
    labels.sort_unstable();
    Some(labels)
}

/// The project `item` is filed under, as its facets name it: its id, or `Some(None)` when it is
/// in none — and `None` when the member is missing or names a project without a string id.
fn project(item: &Value) -> Option<Option<&str>> {
    match item.get("project")? {
        Value::Null => Some(None),
        project => Some(Some(text(project, "id")?)),
    }
}

/// A `{name, type}` status or workflow state, as a facet names it, when both are strings.
fn named_type(status: &Value) -> Option<NamedType<'_>> {
    Some((text(status, "name")?, text(status, "type")?))
}

/// An instant, read and spelled back the one way this module spells it.
fn instant(value: &Value) -> Option<String> {
    let at: DateTime<Utc> = value.as_str()?.parse().ok()?;
    Some(at.to_rfc3339_opts(chrono::SecondsFormat::AutoSi, true))
}

/// `updatedAt`, read as an instant and spelled back the one way this module spells it.
fn updated(item: &Value) -> Option<String> {
    instant(item.get("updatedAt")?)
}

/// The nodes of the connection `key` of `item` when they are the whole of it — a page reporting
/// no further page either way it walks, of at most [`PAGE`] rows — or `None`.
///
/// A page walked forwards says so with `hasNextPage`, one walked backwards with
/// `hasPreviousPage`; the caller of a page that resumed from a cursor knows it is not the whole
/// and asks for none.
fn whole_page<'a>(item: &'a Value, key: &str) -> Option<&'a Vec<Value>> {
    let page = item.get(key)?;
    let info = page.get("pageInfo")?;
    let more = info
        .get("hasNextPage")
        .or_else(|| info.get("hasPreviousPage"))?;
    if more != &Value::Bool(false) {
        return None;
    }
    let nodes = page.get("nodes")?.as_array()?;
    (nodes.len() <= PAGE).then_some(nodes)
}

/// The digest of `rows`, sorted.
fn rows_digest<T: Ord + Serialize>(mut rows: Vec<T>) -> Option<Sha256Hex> {
    rows.sort_unstable();
    Some(Sha256Hex::of(serde_json::to_string(&rows).ok()?.as_bytes()))
}

/// The digest of the relations page `key` of `item`, each row `[id, type, <far>.id]`.
fn relation_digest(item: &Value, key: &str, far: &str) -> Option<Sha256Hex> {
    rows_digest(
        whole_page(item, key)?
            .iter()
            .map(|node| {
                Some((
                    node.get("id")?.as_str()?,
                    node.get("type")?.as_str()?,
                    node.get(far)?.get("id")?.as_str()?,
                ))
            })
            .collect::<Option<Vec<_>>>()?,
    )
}

/// The digest of an issue's comments page, each row `[id, updatedAt]`.
fn comment_digest(issue: &Value) -> Option<Sha256Hex> {
    rows_digest(
        whole_page(issue, "comments")?
            .iter()
            .map(|node| Some((node.get("id")?.as_str()?, instant(node.get("updatedAt")?)?)))
            .collect::<Option<Vec<_>>>()?,
    )
}

/// The digest one part of a task's token is spelled from, read from `issue`.
fn task_part(issue: &Value, part: Part) -> Option<Sha256Hex> {
    match part {
        Part::Comments => comment_digest(issue),
        Part::Relations => relation_digest(issue, "relations", "relatedIssue"),
        Part::Inverse => relation_digest(issue, "inverseRelations", "issue"),
    }
}

/// `lin1|<updatedAt>|<facets>` of the issue `issue`.
fn task_base(issue: &Value) -> Option<String> {
    let facets = TaskFacets {
        key: text(issue, "identifier")?,
        labels: labels(issue)?,
        project: project(issue)?,
        state: named_type(issue.get("state")?)?,
        url: nullable_text(issue, "url")?,
    };
    Some(format!("{PREFIX}{}|{}", updated(issue)?, digest(&facets)?))
}

/// `base` with each of `parts` of `item` appended, or `None` when any is not whole.
fn with_parts(
    base: String,
    parts: &[Part],
    read: impl Fn(Part) -> Option<Sha256Hex>,
) -> Option<String> {
    let mut token = base;
    for part in parts {
        token.push('|');
        token.push_str(part.tag());
        token.push_str(&read(*part)?.0);
    }
    Some(token)
}

/// The token of the issue `issue`, as one response answered it — with the digests of its first
/// page of comments, relations and inverse relations when [`Spelling::Attached`], and none at all when any of
/// those pages is not whole — or `None` when the response does not carry every part whole.
#[must_use]
pub fn task(issue: &Value, spelling: Spelling) -> Option<String> {
    let base = task_base(issue)?;
    match spelling {
        Spelling::Attached => with_parts(base, &Part::ALL, |part| task_part(issue, part)),
        Spelling::Plain => Some(base),
    }
}

/// The part of the attached token of the issue `issue` that a page of a forward-edge walk past
/// its first is held to: the token up to its relations part, which a page answering only part of
/// the relations cannot spell.
#[must_use]
pub fn task_before_relations(issue: &Value) -> Option<String> {
    with_parts(task_base(issue)?, &[Part::Comments], |part| {
        task_part(issue, part)
    })
}

/// The token of the project `project`, as one response answered it — with the digests of its
/// first page of relations and of inverse relations when [`Spelling::Attached`], and none at all
/// when either page is not whole.
#[must_use]
pub fn project_token(project: &Value, spelling: Spelling) -> Option<String> {
    let base = project_before_relations(project)?;
    match spelling {
        Spelling::Attached => {
            with_parts(base, &[Part::Relations, Part::Inverse], |part| match part {
                Part::Inverse => relation_digest(project, "inverseRelations", "project"),
                _ => relation_digest(project, "relations", "relatedProject"),
            })
        }
        Spelling::Plain => Some(base),
    }
}

/// The part of the attached token of the project `project` that a page of a forward-edge walk
/// past its first is held to: the token without its relations part.
#[must_use]
pub fn project_before_relations(project: &Value) -> Option<String> {
    let facets = ProjectFacets {
        labels: labels(project)?,
        status: named_type(project.get("status")?)?,
    };
    Some(format!(
        "{PREFIX}{}|{}",
        updated(project)?,
        digest(&facets)?
    ))
}

/// The token of the document `document`, as one response answered it: its content's digest is
/// of the content as Linear holds it, metadata slot and all.
#[must_use]
pub fn document_token(document: &Value) -> Option<String> {
    let facets = DocumentFacets {
        content: Sha256Hex::of(
            nullable_text(document, "content")?
                .unwrap_or_default()
                .as_bytes(),
        ),
        project: project(document)?,
        title: text(document, "title")?,
        url: text(document, "url")?,
    };
    Some(format!(
        "{PREFIX}{}|{}",
        updated(document)?,
        digest(&facets)?
    ))
}

/// The token `token` with its relations part and every part after it taken off: what a later
/// page of one walk, read with no whole relations page of its own, is held to.
#[must_use]
pub fn without_relations(token: &str) -> &str {
    token
        .split_once(&format!("|{}", Part::Relations.tag()))
        .map_or(token, |(base, _)| base)
}

/// The parts a token carries beside its time and its facets: none, as every plain token and a
/// document's; a relations and an inverse relations part, as an attached project's; or, as an
/// attached task's, a comments, a relations and an inverse relations part, in that order.
/// Nothing else is a token.
#[derive(Debug, PartialEq, Eq)]
enum Extra {
    None,
    Project {
        relations: Sha256Hex,
        inverse: Sha256Hex,
    },
    Task {
        comments: Sha256Hex,
        relations: Sha256Hex,
        inverse: Sha256Hex,
    },
}

/// What one token of this plugin is made of.
struct Parts {
    updated: DateTime<Utc>,
    facets: Sha256Hex,
    extra: Extra,
}

/// The digest `text` spells after `part`'s tag, when it spells one.
fn tagged(text: &str, part: Part) -> Option<Sha256Hex> {
    Sha256Hex::parse(text.strip_prefix(part.tag())?)
}

fn parts(token: &str) -> Option<Parts> {
    let mut parts = token.strip_prefix(PREFIX)?.split('|');
    let updated = DateTime::parse_from_rfc3339(parts.next()?)
        .ok()?
        .with_timezone(&Utc);
    let facets = Sha256Hex::parse(parts.next()?)?;
    let rest: Vec<&str> = parts.collect();
    let extra = match rest.as_slice() {
        [] => Extra::None,
        [relations, inverse] => Extra::Project {
            relations: tagged(relations, Part::Relations)?,
            inverse: tagged(inverse, Part::Inverse)?,
        },
        [comments, relations, inverse] => Extra::Task {
            comments: tagged(comments, Part::Comments)?,
            relations: tagged(relations, Part::Relations)?,
            inverse: tagged(inverse, Part::Inverse)?,
        },
        _ => return None,
    };
    Some(Parts {
        updated,
        facets,
        extra,
    })
}

/// How the version `a` of one item stands to its version `b`: by `updatedAt` as an instant when
/// their facets and every other part — which parts are present, and each one's value — are
/// equal, `Equal` only when every part is, and `None` when either is not a token of this plugin
/// or any of those differ, which says nothing about which reading came first.
///
/// So a token of the spelling an earlier release gave a task or a project with the cache
/// attached — a relations part alone — is never ordered beside one of this spelling, and an entry
/// that release wrote is read again.
#[must_use]
pub fn order(a: &str, b: &str) -> Option<Ordering> {
    let (a, b) = (parts(a)?, parts(b)?);
    (a.facets == b.facets && a.extra == b.extra).then(|| a.updated.cmp(&b.updated))
}

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

    /// An issue as the cache's widened reads answer it: no comments, no inverse relations, and
    /// `relations` as given.
    fn issue(updated: &str, label: &str, relations: Value) -> Value {
        json!({
            "id": "i1", "identifier": "ENG-1", "url": "https://linear.app/x/issue/ENG-1",
            "updatedAt": updated, "state": {"name": "Todo", "type": "unstarted"},
            "project": {"id": "p1"},
            "labels": {"nodes": [{"id": "l1", "name": label, "color": "#ff0000"}]},
            "comments": {"nodes": [], "pageInfo": {"hasNextPage": false}},
            "relations": relations,
            "inverseRelations": inverse(&[], false),
        })
    }

    fn page(rows: &[(&str, &str)], more: bool) -> Value {
        json!({
            "nodes": rows.iter().map(|(id, far)| json!({"id": id, "type": "blocks",
                                                        "relatedIssue": {"id": far}}))
                .collect::<Vec<_>>(),
            "pageInfo": {"hasNextPage": more},
        })
    }

    fn inverse(rows: &[(&str, &str)], more: bool) -> Value {
        json!({
            "nodes": rows.iter().map(|(id, near)| json!({"id": id, "type": "blocks",
                                                         "issue": {"id": near}}))
                .collect::<Vec<_>>(),
            "pageInfo": {"hasNextPage": more},
        })
    }

    fn comments(rows: &[(&str, &str)], more: bool) -> Value {
        json!({
            "nodes": rows.iter().map(|(id, updated)| json!({"id": id, "updatedAt": updated}))
                .collect::<Vec<_>>(),
            "pageInfo": {"hasNextPage": more},
        })
    }

    #[test]
    fn a_later_time_with_the_same_facets_and_parts_orders_after() {
        let none = page(&[], false);
        let before = task(
            &issue("2026-10-01T00:00:00Z", "bug", none.clone()),
            Spelling::Attached,
        )
        .unwrap();
        let after = task(
            &issue("2026-10-01T00:00:01Z", "bug", none),
            Spelling::Attached,
        )
        .unwrap();
        assert_eq!(order(&after, &before), Some(Ordering::Greater));
        assert_eq!(order(&before, &after), Some(Ordering::Less));
        assert_eq!(order(&before, &before), Some(Ordering::Equal));
    }

    #[test]
    fn another_facet_or_part_is_never_ordered() {
        let none = page(&[], false);
        let held = issue("2026-10-01T00:00:00Z", "bug", none.clone());
        let before = task(&held, Spelling::Attached).unwrap();
        let renamed = task(
            &issue("2026-10-01T00:00:05Z", "defect", none.clone()),
            Spelling::Attached,
        )
        .unwrap();
        assert_eq!(order(&renamed, &before), None, "a label renamed");
        let related = task(
            &issue("2026-10-01T00:00:05Z", "bug", page(&[("r1", "i2")], false)),
            Spelling::Attached,
        )
        .unwrap();
        assert_eq!(order(&related, &before), None, "a relation added");
        let mut depended = held.clone();
        depended["inverseRelations"] = inverse(&[("r2", "i3")], false);
        assert_eq!(
            order(&task(&depended, Spelling::Attached).unwrap(), &before),
            None,
            "an inverse relation added"
        );
        let mut commented = held.clone();
        commented["comments"] = comments(&[("c1", "2026-10-01T00:00:00Z")], false);
        let commented_token = task(&commented, Spelling::Attached).unwrap();
        assert_eq!(order(&commented_token, &before), None, "a comment added");
        let mut edited = commented.clone();
        edited["comments"] = comments(&[("c1", "2026-10-01T00:00:09Z")], false);
        assert_eq!(
            order(
                &task(&edited, Spelling::Attached).unwrap(),
                &commented_token
            ),
            None,
            "a comment edited"
        );
        assert_eq!(order(&before, &commented_token), None, "a comment deleted");
        let unattached =
            task(&issue("2026-10-01T00:00:00Z", "bug", none), Spelling::Plain).unwrap();
        assert!(!unattached.contains("|r:") && !unattached.contains("|c:"));
        assert_eq!(
            order(&unattached, &before),
            None,
            "a token with the cache's parts and one without"
        );
        assert_eq!(order("gh3|x", &before), None);
        assert_eq!(order(&format!("{before}|extra"), &before), None);
    }

    #[test]
    fn the_earlier_spelling_of_an_attached_token_is_never_ordered_beside_this_one() {
        let held = issue("2026-10-01T00:00:00Z", "bug", page(&[], false));
        let now = task(&held, Spelling::Attached).unwrap();
        // What the release before this one spelled for the same issue: its relations part alone.
        let relations = relation_digest(&held, "relations", "relatedIssue").unwrap();
        let earlier = format!("{}|r:{relations}", task(&held, Spelling::Plain).unwrap());
        assert!(
            parts(&earlier).is_none(),
            "a relations part alone is no shape of this one"
        );
        assert_eq!(order(&earlier, &now), None);
        assert_eq!(order(&now, &earlier), None);
        // A part out of its one order, or twice, is no token of this plugin.
        let (base, rest) = now.split_once("|c:").unwrap();
        let comments_part = rest.split('|').next().unwrap();
        assert_eq!(
            order(&format!("{base}|r:{relations}|c:{comments_part}"), &now),
            None
        );
        assert!(parts(&format!("{base}|r:{relations}|c:{comments_part}")).is_none());
        assert!(parts(&format!("{base}|c:{comments_part}|c:{comments_part}")).is_none());
        // Nor is any combination that is neither a project's two parts nor a task's three.
        for incomplete in [
            format!("{base}|c:{comments_part}"),
            format!("{base}|c:{comments_part}|r:{relations}"),
            format!("{base}|i:{relations}"),
        ] {
            assert!(parts(&incomplete).is_none(), "{incomplete}");
            assert_eq!(order(&incomplete, &incomplete), None, "{incomplete}");
        }
    }

    #[test]
    fn a_part_read_from_part_of_a_connection_gives_no_token() {
        let more = page(&[("r1", "i2")], true);
        assert_eq!(
            task(
                &issue("2026-10-01T00:00:00Z", "bug", more),
                Spelling::Attached
            ),
            None
        );
        let rows: Vec<(String, String)> = (0..=PAGE)
            .map(|n| (format!("r{n}"), format!("i{n}")))
            .collect();
        let eleven: Vec<(&str, &str)> = rows
            .iter()
            .map(|(id, far)| (id.as_str(), far.as_str()))
            .collect();
        assert_eq!(
            task(
                &issue("2026-10-01T00:00:00Z", "bug", page(&eleven, false)),
                Spelling::Attached
            ),
            None
        );
        let whole = issue("2026-10-01T00:00:00Z", "bug", page(&[], false));
        for (connection, value) in [
            ("inverseRelations", inverse(&[("r1", "i2")], true)),
            ("inverseRelations", inverse(&eleven, false)),
            (
                "comments",
                comments(&[("c1", "2026-10-01T00:00:00Z")], true),
            ),
            (
                "comments",
                json!({"nodes": [], "pageInfo": {"hasPreviousPage": true}}),
            ),
        ] {
            let mut partial = whole.clone();
            partial[connection] = value.clone();
            assert_eq!(
                task(&partial, Spelling::Attached),
                None,
                "{connection}: {value}"
            );
            assert!(
                task(&partial, Spelling::Plain).is_some(),
                "{connection}: a token without the cache's parts reads none of them"
            );
        }
        let stamps: Vec<String> = (0..=PAGE).map(|n| format!("c{n}")).collect();
        let crowd: Vec<(&str, &str)> = stamps
            .iter()
            .map(|id| (id.as_str(), "2026-10-01T00:00:00Z"))
            .collect();
        let mut crowded = whole.clone();
        crowded["comments"] = comments(&crowd, false);
        assert_eq!(task(&crowded, Spelling::Attached), None, "eleven comments");
        let mut crowded = whole;
        crowded["labels"]["nodes"] = Value::Array(
            (0..DEFAULT_LABEL_PAGE)
                .map(|n| json!({"id": format!("l{n}"), "name": "x", "color": null}))
                .collect(),
        );
        assert_eq!(task(&crowded, Spelling::Attached), None);
        assert_eq!(task(&crowded, Spelling::Plain), None);
    }

    #[test]
    fn a_comments_page_read_backwards_or_forwards_spells_one_part() {
        let mut forwards = issue("2026-10-01T00:00:00Z", "bug", page(&[], false));
        forwards["comments"] = comments(
            &[
                ("c1", "2026-10-01T00:00:00Z"),
                ("c2", "2026-10-01T00:00:01.000Z"),
            ],
            false,
        );
        let mut backwards = forwards.clone();
        backwards["comments"] = json!({
            "nodes": [
                {"id": "c2", "body": "two", "updatedAt": "2026-10-01T00:00:01Z",
                 "user": {"displayName": "a person"}},
                {"id": "c1", "body": "one", "updatedAt": "2026-10-01T00:00:00Z", "user": null},
            ],
            "pageInfo": {"hasPreviousPage": false, "startCursor": "c1"},
        });
        assert_eq!(
            task(&forwards, Spelling::Attached),
            task(&backwards, Spelling::Attached)
        );
        assert!(task(&forwards, Spelling::Attached).is_some());
    }

    #[test]
    fn a_part_of_another_json_type_than_linears_schema_gives_no_token() {
        let whole = issue("2026-10-01T00:00:00Z", "bug", page(&[], false));
        assert!(task(&whole, Spelling::Attached).is_some());
        for (part, value) in [
            ("/identifier", json!(7)),
            ("/url", json!(["a"])),
            ("/project", json!({"id": 7})),
            ("/project", json!("p1")),
            ("/state/type", json!(null)),
            ("/state/name", json!(1)),
            ("/labels/nodes/0/name", json!(null)),
            ("/labels/nodes/0/id", json!(1)),
            ("/labels/nodes/0/color", json!(0)),
        ] {
            let mut broken = whole.clone();
            *broken.pointer_mut(part).expect("the part") = value.clone();
            assert_eq!(task(&broken, Spelling::Attached), None, "{part} as {value}");
        }
        let mut broken = whole;
        broken["comments"] = comments(&[("c1", "yesterday")], false);
        assert_eq!(
            task(&broken, Spelling::Attached),
            None,
            "a comment time that is no instant"
        );
        let document = json!({"title": "Design", "url": "https://linear.app/x/document/design",
                              "project": null, "updatedAt": "2026-10-01T00:00:00Z",
                              "content": null});
        assert!(
            document_token(&document).is_some(),
            "Linear's content may be null"
        );
        for (part, value) in [
            ("/title", json!(null)),
            ("/url", json!(null)),
            ("/content", json!(1)),
        ] {
            let mut broken = document.clone();
            *broken.pointer_mut(part).expect("the part") = value.clone();
            assert_eq!(document_token(&broken), None, "{part} as {value}");
        }
    }

    #[test]
    fn the_pages_a_token_is_read_from_are_the_ones_the_cache_selects() {
        for selected in [
            crate::graphql::RELATIONS_PAGE,
            crate::graphql::INVERSE_RELATIONS_PAGE,
            crate::graphql::COMMENTS_PAGE,
            crate::graphql::PROJECT_RELATIONS_PAGE,
            crate::graphql::PROJECT_INVERSE_RELATIONS_PAGE,
        ] {
            assert!(
                selected.contains(&format!("(first:{PAGE})")),
                "{selected} selects a page of {PAGE}"
            );
        }
    }

    #[test]
    fn a_projects_token_carries_its_relations_and_inverse_relations_only_attached() {
        let none = json!({"nodes": [], "pageInfo": {"hasNextPage": false}});
        let with = |relations: Value, inverse: Value| {
            json!({"updatedAt": "2026-10-01T00:00:00Z", "status": {"name": "Doing", "type": "started"},
                   "labels": {"nodes": []}, "relations": relations, "inverseRelations": inverse})
        };
        let project = |relations: Value| with(relations, none.clone());
        let related = json!({"nodes": [{"id": "pr1", "type": "dependency",
                                        "relatedProject": {"id": "p2"}}],
                             "pageInfo": {"hasNextPage": false}});
        let none = json!({"nodes": [], "pageInfo": {"hasNextPage": false}});
        let plain = project_token(&project(none.clone()), Spelling::Plain).unwrap();
        assert!(!plain.contains("|r:"));
        let attached = project_token(&project(none.clone()), Spelling::Attached).unwrap();
        let added = project_token(&project(related), Spelling::Attached).unwrap();
        assert_eq!(order(&attached, &added), None, "a project relation added");
        assert_eq!(order(&plain, &attached), None);
        assert_eq!(without_relations(&added), plain);
        let depended = with(
            none.clone(),
            json!({"nodes": [{"id": "pr2", "type": "dependency", "project": {"id": "p3"}}],
                   "pageInfo": {"hasNextPage": false}}),
        );
        let depended = project_token(&depended, Spelling::Attached).unwrap();
        assert_eq!(
            order(&attached, &depended),
            None,
            "a project depending on it added"
        );
        assert_eq!(without_relations(&depended), plain);
        let more = json!({"nodes": [], "pageInfo": {"hasNextPage": true}});
        assert_eq!(
            project_token(&project(more.clone()), Spelling::Attached),
            None
        );
        assert_eq!(
            project_token(&with(none.clone(), more), Spelling::Attached),
            None
        );
    }

    #[test]
    fn a_documents_token_moves_with_its_content_and_the_relations_parts_come_off() {
        let document = |content: &str| {
            json!({"title": "Design", "url": "https://linear.app/x/document/design", "project": null,
                   "updatedAt": "2026-10-01T00:00:00Z", "content": content})
        };
        let one = document_token(&document("a")).unwrap();
        let other = document_token(&document("a, edited")).unwrap();
        assert_eq!(order(&one, &other), None);
        let held = issue("2026-10-01T00:00:00Z", "bug", page(&[], false));
        let token = task(&held, Spelling::Attached).unwrap();
        assert_eq!(
            without_relations(&token),
            task_before_relations(&held).unwrap()
        );
        assert!(without_relations(&token).contains("|c:"));
        assert!(!without_relations(&token).contains("|i:"));
    }
}