rustledger-ffi-wasi 0.21.0

Slimmed FFI-support helpers reused by the rustledger WASI component FFI (loader orchestration + WIT-input construction + directive hashing; the wasip1 JSON-RPC surface and Directive-to-JSON DTO were removed in #1419)
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
//! Input types for JSON deserialization.

use std::collections::HashMap;

use rustledger_core::{Directive, MetaValue, Metadata, NaiveDate};
use serde::Deserialize;

/// Parse an `InputAmount` to a host `Amount`, propagating decimal parse
/// errors instead of silently coercing them to zero.
///
/// Pre-fix every amount-bearing field on the wire used
/// `unwrap_or_else(|_| Decimal::from(0))`, which meant a balance
/// assertion like `{"amount": {"number": "garbage", "currency":
/// "USD"}}` was accepted as `0 USD` — silently defeating balance
/// checks (review B-4.1). All callers now propagate the parse error
/// to the wire client.
fn parse_input_amount(
    field: &str,
    amount: &InputAmount,
) -> Result<rustledger_core::Amount, String> {
    let number = rustledger_core::Decimal::from_str_exact(&amount.number)
        .map_err(|e| format!("invalid {field} number {:?}: {e}", amount.number))?;
    Ok(rustledger_core::Amount {
        number,
        currency: amount.currency.clone().into(),
    })
}

/// Input amount for entry creation.
#[derive(Debug, Deserialize, Clone)]
pub struct InputAmount {
    pub number: String,
    pub currency: String,
}

/// Input cost-number for entry creation.
///
/// Mirrors the host `CostNumber` enum on the wire. Consumers supply
/// `{"kind": "per_unit", "value": "..."}` or `{"kind": "total", "value":
/// "..."}` for unbooked specs. `per_unit_from_total` is reserved for
/// already-booked posting input and is rejected if the per-unit and
/// total are inconsistent with the supplied units.
#[derive(Debug, Deserialize, Clone)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum InputCostNumber {
    /// `{value USD}` — per-unit cost.
    PerUnit {
        /// Per-unit value.
        value: String,
    },
    /// `{{value USD}}` — total cost.
    Total {
        /// Total value.
        value: String,
    },
    /// `{per_unit # total USD}` — compound cost as written (beancount
    /// `compound_amount`); the cost totals `N * per_unit + total`.
    Compound {
        /// Per-unit component (zero when omitted).
        per_unit: String,
        /// Lump-total component (zero when omitted).
        total: String,
    },
    /// Post-booking: derived per-unit and preserved source total.
    PerUnitFromTotal {
        /// Derived per-unit.
        per_unit: String,
        /// Source total.
        total: String,
    },
}

/// Input cost for entry creation.
///
/// `Option` fields follow serde's standard convention: an omitted JSON
/// field is treated as `None` (this can't be tightened without a
/// custom `Deserialize` impl — serde's `Option` deserializer is
/// inherently lenient). `#[serde(deny_unknown_fields)]` catches the
/// other half of the client-bug risk: a misspelled field name will
/// fail to parse instead of silently being dropped (review A-3.8).
#[derive(Debug, Deserialize, Clone)]
#[serde(deny_unknown_fields)]
pub struct InputCost {
    /// Cost number (per-unit, total, or post-booking pair).
    /// `None` / absent corresponds to a bare `{}` cost spec.
    #[serde(default)]
    pub number: Option<InputCostNumber>,
    /// Cost currency.
    #[serde(default)]
    pub currency: Option<String>,
    /// Acquisition date.
    #[serde(default)]
    pub date: Option<String>,
    /// Lot label.
    #[serde(default)]
    pub label: Option<String>,
    /// Merge-into-existing-lot flag (the `*` marker on a cost spec —
    /// triggers average-cost booking for the position). Pre-A-4.6 the
    /// FFI bridge hard-coded `false`, which silently diverged from the
    /// plugin egress (`from_wrapper.rs`) that does accept the field.
    /// Both ingress surfaces now consume `merge` uniformly.
    #[serde(default)]
    pub merge: bool,
}

/// Input posting for entry creation.
#[derive(Debug, Deserialize, Clone)]
pub struct InputPosting {
    pub account: String,
    #[serde(default)]
    pub units: Option<InputAmount>,
    #[serde(default)]
    pub cost: Option<InputCost>,
    #[serde(default)]
    pub price: Option<InputAmount>,
    #[serde(default)]
    pub meta: HashMap<String, serde_json::Value>,
}

/// Input entry for create-entry/format-entry commands.
#[derive(Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum InputEntry {
    Transaction {
        date: String,
        #[serde(default = "default_flag")]
        flag: String,
        #[serde(default)]
        payee: Option<String>,
        #[serde(default)]
        narration: Option<String>,
        #[serde(default)]
        tags: Vec<String>,
        #[serde(default)]
        links: Vec<String>,
        #[serde(default)]
        postings: Vec<InputPosting>,
        #[serde(default)]
        meta: HashMap<String, serde_json::Value>,
    },
    Open {
        date: String,
        account: String,
        #[serde(default)]
        currencies: Vec<String>,
        #[serde(default)]
        booking: Option<String>,
        #[serde(default)]
        meta: HashMap<String, serde_json::Value>,
    },
    Close {
        date: String,
        account: String,
        #[serde(default)]
        meta: HashMap<String, serde_json::Value>,
    },
    Balance {
        date: String,
        account: String,
        amount: InputAmount,
        #[serde(default)]
        meta: HashMap<String, serde_json::Value>,
    },
    Pad {
        date: String,
        account: String,
        source_account: String,
        #[serde(default)]
        meta: HashMap<String, serde_json::Value>,
    },
    Commodity {
        date: String,
        currency: String,
        #[serde(default)]
        meta: HashMap<String, serde_json::Value>,
    },
    Price {
        date: String,
        currency: String,
        amount: InputAmount,
        #[serde(default)]
        meta: HashMap<String, serde_json::Value>,
    },
    Event {
        date: String,
        event_type: String,
        value: String,
        #[serde(default)]
        meta: HashMap<String, serde_json::Value>,
    },
    Note {
        date: String,
        account: String,
        comment: String,
        #[serde(default)]
        meta: HashMap<String, serde_json::Value>,
    },
    Document {
        date: String,
        account: String,
        path: String,
        /// Tags attached to the document directive (issue #1144 added
        /// these to core `Document`; plumbed through to the RPC input
        /// in #1213).
        #[serde(default)]
        tags: Vec<String>,
        /// Links attached to the document directive (issue #1144).
        #[serde(default)]
        links: Vec<String>,
        #[serde(default)]
        meta: HashMap<String, serde_json::Value>,
    },
    Query {
        date: String,
        name: String,
        query_string: String,
        #[serde(default)]
        meta: HashMap<String, serde_json::Value>,
    },
    Custom {
        date: String,
        custom_type: String,
        #[serde(default)]
        values: Vec<serde_json::Value>,
        #[serde(default)]
        meta: HashMap<String, serde_json::Value>,
    },
}

fn default_flag() -> String {
    "*".to_string()
}

/// Convert a JSON metadata value to a core `MetaValue`.
///
/// Thin wrapper over the single source [`rustledger_core::json_to_meta_value`];
/// kept so call sites read in ffi-wasi terms. Unparsable numbers / unrecognized
/// shapes become `MetaValue::None` (informational metadata, no coercion/panic).
pub fn json_to_meta_value(value: &serde_json::Value) -> MetaValue {
    rustledger_core::json_to_meta_value(value)
}

/// Convert `HashMap<String, Value>` to core Metadata.
pub fn json_map_to_metadata(map: &HashMap<String, serde_json::Value>) -> Metadata {
    map.iter()
        .map(|(k, v)| (k.clone(), json_to_meta_value(v)))
        .collect()
}

/// Validate a wire-supplied account name and convert it, rejecting names the
/// parser could never read back. The builder path (`entry.create` /
/// `entry.createBatch`) bypasses the loader pipeline entirely, so without
/// this gate it admitted arbitrary strings as accounts — weaker than any
/// surface in the system, and the resulting directives could not round-trip
/// through text. The rule is the canonical
/// [`rustledger_parser::is_valid_account_name`] (the lexer itself).
fn parse_account(context: &str, value: &str) -> Result<rustledger_core::Account, String> {
    if rustledger_parser::is_valid_account_name(value) {
        Ok(value.to_string().into())
    } else {
        Err(format!(
            "invalid {context} account {value:?}: not a valid beancount account \
             name (expected Type:Component[:Component...] — components start \
             with an uppercase or caseless letter, sub-components may start \
             with a digit; letters, digits, and hyphens only)"
        ))
    }
}

/// Convert `InputEntry` to core Directive.
pub fn input_entry_to_directive(entry: &InputEntry) -> Result<Directive, String> {
    match entry {
        InputEntry::Transaction {
            date,
            flag,
            payee,
            narration,
            tags,
            links,
            postings,
            meta,
        } => {
            let date = date
                .parse::<NaiveDate>()
                .map_err(|e| format!("Invalid date '{date}': {e}"))?;

            let flag = match flag.as_str() {
                "*" | "txn" => '*',
                "!" => '!',
                other => other.chars().next().unwrap_or('*'),
            };

            let postings: Vec<rustledger_core::Spanned<rustledger_core::Posting>> = postings
                .iter()
                .map(|p| {
                    let units = p
                        .units
                        .as_ref()
                        .map(|u| parse_input_amount("posting units", u))
                        .transpose()?
                        .map(rustledger_core::IncompleteAmount::Complete);

                    let cost = p
                        .cost
                        .as_ref()
                        .map(|c| {
                            // The wire `InputCostNumber` is a tagged enum
                            // mirroring the host `CostNumber`. The type
                            // system prevents the both-set state; we
                            // additionally enforce the
                            // `per_unit * |units| == total` invariant for
                            // PerUnitFromTotal so external clients cannot
                            // smuggle in inconsistent post-booking pairs.
                            // Inconsistent pairs become a parse error
                            // (review B-3.1) — silently falling back to
                            // PerUnit and dropping the supplied total
                            // would itself be a corruption pattern.
                            let parse = |s: &str| {
                                rustledger_core::Decimal::from_str_exact(s).map_err(|e| {
                                    format!("invalid cost number {s:?}: {e}")
                                })
                            };
                            let posting_units = units
                                .as_ref()
                                .and_then(|u: &rustledger_core::IncompleteAmount| u.as_amount());
                            let number = match c.number.as_ref() {
                                None => None,
                                Some(crate::types::input::InputCostNumber::PerUnit { value }) => {
                                    Some(rustledger_core::CostNumber::PerUnit { value: parse(value)? })
                                }
                                Some(crate::types::input::InputCostNumber::Total { value }) => {
                                    Some(rustledger_core::CostNumber::Total { value: parse(value)? })
                                }
                                Some(crate::types::input::InputCostNumber::Compound {
                                    per_unit,
                                    total,
                                }) => Some(rustledger_core::CostNumber::Compound {
                                    per_unit: parse(per_unit)?,
                                    total: parse(total)?,
                                }),
                                Some(crate::types::input::InputCostNumber::PerUnitFromTotal {
                                    per_unit,
                                    total,
                                }) => {
                                    let per_unit_d = parse(per_unit)?;
                                    let total_d = parse(total)?;
                                    // PerUnitFromTotal is the post-booking
                                    // shape — the wire client MUST supply
                                    // units. Missing units → reject (not
                                    // "fall back to PerUnit", which would
                                    // silently drop the supplied total).
                                    let units_n = posting_units.as_ref().map(|a| a.number).ok_or_else(|| {
                                        "PerUnitFromTotal cost requires units on the posting — \
                                         this is the post-booking shape and is meaningless without units. \
                                         Send `{kind:\"per_unit\", value:...}` or `{kind:\"total\", value:...}` for unbooked specs.".to_string()
                                    })?;
                                    let booked = rustledger_core::BookedCost::try_new(
                                        per_unit_d, total_d, units_n,
                                    )
                                    .map_err(|e| format!("{e}"))?;
                                    Some(rustledger_core::CostNumber::PerUnitFromTotal(booked))
                                }
                            };
                            Ok::<_, String>(rustledger_core::CostSpec {
                                number,
                                currency: c.currency.clone().map(Into::into),
                                date: c.date.as_ref().and_then(|d| d.parse::<NaiveDate>().ok()),
                                label: c.label.clone(),
                                merge: c.merge,
                            })
                        })
                        .transpose()?;

                    let price = p
                        .price
                        .as_ref()
                        .map(|pr| parse_input_amount("posting price", pr))
                        .transpose()?
                        .map(rustledger_core::PriceAnnotation::unit);

                    Ok::<_, String>(rustledger_core::Spanned::synthesized(rustledger_core::Posting {
                        account: parse_account("posting", &p.account)?,
                        units,
                        cost,
                        price,
                        flag: None,
                        meta: json_map_to_metadata(&p.meta),
                        comments: Vec::new(),
                        trailing_comments: Vec::new(),
                    }))
                })
                .collect::<Result<_, String>>()?;

            Ok(Directive::Transaction(rustledger_core::Transaction {
                date,
                flag,
                payee: payee.clone().map(Into::into),
                narration: narration.clone().unwrap_or_default().into(),
                tags: tags.iter().map(|t| t.clone().into()).collect(),
                links: links.iter().map(|l| l.clone().into()).collect(),
                postings,
                meta: json_map_to_metadata(meta),
                trailing_comments: Vec::new(),
            }))
        }
        InputEntry::Open {
            date,
            account,
            currencies,
            booking,
            meta,
        } => {
            let date = date
                .parse::<NaiveDate>()
                .map_err(|e| format!("Invalid date '{date}': {e}"))?;
            Ok(Directive::Open(rustledger_core::Open {
                date,
                account: parse_account("open", account)?,
                currencies: currencies.iter().map(|c| c.clone().into()).collect(),
                booking: booking.clone(),
                meta: json_map_to_metadata(meta),
            }))
        }
        InputEntry::Close {
            date,
            account,
            meta,
        } => {
            let date = date
                .parse::<NaiveDate>()
                .map_err(|e| format!("Invalid date '{date}': {e}"))?;
            Ok(Directive::Close(rustledger_core::Close {
                date,
                account: parse_account("close", account)?,
                meta: json_map_to_metadata(meta),
            }))
        }
        InputEntry::Balance {
            date,
            account,
            amount,
            meta,
        } => {
            let date = date
                .parse::<NaiveDate>()
                .map_err(|e| format!("Invalid date '{date}': {e}"))?;
            Ok(Directive::Balance(rustledger_core::Balance {
                date,
                account: parse_account("balance", account)?,
                amount: parse_input_amount("balance amount", amount)?,
                tolerance: None,
                meta: json_map_to_metadata(meta),
            }))
        }
        InputEntry::Pad {
            date,
            account,
            source_account,
            meta,
        } => {
            let date = date
                .parse::<NaiveDate>()
                .map_err(|e| format!("Invalid date '{date}': {e}"))?;
            Ok(Directive::Pad(rustledger_core::Pad {
                date,
                account: parse_account("pad", account)?,
                source_account: parse_account("pad source", source_account)?,
                meta: json_map_to_metadata(meta),
            }))
        }
        InputEntry::Commodity {
            date,
            currency,
            meta,
        } => {
            let date = date
                .parse::<NaiveDate>()
                .map_err(|e| format!("Invalid date '{date}': {e}"))?;
            Ok(Directive::Commodity(rustledger_core::Commodity {
                date,
                currency: currency.clone().into(),
                meta: json_map_to_metadata(meta),
            }))
        }
        InputEntry::Price {
            date,
            currency,
            amount,
            meta,
        } => {
            let date = date
                .parse::<NaiveDate>()
                .map_err(|e| format!("Invalid date '{date}': {e}"))?;
            Ok(Directive::Price(rustledger_core::Price {
                date,
                currency: currency.clone().into(),
                amount: parse_input_amount("price amount", amount)?,
                meta: json_map_to_metadata(meta),
            }))
        }
        InputEntry::Event {
            date,
            event_type,
            value,
            meta,
        } => {
            let date = date
                .parse::<NaiveDate>()
                .map_err(|e| format!("Invalid date '{date}': {e}"))?;
            Ok(Directive::Event(rustledger_core::Event {
                date,
                event_type: event_type.clone(),
                value: value.clone(),
                meta: json_map_to_metadata(meta),
            }))
        }
        InputEntry::Note {
            date,
            account,
            comment,
            meta,
        } => {
            let date = date
                .parse::<NaiveDate>()
                .map_err(|e| format!("Invalid date '{date}': {e}"))?;
            Ok(Directive::Note(rustledger_core::Note {
                date,
                account: parse_account("note", account)?,
                comment: comment.clone(),
                meta: json_map_to_metadata(meta),
            }))
        }
        InputEntry::Document {
            date,
            account,
            path,
            tags,
            links,
            meta,
        } => {
            let date = date
                .parse::<NaiveDate>()
                .map_err(|e| format!("Invalid date '{date}': {e}"))?;
            Ok(Directive::Document(rustledger_core::Document {
                date,
                account: parse_account("document", account)?,
                path: path.clone(),
                tags: tags.iter().map(|t| t.clone().into()).collect(),
                links: links.iter().map(|l| l.clone().into()).collect(),
                meta: json_map_to_metadata(meta),
            }))
        }
        InputEntry::Query {
            date,
            name,
            query_string,
            meta,
        } => {
            let date = date
                .parse::<NaiveDate>()
                .map_err(|e| format!("Invalid date '{date}': {e}"))?;
            Ok(Directive::Query(rustledger_core::Query {
                date,
                name: name.clone(),
                query: query_string.clone(),
                meta: json_map_to_metadata(meta),
            }))
        }
        InputEntry::Custom {
            date,
            custom_type,
            values,
            meta,
        } => {
            let date = date
                .parse::<NaiveDate>()
                .map_err(|e| format!("Invalid date '{date}': {e}"))?;
            Ok(Directive::Custom(rustledger_core::Custom {
                date,
                custom_type: custom_type.clone(),
                values: values.iter().map(json_to_meta_value).collect(),
                meta: json_map_to_metadata(meta),
            }))
        }
    }
}

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

    // ===== Input cost-number wire-format tests (#1164) =====
    //
    // The wire `InputCostNumber` enum is the boundary that makes the
    // both-set invalid state structurally unrepresentable. These tests
    // pin that property — neither serde nor the bridge can construct
    // a CostSpec with both per-unit AND total set unless they come in
    // via the explicit `per_unit_from_total` variant (which carries
    // the post-booking invariant).

    #[test]
    fn input_cost_number_per_unit_parses() {
        let json = r#"{"kind": "per_unit", "value": "100"}"#;
        let cn: InputCostNumber = serde_json::from_str(json).unwrap();
        match cn {
            InputCostNumber::PerUnit { value } => assert_eq!(value, "100"),
            _ => panic!("expected PerUnit"),
        }
    }

    #[test]
    fn input_cost_number_total_parses() {
        let json = r#"{"kind": "total", "value": "1500"}"#;
        let cn: InputCostNumber = serde_json::from_str(json).unwrap();
        match cn {
            InputCostNumber::Total { value } => assert_eq!(value, "1500"),
            _ => panic!("expected Total"),
        }
    }

    #[test]
    fn input_cost_number_per_unit_from_total_parses() {
        let json = r#"{"kind": "per_unit_from_total", "per_unit": "150", "total": "300"}"#;
        let cn: InputCostNumber = serde_json::from_str(json).unwrap();
        match cn {
            InputCostNumber::PerUnitFromTotal { per_unit, total } => {
                assert_eq!(per_unit, "150");
                assert_eq!(total, "300");
            }
            _ => panic!("expected PerUnitFromTotal"),
        }
    }

    #[test]
    fn input_cost_number_rejects_unknown_kind() {
        // Wire shape strict: unknown discriminator is an error, not a
        // silent fallback. Important so future variants don't get
        // confused with mistyped input.
        let json = r#"{"kind": "per_unit_with_total", "value": "100"}"#;
        let result: Result<InputCostNumber, _> = serde_json::from_str(json);
        assert!(result.is_err(), "expected error for unknown kind, got Ok");
    }

    #[test]
    fn input_cost_number_rejects_missing_kind() {
        // No `kind` discriminator → serde can't pick a variant.
        let json = r#"{"value": "100"}"#;
        let result: Result<InputCostNumber, _> = serde_json::from_str(json);
        assert!(result.is_err(), "expected error without kind tag, got Ok");
    }

    #[test]
    fn input_cost_number_rejects_legacy_flat_shape() {
        // The pre-#1164 wire shape `{"number_per": "...", "number_total": null}`
        // is gone. Sending it gets a parse error, which is the right
        // behavior — silent coercion to `PerUnit` would mask client
        // bugs and re-introduce the invalid both-set state through
        // the bridge.
        let json = r#"{"number_per": "100", "number_total": null}"#;
        let result: Result<InputCostNumber, _> = serde_json::from_str(json);
        assert!(
            result.is_err(),
            "expected error for legacy flat shape, got Ok"
        );
    }

    #[test]
    fn input_cost_with_no_number_parses_as_bare_brace() {
        // `{}` lot match: number absent → bare cost spec. Serde's
        // Option deserializer treats missing fields as `None` by
        // convention; we lean on `deny_unknown_fields` for the other
        // client-bug case (misspelled field).
        let json = r#"{"currency": "USD"}"#;
        let cost: InputCost = serde_json::from_str(json).unwrap();
        assert!(cost.number.is_none());
        assert_eq!(cost.currency.as_deref(), Some("USD"));
    }

    #[test]
    fn input_cost_rejects_unknown_field() {
        // `deny_unknown_fields` catches misspelled fields that would
        // otherwise be silently dropped (review A-3.8). A client
        // sending an unrecognized key (e.g. `cost_number` instead of
        // `number`) gets a parse error instead of an unexpectedly
        // bare cost spec on the directive.
        let json = r#"{"cost_number": {"kind": "per_unit", "value": "100"}, "currency": "USD"}"#;
        let result: Result<InputCost, _> = serde_json::from_str(json);
        assert!(
            result.is_err(),
            "expected parse error for unknown field, got Ok"
        );
    }

    #[test]
    fn input_cost_per_unit_from_total_rejected_when_inconsistent() {
        // Bridge-level test through the actual conversion path:
        // PerUnitFromTotal with mismatched per_unit/total/units must
        // produce a typed error string, not silently coerce to
        // PerUnit. Pre-fix this fell back to `PerUnit { value:
        // per_unit_d }`, dropping the supplied total.
        let entry_json = r#"{
            "type": "transaction",
            "date": "2024-01-15",
            "flag": "*",
            "payee": null,
            "narration": "Buy stock",
            "tags": [],
            "links": [],
            "meta": {},
            "postings": [
                {
                    "account": "Assets:Stock",
                    "units": {"number": "10", "currency": "STK"},
                    "cost": {
                        "number": {"kind": "per_unit_from_total", "per_unit": "999999", "total": "0.01"},
                        "currency": "USD",
                        "date": null,
                        "label": null
                    },
                    "price": null,
                    "meta": {}
                }
            ]
        }"#;
        let entry: InputEntry = serde_json::from_str(entry_json).unwrap();
        let result = input_entry_to_directive(&entry);
        assert!(
            result.is_err(),
            "inconsistent PerUnitFromTotal must reject at the bridge"
        );
        let err = result.unwrap_err();
        // Diagnostic mentions the invariant so plugin authors can fix
        // their wire client.
        assert!(
            err.contains("invariant") || err.contains("per_unit") || err.contains("total"),
            "error message must describe the invariant violation, got: {err}"
        );
    }

    #[test]
    fn balance_with_malformed_amount_is_rejected() {
        // The load-bearing B-4.1 regression guard: a balance
        // assertion with a non-numeric amount field used to be
        // silently accepted as `0 USD`, defeating balance checks.
        // The wire bridge now propagates the parse error so the
        // client knows their payload was malformed.
        let entry_json = r#"{
            "type": "balance",
            "date": "2024-01-15",
            "account": "Assets:Bank",
            "amount": {"number": "garbage", "currency": "USD"},
            "meta": {}
        }"#;
        let entry: InputEntry = serde_json::from_str(entry_json).unwrap();
        let result = input_entry_to_directive(&entry);
        assert!(
            result.is_err(),
            "malformed balance amount must surface a parse error, not silently coerce to 0"
        );
        let err = result.unwrap_err();
        assert!(
            err.contains("balance amount") && err.contains("garbage"),
            "error must name both the field and the offending value, got: {err}"
        );
    }

    #[test]
    fn price_with_malformed_amount_is_rejected() {
        let entry_json = r#"{
            "type": "price",
            "date": "2024-01-15",
            "currency": "AAPL",
            "amount": {"number": "abc", "currency": "USD"},
            "meta": {}
        }"#;
        let entry: InputEntry = serde_json::from_str(entry_json).unwrap();
        let result = input_entry_to_directive(&entry);
        assert!(
            result.is_err(),
            "malformed price amount must surface a parse error"
        );
        assert!(result.unwrap_err().contains("price amount"));
    }

    #[test]
    fn posting_with_malformed_units_is_rejected() {
        let entry_json = r#"{
            "type": "transaction",
            "date": "2024-01-15",
            "flag": "*",
            "payee": null,
            "narration": "Buy",
            "tags": [], "links": [],
            "meta": {},
            "postings": [
                {
                    "account": "Assets:Stock",
                    "units": {"number": "not-a-number", "currency": "STK"},
                    "cost": null,
                    "price": null,
                    "meta": {}
                }
            ]
        }"#;
        let entry: InputEntry = serde_json::from_str(entry_json).unwrap();
        let result = input_entry_to_directive(&entry);
        assert!(
            result.is_err(),
            "malformed posting units must surface a parse error"
        );
        assert!(result.unwrap_err().contains("posting units"));
    }

    /// Regression for #1213: `Document` directives constructed via
    /// the RPC input side must carry `tags` and `links` through to
    /// the resulting core `Document`. Pre-#1213 the bridge hardcoded
    /// empty `Vec::new()` even when the caller supplied the fields.
    #[test]
    fn document_tags_and_links_round_trip_1213() {
        let entry_json = r#"{
            "type": "document",
            "date": "2024-01-15",
            "account": "Assets:Bank",
            "path": "statements/2024-01.pdf",
            "tags": ["statement", "bank"],
            "links": ["inv-2024-01"],
            "meta": {}
        }"#;
        let entry: InputEntry = serde_json::from_str(entry_json).unwrap();
        let directive = input_entry_to_directive(&entry).expect("valid document must convert");
        let Directive::Document(doc) = directive else {
            panic!("expected Document directive");
        };
        assert_eq!(doc.tags.len(), 2);
        assert_eq!(doc.tags[0].to_string(), "statement");
        assert_eq!(doc.tags[1].to_string(), "bank");
        assert_eq!(doc.links.len(), 1);
        assert_eq!(doc.links[0].to_string(), "inv-2024-01");
    }

    /// Backward-compat: a Document payload without `tags`/`links`
    /// fields (the pre-#1213 RPC clients still in the wild) must
    /// continue to deserialize as empty vectors via `serde(default)`.
    #[test]
    fn document_tags_and_links_default_to_empty_1213() {
        let entry_json = r#"{
            "type": "document",
            "date": "2024-01-15",
            "account": "Assets:Bank",
            "path": "statements/2024-01.pdf",
            "meta": {}
        }"#;
        let entry: InputEntry = serde_json::from_str(entry_json).unwrap();
        let directive = input_entry_to_directive(&entry).expect("legacy payload must convert");
        let Directive::Document(doc) = directive else {
            panic!("expected Document directive");
        };
        assert!(doc.tags.is_empty());
        assert!(doc.links.is_empty());
    }

    #[test]
    fn input_cost_per_unit_from_total_rejected_when_units_missing() {
        // PerUnitFromTotal is post-booking; a plugin sending it
        // without units is malformed (review B-3.1). The bridge must
        // reject rather than default units to 0 (which the
        // pre-fix `invariant_holds` short-circuit accepted).
        let entry_json = r#"{
            "type": "transaction",
            "date": "2024-01-15",
            "flag": "*",
            "payee": null,
            "narration": "Buy stock",
            "tags": [],
            "links": [],
            "meta": {},
            "postings": [
                {
                    "account": "Assets:Stock",
                    "units": null,
                    "cost": {
                        "number": {"kind": "per_unit_from_total", "per_unit": "999999", "total": "0.01"},
                        "currency": "USD",
                        "date": null,
                        "label": null
                    },
                    "price": null,
                    "meta": {}
                }
            ]
        }"#;
        let entry: InputEntry = serde_json::from_str(entry_json).unwrap();
        let result = input_entry_to_directive(&entry);
        assert!(
            result.is_err(),
            "PerUnitFromTotal without units must reject (post-booking shape requires units)"
        );
    }

    // ===== Builder ingress account validation (L4) =====

    #[test]
    fn create_rejects_unparsable_account() {
        // The create/batch path bypasses the loader pipeline; accounts must
        // still be held to the canonical lexer rule or unroundtrippable
        // directives enter programmatically.
        let entry = InputEntry::Open {
            date: "2024-01-01".to_string(),
            account: "assets:cash".to_string(), // lowercase root
            currencies: vec![],
            booking: None,
            meta: Default::default(),
        };
        let err = input_entry_to_directive(&entry).unwrap_err();
        assert!(err.contains("invalid open account"), "{err}");

        let entry = InputEntry::Close {
            date: "2024-01-01".to_string(),
            account: "Assets:Ca sh".to_string(),
            meta: Default::default(),
        };
        let err = input_entry_to_directive(&entry).unwrap_err();
        assert!(err.contains("invalid close account"), "{err}");
    }

    #[test]
    fn create_accepts_valid_unicode_account() {
        let entry = InputEntry::Open {
            date: "2024-01-01".to_string(),
            account: "資産:現金".to_string(),
            currencies: vec![],
            booking: None,
            meta: Default::default(),
        };
        let d = input_entry_to_directive(&entry).expect("valid unicode account");
        match d {
            Directive::Open(o) => assert_eq!(o.account.as_str(), "資産:現金"),
            other => panic!("expected Open, got {other:?}"),
        }
    }
}