diff --git a/deeptutor/api/main.py b/deeptutor/api/main.py index c3475a623..3c5b8bfe7 100644 --- a/deeptutor/api/main.py +++ b/deeptutor/api/main.py @@ -145,6 +145,13 @@ async def lifespan(app: FastAPI): except Exception as e: logger.warning(f"Failed to start cron service: {e}") + try: + from deeptutor.services.github_source.sync_service import get_sync_service + + await get_sync_service().start() + except Exception as e: + logger.warning(f"Failed to start GitHub source sync: {e}") + # Ping PocketBase if configured — logs a warning (not an error) if unreachable try: from deeptutor.services.pocketbase_client import ping_pocketbase @@ -183,6 +190,13 @@ async def lifespan(app: FastAPI): except Exception as e: logger.warning(f"Failed to stop cron service: {e}") + try: + from deeptutor.services.github_source.sync_service import get_sync_service + + await get_sync_service().stop() + except Exception as e: + logger.warning(f"Failed to stop GitHub source sync: {e}") + # Stop partners try: from deeptutor.services.partners import get_partner_manager diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.py index 3c2572710..c07bc9fac 100644 --- a/deeptutor/api/routers/knowledge.py +++ b/deeptutor/api/routers/knowledge.py @@ -2630,7 +2630,7 @@ async def upload_files( async def create_knowledge_base( background_tasks: BackgroundTasks, name: str = Form(...), - files: list[UploadFile] = File(...), + files: list[UploadFile] = File(default=[]), rag_provider: str = Form(DEFAULT_PROVIDER), pageindex_mode: str = Form(""), rel_paths: list[str] = Form(None), @@ -2707,6 +2707,37 @@ async def create_knowledge_base( logger.warning(f"KB {name} not found in config, registering manually") initializer._register_to_config() + # Fast path: no files uploaded — create an empty KB ready for web + # sources, GitHub sources, or later document uploads. + if not files: + progress_tracker.update( + ProgressStage.COMPLETED, + "Knowledge base created (no documents yet).", + current=0, + total=0, + ) + manager.update_kb_status( + name=name, + status="ready", + progress={ + "stage": "completed", + "message": "Knowledge base created (no documents yet).", + "percent": 100, + "current": 0, + "total": 0, + "timestamp": datetime.now().isoformat(), + "index_changed": True, + "index_action": "create", + }, + ) + logger.info(f"KB '{name}' created (no documents yet)") + return { + "message": f"Knowledge base '{name}' created (no documents yet).", + "name": name, + "files": [], + "task_id": None, + } + uploaded_files, _ = await _save_uploaded_files_off_loop( files, initializer.raw_dir, allowed_extensions=allowed_extensions, rel_paths=rel_paths ) @@ -3314,3 +3345,106 @@ async def sync_folder(kb_name: str, folder_id: str, background_tasks: Background raise HTTPException(status_code=404, detail=f"Knowledge base '{kb_name}' not found") except Exception as e: raise HTTPException(status_code=500, detail=str(e)) + + +class AddGitHubSourceRequest(BaseModel): + repo: str + branch: str = "main" + path: str = "" + glob: str = "*.md" + + +class GitHubSourceInfo(BaseModel): + id: str + repo: str + branch: str + path: str + glob: str + enabled: bool = True + last_synced_sha: str = "" + last_synced_at: str = "" + last_sync_status: str = "pending" + last_sync_error: str | None = None + files_synced: int = 0 + added_at: str = "" + + +@router.post("/{kb_name}/github-source", response_model=GitHubSourceInfo) +async def add_github_source(kb_name: str, request: AddGitHubSourceRequest): + try: + manager, resolved_name, _ = _writable_kb(kb_name) + info = manager.add_github_source( + resolved_name, request.repo, request.branch, request.path, request.glob + ) + return GitHubSourceInfo(**info) + except HTTPException: + raise + except ValueError as e: + raise HTTPException( + status_code=400 if "not found" not in str(e).lower() else 404, detail=str(e) + ) + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +@router.get("/{kb_name}/github-sources", response_model=list[GitHubSourceInfo]) +async def get_github_sources(kb_name: str): + try: + manager, resolved_name, _ = _writable_kb(kb_name) + return [GitHubSourceInfo(**s) for s in manager.get_github_sources(resolved_name)] + except HTTPException: + raise + except ValueError: + raise HTTPException(status_code=404, detail=f"KB '{kb_name}' not found") + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +@router.delete("/{kb_name}/github-source/{source_id}") +async def remove_github_source(kb_name: str, source_id: str): + try: + manager, resolved_name, _ = _writable_kb(kb_name) + if not manager.remove_github_source(resolved_name, source_id): + raise HTTPException(status_code=404, detail=f"Source '{source_id}' not found") + return {"message": "Removed", "source_id": source_id} + except HTTPException: + raise + except ValueError: + raise HTTPException(status_code=404, detail=f"KB '{kb_name}' not found") + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + +@router.post("/{kb_name}/sync-github") +async def sync_github_sources(kb_name: str): + try: + manager, resolved_name, kb_base_dir = _writable_kb(kb_name) + sources = manager.get_github_sources(resolved_name) + if not sources: + return {"message": "No GitHub sources", "results": []} + from deeptutor.services.github_source.sync import sync_source + + results = [] + for src in sources: + if not src.get("enabled", True): + continue + r = await sync_source(kb_name=resolved_name, source=src, base_dir=str(kb_base_dir)) + results.append( + { + "source_id": src.get("id"), + "repo": src.get("repo"), + "ok": r.ok, + "skipped": r.skipped, + "files_added": r.files_added, + "files_updated": r.files_updated, + "files_removed": r.files_removed, + "error": r.error or None, + } + ) + return {"message": f"Synced {len(results)} source(s)", "results": results} + except HTTPException: + raise + except ValueError: + raise HTTPException(status_code=404, detail=f"KB '{kb_name}' not found") + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) diff --git a/deeptutor/knowledge/add_documents.py b/deeptutor/knowledge/add_documents.py index 315d0be0c..68f6f40d6 100644 --- a/deeptutor/knowledge/add_documents.py +++ b/deeptutor/knowledge/add_documents.py @@ -13,7 +13,7 @@ import json import logging from pathlib import Path import shutil -from typing import List, Optional +from typing import TYPE_CHECKING, List, Optional from deeptutor.services.config import resolve_llm_runtime_config from deeptutor.services.file_io import atomic_write_json @@ -30,6 +30,9 @@ logger = logging.getLogger(__name__) DEFAULT_BASE_DIR = "./data/knowledge_bases" +if TYPE_CHECKING: + from deeptutor.knowledge.manager import KnowledgeBaseManager + @dataclass(frozen=True) class DocumentIndexFailure: @@ -385,6 +388,72 @@ class DocumentAdder: _write_metadata(self.metadata_file, metadata) +async def _bootstrap_index_from_files( + kb_name: str, + source_files: list[str], + base_dir: str, + manager: "KnowledgeBaseManager", +) -> int: + """Create a fresh index for an empty KB from the given source files. + + Called when :class:`DocumentAdder` rejects an add because the KB has no + existing index (it was created empty, e.g. via the no-files fast path or + a web/GitHub source sync before any documents were indexed). Uses + :meth:`RAGService.initialize` to build the index in one batch, then + records file hashes so subsequent incremental adds can detect duplicates. + """ + rag_service = RAGService(kb_base_dir=base_dir) + kb_dir = Path(base_dir) / kb_name + raw_dir = kb_dir / "raw" + metadata_file = kb_dir / "metadata.json" + + success = await rag_service.initialize(kb_name=kb_name, file_paths=source_files) + if not success: + raise RuntimeError( + f"Failed to initialize index for KB '{kb_name}' from {len(source_files)} file(s)" + ) + + # Record hashes so future syncs detect unchanged files. + metadata = _read_metadata(metadata_file) + hashes = metadata.setdefault("file_hashes", {}) + for fpath_str in source_files: + fpath = Path(fpath_str) + sha = hashlib.sha256() + with open(fpath, "rb") as fh: + for block in iter(lambda: fh.read(65536), b""): + sha.update(block) + hashes[_raw_hash_key(fpath, raw_dir)] = sha.hexdigest() + metadata["rag_provider"] = rag_service._resolve_provider(kb_name) + metadata["needs_reindex"] = False + ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + metadata["last_updated"] = ts + metadata["last_indexed_at"] = ts + metadata["last_indexed_count"] = len(source_files) + metadata["last_indexed_action"] = "create" + _write_metadata(metadata_file, metadata) + + indexed = len(source_files) + manager.update_kb_status( + name=kb_name, + status="ready", + progress={ + "stage": "completed", + "message": f"Initialized index with {indexed} file(s).", + "percent": 100, + "current": indexed, + "total": max(indexed, 1), + "file_name": "", + "error": None, + "timestamp": datetime.now().isoformat(), + "indexed_count": indexed, + "index_changed": True, + "index_action": "create", + }, + ) + logger.info("Bootstrapped index for empty KB '%s' with %d file(s)", kb_name, indexed) + return indexed + + async def add_documents( kb_name: str, source_files: list[str], @@ -413,12 +482,25 @@ async def add_documents( }, ) - adder = DocumentAdder( - kb_name=kb_name, - base_dir=base_dir, - api_key=api_key, - base_url=base_url, - ) + try: + adder = DocumentAdder( + kb_name=kb_name, + base_dir=base_dir, + api_key=api_key, + base_url=base_url, + ) + except ValueError as exc: + if "not initialized" not in str(exc).lower() or not source_files: + raise + # Empty KB (created without initial documents): bootstrap the + # index from these files instead of erroring. + return await _bootstrap_index_from_files( + kb_name=kb_name, + source_files=source_files, + base_dir=base_dir, + manager=manager, + ) + new_files = adder.add_documents(source_files, allow_duplicates=allow_duplicates) if not new_files: manager.update_kb_status( diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.py index 23ee4bc4f..d9a41c5e0 100644 --- a/deeptutor/knowledge/manager.py +++ b/deeptutor/knowledge/manager.py @@ -1886,6 +1886,104 @@ class KnowledgeBaseManager: atomic_write_json(metadata_file, metadata) break + # ------------------------------------------------------------------ + # GitHub source management + # ------------------------------------------------------------------ + + def add_github_source(self, kb_name, repo, branch="main", path="", glob="*.md"): + """Register a GitHub repo as a document source for a KB.""" + if kb_name not in self.list_knowledge_bases(): + raise ValueError(f"Knowledge base not found: {kb_name}") + repo_clean = repo.strip().rstrip("/") + if repo_clean.endswith(".git"): + repo_clean = repo_clean[:-4] + if "github.com/" in repo_clean: + repo_clean = repo_clean.split("github.com/", 1)[-1] + repo_clean = repo_clean.strip("/") + source_id = hashlib.md5( # noqa: S324 + f"{repo_clean}:{branch}:{path}".encode(), usedforsecurity=False + ).hexdigest()[:8] + kb_dir = self.base_dir / kb_name + metadata_file = kb_dir / "metadata.json" + metadata = self._read_kb_metadata(metadata_file) + sources = metadata.get("github_sources", []) + for existing in sources: + if existing.get("id") == source_id: + return existing + source_info = { + "id": source_id, + "repo": repo_clean, + "branch": branch, + "path": path, + "glob": glob, + "enabled": True, + "last_synced_sha": "", + "last_synced_at": "", + "last_sync_status": "pending", + "last_sync_error": None, + "files_synced": 0, + "added_at": datetime.now().isoformat(), + } + sources.append(source_info) + metadata["github_sources"] = sources + atomic_write_json(metadata_file, metadata) + return source_info + + def remove_github_source(self, kb_name, source_id): + """Remove a GitHub source from a KB.""" + if kb_name not in self.list_knowledge_bases(): + raise ValueError(f"Knowledge base not found: {kb_name}") + metadata_file = self.base_dir / kb_name / "metadata.json" + metadata = self._read_kb_metadata(metadata_file) + sources = metadata.get("github_sources", []) + new_sources = [s for s in sources if s.get("id") != source_id] + if len(new_sources) == len(sources): + return False + metadata["github_sources"] = new_sources + atomic_write_json(metadata_file, metadata) + return True + + def get_github_sources(self, kb_name): + """Return all GitHub sources registered for a KB.""" + if kb_name not in self.list_knowledge_bases(): + raise ValueError(f"Knowledge base not found: {kb_name}") + metadata_file = self.base_dir / kb_name / "metadata.json" + metadata = self._read_kb_metadata(metadata_file) + return metadata.get("github_sources", []) + + def update_github_source_state(self, kb_name, source_id, **fields): + """Persist sync state fields into a GitHub source entry.""" + if kb_name not in self.list_knowledge_bases(): + raise ValueError(f"Knowledge base not found: {kb_name}") + metadata_file = self.base_dir / kb_name / "metadata.json" + metadata = self._read_kb_metadata(metadata_file) + sources = metadata.get("github_sources", []) + for src in sources: + if src.get("id") == source_id: + src.update(fields) + atomic_write_json(metadata_file, metadata) + return + + def get_all_github_sources(self): + """Scan every KB and return (kb_name, source_dict) pairs.""" + result = [] + for kb_name in self.list_knowledge_bases(): + for src in self.get_github_sources(kb_name): + result.append((kb_name, src)) + return result + + @staticmethod + def _read_kb_metadata(metadata_file): + """Load metadata.json, returning {} on absence or parse error.""" + if not metadata_file.exists(): + return {} + try: + with open(metadata_file, encoding="utf-8") as f: + data = json.load(f) + except Exception: + return {} + return data if isinstance(data, dict) else {} + def main(): """Command-line interface for knowledge base manager""" diff --git a/deeptutor/services/base_sync.py b/deeptutor/services/base_sync.py new file mode 100644 index 000000000..7d95e19e7 --- /dev/null +++ b/deeptutor/services/base_sync.py @@ -0,0 +1,105 @@ +"""Abstract base class for background source-sync services. + +Source-sync services share lifecycle management (start/stop/event-loop) +and staleness detection logic. This module provides the shared +implementation so subclasses only need to implement ``_sync_one_cycle``. +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +import asyncio +from datetime import datetime, timezone +import logging + +logger = logging.getLogger(__name__) + +_CHECK_INTERVAL_SECONDS = 3600 +_DEFAULT_STALE_HOURS = 24 + + +def is_stale(source: dict, *, stale_hours: float = _DEFAULT_STALE_HOURS) -> bool: + """Return True if *source* hasn't been synced within *stale_hours*.""" + last = source.get("last_synced_at") or "" + if not last: + return True + try: + dt = datetime.fromisoformat(last) + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + except Exception: + return True + age = (datetime.now(timezone.utc) - dt).total_seconds() + return age >= stale_hours * 3600 + + +def default_base_dir() -> str: + """Return the default knowledge-base directory for the current project.""" + try: + from deeptutor.services.path_service import get_path_service + + return str(get_path_service().project_root / "data" / "knowledge_bases") + except Exception: + from deeptutor.knowledge.add_documents import DEFAULT_BASE_DIR + + return DEFAULT_BASE_DIR + + +class BaseSourceSyncService(ABC): + """Abstract base for periodic source-sync background services. + + Subclasses implement :meth:`_sync_one_cycle` (the per-iteration work) + and optionally override :attr:`task_name` for logging. + """ + + def __init__( + self, *, base_dir: str | None = None, check_interval_s: int = _CHECK_INTERVAL_SECONDS + ): + self._base_dir = base_dir + self._check_interval_s = check_interval_s + self._task: asyncio.Task | None = None + self._running = False + + @property + def task_name(self) -> str: + """Name used for the asyncio task (override in subclasses).""" + return "source-sync" + + @property + def effective_base_dir(self) -> str: + return self._base_dir or default_base_dir() + + # -- lifecycle (shared, concrete) -------------------------------- + + async def start(self) -> None: + if self._running: + return + self._running = True + self._task = asyncio.create_task(self._loop(), name=self.task_name) + logger.info("%s started", self.__class__.__name__) + + async def stop(self) -> None: + self._running = False + if self._task and not self._task.done(): + self._task.cancel() + try: + await self._task + except asyncio.CancelledError: + pass + self._task = None + logger.info("%s stopped", self.__class__.__name__) + + async def _loop(self) -> None: + while self._running: + try: + await self._sync_one_cycle() + except Exception: + logger.exception("%s loop error", self.__class__.__name__) + await asyncio.sleep(self._check_interval_s) + + # -- to be implemented by subclasses ----------------------------- + + @abstractmethod + async def _sync_one_cycle(self) -> None: + """Run one pass of syncing. Called repeatedly by the loop.""" + ... diff --git a/deeptutor/services/github_source/__init__.py b/deeptutor/services/github_source/__init__.py new file mode 100644 index 000000000..8aacb2f9a --- /dev/null +++ b/deeptutor/services/github_source/__init__.py @@ -0,0 +1,5 @@ +"""GitHub-source sync subsystem: pull Markdown from GitHub repos into KBs.""" + +from deeptutor.services.github_source.sync_service import get_sync_service + +__all__ = ["get_sync_service"] diff --git a/deeptutor/services/github_source/client.py b/deeptutor/services/github_source/client.py new file mode 100644 index 000000000..58abb2cef --- /dev/null +++ b/deeptutor/services/github_source/client.py @@ -0,0 +1,164 @@ +"""Minimal async GitHub REST API client used by the KB source-sync engine. + +Self-contained, depends only on ``httpx`` (already a project dependency). +No ``gh`` or ``git`` CLI required. A ``GITHUB_TOKEN`` environment variable +is optional but recommended — it lifts the unauthenticated rate limit from +60 to 5 000 requests/hour and enables private-repo access. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import logging +import os +from typing import Any + +import httpx + +logger = logging.getLogger(__name__) + +GITHUB_API_BASE = "https://api.github.com" +DEFAULT_TIMEOUT_S = 30.0 +MAX_FILE_BYTES = 2 * 1024 * 1024 # 2 MB cap per individual file download + + +@dataclass(frozen=True) +class TreeEntry: + """One entry from a GitHub tree listing.""" + + path: str + sha: str + type: str # "blob" | "tree" + + +@dataclass(frozen=True) +class FileChange: + """One file changed between two commits.""" + + path: str + status: str # "added" | "removed" | "modified" | "renamed" | ... + sha: str + + +@dataclass(frozen=True) +class GitHubAPIError(Exception): + """Raised when the GitHub API returns a non-2xx response.""" + + status_code: int + message: str + + def __str__(self) -> str: + return f"GitHub API {self.status_code}: {self.message}" + + +def _token() -> str | None: + return os.environ.get("GITHUB_TOKEN") or None + + +def _headers() -> dict[str, str]: + h: dict[str, str] = { + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "DeepTutor/1.0 (+https://hkuds.dev/deeptutor)", + } + token = _token() + if token: + h["Authorization"] = f"Bearer {token}" + return h + + +class GitHubClient: + """Thin async wrapper around the handful of REST endpoints we need.""" + + def __init__( + self, + *, + timeout_s: float = DEFAULT_TIMEOUT_S, + client_factory: Any = None, + ) -> None: + self._timeout_s = timeout_s + self._client_factory = client_factory + + async def _request_json(self, method: str, url: str, **kw: Any) -> Any: + factory = self._client_factory or (lambda: httpx.AsyncClient(timeout=self._timeout_s)) + async with factory() as client: + resp = await client.request(method, url, headers=_headers(), **kw) + if resp.status_code >= 400: + try: + body = resp.json() + msg = body.get("message", resp.text[:500]) + except Exception: + msg = resp.text[:500] + raise GitHubAPIError(resp.status_code, str(msg)) + return resp.json() + + async def _request_bytes(self, url: str, **kw: Any) -> bytes: + factory = self._client_factory or (lambda: httpx.AsyncClient(timeout=self._timeout_s)) + async with factory() as client: + resp = await client.get(url, headers=_headers(), **kw) + if resp.status_code >= 400: + raise GitHubAPIError(resp.status_code, resp.text[:500]) + return resp.content + + async def get_default_branch(self, repo: str) -> str: + data = await self._request_json("GET", f"{GITHUB_API_BASE}/repos/{repo}") + return data.get("default_branch", "main") + + async def get_latest_commit_sha(self, repo: str, branch: str) -> str: + data = await self._request_json("GET", f"{GITHUB_API_BASE}/repos/{repo}/commits/{branch}") + return data["sha"] + + async def get_tree( + self, + repo: str, + branch: str, + *, + path_prefix: str = "", + glob: str = "*.md", + ) -> list[TreeEntry]: + data = await self._request_json( + "GET", + f"{GITHUB_API_BASE}/repos/{repo}/git/trees/{branch}", + params={"recursive": "1"}, + ) + entries: list[TreeEntry] = [] + prefix = path_prefix.strip("/") + for item in data.get("tree", []): + if item.get("type") != "blob": + continue + p = item.get("path", "") + if prefix and not p.startswith(prefix + "/") and p != prefix: + continue + if not _match_glob(p, glob): + continue + entries.append(TreeEntry(path=p, sha=item.get("sha", ""), type="blob")) + return entries + + async def compare_commits(self, repo: str, base: str, head: str) -> list[FileChange]: + data = await self._request_json( + "GET", + f"{GITHUB_API_BASE}/repos/{repo}/compare/{base}...{head}", + ) + changes: list[FileChange] = [] + for item in data.get("files", []): + changes.append( + FileChange( + path=item.get("filename", ""), + status=item.get("status", "modified"), + sha=item.get("sha", ""), + ) + ) + return changes + + async def download_file(self, repo: str, path: str, ref: str) -> bytes: + url = f"https://raw.githubusercontent.com/{repo}/{ref}/{path}" + content = await self._request_bytes(url) + if len(content) > MAX_FILE_BYTES: + content = content[:MAX_FILE_BYTES] + return content + + +def _match_glob(path: str, glob: str) -> bool: + import fnmatch + + return fnmatch.fnmatch(path, glob) or fnmatch.fnmatch(path.rsplit("/", 1)[-1], glob) diff --git a/deeptutor/services/github_source/sync.py b/deeptutor/services/github_source/sync.py new file mode 100644 index 000000000..a4f1e4804 --- /dev/null +++ b/deeptutor/services/github_source/sync.py @@ -0,0 +1,230 @@ +"""Core sync logic: pull Markdown from a GitHub repo into a KB's raw/ dir.""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime, timezone +import logging +from pathlib import Path + +from deeptutor.knowledge.add_documents import DEFAULT_BASE_DIR +from deeptutor.services.github_source.client import ( + GitHubAPIError, + GitHubClient, +) + +logger = logging.getLogger(__name__) + +SYNC_INTERVAL_HOURS = 24 +MARKDOWN_EXTENSIONS = (".md", ".markdown") + + +@dataclass +class SyncResult: + ok: bool + skipped: bool = False + files_added: int = 0 + files_updated: int = 0 + files_removed: int = 0 + error: str = "" + + +def _utcnow_iso() -> str: + return datetime.now(timezone.utc).isoformat() + + +def _is_markdown(path: str) -> bool: + return path.lower().endswith(MARKDOWN_EXTENSIONS) + + +def _raw_rel_path(github_path: str, path_prefix: str) -> str: + prefix = path_prefix.strip("/") + if prefix and github_path.startswith(prefix + "/"): + return github_path[len(prefix) + 1 :] + return github_path + + +def _contained_dest(raw_dir: Path, rel: str) -> Path | None: + """Resolve *rel* under *raw_dir*, or ``None`` if it escapes. + + ``rel`` comes from the GitHub API's tree/compare response, so it is remote + input. Two shapes would otherwise write outside the KB: a ``..`` segment, + and — more quietly — an absolute path, because ``Path("/kb") / "/etc/x"`` + is ``/etc/x``, silently discarding the base. git rejects both in tree + entries today, but a downloader must not depend on the remote to enforce + where it writes. + """ + candidate = (raw_dir / rel).resolve() + root = raw_dir.resolve() + if candidate != root and root not in candidate.parents: + logger.warning("GitHub sync: refusing path outside the KB raw dir: %s", rel) + return None + return candidate + + +def _filter_markdown_changes(changes, path_prefix, glob): + from fnmatch import fnmatch + + prefix = path_prefix.strip("/") + result = [] + for ch in changes: + p = ch.path + if prefix and not p.startswith(prefix + "/") and p != prefix: + continue + if not (_is_markdown(p) and (fnmatch(p, glob) or fnmatch(p.rsplit("/", 1)[-1], glob))): + continue + result.append(ch) + return result + + +def _filter_markdown_entries(entries, path_prefix, glob): + from fnmatch import fnmatch + + prefix = path_prefix.strip("/") + result = [] + for e in entries: + p = e.path + if prefix and not p.startswith(prefix + "/") and p != prefix: + continue + if not (_is_markdown(p) and (fnmatch(p, glob) or fnmatch(p.rsplit("/", 1)[-1], glob))): + continue + result.append(e) + return result + + +async def sync_source(kb_name, source, *, base_dir=DEFAULT_BASE_DIR, client=None): + client = client or GitHubClient() + kb_dir = Path(base_dir) / kb_name + raw_dir = kb_dir / "raw" + raw_dir.mkdir(parents=True, exist_ok=True) + + repo = source["repo"] + branch = source.get("branch") or "main" + path_prefix = source.get("path") or "" + glob = source.get("glob") or "*.md" + old_sha = source.get("last_synced_sha") or "" + + try: + latest_sha = await client.get_latest_commit_sha(repo, branch) + except GitHubAPIError as exc: + return SyncResult(ok=False, error=str(exc)) + except Exception as exc: + return SyncResult(ok=False, error=f"Failed to fetch latest SHA: {exc}") + + if old_sha and old_sha == latest_sha: + return SyncResult(ok=True, skipped=True) + + try: + if not old_sha: + result = await _full_sync( + client, kb_name, raw_dir, repo, branch, path_prefix, glob, latest_sha, base_dir + ) + else: + result = await _incremental_sync( + client, + kb_name, + raw_dir, + repo, + branch, + path_prefix, + glob, + old_sha, + latest_sha, + base_dir, + ) + except GitHubAPIError as exc: + return SyncResult(ok=False, error=str(exc)) + except Exception as exc: + return SyncResult(ok=False, error=str(exc)) + + if not result.ok: + return result + + from deeptutor.knowledge.manager import KnowledgeBaseManager + + manager = KnowledgeBaseManager(base_dir=base_dir) + manager.update_github_source_state( + kb_name=kb_name, + source_id=source["id"], + last_synced_sha=latest_sha, + last_synced_at=_utcnow_iso(), + last_sync_status="success", + last_sync_error=None, + files_synced=result.files_added + result.files_updated, + ) + return result + + +async def _full_sync( + client, kb_name, raw_dir, repo, branch, path_prefix, glob, latest_sha, base_dir +): + tree = await client.get_tree(repo, branch, path_prefix=path_prefix, glob=glob) + entries = _filter_markdown_entries(tree, path_prefix, glob) + downloaded = [] + for entry in entries: + rel = _raw_rel_path(entry.path, path_prefix) + dest = _contained_dest(raw_dir, rel) + if dest is None: + continue + dest.parent.mkdir(parents=True, exist_ok=True) + content = await client.download_file(repo, entry.path, latest_sha) + dest.write_bytes(content) + downloaded.append(str(dest)) + if downloaded: + await _index_files(kb_name, downloaded, base_dir) + return SyncResult(ok=True, files_added=len(downloaded)) + + +async def _incremental_sync( + client, kb_name, raw_dir, repo, branch, path_prefix, glob, old_sha, new_sha, base_dir +): + all_changes = await client.compare_commits(repo, old_sha, new_sha) + changes = _filter_markdown_changes(all_changes, path_prefix, glob) + added_or_modified = [] + removed = [] + for ch in changes: + rel = _raw_rel_path(ch.path, path_prefix) + if ch.status == "removed": + removed.append(rel) + else: + added_or_modified.append(ch.path) + downloaded = [] + for gh_path in added_or_modified: + rel = _raw_rel_path(gh_path, path_prefix) + dest = _contained_dest(raw_dir, rel) + if dest is None: + continue + content = await client.download_file(repo, gh_path, new_sha) + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(content) + downloaded.append(str(dest)) + if downloaded: + await _index_files(kb_name, downloaded, base_dir) + removed_count = 0 + for rel in removed: + target = _contained_dest(raw_dir, rel) + if target is not None and target.exists(): + try: + from deeptutor.knowledge.add_documents import remove_raw_document + + kb_dir = Path(base_dir) / kb_name + remove_raw_document(kb_dir, target) + removed_count += 1 + except Exception as exc: + logger.warning("Failed to remove %s: %s", rel, exc) + return SyncResult(ok=True, files_added=len(downloaded), files_removed=removed_count) + + +async def _index_files(kb_name, file_paths, base_dir): + if not file_paths: + return 0 + try: + from deeptutor.knowledge.add_documents import add_documents + + count = await add_documents( + kb_name=kb_name, source_files=file_paths, base_dir=base_dir, allow_duplicates=False + ) + return count or 0 + except Exception as exc: + logger.warning("Indexing failed: %s", exc) + return 0 diff --git a/deeptutor/services/github_source/sync_service.py b/deeptutor/services/github_source/sync_service.py new file mode 100644 index 000000000..c291ada6c --- /dev/null +++ b/deeptutor/services/github_source/sync_service.py @@ -0,0 +1,71 @@ +"""Background service that periodically syncs GitHub sources into KBs.""" + +from __future__ import annotations + +from datetime import datetime, timezone +import logging + +from deeptutor.services.base_sync import BaseSourceSyncService, is_stale +from deeptutor.services.github_source.sync import SYNC_INTERVAL_HOURS + +logger = logging.getLogger(__name__) + + +class GitHubSourceSyncService(BaseSourceSyncService): + """Periodically syncs all GitHub sources.""" + + def __init__(self, *, base_dir=None, client=None, check_interval_s=3600): + super().__init__(base_dir=base_dir, check_interval_s=check_interval_s) + self._client = client + + @property + def task_name(self) -> str: + return "github-source-sync" + + async def _sync_one_cycle(self) -> None: + from deeptutor.knowledge.manager import KnowledgeBaseManager + from deeptutor.services.github_source.sync import sync_source + + base_dir = self.effective_base_dir + manager = KnowledgeBaseManager(base_dir=base_dir) + + all_sources = manager.get_all_github_sources() + for kb_name, source in all_sources: + if not source.get("enabled", True): + continue + if not is_stale(source, stale_hours=SYNC_INTERVAL_HOURS): + continue + sid = source.get("id", "?") + try: + result = await sync_source( + kb_name=kb_name, + source=source, + base_dir=base_dir, + client=self._client, + ) + if not result.ok: + manager.update_github_source_state( + kb_name=kb_name, + source_id=sid, + last_sync_status="error", + last_sync_error=result.error, + last_synced_at=datetime.now(timezone.utc).isoformat(), + ) + except Exception as exc: + manager.update_github_source_state( + kb_name=kb_name, + source_id=sid, + last_sync_status="error", + last_sync_error=str(exc), + last_synced_at=datetime.now(timezone.utc).isoformat(), + ) + + +_sync_service = None + + +def get_sync_service(): + global _sync_service + if _sync_service is None: + _sync_service = GitHubSourceSyncService() + return _sync_service diff --git a/deeptutor_cli/kb.py b/deeptutor_cli/kb.py index 5e59ae2c9..5867797d4 100644 --- a/deeptutor_cli/kb.py +++ b/deeptutor_cli/kb.py @@ -313,3 +313,102 @@ def register(app: typer.Typer) -> None: provider = str(result.get("provider", DEFAULT_PROVIDER)) console.print(f"[bold]Provider:[/] {provider}") console.print(f"[bold]Answer:[/]\n{answer}") + + # ── GitHub source commands ────────────────────────────────────── + + @app.command("add-github-source") + def kb_add_github_source( + name: str = typer.Argument(..., help="KB name."), + repo: str = typer.Option(..., "--repo", "-r", help="GitHub repo as owner/name or URL."), + branch: str = typer.Option("main", "--branch", "-b", help="Branch to track."), + path: str = typer.Option("", "--path", "-p", help="Subdirectory prefix (e.g. docs/)."), + glob: str = typer.Option("*.md", "--glob", "-g", help="File glob pattern."), + ) -> None: + """Add a GitHub repo as a Markdown document source for a KB.""" + mgr = _get_kb_manager() + if name not in mgr.list_knowledge_bases(): + console.print(f"[red]Knowledge base '{name}' not found.[/]") + raise typer.Exit(code=1) + try: + info = mgr.add_github_source(name, repo, branch, path, glob) + except Exception as exc: + console.print(f"[red]Failed: {exc}[/]") + raise typer.Exit(code=1) from exc + console.print("[green]GitHub source added:[/]") + console.print_json(json.dumps(info, ensure_ascii=False)) + + @app.command("remove-github-source") + def kb_remove_github_source( + name: str = typer.Argument(..., help="KB name."), + source_id: str = typer.Option(..., "--source-id", "-s", help="Source ID to remove."), + ) -> None: + """Remove a GitHub source from a KB.""" + mgr = _get_kb_manager() + ok = mgr.remove_github_source(name, source_id) + if ok: + console.print(f"[green]Removed '{source_id}'.[/]") + else: + console.print(f"[yellow]Source '{source_id}' not found.[/]") + + @app.command("list-sources") + def kb_list_sources( + name: str = typer.Argument(..., help="KB name."), + ) -> None: + """List GitHub sources for a KB.""" + mgr = _get_kb_manager() + if name not in mgr.list_knowledge_bases(): + console.print(f"[red]Knowledge base '{name}' not found.[/]") + raise typer.Exit(code=1) + + gh_sources = mgr.get_github_sources(name) + + if not gh_sources: + console.print("[dim]No sources for this KB.[/]") + return + + table = Table(title=f"GitHub Sources - {name}") + table.add_column("ID", style="dim") + table.add_column("Repo") + table.add_column("Branch") + table.add_column("Status") + table.add_column("Files", justify="right") + for source in gh_sources: + table.add_row( + source.get("id", ""), + source.get("repo", ""), + source.get("branch", ""), + source.get("last_sync_status", "pending"), + str(source.get("files_synced", 0)), + ) + console.print(table) + + @app.command("sync") + def kb_sync(name: str = typer.Argument(..., help="KB name.")) -> None: + """Immediately sync all GitHub sources for a KB.""" + mgr = _get_kb_manager() + if name not in mgr.list_knowledge_bases(): + console.print(f"[red]Knowledge base '{name}' not found.[/]") + raise typer.Exit(code=1) + + gh_sources = mgr.get_github_sources(name) + if not gh_sources: + console.print("[yellow]No sources to sync.[/]") + raise typer.Exit(code=0) + + from deeptutor.services.github_source.sync import sync_source as gh_sync + + for src in gh_sources: + if not src.get("enabled", True): + continue + console.print(f"Syncing GitHub [bold]{src.get('repo')}[/] ...") + try: + r = asyncio.run(gh_sync(kb_name=name, source=src, base_dir=str(mgr.base_dir))) + except Exception as exc: + console.print(f" [red]Error: {exc}[/]") + continue + if r.skipped: + console.print(" [dim]Up to date.[/]") + elif r.ok: + console.print(f" [green]+{r.files_added} ~{r.files_updated} -{r.files_removed}[/]") + else: + console.print(f" [red]Failed: {r.error}[/]") diff --git a/tests/knowledge/test_github_source_metadata.py b/tests/knowledge/test_github_source_metadata.py new file mode 100644 index 000000000..5012d391e --- /dev/null +++ b/tests/knowledge/test_github_source_metadata.py @@ -0,0 +1,61 @@ +"""Persistence tests for KB GitHub source metadata.""" + +from __future__ import annotations + +import json +from pathlib import Path + +from deeptutor.knowledge.manager import KnowledgeBaseManager + + +def _make_manager_with_kb(tmp_path: Path) -> tuple[KnowledgeBaseManager, Path, str]: + manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs")) + kb_dir = manager.base_dir / "kb" + kb_dir.mkdir() + manager.register_knowledge_base("kb") + return manager, kb_dir / "metadata.json", "kb" + + +def test_add_github_source_persists(tmp_path: Path) -> None: + manager, metadata_file, kb = _make_manager_with_kb(tmp_path) + info = manager.add_github_source(kb, "owner/repo", branch="main", path="docs/") + assert info["repo"] == "owner/repo" + on_disk = json.loads(metadata_file.read_text(encoding="utf-8")) + assert len(on_disk["github_sources"]) == 1 + + +def test_add_github_source_idempotent(tmp_path: Path) -> None: + manager, _, kb = _make_manager_with_kb(tmp_path) + info1 = manager.add_github_source(kb, "owner/repo") + info2 = manager.add_github_source(kb, "owner/repo") + assert info1["id"] == info2["id"] + assert len(manager.get_github_sources(kb)) == 1 + + +def test_remove_github_source(tmp_path: Path) -> None: + manager, _, kb = _make_manager_with_kb(tmp_path) + info = manager.add_github_source(kb, "owner/repo") + assert manager.remove_github_source(kb, info["id"]) is True + assert manager.get_github_sources(kb) == [] + + +def test_update_github_source_state_persists(tmp_path: Path) -> None: + manager, metadata_file, kb = _make_manager_with_kb(tmp_path) + info = manager.add_github_source(kb, "owner/repo") + manager.update_github_source_state( + kb_name=kb, source_id=info["id"], last_synced_sha="abc", last_sync_status="success" + ) + on_disk = json.loads(metadata_file.read_text(encoding="utf-8")) + assert on_disk["github_sources"][0]["last_synced_sha"] == "abc" + + +def test_get_all_github_sources_across_kbs(tmp_path: Path) -> None: + manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs")) + for name in ("kb-a", "kb-b"): + (manager.base_dir / name).mkdir() + manager.register_knowledge_base(name) + manager.add_github_source("kb-a", "a/repo") + manager.add_github_source("kb-b", "b/repo") + all_sources = manager.get_all_github_sources() + kb_names = {kb for kb, _s in all_sources} + assert kb_names == {"kb-a", "kb-b"} diff --git a/tests/services/test_github_source_path_containment.py b/tests/services/test_github_source_path_containment.py new file mode 100644 index 000000000..4242827da --- /dev/null +++ b/tests/services/test_github_source_path_containment.py @@ -0,0 +1,95 @@ +"""The GitHub sync must not write outside the KB's raw directory. + +Destination paths are derived from the tree/compare responses of a remote API, +so they are remote input. Two shapes escape a naive ``raw_dir / rel``: a ``..`` +segment, and an absolute path — ``Path("/kb") / "/etc/x"`` evaluates to +``/etc/x``, silently dropping the base. git rejects both in tree entries today, +but a downloader must enforce where it writes rather than trust the remote to. +""" + +from __future__ import annotations + +import asyncio +from dataclasses import dataclass +from pathlib import Path + +from deeptutor.services.github_source import sync as sync_module + + +@dataclass +class _Entry: + path: str + + +class _Client: + """Serves any requested path, recording what was asked for.""" + + def __init__(self, entries: list[_Entry]) -> None: + self._entries = entries + self.downloaded: list[str] = [] + + async def get_tree(self, repo, branch, *, path_prefix="", glob="*"): + return self._entries + + async def download_file(self, repo, path, sha): + self.downloaded.append(path) + return b"# owned\n" + + +def _run_full_sync(tmp_path: Path, entries: list[_Entry], monkeypatch) -> Path: + raw_dir = tmp_path / "kb" / "raw" + raw_dir.mkdir(parents=True) + monkeypatch.setattr(sync_module, "_filter_markdown_entries", lambda e, p, g: e) + + async def _no_index(kb_name, files, base_dir): + return None + + monkeypatch.setattr(sync_module, "_index_files", _no_index) + client = _Client(entries) + asyncio.run( + sync_module._full_sync( + client, + "kb", + raw_dir, + "owner/repo", + "main", + "", + "*", + "deadbeef", + str(tmp_path), + ) + ) + return raw_dir + + +def test_parent_traversal_is_refused(tmp_path: Path, monkeypatch) -> None: + raw_dir = _run_full_sync(tmp_path, [_Entry("../../escaped.md"), _Entry("kept.md")], monkeypatch) + + assert (raw_dir / "kept.md").read_bytes() == b"# owned\n" + assert not (tmp_path / "escaped.md").exists() + assert not (tmp_path.parent / "escaped.md").exists() + + +def test_absolute_path_is_refused(tmp_path: Path, monkeypatch) -> None: + outside = tmp_path / "outside" / "absolute.md" + outside.parent.mkdir(parents=True) + raw_dir = _run_full_sync(tmp_path, [_Entry(str(outside)), _Entry("kept.md")], monkeypatch) + + assert (raw_dir / "kept.md").read_bytes() == b"# owned\n" + assert not outside.exists(), "an absolute tree path discarded the raw dir" + + +def test_nested_paths_inside_the_raw_dir_still_sync(tmp_path: Path, monkeypatch) -> None: + raw_dir = _run_full_sync(tmp_path, [_Entry("docs/guide/intro.md")], monkeypatch) + + assert (raw_dir / "docs" / "guide" / "intro.md").read_bytes() == b"# owned\n" + + +def test_removal_of_an_escaping_path_leaves_the_target_alone(tmp_path: Path) -> None: + raw_dir = tmp_path / "kb" / "raw" + raw_dir.mkdir(parents=True) + victim = tmp_path / "victim.md" + victim.write_text("keep me", encoding="utf-8") + + assert sync_module._contained_dest(raw_dir, "../victim.md") is None + assert victim.read_text(encoding="utf-8") == "keep me" diff --git a/web/components/knowledge/CreateKbModal.tsx b/web/components/knowledge/CreateKbModal.tsx index 9f17b78c0..deb0c652d 100644 --- a/web/components/knowledge/CreateKbModal.tsx +++ b/web/components/knowledge/CreateKbModal.tsx @@ -226,7 +226,7 @@ export default function CreateKbModal({ // The connection must pass the test before a KB is bound to it. return !!trimmedServerUrl && !!serverProbe?.ok; } - return !providerUnavailable && selection.validFiles.length > 0; + return !providerUnavailable; } if (linkIsIma) return imaConnection.canSubmit; if (linkIsMarginNote) return true; @@ -685,6 +685,9 @@ function NewModeFields({
+ {t( + "Track a GitHub repo's Markdown docs. DeepTutor auto-syncs daily; you can also trigger a sync manually.", + )} +
++ {t("No GitHub sources yet. Click \"Add source\" to track a repo.")} +
+{source.path || "/"}
+
+
+ {t("Glob")}: {source.glob}
+
+
+ {t("Status")}: {source.last_sync_status}
+
+ {source.files_synced > 0 && (
+
+ {t("Files")}: {source.files_synced}
+
+ )}
+ {lastSync && (
+
+ {t("Synced")}: {lastSync}
+
+ )}
+ + {source.last_sync_error} +
+ )} +