pathfinder-mcp-common 0.1.2

Shared types, errors, and infrastructure for Pathfinder MCP server
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
//! Pathfinder error taxonomy.
//!
//! All tools return errors in a standardized format:
//! `{ "error": "ERROR_CODE", "message": "...", "details": {} }`
//!
//! See PRD ยง5 for the full error taxonomy.

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

/// A standardized error type for Pathfinder operations.
#[derive(Debug, thiserror::Error)]
pub enum PathfinderError {
    /// File path doesn't exist.
    #[error("file not found: {path}")]
    FileNotFound { path: PathBuf },

    /// File already exists (for `create_file`).
    #[error("file already exists: {path}")]
    FileAlreadyExists { path: PathBuf },

    /// Semantic path doesn't resolve.
    #[error("symbol not found: {semantic_path}")]
    SymbolNotFound {
        semantic_path: String,
        did_you_mean: Vec<String>,
    },

    /// Semantic path is malformed or missing required '::' separator.
    #[error("invalid semantic path: {input}")]
    InvalidSemanticPath { input: String, issue: String },

    /// Multiple matches for a semantic path.
    #[error("ambiguous symbol: {semantic_path}")]
    AmbiguousSymbol {
        semantic_path: String,
        matches: Vec<String>,
    },

    /// File changed since last read. OCC violation.
    ///
    /// `lines_changed` is a lightweight `"+N/-M"` summary (O(N) line count comparison).
    /// It helps agents decide whether to retry without a full re-read.
    #[error("version mismatch for {path}")]
    VersionMismatch {
        path: PathBuf,
        current_version_hash: String,
        /// Optional `"+N/-M"` delta between the agent's version and the current version.
        lines_changed: Option<String>,
    },

    /// Edit introduced new errors.
    #[error("validation failed: {count} new errors introduced")]
    ValidationFailed {
        count: usize,
        introduced_errors: Vec<DiagnosticError>,
    },

    /// No language server available for this file type.
    #[error("no LSP available for language: {language}")]
    NoLspAvailable { language: String },

    /// Language server crashed or returned an error.
    #[error("LSP error: {message}")]
    LspError { message: String },

    /// A generic I/O error occurred.
    #[error("I/O error: {message}")]
    IoError { message: String },

    /// LSP didn't respond within timeout.
    #[error("LSP timeout after {timeout_ms}ms")]
    LspTimeout { timeout_ms: u64 },

    /// File is in the sandbox deny-list.
    #[error("access denied: {path}")]
    AccessDenied { path: PathBuf, tier: SandboxTier },

    /// Tree-sitter couldn't parse the file.
    #[error("parse error in {path}: {reason}")]
    ParseError { path: PathBuf, reason: String },

    /// The language of the semantic path's file is not supported.
    #[error("unsupported language for target file: {path}")]
    UnsupportedLanguage { path: PathBuf },

    /// Target symbol is incompatible with the edit type.
    #[error("invalid target: {reason}")]
    InvalidTarget {
        semantic_path: String,
        reason: String,
        /// For batch edits: index of the failed edit.
        edit_index: Option<usize>,
        /// For batch edits: valid options when `edit_type` is missing/invalid.
        valid_edit_types: Option<Vec<String>>,
    },

    /// Response would exceed `max_tokens`.
    #[error("token budget exceeded: {used} / {budget}")]
    TokenBudgetExceeded { used: usize, budget: usize },

    /// `write_file` replacements: `old_text` not found in file content.
    #[error("match not found: old_text not present in file")]
    MatchNotFound { filepath: PathBuf },

    /// `write_file` replacements: `old_text` found multiple times.
    #[error("ambiguous match: old_text found {occurrences} times")]
    AmbiguousMatch {
        filepath: PathBuf,
        occurrences: usize,
    },

    /// `replace_batch` text targeting: `old_text` not found within the
    /// ยฑ25-line context window around `context_line`.
    ///
    /// The entire batch is rejected when any edit fails to resolve.
    #[error("text not found: '{old_text}' not found within ยฑ25 lines of line {context_line} in {filepath}")]
    TextNotFound {
        filepath: PathBuf,
        old_text: String,
        context_line: u32,
        /// Snippet of actual content at `context_line` (for debugging)
        actual_content: Option<String>,
        /// Closest matching substring found in the window (for agent self-correction).
        /// Present when a near-match (>60% character overlap) exists but exact match fails.
        closest_match: Option<String>,
    },

    /// Path traversal detected in `resolve_strict`.
    #[error("path traversal rejected: {path} escapes workspace root {workspace_root}")]
    PathTraversal {
        path: PathBuf,
        workspace_root: PathBuf,
    },
}

impl PathfinderError {
    /// Returns the MCP-facing error code string.
    #[must_use]
    pub fn error_code(&self) -> &'static str {
        match self {
            Self::FileNotFound { .. } => "FILE_NOT_FOUND",
            Self::FileAlreadyExists { .. } => "FILE_ALREADY_EXISTS",
            Self::SymbolNotFound { .. } => "SYMBOL_NOT_FOUND",
            Self::AmbiguousSymbol { .. } => "AMBIGUOUS_SYMBOL",
            Self::VersionMismatch { .. } => "VERSION_MISMATCH",
            Self::ValidationFailed { .. } => "VALIDATION_FAILED",
            Self::NoLspAvailable { .. } => "NO_LSP_AVAILABLE",
            Self::LspError { .. } => "LSP_ERROR",
            Self::LspTimeout { .. } => "LSP_TIMEOUT",
            Self::AccessDenied { .. } => "ACCESS_DENIED",
            Self::IoError { .. } => "INTERNAL_ERROR",
            Self::ParseError { .. } => "PARSE_ERROR",
            Self::UnsupportedLanguage { .. } => "UNSUPPORTED_LANGUAGE",
            Self::InvalidTarget { .. } => "INVALID_TARGET",
            Self::TokenBudgetExceeded { .. } => "TOKEN_BUDGET_EXCEEDED",
            Self::MatchNotFound { .. } => "MATCH_NOT_FOUND",
            Self::AmbiguousMatch { .. } => "AMBIGUOUS_MATCH",
            Self::TextNotFound { .. } => "TEXT_NOT_FOUND",
            Self::InvalidSemanticPath { .. } => "INVALID_SEMANTIC_PATH",
            Self::PathTraversal { .. } => "PATH_TRAVERSAL",
        }
    }

    /// Returns an actionable hint for the agent to self-correct without additional round-trips.
    ///
    /// `SYMBOL_NOT_FOUND` hints are dynamic and built from the `did_you_mean` suggestions.
    /// All other hints are static strings referencing specific Pathfinder tools.
    #[must_use]
    pub fn hint(&self) -> Option<String> {
        match self {
            Self::SymbolNotFound { did_you_mean, .. } => {
                if did_you_mean.is_empty() {
                    Some("Use read_source_file to see available symbols in this file.".to_owned())
                } else {
                    Some(format!(
                        "Did you mean: {}? Use read_source_file to see available symbols.",
                        did_you_mean.join(", ")
                    ))
                }
            }
            Self::InvalidTarget { valid_edit_types, .. } => {
                if valid_edit_types.is_some() {
                    Some("Set edit_type to one of: 'replace_body', 'replace_full', 'insert_before', 'insert_after', 'delete'. Or set old_text + context_line for text-based targeting.".to_owned())
                } else {
                    Some("replace_body requires a block-bodied construct. For constants, use replace_full.".to_owned())
                }
            }
            Self::VersionMismatch { .. } => Some(
                "The file was modified. Use the new hash to retry your edit if the changes \
                 do not overlap with your target."
                    .to_owned(),
            ),
            Self::AccessDenied { .. } => {
                Some("File is outside workspace sandbox. Check .pathfinderignore rules.".to_owned())
            }
            Self::UnsupportedLanguage { .. } => Some(
                "No tree-sitter grammar for this file type. Use read_file and write_file instead."
                    .to_owned(),
            ),
            Self::FileNotFound { .. } => Some(
                "Verify the file path is relative to the workspace root and the file exists."
                    .to_owned(),
            ),
            Self::ValidationFailed { .. } => Some(
                "Set ignore_validation_failures=true to write despite errors, or fix the \
                 introduced errors before retrying."
                    .to_owned(),
            ),
            Self::MatchNotFound { .. } => Some(
                "The old_text was not found in the file. Use read_file to verify the exact text \
                 before retrying."
                    .to_owned(),
            ),
            Self::AmbiguousMatch { occurrences, .. } => Some(format!(
                "old_text matched {occurrences} times. Make it more specific or use \
                 replace_batch with a semantic_path to target a single symbol."
            )),
            Self::TextNotFound { context_line, closest_match, .. } => {
                let base = format!(
                    "The old_text was not found within ยฑ25 lines of line {context_line}. \
                     Use read_source_file to verify the exact text and adjust context_line."
                );
                if let Some(candidate) = closest_match {
                    Some(format!("{base} Closest match found: '{candidate}'."))
                } else {
                    Some(base)
                }
            }
            Self::InvalidSemanticPath { input, .. } => Some(format!(
                "'{input}' is missing the file path โ€” did you mean 'crates/.../file.rs::{input}'? \
                 Semantic paths must include the file path and '::' separator (e.g., 'src/auth.ts::AuthService.login')."
            )),
            Self::PathTraversal { .. } => Some(
                "Path traversal is not allowed. Use a relative path without '..' components or absolute paths."
                    .to_owned(),
            ),
            _ => None,
        }
    }

    /// Serialize to the standard MCP error JSON format.
    #[must_use]
    pub fn to_error_response(&self) -> ErrorResponse {
        ErrorResponse {
            error: self.error_code().to_owned(),
            message: self.to_string(),
            details: self.to_details(),
            hint: self.hint(),
        }
    }

    fn to_details(&self) -> serde_json::Value {
        match self {
            Self::SymbolNotFound { did_you_mean, .. } => {
                serde_json::json!({ "did_you_mean": did_you_mean })
            }
            Self::AmbiguousSymbol { matches, .. } => {
                serde_json::json!({ "matches": matches })
            }
            Self::VersionMismatch {
                current_version_hash,
                lines_changed,
                ..
            } => {
                serde_json::json!({
                    "current_version_hash": current_version_hash,
                    "lines_changed": lines_changed,
                })
            }
            Self::ValidationFailed {
                introduced_errors, ..
            } => {
                serde_json::json!({ "introduced_errors": introduced_errors })
            }
            Self::AmbiguousMatch { occurrences, .. } => {
                serde_json::json!({ "occurrences": occurrences })
            }
            Self::AccessDenied { tier, .. } => {
                serde_json::json!({ "tier": tier })
            }
            Self::TokenBudgetExceeded { used, budget } => {
                serde_json::json!({ "used": used, "budget": budget })
            }
            Self::InvalidSemanticPath { issue, .. } => {
                serde_json::json!({ "issue": issue })
            }
            Self::InvalidTarget {
                edit_index,
                valid_edit_types,
                ..
            } => {
                let mut map = serde_json::Map::new();
                if let Some(idx) = edit_index {
                    map.insert("edit_index".to_string(), serde_json::json!(idx));
                }
                if let Some(types) = valid_edit_types {
                    map.insert("valid_edit_types".to_string(), serde_json::json!(types));
                }
                serde_json::Value::Object(map)
            }
            Self::TextNotFound {
                filepath,
                old_text,
                context_line,
                actual_content,
                closest_match,
            } => {
                let mut map = serde_json::Map::new();
                map.insert("filepath".to_string(), serde_json::json!(filepath));
                map.insert("old_text".to_string(), serde_json::json!(old_text));
                map.insert("context_line".to_string(), serde_json::json!(context_line));
                if let Some(content) = actual_content {
                    map.insert("actual_content".to_string(), serde_json::json!(content));
                }
                if let Some(candidate) = closest_match {
                    map.insert("closest_match".to_string(), serde_json::json!(candidate));
                }
                serde_json::Value::Object(map)
            }
            Self::PathTraversal {
                path,
                workspace_root,
            } => {
                serde_json::json!({ "path": path, "workspace_root": workspace_root })
            }
            _ => serde_json::Value::Object(serde_json::Map::new()),
        }
    }
}

/// Standard MCP error response format.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorResponse {
    /// Error code identifying the type of error.
    pub error: String,
    /// Human-readable message describing the error.
    pub message: String,
    /// Additional details about the error in JSON format.
    pub details: serde_json::Value,
    /// Actionable recovery hint for the agent. Present on most error variants.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hint: Option<String>,
}

/// Compute a lightweight `"+N/-M"` lines-changed summary.
///
/// Compares line counts between `old_content` and `new_content` in O(N) time
/// (no diff algorithm โ€” just counts newlines in each string).
///
/// Used by `VERSION_MISMATCH` errors so agents can gauge how much the file
/// changed and decide whether to retry without a full re-read.
#[must_use]
pub fn compute_lines_changed(old_content: &str, new_content: &str) -> String {
    let old_lines = old_content.lines().count();
    let new_lines = new_content.lines().count();
    let added = new_lines.saturating_sub(old_lines);
    let removed = old_lines.saturating_sub(new_lines);
    format!("+{added}/-{removed}")
}

/// A diagnostic error reported by the LSP.
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
pub struct DiagnosticError {
    /// The severity level of the diagnostic error.
    pub severity: u8,
    /// The diagnostic error code.
    pub code: String,
    /// The error message describing the diagnostic.
    pub message: String,
    /// The file path related to the diagnostic.
    pub file: String,
}

/// Sandbox tier that denied access.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum SandboxTier {
    /// Always excluded, not configurable.
    HardcodedDeny,
    /// Excluded by default, overridable in config.
    DefaultDeny,
    /// User-defined via `.pathfinderignore`.
    UserDefined,
}

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

    #[test]
    fn test_error_code_mapping() {
        let err = PathfinderError::FileNotFound {
            path: "src/main.rs".into(),
        };
        assert_eq!(err.error_code(), "FILE_NOT_FOUND");

        let err = PathfinderError::SymbolNotFound {
            semantic_path: "src/auth.ts::AuthService.login".into(),
            did_you_mean: vec!["AuthService.logout".into()],
        };
        assert_eq!(err.error_code(), "SYMBOL_NOT_FOUND");
    }

    #[test]
    fn test_error_response_serialization() {
        let err = PathfinderError::VersionMismatch {
            path: "src/main.rs".into(),
            current_version_hash: "sha256:abc123".into(),
            lines_changed: Some("+5/-2".into()),
        };
        let response = err.to_error_response();

        assert_eq!(response.error, "VERSION_MISMATCH");
        assert_eq!(response.details["current_version_hash"], "sha256:abc123");
        assert_eq!(response.details["lines_changed"], "+5/-2");
        assert!(
            response.hint.is_some(),
            "VERSION_MISMATCH should carry a hint"
        );

        // Verify it round-trips through JSON
        let json = serde_json::to_string(&response).expect("serialization should succeed");
        let deserialized: ErrorResponse =
            serde_json::from_str(&json).expect("deserialization should succeed");
        assert_eq!(deserialized.error, "VERSION_MISMATCH");
    }

    #[test]
    fn test_all_error_codes_are_screaming_snake_case() {
        let errors: Vec<PathfinderError> = vec![
            PathfinderError::FileNotFound { path: "a".into() },
            PathfinderError::FileAlreadyExists { path: "a".into() },
            PathfinderError::SymbolNotFound {
                semantic_path: "a".into(),
                did_you_mean: vec![],
            },
            PathfinderError::AmbiguousSymbol {
                semantic_path: "a".into(),
                matches: vec![],
            },
            PathfinderError::VersionMismatch {
                path: "a".into(),
                current_version_hash: "x".into(),
                lines_changed: None,
            },
            PathfinderError::ValidationFailed {
                count: 0,
                introduced_errors: vec![],
            },
            PathfinderError::NoLspAvailable {
                language: "a".into(),
            },
            PathfinderError::LspError {
                message: "a".into(),
            },
            PathfinderError::LspTimeout { timeout_ms: 0 },
            PathfinderError::AccessDenied {
                path: "a".into(),
                tier: SandboxTier::HardcodedDeny,
            },
            PathfinderError::ParseError {
                path: "a".into(),
                reason: "a".into(),
            },
            PathfinderError::UnsupportedLanguage { path: "a".into() },
            PathfinderError::InvalidTarget {
                semantic_path: "a".into(),
                reason: "a".into(),
                edit_index: None,
                valid_edit_types: None,
            },
            PathfinderError::TokenBudgetExceeded { used: 0, budget: 0 },
            PathfinderError::MatchNotFound {
                filepath: "a".into(),
            },
            PathfinderError::AmbiguousMatch {
                filepath: "a".into(),
                occurrences: 0,
            },
            PathfinderError::IoError {
                message: "disk full".into(),
            },
            PathfinderError::TextNotFound {
                filepath: "a.vue".into(),
                old_text: "<button>Check</button>".into(),
                context_line: 42,
                actual_content: None,
                closest_match: None,
            },
            PathfinderError::InvalidSemanticPath {
                input: "send".into(),
                issue: "missing ::".into(),
            },
        ];

        for err in &errors {
            let code = err.error_code();
            assert!(
                code.chars().all(|c| c.is_ascii_uppercase() || c == '_'),
                "Error code '{code}' is not SCREAMING_SNAKE_CASE"
            );
        }
    }

    #[test]
    fn test_symbol_not_found_details_include_did_you_mean() {
        let err = PathfinderError::SymbolNotFound {
            semantic_path: "src/auth.ts::startServer".into(),
            did_you_mean: vec!["stopServer".into(), "startService".into()],
        };
        let response = err.to_error_response();
        let suggestions = response.details["did_you_mean"]
            .as_array()
            .expect("did_you_mean should be an array");
        assert_eq!(suggestions.len(), 2);
    }

    // โ”€โ”€ E7.2: compute_lines_changed โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    #[test]
    fn test_compute_lines_changed_lines_added() {
        // old: 2 lines, new: 5 lines โ†’ +3/-0
        let old = "line1\nline2";
        let new = "line1\nline2\nline3\nline4\nline5";
        assert_eq!(compute_lines_changed(old, new), "+3/-0");
    }

    #[test]
    fn test_compute_lines_changed_lines_removed() {
        // old: 4 lines, new: 2 lines โ†’ +0/-2
        let old = "a\nb\nc\nd";
        let new = "a\nb";
        assert_eq!(compute_lines_changed(old, new), "+0/-2");
    }

    #[test]
    fn test_compute_lines_changed_mixed() {
        // old: 3 lines, new: 4 lines โ†’ +1/-0
        let old = "a\nb\nc";
        let new = "a\nb\nc\nd";
        assert_eq!(compute_lines_changed(old, new), "+1/-0");
    }

    #[test]
    fn test_compute_lines_changed_identical() {
        let content = "same\ncontent\nhere";
        assert_eq!(compute_lines_changed(content, content), "+0/-0");
    }

    #[test]
    fn test_compute_lines_changed_empty_to_nonempty() {
        assert_eq!(compute_lines_changed("", "a\nb\nc"), "+3/-0");
    }

    // โ”€โ”€ E7.3: hint() method โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

    #[test]
    fn test_version_mismatch_hint_is_present() {
        let err = PathfinderError::VersionMismatch {
            path: "src/lib.rs".into(),
            current_version_hash: "sha256:new".into(),
            lines_changed: Some("+2/-1".into()),
        };
        let hint = err.hint().expect("VERSION_MISMATCH should have a hint");
        assert!(
            hint.contains("new hash"),
            "hint should mention re-reading: {hint}"
        );
    }

    #[test]
    fn test_symbol_not_found_hint_with_suggestions() {
        let err = PathfinderError::SymbolNotFound {
            semantic_path: "src/auth.ts::login".into(),
            did_you_mean: vec!["logout".into(), "logIn".into()],
        };
        let hint = err.hint().expect("should have hint");
        assert!(
            hint.contains("logout"),
            "hint should include suggestions: {hint}"
        );
        assert!(
            hint.contains("logIn"),
            "hint should include all suggestions: {hint}"
        );
    }

    #[test]
    fn test_symbol_not_found_hint_without_suggestions() {
        let err = PathfinderError::SymbolNotFound {
            semantic_path: "src/auth.ts::unknown".into(),
            did_you_mean: vec![],
        };
        let hint = err
            .hint()
            .expect("should have hint even without suggestions");
        assert!(
            hint.contains("read_source_file"),
            "hint should point to read_source_file: {hint}"
        );
    }

    #[test]
    fn test_access_denied_hint_mentions_sandbox() {
        let err = PathfinderError::AccessDenied {
            path: ".env".into(),
            tier: SandboxTier::HardcodedDeny,
        };
        let hint = err.hint().expect("ACCESS_DENIED should have a hint");
        assert!(
            hint.contains("sandbox"),
            "hint should mention sandbox: {hint}"
        );
    }

    #[test]
    fn test_unsupported_language_hint_mentions_write_file() {
        let err = PathfinderError::UnsupportedLanguage {
            path: "data.xyz".into(),
        };
        let hint = err.hint().expect("UNSUPPORTED_LANGUAGE should have a hint");
        assert!(
            hint.contains("write_file"),
            "hint should mention write_file: {hint}"
        );
    }

    #[test]
    fn test_validation_failed_hint_mentions_ignore_flag() {
        let err = PathfinderError::ValidationFailed {
            count: 2,
            introduced_errors: vec![],
        };
        let hint = err.hint().expect("VALIDATION_FAILED should have a hint");
        assert!(
            hint.contains("ignore_validation_failures"),
            "hint should mention the flag: {hint}"
        );
    }

    #[test]
    fn test_match_not_found_hint_mentions_read_file() {
        let err = PathfinderError::MatchNotFound {
            filepath: "config.yaml".into(),
        };
        let hint = err.hint().expect("MATCH_NOT_FOUND should have a hint");
        assert!(
            hint.contains("read_file"),
            "hint should mention read_file: {hint}"
        );
    }

    #[test]
    fn test_hint_serialized_in_error_response() {
        let err = PathfinderError::InvalidTarget {
            semantic_path: "src/lib.rs::CONST".into(),
            reason: "not a block construct".into(),
            edit_index: None,
            valid_edit_types: None,
        };
        let resp = err.to_error_response();
        assert!(
            resp.hint.is_some(),
            "hint must be serialized in ErrorResponse"
        );
        let json = serde_json::to_value(&resp).expect("serialize");
        assert!(
            json.get("hint").is_some(),
            "hint must appear in JSON output"
        );
    }

    #[test]
    fn test_text_not_found_hint_mentions_context_line() {
        let err = PathfinderError::TextNotFound {
            filepath: "src/component.vue".into(),
            old_text: "<button>Check</button>".to_owned(),
            context_line: 42,
            actual_content: None,
            closest_match: None,
        };
        assert_eq!(err.error_code(), "TEXT_NOT_FOUND");
        let hint = err.hint().expect("TEXT_NOT_FOUND should have a hint");
        assert!(
            hint.contains("42"),
            "hint should mention context_line: {hint}"
        );
        assert!(
            hint.contains("read_source_file"),
            "hint should reference read_source_file: {hint}"
        );
    }

    #[test]
    fn test_text_not_found_hint_with_closest_match() {
        let err = PathfinderError::TextNotFound {
            filepath: "src/auth.ts".into(),
            old_text: "const x = 1;".to_owned(),
            context_line: 10,
            actual_content: None,
            closest_match: Some("const x = 2;".to_owned()),
        };
        let hint = err
            .hint()
            .expect("TEXT_NOT_FOUND with closest_match should have a hint");
        assert!(
            hint.contains("const x = 2;"),
            "hint should include the closest match candidate: {hint}"
        );
        let response = err.to_error_response();
        assert_eq!(response.details["closest_match"], "const x = 2;");
    }

    #[test]
    fn test_path_traversal_error() {
        let err = PathfinderError::PathTraversal {
            path: "../../etc/passwd".into(),
            workspace_root: "/workspace".into(),
        };

        assert_eq!(err.error_code(), "PATH_TRAVERSAL");
        let hint = err.hint().expect("PATH_TRAVERSAL should have a hint");
        assert!(
            hint.contains("not allowed"),
            "hint should explain traversal is not allowed: {hint}"
        );

        let response = err.to_error_response();
        assert_eq!(response.error, "PATH_TRAVERSAL");
        assert_eq!(response.details["path"], "../../etc/passwd");
        assert_eq!(response.details["workspace_root"], "/workspace");
    }
}