haematite-cli 0.21.1

The haematite command: serve a store, its door and Studio, answer MCP, query with jq, and host the store's assistant seat
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
use std::collections::BTreeMap;
use std::num::{NonZeroU32, NonZeroU64};

use schemars::JsonSchema;
use serde::{Deserialize, Deserializer, Serialize, de::Error};
use serde_json::value::RawValue;

use crate::serve::protocol;

#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]
#[serde(transparent)]
pub struct Version(#[schemars(with = "VersionShape")] pub protocol::Version);

#[derive(Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
struct VersionShape {
    generation: String,
    sequence: String,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Selection {
    pub branch: String,
    pub version: Option<Version>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Snapshot {
    pub branch: String,
    pub version: Version,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct PageLimits {
    #[schemars(range(min = 1, max = u32::MAX))]
    pub rows: NonZeroU32,
    pub bytes: NonZeroU64,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Page<T> {
    pub entries: Vec<T>,
    pub next_after: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RecordRef {
    pub collection: String,
    pub document_id: String,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RecordWrite {
    pub document_id: String,
    pub document: Box<RawValue>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RecordValue {
    pub record: RecordRef,
    pub document: Box<RawValue>,
}

#[derive(Debug, Serialize, JsonSchema)]
#[serde(untagged)]
pub enum CollectionShape {
    Remove,
    Boolean(bool),
    Rules(#[schemars(with = "BTreeMap<String, Box<RawValue>>")] Box<RawValue>),
}

impl<'de> Deserialize<'de> for CollectionShape {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let raw = Box::<RawValue>::deserialize(deserializer)?;
        match raw.get() {
            "null" => Ok(Self::Remove),
            "true" => Ok(Self::Boolean(true)),
            "false" => Ok(Self::Boolean(false)),
            text if text.starts_with('{') => Ok(Self::Rules(raw)),
            _ => Err(D::Error::custom(
                "schema must be null, a boolean, or an object",
            )),
        }
    }
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CollectionInfo {
    pub name: String,
    pub schema: CollectionShape,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Cardinality {
    OneToOne,
    OneToMany,
    ManyToMany,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RelationInfo {
    pub relation: String,
    pub from_collection: String,
    pub to_collection: String,
    pub cardinality: Cardinality,
    pub relationships: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub relationships_reason: Option<RelationCountReason>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RelationCountReason {
    Withheld,
    CountsNotReady,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct VectorField {
    pub collection: String,
    pub field: String,
    pub dimensions: NonZeroU64,
    pub count: Option<u64>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct Counts {
    pub collections: u64,
    pub documents: u64,
    pub edges: u64,
    pub vectors: u64,
}

#[derive(Debug, Default, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct DescribeCursors {
    pub branches: Option<String>,
    pub collections: Option<String>,
    pub relations: Option<String>,
    pub vector_fields: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct DescribeStoreInput {
    pub selection: Selection,
    pub page: PageLimits,
    pub after: DescribeCursors,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct DescribeStoreOutput {
    pub selection: Snapshot,
    pub branches: Page<Snapshot>,
    pub collections: Page<CollectionInfo>,
    pub relations: Page<RelationInfo>,
    pub vector_fields: Page<VectorField>,
    pub counts: Counts,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RunQueryInput {
    pub selection: Selection,
    pub query: String,
    #[serde(default)]
    pub parameters: BTreeMap<String, Box<RawValue>>,
    pub page: PageLimits,
    pub after: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct QueryRow {
    pub value: Box<RawValue>,
    pub origin: Option<RecordRef>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RunQueryOutput {
    pub selection: Snapshot,
    pub rows: Page<QueryRow>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct HistoryRoot {
    pub shard: usize,
    pub root: String,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct HistoryEntry {
    pub branch: String,
    pub version: Version,
    pub roots: Vec<HistoryRoot>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ReadHistoryInput {
    pub selection: Selection,
    pub page: PageLimits,
    pub after: Option<String>,
    pub record: Option<RecordRef>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ReadHistoryOutput {
    pub selection: Snapshot,
    pub history: Page<HistoryEntry>,
    pub record: Option<RecordValue>,
}

macro_rules! writing_input {
    ($name:ident { $($(#[$attribute:meta])* $field:ident: $ty:ty),* $(,)? }) => {
        #[derive(Debug, Serialize, Deserialize, JsonSchema)]
        #[serde(deny_unknown_fields)]
        pub struct $name {
            pub request_id: String,
            pub branch: String,
            pub expected: Version,
            $( $(#[$attribute])* pub $field: $ty, )*
        }
    };
}

writing_input!(DefineCollectionInput {
    collection: String,
    schema: CollectionShape,
});
writing_input!(PutRecordsInput {
    collection: String,
    #[serde(deserialize_with = "nonempty_records")]
    #[schemars(length(min = 1))]
    records: Vec<RecordWrite>,
});
writing_input!(DeleteRecordInput { record: RecordRef });
writing_input!(LinkRecordsInput {
    relation: String,
    from: RecordRef,
    to: RecordRef,
    properties: BTreeMap<String, Box<RawValue>>,
});
writing_input!(UnlinkRecordsInput {
    relation: String,
    from: RecordRef,
    to: RecordRef,
});
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CreateBranchInput {
    /// Mutation identifier echoed by the receipt for reconciliation.
    pub request_id: String,
    /// Source branch whose current head guards the fork.
    pub branch: String,
    /// Expected current head of the source branch, checked before the fork.
    pub expected: Version,
    /// Name of the new destination branch.
    pub name: String,
    /// Retained source version from which the destination forks.
    pub from: Version,
}

fn nonempty_records<'de, D: Deserializer<'de>>(
    deserializer: D,
) -> Result<Vec<RecordWrite>, D::Error> {
    let records = Vec::<RecordWrite>::deserialize(deserializer)?;
    if records.is_empty() {
        return Err(D::Error::custom("records must contain at least one record"));
    }
    Ok(records)
}

macro_rules! writing_output {
    ($($name:ident),* $(,)?) => {
        $(
            #[derive(Debug, Serialize, Deserialize, JsonSchema)]
            #[serde(deny_unknown_fields)]
            pub struct $name {
                pub branch: String,
                pub version: Version,
                pub request_id: String,
            }
        )*
    };
}

writing_output!(
    DefineCollectionOutput,
    PutRecordsOutput,
    DeleteRecordOutput,
    LinkRecordsOutput,
    UnlinkRecordsOutput,
);

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MergeBranchInput {
    /// Mutation identifier echoed by the receipt for reconciliation.
    pub request_id: String,
    /// Branch merged into, whose current head guards the merge.
    pub branch: String,
    /// Expected current head of `branch`, checked before the merge.
    pub expected: Version,
    /// Reviewed branch merged in; it is left as it is.
    pub from: String,
    /// Version of `from` that `review_branch` read; any other is refused.
    pub reviewed: Version,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MergeBranchOutput {
    /// Branch merged into.
    pub branch: String,
    /// Version of `branch` that carries the merge and its receipt.
    pub version: Version,
    /// Mutation identifier echoed from the request for reconciliation.
    pub request_id: String,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct CreateBranchOutput {
    /// New destination branch, matching the requested name.
    pub branch: String,
    /// Version of the newly created destination branch.
    pub version: Version,
    /// Mutation identifier echoed from the request for reconciliation.
    pub request_id: String,
}

#[derive(Debug, Default, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ReviewCursors {
    pub diff: Option<String>,
    pub counts: Option<String>,
    pub conflicts: Option<String>,
    pub dangling: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ReviewBranchInput {
    pub selection: Selection,
    pub page: PageLimits,
    pub after: ReviewCursors,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DifferenceKind {
    Added,
    Changed,
    Removed,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum ReviewOwner {
    Collection {
        collection: String,
    },
    Document {
        record: RecordRef,
    },
    Relation {
        relation: String,
    },
    Edge {
        relation: String,
        from: RecordRef,
        to: RecordRef,
    },
    Vector {
        record: RecordRef,
        field: String,
    },
    VectorField {
        collection: String,
        field: String,
    },
}

#[derive(Debug, Serialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum ReviewValue {
    Absent,
    Value { value: Box<RawValue> },
}

impl<'de> Deserialize<'de> for ReviewValue {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(rename_all = "snake_case")]
        enum Kind {
            Absent,
            Value,
        }

        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Encoded {
            kind: Kind,
            #[serde(default, deserialize_with = "present_review_value")]
            value: Option<Box<RawValue>>,
        }

        let encoded = Encoded::deserialize(deserializer)?;
        match (encoded.kind, encoded.value) {
            (Kind::Absent, None) => Ok(Self::Absent),
            (Kind::Value, Some(value)) => Ok(Self::Value { value }),
            (Kind::Absent, Some(_)) => {
                Err(D::Error::custom("an absent review value has a payload"))
            }
            (Kind::Value, None) => Err(D::Error::custom("a present review value has no payload")),
        }
    }
}

fn present_review_value<'de, D: Deserializer<'de>>(
    deserializer: D,
) -> Result<Option<Box<RawValue>>, D::Error> {
    Box::<RawValue>::deserialize(deserializer).map(Some)
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ReviewLine {
    pub kind: DifferenceKind,
    pub owner: ReviewOwner,
    pub before: ReviewValue,
    pub after: ReviewValue,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ReviewCounts {
    pub changes: u64,
    pub conflicts: u64,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ReviewCountPage {
    pub partial: ReviewCounts,
    pub next_after: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ConflictState {
    SourceOnly,
    SameOnBoth,
    Conflict,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ConflictLine {
    pub owner: ReviewOwner,
    pub ancestor: ReviewValue,
    pub target: ReviewValue,
    pub source: ReviewValue,
    pub state: ConflictState,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub choice_token: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum MissingEnd {
    From,
    To,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum RemovedBy {
    Source,
    Target,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum DanglingState {
    Dangling,
    DependsOnChoice,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct DanglingLine {
    pub choice_token: String,
    pub relation: String,
    pub from: RecordRef,
    pub to: RecordRef,
    pub missing_end: MissingEnd,
    pub removed_by: RemovedBy,
    pub state: DanglingState,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ReviewBranchOutput {
    pub selection: Snapshot,
    pub from: Snapshot,
    pub target: Snapshot,
    pub diff: Page<ReviewLine>,
    pub counts: ReviewCountPage,
    pub conflicts: Page<ConflictLine>,
    pub dangling: Page<DanglingLine>,
    pub base_moved: Option<u64>,
}

#[cfg(test)]
pub(super) mod tests {
    use std::error::Error;

    use serde::de::DeserializeOwned;
    use serde_json::{Value, json};

    use super::{
        CreateBranchInput, DefineCollectionInput, DeleteRecordInput, DescribeStoreInput,
        LinkRecordsInput, MergeBranchInput, PageLimits, PutRecordsInput, ReadHistoryInput,
        RelationCountReason, RelationInfo, ReviewBranchInput, RunQueryInput, RunQueryOutput,
        UnlinkRecordsInput, Version,
    };

    type TestResult = Result<(), Box<dyn Error>>;

    const SELECTED: &str = r#"{"branch":"feature","version":{"generation":"1","sequence":"2"}}"#;
    const WRITE: &str =
        r#""request_id":"r1","branch":"feature","expected":{"generation":"1","sequence":"2"}"#;

    pub(in crate::mcp) fn inputs() -> Vec<(&'static str, String)> {
        vec![
            (
                "describe_store",
                format!(
                    r#"{{"selection":{SELECTED},"page":{{"rows":10,"bytes":4096}},"after":{{}}}}"#
                ),
            ),
            (
                "run_query",
                format!(
                    r#"{{"selection":{SELECTED},"query":"records | '.'","page":{{"rows":10,"bytes":4096}}}}"#
                ),
            ),
            (
                "read_history",
                format!(r#"{{"selection":{SELECTED},"page":{{"rows":10,"bytes":4096}}}}"#),
            ),
            (
                "define_collection",
                format!(r#"{{{WRITE},"collection":"records","schema":{{"type":"object"}}}}"#),
            ),
            (
                "put_records",
                format!(
                    r#"{{{WRITE},"collection":"records","records":[{{"document_id":"a","document":{{"n":1e2}}}}]}}"#
                ),
            ),
            (
                "delete_record",
                format!(r#"{{{WRITE},"record":{{"collection":"records","document_id":"a"}}}}"#),
            ),
            (
                "link_records",
                format!(
                    r#"{{{WRITE},"relation":"links","from":{{"collection":"records","document_id":"a"}},"to":{{"collection":"records","document_id":"b"}},"properties":{{}}}}"#
                ),
            ),
            (
                "unlink_records",
                format!(
                    r#"{{{WRITE},"relation":"links","from":{{"collection":"records","document_id":"a"}},"to":{{"collection":"records","document_id":"b"}}}}"#
                ),
            ),
            (
                "create_branch",
                format!(r#"{{{WRITE},"name":"new","from":{{"generation":"1","sequence":"2"}}}}"#),
            ),
            (
                "review_branch",
                format!(
                    r#"{{"selection":{SELECTED},"page":{{"rows":10,"bytes":4096}},"after":{{}}}}"#
                ),
            ),
            (
                "merge_branch",
                format!(
                    r#"{{{WRITE},"from":"import","reviewed":{{"generation":"3","sequence":"4"}}}}"#
                ),
            ),
        ]
    }

    fn refuses_unknown<T: DeserializeOwned>(input: &str) -> TestResult {
        let _: T = serde_json::from_str(input)?;
        let mut value: Value = serde_json::from_str(input)?;
        value
            .as_object_mut()
            .ok_or("input is not an object")?
            .insert("caller".to_owned(), json!({"subject":"forged"}));
        let error = serde_json::from_str::<T>(&serde_json::to_string(&value)?)
            .err()
            .ok_or("unknown caller member accepted")?;
        assert!(error.to_string().contains("unknown field"), "{error}");
        Ok(())
    }

    #[test]
    fn every_tool_input_refuses_unknown_members() -> TestResult {
        let fixtures = inputs();
        refuses_unknown::<DescribeStoreInput>(&fixtures[0].1)?;
        refuses_unknown::<RunQueryInput>(&fixtures[1].1)?;
        refuses_unknown::<ReadHistoryInput>(&fixtures[2].1)?;
        refuses_unknown::<DefineCollectionInput>(&fixtures[3].1)?;
        refuses_unknown::<PutRecordsInput>(&fixtures[4].1)?;
        refuses_unknown::<DeleteRecordInput>(&fixtures[5].1)?;
        refuses_unknown::<LinkRecordsInput>(&fixtures[6].1)?;
        refuses_unknown::<UnlinkRecordsInput>(&fixtures[7].1)?;
        refuses_unknown::<CreateBranchInput>(&fixtures[8].1)?;
        refuses_unknown::<ReviewBranchInput>(&fixtures[9].1)?;
        refuses_unknown::<MergeBranchInput>(&fixtures[10].1)
    }

    #[test]
    fn relation_metadata_preserves_a_known_relationship_count() -> TestResult {
        let text = r#"{"relation":"links","from_collection":"records","to_collection":"records","cardinality":"many_to_many","relationships":0}"#;
        let relation: RelationInfo = serde_json::from_str(text)?;
        assert_eq!(relation.relationships, Some(0));
        assert_eq!(relation.relationships_reason, None);
        let encoded = serde_json::to_value(&relation)?;
        assert_eq!(encoded["relationships"], 0);
        assert!(encoded.get("relationships_reason").is_none());
        Ok(())
    }

    #[test]
    fn relation_metadata_preserves_each_named_unknown_count_reason() -> TestResult {
        for (name, expected) in [
            ("withheld", RelationCountReason::Withheld),
            ("counts_not_ready", RelationCountReason::CountsNotReady),
        ] {
            let text = format!(
                r#"{{"relation":"links","from_collection":"records","to_collection":"records","cardinality":"many_to_many","relationships":null,"relationships_reason":"{name}"}}"#
            );
            let relation: RelationInfo = serde_json::from_str(&text)?;
            assert_eq!(relation.relationships, None);
            assert_eq!(relation.relationships_reason, Some(expected));
            let encoded = serde_json::to_value(&relation)?;
            assert!(encoded["relationships"].is_null());
            assert_eq!(encoded["relationships_reason"], name);
        }
        Ok(())
    }

    #[test]
    fn version_uses_decimal_strings_without_rounding() -> TestResult {
        let text = r#"{"generation":"18446744073709551615","sequence":"9007199254740993"}"#;
        let version: Version = serde_json::from_str(text)?;
        assert_eq!(version.0.generation, u64::MAX);
        assert_eq!(version.0.sequence, 9_007_199_254_740_993);
        assert_eq!(serde_json::to_string(&version)?, text);
        for invalid in [
            r#"{"generation":1,"sequence":"2"}"#,
            r#"{"generation":"1","sequence":2}"#,
            r#"{"generation":"18446744073709551616","sequence":"2"}"#,
            r#"{"generation":"1","sequence":"1e2"}"#,
            r#"{"generation":"1","sequence":"-1"}"#,
            r#"{"generation":"1","sequence":"2","extra":true}"#,
        ] {
            assert!(
                serde_json::from_str::<Version>(invalid).is_err(),
                "{invalid}"
            );
        }
        Ok(())
    }

    #[test]
    fn a_record_retains_its_number_spelling_through_input_and_output() -> TestResult {
        for body in [
            r#"{"n":1e2}"#,
            r#"{ "n" : 1E+02, "zero": -0, "fraction": 1.2300 }"#,
            r#"{"big":18446744073709551616001,"nested":[1e-09,0.00]}"#,
        ] {
            let text = format!(
                r#"{{{WRITE},"collection":"records","records":[{{"document_id":"a","document":{body}}}]}}"#
            );
            let input: PutRecordsInput = serde_json::from_str(&text)?;
            assert_eq!(input.records[0].document.get(), body);
            let encoded = serde_json::to_string(&input)?;
            let again: PutRecordsInput = serde_json::from_str(&encoded)?;
            assert_eq!(again.records[0].document.get(), body);
            let output_text = format!(
                r#"{{"selection":{SELECTED},"rows":{{"entries":[{{"value":{body},"origin":null}}],"next_after":null}}}}"#
            );
            let output: RunQueryOutput = serde_json::from_str(&output_text)?;
            let encoded = serde_json::to_string(&output)?;
            let again: RunQueryOutput = serde_json::from_str(&encoded)?;
            assert_eq!(again.rows.entries[0].value.get(), body);
            let value_text = format!(r#"{{"kind":"value","value":{body}}}"#);
            let value: super::ReviewValue = serde_json::from_str(&value_text)?;
            let encoded = serde_json::to_string(&value)?;
            let again: super::ReviewValue = serde_json::from_str(&encoded)?;
            let super::ReviewValue::Value { value } = again else {
                return Err("present review value decoded as absent".into());
            };
            assert_eq!(value.get(), body);
        }
        for text in [
            r#"{"kind":"absent"}"#,
            r#"{"kind":"value","value":null}"#,
            r#"{"kind":"value","value":""}"#,
        ] {
            let value: super::ReviewValue = serde_json::from_str(text)?;
            assert_eq!(serde_json::to_string(&value)?, text);
        }
        for invalid in [
            r#"{"kind":"absent","value":null}"#,
            r#"{"kind":"value"}"#,
            r#"{"kind":"absent","extra":true}"#,
            r#"{"kind":"other"}"#,
        ] {
            assert!(serde_json::from_str::<super::ReviewValue>(invalid).is_err());
        }
        Ok(())
    }

    #[test]
    fn empty_imports_and_zero_page_limits_are_refused() {
        let empty = format!(r#"{{{WRITE},"collection":"records","records":[]}}"#);
        assert!(serde_json::from_str::<PutRecordsInput>(&empty).is_err());
        for page in [r#"{"rows":0,"bytes":4096}"#, r#"{"rows":10,"bytes":0}"#] {
            assert!(serde_json::from_str::<PageLimits>(page).is_err());
        }
    }

    #[test]
    fn a_write_never_defaults_its_branch() -> TestResult {
        let fixture = inputs();
        for (name, input) in &fixture[3..9] {
            let mut value: Value = serde_json::from_str(input)?;
            value
                .as_object_mut()
                .ok_or("input is not an object")?
                .remove("branch");
            assert!(value.get("branch").is_none(), "{name}");
            let encoded = serde_json::to_string(&value)?;
            let refused = match *name {
                "define_collection" => {
                    serde_json::from_str::<DefineCollectionInput>(&encoded).is_err()
                }
                "put_records" => serde_json::from_str::<PutRecordsInput>(&encoded).is_err(),
                "delete_record" => serde_json::from_str::<DeleteRecordInput>(&encoded).is_err(),
                "link_records" => serde_json::from_str::<LinkRecordsInput>(&encoded).is_err(),
                "unlink_records" => serde_json::from_str::<UnlinkRecordsInput>(&encoded).is_err(),
                "create_branch" => serde_json::from_str::<CreateBranchInput>(&encoded).is_err(),
                _ => return Err("unexpected writing tool fixture".into()),
            };
            assert!(refused, "{name}");
        }
        Ok(())
    }
    #[test]
    fn a_collection_object_keeps_its_original_text() -> TestResult {
        use super::CollectionShape;

        let text = r#"{ "type":"object", "minimum":1e2, "maximum":18446744073709551616001 }"#;
        let shape: CollectionShape = serde_json::from_str(text)?;
        assert_eq!(serde_json::to_string(&shape)?, text);
        for invalid in ["[]", r#""object""#, "123"] {
            assert!(serde_json::from_str::<CollectionShape>(invalid).is_err());
        }
        Ok(())
    }
}