car-server-core 0.55.0

Transport-neutral library for the CAR daemon JSON-RPC dispatcher (used by car-server and tokhn-daemon)
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, BTreeSet};
use std::path::Path;

use syn::visit::{self, Visit};
use syn::{Expr, ExprCall, ExprField, ExprMatch, ExprPath, Item, ItemFn, Lit, Member, Pat};

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum RpcCallerRole {
    Agent,
    Owner,
    Operator,
    Host,
}

impl RpcCallerRole {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Agent => "agent",
            Self::Owner => "owner",
            Self::Operator => "operator",
            Self::Host => "host",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExtractedRpcMethod {
    pub method: String,
    pub documented: bool,
    pub role: RpcCallerRole,
}

#[derive(Debug, Clone, Default)]
struct FunctionSignals {
    callees: BTreeSet<String>,
    host: bool,
    owner: bool,
    agent: bool,
    owner_client: bool,
    session_client_id: bool,
}

impl FunctionSignals {
    fn merge(&mut self, other: &Self) {
        self.host |= other.host;
        self.owner |= other.owner;
        self.agent |= other.agent;
        self.owner_client |= other.owner_client;
        self.session_client_id |= other.session_client_id;
        self.callees.extend(other.callees.iter().cloned());
    }

    fn role(&self) -> RpcCallerRole {
        if self.host {
            RpcCallerRole::Host
        } else if self.owner || (self.owner_client && self.session_client_id) {
            RpcCallerRole::Owner
        } else if self.agent {
            RpcCallerRole::Agent
        } else {
            RpcCallerRole::Operator
        }
    }
}

#[derive(Default)]
struct SignalVisitor {
    signals: FunctionSignals,
}

impl<'ast> Visit<'ast> for SignalVisitor {
    fn visit_expr_call(&mut self, node: &'ast ExprCall) {
        if let Expr::Path(path) = node.func.as_ref() {
            // Only an unqualified call can name one of handler.rs's top-level
            // helpers. Using the trailing segment of `module::handle` would
            // accidentally resolve it to an unrelated local `handle` function.
            if path.qself.is_none() && path.path.segments.len() == 1 {
                let callee = path.path.segments[0].ident.to_string();
                match callee.as_str() {
                    "require_approval_authority" | "require_agent_permissions_authority" => {
                        self.signals.host = true;
                    }
                    "authorize_run_access" => self.signals.owner = true,
                    _ => {}
                }
                self.signals.callees.insert(callee);
            }
        }
        visit::visit_expr_call(self, node);
    }

    fn visit_expr_field(&mut self, node: &'ast ExprField) {
        let Member::Named(member) = &node.member else {
            visit::visit_expr_field(self, node);
            return;
        };
        if is_path(node.base.as_ref(), "session") {
            match member.to_string().as_str() {
                "agent_id" => self.signals.agent = true,
                "client_id" => self.signals.session_client_id = true,
                _ => {}
            }
        }
        visit::visit_expr_field(self, node);
    }

    fn visit_expr_path(&mut self, node: &'ast ExprPath) {
        if node.qself.is_none() && node.path.is_ident("owner_client") {
            self.signals.owner_client = true;
        }
        visit::visit_expr_path(self, node);
    }
}

// Only an unconditional leading host-refusal guard establishes this role.
// Merely reading is_host (or conditionally restricting agents) is not enough.
fn starts_with_host_refusal(function: &ItemFn) -> bool {
    let Some(syn::Stmt::Expr(Expr::If(guard), _)) = function.block.stmts.first() else {
        return false;
    };
    let Expr::Unary(negated) = guard.cond.as_ref() else {
        return false;
    };
    if !matches!(negated.op, syn::UnOp::Not(_)) {
        return false;
    }
    let Expr::MethodCall(load) = negated.expr.as_ref() else {
        return false;
    };
    let Expr::Field(field) = load.receiver.as_ref() else {
        return false;
    };
    if load.method != "load"
        || !is_path(field.base.as_ref(), "session")
        || !matches!(&field.member, Member::Named(name) if name == "is_host")
    {
        return false;
    }
    let [syn::Stmt::Expr(Expr::Return(ret), _)] = guard.then_branch.stmts.as_slice() else {
        return false;
    };
    matches!(ret.expr.as_deref(), Some(Expr::Call(call)) if is_path(call.func.as_ref(), "Err"))
}

fn top_level_function_signals(syntax: &syn::File) -> BTreeMap<String, FunctionSignals> {
    syntax
        .items
        .iter()
        .filter_map(|item| {
            let Item::Fn(function) = item else {
                return None;
            };
            let mut visitor = SignalVisitor::default();
            visitor.visit_block(&function.block);
            visitor.signals.host |= starts_with_host_refusal(function);
            Some((function.sig.ident.to_string(), visitor.signals))
        })
        .collect()
}

fn resolved_signals(
    direct: &FunctionSignals,
    functions: &BTreeMap<String, FunctionSignals>,
) -> FunctionSignals {
    fn visit_callee(
        name: &str,
        functions: &BTreeMap<String, FunctionSignals>,
        visiting: &mut BTreeSet<String>,
        resolved: &mut FunctionSignals,
    ) {
        if !visiting.insert(name.to_string()) {
            return;
        }
        if let Some(signals) = functions.get(name) {
            resolved.merge(signals);
            for callee in &signals.callees {
                visit_callee(callee, functions, visiting, resolved);
            }
        }
        visiting.remove(name);
    }

    let mut resolved = direct.clone();
    let mut visiting = BTreeSet::new();
    for callee in &direct.callees {
        visit_callee(callee, functions, &mut visiting, &mut resolved);
    }
    resolved
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DispatchFunction {
    Primary,
    DaemonOwnedAuth,
}

struct DispatchVisitor<'functions> {
    function: Option<DispatchFunction>,
    functions: &'functions BTreeMap<String, FunctionSignals>,
    alias_groups: Vec<(Vec<String>, RpcCallerRole)>,
    selected_tables: usize,
    unsupported_arms: usize,
}

impl<'functions> DispatchVisitor<'functions> {
    fn new(functions: &'functions BTreeMap<String, FunctionSignals>) -> Self {
        Self {
            function: None,
            functions,
            alias_groups: Vec::new(),
            selected_tables: 0,
            unsupported_arms: 0,
        }
    }
}

impl<'ast> Visit<'ast> for DispatchVisitor<'_> {
    fn visit_item_fn(&mut self, node: &'ast ItemFn) {
        let previous = self.function;
        self.function = match node.sig.ident.to_string().as_str() {
            "run_dispatch" => Some(DispatchFunction::Primary),
            "dispatch_daemon_owned_auth" => Some(DispatchFunction::DaemonOwnedAuth),
            _ => None,
        };
        visit::visit_item_fn(self, node);
        self.function = previous;
    }

    fn visit_expr_match(&mut self, node: &'ast ExprMatch) {
        let is_dispatch = match self.function {
            Some(DispatchFunction::Primary) => is_as_str_call_on(&node.expr, "method_owned"),
            Some(DispatchFunction::DaemonOwnedAuth) => is_path(&node.expr, "method"),
            None => false,
        };
        if is_dispatch {
            self.selected_tables += 1;
            for arm in &node.arms {
                let mut methods = Vec::new();
                collect_string_patterns(&arm.pat, &mut methods);
                if methods.is_empty() {
                    if !matches!(&arm.pat, Pat::Wild(_)) {
                        self.unsupported_arms += 1;
                    }
                } else {
                    let role = if self.function == Some(DispatchFunction::DaemonOwnedAuth) {
                        RpcCallerRole::Host
                    } else {
                        let mut direct = SignalVisitor::default();
                        direct.visit_expr(&arm.body);
                        resolved_signals(&direct.signals, self.functions).role()
                    };
                    self.alias_groups.push((methods, role));
                }
            }
            // Method arms contain many implementation matches. They are not dispatch
            // tables, even when one happens to inspect a variable named `method`.
            return;
        }
        visit::visit_expr_match(self, node);
    }
}

fn is_as_str_call_on(expression: &Expr, identifier: &str) -> bool {
    let Expr::MethodCall(call) = expression else {
        return false;
    };
    call.method == "as_str" && call.args.is_empty() && is_path(&call.receiver, identifier)
}

fn is_path(expression: &Expr, identifier: &str) -> bool {
    matches!(
        expression,
        Expr::Path(path)
            if path.qself.is_none()
                && path.path.segments.len() == 1
                && path.path.is_ident(identifier)
    )
}

fn collect_string_patterns(pattern: &Pat, out: &mut Vec<String>) {
    match pattern {
        Pat::Lit(literal) => {
            if let Lit::Str(value) = &literal.lit {
                out.push(value.value());
            }
        }
        Pat::Or(patterns) => {
            for case in &patterns.cases {
                collect_string_patterns(case, out);
            }
        }
        Pat::Paren(pattern) => collect_string_patterns(&pattern.pat, out),
        _ => {}
    }
}

/// Extract the daemon's client-to-server string-literal dispatch arms.
///
/// The primary dispatcher and its pre-handshake auth sub-dispatch are selected
/// structurally. Other string matches and literals in handler implementations
/// are deliberately excluded. Every alias spelling is checked independently so
/// adding a new literal to an already-documented arm still trips the ratchet.
#[cfg_attr(not(test), allow(dead_code))]
pub fn extract_rpc_methods(
    handler_source: &str,
    protocol_documentation: &str,
) -> Result<Vec<ExtractedRpcMethod>, String> {
    extract_rpc_methods_and_table_count(handler_source, protocol_documentation)
        .map(|(methods, _)| methods)
}

/// Look up a role only after the method has been extracted from the real
/// dispatcher. This explicit failure path is used by the generator's negative
/// control: a method absent from the daemon cannot silently default to
/// `operator`.
pub fn role_for_method(
    methods: &[ExtractedRpcMethod],
    method: &str,
) -> Result<RpcCallerRole, String> {
    methods
        .iter()
        .find(|item| item.method == method)
        .map(|item| item.role)
        .ok_or_else(|| format!("cannot derive caller role for unknown method `{method}`"))
}

fn extract_rpc_methods_and_table_count(
    handler_source: &str,
    protocol_documentation: &str,
) -> Result<(Vec<ExtractedRpcMethod>, usize), String> {
    let syntax = syn::parse_file(handler_source)
        .map_err(|error| format!("parse car-server-core/src/handler.rs: {error}"))?;
    let functions = top_level_function_signals(&syntax);
    let mut visitor = DispatchVisitor::new(&functions);
    visitor.visit_file(&syntax);
    if visitor.alias_groups.is_empty() {
        return Err("found no JSON-RPC string-literal dispatch arms".into());
    }
    if visitor.unsupported_arms != 0 {
        return Err(format!(
            "found {} non-wildcard JSON-RPC dispatch arm(s) without a string-literal method pattern",
            visitor.unsupported_arms
        ));
    }

    let selected_tables = visitor.selected_tables;
    let mut methods = BTreeMap::new();
    for (aliases, role) in visitor.alias_groups {
        for method in aliases {
            let documented = documentation_mentions(protocol_documentation, &method);
            if methods.insert(method.clone(), (documented, role)).is_some() {
                return Err(format!(
                    "duplicate JSON-RPC dispatch method `{method}` in handler.rs"
                ));
            }
        }
    }

    Ok((
        methods
            .into_iter()
            .map(|(method, (documented, role))| ExtractedRpcMethod {
                method,
                documented,
                role,
            })
            .collect(),
        selected_tables,
    ))
}

fn cross_check_dispatch_table_count(handler_source: &str, selected: usize) -> Result<(), String> {
    // This intentionally cheap lexical check is independent of the syn visitor.
    // The bounded function regions let it see a nested same-scrutinee match that
    // the visitor's deliberate early return would otherwise skip.
    let textual = count_in_function(
        handler_source,
        "pub async fn run_dispatch",
        "\nasync fn send_response",
        "match method_owned.as_str()",
    )? + count_in_function(
        handler_source,
        "async fn dispatch_daemon_owned_auth",
        "\nasync fn handle_auth_start",
        "match method {",
    )?;
    if textual != selected {
        return Err(format!(
            "JSON-RPC dispatch-table cross-check failed: syn selected {selected}, handler text contains {textual}"
        ));
    }
    Ok(())
}

fn count_in_function(
    source: &str,
    start_marker: &str,
    end_marker: &str,
    needle: &str,
) -> Result<usize, String> {
    if source.matches(start_marker).count() != 1 {
        return Err(format!(
            "JSON-RPC dispatch-table cross-check expected exactly one `{start_marker}`"
        ));
    }
    let start = source.find(start_marker).expect("count checked above");
    let remainder = &source[start..];
    let end = remainder.find(end_marker).ok_or_else(|| {
        format!(
            "JSON-RPC dispatch-table cross-check found no `{end_marker}` after `{start_marker}`"
        )
    })?;
    Ok(remainder[..end].matches(needle).count())
}

/// A method is documented only by its own reference entry, never by a mention
/// in another method's prose or in an example. Most entries are level-four
/// headings. Compact grouped references may use a table row or a leading
/// method-name bullet; only the identifying cells/prefix are considered.
fn documentation_mentions(documentation: &str, method: &str) -> bool {
    let mut in_a2a_alias_table = false;
    for line in documentation.lines() {
        let line = line.trim();
        if line == "| v1.0 PascalCase | v0.3 slash form |" {
            in_a2a_alias_table = true;
            continue;
        }
        if let Some(heading) = line.strip_prefix("#### ") {
            in_a2a_alias_table = false;
            if heading.starts_with('`') && code_spans_mention_method(heading, method) {
                return true;
            }
            continue;
        }
        if line.starts_with('|') {
            let mut cells = line.split('|').skip(1);
            if cells
                .next()
                .is_some_and(|cell| code_spans_mention_method(cell, method))
            {
                return true;
            }
            if in_a2a_alias_table
                && cells
                    .next()
                    .is_some_and(|cell| code_spans_mention_method(cell, method))
            {
                return true;
            }
            continue;
        }
        in_a2a_alias_table = false;
        let Some(bullet) = line.strip_prefix("- ") else {
            continue;
        };
        let bullet = bullet.strip_prefix("**").unwrap_or(bullet);
        if !bullet.starts_with('`') {
            continue;
        }
        let identifier_prefix = bullet.split_once("").map_or(bullet, |(prefix, _)| prefix);
        if code_spans_mention_method(identifier_prefix, method) {
            return true;
        }
    }
    false
}

fn code_spans_mention_method(text: &str, method: &str) -> bool {
    text.split('`')
        .skip(1)
        .step_by(2)
        .any(|code| text_mentions_method(code, method))
}

fn text_mentions_method(text: &str, method: &str) -> bool {
    text.match_indices(method).any(|(start, _)| {
        let before = text[..start].chars().next_back();
        let end = start + method.len();
        let after = text[end..].chars().next();
        !before.is_some_and(is_method_character) && !after.is_some_and(is_method_character)
    })
}

fn is_method_character(character: char) -> bool {
    character.is_ascii_alphanumeric() || matches!(character, '_' | '.' | '/' | '-')
}

pub fn emit_rpc_inventory(manifest_dir: &Path, out_dir: &Path) -> Result<(), String> {
    let workspace = manifest_dir
        .parent()
        .and_then(Path::parent)
        .ok_or("car-cli is not under <workspace>/crates/car-cli")?;
    let repository = workspace
        .parent()
        .ok_or("car-rs workspace has no repository parent")?;
    let handler = workspace.join("crates/car-server-core/src/handler.rs");
    let protocol = repository.join("docs/websocket-protocol.md");
    println!("cargo:rerun-if-changed={}", handler.display());
    println!("cargo:rerun-if-changed={}", protocol.display());

    let source = read(&handler)?;
    let documentation = read(&protocol)?;
    let (methods, selected_tables) = extract_rpc_methods_and_table_count(&source, &documentation)?;
    cross_check_dispatch_table_count(&source, selected_tables)?;
    let values = methods
        .iter()
        .map(|item| {
            let role = role_for_method(&methods, &item.method)?;
            Ok(serde_json::json!({
                "method": item.method,
                "documented": item.documented,
                "role": role.as_str(),
            }))
        })
        .collect::<Result<Vec<_>, String>>()?;
    let mut bytes = serde_json::to_vec_pretty(&values)
        .map_err(|error| format!("serialize JSON-RPC capability inventory: {error}"))?;
    bytes.push(b'\n');
    let output_path = out_dir.join("capability-rpc-methods.json");
    std::fs::write(&output_path, bytes)
        .map_err(|error| format!("write {}: {error}", output_path.display()))
}

fn read(path: &Path) -> Result<String, String> {
    std::fs::read_to_string(path).map_err(|error| format!("read {}: {error}", path.display()))
}

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

    #[test]
    fn direct_host_refusal_is_distinct_from_host_observation_or_conditional_access() {
        let source = r#"
            async fn run_dispatch() {
                match method_owned.as_str() {
                    "session.clear_halt" => clear(&session),
                    "read" => read(&session),
                    "conditional" => conditional(&session),
                    "not_refusal" => not_refusal(&session),
                    _ => (),
                }
            }
            fn clear(session: &Session) {
                if !session.is_host.load(Ordering::Acquire) { return Err("host required"); }
                Ok(())
            }
            fn read(session: &Session) { let role = session.is_host.load(Ordering::Acquire); }
            fn conditional(session: &Session) {
                if bound && !session.is_host.load(Ordering::Acquire) { return Err("bound"); }
            }
            fn not_refusal(session: &Session) {
                if !session.is_host.load(Ordering::Acquire) { return Ok(false); }
            }
        "#;
        let methods = extract_rpc_methods(source, "").unwrap();
        assert_eq!(
            role_for_method(&methods, "session.clear_halt").unwrap(),
            RpcCallerRole::Host
        );
        for method in ["read", "conditional", "not_refusal"] {
            assert_eq!(
                role_for_method(&methods, method).unwrap(),
                RpcCallerRole::Operator
            );
        }
    }

    const FIXTURE: &str = r#"
        async fn run_dispatch() {
            let _ = "not.a.dispatch.arm";
            match unrelated.as_str() {
                "also.not_dispatched" => (),
                _ => (),
            }
            match method_owned.as_str() {
                "alpha.one" => handle_agent(&session),
                "beta/two"
                | "BetaTwo"
                | "beta.two" => (),
                "infer.cancel" => handle_r16_owner(&session),
                "runs.cancel" => handle_authorized_owner(),
                "permission.approve" => handle_host(&session),
                _ => (),
            }
        }

        fn handle_agent(session: &Session) {
            let _ = &session.agent_id;
        }

        fn handle_r16_owner(session: &Session) {
            let _ = &session.client_id;
            let _ = owner_client;
        }

        fn handle_authorized_owner() {
            authorize_run_access();
        }

        fn handle_host(session: &Session) {
            require_approval_authority(session);
        }

        async fn dispatch_daemon_owned_auth(method: &str) {
            match method {
                "session.auth" => (),
                _ => (),
            }
        }

        fn another_function(method: &str) {
            match method {
                "not.dispatched" => (),
                _ => (),
            }
        }
    "#;

    #[test]
    fn extracts_multiline_aliases_and_both_dispatchers_only() {
        let documentation = r#"
#### `alpha.one`
| `beta/two` | alias reference |
#### `session.auth`
A cross-reference to `infer.cancel` and `infer.cancel.v1` is not its own entry.
"#;
        let methods = extract_rpc_methods(FIXTURE, documentation).unwrap();
        assert_eq!(
            methods,
            vec![
                ExtractedRpcMethod {
                    method: "BetaTwo".into(),
                    documented: false,
                    role: RpcCallerRole::Operator,
                },
                ExtractedRpcMethod {
                    method: "alpha.one".into(),
                    documented: true,
                    role: RpcCallerRole::Agent,
                },
                ExtractedRpcMethod {
                    method: "beta.two".into(),
                    documented: false,
                    role: RpcCallerRole::Operator,
                },
                ExtractedRpcMethod {
                    method: "beta/two".into(),
                    documented: true,
                    role: RpcCallerRole::Operator,
                },
                ExtractedRpcMethod {
                    method: "infer.cancel".into(),
                    documented: false,
                    role: RpcCallerRole::Owner,
                },
                ExtractedRpcMethod {
                    method: "permission.approve".into(),
                    documented: false,
                    role: RpcCallerRole::Host,
                },
                ExtractedRpcMethod {
                    method: "runs.cancel".into(),
                    documented: false,
                    role: RpcCallerRole::Owner,
                },
                ExtractedRpcMethod {
                    method: "session.auth".into(),
                    documented: true,
                    role: RpcCallerRole::Host,
                },
            ]
        );
    }

    #[test]
    fn role_lookup_refuses_a_method_absent_from_the_real_dispatcher() {
        let methods = extract_rpc_methods(FIXTURE, "").unwrap();
        let error = role_for_method(&methods, "not.real").unwrap_err();
        assert_eq!(
            error,
            "cannot derive caller role for unknown method `not.real`"
        );
    }

    #[test]
    fn exact_documentation_boundary_rejects_capability_suffixes() {
        assert!(!documentation_mentions(
            "#### `infer.cancel.v1`",
            "infer.cancel"
        ));
        assert!(documentation_mentions(
            "#### `infer.cancel`",
            "infer.cancel"
        ));
        assert!(documentation_mentions(
            "#### `diagnostics.secret_store_activity {}`",
            "diagnostics.secret_store_activity"
        ));
        assert!(!documentation_mentions(
            "ordinary prose can say verify without documenting the RPC",
            "verify"
        ));
    }

    #[test]
    fn deleting_a_method_section_is_not_masked_by_a_cross_reference() {
        let with_section = r#"
#### `infer.cancel`
- **Params**: `{ request_id }`

#### `infer.deadline`
- **Returns**: the same status vocabulary as `infer.cancel`.
"#;
        let without_section = r#"
#### `infer.deadline`
- **Returns**: the same status vocabulary as `infer.cancel`.
"#;
        assert!(documentation_mentions(with_section, "infer.cancel"));
        assert!(!documentation_mentions(without_section, "infer.cancel"));
    }

    #[test]
    fn compact_table_and_bullet_entries_are_dedicated_references() {
        let documentation = r#"
| v1.0 PascalCase | v0.3 slash form |
|---|---|
| `SendStreamingMessage` | `message/stream` |
- **`permission.approve`** / **`permission.reject`** — Params `{ fingerprint }`.
"#;
        for method in [
            "SendStreamingMessage",
            "message/stream",
            "permission.approve",
            "permission.reject",
        ] {
            assert!(documentation_mentions(documentation, method), "{method}");
        }
    }

    #[test]
    fn rejects_non_literal_dispatch_arms_and_duplicate_methods() {
        let unsupported = FIXTURE.replacen(
            "\"infer.cancel\" => handle_r16_owner(&session)",
            "METHOD => ()",
            1,
        );
        let error = extract_rpc_methods(&unsupported, "").unwrap_err();
        assert!(
            error.contains("without a string-literal method pattern"),
            "{error}"
        );

        let duplicate = FIXTURE.replacen("\"session.auth\" => ()", "\"alpha.one\" => ()", 1);
        let error = extract_rpc_methods(&duplicate, "").unwrap_err();
        assert!(
            error.contains("duplicate JSON-RPC dispatch method `alpha.one`"),
            "{error}"
        );
    }

    #[test]
    fn textual_table_count_detects_a_nested_same_scrutinee_match() {
        let fixture = r#"
pub async fn run_dispatch() {
    match method_owned.as_str() {
        "alpha.one" => (),
        _ => (),
    }
}
async fn send_response() {}
async fn dispatch_daemon_owned_auth(method: &str) {
    match method {
        "session.auth" => (),
        _ => (),
    }
}
async fn handle_auth_start() {}
"#;
        let (_, selected) = extract_rpc_methods_and_table_count(fixture, "").unwrap();
        assert_eq!(selected, 2);
        cross_check_dispatch_table_count(fixture, selected).unwrap();

        let nested = fixture.replacen(
            "\"alpha.one\" => (),",
            "\"alpha.one\" => { match method_owned.as_str() { \"nested\" => (), _ => () } },",
            1,
        );
        let (_, selected) = extract_rpc_methods_and_table_count(&nested, "").unwrap();
        assert_eq!(selected, 2);
        let error = cross_check_dispatch_table_count(&nested, selected).unwrap_err();
        assert!(
            error.contains("syn selected 2, handler text contains 3"),
            "{error}"
        );
    }
}