zeph-config 0.20.1

Pure-data configuration types for Zeph
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
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::path::{Component, Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::defaults::default_true;

fn default_acp_agent_name() -> String {
    "zeph".to_owned()
}

fn default_acp_agent_version() -> String {
    env!("CARGO_PKG_VERSION").to_owned()
}

fn default_acp_max_sessions() -> usize {
    4
}

fn default_acp_session_idle_timeout_secs() -> u64 {
    1800
}

fn default_acp_broadcast_capacity() -> usize {
    256
}

fn default_acp_transport() -> AcpTransport {
    AcpTransport::Stdio
}

fn default_acp_http_bind() -> String {
    "127.0.0.1:9800".to_owned()
}

fn default_acp_discovery_enabled() -> bool {
    true
}

fn default_acp_lsp_max_diagnostics_per_file() -> usize {
    20
}

fn default_acp_lsp_max_diagnostic_files() -> usize {
    5
}

fn default_acp_lsp_max_references() -> usize {
    100
}

fn default_acp_lsp_max_workspace_symbols() -> usize {
    50
}

fn default_acp_lsp_request_timeout_secs() -> u64 {
    10
}
fn default_lsp_mcp_server_id() -> String {
    "mcpls".into()
}
fn default_lsp_token_budget() -> usize {
    2000
}
fn default_lsp_max_per_file() -> usize {
    20
}
fn default_lsp_max_symbols() -> usize {
    5
}
fn default_lsp_call_timeout_secs() -> u64 {
    5
}

/// Auth methods recognised by Zeph's ACP handler.
///
/// PR 4 MVP restricts this to `Agent` only. Future variants (`EnvVar`, `Terminal`) will
/// be added in follow-up issues with their sub-struct payloads.
///
/// # Examples
///
/// ```rust
/// use zeph_config::AcpAuthMethod;
/// use serde_json;
///
/// let m: AcpAuthMethod = serde_json::from_str(r#""agent""#).unwrap();
/// assert_eq!(m, AcpAuthMethod::Agent);
/// assert!(serde_json::from_str::<AcpAuthMethod>(r#""envvar""#).is_err());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AcpAuthMethod {
    /// Vault-backed agent auth — the sole supported method in PR 4.
    Agent,
}

impl<'de> serde::Deserialize<'de> for AcpAuthMethod {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        match s.as_str() {
            "agent" => Ok(Self::Agent),
            other => Err(serde::de::Error::unknown_variant(other, &["agent"])),
        }
    }
}

impl std::fmt::Display for AcpAuthMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Agent => f.write_str("agent"),
        }
    }
}

fn default_acp_auth_methods() -> Vec<AcpAuthMethod> {
    vec![AcpAuthMethod::Agent]
}

/// Error returned when parsing an [`AdditionalDir`] fails.
#[derive(Debug, thiserror::Error)]
pub enum AdditionalDirError {
    /// The raw path contains a `..` component.
    #[error("path `{0}` contains `..` traversal")]
    Traversal(PathBuf),
    /// The canonical path is a reserved system or credentials location.
    #[error("path `{0}` is a reserved system or credentials directory")]
    Reserved(PathBuf),
    /// `std::fs::canonicalize` failed.
    #[error("failed to canonicalize `{path}`: {source}")]
    Canonicalize {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
}

/// A single entry in the `acp.additional_directories` policy allowlist.
///
/// Constructed via [`Self::parse`], which:
/// 1. Rejects any path containing a `..` component (component-aware check).
/// 2. Expands a leading `~` to the user's home directory.
/// 3. Calls `std::fs::canonicalize`.
/// 4. Rejects paths prefixed by `/proc`, `/sys`, `{HOME}/.ssh`, `{HOME}/.gnupg`, or `{HOME}/.aws`.
///
/// # Examples
///
/// ```rust,no_run
/// use zeph_config::AdditionalDir;
///
/// let dir = AdditionalDir::parse("/tmp/workspace").unwrap();
/// assert!(dir.as_path().is_absolute());
/// assert!(AdditionalDir::parse("/proc/self").is_err());
/// ```
#[derive(Clone, PartialEq, Eq)]
pub struct AdditionalDir(PathBuf);

impl AdditionalDir {
    /// Parse and validate a raw path as a policy allowlist entry.
    ///
    /// # Errors
    ///
    /// Returns [`AdditionalDirError`] on traversal, reserved prefix, or canonicalization failure.
    pub fn parse(raw: impl Into<PathBuf>) -> Result<Self, AdditionalDirError> {
        let raw: PathBuf = raw.into();

        // Expand leading `~`.
        let expanded = if raw.starts_with("~") {
            let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("/"));
            home.join(raw.strip_prefix("~").unwrap_or(&raw))
        } else {
            raw.clone()
        };

        // Reject `..` components (component-aware, not string-based).
        for component in expanded.components() {
            if component == Component::ParentDir {
                return Err(AdditionalDirError::Traversal(raw));
            }
        }

        let canon =
            std::fs::canonicalize(&expanded).map_err(|e| AdditionalDirError::Canonicalize {
                path: raw.clone(),
                source: e,
            })?;

        // Reject reserved locations.
        let reserved = reserved_prefixes();
        for prefix in &reserved {
            if canon.starts_with(prefix) {
                return Err(AdditionalDirError::Reserved(canon));
            }
        }

        Ok(Self(canon))
    }

    /// Returns the canonicalized path.
    #[must_use]
    pub fn as_path(&self) -> &Path {
        &self.0
    }
}

fn reserved_prefixes() -> Vec<PathBuf> {
    let mut prefixes = vec![PathBuf::from("/proc"), PathBuf::from("/sys")];
    if let Some(home) = dirs::home_dir() {
        prefixes.push(home.join(".ssh"));
        prefixes.push(home.join(".gnupg"));
        prefixes.push(home.join(".aws"));
    }
    prefixes
}

impl std::fmt::Debug for AdditionalDir {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "AdditionalDir({:?})", self.0)
    }
}

impl std::fmt::Display for AdditionalDir {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0.display())
    }
}

impl Serialize for AdditionalDir {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        self.0.to_string_lossy().serialize(s)
    }
}

impl<'de> serde::Deserialize<'de> for AdditionalDir {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = String::deserialize(d)?;
        Self::parse(s).map_err(serde::de::Error::custom)
    }
}

/// TUI (terminal user interface) configuration, nested under `[tui]` in TOML.
///
/// # Example (TOML)
///
/// ```toml
/// [tui]
/// show_source_labels = true
/// ```
#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize)]
pub struct TuiConfig {
    /// Show memory source labels (episodic / semantic / graph) in the message view.
    /// Default: `false`.
    #[serde(default)]
    pub show_source_labels: bool,
}

/// ACP server transport mode.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AcpTransport {
    /// JSON-RPC over stdin/stdout (default, IDE embedding).
    #[default]
    Stdio,
    /// JSON-RPC over HTTP+SSE and WebSocket.
    Http,
    /// Both stdio and HTTP transports active simultaneously.
    Both,
}

/// Configuration for a named sub-agent preset in `[[acp.subagents.presets]]`.
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct SubagentPresetConfig {
    /// Identifier used to reference this preset by name.
    pub name: String,
    /// Shell command string to spawn the sub-agent (e.g. `"cargo run -- --acp"`).
    pub command: String,
    /// Optional working directory for the spawned subprocess.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cwd: Option<PathBuf>,
    /// Timeout in seconds for the `initialize` + `session/new` handshake. Default: 30.
    #[serde(default = "default_subagent_handshake_timeout_secs")]
    pub handshake_timeout_secs: u64,
    /// Timeout in seconds for a single prompt round-trip. Default: 600.
    #[serde(default = "default_subagent_prompt_timeout_secs")]
    pub prompt_timeout_secs: u64,
}

/// Configuration block for the `[acp.subagents]` TOML section.
///
/// # Example
///
/// ```toml
/// [acp.subagents]
/// enabled = true
///
/// [[acp.subagents.presets]]
/// name = "inner"
/// command = "cargo run --quiet -- --acp"
/// ```
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
pub struct AcpSubagentsConfig {
    /// Whether sub-agent spawning is enabled at runtime. Default: `false`.
    #[serde(default)]
    pub enabled: bool,

    /// Named presets available via CLI (`zeph acp subagent list`) and TUI palette.
    #[serde(default)]
    pub presets: Vec<SubagentPresetConfig>,
}

fn default_subagent_handshake_timeout_secs() -> u64 {
    30
}

fn default_subagent_prompt_timeout_secs() -> u64 {
    600
}

/// ACP (Agent Communication Protocol) server configuration, nested under `[acp]` in TOML.
///
/// When `enabled = true`, Zeph exposes an ACP endpoint that IDE integrations (e.g. Zed, VS Code)
/// can connect to for conversational coding assistance. Supports stdio and HTTP transports.
///
/// # Example (TOML)
///
/// ```toml
/// [acp]
/// enabled = true
/// transport = "stdio"
/// agent_name = "zeph"
/// max_sessions = 4
/// ```
#[derive(Clone, Deserialize, Serialize)]
pub struct AcpConfig {
    /// Enable the ACP server. Default: `false`.
    #[serde(default)]
    pub enabled: bool,
    /// Agent name advertised in the ACP `initialize` response. Default: `"zeph"`.
    #[serde(default = "default_acp_agent_name")]
    pub agent_name: String,
    /// Agent version advertised in the ACP `initialize` response. Default: crate version.
    #[serde(default = "default_acp_agent_version")]
    pub agent_version: String,
    /// Maximum number of concurrent ACP sessions. Default: `4`.
    #[serde(default = "default_acp_max_sessions")]
    pub max_sessions: usize,
    /// Seconds of inactivity before an idle session is closed. Default: `1800`.
    #[serde(default = "default_acp_session_idle_timeout_secs")]
    pub session_idle_timeout_secs: u64,
    /// Broadcast channel capacity for streaming events. Default: `256`.
    #[serde(default = "default_acp_broadcast_capacity")]
    pub broadcast_capacity: usize,
    /// Path to the ACP permission TOML file controlling per-session tool access.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub permission_file: Option<std::path::PathBuf>,
    /// List of `{provider}:{model}` identifiers advertised to the IDE for model switching.
    /// Example: `["claude:claude-sonnet-4-5", "ollama:llama3"]`
    #[serde(default)]
    pub available_models: Vec<String>,
    /// Transport mode: "stdio" (default), "http", or "both".
    #[serde(default = "default_acp_transport")]
    pub transport: AcpTransport,
    /// Bind address for the HTTP transport.
    #[serde(default = "default_acp_http_bind")]
    pub http_bind: String,
    /// Bearer token for HTTP and WebSocket transport authentication.
    /// When set, all /acp and /acp/ws requests must include `Authorization: Bearer <token>`.
    /// Omit for local unauthenticated access. TLS termination is assumed to be handled by a
    /// reverse proxy.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub auth_token: Option<String>,
    /// Whether to serve the /.well-known/acp.json agent discovery manifest.
    /// Only effective when transport is "http" or "both". Default: true.
    #[serde(default = "default_acp_discovery_enabled")]
    pub discovery_enabled: bool,
    /// LSP extension configuration (`[acp.lsp]`).
    #[serde(default)]
    pub lsp: AcpLspConfig,
    /// Allowlist of workspace directories that ACP clients may reference in session requests.
    ///
    /// Paths are canonicalized at config load; traversal (`..`) and reserved locations
    /// (`/proc`, `/sys`, `~/.ssh`, `~/.gnupg`, `~/.aws`) are rejected with an error.
    /// An empty list means clients may not request any additional directories beyond the
    /// session `cwd`.
    ///
    /// This is a **policy** allowlist, not a protocol advertisement: the agent never returns
    /// `additional_directories` in any response; instead it validates each session request's
    /// `additional_directories` field against this list and rejects with `invalid_params`
    /// on any violation.
    #[serde(default)]
    pub additional_directories: Vec<AdditionalDir>,
    /// Auth methods advertised in the ACP `initialize` response.
    ///
    /// PR 4 MVP accepts only `"agent"`. Config load fails on any other value so drift
    /// from the schema is detected at startup rather than silently ignored.
    #[serde(default = "default_acp_auth_methods")]
    pub auth_methods: Vec<AcpAuthMethod>,
    /// Echo `PromptRequest.message_id` onto `PromptResponse.user_message_id` and every
    /// streamed chunk, enabling IDE-side correlation.
    ///
    /// Requires the `unstable-message-id` feature. Default: `true`.
    #[serde(default = "default_true")]
    pub message_ids_enabled: bool,
    /// Sub-agent delegation configuration (`[acp.subagents]`).
    #[serde(default)]
    pub subagents: AcpSubagentsConfig,
}

impl Default for AcpConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            agent_name: default_acp_agent_name(),
            agent_version: default_acp_agent_version(),
            max_sessions: default_acp_max_sessions(),
            session_idle_timeout_secs: default_acp_session_idle_timeout_secs(),
            broadcast_capacity: default_acp_broadcast_capacity(),
            permission_file: None,
            available_models: Vec::new(),
            transport: default_acp_transport(),
            http_bind: default_acp_http_bind(),
            auth_token: None,
            discovery_enabled: default_acp_discovery_enabled(),
            lsp: AcpLspConfig::default(),
            additional_directories: Vec::new(),
            auth_methods: default_acp_auth_methods(),
            message_ids_enabled: true,
            subagents: AcpSubagentsConfig::default(),
        }
    }
}

impl std::fmt::Debug for AcpConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AcpConfig")
            .field("enabled", &self.enabled)
            .field("agent_name", &self.agent_name)
            .field("agent_version", &self.agent_version)
            .field("max_sessions", &self.max_sessions)
            .field("session_idle_timeout_secs", &self.session_idle_timeout_secs)
            .field("broadcast_capacity", &self.broadcast_capacity)
            .field("permission_file", &self.permission_file)
            .field("available_models", &self.available_models)
            .field("transport", &self.transport)
            .field("http_bind", &self.http_bind)
            .field(
                "auth_token",
                &self.auth_token.as_ref().map(|_| "[REDACTED]"),
            )
            .field("discovery_enabled", &self.discovery_enabled)
            .field("lsp", &self.lsp)
            .field("additional_directories", &self.additional_directories)
            .field("auth_methods", &self.auth_methods)
            .field("message_ids_enabled", &self.message_ids_enabled)
            .field("subagents", &self.subagents)
            .finish()
    }
}

/// Configuration for the ACP LSP extension.
///
/// Controls LSP code intelligence features when connected to an IDE that advertises
/// `meta["lsp"]` capability during ACP `initialize`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AcpLspConfig {
    /// Enable LSP extension when the IDE supports it. Default: `true`.
    #[serde(default = "default_true")]
    pub enabled: bool,
    /// Automatically fetch diagnostics when `lsp/didSave` notification is received.
    #[serde(default = "default_true")]
    pub auto_diagnostics_on_save: bool,
    /// Maximum diagnostics to accept per file. Default: 20.
    #[serde(default = "default_acp_lsp_max_diagnostics_per_file")]
    pub max_diagnostics_per_file: usize,
    /// Maximum files in `DiagnosticsCache` (LRU eviction). Default: 5.
    #[serde(default = "default_acp_lsp_max_diagnostic_files")]
    pub max_diagnostic_files: usize,
    /// Maximum reference locations returned. Default: 100.
    #[serde(default = "default_acp_lsp_max_references")]
    pub max_references: usize,
    /// Maximum workspace symbol search results. Default: 50.
    #[serde(default = "default_acp_lsp_max_workspace_symbols")]
    pub max_workspace_symbols: usize,
    /// Timeout in seconds for LSP `ext_method` calls. Default: 10.
    #[serde(default = "default_acp_lsp_request_timeout_secs")]
    pub request_timeout_secs: u64,
}

impl Default for AcpLspConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            auto_diagnostics_on_save: true,
            max_diagnostics_per_file: default_acp_lsp_max_diagnostics_per_file(),
            max_diagnostic_files: default_acp_lsp_max_diagnostic_files(),
            max_references: default_acp_lsp_max_references(),
            max_workspace_symbols: default_acp_lsp_max_workspace_symbols(),
            request_timeout_secs: default_acp_lsp_request_timeout_secs(),
        }
    }
}

// ── LSP context injection ─────────────────────────────────────────────────────

/// Minimum diagnostic severity to include in LSP context injection.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum DiagnosticSeverity {
    #[default]
    Error,
    Warning,
    Info,
    Hint,
}

/// Configuration for the diagnostics-on-save hook (`[agent.lsp.diagnostics]`).
///
/// Flood control relies on `token_budget` in [`LspConfig`], not a per-file count.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct DiagnosticsConfig {
    /// Enable automatic diagnostics fetching after the `write` tool.
    pub enabled: bool,
    /// Maximum diagnostics entries per file.
    #[serde(default = "default_lsp_max_per_file")]
    pub max_per_file: usize,
    /// Minimum severity to include.
    #[serde(default)]
    pub min_severity: DiagnosticSeverity,
}
impl Default for DiagnosticsConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_per_file: default_lsp_max_per_file(),
            min_severity: DiagnosticSeverity::default(),
        }
    }
}

/// Configuration for the hover-on-read hook (`[agent.lsp.hover]`).
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct HoverConfig {
    /// Enable hover info pre-fetch after the `read` tool. Disabled by default.
    pub enabled: bool,
    /// Maximum hover entries per file (Rust-only for MVP).
    #[serde(default = "default_lsp_max_symbols")]
    pub max_symbols: usize,
}
impl Default for HoverConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            max_symbols: default_lsp_max_symbols(),
        }
    }
}

/// Top-level LSP context injection configuration (`[agent.lsp]` TOML section).
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(default)]
pub struct LspConfig {
    /// Enable LSP context injection hooks.
    pub enabled: bool,
    /// MCP server ID to route LSP calls through (default: "mcpls").
    #[serde(default = "default_lsp_mcp_server_id")]
    pub mcp_server_id: String,
    /// Maximum tokens to spend on injected LSP context per turn.
    #[serde(default = "default_lsp_token_budget")]
    pub token_budget: usize,
    /// Timeout in seconds for each MCP LSP call.
    #[serde(default = "default_lsp_call_timeout_secs")]
    pub call_timeout_secs: u64,
    /// Diagnostics-on-save hook configuration.
    #[serde(default)]
    pub diagnostics: DiagnosticsConfig,
    /// Hover-on-read hook configuration.
    #[serde(default)]
    pub hover: HoverConfig,
}
impl Default for LspConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            mcp_server_id: default_lsp_mcp_server_id(),
            token_budget: default_lsp_token_budget(),
            call_timeout_secs: default_lsp_call_timeout_secs(),
            diagnostics: DiagnosticsConfig::default(),
            hover: HoverConfig::default(),
        }
    }
}

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

    #[test]
    fn acp_auth_method_unknown_variant_fails() {
        assert!(serde_json::from_str::<AcpAuthMethod>(r#""bearer""#).is_err());
        assert!(serde_json::from_str::<AcpAuthMethod>(r#""envvar""#).is_err());
        assert!(serde_json::from_str::<AcpAuthMethod>(r#""Agent""#).is_err());
    }

    #[test]
    fn acp_auth_method_known_variant_succeeds() {
        let m = serde_json::from_str::<AcpAuthMethod>(r#""agent""#).unwrap();
        assert_eq!(m, AcpAuthMethod::Agent);
    }

    #[test]
    fn additional_dir_rejects_dotdot_traversal() {
        let result = AdditionalDir::parse(std::path::PathBuf::from("/tmp/../etc"));
        assert!(
            matches!(result, Err(AdditionalDirError::Traversal(_))),
            "expected Traversal, got {result:?}"
        );
    }

    #[test]
    fn additional_dir_rejects_proc() {
        // /proc must exist on Linux CI; skip on macOS if not present.
        if !std::path::Path::new("/proc").exists() {
            return;
        }
        let result = AdditionalDir::parse(std::path::PathBuf::from("/proc/self"));
        assert!(
            matches!(result, Err(AdditionalDirError::Reserved(_))),
            "expected Reserved, got {result:?}"
        );
    }

    #[test]
    fn additional_dir_rejects_ssh() {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/root".to_owned());
        let ssh = std::path::PathBuf::from(format!("{home}/.ssh"));
        if !ssh.exists() {
            return;
        }
        let result = AdditionalDir::parse(ssh.clone());
        assert!(
            matches!(result, Err(AdditionalDirError::Reserved(_))),
            "expected Reserved for {ssh:?}, got {result:?}"
        );
    }

    #[test]
    fn additional_dir_accepts_tmp() {
        let tmp = std::env::temp_dir();
        // tempdir always exists; /tmp is not reserved.
        match AdditionalDir::parse(tmp.clone()) {
            Ok(dir) => {
                // canonicalized path stored correctly
                assert!(dir.as_path().is_absolute());
            }
            Err(AdditionalDirError::Canonicalize { .. }) => {
                // temp_dir may be a symlink that canonicalizes to something else — acceptable
            }
            Err(e) => panic!("unexpected error for {tmp:?}: {e:?}"),
        }
    }
}