~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix: address all djpetti code review comments from PR #929
LearningCircuit9c1e8bc32272
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.jsonindex e007f8667d..47fd6861c2 100644--- a/src/local_deep_research/defaults/default_settings.json+++ b/src/local_deep_research/defaults/default_settings.json@@ -5318,7 +5318,7 @@"value": false,"visible": true},- "research_library.enable_txt_storage": {+ "research_library.enable_txt_storage": {"category": "research_library","description": "⚠️ PRIVACY WARNING: Text files will be stored unencrypted on disk for RAG/ChromaDB integration. This exposes document contents to anyone with filesystem access.","editable": true,diff --git a/src/local_deep_research/library/download_management/failure_classifier.py b/src/local_deep_research/library/download_management/failure_classifier.pyindex 32d345ca4f..163cb86a8f 100644--- a/src/local_deep_research/library/download_management/failure_classifier.py+++ b/src/local_deep_research/library/download_management/failure_classifier.py@@ -36,7 +36,7 @@ class BaseFailure(ABC):self.created_at = datetime.now(UTC)logger.debug(- f"[FAILURE_CLASSIFIER] Created {self.__class__.__name__}: {error_type} - {message}"+ f"Created {self.__class__.__name__}: {error_type} - {message}")def is_permanent(self) -> bool:diff --git a/src/local_deep_research/library/download_management/filters/resource_filter.py b/src/local_deep_research/library/download_management/filters/resource_filter.pyindex e85134281c..5e562be8cb 100644--- a/src/local_deep_research/library/download_management/filters/resource_filter.py+++ b/src/local_deep_research/library/download_management/filters/resource_filter.py@@ -26,7 +26,7 @@ class ResourceFilter:"""self.username = usernameself.retry_manager = RetryManager(username, password)- logger.info(f"[RESOURCE_FILTER] Initialized for user: {username}")+ logger.info(f"Initialized for user: {username}")def filter_downloadable_resources(self, resources: List, check_files: bool = Truediff --git a/src/local_deep_research/library/download_management/models/__init__.py b/src/local_deep_research/library/download_management/models/__init__.pyindex e609346cc3..0b830b9b7a 100644--- a/src/local_deep_research/library/download_management/models/__init__.py+++ b/src/local_deep_research/library/download_management/models/__init__.py@@ -5,6 +5,7 @@ Contains ORM models for tracking resource download status and retry logic."""from datetime import datetime, UTC+from enum import Enumfrom functools import partialfrom sqlalchemy import Column, Integer, String, Text, DateTimefrom sqlalchemy.ext.declarative import declarative_base@@ -12,6 +13,21 @@ from sqlalchemy.ext.declarative import declarative_baseBase = declarative_base()+class FailureType(str, Enum):+ """Enum for failure types - ensures consistency across the codebase"""++ NOT_FOUND = "not_found"+ FORBIDDEN = "forbidden"+ GONE = "gone"+ RATE_LIMITED = "rate_limited"+ SERVER_ERROR = "server_error"+ RECAPTCHA_PROTECTION = "recaptcha_protection"+ INCOMPATIBLE_FORMAT = "incompatible_format"+ TIMEOUT = "timeout"+ NETWORK_ERROR = "network_error"+ UNKNOWN_ERROR = "unknown_error"++class ResourceDownloadStatus(Base):"""Database model for tracking resource download status"""diff --git a/src/local_deep_research/library/download_management/retry_manager.py b/src/local_deep_research/library/download_management/retry_manager.pyindex 0213b2986f..06fb134b9d 100644--- a/src/local_deep_research/library/download_management/retry_manager.py+++ b/src/local_deep_research/library/download_management/retry_manager.py@@ -263,11 +263,18 @@ class RetryManager:Returns:Number of resources that had their daily counter reset"""- # This would be called by a daily cron job- logger.info(- "[RETRY_MANAGER] Daily retry counter reset would be called here"- )- return 0 # Implementation would reset today_retry_count in database+ with self.status_tracker._get_session() as session:+ # Reset all today_retry_count to 0+ from .models import ResourceDownloadStatus++ result = session.query(ResourceDownloadStatus).update(+ {"today_retry_count": 0, "updated_at": datetime.now(UTC)}+ )+ session.commit()+ logger.info(+ f"[RETRY_MANAGER] Reset daily retry counters for {result} resources"+ )+ return resultdef clear_old_permanent_failures(self, days: int = 30) -> int:"""diff --git a/src/local_deep_research/library/download_management/status_tracker.py b/src/local_deep_research/library/download_management/status_tracker.pyindex 245cd58687..db3896ec58 100644--- a/src/local_deep_research/library/download_management/status_tracker.py+++ b/src/local_deep_research/library/download_management/status_tracker.py@@ -12,6 +12,7 @@ from loguru import loggerfrom sqlalchemy.orm import sessionmaker, Sessionfrom .models import ResourceDownloadStatus, Base+from .failure_classifier import BaseFailureclass ResourceStatusTracker:@@ -46,7 +47,10 @@ class ResourceStatusTracker:return self.Session()def mark_failure(- self, resource_id: int, failure, session: Optional[Session] = None+ self,+ resource_id: int,+ failure: BaseFailure,+ session: Optional[Session] = None,) -> None:"""Mark a resource as failed with classification.diff --git a/src/local_deep_research/news/subscription_manager/scheduler.py b/src/local_deep_research/news/subscription_manager/scheduler.pyindex 59a8d80279..b0093673b4 100644--- a/src/local_deep_research/news/subscription_manager/scheduler.py+++ b/src/local_deep_research/news/subscription_manager/scheduler.py@@ -669,70 +669,59 @@ class NewsScheduler:from ...database.models.research import (ResearchResource,)- from ...database.session_context import (- get_user_db_session,- )download_service = DownloadService(username=username, password=password)- # Get all resources for this research- with get_user_db_session(- username, password- ) as resource_db:- resources = (- resource_db.query(ResearchResource)- .filter_by(research_id=research.id)- .all()- )- processed_count = 0- for resource in resources:- # We need to pass the password to the download service- # The DownloadService creates its own database sessions, so we need to ensure password is available- try:- success, error = (- download_service.download_as_text(- resource.id,- save_files=False,- )+ # Get all resources for this research (reuse existing db session)+ resources = (+ db.query(ResearchResource)+ .filter_by(research_id=research.id)+ .all()+ )+ processed_count = 0+ for resource in resources:+ # We need to pass the password to the download service+ # The DownloadService creates its own database sessions, so we need to ensure password is available+ try:+ success, error = (+ download_service.download_as_text(+ resource.id,+ save_files=False,)- if success:- processed_count += 1- logger.info(- f"[DOC_SCHEDULER] Successfully extracted text for resource {resource.id}"- )- else:- logger.warning(- f"[DOC_SCHEDULER] Failed to extract text for resource {resource.id}: {error}"- )- except Exception as resource_error:- logger.exception(- f"[DOC_SCHEDULER] Error processing resource {resource.id}: {resource_error}"+ )+ if success:+ processed_count += 1+ logger.info(+ f"[DOC_SCHEDULER] Successfully extracted text for resource {resource.id}")- logger.info(- f"[DOC_SCHEDULER] Text extraction completed for research {research.id}: {processed_count}/{len(resources)} resources processed"- )+ else:+ logger.warning(+ f"[DOC_SCHEDULER] Failed to extract text for resource {resource.id}: {error}"+ )+ except Exception as resource_error:+ logger.exception(+ f"[DOC_SCHEDULER] Error processing resource {resource.id}: {resource_error}"+ )+ logger.info(+ f"[DOC_SCHEDULER] Text extraction completed for research {research.id}: {processed_count}/{len(resources)} resources processed"+ )except Exception as e:logger.exception(f"[DOC_SCHEDULER] Failed to extract text for research {research.id}: {e}")if generate_rag:- logger.info(- f"[DOC_SCHEDULER] Generating RAG embeddings for research {research.id}"+ # NOTE: RAG generation is not yet implemented for scheduled document processing+ # RAG embeddings are currently handled automatically when documents are added+ # to the library through the regular upload flow.+ # TODO: Implement scheduled RAG generation for research documents+ logger.warning(+ f"[DOC_SCHEDULER] RAG generation requested for research {research.id} "+ f"but this feature is not yet implemented. RAG embeddings will need to be "+ f"generated manually through the library interface.")- try:- # RAG generation is typically handled automatically when documents are added to the library- # For now, we'll just log that RAG would be generated- logger.info(- f"[DOC_SCHEDULER] RAG generation would be triggered for research {research.id}"- )- # TODO: Implement actual RAG generation once we understand the RAG system better- except Exception as e:- logger.exception(- f"[DOC_SCHEDULER] Failed to generate RAG embeddings for research {research.id}: {e}"- )processed_count += 1logger.debug(diff --git a/src/local_deep_research/research_library/downloaders/arxiv.py b/src/local_deep_research/research_library/downloaders/arxiv.pyindex b1a323764c..d19f4dca89 100644--- a/src/local_deep_research/research_library/downloaders/arxiv.py+++ b/src/local_deep_research/research_library/downloaders/arxiv.py@@ -102,18 +102,13 @@ class ArxivDownloader(BaseDownloader):logger.info(f"Downloading arXiv PDF: {arxiv_id}")- # Use enhanced headers for arXiv to avoid reCAPTCHA+ # Use honest user agent - arXiv supports academic tools with proper identificationenhanced_headers = {- "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",- "Accept": "application/pdf,application/octet-stream,application/vnd.ms-pdf,application/x-pdf,application/x-bzpdf,application/x-gzpdf,*/*;q=0.9",+ "User-Agent": "Local-Deep-Research/1.0 (Academic Research Tool; https://github.com/LearningCircuit/local-deep-research)",+ "Accept": "application/pdf,application/octet-stream,*/*","Accept-Language": "en-US,en;q=0.9","Accept-Encoding": "gzip, deflate, br","Connection": "keep-alive",- "Upgrade-Insecure-Requests": "1",- "Sec-Fetch-Dest": "document",- "Sec-Fetch-Mode": "navigate",- "Sec-Fetch-Site": "none",- "Cache-Control": "max-age=0",}return super()._download_pdf(pdf_url, headers=enhanced_headers)diff --git a/src/local_deep_research/research_scheduler/document_scheduler.py b/src/local_deep_research/research_scheduler/document_scheduler.pyindex b1f7b491db..79ac36e5af 100644--- a/src/local_deep_research/research_scheduler/document_scheduler.py+++ b/src/local_deep_research/research_scheduler/document_scheduler.py@@ -6,6 +6,7 @@ This utility class interfaces with the NewsScheduler to provide document processfrom typing import Any, Dictfrom loguru import logger+from ..news.subscription_manager.scheduler import get_news_schedulerclass DocumentSchedulerUtil:@@ -32,9 +33,6 @@ class DocumentSchedulerUtil:Dictionary containing document processing status information"""try:- # Import NewsScheduler here to avoid circular imports- from ..news.subscription_manager.scheduler import get_news_scheduler-scheduler = get_news_scheduler()return scheduler.get_document_scheduler_status(username)@@ -64,9 +62,6 @@ class DocumentSchedulerUtil:Tuple of (success: bool, message: str)"""try:- # Import NewsScheduler here to avoid circular imports- from ..news.subscription_manager.scheduler import get_news_scheduler-scheduler = get_news_scheduler()success = scheduler.trigger_document_processing(username)diff --git a/src/local_deep_research/security/file_integrity/base_verifier.py b/src/local_deep_research/security/file_integrity/base_verifier.pyindex 21f36dff86..72b053dcbd 100644--- a/src/local_deep_research/security/file_integrity/base_verifier.py+++ b/src/local_deep_research/security/file_integrity/base_verifier.py@@ -6,10 +6,19 @@ Concrete implementations specify which files to verify and policies."""from abc import ABC, abstractmethod+from enum import Enumfrom pathlib import Pathimport hashlib+class FileType(str, Enum):+ """Enum for file types - ensures consistency across the codebase"""++ FAISS_INDEX = "faiss_index"+ PDF = "pdf"+ EXPORT = "export"++class BaseFileVerifier(ABC):"""Base class for file integrity verification.@@ -34,12 +43,12 @@ class BaseFileVerifier(ABC):pass@abstractmethod- def get_file_type(self) -> str:+ def get_file_type(self) -> FileType:"""Get the file type identifier for this verifier.Returns:- String identifier (e.g., 'faiss_index', 'pdf', 'export')+ FileType enum value"""passdiff --git a/src/local_deep_research/security/file_integrity/integrity_manager.py b/src/local_deep_research/security/file_integrity/integrity_manager.pyindex 7c9650a6da..abe9cd92ea 100644--- a/src/local_deep_research/security/file_integrity/integrity_manager.py+++ b/src/local_deep_research/security/file_integrity/integrity_manager.py@@ -73,6 +73,21 @@ class FileIntegrityManager:except Exception as e:logger.warning(f"[FILE_INTEGRITY] Startup cleanup failed: {e}")+ def _normalize_path(self, file_path: Path) -> str:+ """+ Normalize path for consistent storage and lookup.++ Resolves symlinks, makes absolute, and normalizes separators+ to ensure the same file is always represented the same way.++ Args:+ file_path: Path to normalize++ Returns:+ Normalized path string+ """+ return str(file_path.resolve())+def register_verifier(self, verifier: BaseFileVerifier) -> None:"""Register a file type verifier.@@ -116,12 +131,13 @@ class FileIntegrityManager:# Calculate checksum and get file statschecksum = verifier.calculate_checksum(file_path)file_stat = file_path.stat()+ normalized_path = self._normalize_path(file_path)with get_user_db_session(self.username, self.password) as session:- # Check if record exists+ # Check if record exists (using normalized path)record = (session.query(FileIntegrityRecord)- .filter_by(file_path=str(file_path))+ .filter_by(file_path=normalized_path).first())@@ -136,7 +152,7 @@ class FileIntegrityManager:else:# Create new recordrecord = FileIntegrityRecord(- file_path=str(file_path),+ file_path=normalized_path,file_type=verifier.get_file_type(),checksum=checksum,algorithm=verifier.get_algorithm(),@@ -176,10 +192,12 @@ class FileIntegrityManager:Returns:Tuple of (success, reason_if_failed)"""+ normalized_path = self._normalize_path(file_path)+with get_user_db_session(self.username, self.password) as session:record = (session.query(FileIntegrityRecord)- .filter_by(file_path=str(file_path))+ .filter_by(file_path=normalized_path).first())diff --git a/src/local_deep_research/security/file_integrity/verifiers/faiss_verifier.py b/src/local_deep_research/security/file_integrity/verifiers/faiss_verifier.pyindex 6f1a1c8839..4941b96269 100644--- a/src/local_deep_research/security/file_integrity/verifiers/faiss_verifier.py+++ b/src/local_deep_research/security/file_integrity/verifiers/faiss_verifier.py@@ -7,7 +7,7 @@ candidates for strict integrity verification.from pathlib import Path-from ..base_verifier import BaseFileVerifier+from ..base_verifier import BaseFileVerifier, FileTypeclass FAISSIndexVerifier(BaseFileVerifier):@@ -32,14 +32,14 @@ class FAISSIndexVerifier(BaseFileVerifier):"""return file_path.suffix.lower() == ".faiss"- def get_file_type(self) -> str:+ def get_file_type(self) -> FileType:"""Get file type identifier.Returns:- 'faiss_index'+ FileType.FAISS_INDEX"""- return "faiss_index"+ return FileType.FAISS_INDEXdef allows_modifications(self) -> bool:"""