linear-api 0.1.0

Unofficial async Rust client for the Linear GraphQL API (API-key auth)
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
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
//! Live mutation verification suite — env-gated, every test `#[ignore]`d.
//!
//! Exercises every previously-unverified public API operation (mutations
//! included) against the **real** Linear workspace:
//!
//! ```text
//! LINEAR_API_KEY=lin_api_… cargo test --test live_mutations -- --ignored --test-threads=1
//! ```
//!
//! Ground rules baked into this suite:
//!
//! - Without `LINEAR_API_KEY` every test skips cleanly (prints and returns).
//! - Every created entity is unmistakably labeled: name/title prefixed
//!   `[sdk-smoke] <unix-timestamp>` with a description marking it as
//!   temporary and safe to delete.
//! - No pre-existing entity is ever mutated, commented on, related, or
//!   deleted — tests only touch entities they created in the same run.
//! - Full cleanup: each test registers everything it creates in a
//!   [`Registry`]; teardown runs even when the test body panics
//!   (`catch_unwind`), deletes every entity through the SDK (or
//!   `execute_raw` where the typed surface has no delete, e.g.
//!   `projectDelete`), and **verifies** each entity is gone/trashed by
//!   re-fetching.
//! - The host team is auto-picked as the least-active non-private team
//!   (prefer zero live issues, else the oldest most-recent activity);
//!   override with `LINEAR_LIVE_TEAM_KEY`.

use std::any::Any;
use std::panic::AssertUnwindSafe;
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use futures::{FutureExt, StreamExt, TryStreamExt};
use linear_api::comments::{CommentCreateInput, CommentListRequest};
use linear_api::issues::{
    Issue, IssueCreateInput, IssueUpdateInput, ListIssuesRequest, SearchIssuesRequest,
};
use linear_api::labels::{LabelCreateInput, LabelUpdateInput, ListLabelsRequest};
use linear_api::projects::{
    ListProjectsRequest, ProjectCreateInput, ProjectMilestoneCreateInput,
    ProjectMilestoneUpdateInput, ProjectUpdateInput,
};
use linear_api::workspace::{ListTeamsRequest, ListUsersRequest, ListWorkflowStatesRequest, Team};
use linear_api::{
    CommentId, Error, IdComparator, IssueFilter, IssueId, IssueLabelFilter, IssueRef,
    IssueRelationId, IssueRelationType, LabelId, LinearClient, Priority, ProjectFilter, ProjectId,
    ProjectMilestoneId, StringComparator, TeamFilter, TeamId, TimelessDate, Undefinable,
    WorkflowStateFilter,
};

const MARKER_DESCRIPTION: &str = "temporary linear-api SDK verification — safe to delete";

/// Builds the live client, or skips the test when the key is absent.
fn live_client() -> Option<LinearClient> {
    if std::env::var("LINEAR_API_KEY").is_err() {
        eprintln!("skipping live mutation test: LINEAR_API_KEY is not set");
        return None;
    }
    Some(LinearClient::from_env().expect("LINEAR_API_KEY should build a client"))
}

/// Unix-seconds stamp that makes every run's entity names unique.
fn stamp() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("clock after epoch")
        .as_secs()
}

/// Picks the team to create test entities in.
///
/// `LINEAR_LIVE_TEAM_KEY` wins when set. Otherwise a one-shot survey picks
/// the least-active non-private team: a team with **zero** live issues is
/// preferred (nothing pre-existing to disturb), else the team whose most
/// recently updated issue is oldest.
async fn pick_test_team(client: &LinearClient) -> Team {
    if let Ok(key) = std::env::var("LINEAR_LIVE_TEAM_KEY") {
        let team = client
            .teams()
            .get(&TeamId::new(key))
            .await
            .expect("LINEAR_LIVE_TEAM_KEY should resolve to a team");
        eprintln!(
            "[team] using LINEAR_LIVE_TEAM_KEY override: {} ({}{})",
            team.key, team.name, team.id
        );
        return team;
    }
    let data = client
        .execute_raw(
            "query { teams(first: 50) { nodes { id key private retiredAt \
             latest: issues(first: 1, orderBy: updatedAt) { nodes { updatedAt } } } } }",
            serde_json::json!({}),
        )
        .await
        .expect("team activity survey should succeed");
    let nodes = data["teams"]["nodes"]
        .as_array()
        .expect("teams.nodes should be an array")
        .clone();
    // Sort key: the ISO-8601 `updatedAt` of the team's most recent issue;
    // teams with no issues get "" which sorts before every date. Ties keep
    // the first team listed, so the pick is deterministic.
    let mut best: Option<(String, String)> = None;
    for node in &nodes {
        // Private teams are out of bounds; retired teams reject mutations
        // ("Entity is retired: team").
        if node["private"].as_bool() == Some(true) || !node["retiredAt"].is_null() {
            continue;
        }
        let id = node["id"].as_str().expect("team id").to_owned();
        let latest = node["latest"]["nodes"][0]["updatedAt"]
            .as_str()
            .unwrap_or("")
            .to_owned();
        let replace = match &best {
            None => true,
            Some((current, _)) => latest < *current,
        };
        if replace {
            best = Some((latest, id));
        }
    }
    let (_, id) = best.expect("workspace should have a non-private team");
    let team = client
        .teams()
        .get(&TeamId::new(id))
        .await
        .expect("picked team should resolve");
    eprintln!(
        "[team] auto-picked least-active team: {} ({}{})",
        team.key, team.name, team.id
    );
    team
}

// ---------------------------------------------------------------------------
// Cleanup registry
// ---------------------------------------------------------------------------

/// Everything a test created, torn down (and verified gone) even when the
/// test body panics. Deletion order matters: edges and children first, hosts
/// last.
#[derive(Default)]
struct Registry {
    relations: Vec<(IssueRelationId, IssueId)>,
    comments: Vec<(CommentId, IssueId)>,
    milestones: Vec<(ProjectMilestoneId, ProjectId)>,
    issues: Vec<IssueId>,
    labels: Vec<LabelId>,
    projects: Vec<ProjectId>,
}

type Shared = Arc<Mutex<Registry>>;

fn track(registry: &Shared, register: impl FnOnce(&mut Registry)) {
    register(&mut registry.lock().expect("registry lock"));
}

/// `true` when a delete failed because the entity is already gone — every
/// in-body delete leaves its registry entry behind as a backstop, so cleanup
/// must tolerate double deletes.
fn already_gone(err: &Error) -> bool {
    matches!(err, Error::Api { .. } | Error::MissingData { .. })
}

/// Re-fetches an issue; gone means trashed, archived, or not found.
async fn issue_gone(client: &LinearClient, id: &IssueId) -> Result<bool, String> {
    match client
        .execute_raw(
            "query($id: String!) { issue(id: $id) { id trashed archivedAt } }",
            serde_json::json!({ "id": id.as_str() }),
        )
        .await
    {
        Ok(data) => Ok(data["issue"]["trashed"].as_bool() == Some(true)
            || !data["issue"]["archivedAt"].is_null()),
        Err(err) if already_gone(&err) => Ok(true),
        Err(err) => Err(format!("issue {id}: verify fetch failed: {err}")),
    }
}

/// Re-fetches a project; gone means trashed, archived, or not found.
async fn project_gone(client: &LinearClient, id: &ProjectId) -> Result<bool, String> {
    match client
        .execute_raw(
            "query($id: String!) { project(id: $id) { id trashed archivedAt } }",
            serde_json::json!({ "id": id.as_str() }),
        )
        .await
    {
        Ok(data) => Ok(data["project"]["trashed"].as_bool() == Some(true)
            || !data["project"]["archivedAt"].is_null()),
        Err(err) if already_gone(&err) => Ok(true),
        Err(err) => Err(format!("project {id}: verify fetch failed: {err}")),
    }
}

/// Deletes every registered entity and verifies each is gone. Returns the
/// list of failures instead of panicking so a broken teardown reports every
/// stranded entity at once.
async fn cleanup(client: &LinearClient, registry: Registry) -> Vec<String> {
    let mut failures = Vec::new();

    for (relation, source) in &registry.relations {
        match client.relations().delete(relation).await {
            Ok(()) => {}
            Err(err) if already_gone(&err) => {}
            Err(err) => {
                failures.push(format!("relation {relation}: delete failed: {err}"));
                continue;
            }
        }
        match client.relations().of_issue(source).await {
            Ok(edges) => {
                let still_there = edges
                    .outgoing
                    .iter()
                    .chain(&edges.incoming)
                    .any(|edge| &edge.id == relation);
                if still_there {
                    failures.push(format!("relation {relation}: still present after delete"));
                } else {
                    eprintln!("[cleanup] relation {relation}: deleted, verified gone");
                }
            }
            Err(err) => failures.push(format!("relation {relation}: verify fetch failed: {err}")),
        }
    }

    for (comment, host) in &registry.comments {
        match client.comments().delete(comment).await {
            Ok(()) => {}
            Err(err) if already_gone(&err) => {}
            Err(err) => {
                failures.push(format!("comment {comment}: delete failed: {err}"));
                continue;
            }
        }
        let request = CommentListRequest::builder().first(50).build();
        match client.comments().list_for_issue(host, request).await {
            Ok(page) => {
                if page.nodes.iter().any(|c| &c.id == comment) {
                    failures.push(format!("comment {comment}: still listed after delete"));
                } else {
                    eprintln!("[cleanup] comment {comment}: deleted, verified gone");
                }
            }
            Err(err) => failures.push(format!("comment {comment}: verify fetch failed: {err}")),
        }
    }

    for (milestone, project) in &registry.milestones {
        match client.projects().delete_milestone(milestone).await {
            Ok(()) => {}
            Err(err) if already_gone(&err) => {}
            Err(err) => {
                failures.push(format!("milestone {milestone}: delete failed: {err}"));
                continue;
            }
        }
        match client.projects().milestones(project).await {
            Ok(milestones) => {
                if milestones.iter().any(|m| &m.id == milestone) {
                    failures.push(format!("milestone {milestone}: still listed after delete"));
                } else {
                    eprintln!("[cleanup] milestone {milestone}: deleted, verified gone");
                }
            }
            Err(err) => failures.push(format!("milestone {milestone}: verify fetch failed: {err}")),
        }
    }

    for issue in &registry.issues {
        match client.issues().delete(issue).await {
            Ok(()) => {}
            Err(err) if already_gone(&err) => {}
            Err(err) => {
                failures.push(format!("issue {issue}: delete failed: {err}"));
                continue;
            }
        }
        match issue_gone(client, issue).await {
            Ok(true) => eprintln!("[cleanup] issue {issue}: trashed, verified gone"),
            Ok(false) => failures.push(format!("issue {issue}: still live after delete")),
            Err(message) => failures.push(message),
        }
    }

    for label in &registry.labels {
        match client.labels().delete(label).await {
            Ok(()) => {}
            Err(err) if already_gone(&err) => {}
            Err(err) => {
                failures.push(format!("label {label}: delete failed: {err}"));
                continue;
            }
        }
        let request = ListLabelsRequest::builder()
            .filter(
                IssueLabelFilter::builder()
                    .id(IdComparator::builder().eq(label.to_string()).build())
                    .build(),
            )
            .build();
        match client.labels().list(request).await {
            Ok(page) => {
                if page.nodes.is_empty() {
                    eprintln!("[cleanup] label {label}: deleted, verified gone");
                } else {
                    failures.push(format!("label {label}: still listed after delete"));
                }
            }
            Err(err) => failures.push(format!("label {label}: verify fetch failed: {err}")),
        }
    }

    // The typed surface stops at `projects.archive`; trash-delete goes
    // through the raw escape hatch (this is itself a live `execute_raw`
    // mutation check).
    for project in &registry.projects {
        let deleted = client
            .execute_raw(
                "mutation($id: String!) { projectDelete(id: $id) { success } }",
                serde_json::json!({ "id": project.as_str() }),
            )
            .await;
        match deleted {
            Ok(_) => {}
            Err(err) if already_gone(&err) => {}
            Err(err) => {
                failures.push(format!("project {project}: projectDelete failed: {err}"));
                continue;
            }
        }
        match project_gone(client, project).await {
            Ok(true) => eprintln!("[cleanup] project {project}: trashed, verified gone"),
            Ok(false) => failures.push(format!("project {project}: still live after delete")),
            Err(message) => failures.push(message),
        }
    }

    failures
}

/// Runs teardown after the test body — panic or not — then reports.
async fn finish(client: &LinearClient, registry: Shared, outcome: Result<(), Box<dyn Any + Send>>) {
    let taken = std::mem::take(&mut *registry.lock().expect("registry lock"));
    let failures = cleanup(client, taken).await;
    if let Err(panic) = outcome {
        if !failures.is_empty() {
            eprintln!("cleanup failures after test panic: {failures:#?}");
        }
        std::panic::resume_unwind(panic);
    }
    assert!(failures.is_empty(), "cleanup failures: {failures:#?}");
}

fn team_issue_filter(team: &Team) -> IssueFilter {
    IssueFilter::builder()
        .team(
            TeamFilter::builder()
                .id(IdComparator::builder().eq(team.id.to_string()).build())
                .build(),
        )
        .build()
}

// ---------------------------------------------------------------------------
// Workspace reads (no mutations)
// ---------------------------------------------------------------------------

/// teams.list_stream, teams.get (UUID + key), workflow_states.list,
/// users.list, users.list_stream (seeded cursor), users.get.
#[tokio::test]
#[ignore = "live API test; requires LINEAR_API_KEY"]
async fn live_workspace_reads() {
    let Some(client) = live_client() else { return };
    let team = pick_test_team(&client).await;

    // teams.list_stream drains every page.
    let teams: Vec<Team> = client
        .teams()
        .list_stream(ListTeamsRequest::builder().first(10).build())
        .try_collect()
        .await
        .expect("teams.list_stream should drain");
    assert!(
        teams.iter().any(|t| t.id == team.id),
        "stream should include the test team"
    );
    eprintln!("[workspace] {} teams streamed", teams.len());

    // teams.get resolves both UUIDs and team keys.
    let by_id = client
        .teams()
        .get(&team.id)
        .await
        .expect("teams.get by UUID");
    assert_eq!(by_id.id, team.id);
    let by_key = client
        .teams()
        .get(&TeamId::new(team.key.clone()))
        .await
        .expect("teams.get by key");
    assert_eq!(
        by_key.id, team.id,
        "team key should resolve to the same team"
    );

    // workflow_states.list, filtered to the test team.
    let states = client
        .workflow_states()
        .list(
            ListWorkflowStatesRequest::builder()
                .filter(
                    WorkflowStateFilter::builder()
                        .team(
                            TeamFilter::builder()
                                .id(IdComparator::builder().eq(team.id.to_string()).build())
                                .build(),
                        )
                        .build(),
                )
                .first(50)
                .build(),
        )
        .await
        .expect("workflow_states.list");
    assert!(!states.nodes.is_empty(), "team should have workflow states");
    assert!(states.nodes.iter().all(|s| s.team.id == team.id));
    eprintln!(
        "[workspace] {} workflow states on {}",
        states.nodes.len(),
        team.key
    );

    // users.list + users.get.
    let page1 = client
        .users()
        .list(ListUsersRequest::builder().first(1).build())
        .await
        .expect("users.list");
    assert_eq!(page1.nodes.len(), 1);
    let first_user = &page1.nodes[0];
    let fetched = client.users().get(&first_user.id).await.expect("users.get");
    assert_eq!(fetched.id, first_user.id);
    assert!(!fetched.email.is_empty(), "user should carry an email");

    // users.list_stream honoring a caller-seeded `after` cursor.
    if page1.page_info.has_next_page {
        let cursor = page1
            .page_info
            .end_cursor
            .clone()
            .expect("page with next page should carry an end cursor");
        let two = client
            .users()
            .list(ListUsersRequest::builder().first(2).build())
            .await
            .expect("users.list first(2)");
        let seeded: Vec<_> = client
            .users()
            .list_stream(ListUsersRequest::builder().first(1).after(cursor).build())
            .take(1)
            .try_collect()
            .await
            .expect("users.list_stream seeded");
        assert_eq!(seeded.len(), 1);
        assert_eq!(
            seeded[0].id, two.nodes[1].id,
            "seeded stream should resume exactly after the cursor"
        );
        assert_ne!(seeded[0].id, first_user.id);
    } else {
        let all: Vec<_> = client
            .users()
            .list_stream(ListUsersRequest::builder().first(1).build())
            .try_collect()
            .await
            .expect("users.list_stream");
        assert_eq!(all.len(), 1, "single-user workspace");
    }
}

// ---------------------------------------------------------------------------
// Labels
// ---------------------------------------------------------------------------

/// labels.create → list_stream verify → update (set + Undefinable::Null
/// clear) → ensure (create, then find-not-duplicate) → delete → verify gone.
#[tokio::test]
#[ignore = "live mutation test; requires LINEAR_API_KEY"]
async fn live_label_lifecycle() {
    let Some(client) = live_client() else { return };
    let team = pick_test_team(&client).await;
    let registry: Shared = Arc::default();

    let body = {
        let client = client.clone();
        let registry = registry.clone();
        let team = team.clone();
        async move {
            let marker = format!("[sdk-smoke] {}", stamp());

            // create
            let name = format!("{marker} label");
            let label = client
                .labels()
                .create(
                    LabelCreateInput::builder()
                        .name(name.clone())
                        .color("#5E6AD2")
                        .description(MARKER_DESCRIPTION)
                        .team_id(team.id.clone())
                        .build(),
                )
                .await
                .expect("labels.create");
            track(&registry, |r| r.labels.push(label.id.clone()));
            eprintln!("[created] label {} ({})", label.id, label.name);
            assert_eq!(label.name, name);
            assert_eq!(label.description.as_deref(), Some(MARKER_DESCRIPTION));
            assert_eq!(
                label.team.as_ref().map(|t| &t.id),
                Some(&team.id),
                "label should be scoped to the test team"
            );

            // verify via list_stream (exact-name filter)
            let listed: Vec<_> = client
                .labels()
                .list_stream(
                    ListLabelsRequest::builder()
                        .filter(
                            IssueLabelFilter::builder()
                                .name(StringComparator::builder().eq(name.clone()).build())
                                .build(),
                        )
                        .first(10)
                        .build(),
                )
                .try_collect()
                .await
                .expect("labels.list_stream");
            assert_eq!(listed.len(), 1, "exactly the created label should match");
            assert_eq!(listed[0].id, label.id);

            // update: set color + description
            let updated = client
                .labels()
                .update(
                    &label.id,
                    LabelUpdateInput::builder()
                        .color("#26B5CE")
                        .description(format!("updated — {MARKER_DESCRIPTION}"))
                        .build(),
                )
                .await
                .expect("labels.update set");
            assert_eq!(updated.color.to_uppercase(), "#26B5CE");
            assert_eq!(
                updated.description.as_deref(),
                Some(format!("updated — {MARKER_DESCRIPTION}").as_str())
            );

            // update: rename + clear the description (tri-state Null)
            let renamed = format!("{marker} label (renamed)");
            let cleared = client
                .labels()
                .update(
                    &label.id,
                    LabelUpdateInput::builder()
                        .name(renamed.clone())
                        .description(Undefinable::Null)
                        .build(),
                )
                .await
                .expect("labels.update clear");
            assert_eq!(cleared.name, renamed);
            assert!(
                cleared.description.as_deref().unwrap_or("").is_empty(),
                "Undefinable::Null should clear the description, got {:?}",
                cleared.description
            );
            assert_eq!(
                cleared.color.to_uppercase(),
                "#26B5CE",
                "omitted (Undefined) fields should stay unchanged"
            );

            // ensure: first call creates…
            let ensure_name = format!("{marker} ensure");
            let ensured = client
                .labels()
                .ensure(Some(&team.id), &ensure_name)
                .await
                .expect("labels.ensure (create path)");
            track(&registry, |r| r.labels.push(ensured.id.clone()));
            eprintln!("[created] label {} ({})", ensured.id, ensured.name);
            assert_eq!(ensured.name, ensure_name);
            // …second call finds the same label instead of duplicating.
            let again = client
                .labels()
                .ensure(Some(&team.id), &ensure_name)
                .await
                .expect("labels.ensure (find path)");
            assert_eq!(
                again.id, ensured.id,
                "ensure should find the existing label, not duplicate it"
            );

            // delete + verify gone (registry re-verifies as a backstop)
            client
                .labels()
                .delete(&label.id)
                .await
                .expect("labels.delete");
            let after: Vec<_> = client
                .labels()
                .list_stream(
                    ListLabelsRequest::builder()
                        .filter(
                            IssueLabelFilter::builder()
                                .id(IdComparator::builder().eq(label.id.to_string()).build())
                                .build(),
                        )
                        .build(),
                )
                .try_collect()
                .await
                .expect("labels.list_stream after delete");
            assert!(after.is_empty(), "deleted label should not be listed");
        }
    };

    let outcome = AssertUnwindSafe(Box::pin(body)).catch_unwind().await;
    finish(&client, registry, outcome).await;
}

// ---------------------------------------------------------------------------
// Issues
// ---------------------------------------------------------------------------

/// issues.create → get (UUID + identifier) → update (set + Undefinable::Null
/// clear) → batch_create → list_stream (full + seeded cursor) →
/// add_label/remove_label → search → archive → delete → verify gone.
///
/// The lifecycle is split into `Box::pin`ned phase futures: a single giant
/// async block overflows the default test stack in debug builds (unoptimized
/// async state machines produce huge poll frames); boxing each phase keeps
/// every frame small.
#[tokio::test]
#[ignore = "live mutation test; requires LINEAR_API_KEY"]
async fn live_issue_lifecycle() {
    let Some(client) = live_client() else { return };
    let team = pick_test_team(&client).await;
    let registry: Shared = Arc::default();

    let body = {
        let client = client.clone();
        let registry = registry.clone();
        let team = team.clone();
        async move {
            let run_stamp = stamp();
            let marker = format!("[sdk-smoke] {run_stamp}");
            let alpha = Box::pin(issue_crud_phase(&client, &registry, &team, &marker)).await;
            let beta = Box::pin(issue_batch_stream_phase(
                &client, &registry, &team, &marker, &alpha,
            ))
            .await;
            Box::pin(issue_label_phase(
                &client, &registry, &team, &marker, &alpha,
            ))
            .await;
            Box::pin(issue_search_phase(&client, run_stamp, &alpha)).await;
            Box::pin(issue_archive_delete_phase(&client, &beta)).await;
        }
    };

    let outcome = AssertUnwindSafe(Box::pin(body)).catch_unwind().await;
    finish(&client, registry, outcome).await;
}

/// issues.create → issues.get (UUID + human identifier) → issues.update
/// (set, then tri-state clear). Returns the created issue.
async fn issue_crud_phase(
    client: &LinearClient,
    registry: &Shared,
    team: &Team,
    marker: &str,
) -> Issue {
    // create
    let alpha = client
        .issues()
        .create(
            IssueCreateInput::builder()
                .team_id(team.id.clone())
                .title(format!("{marker} issue alpha"))
                .description(MARKER_DESCRIPTION)
                .priority(Priority::Low)
                .build(),
        )
        .await
        .expect("issues.create");
    track(registry, |r| r.issues.push(alpha.id.clone()));
    eprintln!("[created] issue {} ({})", alpha.id, alpha.identifier);
    assert_eq!(alpha.title, format!("{marker} issue alpha"));
    assert_eq!(alpha.team.id, team.id);
    assert_eq!(alpha.priority, Priority::Low);
    assert_eq!(alpha.description.as_deref(), Some(MARKER_DESCRIPTION));

    // get by UUID and by human identifier
    let by_id = client
        .issues()
        .get(&alpha.id)
        .await
        .expect("issues.get by UUID");
    assert_eq!(by_id.id, alpha.id);
    let by_identifier = client
        .issues()
        .get(IssueRef::identifier(alpha.identifier.clone()))
        .await
        .expect("issues.get by identifier");
    assert_eq!(
        by_identifier.id, alpha.id,
        "identifier should resolve to the same issue"
    );

    // update: set title/description/due date
    let renamed = format!("{marker} issue alpha (renamed)");
    let due: TimelessDate = "2030-01-02".parse().expect("valid date");
    let updated = client
        .issues()
        .update(
            &alpha.id,
            IssueUpdateInput::builder()
                .title(renamed.clone())
                .description(format!("updated — {MARKER_DESCRIPTION}"))
                .due_date(due)
                .build(),
        )
        .await
        .expect("issues.update set");
    assert_eq!(updated.title, renamed);
    assert_eq!(updated.due_date, Some(due), "due date should be set");
    assert_eq!(
        updated.description.as_deref(),
        Some(format!("updated — {MARKER_DESCRIPTION}").as_str())
    );

    // update: tri-state clear — Null clears, Undefined leaves alone.
    // Live-verified server quirk (2026-07-05, also confirmed with raw
    // GraphQL): `description: null` is IGNORED for the document-backed
    // description field, while `dueDate: null` clears normally.
    let cleared = client
        .issues()
        .update(
            &alpha.id,
            IssueUpdateInput::builder()
                .description(Undefinable::Null)
                .due_date(Undefinable::Null)
                .build(),
        )
        .await
        .expect("issues.update clear");
    assert_eq!(
        cleared.title, renamed,
        "omitted (Undefined) fields should stay unchanged"
    );
    assert!(
        cleared.due_date.is_none(),
        "Undefinable::Null should clear dueDate"
    );
    assert_eq!(
        cleared.description.as_deref(),
        Some(format!("updated — {MARKER_DESCRIPTION}").as_str()),
        "Linear ignores `description: null` (document-backed field)"
    );
    // Clearing the description takes an empty string instead.
    let desc_cleared = client
        .issues()
        .update(
            &alpha.id,
            IssueUpdateInput::builder()
                .description(String::new())
                .build(),
        )
        .await
        .expect("issues.update clear description via empty string");
    assert!(
        desc_cleared.description.as_deref().unwrap_or("").is_empty(),
        "an empty string should clear the description, got {:?}",
        desc_cleared.description
    );

    alpha
}

/// issues.batch_create → issues.list_stream (full drain + caller-seeded
/// cursor). Returns the id of the first batch issue ("beta").
async fn issue_batch_stream_phase(
    client: &LinearClient,
    registry: &Shared,
    team: &Team,
    marker: &str,
    alpha: &Issue,
) -> IssueId {
    // batch_create: two issues in one transaction, order preserved
    let batch = client
        .issues()
        .batch_create(vec![
            IssueCreateInput::builder()
                .team_id(team.id.clone())
                .title(format!("{marker} issue beta"))
                .description(MARKER_DESCRIPTION)
                .build(),
            IssueCreateInput::builder()
                .team_id(team.id.clone())
                .title(format!("{marker} issue gamma"))
                .description(MARKER_DESCRIPTION)
                .build(),
        ])
        .await
        .expect("issues.batch_create");
    assert_eq!(batch.len(), 2);
    for issue in &batch {
        track(registry, |r| r.issues.push(issue.id.clone()));
        eprintln!("[created] issue {} ({})", issue.id, issue.identifier);
        assert_eq!(issue.team.id, team.id);
    }
    assert_eq!(
        batch[0].title,
        format!("{marker} issue beta"),
        "batch_create should preserve input order"
    );
    assert_eq!(batch[1].title, format!("{marker} issue gamma"));
    let beta = batch[0].id.clone();
    let gamma = batch[1].id.clone();

    // list_stream: full drain (page size 1 forces pagination)…
    let filter = team_issue_filter(team);
    let all: Vec<_> = client
        .issues()
        .list_stream(
            ListIssuesRequest::builder()
                .filter(filter.clone())
                .first(1)
                .build(),
        )
        .try_collect()
        .await
        .expect("issues.list_stream");
    assert!(all.len() >= 3, "the three created issues should be live");
    for wanted in [&alpha.id, &beta, &gamma] {
        assert!(
            all.iter().any(|i| &i.id == wanted),
            "stream should contain created issue {wanted}"
        );
    }
    // …and a caller-seeded cursor resuming exactly after page 1.
    let page1 = client
        .issues()
        .list(
            ListIssuesRequest::builder()
                .filter(filter.clone())
                .first(1)
                .build(),
        )
        .await
        .expect("issues.list page 1");
    assert_eq!(page1.nodes.len(), 1);
    assert!(page1.page_info.has_next_page);
    assert_eq!(all[0].id, page1.nodes[0].id);
    let cursor = page1.page_info.end_cursor.clone().expect("end cursor");
    let seeded: Vec<_> = client
        .issues()
        .list_stream(
            ListIssuesRequest::builder()
                .filter(filter)
                .first(1)
                .after(cursor)
                .build(),
        )
        .try_collect()
        .await
        .expect("issues.list_stream seeded");
    let seeded_ids: Vec<_> = seeded.iter().map(|i| i.id.clone()).collect();
    let tail_ids: Vec<_> = all[1..].iter().map(|i| i.id.clone()).collect();
    assert_eq!(
        seeded_ids, tail_ids,
        "seeded stream should resume exactly after page 1"
    );

    beta
}

/// labels.create → issues.add_label → issues.remove_label.
async fn issue_label_phase(
    client: &LinearClient,
    registry: &Shared,
    team: &Team,
    marker: &str,
    alpha: &Issue,
) {
    let label = client
        .labels()
        .create(
            LabelCreateInput::builder()
                .name(format!("{marker} issue-label"))
                .color("#5E6AD2")
                .description(MARKER_DESCRIPTION)
                .team_id(team.id.clone())
                .build(),
        )
        .await
        .expect("labels.create (for add_label)");
    track(registry, |r| r.labels.push(label.id.clone()));
    eprintln!("[created] label {} ({})", label.id, label.name);
    let with_label = client
        .issues()
        .add_label(&alpha.id, &label.id)
        .await
        .expect("issues.add_label");
    assert!(
        with_label.labels.iter().any(|l| l.id == label.id),
        "issue should carry the added label"
    );
    let without_label = client
        .issues()
        .remove_label(&alpha.id, &label.id)
        .await
        .expect("issues.remove_label");
    assert!(
        without_label.labels.iter().all(|l| l.id != label.id),
        "issue should no longer carry the removed label"
    );
    let refetched = client.issues().get(&alpha.id).await.expect("issues.get");
    assert!(refetched.labels.iter().all(|l| l.id != label.id));
}

/// issues.search — the full-text index lags creation; the call itself (wire
/// format + decode) is verified even when the fresh issue is not indexed yet.
async fn issue_search_phase(client: &LinearClient, run_stamp: u64, alpha: &Issue) {
    let term = format!("sdk-smoke {run_stamp}");
    let mut found = false;
    for attempt in 1..=4u32 {
        let hits = client
            .issues()
            .search(
                SearchIssuesRequest::builder()
                    .term(term.clone())
                    .first(10)
                    .build(),
            )
            .await
            .expect("issues.search");
        eprintln!("[search] attempt {attempt}: {} hit(s)", hits.nodes.len());
        if hits.nodes.iter().any(|hit| hit.id == alpha.id) {
            found = true;
            break;
        }
        tokio::time::sleep(Duration::from_secs(5)).await;
    }
    if !found {
        eprintln!("[search] created issue not indexed yet — searchIssues call itself verified");
    }
}

/// issues.archive → verify archivedAt → issues.delete → verify trashed.
async fn issue_archive_delete_phase(client: &LinearClient, beta: &IssueId) {
    client.issues().archive(beta).await.expect("issues.archive");
    let archived = client
        .issues()
        .get(beta)
        .await
        .expect("issues.get on archived issue");
    assert!(
        archived.archived_at.is_some(),
        "archive should set archivedAt"
    );

    client.issues().delete(beta).await.expect("issues.delete");
    assert_eq!(
        issue_gone(client, beta).await,
        Ok(true),
        "deleted issue should be trashed"
    );
}

// ---------------------------------------------------------------------------
// Relations
// ---------------------------------------------------------------------------

/// relations.create (Related, via human identifiers) → of_issue verify →
/// delete → create_blocks (via UUIDs) → blocks()/blocked_by() in **both**
/// directions → delete → verify gone.
#[tokio::test]
#[ignore = "live mutation test; requires LINEAR_API_KEY"]
async fn live_relation_lifecycle() {
    let Some(client) = live_client() else { return };
    let team = pick_test_team(&client).await;
    let registry: Shared = Arc::default();

    let body = {
        let client = client.clone();
        let registry = registry.clone();
        let team = team.clone();
        async move {
            let marker = format!("[sdk-smoke] {}", stamp());
            let pair = client
                .issues()
                .batch_create(vec![
                    IssueCreateInput::builder()
                        .team_id(team.id.clone())
                        .title(format!("{marker} relation source"))
                        .description(MARKER_DESCRIPTION)
                        .build(),
                    IssueCreateInput::builder()
                        .team_id(team.id.clone())
                        .title(format!("{marker} relation target"))
                        .description(MARKER_DESCRIPTION)
                        .build(),
                ])
                .await
                .expect("issues.batch_create (relation hosts)");
            let source = pair[0].clone();
            let target = pair[1].clone();
            for issue in &pair {
                track(&registry, |r| r.issues.push(issue.id.clone()));
                eprintln!("[created] issue {} ({})", issue.id, issue.identifier);
            }

            // Related edge, created through human identifiers.
            let related = client
                .relations()
                .create(
                    IssueRef::identifier(source.identifier.clone()),
                    IssueRef::identifier(target.identifier.clone()),
                    IssueRelationType::Related,
                )
                .await
                .expect("relations.create");
            track(&registry, |r| {
                r.relations.push((related.id.clone(), source.id.clone()));
            });
            eprintln!("[created] relation {} (related)", related.id);
            assert_eq!(related.relation_type, IssueRelationType::Related);
            assert_eq!(related.issue.id, source.id);
            assert_eq!(related.related_issue.id, target.id);
            let edges = client
                .relations()
                .of_issue(&source.id)
                .await
                .expect("relations.of_issue");
            assert!(edges.outgoing.iter().any(|e| e.id == related.id));

            // delete → verify the edge disappears from both sides
            client
                .relations()
                .delete(&related.id)
                .await
                .expect("relations.delete");
            let edges = client
                .relations()
                .of_issue(&source.id)
                .await
                .expect("relations.of_issue after delete");
            assert!(
                edges.outgoing.iter().all(|e| e.id != related.id),
                "deleted relation should disappear"
            );

            // Blocks edge, created through UUIDs; direction is positional.
            let blocks = client
                .relations()
                .create_blocks(&source.id, &target.id)
                .await
                .expect("relations.create_blocks");
            track(&registry, |r| {
                r.relations.push((blocks.id.clone(), source.id.clone()));
            });
            eprintln!("[created] relation {} (blocks)", blocks.id);
            assert_eq!(blocks.relation_type, IssueRelationType::Blocks);
            assert_eq!(blocks.issue.id, source.id);
            assert_eq!(blocks.related_issue.id, target.id);

            // Both direction views against the live wire format:
            let source_edges = client
                .relations()
                .of_issue(&source.id)
                .await
                .expect("relations.of_issue (blocker)");
            assert!(
                source_edges.blocks().iter().any(|s| s.id == target.id),
                "blocker's blocks() should contain the blocked issue"
            );
            let target_edges = client
                .relations()
                .of_issue(&target.id)
                .await
                .expect("relations.of_issue (blocked)");
            assert!(
                target_edges.blocked_by().iter().any(|s| s.id == source.id),
                "blocked issue's blocked_by() should contain the blocker"
            );

            // delete → verify both directions are empty again
            client
                .relations()
                .delete(&blocks.id)
                .await
                .expect("relations.delete (blocks)");
            let source_edges = client
                .relations()
                .of_issue(&source.id)
                .await
                .expect("relations.of_issue after blocks delete");
            assert!(source_edges.blocks().is_empty());
            let target_edges = client
                .relations()
                .of_issue(&target.id)
                .await
                .expect("relations.of_issue after blocks delete (target)");
            assert!(target_edges.blocked_by().is_empty());
        }
    };

    let outcome = AssertUnwindSafe(Box::pin(body)).catch_unwind().await;
    finish(&client, registry, outcome).await;
}

// ---------------------------------------------------------------------------
// Comments
// ---------------------------------------------------------------------------

/// comments.create → create_on → threaded create (parent_id) →
/// list_for_issue verify → update → list_for_issue_stream (page size 1) →
/// delete → verify gone.
#[tokio::test]
#[ignore = "live mutation test; requires LINEAR_API_KEY"]
async fn live_comment_lifecycle() {
    let Some(client) = live_client() else { return };
    let team = pick_test_team(&client).await;
    let registry: Shared = Arc::default();

    let body = {
        let client = client.clone();
        let registry = registry.clone();
        let team = team.clone();
        async move {
            let marker = format!("[sdk-smoke] {}", stamp());
            let host = client
                .issues()
                .create(
                    IssueCreateInput::builder()
                        .team_id(team.id.clone())
                        .title(format!("{marker} comment host"))
                        .description(MARKER_DESCRIPTION)
                        .build(),
                )
                .await
                .expect("issues.create (comment host)");
            track(&registry, |r| r.issues.push(host.id.clone()));
            eprintln!("[created] issue {} ({})", host.id, host.identifier);

            // create (explicit input)
            let root = client
                .comments()
                .create(
                    CommentCreateInput::builder()
                        .issue_id(host.id.to_string())
                        .body(format!("{marker} root comment — {MARKER_DESCRIPTION}"))
                        .build(),
                )
                .await
                .expect("comments.create");
            track(&registry, |r| {
                r.comments.push((root.id.clone(), host.id.clone()));
            });
            eprintln!("[created] comment {} (root)", root.id);
            assert!(root.parent.is_none());
            assert!(root.body.contains("root comment"));

            // create_on (convenience wrapper)
            let second = client
                .comments()
                .create_on(
                    &host.id,
                    format!("{marker} second comment — {MARKER_DESCRIPTION}"),
                )
                .await
                .expect("comments.create_on");
            track(&registry, |r| {
                r.comments.push((second.id.clone(), host.id.clone()));
            });
            eprintln!("[created] comment {} (create_on)", second.id);

            // threaded reply via parent_id
            let reply = client
                .comments()
                .create(
                    CommentCreateInput::builder()
                        .issue_id(host.id.to_string())
                        .body(format!("{marker} threaded reply — {MARKER_DESCRIPTION}"))
                        .parent_id(root.id.clone())
                        .build(),
                )
                .await
                .expect("comments.create (threaded)");
            track(&registry, |r| {
                r.comments.push((reply.id.clone(), host.id.clone()));
            });
            eprintln!("[created] comment {} (reply to {})", reply.id, root.id);
            assert_eq!(
                reply.parent.as_ref().map(|p| &p.id),
                Some(&root.id),
                "threaded reply should carry its parent id"
            );

            // list_for_issue sees all three, threading intact
            let page = client
                .comments()
                .list_for_issue(&host.id, CommentListRequest::builder().first(50).build())
                .await
                .expect("comments.list_for_issue");
            for wanted in [&root.id, &second.id, &reply.id] {
                assert!(
                    page.nodes.iter().any(|c| &c.id == wanted),
                    "thread should contain comment {wanted}"
                );
            }
            let listed_reply = page
                .nodes
                .iter()
                .find(|c| c.id == reply.id)
                .expect("reply should be listed");
            assert_eq!(listed_reply.parent.as_ref().map(|p| &p.id), Some(&root.id));

            // update
            let new_body = format!("{marker} threaded reply (edited) — {MARKER_DESCRIPTION}");
            let edited = client
                .comments()
                .update(&reply.id, new_body.clone())
                .await
                .expect("comments.update");
            assert_eq!(edited.body, new_body);

            // list_for_issue_stream with page size 1 (forces pagination)
            let streamed: Vec<_> = client
                .comments()
                .list_for_issue_stream(&host.id, CommentListRequest::builder().first(1).build())
                .try_collect()
                .await
                .expect("comments.list_for_issue_stream");
            assert!(streamed.len() >= 3);
            let streamed_reply = streamed
                .iter()
                .find(|c| c.id == reply.id)
                .expect("stream should contain the reply");
            assert_eq!(streamed_reply.body, new_body, "update should persist");

            // delete → verify it leaves the thread
            client
                .comments()
                .delete(&reply.id)
                .await
                .expect("comments.delete");
            let after = client
                .comments()
                .list_for_issue(&host.id, CommentListRequest::builder().first(50).build())
                .await
                .expect("comments.list_for_issue after delete");
            assert!(
                after.nodes.iter().all(|c| c.id != reply.id),
                "deleted comment should leave the thread"
            );
        }
    };

    let outcome = AssertUnwindSafe(Box::pin(body)).catch_unwind().await;
    finish(&client, registry, outcome).await;
}

// ---------------------------------------------------------------------------
// Projects & milestones
// ---------------------------------------------------------------------------

/// projects.statuses → create → get → list_stream → update (set +
/// Undefinable::Null clear) → create_milestone → milestones →
/// update_milestone (set + clear) → delete_milestone → archive →
/// trash-delete via execute_raw → verify gone.
///
/// Split into `Box::pin`ned phases for the same debug-build stack reasons as
/// [`live_issue_lifecycle`].
#[tokio::test]
#[ignore = "live mutation test; requires LINEAR_API_KEY"]
async fn live_project_lifecycle() {
    let Some(client) = live_client() else { return };
    let team = pick_test_team(&client).await;
    let registry: Shared = Arc::default();

    let body = {
        let client = client.clone();
        let registry = registry.clone();
        let team = team.clone();
        async move {
            let marker = format!("[sdk-smoke] {}", stamp());
            let project = Box::pin(project_create_phase(&client, &registry, &team, &marker)).await;
            Box::pin(project_update_phase(&client, &project, &marker)).await;
            Box::pin(project_milestone_phase(
                &client, &registry, &project, &marker,
            ))
            .await;
            Box::pin(project_archive_phase(&client, &project)).await;
        }
    };

    let outcome = AssertUnwindSafe(Box::pin(body)).catch_unwind().await;
    finish(&client, registry, outcome).await;
}

/// projects.statuses → projects.create → projects.get → projects.list_stream.
/// Returns the created project's id.
async fn project_create_phase(
    client: &LinearClient,
    registry: &Shared,
    team: &Team,
    marker: &str,
) -> ProjectId {
    // statuses (workspace-level read)
    let statuses = client
        .projects()
        .statuses()
        .await
        .expect("projects.statuses");
    assert!(
        !statuses.is_empty(),
        "workspace should define project statuses"
    );
    eprintln!("[projects] {} workspace project statuses", statuses.len());

    // create
    let name = format!("{marker} project");
    let project = client
        .projects()
        .create(
            ProjectCreateInput::builder()
                .name(name.clone())
                .team_ids(vec![team.id.clone()])
                .description(MARKER_DESCRIPTION.to_owned())
                .build(),
        )
        .await
        .expect("projects.create");
    track(registry, |r| r.projects.push(project.id.clone()));
    eprintln!("[created] project {} ({})", project.id, project.name);
    assert_eq!(project.name, name);
    assert!(project.teams.iter().any(|t| t.id == team.id));
    assert_eq!(project.description, MARKER_DESCRIPTION);

    // get
    let fetched = client
        .projects()
        .get(&project.id)
        .await
        .expect("projects.get");
    assert_eq!(fetched.id, project.id);
    assert_eq!(fetched.name, name);

    // list_stream (exact-name filter)
    let listed: Vec<_> = client
        .projects()
        .list_stream(
            ListProjectsRequest::builder()
                .filter(
                    ProjectFilter::builder()
                        .name(StringComparator::builder().eq(name.clone()).build())
                        .build(),
                )
                .first(1)
                .build(),
        )
        .try_collect()
        .await
        .expect("projects.list_stream");
    assert!(
        listed.iter().any(|p| p.id == project.id),
        "stream should find the created project by name"
    );

    project.id
}

/// projects.update: set name/description/content/target date, then tri-state
/// clear.
async fn project_update_phase(client: &LinearClient, project: &ProjectId, marker: &str) {
    let renamed = format!("{marker} project (renamed)");
    let target: TimelessDate = "2030-06-30".parse().expect("valid date");
    let updated = client
        .projects()
        .update(
            project,
            ProjectUpdateInput::builder()
                .name(renamed.clone())
                .description(format!("updated — {MARKER_DESCRIPTION}"))
                .content(format!("Long-form content. {MARKER_DESCRIPTION}"))
                .target_date(target)
                .build(),
        )
        .await
        .expect("projects.update set");
    assert_eq!(updated.name, renamed);
    assert_eq!(updated.target_date, Some(target));
    assert!(
        updated
            .content
            .as_deref()
            .unwrap_or("")
            .contains("Long-form"),
        "content should be set"
    );

    // update: tri-state clear.
    // Live-verified server quirk (2026-07-05, also confirmed with raw
    // GraphQL): `content: null` — and even `content: ""` — is IGNORED
    // for the document-backed content field; `targetDate: null`
    // clears normally.
    let cleared = client
        .projects()
        .update(
            project,
            ProjectUpdateInput::builder()
                .target_date(Undefinable::Null)
                .content(Undefinable::Null)
                .build(),
        )
        .await
        .expect("projects.update clear");
    assert_eq!(
        cleared.name, renamed,
        "omitted fields should stay unchanged"
    );
    assert!(
        cleared.target_date.is_none(),
        "Null should clear targetDate"
    );
    assert!(
        cleared
            .content
            .as_deref()
            .unwrap_or("")
            .contains("Long-form"),
        "Linear ignores `content: null` (document-backed field), got {:?}",
        cleared.content
    );
}

/// projects.create_milestone → projects.milestones → projects.update_milestone
/// (set, then tri-state clear) → projects.delete_milestone → verify gone.
async fn project_milestone_phase(
    client: &LinearClient,
    registry: &Shared,
    project: &ProjectId,
    marker: &str,
) {
    // milestone: create
    let milestone_target: TimelessDate = "2030-03-31".parse().expect("valid date");
    let milestone = client
        .projects()
        .create_milestone(
            ProjectMilestoneCreateInput::builder()
                .project_id(project.clone())
                .name(format!("{marker} milestone"))
                .description(MARKER_DESCRIPTION.to_owned())
                .target_date(milestone_target)
                .build(),
        )
        .await
        .expect("projects.create_milestone");
    track(registry, |r| {
        r.milestones.push((milestone.id.clone(), project.clone()));
    });
    eprintln!("[created] milestone {} ({})", milestone.id, milestone.name);
    assert_eq!(milestone.target_date, Some(milestone_target));

    // milestone: list
    let milestones = client
        .projects()
        .milestones(project)
        .await
        .expect("projects.milestones");
    assert!(
        milestones
            .iter()
            .any(|m| m.id == milestone.id && m.target_date == Some(milestone_target)),
        "milestones should list the created milestone"
    );

    // milestone: update set, then tri-state clear
    let milestone_renamed = format!("{marker} milestone (renamed)");
    let ms_updated = client
        .projects()
        .update_milestone(
            &milestone.id,
            ProjectMilestoneUpdateInput::builder()
                .name(milestone_renamed.clone())
                .description(format!("updated — {MARKER_DESCRIPTION}"))
                .build(),
        )
        .await
        .expect("projects.update_milestone set");
    assert_eq!(ms_updated.name, milestone_renamed);
    // Live-verified server quirk (2026-07-05, also confirmed with raw
    // GraphQL): milestone `description: null` — and even `""` — is
    // IGNORED (document-backed field); `targetDate: null` clears
    // normally.
    let ms_cleared = client
        .projects()
        .update_milestone(
            &milestone.id,
            ProjectMilestoneUpdateInput::builder()
                .description(Undefinable::Null)
                .target_date(Undefinable::Null)
                .build(),
        )
        .await
        .expect("projects.update_milestone clear");
    assert_eq!(ms_cleared.name, milestone_renamed);
    assert_eq!(
        ms_cleared.description.as_deref(),
        Some(format!("updated — {MARKER_DESCRIPTION}").as_str()),
        "Linear ignores milestone `description: null` (document-backed field)"
    );
    assert!(
        ms_cleared.target_date.is_none(),
        "Null should clear targetDate"
    );

    // milestone: delete → verify gone
    client
        .projects()
        .delete_milestone(&milestone.id)
        .await
        .expect("projects.delete_milestone");
    let remaining = client
        .projects()
        .milestones(project)
        .await
        .expect("projects.milestones after delete");
    assert!(
        remaining.iter().all(|m| m.id != milestone.id),
        "deleted milestone should disappear"
    );
}

/// projects.archive → verify archivedAt. The trash-delete happens in cleanup
/// via the execute_raw projectDelete fallback.
async fn project_archive_phase(client: &LinearClient, project: &ProjectId) {
    client
        .projects()
        .archive(project)
        .await
        .expect("projects.archive");
    let archived = client
        .projects()
        .get(project)
        .await
        .expect("projects.get on archived project");
    assert!(
        archived.archived_at.is_some(),
        "archive should set archivedAt"
    );
}