plana 0.2.2

PLANA protocol foundation: the canonical JSON-RPC 2.0 wire layer (unix-socket / HTTP / WS bindings, typed method routing) merged with the generic protocol core (handshake, identity, RBAC, regions, health descriptors) — the base every plana-rpc-* and domain-profile crate builds on.
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
use serde_json::Value;
use std::collections::{HashMap, VecDeque};
use strum::{Display, EnumIter, EnumString};
use tokio::sync::oneshot;
use uuid::Uuid;

// ══════════════════════════════════════════════════════════════
// namespace!  macro  —  single source of truth for each namespace.
//
// Each line:   Variant  [as Kind]  [=> ResponseVariant]
//   - "as Kind"  defaults to SyncReq;  OneWay / AsyncReq for others.
//   - "=> Resp"  pairs request→response.
//   - No hand-written wire strings — derived from enum path.
//
// Generates:
//   1.  Inner enum (SyncMethod, CliMethod, …) with strum derives
//   2.  wire()  —  "{Prefix}.{Variant}"  via concat!
//   3.  kind() / is_one_way() / response()  for the inner enum
//   4.  Paste-based flat aliases on Method  (Method::SyncServerVersion)
//
// `#[macro_export]` (plus the `$crate::`-qualified bodies below) makes the
// macro usable from external crates: it resolves at the foundation crate root
// as `plana::namespace`. The former `plana_jsonrpc::namespace` and
// `plana::jsonrpc::namespace` paths no longer exist after the JSON-RPC layer
// was absorbed into `plana`. Invokers only need the
// `strum::{Display, EnumIter, EnumString}` derives in scope.
#[macro_export]
macro_rules! namespace {
    (
        $prefix:literal, $ns:ident, $inner:ident,
        $( $variant:ident $(as $kind:ident)? $(=> $response:ident)? ),* $(,)?
    ) => {
        #[derive(Debug,Clone,Copy,PartialEq,Eq,Hash,Display,EnumString,EnumIter)]
        pub enum $inner { $( $variant, )* }

        impl $inner {
            pub fn wire(self) -> &'static str {
                match self { $(Self::$variant => concat!($prefix,".",stringify!($variant)),)* }
            }
            pub fn kind(self) -> $crate::jsonrpc::pending::MessageKind {
                match self {
                    // The `let _ = stringify!($($kind)?);` lines are no-op
                    // disambiguators: they pin the optional `$kind`/`$response`
                    // fragment as used inside the arm, so the `$($x)?` optional
                    // repetition resolves deterministically at macro-expansion
                    // time. The actual value comes from the helper macro
                    // invocation on the next line.
                    $( Self::$variant => { let _ = stringify!($($kind)?); $crate::namespace_kind!($($kind)?) }, )*
                }
            }
            pub fn is_one_way(self) -> bool { matches!(self.kind(), $crate::jsonrpc::pending::MessageKind::OneWay) }
            pub fn response(self) -> Option<Self> {
                match self {
                    $( Self::$variant => { let _ = stringify!($($response)?); $crate::namespace_resp!($($response)?) }, )*
                }
            }
        }
    };
}

// Helper macros for `namespace!` above. They are referenced through
// `$crate::`-qualified paths inside `namespace!`'s expansion, so they must
// stay `#[macro_export]`ed to be resolvable when the expansion runs in an
// external crate; `#[doc(hidden)]` keeps them out of the public docs (they
// are not part of the intended consumer surface).
#[doc(hidden)]
#[macro_export]
macro_rules! namespace_kind {
    ($k:ident) => {
        $crate::jsonrpc::pending::MessageKind::$k
    };
    () => {
        $crate::jsonrpc::pending::MessageKind::SyncReq
    };
}
#[doc(hidden)]
#[macro_export]
macro_rules! namespace_resp {
    ($r:ident) => {
        Some(Self::$r)
    };
    () => {
        None
    };
}

// ══════════════════════════════════════════════════════════════
// Method enum — namespace wrapper
// ══════════════════════════════════════════════════════════════

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Method {
    Sync(SyncMethod),
    Cli(CliMethod),
    Tool(ToolMethod),
    Skill(SkillMethod),
    Base(BaseMethod),
    Device(DeviceMethod),
    Screen(ScreenMethod),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MessageKind {
    OneWay,
    SyncReq,
    AsyncReq,
}

// ── Per-namespace definitions ─────────────────────────────────

namespace!("Sync", Sync, SyncMethod,
    ServerVersion              as OneWay,
    ConnectHandshake           as SyncReq   => HandshakeAck,
    HandshakeAck               as OneWay,
    VersionMismatch            as OneWay,
    ScepterIdentity            as OneWay,
    StatePatch                 as OneWay,
    StateSnapshot              as OneWay,
    ChannelEvent               as OneWay,
    RequestGlobalSnapshot      as SyncReq   => GlobalSnapshot,
    GlobalSnapshot             as OneWay,
    RequestContainerSnapshot   as SyncReq   => ContainerSnapshot,
    ContainerSnapshot          as OneWay,
    RequestTasksSnapshot       as SyncReq   => TasksSnapshot,
    TasksSnapshot              as OneWay,
    RequestVmSnapshot          as SyncReq   => VmSnapshot,
    VmSnapshot                 as OneWay,
    RequestFullSnapshot        as SyncReq   => FullSnapshot,
    FullSnapshot               as OneWay,
    GetProvidersFromFs         as SyncReq   => ProvidersFromFsResponse,
    ProvidersFromFsResponse    as OneWay,
    GetModelsFromFs            as SyncReq   => ModelsFromFsResponse,
    ModelsFromFsResponse       as OneWay,
    GetUserConfig              as SyncReq   => UserConfigResponse,
    UserConfigResponse         as OneWay,
    ModelsSnapshot             as OneWay,
    ProvidersSnapshot          as OneWay,
    UserMessage                as OneWay,
    AgentResponse              as OneWay,
    AgentStreamingChunk        as OneWay,
    AgentThinkingStep          as OneWay,
    AgentReport                as OneWay,
    AgentReportReply           as OneWay,
    AgentToolCall              as OneWay,
    AgentTransfer              as OneWay,
    AgentPatch                 as OneWay,
    AgentUpdate                as OneWay,
    AgentListResponse          as OneWay,
    AgentSnapshot              as OneWay,
    OrchestrationStatus        as OneWay,
    ToolResult                 as OneWay,
    TaskCreated                as OneWay,
    TaskStatusUpdate           as OneWay,
    TaskPatch                  as OneWay,
    ContainerPatch             as OneWay,
    SystemMessage              as OneWay,
    AskHumanRequest            as OneWay,
    AskHumanReply              as AsyncReq  => AskHumanReplyResponse,
    AskHumanReplyResponse      as OneWay,
    HumanReviewRequest         as OneWay,
    HumanReviewResponse        as OneWay,
    SkillChainStart            as OneWay,
    SkillChainStep             as OneWay,
    SkillChainComplete         as OneWay,
    YoloStart                  as AsyncReq  => YoloStartResponse,
    YoloStartResponse          as OneWay,
    YoloStop                   as AsyncReq  => YoloStopResponse,
    YoloStopResponse           as OneWay,
    YoloTerminate              as AsyncReq  => YoloTerminateResponse,
    YoloTerminateResponse      as OneWay,
    YoloStatus                 as AsyncReq  => YoloStatusResponse,
    YoloStatusResponse         as OneWay,
    YoloGetConfig              as AsyncReq  => YoloConfigResponse,
    YoloConfigResponse         as OneWay,
    YoloUpdateTask             as AsyncReq  => YoloUpdateTaskResponse,
    YoloUpdateTaskResponse     as OneWay,
    YoloSetTierInterval        as AsyncReq  => YoloSetTierIntervalResponse,
    YoloSetTierIntervalResponse as OneWay,
    YoloRunTierNow             as AsyncReq  => YoloRunTierNowResponse,
    YoloRunTierNowResponse     as OneWay,
    YoloCycleStep              as OneWay,
    YoloCycleComplete          as OneWay,
    YoloTaskStart              as OneWay,
    YoloTaskDone               as OneWay,
    YoloTaskError              as OneWay,
    OpenWorkspace              as SyncReq   => OpenWorkspaceResponse,
    OpenWorkspaceResponse      as OneWay,
    RequestWorkspaceStatus     as SyncReq   => WorkspaceStatus,
    WorkspaceStatus            as OneWay,
    ListAgents                 as SyncReq   => AgentListResponse,
    PolemosDeviceList          as OneWay,
    ListPolemosDevices         as SyncReq,
    RegisterPolemosDevice      as SyncReq   => RegisterPolemosDeviceResponse,
    RegisterPolemosDeviceResponse as OneWay,
    AuthLogin                  as SyncReq   => AuthLoginResponse,
    AuthLoginResponse          as OneWay,
    AuthRegister               as SyncReq   => AuthRegisterResponse,
    AuthRegisterResponse       as OneWay,
    AuthListUsers              as SyncReq   => AuthListUsersResponse,
    AuthListUsersResponse      as OneWay,
    AuthGetUser                as SyncReq   => AuthGetUserResponse,
    AuthGetUserResponse        as OneWay,
    AuthDeleteUser             as SyncReq   => AuthDeleteUserResponse,
    AuthDeleteUserResponse     as OneWay,
    AuthChangePassword         as SyncReq   => AuthChangePasswordResponse,
    AuthChangePasswordResponse as OneWay,
    Ping                       as SyncReq   => Pong,
    Pong                       as OneWay,
    UsagePeriodQuery           as SyncReq   => UsagePeriodResponse,
    UsagePeriodResponse        as OneWay,
    Layer2AgentList            as AsyncReq  => Layer2AgentListResponse,
    Layer2AgentListResponse    as OneWay,
    Layer2AgentToolTools       as AsyncReq  => Layer2AgentToolResponse,
    Layer2AgentToolResponse    as OneWay,
    Layer2AgentSkills          as AsyncReq  => Layer2AgentSkillsResponse,
    Layer2AgentSkillsResponse  as OneWay,
    GetUserPreferences         as SyncReq,
    SyncPreferences            as SyncReq,
    AudioPullProgress          as OneWay,
    AudioStatusChanged         as OneWay,
    VoiceEngineProgress        as OneWay,
    ServerInfo                 as OneWay,
    CrossWorkspaceDenied       as OneWay,
    RequestBridgeNetwork       as SyncReq,
    RequestFileTree            as SyncReq,
    RequestFileRead            as SyncReq,
    RequestModelList           as SyncReq,
    RequestModelServerAction   as SyncReq,
    AgentChunkRange            as OneWay,
    AgentChunkCount            as OneWay,
    IndustrialTelemetryPush        as OneWay,
    IndustrialAlarmPush            as OneWay,
    IndustrialWriteApprovalPush    as OneWay,
    DashboardLayoutPush            as OneWay,
    ViewDataPush                   as OneWay,
    ViewInstancePush               as OneWay,
    PipelineProgress               as OneWay,
    PipelineDone                   as OneWay,
    ServerLogEntry             as OneWay,
    ContainerLogEntry          as OneWay,
);

namespace!(
    "Cli",
    Cli,
    CliMethod,
    Status,
    ChatHistory,
    TimelineList,
    TimelineShow,
    RecentChats,
    ListPolemosDevices,
    SessionStats,
    SessionPurge,
    SessionVacuum,
    Search,
    TraceChain,
    ListTools,
    ListSkills,
    ListWorkspaces,
    OpenWorkspace,
    SwitchWorkspace,
);

namespace!("Tool", Tool, ToolMethod,
    CallTool         as AsyncReq => ToolCallResult,
    ToolCallResult   as OneWay,
    ListTools        as SyncReq  => ToolsListResponse,
    ToolsListResponse as OneWay,
);

namespace!("Skill", Skill, SkillMethod,
    CallSkill         as AsyncReq => SkillCallResult,
    SkillCallResult   as OneWay,
    ListSkills        as SyncReq  => SkillsListResponse,
    SkillsListResponse as OneWay,
);

namespace!("Base", Base, BaseMethod,
    Heartbeat        as SyncReq => HeartbeatAck,
    HeartbeatAck     as OneWay,
    Error            as OneWay,
    Ack              as OneWay,
);

namespace!("Device", Device, DeviceMethod,
    PolemosRegister   as SyncReq => PolemosRegisterAck,
    PolemosRegisterAck as OneWay,
    Heartbeat         as SyncReq => HeartbeatAck,
    HeartbeatAck      as OneWay,
    TerminalOpen      as SyncReq => TerminalReady,
    TerminalReady     as OneWay,
    TerminalInput     as OneWay,
    TerminalResize    as OneWay,
    TerminalPoll      as SyncReq => TerminalPollResult,
    TerminalPollResult as OneWay,
    TerminalClose     as SyncReq => TerminalCloseAck,
    TerminalCloseAck  as OneWay,
    FileList          as SyncReq => FileListResult,
    FileListResult    as OneWay,
    FileDownload      as SyncReq => FileDownloadResult,
    FileDownloadResult as OneWay,
    FileUpload        as SyncReq => FileUploadResult,
    FileUploadResult  as OneWay,
    Ping              as SyncReq => Pong,
    Pong              as OneWay,
    WebrtcOffer       as SyncReq => WebrtcAnswer,
    WebrtcAnswer      as OneWay,
    WebrtcIce         as OneWay,
    SubscribeOutput   as OneWay,
    TerminalList      as SyncReq,
    TerminalOutput    as OneWay,
    Error             as OneWay,
);

namespace!(
    "Screen",
    Screen,
    ScreenMethod,
    Offer as OneWay,
    Answer as OneWay,
    Ice as OneWay,
    IceCandidate as OneWay,
);

// ══════════════════════════════════════════════════════════════
// Generated flat aliases on Method (via paste)
// ══════════════════════════════════════════════════════════════

macro_rules! flat_aliases {
    ($ns:ident, $inner:ident, $($variant:ident),* $(,)?) => {
        impl Method {
            // The paste-generated aliases mix namespaces and variants
            // (e.g. `SyncServerVersion`); keep the mixed case.
            $( paste::paste! { #[allow(non_upper_case_globals)] pub const [<$ns $variant>]: Method = Method::$ns($inner::$variant); } )*
        }
    };
}

flat_aliases!(
    Sync,
    SyncMethod,
    ServerVersion,
    ConnectHandshake,
    HandshakeAck,
    VersionMismatch,
    ScepterIdentity,
    StatePatch,
    StateSnapshot,
    ChannelEvent,
    RequestGlobalSnapshot,
    GlobalSnapshot,
    RequestContainerSnapshot,
    ContainerSnapshot,
    RequestTasksSnapshot,
    TasksSnapshot,
    RequestVmSnapshot,
    VmSnapshot,
    RequestFullSnapshot,
    FullSnapshot,
    GetProvidersFromFs,
    ProvidersFromFsResponse,
    GetModelsFromFs,
    ModelsFromFsResponse,
    GetUserConfig,
    UserConfigResponse,
    ModelsSnapshot,
    ProvidersSnapshot,
    UserMessage,
    AgentResponse,
    AgentStreamingChunk,
    AgentThinkingStep,
    AgentReport,
    AgentReportReply,
    AgentToolCall,
    AgentTransfer,
    AgentPatch,
    AgentUpdate,
    AgentListResponse,
    AgentSnapshot,
    OrchestrationStatus,
    ToolResult,
    TaskCreated,
    TaskStatusUpdate,
    TaskPatch,
    ContainerPatch,
    SystemMessage,
    AskHumanRequest,
    AskHumanReply,
    AskHumanReplyResponse,
    HumanReviewRequest,
    HumanReviewResponse,
    SkillChainStart,
    SkillChainStep,
    SkillChainComplete,
    YoloStart,
    YoloStartResponse,
    YoloStop,
    YoloStopResponse,
    YoloTerminate,
    YoloTerminateResponse,
    YoloStatus,
    YoloStatusResponse,
    YoloGetConfig,
    YoloConfigResponse,
    YoloUpdateTask,
    YoloUpdateTaskResponse,
    YoloSetTierInterval,
    YoloSetTierIntervalResponse,
    YoloRunTierNow,
    YoloRunTierNowResponse,
    YoloCycleStep,
    YoloCycleComplete,
    YoloTaskStart,
    YoloTaskDone,
    YoloTaskError,
    OpenWorkspace,
    OpenWorkspaceResponse,
    RequestWorkspaceStatus,
    WorkspaceStatus,
    ListAgents,
    PolemosDeviceList,
    ListPolemosDevices,
    RegisterPolemosDevice,
    RegisterPolemosDeviceResponse,
    AuthLogin,
    AuthLoginResponse,
    AuthRegister,
    AuthRegisterResponse,
    AuthListUsers,
    AuthListUsersResponse,
    AuthGetUser,
    AuthGetUserResponse,
    AuthDeleteUser,
    AuthDeleteUserResponse,
    AuthChangePassword,
    AuthChangePasswordResponse,
    Ping,
    Pong,
    UsagePeriodQuery,
    UsagePeriodResponse,
    Layer2AgentList,
    Layer2AgentListResponse,
    Layer2AgentToolTools,
    Layer2AgentToolResponse,
    Layer2AgentSkills,
    Layer2AgentSkillsResponse,
    GetUserPreferences,
    SyncPreferences,
    AudioPullProgress,
    AudioStatusChanged,
    VoiceEngineProgress,
    ServerInfo,
    CrossWorkspaceDenied,
    RequestBridgeNetwork,
    RequestFileTree,
    RequestFileRead,
    RequestModelList,
    RequestModelServerAction,
    AgentChunkRange,
    AgentChunkCount,
    IndustrialTelemetryPush,
    IndustrialAlarmPush,
    IndustrialWriteApprovalPush,
    DashboardLayoutPush,
    ViewDataPush,
    ViewInstancePush,
    PipelineProgress,
    PipelineDone,
    ServerLogEntry,
    ContainerLogEntry,
);
flat_aliases!(
    Cli,
    CliMethod,
    Status,
    ChatHistory,
    TimelineList,
    TimelineShow,
    RecentChats,
    ListPolemosDevices,
    SessionStats,
    SessionPurge,
    SessionVacuum,
    Search,
    TraceChain,
    ListTools,
    ListSkills,
    ListWorkspaces,
    OpenWorkspace,
    SwitchWorkspace
);
flat_aliases!(
    Tool,
    ToolMethod,
    CallTool,
    ToolCallResult,
    ListTools,
    ToolsListResponse
);
flat_aliases!(
    Skill,
    SkillMethod,
    CallSkill,
    SkillCallResult,
    ListSkills,
    SkillsListResponse
);
flat_aliases!(Base, BaseMethod, Heartbeat, HeartbeatAck, Error, Ack);
flat_aliases!(
    Device,
    DeviceMethod,
    PolemosRegister,
    PolemosRegisterAck,
    Heartbeat,
    HeartbeatAck,
    TerminalOpen,
    TerminalReady,
    TerminalInput,
    TerminalResize,
    TerminalPoll,
    TerminalPollResult,
    TerminalClose,
    TerminalCloseAck,
    FileList,
    FileListResult,
    FileDownload,
    FileDownloadResult,
    FileUpload,
    FileUploadResult,
    Ping,
    Pong,
    WebrtcOffer,
    WebrtcAnswer,
    WebrtcIce,
    SubscribeOutput,
    TerminalList,
    TerminalOutput,
    Error,
);
flat_aliases!(Screen, ScreenMethod, Offer, Answer, Ice, IceCandidate);

// ══════════════════════════════════════════════════════════════
// Method impl — delegates to inner
// ══════════════════════════════════════════════════════════════

impl Method {
    pub fn method_name(self) -> &'static str {
        match self {
            Method::Sync(m) => m.wire(),
            Method::Cli(m) => m.wire(),
            Method::Tool(m) => m.wire(),
            Method::Skill(m) => m.wire(),
            Method::Base(m) => m.wire(),
            Method::Device(m) => m.wire(),
            Method::Screen(m) => m.wire(),
        }
    }
    pub fn kind(self) -> MessageKind {
        match self {
            Method::Sync(m) => m.kind(),
            Method::Cli(m) => m.kind(),
            Method::Tool(m) => m.kind(),
            Method::Skill(m) => m.kind(),
            Method::Base(m) => m.kind(),
            Method::Device(m) => m.kind(),
            Method::Screen(m) => m.kind(),
        }
    }
    pub fn is_one_way(self) -> bool {
        matches!(self.kind(), MessageKind::OneWay)
    }
    pub fn response(self) -> Option<Method> {
        match self {
            Method::Sync(m) => m.response().map(Method::Sync),
            Method::Cli(m) => m.response().map(Method::Cli),
            Method::Tool(m) => m.response().map(Method::Tool),
            Method::Skill(m) => m.response().map(Method::Skill),
            Method::Base(m) => m.response().map(Method::Base),
            Method::Device(m) => m.response().map(Method::Device),
            Method::Screen(m) => m.response().map(Method::Screen),
        }
    }
}

impl std::str::FromStr for Method {
    type Err = strum::ParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (ns, action) = s
            .split_once('.')
            .ok_or(strum::ParseError::VariantNotFound)?;
        Ok(match ns {
            "Tui" | "Sync" => Method::Sync(action.parse()?),
            "Cli" => Method::Cli(action.parse()?),
            "Tool" => Method::Tool(action.parse()?),
            "Skill" => Method::Skill(action.parse()?),
            "Base" => Method::Base(action.parse()?),
            "Device" => Method::Device(action.parse()?),
            "Screen" => Method::Screen(action.parse()?),
            _ => return Err(strum::ParseError::VariantNotFound),
        })
    }
}

impl std::fmt::Display for Method {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.method_name())
    }
}

// ══════════════════════════════════════════════════════════════
// PendingRegistry
// ══════════════════════════════════════════════════════════════

pub struct PendingHandle {
    pub id: Uuid,
    rx: oneshot::Receiver<Value>,
}
impl PendingHandle {
    pub async fn wait(self) -> Result<Value, oneshot::error::RecvError> {
        self.rx.await
    }
}

/// Soft ceiling on live pending entries (audit R1-JR-8): at the ceiling
/// the OLDEST entry is evicted (its receiver errors with "registry
/// evicted a stale pending"), so the map can never grow without bound
/// no matter how many deferred ops are registered without resolution.
const MAX_PENDING_ENTRIES: usize = 10_000;

pub struct PendingRegistry {
    pending: HashMap<Uuid, oneshot::Sender<Value>>,
    /// Insertion order for FIFO eviction at [`MAX_PENDING_ENTRIES`].
    insertion_order: VecDeque<Uuid>,
}

impl PendingRegistry {
    pub fn new() -> Self {
        Self {
            pending: HashMap::new(),
            insertion_order: VecDeque::new(),
        }
    }
    pub fn prepare_notify(method: Method, params: Value) -> Value {
        serde_json::json!({"jsonrpc":"2.0","method":method.method_name(),"params":params})
    }
    pub fn request(&mut self, method: Method, params: Value) -> (Value, PendingHandle) {
        let (h, id) = self.register_pending();
        (
            serde_json::json!({"jsonrpc":"2.0","id":id.to_string(),"method":method.method_name(),"params":params}),
            h,
        )
    }
    pub fn request_async(&mut self, method: Method, params: Value) -> (Value, PendingHandle) {
        self.request(method, params)
    }
    pub fn on_response(&mut self, id: &str, result: Value) -> bool {
        Uuid::parse_str(id)
            .ok()
            .and_then(|u| self.pending.remove(&u))
            .map(|tx| {
                let _ = tx.send(result);
            })
            .is_some()
    }
    pub fn on_error(&mut self, id: &str, error: Value) -> bool {
        self.on_response(id, serde_json::json!({"__error":error}))
    }
    pub fn pending_count(&self) -> usize {
        self.pending.len()
    }
    fn register_pending(&mut self) -> (PendingHandle, Uuid) {
        // Audit R1-JR-8: evict the oldest entry at the cap so the map
        // cannot grow without bound.
        while self.pending.len() >= MAX_PENDING_ENTRIES {
            if let Some(oldest) = self.insertion_order.pop_front() {
                self.pending.remove(&oldest);
            } else {
                break;
            }
        }
        let id = Uuid::new_v4();
        let (tx, rx) = oneshot::channel();
        self.pending.insert(id, tx);
        self.insertion_order.push_back(id);
        (PendingHandle { id, rx }, id)
    }
}
impl Default for PendingRegistry {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_wire_from_enum_path() {
        assert_eq!(
            Method::Sync(SyncMethod::ServerVersion).method_name(),
            "Sync.ServerVersion"
        );
        assert_eq!(
            Method::SyncServerVersion.method_name(),
            "Sync.ServerVersion"
        ); // flat alias
        assert_eq!(Method::Cli(CliMethod::Status).method_name(), "Cli.Status");
        assert_eq!(Method::CliStatus.method_name(), "Cli.Status");
        assert_eq!(
            Method::Tool(ToolMethod::CallTool).method_name(),
            "Tool.CallTool"
        );
    }
    #[test]
    fn test_parse_roundtrip() {
        assert_eq!(
            "Sync.ServerVersion"
                .parse::<Method>()
                .unwrap()
                .method_name(),
            "Sync.ServerVersion"
        );
        assert_eq!(
            "Cli.Status".parse::<Method>().unwrap().method_name(),
            "Cli.Status"
        );
        assert_eq!(
            "Device.TerminalOpen"
                .parse::<Method>()
                .unwrap()
                .method_name(),
            "Device.TerminalOpen"
        );
    }
    #[test]
    fn test_kind() {
        assert_eq!(SyncMethod::ServerVersion.kind(), MessageKind::OneWay);
        assert_eq!(SyncMethod::ConnectHandshake.kind(), MessageKind::SyncReq);
        assert_eq!(SyncMethod::YoloStart.kind(), MessageKind::AsyncReq);
        assert_eq!(Method::SyncServerVersion.kind(), MessageKind::OneWay);
    }
    #[test]
    fn test_response() {
        assert_eq!(
            SyncMethod::ConnectHandshake.response(),
            Some(SyncMethod::HandshakeAck)
        );
        assert_eq!(SyncMethod::Ping.response(), Some(SyncMethod::Pong));
        assert_eq!(SyncMethod::ServerVersion.response(), None);
        assert_eq!(Method::SyncServerVersion.response(), None);
    }
    #[tokio::test]
    async fn test_pending() {
        let mut r = PendingRegistry::new();
        let (f, h) = r.request(Method::CliStatus, Value::Null);
        r.on_response(f["id"].as_str().unwrap(), serde_json::json!({"ok":true}));
        assert_eq!(h.wait().await.unwrap(), serde_json::json!({"ok":true}));
    }
    #[test]
    fn test_prepare_notify() {
        let f =
            PendingRegistry::prepare_notify(Method::SyncAgentReport, serde_json::json!({"x":1}));
        assert!(f.get("id").is_none());
        assert_eq!(f["method"], "Sync.AgentReport");
    }
}