scrybe-rpc 0.6.3

Scrybe CLI ↔ GUI wire protocol — JSON-RPC 2.0 types over a Unix socket.
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
//! Scrybe CLI ↔ GUI wire protocol.
//!
//! JSON-RPC 2.0 over a Unix-domain socket (Windows: named pipe). The CLI
//! binary in `scrybe-cli/` is the client; the running Scrybe app in
//! `scrybe-app/src-tauri/` is the server. Both depend on this crate so the
//! protocol has a single source of truth.
//!
//! ## Methods (Phase 1 — GUI-mutating)
//!
//! - `open(path)` — open a tab, or force-refresh if the file is already open
//! - `save(path)` — save an open tab's buffer to disk; no-op if not open
//! - `close(path)` — close a tab; no-op if not open
//! - `quit({ force })` — quit the app; `force=true` skips dirty-buffer prompt
//!
//! ## Framing
//!
//! Newline-delimited JSON. One request per line, one response per line.
//! Multiple requests on a single connection are processed FIFO.
//!
//! ## Socket location
//!
//! `~/.scrybe/sock` by default. Override with the `SCRYBE_SOCK` env var.

use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// JSON-RPC client dialer — shared by the CLI and the MCP server so both talk
/// to the live app through one implementation.
pub mod client;

pub use client::{ClientError, EnvelopeError, UnavailableKind};

/// JSON-RPC 2.0 request envelope.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Request {
    pub jsonrpc: JsonRpcVersion,
    pub id: u64,
    pub method: String,
    #[serde(default, skip_serializing_if = "is_null")]
    pub params: serde_json::Value,
}

/// JSON-RPC 2.0 response envelope. Either `result` or `error` is set, never both.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Response {
    pub jsonrpc: JsonRpcVersion,
    pub id: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<RpcError>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RpcError {
    pub code: i32,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
}

/// Newtype that always serializes / deserializes as the literal string `"2.0"`.
/// Wrong protocol versions are rejected at parse time instead of being a
/// runtime check on every dispatch.
#[derive(Debug, Clone, PartialEq)]
pub struct JsonRpcVersion;

impl Serialize for JsonRpcVersion {
    fn serialize<S: serde::Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
        ser.serialize_str("2.0")
    }
}

impl<'de> Deserialize<'de> for JsonRpcVersion {
    fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
        let s = String::deserialize(de)?;
        if s == "2.0" {
            Ok(Self)
        } else {
            Err(serde::de::Error::custom(format!(
                "unsupported jsonrpc version: {s} (expected \"2.0\")"
            )))
        }
    }
}

fn is_null(v: &serde_json::Value) -> bool {
    v.is_null()
}

// ── Method-specific param + result types ────────────────────────────────────

/// Params for `open`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OpenParams {
    /// Absolute or canonicalizable path to the markdown file.
    pub path: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct OpenResult {
    /// Stable id of the tab. Empty when fire-and-forget.
    #[serde(default)]
    pub tab_id: String,
    /// `true` if the tab already existed and was force-refreshed from disk;
    /// `false` if a new tab was created.
    pub reloaded: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SaveParams {
    pub path: String,
}

/// Result of `save` (reply-correlated): the tab's buffer was written to its
/// file. `was_dirty` reports whether the buffer had unsaved edits before the
/// write — a clean save is a harmless rewrite of identical content. A path
/// that isn't open errors with `ERR_TAB_NOT_OPEN`; each surface decides its
/// own presentation (the CLI keeps its documented silent no-op).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SaveResult {
    pub path: String,
    /// Bytes written to disk.
    pub bytes: u64,
    /// Whether the buffer had unsaved edits at save time.
    pub was_dirty: bool,
}

/// `close`/`quit` result. `applied: false` means the file wasn't open and
/// the command was a no-op (per the design's "silent no-op" rule).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AckResult {
    pub applied: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CloseParams {
    pub path: String,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct QuitParams {
    /// Skip the dirty-buffer confirmation prompt.
    #[serde(default)]
    pub force: bool,
}

// ── Phase 2: read-side params + results ──────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ReadParams {
    pub path: String,
}

/// Result of `read`. Returns the in-memory buffer content (which may differ
/// from disk if there are unsaved edits) along with state metadata.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ReadResult {
    pub path: String,
    pub content: String,
    pub is_dirty: bool,
}

/// One open tab as seen over the socket (`list_tabs`).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TabInfo {
    /// Canonical path, or empty for an untitled buffer.
    pub path: String,
    /// Display title (usually the file name).
    pub title: String,
    /// Unsaved edits present.
    pub is_dirty: bool,
    /// Current view mode (`both` | `edit` | `preview`).
    pub view_mode: String,
    /// True for the currently focused tab.
    pub active: bool,
}

/// Result of `list_tabs`: the live set of open tabs.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ListTabsResult {
    pub tabs: Vec<TabInfo>,
}

/// Params for `reload`: re-read an open tab from disk into its live buffer.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ReloadParams {
    /// Canonical path of the open tab to reload.
    pub path: String,
    /// Reload even if the buffer has unsaved edits (discarding them).
    #[serde(default)]
    pub force: bool,
}

/// Result of `reload`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ReloadResult {
    pub path: String,
    /// Bytes re-read from disk.
    pub bytes: u64,
    /// Whether the buffer had unsaved edits at reload time.
    pub was_dirty: bool,
}

// ── UI-parity methods (A2: the typed replacements for the /tmp signal files) ──

/// Result of `state`: what the human is looking at right now. Mirrors the
/// path bar, tab mode icon, theme dropdown, and Vim toggle — served straight
/// from live frontend state (never a file).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StateResult {
    pub active_path: Option<String>,
    pub active_title: Option<String>,
    pub is_dirty: bool,
    pub view_mode: String,
    pub theme: String,
    pub vim: bool,
    pub wrap: bool,
    pub open_paths: Vec<String>,
}

/// Params for `set_theme`: the editor + preview theme.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SetThemeParams {
    /// One of the app's theme names (`default`, `dark`, `solarized`).
    pub theme: String,
}

/// Result of `set_theme`: echoes the applied theme.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SetThemeResult {
    pub theme: String,
}

/// Params for `view_mode`: a concrete mode or `cycle`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ViewModeParams {
    /// `both`, `edit`, `preview`, or `cycle` (advance both→edit→preview).
    pub mode: String,
}

/// Result of `view_mode`: the CONCRETE mode now active (cycle resolved).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ViewModeResult {
    pub mode: String,
}

/// Params for `set_vim`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SetVimParams {
    pub enabled: bool,
}

/// Result of `set_vim`: echoes the applied setting.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SetVimResult {
    pub enabled: bool,
}

/// Params for `logs`: recent console output from the running app.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct LogsParams {
    /// Max lines from the end of the in-memory ring (default 50, capped by
    /// the frontend's ring size).
    #[serde(default)]
    pub tail: Option<u32>,
}

/// Result of `logs`: newest-last lines from the frontend's console ring.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct LogsResult {
    pub lines: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FindParams {
    pub pattern: String,
    /// If empty, search across all open tabs. Otherwise, search the named
    /// paths (which the GUI may or may not have open — disk fallback for
    /// non-open paths).
    #[serde(default)]
    pub paths: Vec<String>,
    /// Treat `pattern` as a literal string instead of a regex.
    #[serde(default)]
    pub literal: bool,
    /// Match case-sensitively (default: insensitive).
    #[serde(default)]
    pub case_sensitive: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FindHit {
    pub path: String,
    /// 1-indexed line number.
    pub line: u32,
    /// 1-indexed column where the match starts within the line.
    pub column: u32,
    /// The line text (so callers can render context without re-reading).
    pub text: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FindResult {
    pub hits: Vec<FindHit>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SectionParams {
    pub path: String,
    /// Heading text to find. Case-insensitive substring match.
    pub heading: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SectionResult {
    pub heading: String,
    pub level: u8,
    pub content: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct EditParams {
    pub path: String,
    /// 1-indexed inclusive line range to replace. Use the same value for
    /// `start_line` and `end_line` to edit a single line. Use
    /// `start_line == end_line + 1` semantics to insert without replacing
    /// (handled by the frontend's edit logic).
    pub start_line: u32,
    pub end_line: u32,
    /// New content for the range. Trailing newline behavior follows the
    /// frontend's existing edit logic.
    pub content: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct EditResult {
    pub applied: bool,
    pub size_after: usize,
    /// Buffer dirty after the edit — true until an explicit `save` persists
    /// it (edits land in the in-memory buffer only, never directly on disk).
    /// Defaults to `false` for replies from older apps that omit it.
    #[serde(default)]
    pub is_dirty: bool,
}

// ── Reply correlation (server → frontend → server) ───────────────────────────
//
// For commands that need data BACK from the frontend (read, find, section,
// edit), the server emits an event carrying `{id, data}` where `id` is the
// request id. The frontend handles the work and submits a `cli_rpc_reply`
// Tauri command with the same id and a `Reply` payload.

/// Wire format for events the server emits to the frontend that need a
/// reply. The frontend pattern-matches on the embedded `data` shape.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct EventEnvelope<T> {
    pub id: u64,
    pub data: T,
}

/// Wire format for replies the frontend sends back via `cli_rpc_reply`.
/// Either `result` or `error` is set, never both. Mirrors `Response`'s
/// shape (deliberately — the dispatcher converts this into the outgoing
/// JSON-RPC `Response` directly).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Reply {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<RpcError>,
}

impl Reply {
    pub fn ok(result: serde_json::Value) -> Self {
        Self {
            result: Some(result),
            error: None,
        }
    }

    pub fn err(code: i32, message: impl Into<String>) -> Self {
        Self {
            result: None,
            error: Some(RpcError {
                code,
                message: message.into(),
                data: None,
            }),
        }
    }
}

// ── JSON-RPC error codes ────────────────────────────────────────────────────
//
// Standard codes (-32700 to -32603) follow the spec. Application codes live in
// APP_ERR_RANGE below. The full registry is frozen in docs/rpc-contract-0.6.md.

/// The reserved range for Scrybe application error codes, per the JSON-RPC 2.0
/// "server error" convention: every `ERR_*` application code MUST fall inside
/// `-32099..=-32000`, MUST be unique, and — once shipped in a release — MUST
/// keep its meaning forever (the 0.6 contract fixture,
/// `docs/rpc-contract-0.6.md`, is the compatibility artifact). Enforced by the
/// `app_error_codes_unique_and_in_reserved_range` test.
pub const APP_ERR_RANGE: std::ops::RangeInclusive<i32> = -32099..=-32000;

/// Every application-defined error code, in one place. New codes MUST be added
/// here (the registry test checks uniqueness + range membership against this
/// slice) and documented in `docs/rpc-contract-0.6.md`.
pub const APP_ERROR_CODES: &[i32] = &[
    ERR_TAB_NOT_OPEN,
    ERR_DIRTY_QUIT_REFUSED,
    ERR_REPLY_TIMEOUT,
    ERR_SECTION_NOT_FOUND,
    ERR_DIRTY_RELOAD_REFUSED,
];

pub const ERR_PARSE: i32 = -32700;
pub const ERR_INVALID_REQUEST: i32 = -32600;
pub const ERR_METHOD_NOT_FOUND: i32 = -32601;
pub const ERR_INVALID_PARAMS: i32 = -32602;
pub const ERR_INTERNAL: i32 = -32603;

/// The path argument is not a tab currently open in the GUI.
/// `read`/`edit`/`save` reply with this; `close` translates it into
/// `applied: false` instead by design choice.
pub const ERR_TAB_NOT_OPEN: i32 = -32001;

/// `quit` was requested with `force=false` but the app has dirty buffers.
pub const ERR_DIRTY_QUIT_REFUSED: i32 = -32002;

/// The frontend didn't reply to a request-with-reply within the timeout.
/// Most likely cause: the GUI was busy or the user dismissed a modal that
/// blocked the event loop. Caller can retry.
pub const ERR_REPLY_TIMEOUT: i32 = -32003;

/// The requested heading wasn't found in the document.
/// Used by `section`.
pub const ERR_SECTION_NOT_FOUND: i32 = -32004;

/// `reload` was requested without `force` but the tab has unsaved edits.
pub const ERR_DIRTY_RELOAD_REFUSED: i32 = -32005;

// ── Helpers ─────────────────────────────────────────────────────────────────

impl Response {
    pub fn ok(id: u64, result: serde_json::Value) -> Self {
        Self {
            jsonrpc: JsonRpcVersion,
            id,
            result: Some(result),
            error: None,
        }
    }

    pub fn err(id: u64, code: i32, message: impl Into<String>) -> Self {
        Self {
            jsonrpc: JsonRpcVersion,
            id,
            result: None,
            error: Some(RpcError {
                code,
                message: message.into(),
                data: None,
            }),
        }
    }
}

/// Resolve the socket path: `$SCRYBE_SOCK` if set, otherwise `~/.scrybe/sock`.
/// Falls back to `/tmp/.scrybe-sock` only if `$HOME` is also unset.
pub fn default_socket_path() -> PathBuf {
    resolve_socket_path(
        std::env::var("SCRYBE_SOCK").ok().as_deref(),
        std::env::var("HOME").ok().as_deref(),
    )
}

/// Pure resolution logic for [`default_socket_path`]. Split out so it can be
/// unit-tested without mutating process-global env vars (which races across
/// parallel tests).
fn resolve_socket_path(sock_override: Option<&str>, home: Option<&str>) -> PathBuf {
    if let Some(s) = sock_override {
        return PathBuf::from(s);
    }
    if let Some(h) = home {
        return PathBuf::from(h).join(".scrybe").join("sock");
    }
    PathBuf::from("/tmp/.scrybe-sock")
}

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

    #[test]
    fn jsonrpc_version_roundtrip() {
        let req = Request {
            jsonrpc: JsonRpcVersion,
            id: 1,
            method: "open".into(),
            params: serde_json::json!({"path": "/tmp/foo.md"}),
        };
        let s = serde_json::to_string(&req).unwrap();
        assert!(s.contains(r#""jsonrpc":"2.0""#));
        let back: Request = serde_json::from_str(&s).unwrap();
        assert_eq!(back, req);
    }

    #[test]
    fn rejects_wrong_jsonrpc_version() {
        let bad = r#"{"jsonrpc":"1.0","id":1,"method":"open","params":{"path":"x"}}"#;
        let err = serde_json::from_str::<Request>(bad).unwrap_err();
        assert!(err.to_string().contains("unsupported jsonrpc version"));
    }

    #[test]
    fn response_ok_serializes_result_only() {
        let r = Response::ok(7, serde_json::json!({"applied": true}));
        let s = serde_json::to_string(&r).unwrap();
        assert!(s.contains(r#""result":{"applied":true}"#));
        assert!(!s.contains("\"error\""));
    }

    #[test]
    fn response_err_serializes_error_only() {
        let r = Response::err(7, ERR_TAB_NOT_OPEN, "tab not open");
        let s = serde_json::to_string(&r).unwrap();
        assert!(s.contains(r#""code":-32001"#));
        assert!(s.contains(r#""message":"tab not open""#));
        assert!(!s.contains("\"result\""));
    }

    #[test]
    fn open_params_roundtrip() {
        let p = OpenParams {
            path: "/tmp/foo.md".into(),
        };
        let v = serde_json::to_value(&p).unwrap();
        let back: OpenParams = serde_json::from_value(v).unwrap();
        assert_eq!(back, p);
    }

    #[test]
    fn quit_params_force_default_false() {
        let p: QuitParams = serde_json::from_str("{}").unwrap();
        assert!(!p.force);
        let p: QuitParams = serde_json::from_str(r#"{"force": true}"#).unwrap();
        assert!(p.force);
    }

    #[test]
    fn ack_result_roundtrip() {
        let r = AckResult { applied: false };
        let v = serde_json::to_value(&r).unwrap();
        assert_eq!(v, serde_json::json!({"applied": false}));
    }

    #[test]
    fn open_result_default_tab_id() {
        let v = serde_json::json!({"reloaded": true});
        let r: OpenResult = serde_json::from_value(v).unwrap();
        assert_eq!(r.tab_id, "");
        assert!(r.reloaded);
    }

    // ── Phase 2 — read-side type coverage ────────────────────────────────

    #[test]
    fn read_params_roundtrip() {
        let p = ReadParams {
            path: "/tmp/foo.md".into(),
        };
        let s = serde_json::to_string(&p).unwrap();
        assert!(s.contains("/tmp/foo.md"));
        let back: ReadParams = serde_json::from_str(&s).unwrap();
        assert_eq!(back, p);
    }

    #[test]
    fn read_result_roundtrip() {
        let r = ReadResult {
            path: "/tmp/foo.md".into(),
            content: "# H1\n".into(),
            is_dirty: true,
        };
        let v = serde_json::to_value(&r).unwrap();
        let back: ReadResult = serde_json::from_value(v).unwrap();
        assert_eq!(back, r);
    }

    #[test]
    fn find_params_defaults() {
        let p: FindParams = serde_json::from_str(r#"{"pattern": "TODO"}"#).unwrap();
        assert_eq!(p.pattern, "TODO");
        assert!(p.paths.is_empty());
        assert!(!p.literal);
        assert!(!p.case_sensitive);
    }

    #[test]
    fn find_hit_serializes() {
        let h = FindHit {
            path: "/x".into(),
            line: 10,
            column: 5,
            text: "match here".into(),
        };
        let v = serde_json::to_value(&h).unwrap();
        assert_eq!(v["line"], 10);
        assert_eq!(v["column"], 5);
        let back: FindHit = serde_json::from_value(v).unwrap();
        assert_eq!(back, h);
    }

    #[test]
    fn find_result_default_empty() {
        // Empty hits is the legitimate "no matches" case.
        let r = FindResult { hits: vec![] };
        let s = serde_json::to_string(&r).unwrap();
        assert_eq!(s, r#"{"hits":[]}"#);
    }

    #[test]
    fn section_params_roundtrip() {
        let p = SectionParams {
            path: "/tmp/foo.md".into(),
            heading: "Install".into(),
        };
        let v = serde_json::to_value(&p).unwrap();
        let back: SectionParams = serde_json::from_value(v).unwrap();
        assert_eq!(back, p);
    }

    #[test]
    fn section_result_roundtrip() {
        let r = SectionResult {
            heading: "Install".into(),
            level: 2,
            content: "## Install\n\n\n".into(),
        };
        let v = serde_json::to_value(&r).unwrap();
        let back: SectionResult = serde_json::from_value(v).unwrap();
        assert_eq!(back, r);
    }

    #[test]
    fn edit_params_roundtrip() {
        let p = EditParams {
            path: "/tmp/foo.md".into(),
            start_line: 1,
            end_line: 5,
            content: "new content".into(),
        };
        let v = serde_json::to_value(&p).unwrap();
        let back: EditParams = serde_json::from_value(v).unwrap();
        assert_eq!(back, p);
    }

    #[test]
    fn edit_result_serializes() {
        let r = EditResult {
            applied: true,
            size_after: 1024,
            is_dirty: true,
        };
        let v = serde_json::to_value(&r).unwrap();
        assert_eq!(
            v,
            serde_json::json!({"applied": true, "size_after": 1024, "is_dirty": true})
        );
    }

    #[test]
    fn edit_result_is_dirty_defaults_false_for_older_apps() {
        let v = serde_json::json!({"applied": true, "size_after": 10});
        let r: EditResult = serde_json::from_value(v).unwrap();
        assert!(!r.is_dirty);
    }

    #[test]
    fn save_result_roundtrip() {
        let r = SaveResult {
            path: "/tmp/foo.md".into(),
            bytes: 42,
            was_dirty: true,
        };
        let v = serde_json::to_value(&r).unwrap();
        assert_eq!(
            v,
            serde_json::json!({"path": "/tmp/foo.md", "bytes": 42, "was_dirty": true})
        );
        let back: SaveResult = serde_json::from_value(v).unwrap();
        assert_eq!(back, r);
    }

    #[test]
    fn reply_ok_serializes_result_only() {
        let r = Reply::ok(serde_json::json!({"x": 1}));
        let s = serde_json::to_string(&r).unwrap();
        assert!(s.contains(r#""result":{"x":1}"#));
        assert!(!s.contains("\"error\""));
    }

    #[test]
    fn reply_err_serializes_error_only() {
        let r = Reply::err(ERR_TAB_NOT_OPEN, "not open");
        let s = serde_json::to_string(&r).unwrap();
        assert!(s.contains(r#""code":-32001"#));
        assert!(!s.contains("\"result\""));
    }

    #[test]
    fn event_envelope_carries_id_and_data() {
        let env = EventEnvelope {
            id: 7,
            data: serde_json::json!({"path": "/tmp/x"}),
        };
        let v = serde_json::to_value(&env).unwrap();
        assert_eq!(v["id"], 7);
        assert_eq!(v["data"]["path"], "/tmp/x");
    }

    #[test]
    fn app_error_codes_unique_and_in_reserved_range() {
        // The contract registry: every application code lives in
        // APP_ERROR_CODES, is unique, and stays inside the reserved
        // APP_ERR_RANGE (-32099..=-32000). New codes extend the slice —
        // this test then covers them automatically.
        for &c in APP_ERROR_CODES {
            assert!(
                APP_ERR_RANGE.contains(&c),
                "code {c} outside reserved app range {APP_ERR_RANGE:?}"
            );
        }
        let mut sorted = APP_ERROR_CODES.to_vec();
        sorted.sort_unstable();
        sorted.dedup();
        assert_eq!(sorted.len(), APP_ERROR_CODES.len(), "codes collide");
    }

    #[test]
    fn standard_codes_stay_outside_the_app_range() {
        // The spec-standard codes must never drift into (or collide with)
        // the application range.
        for c in [
            ERR_PARSE,
            ERR_INVALID_REQUEST,
            ERR_METHOD_NOT_FOUND,
            ERR_INVALID_PARAMS,
            ERR_INTERNAL,
        ] {
            assert!(
                !APP_ERR_RANGE.contains(&c),
                "standard code {c} collides with the app range"
            );
        }
    }

    #[test]
    fn resolve_socket_path_uses_override() {
        let p = resolve_socket_path(Some("/tmp/custom-scrybe-sock"), Some("/home/test"));
        assert_eq!(p, PathBuf::from("/tmp/custom-scrybe-sock"));
    }

    #[test]
    fn resolve_socket_path_uses_home_when_no_override() {
        let p = resolve_socket_path(None, Some("/home/test"));
        assert_eq!(p, PathBuf::from("/home/test/.scrybe/sock"));
    }

    #[test]
    fn resolve_socket_path_falls_back_when_home_unset() {
        let p = resolve_socket_path(None, None);
        assert_eq!(p, PathBuf::from("/tmp/.scrybe-sock"));
    }

    #[test]
    fn default_socket_path_returns_some_path() {
        // Smoke test: the env-reading wrapper produces *some* path. The
        // resolution logic itself is covered by the pure-function tests above,
        // which don't race on process-global env vars.
        let p = default_socket_path();
        assert!(!p.as_os_str().is_empty());
    }
}