Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
feat: Implement conflicts, seed, vocabulary, and templates modules
KaifAhmad1b187f8b26f82
diff --git a/libs/semantica/conflicts/__init__.py b/libs/semantica/conflicts/__init__.pyindex 3aac239a..ef9c7ff3 100644--- a/libs/semantica/conflicts/__init__.py+++ b/libs/semantica/conflicts/__init__.py@@ -5,17 +5,29 @@ This module identifies conflicts from multiple sources andprovides investigation guides for discrepancies."""-# from .conflict_detector import ConflictDetector-# from .source_tracker import SourceTracker-# from .conflict_resolver import ConflictResolver-# from .investigation_guide import InvestigationGuideGenerator-# from .conflict_analyzer import ConflictAnalyzer+from .conflict_detector import ConflictDetector, Conflict, ConflictType+from .source_tracker import SourceTracker, SourceReference, PropertySource+from .conflict_resolver import ConflictResolver, ResolutionResult, ResolutionStrategy+from .investigation_guide import (+ InvestigationGuideGenerator,+ InvestigationGuide,+ InvestigationStep,+)+from .conflict_analyzer import ConflictAnalyzer, ConflictPattern-# TODO: Implement conflict detection-# - Multi-source conflict identification-# - Property value conflict detection-# - Relationship conflict detection-# - Source tracking for conflicts-# - Investigation guide generation-# - Conflict resolution strategies-# - Conflict pattern analysis+__all__ = [+ "ConflictDetector",+ "Conflict",+ "ConflictType",+ "SourceTracker",+ "SourceReference",+ "PropertySource",+ "ConflictResolver",+ "ResolutionResult",+ "ResolutionStrategy",+ "InvestigationGuideGenerator",+ "InvestigationGuide",+ "InvestigationStep",+ "ConflictAnalyzer",+ "ConflictPattern",+]diff --git a/libs/semantica/conflicts/conflict_analyzer.py b/libs/semantica/conflicts/conflict_analyzer.pyindex 3af2965e..e4a58f81 100644--- a/libs/semantica/conflicts/conflict_analyzer.py+++ b/libs/semantica/conflicts/conflict_analyzer.py@@ -5,10 +5,337 @@ Analyzes patterns in conflicts, identifies conflict types, andprovides insights into conflict sources and trends."""-# TODO: Implement conflict analysis-# - Analyze conflict patterns and trends-# - Classify conflict types-# - Identify high-conflict areas-# - Generate conflict statistics-# - Provide conflict insights and recommendations-# - Support conflict prevention strategies+from typing import Any, Dict, List, Optional+from dataclasses import dataclass, field+from collections import defaultdict, Counter+from datetime import datetime++from .conflict_detector import Conflict, ConflictType+from ..utils.logging import get_logger+++@dataclass+class ConflictPattern:+ """Conflict pattern analysis."""+ pattern_type: str+ frequency: int+ affected_entities: List[str] = field(default_factory=list)+ affected_properties: List[str] = field(default_factory=list)+ common_sources: List[str] = field(default_factory=list)+ metadata: Dict[str, Any] = field(default_factory=dict)+++class ConflictAnalyzer:+ """+ Conflict analyzer for pattern identification and insights.++ • Analyzes conflict patterns and trends+ • Classifies conflict types+ • Identifies high-conflict areas+ • Generates conflict statistics+ • Provides conflict insights and recommendations+ • Supports conflict prevention strategies+ """++ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):+ """+ Initialize conflict analyzer.++ Args:+ config: Configuration dictionary+ **kwargs: Additional configuration options+ """+ self.logger = get_logger("conflict_analyzer")+ self.config = config or {}+ self.config.update(kwargs)++ def analyze_conflicts(+ self,+ conflicts: List[Conflict]+ ) -> Dict[str, Any]:+ """+ Analyze conflicts and generate insights.++ Args:+ conflicts: List of conflicts to analyze++ Returns:+ Analysis results dictionary+ """+ analysis = {+ "total_conflicts": len(conflicts),+ "by_type": self._analyze_by_type(conflicts),+ "by_severity": self._analyze_by_severity(conflicts),+ "by_entity": self._analyze_by_entity(conflicts),+ "by_property": self._analyze_by_property(conflicts),+ "patterns": self._identify_patterns(conflicts),+ "recommendations": self._generate_recommendations(conflicts),+ "statistics": self._calculate_statistics(conflicts)+ }++ return analysis++ def _analyze_by_type(self, conflicts: List[Conflict]) -> Dict[str, Any]:+ """Analyze conflicts by type."""+ by_type = defaultdict(int)+ type_details = defaultdict(list)++ for conflict in conflicts:+ conflict_type = conflict.conflict_type.value+ by_type[conflict_type] += 1+ type_details[conflict_type].append({+ "conflict_id": conflict.conflict_id,+ "entity_id": conflict.entity_id,+ "severity": conflict.severity+ })++ return {+ "counts": dict(by_type),+ "details": dict(type_details)+ }++ def _analyze_by_severity(self, conflicts: List[Conflict]) -> Dict[str, Any]:+ """Analyze conflicts by severity."""+ by_severity = defaultdict(int)+ severity_details = defaultdict(list)++ for conflict in conflicts:+ severity = conflict.severity+ by_severity[severity] += 1+ severity_details[severity].append({+ "conflict_id": conflict.conflict_id,+ "type": conflict.conflict_type.value,+ "entity_id": conflict.entity_id,+ "property_name": conflict.property_name+ })++ return {+ "counts": dict(by_severity),+ "details": dict(severity_details)+ }++ def _analyze_by_entity(self, conflicts: List[Conflict]) -> Dict[str, Any]:+ """Analyze conflicts by entity."""+ by_entity = defaultdict(int)+ entity_conflicts = defaultdict(list)++ for conflict in conflicts:+ if conflict.entity_id:+ by_entity[conflict.entity_id] += 1+ entity_conflicts[conflict.entity_id].append({+ "conflict_id": conflict.conflict_id,+ "property_name": conflict.property_name,+ "type": conflict.conflict_type.value,+ "severity": conflict.severity+ })++ # Get top entities with most conflicts+ top_entities = sorted(+ by_entity.items(),+ key=lambda x: x[1],+ reverse=True+ )[:10]++ return {+ "counts": dict(by_entity),+ "top_entities": [{"entity_id": eid, "conflict_count": count}+ for eid, count in top_entities],+ "details": dict(entity_conflicts)+ }++ def _analyze_by_property(self, conflicts: List[Conflict]) -> Dict[str, Any]:+ """Analyze conflicts by property."""+ by_property = defaultdict(int)+ property_conflicts = defaultdict(list)++ for conflict in conflicts:+ if conflict.property_name:+ by_property[conflict.property_name] += 1+ property_conflicts[conflict.property_name].append({+ "conflict_id": conflict.conflict_id,+ "entity_id": conflict.entity_id,+ "type": conflict.conflict_type.value,+ "severity": conflict.severity+ })++ # Get top properties with most conflicts+ top_properties = sorted(+ by_property.items(),+ key=lambda x: x[1],+ reverse=True+ )[:10]++ return {+ "counts": dict(by_property),+ "top_properties": [{"property_name": prop, "conflict_count": count}+ for prop, count in top_properties],+ "details": dict(property_conflicts)+ }++ def _identify_patterns(self, conflicts: List[Conflict]) -> List[ConflictPattern]:+ """Identify conflict patterns."""+ patterns = []++ # Pattern 1: Same property conflicts across multiple entities+ property_entity_map = defaultdict(set)+ for conflict in conflicts:+ if conflict.property_name and conflict.entity_id:+ property_entity_map[conflict.property_name].add(conflict.entity_id)++ for prop, entities in property_entity_map.items():+ if len(entities) > 3: # Multiple entities affected+ patterns.append(ConflictPattern(+ pattern_type="widespread_property_conflict",+ frequency=len(entities),+ affected_properties=[prop],+ affected_entities=list(entities),+ metadata={"description": f"Property '{prop}' has conflicts across {len(entities)} entities"}+ ))++ # Pattern 2: Same source appears in multiple conflicts+ source_conflict_map = defaultdict(int)+ for conflict in conflicts:+ for source in conflict.sources:+ source_conflict_map[source.get("document", "unknown")] += 1++ problematic_sources = [+ (source, count) for source, count in source_conflict_map.items()+ if count > 5+ ]++ for source, count in problematic_sources:+ patterns.append(ConflictPattern(+ pattern_type="problematic_source",+ frequency=count,+ common_sources=[source],+ metadata={"description": f"Source '{source}' appears in {count} conflicts"}+ ))++ # Pattern 3: High-severity conflicts cluster+ critical_conflicts = [c for c in conflicts if c.severity == "critical"]+ if len(critical_conflicts) > 5:+ patterns.append(ConflictPattern(+ pattern_type="critical_conflict_cluster",+ frequency=len(critical_conflicts),+ metadata={"description": f"{len(critical_conflicts)} critical conflicts detected"}+ ))++ return patterns++ def _generate_recommendations(self, conflicts: List[Conflict]) -> List[str]:+ """Generate recommendations based on conflict analysis."""+ recommendations = []++ if not conflicts:+ return ["No conflicts detected. Continue monitoring."]++ # Analyze patterns+ by_property = self._analyze_by_property(conflicts)+ by_entity = self._analyze_by_entity(conflicts)+ patterns = self._identify_patterns(conflicts)++ # Recommendation 1: High-conflict properties+ top_properties = by_property.get("top_properties", [])+ if top_properties:+ top_prop = top_properties[0]+ recommendations.append(+ f"Property '{top_prop['property_name']}' has {top_prop['conflict_count']} conflicts. "+ f"Consider implementing stricter validation or source verification."+ )++ # Recommendation 2: Problematic sources+ problematic_source_patterns = [p for p in patterns if p.pattern_type == "problematic_source"]+ if problematic_source_patterns:+ for pattern in problematic_source_patterns:+ recommendations.append(+ f"Source '{pattern.common_sources[0]}' appears in multiple conflicts. "+ f"Review source quality and credibility."+ )++ # Recommendation 3: High-conflict entities+ top_entities = by_entity.get("top_entities", [])+ if top_entities:+ top_entity = top_entities[0]+ recommendations.append(+ f"Entity '{top_entity['entity_id']}' has {top_entity['conflict_count']} conflicts. "+ f"Review entity data sources and merge strategy."+ )++ # Recommendation 4: Critical conflicts+ critical_count = len([c for c in conflicts if c.severity == "critical"])+ if critical_count > 0:+ recommendations.append(+ f"{critical_count} critical conflicts detected. Immediate review required."+ )++ if not recommendations:+ recommendations.append("Monitor conflicts and review patterns regularly.")++ return recommendations++ def _calculate_statistics(self, conflicts: List[Conflict]) -> Dict[str, Any]:+ """Calculate conflict statistics."""+ if not conflicts:+ return {+ "total_conflicts": 0,+ "average_confidence": 0.0,+ "conflict_rate": 0.0+ }++ total_conflicts = len(conflicts)+ avg_confidence = sum(c.confidence for c in conflicts) / total_conflicts++ # Count unique entities and properties+ unique_entities = len(set(c.entity_id for c in conflicts if c.entity_id))+ unique_properties = len(set(c.property_name for c in conflicts if c.property_name))++ # Count by source+ source_counts = Counter()+ for conflict in conflicts:+ for source in conflict.sources:+ source_counts[source.get("document", "unknown")] += 1++ return {+ "total_conflicts": total_conflicts,+ "average_confidence": avg_confidence,+ "unique_entities_affected": unique_entities,+ "unique_properties_affected": unique_properties,+ "top_sources": dict(source_counts.most_common(5)),+ "conflict_rate": total_conflicts / max(unique_entities, 1) # Conflicts per entity+ }++ def generate_insights_report(self, conflicts: List[Conflict]) -> Dict[str, Any]:+ """+ Generate comprehensive insights report.++ Args:+ conflicts: List of conflicts++ Returns:+ Insights report dictionary+ """+ analysis = self.analyze_conflicts(conflicts)++ report = {+ "generated_at": datetime.now().isoformat(),+ "summary": {+ "total_conflicts": analysis["total_conflicts"],+ "critical_count": analysis["by_severity"]["counts"].get("critical", 0),+ "high_count": analysis["by_severity"]["counts"].get("high", 0),+ "medium_count": analysis["by_severity"]["counts"].get("medium", 0),+ "low_count": analysis["by_severity"]["counts"].get("low", 0)+ },+ "analysis": analysis,+ "insights": {+ "most_conflict_prone_properties": [+ p["property_name"] for p in analysis["by_property"]["top_properties"][:5]+ ],+ "most_conflict_prone_entities": [+ e["entity_id"] for e in analysis["by_entity"]["top_entities"][:5]+ ],+ "patterns_detected": len(analysis["patterns"]),+ "recommendations": analysis["recommendations"]+ }+ }++ return reportdiff --git a/libs/semantica/conflicts/conflict_detector.py b/libs/semantica/conflicts/conflict_detector.pyindex 03becb17..84659bc8 100644--- a/libs/semantica/conflicts/conflict_detector.py+++ b/libs/semantica/conflicts/conflict_detector.py@@ -5,9 +5,359 @@ Detects conflicts from multiple sources and tracks sourcedisagreements for compliance and investigation."""-# TODO: Implement conflict detector-# - Detect property value conflicts-# - Identify relationship conflicts-# - Track source disagreements-# - Generate conflict reports-# - Provide investigation guides+from typing import Any, Dict, List, Optional, Set+from dataclasses import dataclass, field+from enum import Enum++from .source_tracker import SourceTracker, SourceReference+from ..utils.exceptions import ValidationError, ProcessingError+from ..utils.logging import get_logger+++class ConflictType(str, Enum):+ """Conflict type enumeration."""+ VALUE_CONFLICT = "value_conflict"+ TYPE_CONFLICT = "type_conflict"+ RELATIONSHIP_CONFLICT = "relationship_conflict"+ TEMPORAL_CONFLICT = "temporal_conflict"+ LOGICAL_CONFLICT = "logical_conflict"+++@dataclass+class Conflict:+ """Conflict information."""+ conflict_id: str+ conflict_type: ConflictType+ entity_id: Optional[str] = None+ property_name: Optional[str] = None+ relationship_id: Optional[str] = None+ conflicting_values: List[Any] = field(default_factory=list)+ sources: List[Dict[str, Any]] = field(default_factory=list)+ confidence: float = 1.0+ severity: str = "medium" # low, medium, high, critical+ recommended_action: Optional[str] = None+ metadata: Dict[str, Any] = field(default_factory=dict)+++class ConflictDetector:+ """+ Conflict detector for multi-source conflict identification.++ • Detects property value conflicts+ • Identifies relationship conflicts+ • Tracks source disagreements+ • Generates conflict reports+ • Provides investigation guides+ """++ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):+ """+ Initialize conflict detector.++ Args:+ config: Configuration dictionary+ **kwargs: Additional configuration options:+ - track_provenance: Track source provenance (default: True)+ - conflict_fields: Fields to monitor for conflicts+ - confidence_threshold: Minimum confidence for conflicts (default: 0.7)+ - auto_resolve: Auto-resolve simple conflicts (default: False)+ """+ self.logger = get_logger("conflict_detector")+ self.config = config or {}+ self.config.update(kwargs)++ self.source_tracker = SourceTracker()+ self.track_provenance = self.config.get("track_provenance", True)+ self.conflict_fields = self.config.get("conflict_fields", {})+ self.confidence_threshold = self.config.get("confidence_threshold", 0.7)+ self.auto_resolve = self.config.get("auto_resolve", False)++ self.detected_conflicts: Dict[str, Conflict] = {}++ def detect_value_conflicts(+ self,+ entities: List[Dict[str, Any]],+ property_name: str,+ entity_type: Optional[str] = None+ ) -> List[Conflict]:+ """+ Detect property value conflicts.++ Args:+ entities: List of entity dictionaries+ property_name: Property name to check+ entity_type: Optional entity type filter++ Returns:+ List of detected conflicts+ """+ conflicts = []++ # Group entities by ID (same entity from different sources)+ entity_groups: Dict[str, List[Dict[str, Any]]] = {}++ for entity in entities:+ entity_id = entity.get("id") or entity.get("entity_id")+ if not entity_id:+ continue++ if entity_type and entity.get("type") != entity_type:+ continue++ if entity_id not in entity_groups:+ entity_groups[entity_id] = []+ entity_groups[entity_id].append(entity)++ # Check each entity group for conflicts+ for entity_id, entity_list in entity_groups.items():+ if len(entity_list) < 2:+ continue # Need at least 2 sources to have conflict++ values = []+ sources = []++ for entity in entity_list:+ if property_name in entity:+ value = entity[property_name]+ values.append(value)++ # Track source if available+ if self.track_provenance:+ source_ref = SourceReference(+ document=entity.get("source", "unknown"),+ page=entity.get("page"),+ section=entity.get("section"),+ confidence=entity.get("confidence", 1.0),+ metadata=entity.get("metadata", {})+ )+ self.source_tracker.track_property_source(+ entity_id,+ property_name,+ value,+ source_ref+ )+ sources.append({+ "document": source_ref.document,+ "page": source_ref.page,+ "confidence": source_ref.confidence+ })++ # Check for value conflicts+ unique_values = list(set(str(v) for v in values if v is not None))++ if len(unique_values) > 1:+ conflict = Conflict(+ conflict_id=f"{entity_id}_{property_name}_conflict",+ conflict_type=ConflictType.VALUE_CONFLICT,+ entity_id=entity_id,+ property_name=property_name,+ conflicting_values=values,+ sources=sources,+ confidence=self._calculate_conflict_confidence(values, sources),+ severity=self._calculate_severity(property_name, values),+ recommended_action=self._recommend_action(property_name, values)+ )+ conflicts.append(conflict)+ self.detected_conflicts[conflict.conflict_id] = conflict++ self.logger.warning(+ f"Value conflict detected: {entity_id}.{property_name} "+ f"has conflicting values: {unique_values}"+ )++ return conflicts++ def detect_property_conflicts(+ self,+ entities: List[Dict[str, Any]],+ property_name: str+ ) -> List[Conflict]:+ """+ Detect conflicts in a specific property across entities.++ Args:+ entities: List of entity dictionaries+ property_name: Property name to check++ Returns:+ List of detected conflicts+ """+ return self.detect_value_conflicts(entities, property_name)++ def detect_relationship_conflicts(+ self,+ relationships: List[Dict[str, Any]]+ ) -> List[Conflict]:+ """+ Detect conflicts in relationships.++ Args:+ relationships: List of relationship dictionaries++ Returns:+ List of detected conflicts+ """+ conflicts = []++ # Group relationships by ID+ rel_groups: Dict[str, List[Dict[str, Any]]] = {}++ for rel in relationships:+ rel_id = rel.get("id") or f"{rel.get('source_id')}_{rel.get('target_id')}_{rel.get('type')}"++ if rel_id not in rel_groups:+ rel_groups[rel_id] = []+ rel_groups[rel_id].append(rel)++ # Check for conflicts+ for rel_id, rel_list in rel_groups.items():+ if len(rel_list) < 2:+ continue++ # Check for conflicting properties+ for prop_name in ["type", "properties", "confidence"]:+ values = [r.get(prop_name) for r in rel_list if prop_name in r]+ unique_values = list(set(str(v) for v in values if v is not None))++ if len(unique_values) > 1:+ conflict = Conflict(+ conflict_id=f"{rel_id}_{prop_name}_conflict",+ conflict_type=ConflictType.RELATIONSHIP_CONFLICT,+ relationship_id=rel_id,+ property_name=prop_name,+ conflicting_values=values,+ confidence=0.8,+ severity="medium",+ recommended_action="Review relationship definition"+ )+ conflicts.append(conflict)+ self.detected_conflicts[conflict.conflict_id] = conflict++ return conflicts++ def detect_entity_conflicts(+ self,+ entities: List[Dict[str, Any]],+ entity_type: Optional[str] = None+ ) -> List[Conflict]:+ """+ Detect conflicts across all monitored properties for entities.++ Args:+ entities: List of entity dictionaries+ entity_type: Optional entity type filter++ Returns:+ List of detected conflicts+ """+ all_conflicts = []++ # Get fields to monitor+ if entity_type and entity_type in self.conflict_fields:+ fields_to_check = self.conflict_fields[entity_type]+ else:+ # Check all common properties+ fields_to_check = set()+ for entity in entities:+ fields_to_check.update(entity.keys())+ fields_to_check = list(fields_to_check - {"id", "entity_id", "type", "source", "metadata"})++ # Check each field+ for field in fields_to_check:+ conflicts = self.detect_value_conflicts(entities, field, entity_type)+ all_conflicts.extend(conflicts)++ return all_conflicts++ def _calculate_conflict_confidence(+ self,+ values: List[Any],+ sources: List[Dict[str, Any]]+ ) -> float:+ """Calculate confidence score for conflict."""+ if not sources:+ return 0.5++ # Average confidence of sources+ avg_confidence = sum(s.get("confidence", 0.5) for s in sources) / len(sources)++ # Higher confidence if values are very different+ value_diversity = len(set(str(v) for v in values)) / len(values) if values else 0++ return min(1.0, avg_confidence * (1 + value_diversity))++ def _calculate_severity(+ self,+ property_name: str,+ values: List[Any]+ ) -> str:+ """Calculate conflict severity."""+ # Critical fields+ critical_fields = ["id", "name", "type", "founded_year", "revenue"]+ if property_name.lower() in critical_fields:+ return "critical"++ # High severity for numeric conflicts with large differences+ try:+ numeric_values = [float(v) for v in values if v is not None]+ if numeric_values:+ value_range = max(numeric_values) - min(numeric_values)+ if value_range > 1000: # Large difference+ return "high"+ except (ValueError, TypeError):+ pass++ return "medium"++ def _recommend_action(+ self,+ property_name: str,+ values: List[Any]+ ) -> str:+ """Recommend action for conflict."""+ if len(set(values)) == 2:+ return "Compare source documents and use most recent or authoritative source"+ else:+ return "Multiple conflicting values detected. Manual review recommended."++ def get_conflict_report(self) -> Dict[str, Any]:+ """+ Generate conflict report.++ Returns:+ Conflict report dictionary+ """+ report = {+ "total_conflicts": len(self.detected_conflicts),+ "by_type": {},+ "by_severity": {},+ "conflicts": []+ }++ for conflict in self.detected_conflicts.values():+ # Count by type+ conflict_type = conflict.conflict_type.value+ report["by_type"][conflict_type] = report["by_type"].get(conflict_type, 0) + 1++ # Count by severity+ report["by_severity"][conflict.severity] = report["by_severity"].get(conflict.severity, 0) + 1++ # Add conflict details+ conflict_data = {+ "conflict_id": conflict.conflict_id,+ "type": conflict_type,+ "entity_id": conflict.entity_id,+ "property_name": conflict.property_name,+ "severity": conflict.severity,+ "conflicting_values": conflict.conflicting_values,+ "sources": conflict.sources,+ "recommended_action": conflict.recommended_action+ }+ report["conflicts"].append(conflict_data)++ return report++ def clear_conflicts(self) -> None:+ """Clear all detected conflicts."""+ self.detected_conflicts.clear()+ self.logger.info("Cleared all detected conflicts")diff --git a/libs/semantica/conflicts/conflict_resolver.py b/libs/semantica/conflicts/conflict_resolver.pyindex 42187954..13b49a27 100644--- a/libs/semantica/conflicts/conflict_resolver.py+++ b/libs/semantica/conflicts/conflict_resolver.py@@ -5,10 +5,380 @@ Provides strategies for resolving detected conflicts includingvoting mechanisms, credibility-based resolution, and expert review."""-# TODO: Implement conflict resolution-# - Automatic conflict resolution strategies-# - Voting-based resolution from multiple sources-# - Credibility-weighted conflict resolution-# - Manual conflict resolution workflow-# - Resolution rule configuration-# - Conflict resolution history tracking+from typing import Any, Dict, List, Optional, Callable+from dataclasses import dataclass, field+from enum import Enum+from collections import Counter++from .conflict_detector import Conflict, ConflictType+from .source_tracker import SourceTracker+from ..utils.exceptions import ValidationError, ProcessingError+from ..utils.logging import get_logger+++class ResolutionStrategy(str, Enum):+ """Conflict resolution strategy."""+ VOTING = "voting"+ CREDIBILITY_WEIGHTED = "credibility_weighted"+ MOST_RECENT = "most_recent"+ FIRST_SEEN = "first_seen"+ HIGHEST_CONFIDENCE = "highest_confidence"+ MANUAL_REVIEW = "manual_review"+ EXPERT_REVIEW = "expert_review"+++@dataclass+class ResolutionResult:+ """Conflict resolution result."""+ conflict_id: str+ resolved: bool+ resolved_value: Any = None+ resolution_strategy: Optional[str] = None+ confidence: float = 0.0+ sources_used: List[str] = field(default_factory=list)+ resolution_notes: Optional[str] = None+ metadata: Dict[str, Any] = field(default_factory=dict)+++class ConflictResolver:+ """+ Conflict resolver with multiple resolution strategies.++ • Automatic conflict resolution strategies+ • Voting-based resolution from multiple sources+ • Credibility-weighted conflict resolution+ • Manual conflict resolution workflow+ • Resolution rule configuration+ • Conflict resolution history tracking+ """++ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):+ """+ Initialize conflict resolver.++ Args:+ config: Configuration dictionary+ **kwargs: Additional configuration options:+ - default_strategy: Default resolution strategy+ - source_tracker: Source tracker instance+ - resolution_rules: Custom resolution rules+ """+ self.logger = get_logger("conflict_resolver")+ self.config = config or {}+ self.config.update(kwargs)++ self.source_tracker = self.config.get("source_tracker") or SourceTracker()+ self.default_strategy = ResolutionStrategy(+ self.config.get("default_strategy", "voting")+ )+ self.resolution_rules: Dict[str, ResolutionStrategy] = self.config.get(+ "resolution_rules", {}+ )++ self.resolution_history: List[ResolutionResult] = []++ def resolve_conflict(+ self,+ conflict: Conflict,+ strategy: Optional[ResolutionStrategy] = None+ ) -> ResolutionResult:+ """+ Resolve a conflict using specified strategy.++ Args:+ conflict: Conflict to resolve+ strategy: Resolution strategy (uses default if None)++ Returns:+ Resolution result+ """+ if not strategy:+ # Check for property-specific rule+ if conflict.property_name:+ rule_key = f"{conflict.entity_id}.{conflict.property_name}"+ if rule_key in self.resolution_rules:+ strategy = self.resolution_rules[rule_key]+ else:+ strategy = self.default_strategy+ else:+ strategy = self.default_strategy++ self.logger.info(+ f"Resolving conflict {conflict.conflict_id} using strategy: {strategy.value}"+ )++ if strategy == ResolutionStrategy.VOTING:+ result = self._resolve_by_voting(conflict)+ elif strategy == ResolutionStrategy.CREDIBILITY_WEIGHTED:+ result = self._resolve_by_credibility(conflict)+ elif strategy == ResolutionStrategy.MOST_RECENT:+ result = self._resolve_by_recency(conflict)+ elif strategy == ResolutionStrategy.FIRST_SEEN:+ result = self._resolve_by_first_seen(conflict)+ elif strategy == ResolutionStrategy.HIGHEST_CONFIDENCE:+ result = self._resolve_by_confidence(conflict)+ elif strategy == ResolutionStrategy.MANUAL_REVIEW:+ result = self._flag_for_manual_review(conflict)+ elif strategy == ResolutionStrategy.EXPERT_REVIEW:+ result = self._flag_for_expert_review(conflict)+ else:+ result = self._resolve_by_voting(conflict)++ result.resolution_strategy = strategy.value+ self.resolution_history.append(result)++ return result++ def resolve_conflicts(+ self,+ conflicts: List[Conflict],+ strategy: Optional[ResolutionStrategy] = None+ ) -> List[ResolutionResult]:+ """+ Resolve multiple conflicts.++ Args:+ conflicts: List of conflicts to resolve+ strategy: Resolution strategy (uses default if None)++ Returns:+ List of resolution results+ """+ results = []++ for conflict in conflicts:+ result = self.resolve_conflict(conflict, strategy)+ results.append(result)++ return results++ def _resolve_by_voting(self, conflict: Conflict) -> ResolutionResult:+ """Resolve conflict by voting (most common value wins)."""+ if not conflict.conflicting_values:+ return ResolutionResult(+ conflict_id=conflict.conflict_id,+ resolved=False,+ resolution_notes="No conflicting values to resolve"+ )++ # Count value occurrences+ value_counts = Counter(conflict.conflicting_values)+ most_common_value, count = value_counts.most_common(1)[0]++ # Calculate confidence based on vote ratio+ total_votes = len(conflict.conflicting_values)+ confidence = count / total_votes if total_votes > 0 else 0.0++ sources_used = [s.get("document", "unknown") for s in conflict.sources]++ return ResolutionResult(+ conflict_id=conflict.conflict_id,+ resolved=True,+ resolved_value=most_common_value,+ confidence=confidence,+ sources_used=sources_used,+ resolution_notes=f"Resolved by voting: {count}/{total_votes} votes for this value"+ )++ def _resolve_by_credibility(self, conflict: Conflict) -> ResolutionResult:+ """Resolve conflict by credibility-weighted voting."""+ if not conflict.conflicting_values or not conflict.sources:+ return ResolutionResult(+ conflict_id=conflict.conflict_id,+ resolved=False,+ resolution_notes="Insufficient data for credibility-based resolution"+ )++ # Weight values by source credibility+ value_weights: Dict[Any, float] = {}++ for i, value in enumerate(conflict.conflicting_values):+ source = conflict.sources[i] if i < len(conflict.sources) else {}+ document = source.get("document", "unknown")+ source_confidence = source.get("confidence", 0.5)+ credibility = self.source_tracker.get_source_credibility(document)++ weight = source_confidence * credibility++ if value not in value_weights:+ value_weights[value] = 0.0+ value_weights[value] += weight++ # Get value with highest weight+ if not value_weights:+ return ResolutionResult(+ conflict_id=conflict.conflict_id,+ resolved=False,+ resolution_notes="Could not calculate credibility weights"+ )++ resolved_value = max(value_weights.items(), key=lambda x: x[1])[0]+ total_weight = sum(value_weights.values())+ confidence = value_weights[resolved_value] / total_weight if total_weight > 0 else 0.0++ sources_used = [s.get("document", "unknown") for s in conflict.sources]++ return ResolutionResult(+ conflict_id=conflict.conflict_id,+ resolved=True,+ resolved_value=resolved_value,+ confidence=confidence,+ sources_used=sources_used,+ resolution_notes=f"Resolved by credibility-weighted voting (weight: {value_weights[resolved_value]:.2f})"+ )++ def _resolve_by_recency(self, conflict: Conflict) -> ResolutionResult:+ """Resolve conflict by using most recent value."""+ if not conflict.sources:+ return ResolutionResult(+ conflict_id=conflict.conflict_id,+ resolved=False,+ resolution_notes="No source timestamps available"+ )++ # Find most recent source (by timestamp if available)+ most_recent_idx = 0+ most_recent_time = None++ for i, source in enumerate(conflict.sources):+ # Check metadata for timestamp+ timestamp = source.get("metadata", {}).get("timestamp")+ if timestamp:+ if not most_recent_time or timestamp > most_recent_time:+ most_recent_time = timestamp+ most_recent_idx = i++ resolved_value = conflict.conflicting_values[most_recent_idx]+ sources_used = [conflict.sources[most_recent_idx].get("document", "unknown")]++ return ResolutionResult(+ conflict_id=conflict.conflict_id,+ resolved=True,+ resolved_value=resolved_value,+ confidence=0.8,+ sources_used=sources_used,+ resolution_notes="Resolved by most recent value"+ )++ def _resolve_by_first_seen(self, conflict: Conflict) -> ResolutionResult:+ """Resolve conflict by using first seen value."""+ if not conflict.conflicting_values:+ return ResolutionResult(+ conflict_id=conflict.conflict_id,+ resolved=False+ )++ resolved_value = conflict.conflicting_values[0]+ sources_used = [conflict.sources[0].get("document", "unknown")] if conflict.sources else []++ return ResolutionResult(+ conflict_id=conflict.conflict_id,+ resolved=True,+ resolved_value=resolved_value,+ confidence=0.7,+ sources_used=sources_used,+ resolution_notes="Resolved by first seen value"+ )++ def _resolve_by_confidence(self, conflict: Conflict) -> ResolutionResult:+ """Resolve conflict by using value with highest confidence."""+ if not conflict.sources:+ return ResolutionResult(+ conflict_id=conflict.conflict_id,+ resolved=False,+ resolution_notes="No source confidence data available"+ )++ # Find source with highest confidence+ max_confidence = 0.0+ best_idx = 0++ for i, source in enumerate(conflict.sources):+ confidence = source.get("confidence", 0.0)+ if confidence > max_confidence:+ max_confidence = confidence+ best_idx = i++ resolved_value = conflict.conflicting_values[best_idx]+ sources_used = [conflict.sources[best_idx].get("document", "unknown")]++ return ResolutionResult(+ conflict_id=conflict.conflict_id,+ resolved=True,+ resolved_value=resolved_value,+ confidence=max_confidence,+ sources_used=sources_used,+ resolution_notes=f"Resolved by highest confidence ({max_confidence:.2f})"+ )++ def _flag_for_manual_review(self, conflict: Conflict) -> ResolutionResult:+ """Flag conflict for manual review."""+ return ResolutionResult(+ conflict_id=conflict.conflict_id,+ resolved=False,+ resolution_notes="Flagged for manual review",+ metadata={"requires_manual_review": True, "severity": conflict.severity}+ )++ def _flag_for_expert_review(self, conflict: Conflict) -> ResolutionResult:+ """Flag conflict for expert review."""+ return ResolutionResult(+ conflict_id=conflict.conflict_id,+ resolved=False,+ resolution_notes="Flagged for expert review",+ metadata={"requires_expert_review": True, "severity": conflict.severity}+ )++ def set_resolution_rule(+ self,+ entity_id: str,+ property_name: str,+ strategy: ResolutionStrategy+ ) -> bool:+ """+ Set custom resolution rule for specific property.++ Args:+ entity_id: Entity identifier+ property_name: Property name+ strategy: Resolution strategy++ Returns:+ True if rule set successfully+ """+ rule_key = f"{entity_id}.{property_name}"+ self.resolution_rules[rule_key] = strategy+ self.logger.info(f"Set resolution rule: {rule_key} -> {strategy.value}")+ return True++ def get_resolution_history(self) -> List[ResolutionResult]:+ """+ Get conflict resolution history.++ Returns:+ List of resolution results+ """+ return self.resolution_history.copy()++ def get_resolution_statistics(self) -> Dict[str, Any]:+ """+ Get resolution statistics.++ Returns:+ Statistics dictionary+ """+ total = len(self.resolution_history)+ resolved = sum(1 for r in self.resolution_history if r.resolved)++ by_strategy = {}+ for result in self.resolution_history:+ strategy = result.resolution_strategy or "unknown"+ by_strategy[strategy] = by_strategy.get(strategy, 0) + 1++ return {+ "total_resolutions": total,+ "resolved_count": resolved,+ "unresolved_count": total - resolved,+ "resolution_rate": resolved / total if total > 0 else 0.0,+ "by_strategy": by_strategy+ }diff --git a/libs/semantica/conflicts/investigation_guide.py b/libs/semantica/conflicts/investigation_guide.pyindex 0b8f5764..f70d5c72 100644--- a/libs/semantica/conflicts/investigation_guide.py+++ b/libs/semantica/conflicts/investigation_guide.py@@ -5,10 +5,371 @@ Generates investigation guides for detected conflicts to helpdomain experts investigate and resolve discrepancies."""-# TODO: Implement investigation guide generation-# - Generate conflict investigation checklists-# - Identify conflicting source documents-# - Provide conflict context and history-# - Suggest investigation steps-# - Generate conflict summary reports-# - Support compliance audit workflows+from typing import Any, Dict, List, Optional+from dataclasses import dataclass, field+from datetime import datetime++from .conflict_detector import Conflict, ConflictType+from .source_tracker import SourceTracker+from ..utils.logging import get_logger+++@dataclass+class InvestigationStep:+ """Investigation step definition."""+ step_number: int+ description: str+ action: str+ expected_outcome: Optional[str] = None+ metadata: Dict[str, Any] = field(default_factory=dict)+++@dataclass+class InvestigationGuide:+ """Investigation guide for a conflict."""+ conflict_id: str+ conflict_summary: str+ severity: str+ conflicting_sources: List[Dict[str, Any]] = field(default_factory=list)+ investigation_steps: List[InvestigationStep] = field(default_factory=list)+ recommended_actions: List[str] = field(default_factory=list)+ context: Dict[str, Any] = field(default_factory=dict)+ generated_at: str = field(default_factory=lambda: datetime.now().isoformat())+++class InvestigationGuideGenerator:+ """+ Investigation guide generator for conflicts.++ • Generates conflict investigation checklists+ • Identifies conflicting source documents+ • Provides conflict context and history+ • Suggests investigation steps+ • Generates conflict summary reports+ • Supports compliance audit workflows+ """++ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):+ """+ Initialize investigation guide generator.++ Args:+ config: Configuration dictionary+ **kwargs: Additional configuration options:+ - source_tracker: Source tracker instance+ - include_traceability: Include traceability information+ """+ self.logger = get_logger("investigation_guide")+ self.config = config or {}+ self.config.update(kwargs)++ self.source_tracker = self.config.get("source_tracker") or SourceTracker()+ self.include_traceability = self.config.get("include_traceability", True)++ def generate_guide(+ self,+ conflict: Conflict,+ additional_context: Optional[Dict[str, Any]] = None+ ) -> InvestigationGuide:+ """+ Generate investigation guide for a conflict.++ Args:+ conflict: Conflict to investigate+ additional_context: Additional context information++ Returns:+ Investigation guide+ """+ guide = InvestigationGuide(+ conflict_id=conflict.conflict_id,+ conflict_summary=self._generate_summary(conflict),+ severity=conflict.severity,+ conflicting_sources=conflict.sources,+ investigation_steps=self._generate_investigation_steps(conflict),+ recommended_actions=self._generate_recommended_actions(conflict),+ context=additional_context or {}+ )++ return guide++ def generate_guides(+ self,+ conflicts: List[Conflict],+ additional_context: Optional[Dict[str, Any]] = None+ ) -> List[InvestigationGuide]:+ """+ Generate investigation guides for multiple conflicts.++ Args:+ conflicts: List of conflicts+ additional_context: Additional context information++ Returns:+ List of investigation guides+ """+ guides = []++ for conflict in conflicts:+ guide = self.generate_guide(conflict, additional_context)+ guides.append(guide)++ return guides++ def _generate_summary(self, conflict: Conflict) -> str:+ """Generate conflict summary."""+ parts = []++ parts.append(f"Conflict Type: {conflict.conflict_type.value}")++ if conflict.entity_id:+ parts.append(f"Entity: {conflict.entity_id}")++ if conflict.property_name:+ parts.append(f"Property: {conflict.property_name}")++ if conflict.conflicting_values:+ unique_values = list(set(str(v) for v in conflict.conflicting_values))+ parts.append(f"Conflicting Values: {', '.join(unique_values)}")++ parts.append(f"Severity: {conflict.severity}")++ if conflict.sources:+ source_docs = list(set(s.get("document", "unknown") for s in conflict.sources))+ parts.append(f"Sources: {', '.join(source_docs)}")++ return " | ".join(parts)++ def _generate_investigation_steps(+ self,+ conflict: Conflict+ ) -> List[InvestigationStep]:+ """Generate investigation steps."""+ steps = []++ # Step 1: Review conflict details+ steps.append(InvestigationStep(+ step_number=1,+ description="Review conflict details and context",+ action="Examine the conflict summary and identify the conflicting values",+ expected_outcome="Understanding of the nature and scope of the conflict"+ ))++ # Step 2: Identify source documents+ if conflict.sources:+ source_list = ", ".join(set(s.get("document", "unknown") for s in conflict.sources))+ steps.append(InvestigationStep(+ step_number=2,+ description="Identify all source documents",+ action=f"Locate and review the following source documents: {source_list}",+ expected_outcome="All source documents identified and accessible"+ ))++ # Step 3: Compare source documents+ if conflict.sources and len(conflict.sources) > 1:+ steps.append(InvestigationStep(+ step_number=3,+ description="Compare conflicting information across sources",+ action="Review each source document and note the specific value and context for each",+ expected_outcome="List of values and their sources with context"+ ))++ # Step 4: Check source credibility+ if conflict.sources:+ steps.append(InvestigationStep(+ step_number=4,+ description="Assess source credibility and reliability",+ action="Review source credibility scores and document metadata",+ expected_outcome="Source credibility assessment completed"+ ))++ # Step 5: Determine resolution+ steps.append(InvestigationStep(+ step_number=5,+ description="Determine resolution approach",+ action="Choose resolution strategy based on source credibility, recency, and business rules",+ expected_outcome="Resolution approach selected"+ ))++ # Step 6: Document resolution+ steps.append(InvestigationStep(+ step_number=6,+ description="Document resolution decision",+ action="Record the resolved value, resolution method, and rationale",+ expected_outcome="Resolution documented with traceability"+ ))++ return steps++ def _generate_recommended_actions(self, conflict: Conflict) -> List[str]:+ """Generate recommended actions."""+ actions = []++ # Severity-based actions+ if conflict.severity == "critical":+ actions.append("URGENT: Critical conflict requires immediate attention")+ actions.append("Escalate to domain expert or data owner")++ elif conflict.severity == "high":+ actions.append("High priority: Review within 24 hours")+ actions.append("Consult with subject matter expert")++ # Type-based actions+ if conflict.conflict_type == ConflictType.VALUE_CONFLICT:+ actions.append("Compare source documents side-by-side")+ actions.append("Check for data entry errors or typos")+ actions.append("Verify if values represent different time periods")++ elif conflict.conflict_type == ConflictType.TYPE_CONFLICT:+ actions.append("Review entity type definitions")+ actions.append("Check for classification errors")++ elif conflict.conflict_type == ConflictType.TEMPORAL_CONFLICT:+ actions.append("Check temporal context of each value")+ actions.append("Determine if conflict represents historical change")++ # Source-based actions+ if conflict.sources:+ source_docs = set(s.get("document", "unknown") for s in conflict.sources)+ if len(source_docs) > 1:+ actions.append(f"Review {len(source_docs)} conflicting source documents")+ actions.append("Identify most authoritative source")++ # Default actions+ if not actions:+ actions.append("Review conflict details and determine appropriate resolution")+ actions.append("Document resolution decision for future reference")++ return actions++ def generate_conflict_report(+ self,+ conflicts: List[Conflict],+ format: str = "detailed"+ ) -> Dict[str, Any]:+ """+ Generate comprehensive conflict report.++ Args:+ conflicts: List of conflicts+ format: Report format ('detailed', 'summary')++ Returns:+ Conflict report dictionary+ """+ guides = self.generate_guides(conflicts)++ report = {+ "generated_at": datetime.now().isoformat(),+ "total_conflicts": len(conflicts),+ "conflicts": []+ }++ for guide in guides:+ conflict_data = {+ "conflict_id": guide.conflict_id,+ "summary": guide.conflict_summary,+ "severity": guide.severity,+ "conflicting_sources": guide.conflicting_sources,+ "recommended_actions": guide.recommended_actions+ }++ if format == "detailed":+ conflict_data["investigation_steps"] = [+ {+ "step_number": step.step_number,+ "description": step.description,+ "action": step.action,+ "expected_outcome": step.expected_outcome+ }+ for step in guide.investigation_steps+ ]++ report["conflicts"].append(conflict_data)++ # Add summary statistics+ severity_counts = {}+ for conflict in conflicts:+ severity = conflict.severity+ severity_counts[severity] = severity_counts.get(severity, 0) + 1++ report["summary"] = {+ "by_severity": severity_counts,+ "critical_count": severity_counts.get("critical", 0),+ "high_count": severity_counts.get("high", 0),+ "medium_count": severity_counts.get("medium", 0),+ "low_count": severity_counts.get("low", 0)+ }++ return report++ def export_investigation_checklist(+ self,+ guide: InvestigationGuide,+ format: str = "text"+ ) -> str:+ """+ Export investigation guide as checklist.++ Args:+ guide: Investigation guide+ format: Export format ('text', 'markdown')++ Returns:+ Checklist string+ """+ if format == "markdown":+ lines = [+ f"# Investigation Guide: {guide.conflict_id}",+ "",+ f"**Conflict Summary:** {guide.conflict_summary}",+ f"**Severity:** {guide.severity}",+ "",+ "## Investigation Steps",+ ""+ ]++ for step in guide.investigation_steps:+ lines.append(f"### Step {step.step_number}: {step.description}")+ lines.append(f"- **Action:** {step.action}")+ if step.expected_outcome:+ lines.append(f"- **Expected Outcome:** {step.expected_outcome}")+ lines.append("")++ lines.extend([+ "## Recommended Actions",+ ""+ ])++ for action in guide.recommended_actions:+ lines.append(f"- {action}")++ return "\n".join(lines)++ else: # text format+ lines = [+ f"INVESTIGATION GUIDE: {guide.conflict_id}",+ "=" * 60,+ f"Conflict Summary: {guide.conflict_summary}",+ f"Severity: {guide.severity}",+ "",+ "INVESTIGATION STEPS:",+ ""+ ]++ for step in guide.investigation_steps:+ lines.append(f"Step {step.step_number}: {step.description}")+ lines.append(f" Action: {step.action}")+ if step.expected_outcome:+ lines.append(f" Expected Outcome: {step.expected_outcome}")+ lines.append("")++ lines.extend([+ "RECOMMENDED ACTIONS:",+ ""+ ])++ for action in guide.recommended_actions:+ lines.append(f" - {action}")++ return "\n".join(lines)diff --git a/libs/semantica/conflicts/source_tracker.py b/libs/semantica/conflicts/source_tracker.pyindex f90e1bf6..332913b4 100644--- a/libs/semantica/conflicts/source_tracker.py+++ b/libs/semantica/conflicts/source_tracker.py@@ -5,10 +5,447 @@ Tracks source information for entities and properties to enableconflict investigation and source disagreement analysis."""-# TODO: Implement source tracking for conflicts-# - Track source documents for each property value-# - Maintain source provenance for entities-# - Track source disagreements and conflicts-# - Generate source analysis reports-# - Support source credibility scoring-# - Enable traceability for conflict resolution+from typing import Any, Dict, List, Optional, Set+from dataclasses import dataclass, field+from datetime import datetime+from collections import defaultdict++from ..utils.exceptions import ValidationError+from ..utils.logging import get_logger+++@dataclass+class SourceReference:+ """Source reference for a property value."""+ document: str+ page: Optional[int] = None+ section: Optional[str] = None+ line: Optional[int] = None+ timestamp: Optional[datetime] = None+ confidence: float = 1.0+ metadata: Dict[str, Any] = field(default_factory=dict)+++@dataclass+class PropertySource:+ """Source information for a property value."""+ property_name: str+ value: Any+ sources: List[SourceReference] = field(default_factory=list)+ entity_id: Optional[str] = None+ metadata: Dict[str, Any] = field(default_factory=dict)+++class SourceTracker:+ """+ Source tracker for conflict detection.++ • Tracks source documents for each property value+ • Maintains source provenance for entities+ • Tracks source disagreements and conflicts+ • Generates source analysis reports+ • Supports source credibility scoring+ • Enables traceability for conflict resolution+ """++ def __init__(self, config: Optional[Dict[str, Any]] = None, **kwargs):+ """+ Initialize source tracker.++ Args:+ config: Configuration dictionary+ **kwargs: Additional configuration options+ """+ self.logger = get_logger("source_tracker")+ self.config = config or {}+ self.config.update(kwargs)++ # Entity -> Property -> PropertySource+ self.entity_sources: Dict[str, Dict[str, PropertySource]] = defaultdict(dict)++ # Relationship sources+ self.relationship_sources: Dict[str, List[SourceReference]] = defaultdict(list)++ # Source credibility scores+ self.source_credibility: Dict[str, float] = {}++ def track_entity_source(+ self,+ entity_id: str,+ source: SourceReference,+ **metadata+ ) -> bool:+ """+ Track source for an entity.++ Args:+ entity_id: Entity identifier+ source: Source reference+ **metadata: Additional metadata++ Returns:+ True if tracking successful+ """+ if entity_id not in self.entity_sources:+ self.entity_sources[entity_id] = {}++ # Store entity-level source+ if "_entity_sources" not in self.entity_sources[entity_id]:+ self.entity_sources[entity_id]["_entity_sources"] = PropertySource(+ property_name="_entity_sources",+ value=entity_id,+ entity_id=entity_id+ )++ self.entity_sources[entity_id]["_entity_sources"].sources.append(source)+ self.logger.debug(f"Tracked entity source: {entity_id} from {source.document}")+ return True++ def track_property_source(+ self,+ entity_id: str,+ property_name: str,+ value: Any,+ source: SourceReference,+ **metadata+ ) -> bool:+ """+ Track source for a property value.++ Args:+ entity_id: Entity identifier+ property_name: Property name+ value: Property value+ source: Source reference+ **metadata: Additional metadata++ Returns:+ True if tracking successful+ """+ if entity_id not in self.entity_sources:+ self.entity_sources[entity_id] = {}++ if property_name not in self.entity_sources[entity_id]:+ self.entity_sources[entity_id][property_name] = PropertySource(+ property_name=property_name,+ value=value,+ entity_id=entity_id,+ metadata=metadata+ )++ property_source = self.entity_sources[entity_id][property_name]++ # Add source if not already present+ source_exists = any(+ s.document == source.document and+ s.page == source.page and+ s.section == source.section+ for s in property_source.sources+ )++ if not source_exists:+ property_source.sources.append(source)++ # Update value if different (will be used for conflict detection)+ if property_source.value != value:+ property_source.value = value # Store latest value++ self.logger.debug(+ f"Tracked property source: {entity_id}.{property_name} = {value} "+ f"from {source.document}"+ )+ return True++ def track_relationship_source(+ self,+ relationship_id: str,+ source: SourceReference,+ **metadata+ ) -> bool:+ """+ Track source for a relationship.++ Args:+ relationship_id: Relationship identifier+ source: Source reference+ **metadata: Additional metadata++ Returns:+ True if tracking successful+ """+ source_exists = any(+ s.document == source.document and+ s.page == source.page+ for s in self.relationship_sources[relationship_id]+ )++ if not source_exists:+ self.relationship_sources[relationship_id].append(source)++ self.logger.debug(+ f"Tracked relationship source: {relationship_id} from {source.document}"+ )+ return True++ def get_entity_sources(self, entity_id: str) -> List[SourceReference]:+ """+ Get all sources for an entity.++ Args:+ entity_id: Entity identifier++ Returns:+ List of source references+ """+ sources = []++ if entity_id in self.entity_sources:+ # Get entity-level sources+ if "_entity_sources" in self.entity_sources[entity_id]:+ sources.extend(+ self.entity_sources[entity_id]["_entity_sources"].sources+ )++ # Get all property sources+ for prop_source in self.entity_sources[entity_id].values():+ sources.extend(prop_source.sources)++ # Deduplicate+ seen = set()+ unique_sources = []+ for source in sources:+ key = (source.document, source.page, source.section)+ if key not in seen:+ seen.add(key)+ unique_sources.append(source)++ return unique_sources++ def get_property_sources(+ self,+ entity_id: str,+ property_name: str+ ) -> Optional[PropertySource]:+ """+ Get sources for a specific property.++ Args:+ entity_id: Entity identifier+ property_name: Property name++ Returns:+ PropertySource or None if not found+ """+ if entity_id in self.entity_sources:+ return self.entity_sources[entity_id].get(property_name)+ return None++ def get_relationship_sources(self, relationship_id: str) -> List[SourceReference]:+ """+ Get sources for a relationship.++ Args:+ relationship_id: Relationship identifier++ Returns:+ List of source references+ """+ return self.relationship_sources.get(relationship_id, [])++ def find_source_disagreements(+ self,+ entity_id: str,+ property_name: str+ ) -> List[Dict[str, Any]]:+ """+ Find source disagreements for a property.++ Args:+ entity_id: Entity identifier+ property_name: Property name++ Returns:+ List of disagreement records+ """+ property_source = self.get_property_sources(entity_id, property_name)+ if not property_source or len(property_source.sources) < 2:+ return []++ # Group sources by value (if we have multiple values)+ # For now, we'll check if sources have different confidence or metadata+ disagreements = []++ sources = property_source.sources+ for i, source1 in enumerate(sources):+ for source2 in sources[i+1:]:+ # Check for disagreements in confidence, metadata, or document+ if (source1.document != source2.document or+ source1.confidence != source2.confidence):+ disagreements.append({+ "entity_id": entity_id,+ "property_name": property_name,+ "source1": {+ "document": source1.document,+ "page": source1.page,+ "confidence": source1.confidence+ },+ "source2": {+ "document": source2.document,+ "page": source2.page,+ "confidence": source2.confidence+ }+ })++ return disagreements++ def set_source_credibility(+ self,+ document: str,+ credibility: float+ ) -> bool:+ """+ Set credibility score for a source document.++ Args:+ document: Document identifier+ credibility: Credibility score (0.0 to 1.0)++ Returns:+ True if set successfully+ """+ if not 0.0 <= credibility <= 1.0:+ raise ValidationError("Credibility must be between 0.0 and 1.0")++ self.source_credibility[document] = credibility+ self.logger.info(f"Set credibility for {document}: {credibility}")+ return True++ def get_source_credibility(self, document: str) -> float:+ """+ Get credibility score for a source document.++ Args:+ document: Document identifier++ Returns:+ Credibility score (default: 0.5)+ """+ return self.source_credibility.get(document, 0.5)++ def generate_source_report(+ self,+ entity_id: Optional[str] = None+ ) -> Dict[str, Any]:+ """+ Generate source analysis report.++ Args:+ entity_id: Optional entity ID to filter by++ Returns:+ Source report dictionary+ """+ report = {+ "generated_at": datetime.now().isoformat(),+ "entities_tracked": 0,+ "properties_tracked": 0,+ "relationships_tracked": len(self.relationship_sources),+ "total_sources": 0,+ "source_credibility": dict(self.source_credibility),+ "entities": []+ }++ entities_to_report = [entity_id] if entity_id else list(self.entity_sources.keys())++ for eid in entities_to_report:+ if eid not in self.entity_sources:+ continue++ entity_info = {+ "entity_id": eid,+ "properties": [],+ "total_sources": 0+ }++ for prop_name, prop_source in self.entity_sources[eid].items():+ if prop_name == "_entity_sources":+ continue++ prop_info = {+ "property_name": prop_name,+ "value": prop_source.value,+ "sources": [+ {+ "document": s.document,+ "page": s.page,+ "section": s.section,+ "confidence": s.confidence,+ "credibility": self.get_source_credibility(s.document)+ }+ for s in prop_source.sources+ ],+ "source_count": len(prop_source.sources)+ }++ entity_info["properties"].append(prop_info)+ entity_info["total_sources"] += len(prop_source.sources)+ report["total_sources"] += len(prop_source.sources)++ if entity_info["properties"]:+ report["entities"].append(entity_info)+ report["entities_tracked"] += 1+ report["properties_tracked"] += len(entity_info["properties"])++ return report++ def get_traceability_chain(+ self,+ entity_id: str,+ property_name: Optional[str] = None+ ) -> List[Dict[str, Any]]:+ """+ Get traceability chain for an entity or property.++ Args:+ entity_id: Entity identifier+ property_name: Optional property name++ Returns:+ List of traceability records+ """+ chain = []++ if property_name:+ prop_source = self.get_property_sources(entity_id, property_name)+ if prop_source:+ for source in prop_source.sources:+ chain.append({+ "type": "property",+ "entity_id": entity_id,+ "property_name": property_name,+ "value": prop_source.value,+ "source": {+ "document": source.document,+ "page": source.page,+ "section": source.section,+ "confidence": source.confidence,+ "timestamp": source.timestamp.isoformat() if source.timestamp else None+ }+ })+ else:+ # Get all entity sources+ sources = self.get_entity_sources(entity_id)+ for source in sources:+ chain.append({+ "type": "entity",+ "entity_id": entity_id,+ "source": {+ "document": source.document,+ "page": source.page,+ "section": source.section,+ "confidence": source.confidence,+ "timestamp": source.timestamp.isoformat() if source.timestamp else None+ }+ })++ return chain