onetaskgraph-plugin-api 0.2.21

The plugin contract onetaskgraph sources implement: the traits, the work types, and the capability declaration.
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
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
//! The contract, exercised the way a plugin author meets it.
//!
//! These drive the public surface — the traits through `dyn`, the newtypes through
//! their real constructors, the work types through serde — rather than asserting on
//! internals, because that surface is what six other crates are written against.

use chrono::{TimeZone as _, Utc};
use onetaskgraph_plugin_api::{
    Capabilities, Cursor, DependencyEdge, DependencyKind, DependencySupport, Direction, Document,
    DocumentQuery, Health, ItemKind, ItemWrite, Label, LabelFilter, Location, NativeId, Page,
    PageRequest, Project, ProjectFilter, ProjectQuery, SOURCE_NAME_PATTERN, SecretResolver,
    SourceError, SourceName, SourcePlugin, Status, StatusCategory, Support, Task, TaskQuery,
    TaskSource, TextFields, TextQuery, WriteSupport,
};
use schemars::{Schema, schema_for};
use secrecy::{ExposeSecret as _, SecretString};

/// A source that answers everything emptily. Enough to prove the trait is usable
/// through `dyn`, which is the property the engine's `Vec<Box<dyn TaskSource>>`
/// depends on.
struct Silent(&'static str);

#[async_trait::async_trait]
impl TaskSource for Silent {
    fn kind(&self) -> &'static str {
        self.0
    }
    fn capabilities(&self) -> Capabilities {
        Capabilities {
            projects: Support::Native,
            documents: Support::Unsupported,
            orphan_tasks: Support::Native,
            filter_by_label: Support::Unsupported,
            filter_by_status: Support::Native,
            search_title: Support::Native,
            search_content: Support::Unsupported,
            task_dependencies: DependencySupport::ForwardOnly,
            project_dependencies: DependencySupport::BothDirections,
            max_page_size: 25,
        }
    }
    async fn health(&self) -> Result<Health, SourceError> {
        Ok(Health {
            reachable: true,
            detail: None,
        })
    }
    async fn get_task(&self, _id: &NativeId) -> Result<Option<Task>, SourceError> {
        Ok(None)
    }
    async fn get_project(&self, _id: &NativeId) -> Result<Option<Project>, SourceError> {
        Ok(None)
    }
    async fn query_tasks(
        &self,
        _query: &TaskQuery,
        _page: &PageRequest,
    ) -> Result<Page<Task>, SourceError> {
        Ok(Page::last(Vec::new()))
    }
    async fn query_projects(
        &self,
        _query: &ProjectQuery,
        _page: &PageRequest,
    ) -> Result<Page<Project>, SourceError> {
        Ok(Page::last(Vec::new()))
    }
    async fn labels(&self, _page: &PageRequest) -> Result<Page<Label>, SourceError> {
        Ok(Page::last(Vec::new()))
    }
    async fn task_dependencies(
        &self,
        _id: &NativeId,
        _direction: Direction,
        _page: &PageRequest,
    ) -> Result<Page<DependencyEdge>, SourceError> {
        Ok(Page::last(Vec::new()))
    }
    async fn project_dependencies(
        &self,
        _id: &NativeId,
        _direction: Direction,
        _page: &PageRequest,
    ) -> Result<Page<DependencyEdge>, SourceError> {
        Ok(Page::last(Vec::new()))
    }
}

/// A second, unrelated implementation, so the collection below is genuinely
/// heterogeneous rather than one type twice.
struct Refusing;

#[async_trait::async_trait]
impl TaskSource for Refusing {
    fn kind(&self) -> &'static str {
        "refusing"
    }
    fn capabilities(&self) -> Capabilities {
        Silent("x").capabilities()
    }
    async fn health(&self) -> Result<Health, SourceError> {
        Err(SourceError::Unavailable {
            message: "no route to host".to_owned(),
        })
    }
    async fn get_task(&self, _id: &NativeId) -> Result<Option<Task>, SourceError> {
        Err(SourceError::RateLimited {
            retry_after_seconds: Some(30),
            message: None,
        })
    }
    async fn get_project(&self, _id: &NativeId) -> Result<Option<Project>, SourceError> {
        Ok(None)
    }
    async fn query_tasks(
        &self,
        _query: &TaskQuery,
        _page: &PageRequest,
    ) -> Result<Page<Task>, SourceError> {
        Ok(Page::last(Vec::new()))
    }
    async fn query_projects(
        &self,
        _query: &ProjectQuery,
        _page: &PageRequest,
    ) -> Result<Page<Project>, SourceError> {
        Ok(Page::last(Vec::new()))
    }
    async fn labels(&self, _page: &PageRequest) -> Result<Page<Label>, SourceError> {
        Ok(Page::last(Vec::new()))
    }
    async fn task_dependencies(
        &self,
        _id: &NativeId,
        _direction: Direction,
        _page: &PageRequest,
    ) -> Result<Page<DependencyEdge>, SourceError> {
        Ok(Page::last(Vec::new()))
    }
    async fn project_dependencies(
        &self,
        _id: &NativeId,
        _direction: Direction,
        _page: &PageRequest,
    ) -> Result<Page<DependencyEdge>, SourceError> {
        Ok(Page::last(Vec::new()))
    }
}

#[tokio::test]
async fn the_engine_can_hold_a_heterogeneous_collection_of_boxed_sources() {
    // This is what dyn-compatibility buys, and the only reason it is a
    // requirement: the engine fans one query out over sources of different types.
    let sources: Vec<Box<dyn TaskSource>> = vec![Box::new(Silent("silent")), Box::new(Refusing)];

    let kinds: Vec<&str> = sources.iter().map(|source| source.kind()).collect();
    assert_eq!(kinds, ["silent", "refusing"]);

    let health: Vec<bool> = {
        let mut out = Vec::new();
        for source in &sources {
            out.push(source.health().await.is_ok());
        }
        out
    };
    assert_eq!(health, [true, false]);

    let page = PageRequest {
        cursor: None,
        limit: 10,
    };
    let first = sources[0]
        .query_tasks(&TaskQuery::default(), &page)
        .await
        .expect("the silent source answers");
    assert!(first.items.is_empty());
    assert!(first.next.is_none());
}

#[tokio::test]
async fn a_source_reports_its_own_capability_declaration() {
    let source: Box<dyn TaskSource> = Box::new(Silent("silent"));
    let declared = source.capabilities();

    assert!(declared.filter_by_status.is_native());
    assert!(!declared.filter_by_label.is_native());
    assert!(declared.project_dependencies.answers_reverse());
    assert!(!declared.task_dependencies.answers_reverse());
    assert_eq!(declared.max_page_size, 25);
}

#[tokio::test]
async fn every_remaining_trait_method_is_reachable_through_dyn() {
    let source: Box<dyn TaskSource> = Box::new(Silent("silent"));
    let id = NativeId::from("t-1");
    let page = PageRequest {
        cursor: Some(Cursor("0".to_owned())),
        limit: 5,
    };

    assert!(source.get_task(&id).await.expect("answers").is_none());
    assert!(source.get_project(&id).await.expect("answers").is_none());
    assert!(
        source
            .query_projects(&ProjectQuery::default(), &page)
            .await
            .expect("answers")
            .items
            .is_empty()
    );
    assert!(
        source
            .labels(&page)
            .await
            .expect("answers")
            .items
            .is_empty()
    );
    assert!(
        source
            .task_dependencies(&id, Direction::DependsOn, &page)
            .await
            .expect("answers")
            .items
            .is_empty()
    );
    assert!(
        source
            .project_dependencies(&id, Direction::DependedOnBy, &page)
            .await
            .expect("answers")
            .items
            .is_empty()
    );

    let refusing: Box<dyn TaskSource> = Box::new(Refusing);
    let error = refusing.get_task(&id).await.expect_err("rate-limited");
    assert_eq!(
        error,
        SourceError::RateLimited {
            retry_after_seconds: Some(30),
            message: None,
        }
    );
    assert!(
        refusing
            .query_tasks(&TaskQuery::default(), &page)
            .await
            .expect("answers")
            .items
            .is_empty()
    );
    assert!(refusing.get_project(&id).await.expect("answers").is_none());
    assert!(
        refusing
            .query_projects(&ProjectQuery::default(), &page)
            .await
            .expect("answers")
            .items
            .is_empty()
    );
    assert!(
        refusing
            .labels(&page)
            .await
            .expect("answers")
            .items
            .is_empty()
    );
    assert!(
        refusing
            .task_dependencies(&id, Direction::DependsOn, &page)
            .await
            .expect("answers")
            .items
            .is_empty()
    );
    assert!(
        refusing
            .project_dependencies(&id, Direction::DependsOn, &page)
            .await
            .expect("answers")
            .items
            .is_empty()
    );
    assert_eq!(refusing.capabilities().max_page_size, 25);
}

/// A resolver over a fixed table, standing in for the process environment.
struct Table(Vec<(&'static str, &'static str)>);

impl SecretResolver for Table {
    fn get(&self, var: &str) -> Option<SecretString> {
        self.0
            .iter()
            .find(|(name, _)| *name == var)
            .map(|(_, value)| SecretString::from((*value).to_owned()))
    }
}

/// A plugin that builds a source only once its named credential resolves — the
/// shape every real plugin's `build` takes.
struct Gated;

impl SourcePlugin for Gated {
    fn kind(&self) -> &'static str {
        "gated"
    }
    fn config_schema(&self) -> Schema {
        schema_for!(TaskQuery)
    }
    fn build(
        &self,
        name: &SourceName,
        config: &serde_json::Value,
        secrets: &dyn SecretResolver,
    ) -> Result<Box<dyn TaskSource>, SourceError> {
        let var = config["api_key_env"]
            .as_str()
            .ok_or_else(|| SourceError::Config {
                message: format!("source {name}: config.api_key_env must be a string"),
            })?;
        let key = secrets.get(var).ok_or_else(|| SourceError::Auth {
            message: format!("source {name}: nothing defines {var}"),
        })?;
        assert!(!key.expose_secret().is_empty());
        Ok(Box::new(Silent("gated")))
    }
}

#[test]
fn a_plugin_builds_a_source_from_a_config_block_and_a_named_credential() {
    let name = SourceName::new("work").expect("a valid name");
    let secrets = Table(vec![("LINEAR_API_KEY", "lin_api_live")]);

    let built = Gated
        .build(
            &name,
            &serde_json::json!({ "api_key_env": "LINEAR_API_KEY" }),
            &secrets,
        )
        .expect("the credential resolves");
    assert_eq!(built.kind(), "gated");
    assert_eq!(Gated.kind(), "gated");
    assert!(Gated.config_schema().as_value().is_object());
}

#[test]
fn a_plugin_refuses_when_the_named_credential_is_absent() {
    let name = SourceName::new("work").expect("a valid name");
    let secrets = Table(Vec::new());

    let Err(error) = Gated.build(
        &name,
        &serde_json::json!({ "api_key_env": "LINEAR_API_KEY" }),
        &secrets,
    ) else {
        panic!("nothing defines the variable, so build must refuse");
    };
    assert_eq!(
        error,
        SourceError::Auth {
            message: "source work: nothing defines LINEAR_API_KEY".to_owned()
        }
    );
    assert!(secrets.get("ABSENT").is_none());
}

#[test]
fn a_plugin_refuses_a_config_block_of_the_wrong_shape() {
    let name = SourceName::new("work").expect("a valid name");
    let Err(error) = Gated.build(&name, &serde_json::json!({}), &Table(Vec::new())) else {
        panic!("the config block is the wrong shape, so build must refuse");
    };
    assert!(
        matches!(&error, SourceError::Config { message } if message.contains("api_key_env")),
        "{error:?}"
    );
}

#[test]
fn a_source_name_accepts_the_documented_pattern_and_rejects_everything_else() {
    for good in ["work", "notes", "gh-main", "s3", "0"] {
        let name = SourceName::new(good).expect("a valid name");
        assert_eq!(name.as_str(), good);
        assert_eq!(name.to_string(), good);
        assert_eq!(String::from(name.clone()), good);
        assert_eq!(SourceName::try_from(good.to_owned()).expect("valid"), name);
    }

    // Underscores are the load-bearing exclusion: `ONETASKGRAPH_SOURCES__<NAME>__…`
    // joins segments with a double underscore, so a name holding one is ambiguous.
    for bad in ["gh_main", "Work", "-lead", "", "notes!", "a b"] {
        let Err(error) = SourceName::new(bad) else {
            panic!("{bad:?} is not a usable source name");
        };
        let SourceError::Config { message } = error else {
            panic!("a bad name is a configuration error");
        };
        assert!(message.contains(SOURCE_NAME_PATTERN), "{message}");
    }
}

#[test]
fn a_source_name_round_trips_through_json_and_rejects_a_bad_one_at_the_boundary() {
    let name = SourceName::new("gh-main").expect("valid");
    let encoded = serde_json::to_string(&name).expect("encodes");
    assert_eq!(encoded, "\"gh-main\"");
    assert_eq!(
        serde_json::from_str::<SourceName>(&encoded).expect("decodes"),
        name
    );
    assert!(serde_json::from_str::<SourceName>("\"gh_main\"").is_err());

    let schema = serde_json::to_value(schema_for!(SourceName)).expect("renders");
    assert_eq!(schema["pattern"], SOURCE_NAME_PATTERN);
}

#[test]
fn a_native_id_carries_whatever_the_source_says_including_colons() {
    let id = NativeId::from("urn:task:7");
    assert_eq!(id.as_str(), "urn:task:7");
    assert_eq!(id.to_string(), "urn:task:7");
    assert_eq!(NativeId::from("urn:task:7".to_owned()), id);
    assert_eq!(
        serde_json::to_string(&id).expect("encodes"),
        "\"urn:task:7\""
    );
}

#[test]
fn repository_origins_accept_only_the_normalized_public_identity() {
    let repository =
        onetaskgraph_plugin_api::Repository::try_from("github.com/example/work".to_owned())
            .expect("normalized origin");
    assert_eq!(repository.as_str(), "github.com/example/work");
    assert_eq!(String::from(repository), "github.com/example/work");

    for invalid in [
        "",
        "github.com/example",
        "https://github.com/example/work",
        "github.com/example/work.git",
        "github.com/example/work tree",
        "github.com//work",
        "github.com/../work",
    ] {
        let error = onetaskgraph_plugin_api::Repository::try_from(invalid.to_owned())
            .expect_err("non-normalized origin is rejected");
        assert!(error.contains("normalized repository origin"), "{error}");
    }
}

#[test]
fn repository_origins_are_read_from_the_one_reserved_key_they_are_recorded_under() {
    let metadata = [(
        onetaskgraph_plugin_api::Repository::METADATA_KEY.to_owned(),
        serde_json::json!(["github.com/example/work", "github.com/example/docs"]),
    )]
    .into();
    let origins = onetaskgraph_plugin_api::Repository::from_metadata(&metadata)
        .expect("a list of normalized origins");
    assert_eq!(
        origins
            .iter()
            .map(onetaskgraph_plugin_api::Repository::as_str)
            .collect::<Vec<_>>(),
        ["github.com/example/work", "github.com/example/docs"]
    );

    assert!(
        onetaskgraph_plugin_api::Repository::from_metadata(&Default::default())
            .expect("an item recording none")
            .is_empty()
    );

    for (value, expected) in [
        (serde_json::json!("github.com/example/work"), "not a list"),
        (
            serde_json::json!(["github.com/example/work", "github.com/example/work"]),
            "listed twice",
        ),
        (serde_json::json!(["work"]), "normalized repository origin"),
    ] {
        let metadata = [(
            onetaskgraph_plugin_api::Repository::METADATA_KEY.to_owned(),
            value,
        )]
        .into();
        let error = onetaskgraph_plugin_api::Repository::from_metadata(&metadata)
            .expect_err("a repository list this interface cannot represent");
        assert!(error.contains(expected), "{error}");
    }
}

#[test]
fn a_repeated_repository_origin_is_refused_wherever_a_work_item_is_decoded() {
    let repeated = serde_json::json!({
        "id": "ENG-1", "title": "Ship", "content": null,
        "status": {"category": "todo", "name": "Todo"}, "labels": [], "project": null,
        "url": null, "created_at": null, "updated_at": null,
        "repositories": ["github.com/example/work", "github.com/example/work"]
    });
    let error = serde_json::from_value::<Task>(repeated.clone()).expect_err("a repeat is refused");
    assert!(error.to_string().contains("listed twice"), "{error}");

    let mut project = repeated;
    project
        .as_object_mut()
        .expect("an object")
        .remove("project");
    assert!(serde_json::from_value::<Project>(project).is_err());
}

/// The name the source reading these near items is configured under.
///
/// A qualified far end is judged against it, so it has to be a real `SourceName` rather
/// than a literal spelled into each assertion.
fn near_source() -> SourceName {
    SourceName::new("work").expect("a usable source name")
}

#[test]
fn a_near_item_records_the_far_ends_its_backend_cannot_name() {
    let metadata = [(
        DependencyEdge::RECORDED_KEY.to_owned(),
        serde_json::json!(["T-2", {"id": "elsewhere:P-9", "kind": "project"}]),
    )]
    .into();
    // A source with no relationship of its own may record anything, including a far end
    // in this source.
    let edges = DependencyEdge::recorded(
        &metadata,
        &NativeId::from("T-1"),
        ItemKind::Task,
        &near_source(),
        None,
    )
    .expect("a list of endpoints");

    assert_eq!(edges.len(), 2);
    assert_eq!(edges[0].from.id(), "T-1");
    assert_eq!(edges[0].to.id(), "T-2");
    assert!(!edges[0].to.is_qualified());
    assert_eq!(edges[0].kind, DependencyKind::Blocks);
    assert_eq!(edges[1].to.id(), "elsewhere:P-9");
    assert!(edges[1].to.is_qualified());
    assert_eq!(edges[1].to.kind, ItemKind::Project);

    assert!(
        DependencyEdge::recorded(
            &Default::default(),
            &NativeId::from("T-1"),
            ItemKind::Task,
            &near_source(),
            Some(ItemKind::Task)
        )
        .expect("an item recording nothing")
        .is_empty()
    );

    let malformed = [(
        DependencyEdge::RECORDED_KEY.to_owned(),
        serde_json::json!({"id": "elsewhere:P-9"}),
    )]
    .into();
    let error = DependencyEdge::recorded(
        &malformed,
        &NativeId::from("T-1"),
        ItemKind::Task,
        &near_source(),
        None,
    )
    .expect_err("a mapping is not a list of endpoints");
    assert!(error.contains(DependencyEdge::RECORDED_KEY), "{error}");
}

#[test]
fn a_far_end_the_near_backend_could_have_named_is_refused_rather_than_read() {
    use onetaskgraph_plugin_api::ItemKind;

    // The rule this key exists to serve is the backend's own relationship first, so an
    // unqualified far end of the kind that backend relates is misplaced, not a shortcut.
    let same_kind = [(
        DependencyEdge::RECORDED_KEY.to_owned(),
        serde_json::json!(["T-2"]),
    )]
    .into();
    let error = DependencyEdge::recorded(
        &same_kind,
        &NativeId::from("T-1"),
        ItemKind::Task,
        &near_source(),
        Some(ItemKind::Task),
    )
    .expect_err("a task naming a task of this source is the backend's own edge");
    assert!(error.contains("T-2"), "{error}");
    assert!(error.contains("relate natively"), "{error}");
    assert!(error.contains(DependencyEdge::RECORDED_KEY), "{error}");

    // A far end in another source is never refused: no backend relates an id in a system
    // it knows nothing about, which is the whole case this key is for.
    let qualified = [(
        DependencyEdge::RECORDED_KEY.to_owned(),
        serde_json::json!([{"id": "elsewhere:T-9", "kind": "task"}]),
    )]
    .into();
    assert_eq!(
        DependencyEdge::recorded(
            &qualified,
            &NativeId::from("T-1"),
            ItemKind::Task,
            &near_source(),
            Some(ItemKind::Task)
        )
        .expect("a far end in another source")
        .len(),
        1
    );

    // Nor is a far end of the other kind, which the same backend cannot relate either.
    let other_kind = [(
        DependencyEdge::RECORDED_KEY.to_owned(),
        serde_json::json!([{"id": "P-9", "kind": "project"}]),
    )]
    .into();
    assert_eq!(
        DependencyEdge::recorded(
            &other_kind,
            &NativeId::from("T-1"),
            ItemKind::Task,
            &near_source(),
            Some(ItemKind::Task)
        )
        .expect("a level this backend cannot relate across")
        .len(),
        1
    );
}

#[test]
fn a_far_end_qualified_to_the_near_source_is_refused_like_a_bare_one() {
    use onetaskgraph_plugin_api::ItemKind;

    // Writing the near source out changes the spelling of the entry, not where the edge
    // belongs: `work:T-2` on a `work` task is still an edge that backend relates itself.
    let own_source = [(
        DependencyEdge::RECORDED_KEY.to_owned(),
        serde_json::json!([{"id": "work:T-2", "kind": "task"}]),
    )]
    .into();
    let error = DependencyEdge::recorded(
        &own_source,
        &NativeId::from("T-1"),
        ItemKind::Task,
        &near_source(),
        Some(ItemKind::Task),
    )
    .expect_err("a task naming a task of its own source is the backend's own edge");
    assert!(error.contains("work:T-2"), "{error}");
    assert!(error.contains("relate natively"), "{error}");

    // Another source named in full stays the case this key exists for, and a source whose
    // name merely starts the same is another source like any other.
    for far in ["elsewhere:T-9", "work-two:T-9"] {
        let elsewhere = [(
            DependencyEdge::RECORDED_KEY.to_owned(),
            serde_json::json!([{"id": far, "kind": "task"}]),
        )]
        .into();
        let edges = DependencyEdge::recorded(
            &elsewhere,
            &NativeId::from("T-1"),
            ItemKind::Task,
            &near_source(),
            Some(ItemKind::Task),
        )
        .expect("a far end in another source");
        assert_eq!(edges.len(), 1, "{far}");
        assert_eq!(edges[0].to.id(), far);
        assert_eq!(edges[0].to.source(), Some(far.split(':').next().unwrap()));
    }

    // The near source qualifies a level its own relationship cannot cross, so this one is
    // the key's case even though it names this very source.
    let other_level = [(
        DependencyEdge::RECORDED_KEY.to_owned(),
        serde_json::json!([{"id": "work:P-9", "kind": "project"}]),
    )]
    .into();
    let edges = DependencyEdge::recorded(
        &other_level,
        &NativeId::from("T-1"),
        ItemKind::Task,
        &near_source(),
        Some(ItemKind::Task),
    )
    .expect("a level this backend cannot relate across");
    assert_eq!(edges.len(), 1);
    assert_eq!(edges[0].to.source(), Some("work"));

    // A backend with no relationship at all still records anything, its own source
    // included: there is no native place for that edge to belong to.
    assert_eq!(
        DependencyEdge::recorded(
            &own_source,
            &NativeId::from("T-1"),
            ItemKind::Task,
            &near_source(),
            None,
        )
        .expect("a backend with nothing to relate through")
        .len(),
        1
    );
}

/// The third key is one plugin's, and the difference is the point.
///
/// `onetaskgraph.repositories` and `onetaskgraph.depends_on` are obligations on every
/// source. `onetaskgraph.item_kind` is spelled here for the same reason — a key under
/// this product's prefix is the product's to name, so no plugin can invent a colliding
/// one — but it obliges nobody: a source with a native notion of its own kinds never
/// reads or writes it and passes it through as ordinary caller metadata.
#[test]
fn the_three_reserved_keys_are_spelled_once_and_under_this_products_prefix() {
    for key in [
        onetaskgraph_plugin_api::Repository::METADATA_KEY,
        DependencyEdge::RECORDED_KEY,
        ItemKind::METADATA_KEY,
    ] {
        assert!(key.starts_with("onetaskgraph."), "{key}");
    }
}

#[test]
fn the_item_kind_marker_accepts_exactly_its_two_spellings() {
    let marked = |value: serde_json::Value| {
        std::collections::BTreeMap::from([(ItemKind::METADATA_KEY.to_owned(), value)])
    };
    assert_eq!(ItemKind::Project.marker(), "project");
    assert_eq!(ItemKind::Task.marker(), "task");
    assert_eq!(
        ItemKind::from_metadata(&marked(serde_json::json!("project"))),
        Ok(Some(ItemKind::Project))
    );
    assert_eq!(
        ItemKind::from_metadata(&marked(serde_json::json!("task"))),
        Ok(Some(ItemKind::Task))
    );
    assert_eq!(
        ItemKind::from_metadata(&std::collections::BTreeMap::new()),
        Ok(None),
        "an unmarked item carries no kind rather than a wrong one"
    );
    for malformed in [
        serde_json::json!("Project"),
        serde_json::json!("issue"),
        serde_json::json!(""),
        serde_json::json!(1),
        serde_json::json!(["project"]),
        serde_json::Value::Null,
    ] {
        let refusal = ItemKind::from_metadata(&marked(malformed.clone()))
            .expect_err(&format!("{malformed} is not a marker"));
        assert!(refusal.contains(ItemKind::METADATA_KEY), "{refusal}");
        assert!(
            refusal.contains("project") && refusal.contains("task"),
            "{refusal}"
        );
    }
}

#[test]
fn dependency_endpoints_validate_and_preserve_qualified_ids() {
    let endpoint: onetaskgraph_plugin_api::DependencyEndpoint =
        serde_json::from_value(serde_json::json!({"id":"other:P-9", "kind":"project"}))
            .expect("qualified endpoint");
    assert_eq!(endpoint.to_string(), "other:P-9");
    assert_ne!(endpoint, NativeId::from("P-9"));

    let native = onetaskgraph_plugin_api::DependencyEndpoint::from_native(
        NativeId::from("urn:task:7"),
        onetaskgraph_plugin_api::ItemKind::Task,
    );
    assert_eq!(native.id(), "urn:task:7");
    assert_eq!(native.into_id(), "urn:task:7");

    // An id built through the validating constructor without a colon stays this source's
    // own, which is what keeps a bare far id a native one.
    let unqualified = onetaskgraph_plugin_api::DependencyEndpoint::new(
        "T-2".to_owned(),
        onetaskgraph_plugin_api::ItemKind::Task,
    )
    .expect("an unqualified endpoint");
    assert!(!unqualified.is_qualified());
    assert_eq!(unqualified, NativeId::from("T-2"));

    for invalid in [
        serde_json::json!({"id":"", "kind":"task"}),
        serde_json::json!({"id":"bad source:T-1", "kind":"task"}),
        serde_json::json!({"id":"other:", "kind":"project"}),
        serde_json::json!(""),
    ] {
        assert!(
            serde_json::from_value::<onetaskgraph_plugin_api::DependencyEndpoint>(invalid).is_err()
        );
    }
}

#[test]
fn a_task_round_trips_through_json_with_every_field_populated() {
    let task = Task {
        id: NativeId::from("ENG-1"),
        title: "Ship the contract".to_owned(),
        content: Some("Two crates, one direction.".to_owned()),
        status: Status {
            category: StatusCategory::InProgress,
            name: "In Review".to_owned(),
        },
        labels: vec![Label {
            id: NativeId::from("l-1"),
            name: "infra".to_owned(),
            color: Some("#336699".to_owned()),
        }],
        project: Some(NativeId::from("P-1")),
        url: Some("https://example.invalid/ENG-1".to_owned()),
        location: Some(Location::Url("https://example.invalid/ENG-1".to_owned())),
        created_at: Some(Utc.with_ymd_and_hms(2026, 8, 22, 9, 0, 0).unwrap()),
        updated_at: None,
        metadata: [("onepipeline.turn_budget".to_owned(), serde_json::json!(12))].into(),
        repositories: vec![
            onetaskgraph_plugin_api::Repository::try_from("github.com/example/work".to_owned())
                .expect("normalized origin"),
        ],
    };

    let encoded = serde_json::to_string(&task).expect("encodes");
    assert_eq!(
        serde_json::from_str::<Task>(&encoded).expect("decodes"),
        task
    );
    // The source's own wording survives normalisation.
    assert_eq!(task.status.name, "In Review");
    assert_eq!(task.status.category, StatusCategory::InProgress);
}

#[test]
fn a_project_and_an_orphan_task_round_trip_through_json() {
    let project = Project {
        id: NativeId::from("P-1"),
        title: "Foundation".to_owned(),
        content: None,
        status: Status {
            category: StatusCategory::Backlog,
            name: "Planned".to_owned(),
        },
        labels: Vec::new(),
        url: None,
        location: None,
        created_at: None,
        updated_at: Some(Utc.with_ymd_and_hms(2026, 8, 22, 9, 0, 0).unwrap()),
        metadata: Default::default(),
        repositories: Vec::new(),
    };
    let encoded = serde_json::to_string(&project).expect("encodes");
    assert_eq!(
        serde_json::from_str::<Project>(&encoded).expect("decodes"),
        project
    );

    // A task belonging to no project is a first-class case, not an edge case.
    let orphan: Task = serde_json::from_value(serde_json::json!({
        "id": "T-9",
        "title": "Loose end",
        "content": null,
        "status": { "category": "todo", "name": "Todo" },
        "labels": [],
        "project": null,
        "url": null,
        "created_at": null,
        "updated_at": null,
    }))
    .expect("decodes");
    assert!(orphan.project.is_none());
    assert_eq!(orphan.status.category, StatusCategory::Todo);
}

#[test]
fn the_normalised_vocabularies_serialise_as_kebab_case() {
    let categories = [
        (StatusCategory::Draft, "draft"),
        (StatusCategory::Backlog, "backlog"),
        (StatusCategory::Todo, "todo"),
        (StatusCategory::InProgress, "in-progress"),
        (StatusCategory::Done, "done"),
        (StatusCategory::Cancelled, "cancelled"),
        (StatusCategory::Unknown, "unknown"),
    ];
    for (value, wire) in categories {
        assert_eq!(
            serde_json::to_value(value).expect("encodes"),
            serde_json::json!(wire)
        );
        assert_eq!(
            serde_json::from_value::<StatusCategory>(serde_json::json!(wire)).expect("decodes"),
            value
        );
    }

    assert_eq!(
        serde_json::to_value(DependencyKind::Blocks).expect("encodes"),
        serde_json::json!("blocks")
    );
    assert_eq!(
        serde_json::to_value(DependencyKind::Related).expect("encodes"),
        serde_json::json!("related")
    );
    assert_eq!(
        serde_json::to_value(Direction::DependedOnBy).expect("encodes"),
        serde_json::json!("depended-on-by")
    );
    assert_eq!(
        serde_json::to_value(Direction::DependsOn).expect("encodes"),
        serde_json::json!("depends-on")
    );
    assert_eq!(
        serde_json::to_value(TextFields::TitleOrContent).expect("encodes"),
        serde_json::json!("title-or-content")
    );
    assert_eq!(
        serde_json::to_value(TextFields::Title).expect("encodes"),
        serde_json::json!("title")
    );
    assert_eq!(
        serde_json::to_value(TextFields::Content).expect("encodes"),
        serde_json::json!("content")
    );
    assert_eq!(
        serde_json::to_value(Support::Unsupported).expect("encodes"),
        serde_json::json!("unsupported")
    );
    assert_eq!(
        serde_json::to_value(DependencySupport::ForwardOnly).expect("encodes"),
        serde_json::json!("forward-only")
    );
}

#[test]
fn a_dependency_edge_round_trips_through_json() {
    let edge = DependencyEdge {
        from: onetaskgraph_plugin_api::DependencyEndpoint::new(
            "source:A".into(),
            onetaskgraph_plugin_api::ItemKind::Task,
        )
        .expect("valid endpoint"),
        to: onetaskgraph_plugin_api::DependencyEndpoint::new(
            "other:B".into(),
            onetaskgraph_plugin_api::ItemKind::Project,
        )
        .expect("valid endpoint"),
        kind: DependencyKind::Blocks,
    };
    let encoded = serde_json::to_string(&edge).expect("encodes");
    assert_eq!(
        serde_json::from_str::<DependencyEdge>(&encoded).expect("decodes"),
        edge
    );
    let legacy: DependencyEdge = serde_json::from_value(serde_json::json!({
        "from":"A", "to":"B", "kind":"related"
    }))
    .expect("legacy native endpoints still decode");
    assert_eq!(legacy.from.to_string(), "A");
    assert_eq!(legacy.from.kind, onetaskgraph_plugin_api::ItemKind::Task);
}

#[test]
fn an_empty_label_filter_constrains_nothing_and_a_populated_one_does() {
    assert!(LabelFilter::default().is_empty());
    assert!(
        !LabelFilter {
            none_of: vec!["wontfix".to_owned()],
            ..LabelFilter::default()
        }
        .is_empty()
    );
    assert!(
        !LabelFilter {
            any_of: vec!["infra".to_owned()],
            ..LabelFilter::default()
        }
        .is_empty()
    );
    assert!(
        !LabelFilter {
            all_of: vec!["infra".to_owned()],
            ..LabelFilter::default()
        }
        .is_empty()
    );
}

#[test]
fn a_query_round_trips_with_every_filter_populated() {
    let query = TaskQuery {
        text: Some(TextQuery {
            terms: "contract".to_owned(),
            fields: TextFields::TitleOrContent,
        }),
        labels: LabelFilter {
            any_of: vec!["infra".to_owned()],
            all_of: vec!["p1".to_owned()],
            none_of: vec!["wontfix".to_owned()],
        },
        statuses: vec![StatusCategory::Todo, StatusCategory::InProgress],
        project: ProjectFilter::Is(NativeId::from("P-1")),
    };
    let encoded = serde_json::to_string(&query).expect("encodes");
    assert_eq!(
        serde_json::from_str::<TaskQuery>(&encoded).expect("decodes"),
        query
    );

    let projects = ProjectQuery {
        text: None,
        labels: LabelFilter::default(),
        statuses: vec![StatusCategory::Done],
    };
    let encoded = serde_json::to_string(&projects).expect("encodes");
    assert_eq!(
        serde_json::from_str::<ProjectQuery>(&encoded).expect("decodes"),
        projects
    );

    assert_eq!(ProjectFilter::default(), ProjectFilter::Any);
    for filter in [
        ProjectFilter::Any,
        ProjectFilter::Orphans,
        ProjectFilter::Is(NativeId::from("P-2")),
    ] {
        let encoded = serde_json::to_string(&filter).expect("encodes");
        assert_eq!(
            serde_json::from_str::<ProjectFilter>(&encoded).expect("decodes"),
            filter
        );
    }
}

#[test]
fn a_page_carries_a_cursor_only_while_the_walk_continues() {
    let exhausted = Page::last(vec![1_u8, 2, 3]);
    assert!(exhausted.next.is_none());

    let more = Page {
        items: vec![1_u8],
        next: Some(Cursor("3".to_owned())),
    };
    let encoded = serde_json::to_string(&more).expect("encodes");
    assert_eq!(
        serde_json::from_str::<Page<u8>>(&encoded).expect("decodes"),
        more
    );

    let request = PageRequest {
        cursor: Some(Cursor("3".to_owned())),
        limit: 50,
    };
    let encoded = serde_json::to_string(&request).expect("encodes");
    assert_eq!(
        serde_json::from_str::<PageRequest>(&encoded).expect("decodes"),
        request
    );
}

#[test]
fn a_page_request_for_no_rows_is_refused_where_the_request_is_read() {
    // A page of no rows is not a page. Coercing zero to one would turn a caller's bug
    // into a walk that never advances, so it is refused at the boundary instead.
    let error = serde_json::from_str::<PageRequest>(r#"{"cursor":null,"limit":0}"#)
        .expect_err("a zero limit is not a page size");
    assert!(
        error.to_string().contains("limit must be at least 1"),
        "{error}"
    );

    let smallest: PageRequest =
        serde_json::from_str(r#"{"cursor":null,"limit":1}"#).expect("one row is a page");
    assert_eq!(smallest.limit, 1);
}

#[test]
fn health_round_trips_in_both_shapes() {
    for health in [
        Health {
            reachable: true,
            detail: Some("200 OK".to_owned()),
        },
        Health {
            reachable: false,
            detail: None,
        },
    ] {
        let encoded = serde_json::to_string(&health).expect("encodes");
        assert_eq!(
            serde_json::from_str::<Health>(&encoded).expect("decodes"),
            health
        );
    }
}

#[test]
fn every_error_variant_renders_a_message_and_survives_the_stdio_boundary() {
    // Owned data only, so an error crosses JSON-over-stdio to a subprocess-hosted
    // plugin and back without losing anything.
    let cases = [
        (
            SourceError::Config {
                message: "team is required".to_owned(),
            },
            "configuration for this source is invalid: team is required",
            "config",
        ),
        (
            SourceError::Auth {
                message: "token rejected".to_owned(),
            },
            "authentication for this source failed: token rejected",
            "auth",
        ),
        (
            SourceError::Refused {
                message: "forbidden".to_owned(),
            },
            "the source refused the request: forbidden",
            "refused",
        ),
        (
            SourceError::RateLimited {
                retry_after_seconds: Some(30),
                message: None,
            },
            "the source rate-limited the request",
            "rate-limited",
        ),
        (
            SourceError::RateLimited {
                retry_after_seconds: None,
                message: Some("the burst limiter refused this, and nothing reports it".to_owned()),
            },
            "the source rate-limited the request: the burst limiter refused this, and nothing \
             reports it",
            "rate-limited",
        ),
        (
            SourceError::Unavailable {
                message: "no route".to_owned(),
            },
            "the source could not be reached: no route",
            "unavailable",
        ),
        (
            SourceError::Malformed {
                message: "not a date".to_owned(),
            },
            "the source returned data this interface cannot represent: not a date",
            "malformed",
        ),
    ];

    for (error, rendered, tag) in cases {
        assert_eq!(error.to_string(), rendered);
        let encoded = serde_json::to_value(&error).expect("encodes");
        assert_eq!(encoded["kind"], tag);
        assert_eq!(
            serde_json::from_value::<SourceError>(encoded).expect("decodes"),
            error
        );
    }
}

#[test]
fn a_rate_limits_optional_message_is_omitted_when_absent_and_read_back_when_it_is_not() {
    // `rate-limited` gained `message` after the protocol had shipped, and §2.1 of
    // docs/plugin-protocol.md is what makes that safe without a version bump: an added
    // member is optional, has a documented default when absent, and an old reader ignores
    // it. Both halves of that are asserted here rather than assumed.
    let silent = SourceError::RateLimited {
        retry_after_seconds: Some(30),
        message: None,
    };
    let encoded = serde_json::to_value(&silent).expect("encodes");
    assert_eq!(
        encoded,
        serde_json::json!({"kind":"rate-limited","retry_after_seconds":30}),
        "a rate limit with nothing to add is not the shape it was before the member existed"
    );

    // What a peer written before the member sends: it is read back as the documented
    // default rather than refused.
    assert_eq!(
        serde_json::from_value::<SourceError>(
            serde_json::json!({"kind":"rate-limited","retry_after_seconds":null})
        )
        .expect("an old peer's rate limit still decodes"),
        SourceError::RateLimited {
            retry_after_seconds: None,
            message: None,
        }
    );

    let said = SourceError::RateLimited {
        retry_after_seconds: None,
        message: Some("the secondary limiter refused this while creating an issue".to_owned()),
    };
    let encoded = serde_json::to_value(&said).expect("encodes");
    assert_eq!(
        encoded["message"],
        "the secondary limiter refused this while creating an issue"
    );
    assert_eq!(
        serde_json::from_value::<SourceError>(encoded).expect("decodes"),
        said,
        "the diagnostic did not survive the stdio boundary"
    );

    // And the schema says it is optional, which is what the SDKs are generated from.
    let schema = serde_json::to_value(schema_for!(SourceError)).expect("a schema");
    let text = schema.to_string();
    assert!(text.contains("rate-limited"), "{text}");
    assert!(
        !text.contains(r#""required":["kind","message","retry_after_seconds"]"#),
        "the added member is required, which refuses every peer written before it: {text}"
    );
}

#[test]
fn every_contract_root_generates_a_json_schema() {
    // Both SDKs are generated from these, so a type that cannot describe itself
    // is a broken contract even when it compiles.
    for schema in [
        schema_for!(Task),
        schema_for!(Project),
        schema_for!(Label),
        schema_for!(Capabilities),
        schema_for!(TaskQuery),
        schema_for!(ProjectQuery),
        schema_for!(Page<Task>),
        schema_for!(PageRequest),
        schema_for!(Health),
        schema_for!(SourceError),
        schema_for!(DependencyEdge),
        schema_for!(Document),
        schema_for!(Location),
        schema_for!(DocumentQuery),
        schema_for!(Page<Document>),
    ] {
        assert!(schema.as_value().is_object());
    }
}

/// Expand a regex character-class body such as `a-z0-9-` into the characters it
/// denotes. A trailing `-` is a literal, which is exactly why the pattern spells
/// the hyphen last.
fn expand_class(body: &str) -> Vec<char> {
    let chars: Vec<char> = body.chars().collect();
    let mut out = Vec::new();
    let mut index = 0;
    while index < chars.len() {
        // `x-y` is a range only when a `y` follows it.
        if index + 2 < chars.len() && chars[index + 1] == '-' {
            out.extend(chars[index]..=chars[index + 2]);
            index += 3;
        } else {
            out.push(chars[index]);
            index += 1;
        }
    }
    out
}

/// Match `value` against the two character classes of `^[first][rest]*$`.
///
/// Derived from the published constant rather than restating it, which is the
/// whole point: this cannot agree with a pattern it did not read.
fn matches_published_pattern(value: &str) -> bool {
    let body = SOURCE_NAME_PATTERN
        .strip_prefix('^')
        .and_then(|rest| rest.strip_suffix('$'))
        .and_then(|rest| rest.strip_suffix('*'))
        .expect("the pattern is anchored and its tail repeats");
    let (first, rest) = body.split_once("][").expect("the pattern has two classes");
    let first = expand_class(first.strip_prefix('[').expect("a class opens the pattern"));
    let rest = expand_class(rest.strip_suffix(']').expect("a class closes the pattern"));

    let mut chars = value.chars();
    let Some(head) = chars.next() else {
        return false;
    };
    first.contains(&head) && chars.all(|c| rest.contains(&c))
}

#[test]
fn source_name_validation_agrees_with_the_pattern_it_publishes() {
    // `SourceName::new` hand-rolls its check for speed while `SOURCE_NAME_PATTERN`
    // is what the JSON Schema publishes to both SDKs, so nothing but this stops the
    // two describing different languages — a name the schema accepts and the
    // constructor rejects, or the reverse. The matcher above is built FROM the
    // constant, so changing either side alone fails here.
    let mut corpus: Vec<String> = vec![
        String::new(),
        "work".to_owned(),
        "gh-main".to_owned(),
        "a1-b2-c3".to_owned(),
        "0".to_owned(),
        "-leading".to_owned(),
        "trailing-".to_owned(),
        "Work".to_owned(),
        "work_name".to_owned(),
        "wörk".to_owned(),
        "a".repeat(200),
    ];
    for byte in 0u8..=127 {
        let c = char::from(byte);
        corpus.push(c.to_string());
        corpus.push(format!("a{c}"));
    }

    for name in corpus {
        assert_eq!(
            SourceName::new(name.clone()).is_ok(),
            matches_published_pattern(&name),
            "SourceName::new and SOURCE_NAME_PATTERN ({SOURCE_NAME_PATTERN}) disagree \
             about {name:?}. They are one rule in two places — change both together, or \
             a configuration the published schema accepts is refused at load."
        );
    }
}

/// The task a write test hands a source. Its own `id` is the id it was read under at the
/// source it came from, which is what a destination creating one may derive a name from.
fn outgoing() -> Task {
    Task {
        id: NativeId::from("T-1"),
        title: "Alpha engine".to_owned(),
        content: None,
        status: Status {
            category: StatusCategory::Todo,
            name: "Todo".to_owned(),
        },
        labels: Vec::new(),
        project: None,
        url: None,
        location: None,
        created_at: None,
        updated_at: None,
        metadata: std::collections::BTreeMap::new(),
        repositories: Vec::new(),
    }
}

#[tokio::test]
async fn a_source_that_implements_only_the_read_methods_declares_no_write_side() {
    // The whole point of defaulting the write seam: a source written before it existed —
    // and one whose backend has nothing to write into — needs no edit and keeps working.
    let source: Box<dyn TaskSource> = Box::new(Silent("read-only"));
    assert_eq!(source.writes(), WriteSupport::Unsupported);
    assert!(!source.writes().is_supported());
    assert!(WriteSupport::Supported.is_supported());

    for refusal in [
        source
            .write_task(&ItemWrite {
                target: None,
                item: outgoing(),
                depends_on: Vec::new(),
            })
            .await,
        source
            .write_project(&ItemWrite {
                target: Some(NativeId::from("P-1")),
                item: Project {
                    id: NativeId::from("P-1"),
                    title: "Engine".to_owned(),
                    content: None,
                    status: Status {
                        category: StatusCategory::Todo,
                        name: "Todo".to_owned(),
                    },
                    labels: Vec::new(),
                    url: None,
                    location: None,
                    created_at: None,
                    updated_at: None,
                    metadata: std::collections::BTreeMap::new(),
                    repositories: Vec::new(),
                },
                depends_on: Vec::new(),
            })
            .await
            .map(|_| NativeId::from("unreachable")),
    ] {
        let Err(SourceError::Refused { message }) = refusal else {
            panic!("a source with no write side must refuse a write: {refusal:?}");
        };
        assert_eq!(message, "the read-only plugin cannot be written");
    }
}

#[test]
fn an_item_write_round_trips_through_json_with_its_edges_and_an_absent_target() {
    let write = ItemWrite {
        target: None,
        item: outgoing(),
        depends_on: vec![DependencyEdge {
            from: onetaskgraph_plugin_api::DependencyEndpoint::from_native(
                NativeId::from("T-1"),
                onetaskgraph_plugin_api::ItemKind::Task,
            ),
            to: onetaskgraph_plugin_api::DependencyEndpoint::new(
                "other:P-9".to_owned(),
                onetaskgraph_plugin_api::ItemKind::Project,
            )
            .expect("a qualified endpoint"),
            kind: DependencyKind::Blocks,
        }],
    };
    let encoded = serde_json::to_value(&write).expect("encodes");
    assert_eq!(encoded["target"], serde_json::Value::Null);
    assert_eq!(encoded["depends_on"][0]["to"]["id"], "other:P-9");
    assert_eq!(
        serde_json::from_value::<ItemWrite<Task>>(encoded).expect("decodes"),
        write
    );

    // `depends_on` defaults, so a peer that records no edges may omit it entirely — which
    // is what lets §2.1 add a member without a version bump on either side.
    let bare: ItemWrite<Task> = serde_json::from_value(
        serde_json::json!({"target": "ENG-1", "item": serde_json::to_value(outgoing()).unwrap()}),
    )
    .expect("decodes without depends_on");
    assert_eq!(bare.target, Some(NativeId::from("ENG-1")));
    assert!(bare.depends_on.is_empty());
}

/// The document a read test hands back, with every field the contract gives it populated.
fn filed() -> Document {
    Document {
        id: NativeId::from("D-1"),
        title: "Why the store holds a document".to_owned(),
        content: Some("A person cannot review a plan node by node.".to_owned()),
        project: Some(NativeId::from("P-1")),
        labels: vec![Label {
            id: NativeId::from("l-1"),
            name: "design".to_owned(),
            color: None,
        }],
        url: Some("https://example.invalid/D-1".to_owned()),
        location: Some(Location::Path("/home/someone/notes/design.md".to_owned())),
        created_at: Some(Utc.with_ymd_and_hms(2026, 8, 31, 9, 0, 0).unwrap()),
        updated_at: None,
        metadata: [("onepipeline.review".to_owned(), serde_json::json!(true))].into(),
        repositories: vec![
            onetaskgraph_plugin_api::Repository::try_from("github.com/example/work".to_owned())
                .expect("normalized origin"),
        ],
    }
}

#[test]
fn a_document_round_trips_through_json_with_every_field_populated() {
    let document = filed();
    let encoded = serde_json::to_value(&document).expect("encodes");

    // A document is not work: it carries no status and no dependency key, and both
    // absences are the contract rather than an oversight.
    assert!(encoded.get("status").is_none(), "{encoded:#}");
    assert!(encoded.get("depends_on").is_none(), "{encoded:#}");

    assert_eq!(
        serde_json::from_value::<Document>(encoded).expect("decodes"),
        document
    );
}

#[test]
fn a_location_is_told_apart_by_which_key_is_present_on_all_three_entities() {
    // A consumer reads a location without knowing the backend, so the whole of what it has
    // to do is look at which key is there: a link it can open, or a path it can read out.
    assert_eq!(
        serde_json::to_value(Location::Url("https://example.invalid/D-1".to_owned()))
            .expect("encodes"),
        serde_json::json!({"url": "https://example.invalid/D-1"})
    );
    assert_eq!(
        serde_json::to_value(Location::Path("/home/someone/notes/design.md".to_owned()))
            .expect("encodes"),
        serde_json::json!({"path": "/home/someone/notes/design.md"})
    );

    let task = Task {
        location: Some(Location::Url("https://example.invalid/ENG-1".to_owned())),
        ..outgoing()
    };
    let project = Project {
        id: NativeId::from("P-1"),
        title: "Foundation".to_owned(),
        content: None,
        status: Status {
            category: StatusCategory::Backlog,
            name: "Planned".to_owned(),
        },
        labels: Vec::new(),
        url: None,
        location: Some(Location::Path("/home/someone/notes/P-1".to_owned())),
        created_at: None,
        updated_at: None,
        metadata: Default::default(),
        repositories: Vec::new(),
    };
    for (encoded, expected) in [
        (
            serde_json::to_value(&task).expect("encodes"),
            serde_json::json!({"url": "https://example.invalid/ENG-1"}),
        ),
        (
            serde_json::to_value(&project).expect("encodes"),
            serde_json::json!({"path": "/home/someone/notes/P-1"}),
        ),
        (
            serde_json::to_value(filed()).expect("encodes"),
            serde_json::json!({"path": "/home/someone/notes/design.md"}),
        ),
    ] {
        assert_eq!(encoded["location"], expected, "{encoded:#}");
    }

    // Neither entity's `url` is touched, replaced or derived from: a source that reported
    // one before this field existed reports exactly the same string now.
    assert_eq!(
        serde_json::to_value(&task).expect("encodes")["url"],
        serde_json::Value::Null
    );
    assert_eq!(
        serde_json::to_value(filed()).expect("encodes")["url"],
        serde_json::json!("https://example.invalid/D-1")
    );
}

#[test]
fn an_entity_that_does_not_say_where_it_is_decodes_as_absent_rather_than_failing() {
    // The default is what makes this addition non-breaking: a peer written before there
    // were locations omits the member, and `None` reads as *the source did not say* rather
    // than as *it is nowhere*.
    let mut without = serde_json::to_value(outgoing()).expect("encodes");
    without
        .as_object_mut()
        .expect("a task is an object")
        .remove("location")
        .expect("the field was there to remove");
    assert_eq!(
        serde_json::from_value::<Task>(without)
            .expect("decodes without a location")
            .location,
        None
    );

    let mut document = serde_json::to_value(filed()).expect("encodes");
    document
        .as_object_mut()
        .expect("a document is an object")
        .remove("location");
    assert_eq!(
        serde_json::from_value::<Document>(document)
            .expect("decodes without a location")
            .location,
        None
    );
}

#[test]
fn a_plugin_that_predates_documents_is_read_as_the_document_free_source_it_is() {
    // §2.1 of the protocol: an optional member with a documented default is not a version
    // bump, so a handshake written before there were documents still deserialises — and
    // says the honest thing rather than nothing.
    let mut declared = serde_json::to_value(Silent("older").capabilities()).expect("encodes");
    declared
        .as_object_mut()
        .expect("a capability value is an object")
        .remove("documents")
        .expect("the field was there to remove");

    let read: Capabilities = serde_json::from_value(declared).expect("decodes without documents");
    assert_eq!(read.documents, Support::Unsupported);
    assert!(!read.documents.is_native());
    // Every other field is what it was, so the default reaches this one and nothing else.
    assert_eq!(read, Silent("older").capabilities());
}

#[tokio::test]
async fn a_source_with_no_documents_refuses_a_document_read_rather_than_answering_an_empty_page() {
    // The whole point of defaulting the document seam: a source with none needs no edit,
    // keeps working, and refuses in the same words every other document-free source does.
    // An empty page here would be indistinguishable from a source that has documents and
    // holds none matching, which is the one wrong answer these methods can give.
    let source: Box<dyn TaskSource> = Box::new(Silent("read-only"));
    assert_eq!(source.capabilities().documents, Support::Unsupported);

    let reads = [
        source
            .get_document(&NativeId::from("D-1"))
            .await
            .map(|found| format!("{found:?}")),
        source
            .query_documents(
                &DocumentQuery {
                    text: Some(TextQuery {
                        terms: "design".to_owned(),
                        fields: TextFields::TitleOrContent,
                    }),
                    labels: LabelFilter::default(),
                    project: ProjectFilter::Is(NativeId::from("P-1")),
                },
                &PageRequest {
                    cursor: None,
                    limit: 10,
                },
            )
            .await
            .map(|page| format!("{page:?}")),
    ];
    for refusal in reads {
        let Err(SourceError::Refused { message }) = refusal else {
            panic!("a source with no documents must refuse a document read: {refusal:?}");
        };
        assert_eq!(message, "the read-only plugin has no documents");
    }

    // The two writes reuse the refusal every other write answers with, because a source
    // with no write side refuses a document write for that reason rather than this one.
    let writes = [
        source
            .write_document(&ItemWrite {
                target: None,
                item: filed(),
                depends_on: Vec::new(),
            })
            .await
            .map(|id| format!("{id:?}")),
        source
            .delete_document(&NativeId::from("D-1"))
            .await
            .map(|()| String::new()),
    ];
    for refusal in writes {
        let Err(SourceError::Refused { message }) = refusal else {
            panic!("a source with no write side must refuse a document write: {refusal:?}");
        };
        assert_eq!(message, "the read-only plugin cannot be written");
    }
}