termwright-protocol 0.3.2

Semantic side-channel client for the termwright terminal test driver: framing, render-commit markers, snapshot validation
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
//! Wire messages: typed builders for what an adapter sends, checked parsers
//! for what it receives.
//!
//! The adapter pushes commits, the driver issues requests, and either side may
//! send an error and close. Everything is validated against the active limits
//! before it is retained; failures are returned, never raised.

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};

use crate::error::ParseError;
use crate::framing::project_dto;
use crate::limits::Limits;
use crate::logs::{validate_log_record, LogRecord};
use crate::marker::MAX_SAFE_INTEGER;
use crate::roles::{valid_capability, Capability, ADAPTER_CAPABILITIES};
use crate::tree::Snapshot;
use crate::validate::validate_snapshot;
use crate::Violation;

/// The wire protocol identifier both sides must agree on.
pub const PROTOCOL_ID: &str = "termwright/2";

/// The current major version.
pub const PROTOCOL_VERSION: u8 = 2;

/// Longest token, identifier or free-text message accepted.
const MAX_IDENTIFIER_LENGTH: usize = 1024;

const ERROR_CODES: [&str; 7] = [
    "bad-token",
    "bad-version",
    "malformed",
    "limit-exceeded",
    "duplicate-semantic-key",
    "adapter-guarantee-violation",
    "internal",
];

const LIMIT_FIELDS: [&str; 11] = [
    "maxFrameBytes",
    "maxSnapshotBytes",
    "maxNodes",
    "maxDepth",
    "maxStringBytes",
    "maxRelationTargets",
    "maxQueuedFrames",
    "maxPendingWaiters",
    "maxSessions",
    "maxLogRecordBytes",
    "maxLogQueue",
];

/// Identifies the adapter implementation to the driver.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AdapterInfo {
    /// Accessible name; empty when the node has none.
    pub name: String,
    /// Adapter version string.
    pub version: String,
}

/// The adapter's handshake: sent exactly once, before anything else.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Hello {
    /// Wire discriminator (`type` on the wire).
    #[serde(rename = "type")]
    pub kind: String,
    /// Protocol identifier; must be `termwright/2`.
    pub protocol: String,
    /// Per-launch session token from the environment.
    pub token: String,
    /// Adapter name and version.
    pub adapter: AdapterInfo,
    /// What this adapter can provide.
    pub capabilities: Vec<Capability>,
    /// Present when the sender is a probe rather than a hand-written adapter.
    ///
    /// Carries what the probe can actually observe — framework and versions,
    /// the best identity it can produce, and its optional abilities — so the
    /// driver negotiates against measured capability rather than a floor.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub probe: Option<ProbeInfo>,
    /// Application providers frozen before this handshake.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub providers: Vec<EvidenceProviderRegistration>,
}

/// Application evidence producer frozen into hello negotiation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct EvidenceProviderRegistration {
    /// Stable provider identity.
    pub id: String,
    /// Provider implementation version.
    pub version: String,
    /// `native` or `declared`.
    pub method: String,
    /// Closed provider capability names frozen into the handshake.
    pub capabilities: Vec<String>,
}

/// How an object's identity behaves across frames.
///
/// `FrameLocal` is a legitimate answer, not a degraded one: in immediate mode
/// the widget is consumed by the render and nothing survives to be named
/// again. A consumer must not correlate frame-local values between frames.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ProbeIdentityKind {
    /// Identities survive across frames and may be correlated.
    Stable,
    /// Identities are meaningful only within their own frame.
    FrameLocal,
}

/// Strongest injection tier that actually engaged for this probe run.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ProbeInjectionTier {
    /// Public framework hook; no injection.
    T0,
    /// Add-only compilation unit.
    T1,
    /// Append-only source mutation.
    T2,
    /// Exact source/control-flow instrumentation.
    T3,
}

/// Whether the semantic tree includes authoritative framework geometry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ProbeSemanticClass {
    /// Semantic tree with framework geometry.
    A,
    /// Semantic tree without authoritative framework geometry.
    B,
}

/// Closed session-capability vocabulary used for named runtime degradation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum DegradedSessionCapability {
    /// Semantic tree publication.
    SemanticTree,
    /// Identity correlation across frames.
    StableIdentity,
    /// Framework-intended geometry.
    IntendedGeometry,
    /// Geometry clipped by framework ancestors.
    ClippedGeometry,
    /// Physically painted terminal region.
    PaintedRegion,
    /// Pointer target geometry.
    PointerGeometry,
    /// Authoritative pointer hit testing.
    PointerHitTesting,
    /// Framework focus state.
    Focus,
    /// Framework scroll state and actions.
    Scroll,
    /// Authoritative render ordering.
    RenderOrder,
    /// Semantic action strategies.
    ActionStrategies,
    /// Keyboard input transport.
    KeyboardInput,
    /// Pointer input transport.
    PointerInput,
    /// Focus input transport.
    FocusInput,
    /// Causally paired semantic and terminal revisions.
    PairedRevisions,
    /// Enumeration of screens other than the currently committed one.
    InactiveScreenTree,
    /// Children hidden behind an application-defined container abstraction.
    CustomContainerEnumeration,
}

/// Runtime attachment facts declared in a first-party probe handshake.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProbeInstrumentation {
    /// Strongest injection tier used by this concrete run.
    pub highest_tier: ProbeInjectionTier,
    /// Geometry completeness class of the emitted tree.
    pub semantic_class: ProbeSemanticClass,
    /// Named session capabilities intentionally unavailable in this integration.
    pub degraded_capabilities: Vec<DegradedSessionCapability>,
}

/// What a probe says about itself when it attaches.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProbeInfo {
    /// Framework name, e.g. `ratatui`.
    pub framework: String,
    /// Version of the framework, when the probe can determine it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub framework_version: Option<String>,
    /// Version of the probe itself, so a mismatch is diagnosable.
    pub probe_version: String,
    /// The best identity this probe can offer for any object.
    pub identity_kind: ProbeIdentityKind,
    /// Optional abilities, from the protocol's closed set.
    pub capabilities: Vec<String>,
    /// Runtime injection facts. Optional for older/custom protocol-v2 probes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instrumentation: Option<ProbeInstrumentation>,
}

impl ProbeInfo {
    /// Validate the closed probe declaration before any hello reaches the wire.
    pub fn validate(&self) -> Result<(), Violation> {
        const CAPABILITIES: &[&str] = &[
            "stable-identity",
            "intended-rect",
            "visible-rect",
            "operations",
            "annotations",
            "frame-begin",
            "paint-order",
        ];
        if self.framework.is_empty() || self.probe_version.is_empty() {
            return Err(Violation::new(
                "schema",
                "probe framework and probeVersion must be non-empty",
            ));
        }
        for (index, capability) in self.capabilities.iter().enumerate() {
            if !CAPABILITIES.contains(&capability.as_str()) {
                return Err(Violation::new(
                    "schema",
                    format!("unknown probe capability {capability}"),
                ));
            }
            if self.capabilities[..index].contains(capability) {
                return Err(Violation::new(
                    "schema",
                    format!("duplicate probe capability {capability}"),
                ));
            }
        }
        if self.identity_kind == ProbeIdentityKind::FrameLocal
            && self
                .capabilities
                .iter()
                .any(|capability| capability == "stable-identity")
        {
            return Err(Violation::new(
                "schema",
                "frame-local identity cannot advertise stable-identity",
            ));
        }
        if let Some(instrumentation) = &self.instrumentation {
            for (index, capability) in instrumentation.degraded_capabilities.iter().enumerate() {
                if instrumentation.degraded_capabilities[..index].contains(capability) {
                    return Err(Violation::new("schema", "duplicate degraded capability"));
                }
            }
            if instrumentation.semantic_class == ProbeSemanticClass::B
                && (!instrumentation
                    .degraded_capabilities
                    .contains(&DegradedSessionCapability::IntendedGeometry)
                    || !instrumentation
                        .degraded_capabilities
                        .contains(&DegradedSessionCapability::ClippedGeometry))
            {
                return Err(Violation::new(
                    "schema",
                    "semantic class B requires intended-geometry and clipped-geometry degradations",
                ));
            }
        }
        Ok(())
    }
}

impl Hello {
    /// Build a handshake for this adapter.
    pub fn new(token: &str, name: &str, version: &str, capabilities: Vec<Capability>) -> Self {
        Self {
            kind: "hello".into(),
            protocol: PROTOCOL_ID.into(),
            token: token.to_owned(),
            adapter: AdapterInfo {
                name: name.to_owned(),
                version: version.to_owned(),
            },
            capabilities,
            probe: None,
            providers: Vec::new(),
        }
    }

    /// Attach a probe's declaration to this handshake.
    #[must_use]
    pub fn with_probe(mut self, probe: ProbeInfo) -> Self {
        self.probe = Some(probe);
        self
    }

    /// Attach application evidence declarations before the hello is sent.
    #[must_use]
    pub fn with_providers(mut self, providers: Vec<EvidenceProviderRegistration>) -> Self {
        self.providers = providers;
        self
    }
}

/// Whether the adapter should emit render markers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct MarkerConfig {
    /// Whether the adapter should emit render markers.
    pub enabled: bool,
}

/// The log-channel allowance, sent only when the adapter announced the `logs`
/// capability. Absent means logs are disabled: an adapter that receives no
/// budget must not emit log messages at all.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LogBudget {
    /// Whether the driver wants log records at all.
    pub enabled: bool,
    /// Sustained ceiling on records per second.
    pub max_records_per_second: i64,
    /// Records allowed in a burst on top of the sustained rate.
    pub burst: i64,
}

/// The driver's reply: session id, negotiated limits, what to push.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HelloAck {
    /// Wire discriminator (`type` on the wire).
    #[serde(rename = "type")]
    pub kind: String,
    /// Protocol identifier; must be `termwright/2`.
    pub protocol: String,
    /// Session this snapshot belongs to.
    pub session_id: String,
    /// Ceilings the driver imposes for this session.
    pub limits: Limits,
    /// What the driver wants pushed: snapshots or revisions.
    pub subscribe: String,
    /// Whether render markers are wanted.
    pub marker: MarkerConfig,
    /// Log-channel budget; `None` means logs are disabled.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub logs: Option<LogBudget>,
}

/// Announces that a render was committed to the terminal.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct RevisionCommit {
    /// Wire discriminator (`type` on the wire).
    #[serde(rename = "type")]
    pub kind: &'static str,
    /// Render revision, strictly increasing per session.
    pub revision: i64,
}

impl RevisionCommit {
    /// Commit `revision`.
    pub fn new(revision: i64) -> Self {
        Self {
            kind: "revision-commit",
            revision,
        }
    }
}

/// Carries a full tree for one revision.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SnapshotMessage<'a> {
    /// Wire discriminator (`type` on the wire).
    #[serde(rename = "type")]
    pub kind: &'static str,
    /// The tree being carried.
    pub snapshot: &'a Snapshot,
}

impl<'a> SnapshotMessage<'a> {
    /// Wrap a snapshot in its envelope.
    pub fn new(snapshot: &'a Snapshot) -> Self {
        Self {
            kind: "snapshot",
            snapshot,
        }
    }
}

/// Carries one application log record to the driver.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct LogMessage<'a> {
    /// Wire discriminator (`type` on the wire).
    #[serde(rename = "type")]
    pub kind: &'static str,
    /// The record.
    pub record: &'a LogRecord,
}

impl<'a> LogMessage<'a> {
    /// Wrap a record in its envelope.
    pub fn new(record: &'a LogRecord) -> Self {
        Self {
            kind: "log",
            record,
        }
    }
}

/// Terminal error: the sender closes after emitting it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProtocolErrorMessage {
    /// Wire discriminator (`type` on the wire).
    #[serde(rename = "type")]
    pub kind: String,
    /// One of the five wire error codes.
    pub code: String,
    /// Human-readable detail; never carries the token.
    pub message: String,
}

impl ProtocolErrorMessage {
    /// Build an error message with one of the five wire codes.
    pub fn new(code: &str, message: impl Into<String>) -> Self {
        Self {
            kind: "error".into(),
            code: code.to_owned(),
            message: message.into(),
        }
    }
}

/// Capabilities for a tree-publishing adapter with qualified geometry.
pub fn default_capabilities() -> Vec<Capability> {
    vec![
        Capability::Tree,
        Capability::IntendedGeometry,
        Capability::ClippedGeometry,
        Capability::States,
        Capability::Actions,
        Capability::RenderRevisions,
    ]
}

// -- parsing ---------------------------------------------------------------

fn project(value: &Value, limits: &Limits) -> Result<(), ParseError> {
    project_dto(value, limits.max_depth).map_err(|violation| {
        if violation.code == "dto-depth" {
            ParseError::new("limit-exceeded", violation.to_string())
        } else {
            ParseError::malformed(violation.to_string())
        }
    })
}

fn as_message(value: &Value) -> Result<(&Map<String, Value>, &str), ParseError> {
    let object = value
        .as_object()
        .ok_or_else(|| ParseError::malformed("unknown or missing message type"))?;
    let kind = object
        .get("type")
        .and_then(Value::as_str)
        .ok_or_else(|| ParseError::malformed("unknown or missing message type"))?;
    Ok((object, kind))
}

/// Check that every required key is present, tolerating unknown ones.
fn required_keys(object: &Map<String, Value>, required: &[&str]) -> Result<(), ParseError> {
    for key in required {
        if !object.contains_key(*key) {
            return Err(ParseError::malformed(format!("missing field \"{key}\"")));
        }
    }
    Ok(())
}

fn require_keys(
    object: &Map<String, Value>,
    required: &[&str],
    optional: &[&str],
) -> Result<(), ParseError> {
    for key in required {
        if !object.contains_key(*key) {
            return Err(ParseError::malformed(format!("missing field \"{key}\"")));
        }
    }
    for key in object.keys() {
        if !required.contains(&key.as_str()) && !optional.contains(&key.as_str()) {
            return Err(ParseError::malformed(format!("unrecognized key \"{key}\"")));
        }
    }
    Ok(())
}

fn identifier(object: &Map<String, Value>, key: &str, allow_empty: bool) -> Result<(), ParseError> {
    let Some(text) = object.get(key).and_then(Value::as_str) else {
        return Err(ParseError::malformed(format!("{key}: expected a string")));
    };
    if text.len() > MAX_IDENTIFIER_LENGTH {
        return Err(ParseError::malformed(format!(
            "{key}: expected at most {MAX_IDENTIFIER_LENGTH} characters"
        )));
    }
    if !allow_empty && text.is_empty() {
        return Err(ParseError::malformed(format!(
            "{key}: expected a non-empty string"
        )));
    }
    Ok(())
}

fn whole_number(object: &Map<String, Value>, key: &str, positive: bool) -> Result<(), ParseError> {
    let number = object
        .get(key)
        .and_then(Value::as_i64)
        .filter(|n| n.abs() <= MAX_SAFE_INTEGER);
    match number {
        Some(number) if positive && number > 0 => Ok(()),
        Some(number) if !positive && number >= 0 => Ok(()),
        _ if positive => Err(ParseError::malformed(format!(
            "{key}: expected a positive safe integer"
        ))),
        _ => Err(ParseError::malformed(format!(
            "{key}: expected a non-negative safe integer"
        ))),
    }
}

fn check_embedded_snapshot(value: &Value, limits: &Limits) -> Result<(), ParseError> {
    match validate_snapshot(value, limits) {
        Ok(()) => Ok(()),
        Err(error) => {
            let code = match error.code {
                "bytes" | "count" | "depth" | "string-bytes" => "limit-exceeded",
                _ => "malformed",
            };
            Err(ParseError::new(code, format!("snapshot {error}")))
        }
    }
}

/// Validate the optional log-channel budget carried by `hello-ack`.
fn check_log_budget(value: &Value) -> Result<(), ParseError> {
    let budget = value
        .as_object()
        .ok_or_else(|| ParseError::malformed("logs: expected an object"))?;
    required_keys(budget, &["enabled", "maxRecordsPerSecond", "burst"])?;
    if !budget["enabled"].is_boolean() {
        return Err(ParseError::malformed("logs.enabled: expected a boolean"));
    }
    whole_number(budget, "maxRecordsPerSecond", true)?;
    whole_number(budget, "burst", false)
}

fn check_error_message(object: &Map<String, Value>, strict: bool) -> Result<(), ParseError> {
    if strict {
        require_keys(object, &["type", "code", "message"], &[])?;
    } else {
        required_keys(object, &["type", "code", "message"])?;
    }
    let code = object
        .get("code")
        .and_then(Value::as_str)
        .unwrap_or_default();
    if !ERROR_CODES.contains(&code) {
        return Err(ParseError::malformed("code: unknown error code"));
    }
    identifier(object, "message", true)
}

fn check_protocol_field(object: &Map<String, Value>) -> Result<(), ParseError> {
    match object.get("protocol").and_then(Value::as_str) {
        Some(protocol) if protocol != PROTOCOL_ID => Err(ParseError::new(
            "bad-version",
            format!("unsupported protocol {protocol}"),
        )),
        _ => Ok(()),
    }
}

/// Validate one adapter → driver message.
///
/// Strict: an unknown field from an adapter is a protocol error, not an
/// extension. See [`parse_driver_message`] for the other direction.
///
/// # Errors
/// Returns a [`ParseError`] whose `code` is `bad-version`, `malformed` or
/// `limit-exceeded`.
pub fn parse_adapter_message(value: &Value, limits: &Limits) -> Result<(), ParseError> {
    project(value, limits)?;
    let (object, kind) = as_message(value)?;

    match kind {
        "hello" => {
            check_protocol_field(object)?;
            require_keys(
                object,
                &["type", "protocol", "token", "adapter", "capabilities"],
                &["probe", "providers"],
            )?;
            identifier(object, "token", false)?;
            let adapter = object
                .get("adapter")
                .and_then(Value::as_object)
                .ok_or_else(|| ParseError::malformed("adapter: expected an object"))?;
            require_keys(adapter, &["name", "version"], &[])?;
            identifier(adapter, "name", false)?;
            identifier(adapter, "version", false)?;
            let capabilities = object
                .get("capabilities")
                .and_then(Value::as_array)
                .ok_or_else(|| ParseError::malformed("capabilities: expected an array"))?;
            if capabilities.len() > ADAPTER_CAPABILITIES.len() {
                return Err(ParseError::malformed("capabilities: too many entries"));
            }
            for item in capabilities {
                match item.as_str() {
                    Some(name) if valid_capability(name) => {}
                    _ => return Err(ParseError::malformed("capabilities: unknown capability")),
                }
            }
            Ok(())
        }
        "revision-commit" => {
            require_keys(object, &["type", "revision"], &[])?;
            whole_number(object, "revision", true)
        }
        "snapshot" => {
            require_keys(object, &["type", "snapshot"], &[])?;
            check_embedded_snapshot(&object["snapshot"], limits)
        }
        "log" => {
            require_keys(object, &["type", "record"], &[])?;
            check_embedded_log_record(&object["record"], limits)
        }
        "error" => check_error_message(object, true),
        _ => Err(ParseError::malformed("unknown or missing message type")),
    }
}

/// Map a record failure onto the wire taxonomy: capacity failures are
/// `limit-exceeded`, the rest are `malformed`.
fn check_embedded_log_record(value: &Value, limits: &Limits) -> Result<(), ParseError> {
    match validate_log_record(value, limits) {
        Ok(()) => Ok(()),
        Err(error) => {
            let code = match error.code {
                "bytes" | "count" | "depth" | "string-bytes" => "limit-exceeded",
                _ => "malformed",
            };
            Err(ParseError::new(code, format!("log record {error}")))
        }
    }
}

/// Validate one driver → adapter message.
///
/// Driver traffic is read tolerantly: unknown fields in the envelope and in
/// the driver's nested objects (`marker`, `logs`, `limits`) are ignored and
/// passed through to the caller, so a newer driver can add a field without
/// breaking an adapter published before it existed.
///
/// The asymmetry is about who is speaking, not about the message: adapter
/// traffic crosses an untrusted boundary, where an unknown field is a signal
/// rather than an extension. Tolerance is not leniency either — known fields
/// keep their types, and the closed sets (message types, error codes,
/// `subscribe`, roles, actions) stay closed in both directions.
///
/// # Errors
/// Returns a [`ParseError`] whose `code` is `bad-version`, `malformed` or
/// `limit-exceeded`.
pub fn parse_driver_message(value: &Value, limits: &Limits) -> Result<(), ParseError> {
    project(value, limits)?;
    let (object, kind) = as_message(value)?;

    match kind {
        "hello-ack" => {
            check_protocol_field(object)?;
            required_keys(
                object,
                &[
                    "type",
                    "protocol",
                    "sessionId",
                    "limits",
                    "subscribe",
                    "marker",
                ],
            )?;
            identifier(object, "sessionId", false)?;
            let limits_object = object
                .get("limits")
                .and_then(Value::as_object)
                .ok_or_else(|| ParseError::malformed("limits: expected an object"))?;
            // Required keys must all be present, but unknown ones are
            // ignored: see the note on `Limits`.
            required_keys(limits_object, &LIMIT_FIELDS)?;
            for field in LIMIT_FIELDS {
                whole_number(limits_object, field, true)?;
            }
            match object.get("subscribe").and_then(Value::as_str) {
                Some("snapshots") | Some("revisions") => {}
                _ => {
                    return Err(ParseError::malformed(
                        "subscribe: expected 'snapshots' or 'revisions'",
                    ))
                }
            }
            let marker = object
                .get("marker")
                .and_then(Value::as_object)
                .ok_or_else(|| ParseError::malformed("marker: expected an object"))?;
            required_keys(marker, &["enabled"])?;
            if !marker["enabled"].is_boolean() {
                return Err(ParseError::malformed("marker.enabled: expected a boolean"));
            }
            if let Some(logs) = object.get("logs") {
                check_log_budget(logs)?;
            }
            Ok(())
        }
        "error" => check_error_message(object, false),
        _ => Err(ParseError::malformed("unknown or missing message type")),
    }
}