# Documentation Accuracy Enforcement Specification

**Status**: Draft
**Type**: Specification
**Created**: 2025-10-18
**Priority**: P0 (Critical - Documentation Quality)
**Complexity**: High
**Target Files**: README.md, CLAUDE.md, GEMINI.md, AGENT.md

---

## Executive Summary

This specification defines a comprehensive documentation accuracy enforcement system that prevents hallucinations, broken references, and inconsistencies in AI agent instruction files (README.md, CLAUDE.md, GEMINI.md, AGENT.md). The system leverages PMAT's existing `context` and `validate-docs` commands, combined with peer-reviewed hallucination detection techniques and codebase cross-validation to ensure documentation remains truthful, accurate, and up-to-date.

## 1. Problem Statement

### 1.1 Current State
- AI agent instruction files (CLAUDE.md, GEMINI.md, AGENT.md, README.md) can contain:
  - **Hallucinated claims** about features that don't exist in the codebase
  - **Broken references** to non-existent files, functions, or modules
  - **Outdated information** about APIs, commands, or capabilities
  - **404 errors** in external links and documentation references
  - **Inconsistencies** between documentation and actual implementation
- No automated validation that documentation claims match codebase reality
- No detection of "plausible but false" statements about code capabilities
- Manual review is error-prone and doesn't scale

### 1.2 Desired State
- **Zero Hallucinations**: All claims about code capabilities verified against actual codebase
- **No Broken References**: All file paths, function names, module references validated
- **404 Detection**: All HTTP/HTTPS links verified and working
- **Cross-Validation**: Documentation claims automatically checked against `pmat context` output
- **Automated Enforcement**: Pre-commit hooks and CI/CD integration prevent bad documentation
- **Scientific Foundation**: Implementation based on peer-reviewed hallucination detection research

## 2. Research Foundation

### 2.1 Peer-Reviewed Hallucination Detection

Based on recent peer-reviewed research (2024-2025):

#### **Semantic Entropy Detection** (Nature, 2024)
- **Paper**: "Detecting hallucinations in large language models using semantic entropy" (Farquhar et al., Nature, June 2024)
- **Method**: Entropy-based uncertainty estimators detect confabulations (arbitrary incorrect generations)
- **Application**: Measure semantic similarity between documentation claims and codebase facts
- **Implementation**: Calculate entropy across multiple paraphrases of documentation statements against verified code facts

#### **Internal Representation Analysis** (IJCAI, 2025)
- **Method**: MIND framework leverages LLM internal representations for hallucination detection
- **Method**: EigenScore explores semantic information within internal representations
- **Application**: Analyze semantic consistency between documentation text and AST-derived code context
- **Implementation**: Use embedding similarity to detect semantically inconsistent claims

#### **Unified Detection Framework** (Complex & Intelligent Systems, 2025)
- **Components**:
  1. **Output Parser**: Extract factual claims from documentation
  2. **Reference Parser**: Extract ground truth from codebase via `pmat context`
  3. **Fact Verifier**: Cross-validate claims against ground truth
  4. **Mitigator**: Flag or auto-correct inconsistencies
- **Application**: End-to-end documentation validation pipeline

### 2.2 Documentation Quality Metrics

From software engineering research:

- **Code-Documentation Coherence**: Measure alignment between code behavior and documentation descriptions
- **Cross-Reference Validation**: Verify all references to code entities exist
- **Temporal Consistency**: Detect outdated claims via git history analysis
- **Coverage Metrics**: Ensure critical features are documented

## 3. Architecture

### 3.1 System Components

```rust
/// Main documentation validator orchestrating all checks
pub struct DocAccuracyValidator {
    hallucination_detector: HallucinationDetector,
    link_validator: LinkValidator,
    context_cross_validator: ContextCrossValidator,
    config: ValidationConfig,
}

/// Configuration for documentation validation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationConfig {
    /// Target documentation files
    pub target_files: Vec<PathBuf>,

    /// Deep context file generated by pmat context
    pub deep_context_path: PathBuf,

    /// Enable hallucination detection
    pub check_hallucinations: bool,

    /// Enable broken link detection
    pub check_links: bool,

    /// Enable cross-validation against codebase
    pub check_code_references: bool,

    /// Semantic similarity threshold (0.0 - 1.0)
    pub similarity_threshold: f32,

    /// Fail on violations
    pub fail_on_error: bool,
}

/// Detects hallucinated claims in documentation
pub struct HallucinationDetector {
    /// AST facts extracted from codebase
    code_facts: CodeFactDatabase,

    /// Semantic similarity engine
    similarity_engine: SemanticSimilarity,

    /// Claim extractor
    claim_extractor: ClaimExtractor,
}

/// Validates links and references
pub struct LinkValidator {
    /// HTTP client for external links
    http_client: HttpClient,

    /// File system validator for internal references
    fs_validator: FileSystemValidator,
}

/// Cross-validates against pmat context output
pub struct ContextCrossValidator {
    /// Deep context data (from pmat context --output deep_context.md)
    deep_context: DeepContextData,

    /// AST analyzer
    ast_analyzer: AstAnalyzer,
}

/// Represents a factual claim extracted from documentation
#[derive(Debug, Clone)]
pub struct Claim {
    /// Source file
    pub source_file: PathBuf,

    /// Line number
    pub line_number: usize,

    /// The claim text
    pub text: String,

    /// Claim type
    pub claim_type: ClaimType,

    /// Extracted entities (functions, files, modules)
    pub entities: Vec<Entity>,
}

/// Type of claim
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ClaimType {
    /// Claims about code capabilities ("PMAT can analyze...")
    Capability,

    /// Claims about code structure ("File X contains...")
    Structure,

    /// Claims about APIs ("Function foo() accepts...")
    Api,

    /// Claims about commands ("Run pmat xyz...")
    Command,

    /// External reference (link, paper, etc.)
    ExternalRef,
}

/// Validation result
#[derive(Debug, Clone)]
pub struct ValidationResult {
    pub claim: Claim,
    pub status: ValidationStatus,
    pub evidence: Option<Evidence>,
    pub error_message: Option<String>,
    pub confidence: f32,
}

/// Validation status
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationStatus {
    /// Claim verified against codebase
    Verified,

    /// Claim could not be verified (potential hallucination)
    Unverified,

    /// Claim contradicts codebase (confirmed hallucination)
    Contradiction,

    /// Reference not found (404, missing file)
    NotFound,

    /// Claim is outdated
    Outdated,

    /// Insufficient evidence to validate
    Inconclusive,
}

/// Evidence supporting or contradicting a claim
#[derive(Debug, Clone)]
pub struct Evidence {
    /// Source of evidence (file, line, AST node)
    pub source: EvidenceSource,

    /// Semantic similarity score (0.0 - 1.0)
    pub similarity: f32,

    /// Supporting text/code
    pub content: String,
}

#[derive(Debug, Clone)]
pub enum EvidenceSource {
    /// From deep context analysis
    DeepContext { file: PathBuf, line: usize },

    /// From AST analysis
    Ast { node_type: String, path: String },

    /// From file system
    FileSystem { path: PathBuf },

    /// From HTTP validation
    Http { url: String, status_code: u16 },
}
```

### 3.2 Integration with Existing PMAT Commands

#### **Step 1: Generate Deep Context**
```bash
pmat context --output deep_context.md --format llm-optimized
```

This produces a comprehensive AST-based analysis containing:
- All functions, classes, modules
- File structure
- Dependencies
- Code metrics
- Language-specific features

#### **Step 2: Validate Documentation**
```bash
pmat validate-readme \
    --deep-context deep_context.md \
    --targets README.md CLAUDE.md GEMINI.md AGENT.md \
    --check-hallucinations \
    --check-links \
    --check-code-refs \
    --fail-on-error
```

### 3.3 Hallucination Detection Algorithm

Based on semantic entropy and cross-validation:

```rust
impl HallucinationDetector {
    /// Detect potential hallucinations in documentation claims
    ///
    /// # Algorithm
    ///
    /// 1. Extract factual claims from documentation
    /// 2. Parse entities (functions, files, modules) from claims
    /// 3. Query code facts database for ground truth
    /// 4. Calculate semantic similarity between claim and facts
    /// 5. Apply confidence threshold
    /// 6. Return validation results
    ///
    /// # Examples
    ///
    /// ```rust
    /// let detector = HallucinationDetector::new(code_facts);
    /// let claim = Claim {
    ///     text: "PMAT can analyze Ruby code complexity".to_string(),
    ///     claim_type: ClaimType::Capability,
    ///     entities: vec![Entity::Language("Ruby")],
    ///     // ...
    /// };
    ///
    /// let result = detector.validate_claim(&claim)?;
    /// assert_eq!(result.status, ValidationStatus::Verified);
    /// assert!(result.confidence > 0.9);
    /// ```
    pub fn validate_claim(&self, claim: &Claim) -> Result<ValidationResult> {
        // 1. Extract entities from claim
        let entities = self.claim_extractor.extract_entities(&claim.text);

        // 2. Query code facts for matching entities
        let facts = self.code_facts.query_entities(&entities)?;

        // 3. If no facts found, claim is potentially hallucinated
        if facts.is_empty() {
            return Ok(ValidationResult {
                claim: claim.clone(),
                status: ValidationStatus::Unverified,
                evidence: None,
                error_message: Some(format!(
                    "No evidence found in codebase for claim: {}",
                    claim.text
                )),
                confidence: 0.0,
            });
        }

        // 4. Calculate semantic similarity between claim and facts
        let similarities: Vec<f32> = facts
            .iter()
            .map(|fact| self.similarity_engine.compare(&claim.text, &fact.description))
            .collect();

        // 5. Compute semantic entropy (variance in similarities)
        let max_similarity = similarities.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
        let avg_similarity = similarities.iter().sum::<f32>() / similarities.len() as f32;
        let entropy = self.compute_entropy(&similarities);

        // 6. Low entropy + high similarity = verified
        // High entropy or low similarity = unverified/contradiction
        let status = if max_similarity > self.config.similarity_threshold && entropy < 0.5 {
            ValidationStatus::Verified
        } else if max_similarity < 0.3 {
            ValidationStatus::Contradiction
        } else {
            ValidationStatus::Inconclusive
        };

        // 7. Find best supporting evidence
        let best_fact_idx = similarities
            .iter()
            .enumerate()
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())
            .map(|(idx, _)| idx)
            .unwrap();

        Ok(ValidationResult {
            claim: claim.clone(),
            status,
            evidence: Some(Evidence {
                source: EvidenceSource::DeepContext {
                    file: facts[best_fact_idx].source_file.clone(),
                    line: facts[best_fact_idx].line_number,
                },
                similarity: max_similarity,
                content: facts[best_fact_idx].description.clone(),
            }),
            error_message: None,
            confidence: max_similarity,
        })
    }

    /// Compute semantic entropy from similarity scores
    ///
    /// Based on Farquhar et al. (Nature, 2024)
    fn compute_entropy(&self, similarities: &[f32]) -> f32 {
        if similarities.is_empty() {
            return 1.0;
        }

        // Normalize similarities to probabilities
        let sum: f32 = similarities.iter().sum();
        let probs: Vec<f32> = similarities.iter().map(|s| s / sum).collect();

        // Calculate Shannon entropy
        let entropy: f32 = probs
            .iter()
            .filter(|&&p| p > 0.0)
            .map(|&p| -p * p.log2())
            .sum();

        // Normalize to [0, 1]
        entropy / (similarities.len() as f32).log2()
    }
}
```

### 3.4 Claim Extraction

```rust
impl ClaimExtractor {
    /// Extract factual claims from documentation
    ///
    /// Patterns detected:
    /// - "PMAT can X" -> Capability claim
    /// - "Run pmat X" -> Command claim
    /// - "File/Module X contains Y" -> Structure claim
    /// - "Function X(Y) -> Z" -> API claim
    /// - "See [link](url)" -> External reference
    ///
    /// # Examples
    ///
    /// ```rust
    /// let extractor = ClaimExtractor::new();
    /// let doc = "PMAT can analyze TypeScript files. Run `pmat analyze complexity`.";
    /// let claims = extractor.extract(doc, PathBuf::from("README.md"))?;
    ///
    /// assert_eq!(claims.len(), 2);
    /// assert_eq!(claims[0].claim_type, ClaimType::Capability);
    /// assert_eq!(claims[1].claim_type, ClaimType::Command);
    /// ```
    pub fn extract(&self, content: &str, source_file: PathBuf) -> Result<Vec<Claim>> {
        let mut claims = Vec::new();

        for (line_num, line) in content.lines().enumerate() {
            // Capability claims: "PMAT can X", "supports X", "analyzes X"
            if let Some(cap) = self.extract_capability_claim(line, line_num, &source_file) {
                claims.push(cap);
            }

            // Command claims: "Run pmat X", "`pmat X`", "Execute pmat X"
            if let Some(cmd) = self.extract_command_claim(line, line_num, &source_file) {
                claims.push(cmd);
            }

            // Structure claims: "File X contains", "Module X provides"
            if let Some(struct_claim) = self.extract_structure_claim(line, line_num, &source_file) {
                claims.push(struct_claim);
            }

            // API claims: "Function X(args)", "Method Y returns Z"
            if let Some(api) = self.extract_api_claim(line, line_num, &source_file) {
                claims.push(api);
            }

            // External references: Markdown links, URLs
            if let Some(ext_ref) = self.extract_external_ref(line, line_num, &source_file) {
                claims.push(ext_ref);
            }
        }

        Ok(claims)
    }

    fn extract_capability_claim(&self, line: &str, line_num: usize, source_file: &PathBuf) -> Option<Claim> {
        // Regex patterns for capability claims
        let patterns = [
            r"PMAT can ([^.]+)",
            r"supports? ([^.]+)",
            r"analyzes? ([^.]+)",
            r"provides? ([^.]+)",
            r"includes? ([^.]+) (support|analysis|feature)",
        ];

        for pattern in &patterns {
            if let Ok(re) = regex::Regex::new(pattern) {
                if let Some(cap) = re.captures(line) {
                    let capability = cap.get(1)?.as_str();
                    let entities = self.extract_entities_from_text(capability);

                    return Some(Claim {
                        source_file: source_file.clone(),
                        line_number: line_num + 1,
                        text: line.to_string(),
                        claim_type: ClaimType::Capability,
                        entities,
                    });
                }
            }
        }

        None
    }

    fn extract_entities_from_text(&self, text: &str) -> Vec<Entity> {
        let mut entities = Vec::new();

        // Language names
        let languages = ["Python", "Rust", "TypeScript", "JavaScript", "Go", "Java", "C++", "C", "Ruby", "PHP", "Swift", "Kotlin", "C#", "Bash"];
        for lang in &languages {
            if text.contains(lang) {
                entities.push(Entity::Language(lang.to_string()));
            }
        }

        // File patterns
        if let Ok(re) = regex::Regex::new(r"([a-zA-Z0-9_/.-]+\.(rs|ts|js|py|go|java|rb|php|swift|kt|cs|sh))") {
            for cap in re.captures_iter(text) {
                entities.push(Entity::File(PathBuf::from(cap.get(1).unwrap().as_str())));
            }
        }

        // Function/method names (simple heuristic)
        if let Ok(re) = regex::Regex::new(r"(\w+)\s*\(") {
            for cap in re.captures_iter(text) {
                entities.push(Entity::Function(cap.get(1).unwrap().as_str().to_string()));
            }
        }

        entities
    }
}

/// Entities extracted from claims
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Entity {
    /// Programming language
    Language(String),

    /// File path
    File(PathBuf),

    /// Function/method name
    Function(String),

    /// Module/class name
    Module(String),

    /// CLI command
    Command(String),

    /// External URL
    Url(String),
}
```

### 3.5 Code Facts Database

```rust
/// Database of verified facts extracted from codebase
pub struct CodeFactDatabase {
    /// Facts indexed by entity type
    facts: HashMap<Entity, Vec<CodeFact>>,

    /// AST analyzer
    ast_analyzer: AstAnalyzer,
}

/// A verified fact about the codebase
#[derive(Debug, Clone)]
pub struct CodeFact {
    /// Entity this fact describes
    pub entity: Entity,

    /// Natural language description
    pub description: String,

    /// Source location
    pub source_file: PathBuf,
    pub line_number: usize,

    /// AST metadata
    pub ast_metadata: Option<AstMetadata>,
}

impl CodeFactDatabase {
    /// Build fact database from deep context output
    ///
    /// # Examples
    ///
    /// ```rust
    /// let deep_context = std::fs::read_to_string("deep_context.md")?;
    /// let db = CodeFactDatabase::from_deep_context(&deep_context)?;
    ///
    /// // Query for Ruby language support
    /// let facts = db.query_entities(&[Entity::Language("Ruby".to_string())])?;
    /// assert!(!facts.is_empty());
    /// ```
    pub fn from_deep_context(content: &str) -> Result<Self> {
        let mut facts: HashMap<Entity, Vec<CodeFact>> = HashMap::new();

        // Parse deep context markdown
        // Extract function declarations, file listings, language support
        let parser = DeepContextParser::new();
        let parsed = parser.parse(content)?;

        // Index all entities
        for function in &parsed.functions {
            let entity = Entity::Function(function.name.clone());
            facts.entry(entity.clone()).or_insert_with(Vec::new).push(CodeFact {
                entity,
                description: function.signature.clone(),
                source_file: function.file.clone(),
                line_number: function.line,
                ast_metadata: Some(function.ast_metadata.clone()),
            });
        }

        for file in &parsed.files {
            let entity = Entity::File(file.path.clone());
            facts.entry(entity.clone()).or_insert_with(Vec::new).push(CodeFact {
                entity,
                description: format!("File: {}", file.path.display()),
                source_file: file.path.clone(),
                line_number: 1,
                ast_metadata: None,
            });
        }

        // Extract language support from analyzer metadata
        for lang in &parsed.supported_languages {
            let entity = Entity::Language(lang.clone());
            facts.entry(entity.clone()).or_insert_with(Vec::new).push(CodeFact {
                entity,
                description: format!("Language support: {}", lang),
                source_file: PathBuf::from("server/src/cli/language_analyzer.rs"),
                line_number: 1,
                ast_metadata: None,
            });
        }

        Ok(Self {
            facts,
            ast_analyzer: AstAnalyzer::new(),
        })
    }

    /// Query facts by entities
    pub fn query_entities(&self, entities: &[Entity]) -> Result<Vec<CodeFact>> {
        let mut results = Vec::new();

        for entity in entities {
            if let Some(facts) = self.facts.get(entity) {
                results.extend(facts.clone());
            }
        }

        Ok(results)
    }
}
```

### 3.6 Context Cross-Validator

```rust
impl ContextCrossValidator {
    /// Cross-validate documentation claims against deep context
    ///
    /// # Examples
    ///
    /// ```rust
    /// let deep_context = DeepContextData::load("deep_context.md")?;
    /// let validator = ContextCrossValidator::new(deep_context);
    ///
    /// let claim = Claim {
    ///     text: "server/src/cli/mod.rs contains language detection".to_string(),
    ///     claim_type: ClaimType::Structure,
    ///     entities: vec![
    ///         Entity::File(PathBuf::from("server/src/cli/mod.rs")),
    ///         Entity::Function("language detection".to_string()),
    ///     ],
    ///     // ...
    /// };
    ///
    /// let result = validator.validate(&claim)?;
    /// assert_eq!(result.status, ValidationStatus::Verified);
    /// ```
    pub fn validate(&self, claim: &Claim) -> Result<ValidationResult> {
        match claim.claim_type {
            ClaimType::Structure => self.validate_structure_claim(claim),
            ClaimType::Api => self.validate_api_claim(claim),
            ClaimType::Capability => self.validate_capability_claim(claim),
            ClaimType::Command => self.validate_command_claim(claim),
            ClaimType::ExternalRef => self.validate_external_ref(claim),
        }
    }

    fn validate_structure_claim(&self, claim: &Claim) -> Result<ValidationResult> {
        // Extract file entity
        let file_entity = claim.entities.iter()
            .find(|e| matches!(e, Entity::File(_)))
            .ok_or_else(|| anyhow!("No file entity in structure claim"))?;

        // Check if file exists in deep context
        let file_path = match file_entity {
            Entity::File(path) => path,
            _ => unreachable!(),
        };

        let exists = self.deep_context.files.iter().any(|f| &f.path == file_path);

        if !exists {
            return Ok(ValidationResult {
                claim: claim.clone(),
                status: ValidationStatus::NotFound,
                evidence: None,
                error_message: Some(format!("File not found in codebase: {}", file_path.display())),
                confidence: 0.0,
            });
        }

        // Extract function/module entity
        let func_entities: Vec<&Entity> = claim.entities.iter()
            .filter(|e| matches!(e, Entity::Function(_) | Entity::Module(_)))
            .collect();

        if func_entities.is_empty() {
            // Just file existence check
            return Ok(ValidationResult {
                claim: claim.clone(),
                status: ValidationStatus::Verified,
                evidence: Some(Evidence {
                    source: EvidenceSource::FileSystem { path: file_path.clone() },
                    similarity: 1.0,
                    content: format!("File exists: {}", file_path.display()),
                }),
                error_message: None,
                confidence: 1.0,
            });
        }

        // Check if file contains mentioned functions
        let file_data = self.deep_context.files.iter()
            .find(|f| &f.path == file_path)
            .unwrap();

        for func_entity in &func_entities {
            let func_name = match func_entity {
                Entity::Function(name) => name,
                Entity::Module(name) => name,
                _ => continue,
            };

            let contains_func = file_data.functions.iter()
                .any(|f| f.name.contains(func_name) || func_name.contains(&f.name));

            if !contains_func {
                return Ok(ValidationResult {
                    claim: claim.clone(),
                    status: ValidationStatus::Contradiction,
                    evidence: Some(Evidence {
                        source: EvidenceSource::Ast {
                            node_type: "function_search".to_string(),
                            path: file_path.display().to_string(),
                        },
                        similarity: 0.0,
                        content: format!("Function '{}' not found in {}", func_name, file_path.display()),
                    }),
                    error_message: Some(format!("Function '{}' not found in file", func_name)),
                    confidence: 0.0,
                });
            }
        }

        Ok(ValidationResult {
            claim: claim.clone(),
            status: ValidationStatus::Verified,
            evidence: Some(Evidence {
                source: EvidenceSource::Ast {
                    node_type: "function_found".to_string(),
                    path: file_path.display().to_string(),
                },
                similarity: 1.0,
                content: format!("Functions found in {}", file_path.display()),
            }),
            error_message: None,
            confidence: 1.0,
        })
    }

    fn validate_command_claim(&self, claim: &Claim) -> Result<ValidationResult> {
        // Extract command entity
        let cmd_entity = claim.entities.iter()
            .find(|e| matches!(e, Entity::Command(_)))
            .ok_or_else(|| anyhow!("No command entity in command claim"))?;

        let cmd_text = match cmd_entity {
            Entity::Command(text) => text,
            _ => unreachable!(),
        };

        // Parse command (e.g., "pmat analyze complexity")
        let parts: Vec<&str> = cmd_text.split_whitespace().collect();
        if parts.is_empty() || parts[0] != "pmat" {
            return Ok(ValidationResult {
                claim: claim.clone(),
                status: ValidationStatus::Inconclusive,
                evidence: None,
                error_message: Some("Not a PMAT command".to_string()),
                confidence: 0.0,
            });
        }

        // Check if command exists in deep context command list
        let command = parts[1..].join(" ");
        let exists = self.deep_context.commands.iter()
            .any(|c| c.name == command || command.starts_with(&c.name));

        if !exists {
            return Ok(ValidationResult {
                claim: claim.clone(),
                status: ValidationStatus::Contradiction,
                evidence: None,
                error_message: Some(format!("Command not found: pmat {}", command)),
                confidence: 0.0,
            });
        }

        Ok(ValidationResult {
            claim: claim.clone(),
            status: ValidationStatus::Verified,
            evidence: Some(Evidence {
                source: EvidenceSource::DeepContext {
                    file: PathBuf::from("CLI"),
                    line: 0,
                },
                similarity: 1.0,
                content: format!("Command verified: pmat {}", command),
            }),
            error_message: None,
            confidence: 1.0,
        })
    }
}
```

## 4. CLI Integration

### 4.1 New Command: `pmat validate-readme`

```rust
/// Validate README/CLAUDE/GEMINI/AGENT documentation accuracy
#[derive(Parser, Debug)]
pub struct ValidateReadmeCmd {
    /// Documentation files to validate
    #[arg(short, long, required = true)]
    pub targets: Vec<PathBuf>,

    /// Deep context file (from pmat context --output)
    #[arg(short, long, default_value = "deep_context.md")]
    pub deep_context: PathBuf,

    /// Enable hallucination detection
    #[arg(long, default_value = "true")]
    pub check_hallucinations: bool,

    /// Enable broken link detection
    #[arg(long, default_value = "true")]
    pub check_links: bool,

    /// Enable code reference validation
    #[arg(long, default_value = "true")]
    pub check_code_refs: bool,

    /// Semantic similarity threshold (0.0 - 1.0)
    #[arg(long, default_value = "0.7")]
    pub similarity_threshold: f32,

    /// Fail build on violations
    #[arg(short, long)]
    pub fail_on_error: bool,

    /// Output format (text, json, junit)
    #[arg(short, long, default_value = "text")]
    pub output: OutputFormat,

    /// Verbose output
    #[arg(short, long)]
    pub verbose: bool,
}

impl ValidateReadmeCmd {
    pub async fn execute(&self) -> Result<ExitCode> {
        // 1. Load or generate deep context
        let deep_context = if self.deep_context.exists() {
            if self.verbose {
                eprintln!("📖 Loading deep context from {}", self.deep_context.display());
            }
            DeepContextData::load(&self.deep_context)?
        } else {
            if self.verbose {
                eprintln!("🔍 Generating deep context...");
            }
            self.generate_deep_context().await?
        };

        // 2. Build code facts database
        if self.verbose {
            eprintln!("🗄️  Building code facts database...");
        }
        let code_facts = CodeFactDatabase::from_deep_context(&deep_context)?;

        // 3. Initialize validators
        let hallucination_detector = HallucinationDetector::new(
            code_facts,
            SemanticSimilarity::new(),
            ClaimExtractor::new(),
        );

        let link_validator = LinkValidator::new(HttpClient::new(), FileSystemValidator::new());

        let context_validator = ContextCrossValidator::new(deep_context);

        let config = ValidationConfig {
            target_files: self.targets.clone(),
            deep_context_path: self.deep_context.clone(),
            check_hallucinations: self.check_hallucinations,
            check_links: self.check_links,
            check_code_references: self.check_code_refs,
            similarity_threshold: self.similarity_threshold,
            fail_on_error: self.fail_on_error,
        };

        let validator = DocAccuracyValidator {
            hallucination_detector,
            link_validator,
            context_cross_validator: context_validator,
            config,
        };

        // 4. Validate all target files
        let mut all_results = Vec::new();

        for target in &self.targets {
            if self.verbose {
                eprintln!("\n📄 Validating {}...", target.display());
            }

            let content = tokio::fs::read_to_string(target).await?;
            let results = validator.validate_file(target, &content).await?;

            all_results.extend(results);
        }

        // 5. Generate summary
        let summary = ValidationSummary::from_results(&all_results);

        // 6. Output results
        match self.output {
            OutputFormat::Text => self.print_text_summary(&summary, &all_results),
            OutputFormat::Json => self.print_json_summary(&summary, &all_results)?,
            OutputFormat::Junit => self.print_junit_summary(&summary, &all_results)?,
        }

        // 7. Exit with appropriate code
        if self.fail_on_error && summary.has_violations() {
            Ok(ExitCode::FAILURE)
        } else {
            Ok(ExitCode::SUCCESS)
        }
    }

    async fn generate_deep_context(&self) -> Result<DeepContextData> {
        // Run: pmat context --output deep_context.md --format llm-optimized
        let output = std::process::Command::new("pmat")
            .args(&["context", "--output", self.deep_context.to_str().unwrap(), "--format", "llm-optimized"])
            .output()?;

        if !output.status.success() {
            anyhow::bail!("Failed to generate deep context: {}", String::from_utf8_lossy(&output.stderr));
        }

        DeepContextData::load(&self.deep_context)
    }

    fn print_text_summary(&self, summary: &ValidationSummary, results: &[ValidationResult]) {
        println!("\n📊 Documentation Accuracy Validation Summary");
        println!("=============================================");
        println!();
        println!("📁 Files validated:       {}", summary.total_files);
        println!("📝 Claims extracted:      {}", summary.total_claims);
        println!("✅ Verified claims:       {}", summary.verified);
        println!("❌ Contradictions:        {}", summary.contradictions);
        println!("⚠️  Unverified:           {}", summary.unverified);
        println!("🔗 Broken links:          {}", summary.broken_links);
        println!("❓ Inconclusive:          {}", summary.inconclusive);
        println!();

        if summary.has_violations() {
            println!("🔴 Violations Detected:");
            println!("=======================");

            for result in results {
                if !matches!(result.status, ValidationStatus::Verified) {
                    println!(
                        "\n  ❌ {}:{}",
                        result.claim.source_file.display(),
                        result.claim.line_number
                    );
                    println!("     Claim: {}", result.claim.text);
                    println!("     Status: {:?}", result.status);
                    println!("     Confidence: {:.2}", result.confidence);

                    if let Some(ref error) = result.error_message {
                        println!("     Error: {}", error);
                    }

                    if let Some(ref evidence) = result.evidence {
                        println!("     Evidence: {}", evidence.content);
                        println!("     Similarity: {:.2}", evidence.similarity);
                    }
                }
            }

            println!();
            println!("💥 Validation FAILED - {} violation(s) found", summary.total_violations());
        } else {
            println!("🎉 All documentation claims verified!");
        }
    }
}
```

### 4.2 Usage Examples

```bash
# Generate deep context first (cached for performance)
pmat context --output deep_context.md --format llm-optimized

# Validate README and CLAUDE.md
pmat validate-readme \
    --targets README.md CLAUDE.md \
    --deep-context deep_context.md \
    --fail-on-error

# Validate all AI agent instruction files
pmat validate-readme \
    --targets README.md CLAUDE.md GEMINI.md AGENT.md \
    --check-hallucinations \
    --check-links \
    --check-code-refs \
    --similarity-threshold 0.8 \
    --fail-on-error

# JSON output for CI/CD
pmat validate-readme \
    --targets CLAUDE.md \
    --output json \
    --fail-on-error > validation-report.json

# Verbose mode for debugging
pmat validate-readme \
    --targets README.md \
    --verbose \
    --fail-on-error
```

## 5. Pre-commit Hook Integration

### 5.1 Pre-commit Hook

```bash
#!/bin/bash
# Pre-commit hook: Documentation accuracy validation
# Ensures README.md, CLAUDE.md, GEMINI.md, AGENT.md contain no hallucinations or broken references

set -e

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo -e "${YELLOW}📚 Pre-commit Quality Gate: Documentation Accuracy${NC}"
echo ""

# Check if documentation files were modified
DOC_FILES=$(git diff --cached --name-only | grep -E '(README\.md|CLAUDE\.md|GEMINI\.md|AGENT\.md)$' || true)

if [ -z "$DOC_FILES" ]; then
    echo -e "${GREEN}✅ No documentation files modified - skipping validation${NC}"
    exit 0
fi

echo -e "${YELLOW}📝 Modified documentation files:${NC}"
echo "$DOC_FILES"
echo ""

# Generate or update deep context
echo -e "${YELLOW}🔍 Generating codebase context...${NC}"
if ! pmat context --output deep_context.md --format llm-optimized --quiet; then
    echo -e "${RED}❌ Failed to generate deep context${NC}"
    exit 1
fi
echo ""

# Validate documentation
echo -e "${YELLOW}🔬 Validating documentation accuracy...${NC}"
TARGET_ARGS=""
for file in $DOC_FILES; do
    TARGET_ARGS="$TARGET_ARGS --targets $file"
done

if pmat validate-readme $TARGET_ARGS \
    --deep-context deep_context.md \
    --check-hallucinations \
    --check-links \
    --check-code-refs \
    --similarity-threshold 0.7 \
    --fail-on-error; then
    echo ""
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${GREEN}✅ QUALITY GATE PASSED: Documentation verified${NC}"
    echo -e "${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
    exit 0
else
    echo ""
    echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${RED}❌ QUALITY GATE FAILED: Documentation validation failed${NC}"
    echo -e "${RED}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
    echo -e "${YELLOW}Documentation contains hallucinations or broken references.${NC}"
    echo ""
    echo "Actions:"
    echo "  1. Fix documentation to match codebase reality, OR"
    echo "  2. Update codebase if documentation is correct"
    echo ""
    echo "To bypass this check (NOT RECOMMENDED):"
    echo "  git commit --no-verify"
    echo ""
    exit 1
fi
```

## 6. Test-Driven Development Plan

### 6.1 Property Tests

```rust
#[cfg(test)]
mod property_tests {
    use super::*;
    use proptest::prelude::*;

    proptest! {
        /// Property: All verifiable claims should have confidence > threshold
        #[test]
        fn test_verified_claims_have_high_confidence(
            claim_text in "[A-Za-z ]+",
            threshold in 0.5f32..1.0f32
        ) {
            // Setup
            let claim = Claim {
                text: format!("PMAT can {}", claim_text),
                claim_type: ClaimType::Capability,
                entities: vec![],
                source_file: PathBuf::from("test.md"),
                line_number: 1,
            };

            // Property: Verified claims must have confidence >= threshold
            // (This property guides implementation)
        }

        /// Property: Semantic similarity is symmetric
        #[test]
        fn test_semantic_similarity_symmetry(
            text_a in ".*",
            text_b in ".*"
        ) {
            let sim_engine = SemanticSimilarity::new();
            let sim_ab = sim_engine.compare(&text_a, &text_b);
            let sim_ba = sim_engine.compare(&text_b, &text_a);

            prop_assert!((sim_ab - sim_ba).abs() < 0.01);
        }

        /// Property: Entropy is bounded [0, 1]
        #[test]
        fn test_entropy_bounded(similarities in prop::collection::vec(0.0f32..1.0f32, 1..100)) {
            let detector = HallucinationDetector::new(/* ... */);
            let entropy = detector.compute_entropy(&similarities);

            prop_assert!(entropy >= 0.0 && entropy <= 1.0);
        }

        /// Property: More similar facts = lower entropy
        #[test]
        fn test_high_similarity_low_entropy() {
            let high_sim = vec![0.9, 0.91, 0.89, 0.90];
            let low_sim = vec![0.1, 0.9, 0.3, 0.7];

            let detector = HallucinationDetector::new(/* ... */);
            let entropy_high = detector.compute_entropy(&high_sim);
            let entropy_low = detector.compute_entropy(&low_sim);

            prop_assert!(entropy_high < entropy_low);
        }
    }
}
```

### 6.2 Unit Tests (TDD Style)

```rust
#[cfg(test)]
mod unit_tests {
    use super::*;

    #[test]
    fn red_test_extract_capability_claim() {
        // RED: Implementation missing
        let extractor = ClaimExtractor::new();
        let doc = "PMAT can analyze TypeScript files for complexity.";
        let claims = extractor.extract(doc, PathBuf::from("README.md")).unwrap();

        assert_eq!(claims.len(), 1);
        assert_eq!(claims[0].claim_type, ClaimType::Capability);
        assert!(claims[0].text.contains("TypeScript"));
    }

    #[test]
    fn red_test_extract_command_claim() {
        // RED: Implementation missing
        let extractor = ClaimExtractor::new();
        let doc = "Run `pmat analyze complexity project/` to analyze your code.";
        let claims = extractor.extract(doc, PathBuf::from("README.md")).unwrap();

        assert_eq!(claims.len(), 1);
        assert_eq!(claims[0].claim_type, ClaimType::Command);
        assert!(claims[0].entities.iter().any(|e| matches!(e, Entity::Command(_))));
    }

    #[test]
    fn red_test_detect_hallucinated_capability() {
        // RED: Implementation missing
        let code_facts = CodeFactDatabase::new(HashMap::new());
        let detector = HallucinationDetector::new(
            code_facts,
            SemanticSimilarity::new(),
            ClaimExtractor::new(),
        );

        let claim = Claim {
            text: "PMAT can compile C++ code to WebAssembly".to_string(),
            claim_type: ClaimType::Capability,
            entities: vec![Entity::Language("C++".to_string())],
            source_file: PathBuf::from("CLAUDE.md"),
            line_number: 42,
        };

        let result = detector.validate_claim(&claim).unwrap();

        // Should be unverified or contradiction (PMAT doesn't compile code)
        assert!(matches!(
            result.status,
            ValidationStatus::Unverified | ValidationStatus::Contradiction
        ));
        assert!(result.confidence < 0.5);
    }

    #[test]
    fn red_test_verify_real_capability() {
        // RED: Implementation missing
        // Setup code facts with Ruby language support
        let mut facts = HashMap::new();
        facts.insert(
            Entity::Language("Ruby".to_string()),
            vec![CodeFact {
                entity: Entity::Language("Ruby".to_string()),
                description: "Ruby language analysis supported".to_string(),
                source_file: PathBuf::from("server/src/cli/language_analyzer.rs"),
                line_number: 150,
                ast_metadata: None,
            }],
        );

        let code_facts = CodeFactDatabase::new(facts);
        let detector = HallucinationDetector::new(
            code_facts,
            SemanticSimilarity::new(),
            ClaimExtractor::new(),
        );

        let claim = Claim {
            text: "PMAT can analyze Ruby code".to_string(),
            claim_type: ClaimType::Capability,
            entities: vec![Entity::Language("Ruby".to_string())],
            source_file: PathBuf::from("README.md"),
            line_number: 10,
        };

        let result = detector.validate_claim(&claim).unwrap();

        assert_eq!(result.status, ValidationStatus::Verified);
        assert!(result.confidence > 0.7);
    }

    #[test]
    fn red_test_validate_structure_claim_file_exists() {
        // RED: Implementation missing
        let deep_context = DeepContextData {
            files: vec![FileData {
                path: PathBuf::from("server/src/cli/mod.rs"),
                functions: vec![],
            }],
            // ...
        };

        let validator = ContextCrossValidator::new(deep_context);

        let claim = Claim {
            text: "File server/src/cli/mod.rs contains language detection".to_string(),
            claim_type: ClaimType::Structure,
            entities: vec![Entity::File(PathBuf::from("server/src/cli/mod.rs"))],
            source_file: PathBuf::from("CLAUDE.md"),
            line_number: 20,
        };

        let result = validator.validate(&claim).unwrap();
        assert_eq!(result.status, ValidationStatus::Verified);
    }

    #[test]
    fn red_test_validate_structure_claim_file_not_found() {
        // RED: Implementation missing
        let deep_context = DeepContextData {
            files: vec![],
            // ...
        };

        let validator = ContextCrossValidator::new(deep_context);

        let claim = Claim {
            text: "File nonexistent.rs contains magic".to_string(),
            claim_type: ClaimType::Structure,
            entities: vec![Entity::File(PathBuf::from("nonexistent.rs"))],
            source_file: PathBuf::from("README.md"),
            line_number: 5,
        };

        let result = validator.validate(&claim).unwrap();
        assert_eq!(result.status, ValidationStatus::NotFound);
    }

    #[tokio::test]
    async fn red_test_validate_external_link_404() {
        // RED: Implementation missing
        let link_validator = LinkValidator::new(HttpClient::new(), FileSystemValidator::new());

        let claim = Claim {
            text: "[broken link](https://httpbin.org/status/404)".to_string(),
            claim_type: ClaimType::ExternalRef,
            entities: vec![Entity::Url("https://httpbin.org/status/404".to_string())],
            source_file: PathBuf::from("README.md"),
            line_number: 100,
        };

        let result = link_validator.validate(&claim).await.unwrap();
        assert_eq!(result.status, ValidationStatus::NotFound);
    }

    #[test]
    fn red_test_semantic_entropy_calculation() {
        // RED: Implementation missing
        let detector = HallucinationDetector::new(/* ... */);

        // High agreement (low entropy)
        let high_agreement = vec![0.95, 0.94, 0.96, 0.95];
        let entropy_low = detector.compute_entropy(&high_agreement);

        // High disagreement (high entropy)
        let high_disagreement = vec![0.1, 0.9, 0.3, 0.7];
        let entropy_high = detector.compute_entropy(&high_disagreement);

        assert!(entropy_low < 0.3);
        assert!(entropy_high > 0.7);
    }

    #[test]
    fn red_test_build_code_facts_from_deep_context() {
        // RED: Implementation missing
        let deep_context_md = r#"
## Functions

### analyze_complexity (server/src/cli/handlers.rs:42)
Analyzes code complexity using cyclomatic and cognitive metrics.

### validate_links (server/src/services/doc_validator.rs:100)
Validates HTTP and file links in markdown documentation.

## Supported Languages
- Python
- Rust
- TypeScript
- JavaScript
"#;

        let db = CodeFactDatabase::from_deep_context(deep_context_md).unwrap();

        // Should have facts for functions
        let func_facts = db.query_entities(&[Entity::Function("analyze_complexity".to_string())]).unwrap();
        assert!(!func_facts.is_empty());

        // Should have facts for languages
        let lang_facts = db.query_entities(&[Entity::Language("Python".to_string())]).unwrap();
        assert!(!lang_facts.is_empty());
    }
}
```

### 6.3 Integration Tests

```rust
#[cfg(test)]
mod integration_tests {
    use super::*;

    #[tokio::test]
    async fn test_end_to_end_validation_clean_docs() {
        // Create test project with accurate documentation
        let temp_dir = tempfile::tempdir().unwrap();
        let project_path = temp_dir.path();

        // Create source file
        std::fs::create_dir_all(project_path.join("src")).unwrap();
        std::fs::write(
            project_path.join("src/lib.rs"),
            "pub fn add(a: i32, b: i32) -> i32 { a + b }"
        ).unwrap();

        // Create accurate README
        std::fs::write(
            project_path.join("README.md"),
            "# Test Project\n\nFile src/lib.rs contains function add()."
        ).unwrap();

        // Generate deep context
        let output = std::process::Command::new("pmat")
            .args(&["context", "--output", "deep_context.md", "--project-path", project_path.to_str().unwrap()])
            .output()
            .unwrap();
        assert!(output.status.success());

        // Validate documentation
        let output = std::process::Command::new("pmat")
            .args(&[
                "validate-readme",
                "--targets", "README.md",
                "--deep-context", "deep_context.md",
                "--fail-on-error",
            ])
            .current_dir(project_path)
            .output()
            .unwrap();

        assert!(output.status.success(), "Accurate documentation should pass validation");
    }

    #[tokio::test]
    async fn test_end_to_end_validation_hallucinated_docs() {
        // Create test project with hallucinated documentation
        let temp_dir = tempfile::tempdir().unwrap();
        let project_path = temp_dir.path();

        // Create source file (no subtract function)
        std::fs::create_dir_all(project_path.join("src")).unwrap();
        std::fs::write(
            project_path.join("src/lib.rs"),
            "pub fn add(a: i32, b: i32) -> i32 { a + b }"
        ).unwrap();

        // Create hallucinated README (claims subtract exists)
        std::fs::write(
            project_path.join("README.md"),
            "# Test Project\n\nFile src/lib.rs contains functions add() and subtract()."
        ).unwrap();

        // Generate deep context
        std::process::Command::new("pmat")
            .args(&["context", "--output", "deep_context.md", "--project-path", project_path.to_str().unwrap()])
            .output()
            .unwrap();

        // Validate documentation
        let output = std::process::Command::new("pmat")
            .args(&[
                "validate-readme",
                "--targets", "README.md",
                "--deep-context", "deep_context.md",
                "--fail-on-error",
            ])
            .current_dir(project_path)
            .output()
            .unwrap();

        assert!(!output.status.success(), "Hallucinated documentation should fail validation");

        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.contains("subtract"), "Error should mention hallucinated function");
    }
}
```

## 7. Quality Gates Integration

Add to `.pmat.toml`:

```toml
[quality_gate]
# Documentation accuracy enforcement
docs_accuracy = {
    targets = ["README.md", "CLAUDE.md", "GEMINI.md", "AGENT.md"],
    deep_context = "deep_context.md",
    check_hallucinations = true,
    check_links = true,
    check_code_refs = true,
    similarity_threshold = 0.7,
    fail_on_error = true
}
```

Usage:

```bash
# Run as part of quality gate
pmat quality-gate --checks docs-accuracy

# Standalone
pmat validate-readme \
    --targets README.md CLAUDE.md \
    --fail-on-error
```

## 8. CI/CD Integration

### 8.1 GitHub Actions

```yaml
name: Documentation Accuracy

on: [push, pull_request]

jobs:
  validate-docs:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Install PMAT
        run: cargo install pmat

      - name: Generate Deep Context
        run: pmat context --output deep_context.md --format llm-optimized

      - name: Validate Documentation
        run: |
          pmat validate-readme \
            --targets README.md CLAUDE.md GEMINI.md AGENT.md \
            --deep-context deep_context.md \
            --check-hallucinations \
            --check-links \
            --check-code-refs \
            --fail-on-error \
            --output json > docs-validation.json

      - name: Upload Validation Report
        uses: actions/upload-artifact@v3
        with:
          name: docs-validation-report
          path: docs-validation.json
```

## 9. Performance Requirements

- **Deep Context Generation**: < 30 seconds for 100K LOC project
- **Claim Extraction**: < 1 second per 1000 lines of documentation
- **Hallucination Detection**: < 100ms per claim
- **Link Validation**: < 5 seconds for 100 links
- **Total Validation**: < 60 seconds for typical project
- **Memory**: < 500MB for 100K LOC project

## 10. Dependencies

```toml
[dependencies]
# Existing
anyhow = "1.0"
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
clap = { version = "4.5", features = ["derive"] }
regex = "1.10"

# New for hallucination detection
sentence-transformers = "0.3"  # Semantic similarity
rust-bert = "0.21"  # NLP models
ndarray = "0.15"  # Numerical arrays for embeddings
approx = "0.5"  # Floating-point comparison

# Existing link validation
reqwest = { version = "0.11", features = ["json"] }
walkdir = "2.4"

[dev-dependencies]
proptest = "1.4"
tempfile = "3.8"
mockito = "1.2"
criterion = "0.5"
```

## 11. Implementation Roadmap

### Phase 1: Claim Extraction & Code Facts (Week 1)
- Implement `ClaimExtractor` with pattern matching
- Build `CodeFactDatabase` from deep context
- Add entity extraction (files, functions, languages)
- Write unit tests for extraction

### Phase 2: Semantic Similarity (Week 2)
- Integrate sentence-transformers for embeddings
- Implement `SemanticSimilarity` engine
- Add semantic entropy calculation
- Write property tests for similarity

### Phase 3: Hallucination Detection (Week 2)
- Implement `HallucinationDetector`
- Add claim validation logic
- Integrate entropy-based detection
- Write comprehensive tests

### Phase 4: Context Cross-Validation (Week 3)
- Implement `ContextCrossValidator`
- Add structure/API/command claim validation
- Integrate with deep context parsing
- Write integration tests

### Phase 5: CLI Integration (Week 3)
- Add `validate-readme` command
- Implement output formatters (text, JSON, JUnit)
- Add pre-commit hook
- Write end-to-end tests

### Phase 6: Quality & Release (Week 4)
- Run all quality gates
- Optimize performance
- Complete documentation
- Publish to crates.io

## 12. Success Criteria

- [ ] All property tests passing
- [ ] All unit tests passing
- [ ] All integration tests passing
- [ ] Test coverage ≥ 85%
- [ ] `pmat quality-gate` passing
- [ ] Detects hallucinations in test cases
- [ ] Validates code references accurately
- [ ] Detects 404 errors in links
- [ ] Pre-commit hook functional
- [ ] CI/CD integration working
- [ ] Performance benchmarks met
- [ ] Documentation complete
- [ ] Published to crates.io

## 13. References

### Peer-Reviewed Research

1. **Farquhar et al. (2024)** - "Detecting hallucinations in large language models using semantic entropy", *Nature*, June 2024
   - DOI: 10.1038/s41586-024-07421-0
   - Method: Entropy-based uncertainty estimation for confabulation detection

2. **IJCAI 2025** - "MIND: Training framework leveraging internal representations for hallucination detection"
   - Method: EigenScore for semantic information exploration
   - Application: Internal representation analysis

3. **Complex & Intelligent Systems (2025)** - "Reducing hallucinations via hierarchical semantic piece"
   - DOI: 10.1007/s40747-025-01833-9
   - Method: Unified framework with output parser, reference parser, fact verifier, mitigator

4. **ACM Computing Surveys (2024)** - "Hallucination Detection in Foundation Models for Decision-Making"
   - DOI: 10.1145/3716846
   - Review of state-of-the-art hallucination detection methods

### Industry Tools & Approaches

5. **KnowledgeOwl** - Broken link checker & report
6. **Dr. Link Check** - Automated link validation
7. **Siteimprove** - Quality assurance: broken links and misspellings
8. **DocAgent** - Multi-agent system for automated code documentation generation

### PMAT Documentation

9. `docs/specifications/doc-validate.md` - Existing link validation spec
10. `docs/features/documentation-enforcement.md` - MCP/CLI documentation enforcement
11. `server/src/cli/handlers/doc_validate_handlers.rs` - Implementation reference

---

**Next Steps**:
1. Review and approve specification
2. Create GitHub issues for each phase
3. Begin TDD implementation starting with RED tests
4. Integrate with existing PMAT quality gates
