diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e551762..c51b6434 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,20 @@ uses [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Removed + +- **Unsupported hosted web application.** Removed the FastAPI app, its + background jobs and cache, the HTTP documentation server, and the web-app + launcher. Use the CLI or MCP server to generate documentation; the static + HTML viewer, GitHub Pages output, landing page, and TechDocs export remain + supported. Docker now runs one-shot CLI commands with a mounted repository + and persistent CLI configuration instead of an HTTP service. See the + [Docker guide](guides/docker.md) for the new workflow. +- **Stale generated self-documentation.** Removed the checked-in `docs/` + snapshot and its saved analysis artifacts. Hand-written documentation + remains in `guides/`; generate a fresh wiki locally with + `codewiki generate --github-pages`. + ### Added - **Backstage TechDocs output.** `codewiki generate --techdocs` (or diff --git a/README.md b/README.md index d38a6a89..a85cb255 100644 --- a/README.md +++ b/README.md @@ -29,11 +29,6 @@ https://github.com/user-attachments/assets/951d5d3c-fd6e-4734-8b16-445d880f95d3 -

- πŸ“š CodeWiki documents itself. Browse the documentation it generated for this repository at - CodeWiki docs. -

-

CodeWiki framework

@@ -46,6 +41,9 @@ overview, with Mermaid diagrams. It works on codebases from a few thousand to over a million lines, in 11 languages. It needs an LLM API key, or a Claude or Codex subscription, or an AI IDE that speaks MCP. +The hosted web app is retired; use the CLI, MCP server, or +[Docker CLI jobs](./guides/docker.md). + ## Quick start **1. Install** @@ -188,8 +186,6 @@ its sub-modules (`auth.md`, `auth/login.md`). `--flat` puts every page in `index.md` and the module tree as the navigation. See [Backstage TechDocs](./guides/backstage-techdocs.md). -This repository's own output is checked in under [`./docs/`](./docs/). - ## Benchmark results Evaluated on [CodeWikiBench](https://github.com/FSoft-AI4Code/CodeWikiBench): @@ -253,7 +249,7 @@ JavaScript, TypeScript). Artifacts lift the build and testing topics, which | [MCP / IDE-driven mode](./guides/mcp-ide-mode.md) | Cursor, Claude Desktop, Claude Code, CodeBuddy | | [Backstage TechDocs](./guides/backstage-techdocs.md) | publish the docs in a Backstage developer portal | | [Development guide](./guides/development.md) | layout, pipeline, adding a language, tests, releasing | -| [Docker setup](./guides/docker.md) | the web application in a container | +| [Docker setup](./guides/docker.md) | run CLI jobs in a container | | [CodeWikiBench](https://github.com/FSoft-AI4Code/CodeWikiBench) | the benchmark | | [Live demo](https://fsoft-ai4code.github.io/codewiki-demo/) | generated documentation examples | diff --git a/codewiki/run_web_app.py b/codewiki/run_web_app.py deleted file mode 100644 index 9f03c817..00000000 --- a/codewiki/run_web_app.py +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env python3 -""" -Startup script for CodeWiki Web Application -""" - -import os -import sys - -# Add src directory to Python path -src_dir = os.path.join(os.path.dirname(__file__), "src") -sys.path.insert(0, src_dir) - -from fe.web_app import main # noqa: E402 - -if __name__ == "__main__": - main() diff --git a/codewiki/src/__init__.py b/codewiki/src/__init__.py index cc5a3b9f..e5f22a9e 100644 --- a/codewiki/src/__init__.py +++ b/codewiki/src/__init__.py @@ -1 +1 @@ -"""CodeWiki backend and frontend modules.""" +"""CodeWiki configuration, analysis, and documentation generation modules.""" diff --git a/codewiki/src/config.py b/codewiki/src/config.py index 38d9d762..d5552378 100644 --- a/codewiki/src/config.py +++ b/codewiki/src/config.py @@ -54,7 +54,7 @@ def set_cli_context(enabled: bool = True): - """Set whether we're running in CLI context (vs web app).""" + """Set whether we're running through the CLI configuration adapter.""" global _CLI_CONTEXT _CLI_CONTEXT = enabled @@ -66,7 +66,7 @@ def is_cli_context() -> bool: # LLM services # In CLI mode, these will be loaded from ~/.codewiki/config.json + keyring -# In web app mode, use environment variables +# The standalone backend entry point uses environment variables. MAIN_MODEL = os.getenv("MAIN_MODEL", "claude-sonnet-4") FALLBACK_MODEL_1 = os.getenv("FALLBACK_MODEL_1", "glm-4p5") CLUSTER_MODEL = os.getenv("CLUSTER_MODEL", MAIN_MODEL) diff --git a/codewiki/src/fe/__init__.py b/codewiki/src/fe/__init__.py deleted file mode 100644 index 63edc7e2..00000000 --- a/codewiki/src/fe/__init__.py +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env python3 -""" -CodeWiki Frontend Module - -Web interface components for the documentation generation service. -""" - -from .web_app import app, main -from .models import JobStatus, JobStatusResponse, RepositorySubmission, CacheEntry -from .cache_manager import CacheManager -from .background_worker import BackgroundWorker -from .github_processor import GitHubRepoProcessor -from .routes import WebRoutes - -__all__ = [ - "app", - "main", - "JobStatus", - "JobStatusResponse", - "RepositorySubmission", - "CacheEntry", - "CacheManager", - "BackgroundWorker", - "GitHubRepoProcessor", - "WebRoutes", -] diff --git a/codewiki/src/fe/background_worker.py b/codewiki/src/fe/background_worker.py deleted file mode 100644 index 6a2d321a..00000000 --- a/codewiki/src/fe/background_worker.py +++ /dev/null @@ -1,265 +0,0 @@ -#!/usr/bin/env python3 -""" -Background worker for processing documentation generation jobs. -""" - -import os -import time -import threading -import subprocess -import asyncio -from datetime import datetime -from pathlib import Path -from queue import Queue -from typing import Dict - -from codewiki.src.be.documentation_generator import DocumentationGenerator -from codewiki.src.config import Config, MAIN_MODEL -from .models import JobStatus -from .cache_manager import CacheManager -from .github_processor import GitHubRepoProcessor -from .config import WebAppConfig -from codewiki.src.utils import file_manager - - -class BackgroundWorker: - """Background worker for processing documentation generation jobs.""" - - def __init__(self, cache_manager: CacheManager, temp_dir: str = None): - self.cache_manager = cache_manager - self.temp_dir = temp_dir or WebAppConfig.TEMP_DIR - self.running = False - self.processing_queue = Queue(maxsize=WebAppConfig.QUEUE_SIZE) - self.job_status: Dict[str, JobStatus] = {} - self.jobs_file = Path(WebAppConfig.CACHE_DIR) / "jobs.json" - self.load_job_statuses() - - def start(self): - """Start the background worker thread.""" - if not self.running: - self.running = True - thread = threading.Thread(target=self._worker_loop, daemon=True) - thread.start() - print("Background worker started") - - def stop(self): - """Stop the background worker.""" - self.running = False - - def add_job(self, job_id: str, job: JobStatus): - """Add a job to the processing queue.""" - self.job_status[job_id] = job - self.processing_queue.put(job_id) - - def get_job_status(self, job_id: str) -> JobStatus: - """Get job status by ID.""" - return self.job_status.get(job_id) - - def get_all_jobs(self) -> Dict[str, JobStatus]: - """Get all job statuses.""" - return self.job_status - - def load_job_statuses(self): - """Load job statuses from disk.""" - if not self.jobs_file.exists(): - # Try to reconstruct from cache if no job file exists - self._reconstruct_jobs_from_cache() - return - - try: - data = file_manager.load_json(self.jobs_file) - - for job_id, job_data in data.items(): - # Only load completed jobs to avoid inconsistent state - if job_data.get("status") == "completed": - self.job_status[job_id] = JobStatus( - job_id=job_data["job_id"], - repo_url=job_data["repo_url"], - status=job_data["status"], - created_at=datetime.fromisoformat(job_data["created_at"]), - started_at=datetime.fromisoformat(job_data["started_at"]) - if job_data.get("started_at") - else None, - completed_at=datetime.fromisoformat(job_data["completed_at"]) - if job_data.get("completed_at") - else None, - error_message=job_data.get("error_message"), - progress=job_data.get("progress", ""), - docs_path=job_data.get("docs_path"), - ) - print( - f"Loaded {len([j for j in self.job_status.values() if j.status == 'completed'])} completed jobs from disk" - ) - except Exception as e: - print(f"Error loading job statuses: {e}") - - def _reconstruct_jobs_from_cache(self): - """Reconstruct job statuses from cache entries for backward compatibility.""" - try: - cache_entries = self.cache_manager.cache_index - reconstructed_count = 0 - - for repo_hash, cache_entry in cache_entries.items(): - # Extract repo info to create job_id - from .github_processor import GitHubRepoProcessor - - try: - repo_info = GitHubRepoProcessor.get_repo_info(cache_entry.repo_url) - job_id = repo_info["full_name"].replace("/", "--") - - # Only add if job doesn't already exist - if job_id not in self.job_status: - self.job_status[job_id] = JobStatus( - job_id=job_id, - repo_url=cache_entry.repo_url, - status="completed", - created_at=cache_entry.created_at, - completed_at=cache_entry.created_at, - docs_path=cache_entry.docs_path, - progress="Reconstructed from cache", - ) - reconstructed_count += 1 - except Exception as e: - print(f"Failed to reconstruct job for {cache_entry.repo_url}: {e}") - - if reconstructed_count > 0: - print(f"Reconstructed {reconstructed_count} job statuses from cache") - self.save_job_statuses() - - except Exception as e: - print(f"Error reconstructing jobs from cache: {e}") - - def save_job_statuses(self): - """Save job statuses to disk.""" - try: - # Ensure cache directory exists - self.jobs_file.parent.mkdir(parents=True, exist_ok=True) - - data = {} - for job_id, job in self.job_status.items(): - data[job_id] = { - "job_id": job.job_id, - "repo_url": job.repo_url, - "status": job.status, - "created_at": job.created_at.isoformat(), - "started_at": job.started_at.isoformat() if job.started_at else None, - "completed_at": job.completed_at.isoformat() if job.completed_at else None, - "error_message": job.error_message, - "progress": job.progress, - "docs_path": job.docs_path, - } - - file_manager.save_json(data, self.jobs_file) - except Exception as e: - print(f"Error saving job statuses: {e}") - - def _worker_loop(self): - """Main worker loop.""" - while self.running: - try: - if not self.processing_queue.empty(): - job_id = self.processing_queue.get(timeout=1) - self._process_job(job_id) - else: - time.sleep(1) - except Exception as e: - print(f"Worker error: {e}") - time.sleep(1) - - def _process_job(self, job_id: str): - """Process a single documentation generation job.""" - if job_id not in self.job_status: - return - - job = self.job_status[job_id] - - try: - # Update job status - job.status = "processing" - job.started_at = datetime.now() - job.progress = "Starting repository clone..." - job.main_model = MAIN_MODEL - - # Check cache first - cached_docs = self.cache_manager.get_cached_docs(job.repo_url) - if cached_docs and Path(cached_docs).exists(): - job.status = "completed" - job.completed_at = datetime.now() - job.docs_path = cached_docs - job.progress = "Documentation retrieved from cache" - if not job.main_model: # Only set if not already set - job.main_model = MAIN_MODEL - - # Save job status to disk - self.save_job_statuses() - - print(f"Job {job_id}: Using cached documentation") - return - - # Clone repository - repo_info = GitHubRepoProcessor.get_repo_info(job.repo_url) - # Use repo full name for temp directory (already URL-safe since job_id is URL-safe) - temp_repo_dir = os.path.join(self.temp_dir, job_id) - - job.progress = f"Cloning repository {repo_info['full_name']}..." - - if not GitHubRepoProcessor.clone_repository( - repo_info["clone_url"], temp_repo_dir, job.commit_id - ): - raise Exception("Failed to clone repository") - - # Generate documentation - job.progress = "Analyzing repository structure..." - - # Create config for documentation generation (using env vars) - import argparse - - args = argparse.Namespace(repo_path=temp_repo_dir) - config = Config.from_args(args) - # Override docs_dir with job-specific directory - config.docs_dir = os.path.join("output", "docs", f"{job_id}-docs") - - job.progress = "Generating documentation..." - - # Generate documentation - doc_generator = DocumentationGenerator(config, job.commit_id) - - # Run the async documentation generation in a new event loop - loop = asyncio.new_event_loop() - asyncio.set_event_loop(loop) - try: - loop.run_until_complete(doc_generator.run()) - finally: - loop.close() - - # Cache the results - docs_path = os.path.abspath(config.docs_dir) - self.cache_manager.add_to_cache(job.repo_url, docs_path) - - # Update job status - job.status = "completed" - job.completed_at = datetime.now() - job.docs_path = docs_path - job.progress = "Documentation generation completed" - - # Save job status to disk - self.save_job_statuses() - - print(f"Job {job_id}: Documentation generated successfully") - - except Exception as e: - # Update job status with error - job.status = "failed" - job.completed_at = datetime.now() - job.error_message = str(e) - job.progress = f"Failed: {str(e)}" - - print(f"Job {job_id}: Failed with error: {e}") - - finally: - # Cleanup temporary repository - if "temp_repo_dir" in locals() and os.path.exists(temp_repo_dir): - try: - subprocess.run(["rm", "-rf", temp_repo_dir], check=True) - except Exception as e: - print(f"Failed to cleanup temp directory: {e}") diff --git a/codewiki/src/fe/cache_manager.py b/codewiki/src/fe/cache_manager.py deleted file mode 100644 index 2a853ef6..00000000 --- a/codewiki/src/fe/cache_manager.py +++ /dev/null @@ -1,119 +0,0 @@ -#!/usr/bin/env python3 -""" -Cache management for documentation generation results. -""" - -import hashlib -from datetime import datetime, timedelta -from pathlib import Path -from typing import Optional, Dict - -from .models import CacheEntry -from .config import WebAppConfig -from codewiki.src.utils import file_manager - - -class CacheManager: - """Manages documentation cache.""" - - def __init__(self, cache_dir: str = None, cache_expiry_days: int = None): - self.cache_dir = Path(cache_dir or WebAppConfig.CACHE_DIR) - self.cache_expiry_days = cache_expiry_days or WebAppConfig.CACHE_EXPIRY_DAYS - self.cache_dir.mkdir(parents=True, exist_ok=True) - self.cache_index: Dict[str, CacheEntry] = {} - self.load_cache_index() - - def load_cache_index(self): - """Load cache index from disk.""" - index_file = self.cache_dir / "cache_index.json" - if index_file.exists(): - try: - data = file_manager.load_json(index_file) - for key, value in data.items(): - self.cache_index[key] = CacheEntry( - repo_url=value["repo_url"], - repo_url_hash=value["repo_url_hash"], - docs_path=value["docs_path"], - created_at=datetime.fromisoformat(value["created_at"]), - last_accessed=datetime.fromisoformat(value["last_accessed"]), - ) - except Exception as e: - print(f"Error loading cache index: {e}") - - def save_cache_index(self): - """Save cache index to disk.""" - index_file = self.cache_dir / "cache_index.json" - try: - data = {} - for key, entry in self.cache_index.items(): - data[key] = { - "repo_url": entry.repo_url, - "repo_url_hash": entry.repo_url_hash, - "docs_path": entry.docs_path, - "created_at": entry.created_at.isoformat(), - "last_accessed": entry.last_accessed.isoformat(), - } - - file_manager.save_json(data, index_file) - except Exception as e: - print(f"Error saving cache index: {e}") - - def get_repo_hash(self, repo_url: str) -> str: - """Generate hash for repository URL.""" - return hashlib.sha256(repo_url.encode()).hexdigest()[:16] - - def get_cached_docs(self, repo_url: str) -> Optional[str]: - """Get cached documentation path if available.""" - repo_hash = self.get_repo_hash(repo_url) - - if repo_hash in self.cache_index: - entry = self.cache_index[repo_hash] - - # Check if cache is still valid - if datetime.now() - entry.created_at < timedelta(days=self.cache_expiry_days): - # Update last accessed - entry.last_accessed = datetime.now() - self.save_cache_index() - return entry.docs_path - else: - # Cache expired, remove it - self.remove_from_cache(repo_url) - - return None - - def add_to_cache(self, repo_url: str, docs_path: str): - """Add documentation to cache.""" - repo_hash = self.get_repo_hash(repo_url) - now = datetime.now() - - self.cache_index[repo_hash] = CacheEntry( - repo_url=repo_url, - repo_url_hash=repo_hash, - docs_path=docs_path, - created_at=now, - last_accessed=now, - ) - - self.save_cache_index() - - def remove_from_cache(self, repo_url: str): - """Remove documentation from cache.""" - repo_hash = self.get_repo_hash(repo_url) - if repo_hash in self.cache_index: - del self.cache_index[repo_hash] - self.save_cache_index() - - def cleanup_expired_cache(self): - """Remove expired cache entries.""" - expired_entries = [] - cutoff = datetime.now() - timedelta(days=self.cache_expiry_days) - - for repo_hash, entry in self.cache_index.items(): - if entry.created_at < cutoff: - expired_entries.append(repo_hash) - - for repo_hash in expired_entries: - del self.cache_index[repo_hash] - - if expired_entries: - self.save_cache_index() diff --git a/codewiki/src/fe/config.py b/codewiki/src/fe/config.py deleted file mode 100644 index 37a208a3..00000000 --- a/codewiki/src/fe/config.py +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env python3 -""" -Configuration settings for the CodeWiki web application. -""" - -import os -from pathlib import Path - - -class WebAppConfig: - """Configuration class for web application settings.""" - - # Directories - CACHE_DIR = "./output/cache" - TEMP_DIR = "./output/temp" - OUTPUT_DIR = "./output" - - # Queue settings - QUEUE_SIZE = 100 - - # Cache settings - CACHE_EXPIRY_DAYS = 365 - - # Job cleanup settings - JOB_CLEANUP_HOURS = 24000 - RETRY_COOLDOWN_MINUTES = 3 - - # Server settings - DEFAULT_HOST = "127.0.0.1" - DEFAULT_PORT = 8000 - - # Git settings - CLONE_TIMEOUT = 300 - CLONE_DEPTH = 1 - - @classmethod - def ensure_directories(cls): - """Ensure all required directories exist.""" - directories = [cls.CACHE_DIR, cls.TEMP_DIR, cls.OUTPUT_DIR] - - for directory in directories: - Path(directory).mkdir(parents=True, exist_ok=True) - - @classmethod - def get_absolute_path(cls, path: str) -> str: - """Get absolute path for a given relative path.""" - return os.path.abspath(path) diff --git a/codewiki/src/fe/github_processor.py b/codewiki/src/fe/github_processor.py deleted file mode 100644 index 602d0ee1..00000000 --- a/codewiki/src/fe/github_processor.py +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env python3 -""" -GitHub repository processing utilities. -""" - -import os -import subprocess -from typing import Dict -from urllib.parse import urlparse - -from .config import WebAppConfig - - -class GitHubRepoProcessor: - """Handles GitHub repository processing.""" - - @staticmethod - def is_valid_github_url(url: str) -> bool: - """Validate if the URL is a valid GitHub repository URL.""" - try: - parsed = urlparse(url) - if parsed.netloc.lower() not in ["github.com", "www.github.com"]: - return False - - path_parts = parsed.path.strip("/").split("/") - if len(path_parts) < 2: - return False - - # Check if it's a valid repo path (owner/repo) - return len(path_parts) >= 2 and all(part for part in path_parts[:2]) - except Exception: - return False - - @staticmethod - def get_repo_info(url: str) -> Dict[str, str]: - """Extract repository information from GitHub URL.""" - parsed = urlparse(url) - path_parts = parsed.path.strip("/").split("/") - - owner = path_parts[0] - repo = path_parts[1] - - # Remove .git suffix if present - if repo.endswith(".git"): - repo = repo[:-4] - - return { - "owner": owner, - "repo": repo, - "full_name": f"{owner}/{repo}", - "clone_url": f"https://github.com/{owner}/{repo}.git", - } - - @staticmethod - def clone_repository(clone_url: str, target_dir: str, commit_id: str = None) -> bool: - """Clone a GitHub repository to the target directory, optionally checking out a specific commit.""" - try: - # Ensure target directory exists - os.makedirs(os.path.dirname(target_dir), exist_ok=True) - - # If specific commit is requested, don't use shallow clone - if commit_id: - # Clone full repository to access specific commit - result = subprocess.run( - ["git", "clone", clone_url, target_dir], - capture_output=True, - stdin=subprocess.DEVNULL, - text=True, - timeout=WebAppConfig.CLONE_TIMEOUT, - ) - - if result.returncode != 0: - print(f"Error cloning repository: {result.stderr}") - return False - - # Checkout specific commit - result = subprocess.run( - ["git", "checkout", commit_id], - cwd=target_dir, - capture_output=True, - stdin=subprocess.DEVNULL, - text=True, - timeout=30, - ) - - if result.returncode != 0: - print(f"Error checking out commit {commit_id}: {result.stderr}") - return False - else: - # Clone repository with shallow depth (default behavior) - result = subprocess.run( - [ - "git", - "clone", - "--depth", - str(WebAppConfig.CLONE_DEPTH), - clone_url, - target_dir, - ], - capture_output=True, - stdin=subprocess.DEVNULL, - text=True, - timeout=WebAppConfig.CLONE_TIMEOUT, - ) - - if result.returncode != 0: - print(f"Error cloning repository: {result.stderr}") - return False - - return True - except Exception as e: - print(f"Error cloning repository: {e}") - return False diff --git a/codewiki/src/fe/models.py b/codewiki/src/fe/models.py deleted file mode 100644 index b8d0301d..00000000 --- a/codewiki/src/fe/models.py +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env python3 -""" -Data models and classes for the CodeWiki web application. -""" - -from datetime import datetime -from typing import Optional -from dataclasses import dataclass -from pydantic import BaseModel, HttpUrl - - -class RepositorySubmission(BaseModel): - """Pydantic model for repository submission form.""" - - repo_url: HttpUrl - - -class JobStatusResponse(BaseModel): - """Pydantic model for job status API response.""" - - job_id: str - repo_url: str - status: str - created_at: datetime - started_at: Optional[datetime] = None - completed_at: Optional[datetime] = None - error_message: Optional[str] = None - progress: str = "" - docs_path: Optional[str] = None - main_model: Optional[str] = None - commit_id: Optional[str] = None - - -@dataclass -class JobStatus: - """Tracks the status of a documentation generation job.""" - - job_id: str - repo_url: str - status: str # 'queued', 'processing', 'completed', 'failed' - created_at: datetime - started_at: Optional[datetime] = None - completed_at: Optional[datetime] = None - error_message: Optional[str] = None - progress: str = "" - docs_path: Optional[str] = None - main_model: Optional[str] = None - commit_id: Optional[str] = None - - -@dataclass -class CacheEntry: - """Represents a cached documentation result.""" - - repo_url: str - repo_url_hash: str - docs_path: str - created_at: datetime - last_accessed: datetime diff --git a/codewiki/src/fe/routes.py b/codewiki/src/fe/routes.py deleted file mode 100644 index 11eaa861..00000000 --- a/codewiki/src/fe/routes.py +++ /dev/null @@ -1,307 +0,0 @@ -#!/usr/bin/env python3 -""" -FastAPI route handlers for the CodeWiki web application. -""" - -from datetime import datetime, timedelta -from pathlib import Path -from dataclasses import asdict - -from traceback import format_exc - -from fastapi import Form, HTTPException, Request, status -from fastapi.responses import HTMLResponse, RedirectResponse - -from .models import JobStatus, JobStatusResponse -from .github_processor import GitHubRepoProcessor -from .background_worker import BackgroundWorker -from .cache_manager import CacheManager -from .templates import WEB_INTERFACE_TEMPLATE -from .template_utils import render_template -from .config import WebAppConfig -from codewiki.src.be.doc_layout import doc_path_map -from codewiki.src.utils import file_manager - - -class WebRoutes: - """Handles all web routes for the application.""" - - def __init__(self, background_worker: BackgroundWorker, cache_manager: CacheManager): - self.background_worker = background_worker - self.cache_manager = cache_manager - - async def index_get(self, request: Request) -> HTMLResponse: - """Main page with form for submitting GitHub repositories.""" - # Clean up old jobs before displaying - # self.cleanup_old_jobs() - - # Get recent jobs (last 10) - all_jobs = self.background_worker.get_all_jobs() - recent_jobs = sorted(all_jobs.values(), key=lambda x: x.created_at, reverse=True)[:100] - - context = { - "message": None, - "message_type": None, - "repo_url": "", - "commit_id": "", - "recent_jobs": recent_jobs, - } - - return HTMLResponse(content=render_template(WEB_INTERFACE_TEMPLATE, context)) - - async def index_post( - self, request: Request, repo_url: str = Form(...), commit_id: str = Form("") - ) -> HTMLResponse: - """Handle repository submission.""" - # Clean up old jobs before processing - self.cleanup_old_jobs() - - message = None - message_type = None - - repo_url = repo_url.strip() - commit_id = commit_id.strip() if commit_id else "" - - if not repo_url: - message = "Please enter a GitHub repository URL" - message_type = "error" - elif not GitHubRepoProcessor.is_valid_github_url(repo_url): - message = "Please enter a valid GitHub repository URL" - message_type = "error" - else: - # Normalize the repo URL for comparison - normalized_repo_url = self._normalize_github_url(repo_url) - - # Get repo info for job ID generation - repo_info = GitHubRepoProcessor.get_repo_info(normalized_repo_url) - job_id = self._repo_full_name_to_job_id(repo_info["full_name"]) - - # Check if already in queue, processing, or recently failed - existing_job = self.background_worker.get_job_status(job_id) - recent_cutoff = datetime.now() - timedelta(minutes=WebAppConfig.RETRY_COOLDOWN_MINUTES) - - if existing_job: - if existing_job.status in ["queued", "processing"]: - pass # Will handle below - elif existing_job.status == "failed" and existing_job.created_at > recent_cutoff: - pass # Will handle below - else: - existing_job = None # Job is old or completed, can reuse - - if existing_job: - if existing_job.status in ["queued", "processing"]: - message = ( - f"Repository is already being processed (Job ID: {existing_job.job_id})" - ) - else: - message = f"Repository recently failed processing. Please wait a few minutes before retrying (Job ID: {existing_job.job_id})" - message_type = "error" - else: - # Check cache - cached_docs = self.cache_manager.get_cached_docs(normalized_repo_url) - if cached_docs and Path(cached_docs).exists(): - message = "Documentation found in cache! Redirecting to view..." - message_type = "success" - # Create a dummy completed job for display - job = JobStatus( - job_id=job_id, - repo_url=normalized_repo_url, # Use normalized URL - status="completed", - created_at=datetime.now(), - completed_at=datetime.now(), - docs_path=cached_docs, - progress="Retrieved from cache", - commit_id=commit_id if commit_id else None, - ) - self.background_worker.job_status[job_id] = job - else: - # Add to queue - try: - job = JobStatus( - job_id=job_id, - repo_url=normalized_repo_url, # Use normalized URL - status="queued", - created_at=datetime.now(), - progress="Waiting in queue...", - commit_id=commit_id if commit_id else None, - ) - - self.background_worker.add_job(job_id, job) - message = f"Repository added to processing queue! Job ID: {job_id}" - message_type = "success" - repo_url = "" # Clear form - - except Exception as e: - message = f"Failed to add repository to queue: {str(e)}\n{format_exc()}" - message_type = "error" - - # Get recent jobs (last 10) - all_jobs = self.background_worker.get_all_jobs() - recent_jobs = sorted(all_jobs.values(), key=lambda x: x.created_at, reverse=True) - - context = { - "message": message, - "message_type": message_type, - "repo_url": repo_url or "", - "commit_id": commit_id or "", - "recent_jobs": recent_jobs, - } - - return HTMLResponse(content=render_template(WEB_INTERFACE_TEMPLATE, context)) - - async def get_job_status(self, job_id: str) -> JobStatusResponse: - """API endpoint to get job status.""" - job = self.background_worker.get_job_status(job_id) - if not job: - raise HTTPException(status_code=404, detail="Job not found") - - return JobStatusResponse(**asdict(job)) - - async def view_docs(self, job_id: str) -> RedirectResponse: - """View generated documentation.""" - job = self.background_worker.get_job_status(job_id) - if not job: - raise HTTPException(status_code=404, detail="Job not found") - - if job.status != "completed" or not job.docs_path: - raise HTTPException(status_code=404, detail="Documentation not available") - - docs_path = Path(job.docs_path) - if not docs_path.exists(): - raise HTTPException(status_code=404, detail="Documentation files not found") - - # Redirect to the documentation viewer - return RedirectResponse(url=f"/static-docs/{job_id}/", status_code=status.HTTP_302_FOUND) - - async def serve_generated_docs( - self, job_id: str, filename: str = "overview.md" - ) -> HTMLResponse: - """Serve generated documentation files.""" - job = self.background_worker.get_job_status(job_id) - docs_path = None - repo_url = None - - if job: - # Job status exists - use it - if job.status != "completed" or not job.docs_path: - raise HTTPException(status_code=404, detail="Documentation not available") - docs_path = Path(job.docs_path) - repo_url = job.repo_url - else: - # No job status - try to find documentation in cache by job_id - # Convert job_id back to repo full name and construct potential paths - repo_full_name = self._job_id_to_repo_full_name(job_id) - potential_repo_url = f"https://github.com/{repo_full_name}" - - # Check if documentation exists in cache - cached_docs = self.cache_manager.get_cached_docs(potential_repo_url) - if cached_docs and Path(cached_docs).exists(): - docs_path = Path(cached_docs) - repo_url = potential_repo_url - - # Recreate job status for consistency - job = JobStatus( - job_id=job_id, - repo_url=potential_repo_url, - status="completed", - created_at=datetime.now(), - completed_at=datetime.now(), - docs_path=cached_docs, - progress="Loaded from cache", - commit_id=None, # No commit info available from cache - ) - self.background_worker.job_status[job_id] = job - self.background_worker.save_job_statuses() - else: - raise HTTPException(status_code=404, detail="Documentation not found") - - if not docs_path or not docs_path.exists(): - raise HTTPException(status_code=404, detail="Documentation files not found") - - # Load module tree - module_tree = None - module_tree_file = docs_path / "module_tree.json" - if module_tree_file.exists(): - try: - module_tree = file_manager.load_json(module_tree_file) - except Exception: - pass - - # Load metadata - metadata = None - metadata_file = docs_path / "metadata.json" - if metadata_file.exists(): - try: - metadata = file_manager.load_json(metadata_file) - except Exception: - pass - - # Serve the requested file (pages may sit in nested folders; never - # outside the docs directory) - file_path = (docs_path / filename).resolve() - try: - file_path.relative_to(docs_path.resolve()) - except ValueError: - raise HTTPException(status_code=403, detail="Access denied") from None - if not file_path.is_file(): - raise HTTPException(status_code=404, detail=f"File {filename} not found") - - try: - content = file_manager.load_text(file_path) - - # Convert markdown to HTML (reuse from visualise_docs.py) - from .visualise_docs import markdown_to_html, get_file_title - from .templates import DOCS_VIEW_TEMPLATE - - html_content = markdown_to_html(content) - title = get_file_title(file_path) - - context = { - "repo_name": repo_url.split("/")[-1], - "title": title, - "content": html_content, - "navigation": module_tree, - "doc_paths": doc_path_map(str(docs_path), module_tree), - "current_page": filename, - "job_id": job_id, - "metadata": metadata, - } - - return HTMLResponse(content=render_template(DOCS_VIEW_TEMPLATE, context)) - - except Exception as e: - raise HTTPException( - status_code=500, detail=f"Error reading {filename}: {e}\n{format_exc()}" - ) - - def _normalize_github_url(self, url: str) -> str: - """Normalize GitHub URL for consistent comparison.""" - try: - # Get repo info to standardize the URL format - repo_info = GitHubRepoProcessor.get_repo_info(url) - return f"https://github.com/{repo_info['full_name']}" - except Exception: - # Fallback to basic normalization - return url.rstrip("/").lower() - - def _repo_full_name_to_job_id(self, full_name: str) -> str: - """Convert repo full name to URL-safe job ID.""" - return full_name.replace("/", "--") - - def _job_id_to_repo_full_name(self, job_id: str) -> str: - """Convert job ID back to repo full name.""" - return job_id.replace("--", "/") - - def cleanup_old_jobs(self): - """Clean up old job status entries.""" - cutoff = datetime.now() - timedelta(hours=WebAppConfig.JOB_CLEANUP_HOURS) - all_jobs = self.background_worker.get_all_jobs() - expired_jobs = [ - job_id - for job_id, job in all_jobs.items() - if job.created_at < cutoff and job.status in ["completed", "failed"] - ] - - for job_id in expired_jobs: - if job_id in self.background_worker.job_status: - del self.background_worker.job_status[job_id] diff --git a/codewiki/src/fe/template_utils.py b/codewiki/src/fe/template_utils.py deleted file mode 100644 index 98754ee8..00000000 --- a/codewiki/src/fe/template_utils.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/env python3 -""" -Template utilities for FastAPI applications using Jinja2. -""" - -from jinja2 import Environment, BaseLoader, select_autoescape -from typing import Dict, Any - - -class StringTemplateLoader(BaseLoader): - """Custom Jinja2 loader for string templates.""" - - def __init__(self, template_string: str): - self.template_string = template_string - - def get_source(self, environment, template): - return self.template_string, None, lambda: True - - -def render_template(template: str, context: Dict[str, Any]) -> str: - """ - Render template using Jinja2. - - Args: - template: HTML template string with Jinja2 syntax - context: Dictionary of variables to substitute - - Returns: - Rendered HTML string - """ - # Create Jinja2 environment with string template - env = Environment( - loader=StringTemplateLoader(template), - autoescape=select_autoescape(["html", "xml"]), - trim_blocks=True, - lstrip_blocks=True, - ) - - # Get template and render - jinja_template = env.get_template("") - return jinja_template.render(**context) - - -def render_navigation(module_tree: Dict[str, Any], current_page: str = "") -> str: - """ - Render navigation HTML from module tree structure. - - Args: - module_tree: Dictionary representing the module tree - current_page: Current page filename for highlighting - - Returns: - HTML string for navigation - """ - if not module_tree: - return "" - - nav_template = """ - {%- for section_key, section_data in module_tree.items() %} - - {%- endfor %} - """ - - return render_template(nav_template, {"module_tree": module_tree, "current_page": current_page}) - - -def render_job_list(jobs: list) -> str: - """ - Render job list HTML. - - Args: - jobs: List of job objects - - Returns: - HTML string for job list - """ - if not jobs: - return "" - - job_list_template = """ - {%- for job in jobs %} -
-
-
{{ job.repo_url }}
-
{{ job.status.title() }}
-
- {%- if job.progress %} -
{{ job.progress }}
- {%- endif %} - {%- if job.status == 'completed' and job.docs_path %} -
- View Documentation -
- {%- endif %} -
- {%- endfor %} - """ - - return render_template(job_list_template, {"jobs": jobs}) diff --git a/codewiki/src/fe/templates.py b/codewiki/src/fe/templates.py deleted file mode 100644 index c269af6d..00000000 --- a/codewiki/src/fe/templates.py +++ /dev/null @@ -1,699 +0,0 @@ -#!/usr/bin/env python3 -""" -HTML templates for the CodeWiki web application. -""" - -# Web interface HTML template -WEB_INTERFACE_TEMPLATE = """ - - - - - - CodeWiki - GitHub Repository Documentation Generator - - - - -
-
- -

Generate comprehensive documentation for any GitHub repository

-
- -
- {% if message %} -
- {{ message }} -
- {% endif %} - -
-
- - -
- -
- - -
- - -
- - {% if recent_jobs %} -
-

Recent Jobs

- {% for job in recent_jobs %} -
-
-
{{ job.repo_url }}
-
{{ job.status }}
-
-
{{ job.progress }}
- {% if job.main_model %} -
- Generated with: {{ job.main_model }} -
- {% endif %} - -
- {% endfor %} -
- {% endif %} -
-
- - - - -""" - -# HTML template for the documentation pages -DOCS_VIEW_TEMPLATE = """ - - - - - - {{ title }} - - - - - -
- - -
-
- {{ content | safe }} -
-
-
- - - - -""" diff --git a/codewiki/src/fe/visualise_docs.py b/codewiki/src/fe/visualise_docs.py deleted file mode 100644 index 1fdd61d8..00000000 --- a/codewiki/src/fe/visualise_docs.py +++ /dev/null @@ -1,281 +0,0 @@ -#!/usr/bin/env python3 -""" -Simple documentation server for hosting documentation folders. - -This server serves documentation folders with the following structure: -- overview.md: The main overview document -- module_tree.json: Hierarchical structure of modules -- Various .md files for different modules - -Usage: - python docs_server.py --docs-folder path/to/docs --port 8080 -""" - -import argparse -import sys -from pathlib import Path -from typing import Dict, Optional - -from fastapi import FastAPI, HTTPException -from fastapi.responses import HTMLResponse -from fastapi.staticfiles import StaticFiles -from markdown_it import MarkdownIt - -from .template_utils import render_template -from .templates import DOCS_VIEW_TEMPLATE -from codewiki.src.be.doc_layout import doc_path_map -from codewiki.src.utils import file_manager - -app = FastAPI( - title="Documentation Server", - description="Simple documentation server for hosting markdown documentation folders", -) - -# Global variables to store configuration -DOCS_FOLDER = None -MODULE_TREE = None - - -def initialize_globals(): - """Initialize global variables from environment or command line args if not already set.""" - global DOCS_FOLDER, MODULE_TREE - - if DOCS_FOLDER is None: - # Try to get from environment variable or use a default - import os - - docs_folder_path = os.environ.get("DOCS_FOLDER") - if docs_folder_path and Path(docs_folder_path).exists(): - DOCS_FOLDER = docs_folder_path - MODULE_TREE = load_module_tree(Path(docs_folder_path)) - else: - # If no environment variable, we need to handle this gracefully - # The FastAPI endpoints will need to check if DOCS_FOLDER is None - pass - - -# Markdown parser -md = MarkdownIt() - - -def load_module_tree(docs_folder: Path) -> Optional[Dict]: - """Load the module tree structure from module_tree.json.""" - tree_file = docs_folder / "module_tree.json" - if not tree_file.exists(): - print(f"Warning: module_tree.json not found in {docs_folder}") - return None - - try: - return file_manager.load_json(tree_file) - except Exception as e: - print(f"Error loading module_tree.json: {e}") - return None - - -def markdown_to_html(content: str) -> str: - """Convert markdown content to HTML, with special handling for mermaid diagrams.""" - # First, convert markdown to HTML - html = md.render(content) - - # Post-process to ensure mermaid code blocks are properly formatted - # Look for code blocks with language-mermaid class and convert them to mermaid divs - import re - - # Pattern to match mermaid code blocks - pattern = r'
(.*?)
' - - def replace_mermaid(match): - mermaid_code = match.group(1) - # Decode HTML entities that might have been encoded - import html - - mermaid_code = html.unescape(mermaid_code) - return f'
{mermaid_code}
' - - # Replace mermaid code blocks with proper mermaid divs - html = re.sub(pattern, replace_mermaid, html, flags=re.DOTALL) - - return html - - -def get_file_title(file_path: Path) -> str: - """Extract title from markdown file, fallback to filename.""" - try: - content = file_manager.load_text(file_path) - first_line = content.split("\n")[0].strip() - if first_line.startswith("# "): - return first_line[2:].strip() - except Exception: - pass - - # Fallback to filename without extension - return file_path.stem.replace("_", " ").title() - - -@app.get("/", response_class=HTMLResponse) -async def index(): - """Serve the overview page as the main page.""" - initialize_globals() - - if DOCS_FOLDER is None: - raise HTTPException( - status_code=500, - detail="Documentation folder not configured. Please set DOCS_FOLDER environment variable or run with --docs-folder argument.", - ) - - overview_file = Path(DOCS_FOLDER) / "overview.md" - - if not overview_file.exists(): - raise HTTPException( - status_code=404, detail="overview.md not found in the documentation folder" - ) - - try: - content = file_manager.load_text(overview_file) - - html_content = markdown_to_html(content) - title = get_file_title(overview_file) - - context = { - "title": title, - "content": html_content, - "navigation": MODULE_TREE, - "doc_paths": doc_path_map(str(DOCS_FOLDER), MODULE_TREE) if DOCS_FOLDER else None, - "current_page": "overview.md", - } - - return HTMLResponse(content=render_template(DOCS_VIEW_TEMPLATE, context)) - - except Exception as e: - raise HTTPException(status_code=500, detail=f"Error reading overview.md: {e}") - - -@app.get("/{filename:path}", response_class=HTMLResponse) -async def serve_doc(filename: str): - """Serve individual documentation files.""" - initialize_globals() - - if DOCS_FOLDER is None: - raise HTTPException( - status_code=500, - detail="Documentation folder not configured. Please set DOCS_FOLDER environment variable or run with --docs-folder argument.", - ) - - # Security check: ensure we're only serving .md files and they exist in the docs folder - if not filename.endswith(".md"): - raise HTTPException(status_code=404, detail="Only markdown files are supported") - - file_path = Path(DOCS_FOLDER) / filename - - # Ensure the file is within the docs folder (prevent directory traversal) - try: - file_path = file_path.resolve() - docs_folder_resolved = Path(DOCS_FOLDER).resolve() - if not str(file_path).startswith(str(docs_folder_resolved)): - raise HTTPException(status_code=403, detail="Access denied") - except Exception: - raise HTTPException(status_code=403, detail="Invalid file path") - - if not file_path.exists(): - raise HTTPException(status_code=404, detail=f"File {filename} not found") - - try: - content = file_manager.load_text(file_path) - - html_content = markdown_to_html(content) - title = get_file_title(file_path) - - context = { - "title": title, - "content": html_content, - "navigation": MODULE_TREE, - "doc_paths": doc_path_map(str(DOCS_FOLDER), MODULE_TREE) if DOCS_FOLDER else None, - "current_page": filename, - } - - return HTMLResponse(content=render_template(DOCS_VIEW_TEMPLATE, context)) - - except Exception as e: - raise HTTPException(status_code=500, detail=f"Error reading {filename}: {e}") - - -# Mount static files -app.mount("/static", StaticFiles(directory="."), name="static") - - -def main(): - """Main function to run the documentation server.""" - parser = argparse.ArgumentParser( - description="Simple documentation server for hosting markdown documentation folders" - ) - parser.add_argument( - "--docs-folder", - type=str, - required=True, - help="Path to the documentation folder containing markdown files and module_tree.json", - ) - parser.add_argument( - "--port", type=int, default=8000, help="Port to run the server on (default: 8000)" - ) - parser.add_argument( - "--host", - type=str, - default="127.0.0.1", - help="Host to bind the server to (default: 127.0.0.1)", - ) - parser.add_argument("--debug", action="store_true", help="Run the server in debug mode") - - args = parser.parse_args() - - # Validate docs folder - docs_folder = Path(args.docs_folder) - if not docs_folder.exists(): - print(f"Error: Documentation folder '{docs_folder}' does not exist") - sys.exit(1) - - if not docs_folder.is_dir(): - print(f"Error: '{docs_folder}' is not a directory") - sys.exit(1) - - # Check for overview.md - overview_file = docs_folder / "overview.md" - if not overview_file.exists(): - print(f"Warning: overview.md not found in '{docs_folder}'") - - # Set global variables and environment variable for uvicorn reload - global DOCS_FOLDER, MODULE_TREE - DOCS_FOLDER = str(docs_folder.resolve()) - MODULE_TREE = load_module_tree(docs_folder) - - # Set environment variable so uvicorn reload can pick it up - import os - - os.environ["DOCS_FOLDER"] = DOCS_FOLDER - - print("πŸ“š Starting documentation server...") - print(f"πŸ“ Documentation folder: {DOCS_FOLDER}") - print(f"🌐 Server running at: http://{args.host}:{args.port}") - print("πŸ“– Main page: overview.md") - - if MODULE_TREE: - modules_count = len(MODULE_TREE) - print(f"πŸ—‚οΈ Found {modules_count} main modules in module_tree.json") - - print("\nPress Ctrl+C to stop the server") - - try: - import uvicorn - - uvicorn.run( - "visualise_docs:app", - host=args.host, - port=args.port, - reload=args.debug, - log_level="debug" if args.debug else "info", - ) - except KeyboardInterrupt: - print("\nπŸ‘‹ Server stopped") - - -if __name__ == "__main__": - main() diff --git a/codewiki/src/fe/web_app.py b/codewiki/src/fe/web_app.py deleted file mode 100644 index e09da282..00000000 --- a/codewiki/src/fe/web_app.py +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/env python3 -""" -CodeWiki Web Application - -A web interface for users to submit GitHub repositories for documentation generation. -Features: -- Simple web form for GitHub repo URL input -- Background processing queue -- Cache system for generated documentation -- Job status tracking -""" - -import argparse -from fastapi import FastAPI, Request, Form -from fastapi.responses import HTMLResponse - -from .cache_manager import CacheManager -from .background_worker import BackgroundWorker -from .routes import WebRoutes -from .config import WebAppConfig - - -# Initialize FastAPI app -app = FastAPI( - title="CodeWiki", description="Generate comprehensive documentation for any GitHub repository" -) - -# Initialize components -cache_manager = CacheManager( - cache_dir=WebAppConfig.CACHE_DIR, cache_expiry_days=WebAppConfig.CACHE_EXPIRY_DAYS -) -background_worker = BackgroundWorker(cache_manager=cache_manager, temp_dir=WebAppConfig.TEMP_DIR) -web_routes = WebRoutes(background_worker=background_worker, cache_manager=cache_manager) - - -# Register routes -@app.get("/", response_class=HTMLResponse) -async def index_get(request: Request): - """Main page with form for submitting GitHub repositories.""" - return await web_routes.index_get(request) - - -@app.post("/", response_class=HTMLResponse) -async def index_post(request: Request, repo_url: str = Form(...), commit_id: str = Form("")): - """Handle repository submission.""" - return await web_routes.index_post(request, repo_url, commit_id) - - -@app.get("/api/job/{job_id}") -async def get_job_status(job_id: str): - """API endpoint to get job status.""" - return await web_routes.get_job_status(job_id) - - -@app.get("/docs/{job_id}") -async def view_docs(job_id: str): - """View generated documentation.""" - return await web_routes.view_docs(job_id) - - -@app.get("/static-docs/{job_id}/") -@app.get("/static-docs/{job_id}/{filename:path}") -async def serve_generated_docs(job_id: str, filename: str = "overview.md"): - """Serve generated documentation files.""" - if not filename: - filename = "overview.md" - return await web_routes.serve_generated_docs(job_id, filename) - - -def main(): - """Main function to run the web application.""" - import uvicorn - - parser = argparse.ArgumentParser( - description="CodeWiki Web Application - Generate documentation for GitHub repositories" - ) - parser.add_argument( - "--host", - type=str, - default=WebAppConfig.DEFAULT_HOST, - help=f"Host to bind the server to (default: {WebAppConfig.DEFAULT_HOST})", - ) - parser.add_argument( - "--port", - type=int, - default=WebAppConfig.DEFAULT_PORT, - help=f"Port to run the server on (default: {WebAppConfig.DEFAULT_PORT})", - ) - parser.add_argument("--debug", action="store_true", help="Run the server in debug mode") - parser.add_argument("--reload", action="store_true", help="Enable auto-reload for development") - - args = parser.parse_args() - - # Ensure required directories exist - WebAppConfig.ensure_directories() - - # Start background worker - background_worker.start() - - print("πŸš€ CodeWiki Web Application starting...") - print(f"🌐 Server running at: http://{args.host}:{args.port}") - print(f"πŸ“ Cache directory: {WebAppConfig.get_absolute_path(WebAppConfig.CACHE_DIR)}") - print(f"πŸ—‚οΈ Temp directory: {WebAppConfig.get_absolute_path(WebAppConfig.TEMP_DIR)}") - print("\nPress Ctrl+C to stop the server") - - try: - uvicorn.run( - "fe.web_app:app", - host=args.host, - port=args.port, - reload=args.reload, - log_level="debug" if args.debug else "info", - ) - except KeyboardInterrupt: - print("\nπŸ‘‹ Server stopped") - background_worker.stop() - - -if __name__ == "__main__": - main() diff --git a/docker/Dockerfile b/docker/Dockerfile index 38fca3c2..c68e943a 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -1,46 +1,26 @@ -# Use Python 3.12 slim image as base FROM python:3.12-slim -# Set working directory WORKDIR /app -# Install system dependencies -RUN apt-get update && apt-get install -y \ - git \ - curl \ - nodejs \ - npm \ +# Node.js/npm are needed at install time by PythonMonkey (mermaid-parser-py). +RUN apt-get update && apt-get install -y --no-install-recommends \ + git nodejs npm \ && rm -rf /var/lib/apt/lists/* -# Copy requirements first for better caching COPY requirements.txt . - -# Install Python dependencies RUN pip install --no-cache-dir -r requirements.txt -# tree-sitter-language-pack 1.x downloads each grammar on first use. Fetch the -# ones the analyzers load at build time, so the image runs offline. +# Preload the grammars used by the analyzers for offline repository analysis. RUN python -c "import tree_sitter_language_pack as t; t.download(['dart', 'go', 'javascript', 'lean', 'typescript', 'vue', 'zig'])" -# Copy application code COPY codewiki ./codewiki -COPY img ./img -COPY pyproject.toml . -COPY README.md . - -# Create output directories -RUN mkdir -p output/cache output/temp output/docs output/dependency_graphs +COPY pyproject.toml README.md ./ +RUN pip install --no-cache-dir --no-deps . -# Set environment variables -ENV PYTHONPATH=/app ENV PYTHONUNBUFFERED=1 +ENV CODEWIKI_NO_KEYRING=1 -# Expose port -EXPOSE 8000 - -# Health check -HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \ - CMD curl -f http://localhost:8000/ || exit 1 - -# Default command -CMD ["python", "codewiki/run_web_app.py", "--host", "0.0.0.0", "--port", "8000"] +# The target repository, including its generated docs, is mounted here. +WORKDIR /workspace +ENTRYPOINT ["python", "-m", "codewiki"] +CMD ["--help"] diff --git a/docker/.dockerignore b/docker/Dockerfile.dockerignore similarity index 95% rename from docker/.dockerignore rename to docker/Dockerfile.dockerignore index ea5641df..e99c5e28 100644 --- a/docker/.dockerignore +++ b/docker/Dockerfile.dockerignore @@ -13,7 +13,7 @@ docker-compose* !env.example # Python -__pycache__/ +**/__pycache__/ *.py[cod] *$py.class *.so @@ -35,7 +35,8 @@ wheels/ *.egg # Virtual environments -.ven +**/.venv/ +venv/ env/ ENV/ diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 28084e7f..bcf802f7 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -1,34 +1,14 @@ services: codewiki: - image: codewiki:0.0.1 + image: codewiki:local build: context: .. dockerfile: docker/Dockerfile - container_name: codewiki - ports: - - "${APP_PORT:-8000}:8000" environment: - - PYTHONPATH=/app - - PYTHONUNBUFFERED=1 - env_file: - - ../.env - networks: - - net + CODEWIKI_NO_KEYRING: "1" volumes: - # Persistent storage for cache and output - - ../output:/app/output - # Git credentials (if needed for private repos) - # - ~/.gitconfig:/root/.gitconfig:ro - - ~/.ssh:/root/.ssh:ro - restart: unless-stopped - healthcheck: - test: ["CMD", "curl", "-f", "http://localhost:8000/"] - interval: 30s - timeout: 10s - retries: 3 - start_period: 20s + - "${CODEWIKI_REPO:-..}:/workspace" + - codewiki-config:/root/.codewiki -networks: - net: - external: true - name: codewiki-network +volumes: + codewiki-config: diff --git a/docker/env.example b/docker/env.example index e8d8c9ea..8950fd57 100644 --- a/docker/env.example +++ b/docker/env.example @@ -1,34 +1,9 @@ -# Copy this file to .env and fill in your API keys - -# ============================================================================= -# LLM API Keys -# ============================================================================= - -MAIN_MODEL = claude-sonnet-4 -FALLBACK_MODEL_1 = glm-4p5 -CLUSTER_MODEL = claude-sonnet-4 -LLM_BASE_URL = http://litellm:4000/ -LLM_API_KEY = sk-1234 - - -# ============================================================================= -# Application Configuration -# ============================================================================= - -# Port for the main web application -APP_PORT=8000 - - -# ============================================================================= -# Logfire Configuration -# ============================================================================= - -# Logfire authentication token (get from ~/.logfire/default.toml after running 'logfire auth') -LOGFIRE_TOKEN= - -# Optional: Logfire project name (defaults to auto-detection) -LOGFIRE_PROJECT_NAME=codewiki - -# Optional: Logfire service name -LOGFIRE_SERVICE_NAME=codewiki - +# Copy to .env in the project root, or set CODEWIKI_REPO in your shell. +# Use an absolute path to the Git repository you want to document. +# The default (..) is relative to docker/docker-compose.yml: CodeWiki itself. +CODEWIKI_REPO=.. + +# Configure the provider using `docker compose ... run --rm codewiki config set`. +# CLI configuration persists in the codewiki-config volume; the container uses +# file-based credential storage because a system keyring is unavailable. +# The former web app's APP_PORT and LLM_* environment settings are not used. diff --git a/docs/Backend_Agent_Tools.md b/docs/Backend_Agent_Tools.md deleted file mode 100644 index bab737d6..00000000 --- a/docs/Backend_Agent_Tools.md +++ /dev/null @@ -1,239 +0,0 @@ -# Backend Agent Tools - -## Purpose - -The **Backend Agent Tools** module provides the low-level, agent-facing "hands" that CodeWiki's -LLM-driven documentation agents use to actually read code and write documentation files. It is -intentionally small and dependency-light: it does not decide *what* documentation to write (that -is the job of the orchestration layer in -[Backend LLM & Documentation Services](Backend_LLM_&_Documentation_Services.md)), it only exposes -safe, well-defined **tool functions** that an LLM agent can call, plus the **shared dependency -bag** (`CodeWikiDeps`) that carries per-run context (paths, component registry, module tree, -config, etc.) into every tool invocation. - -Concretely, this module contains: - -- `CodeWikiDeps` β€” a dataclass bundling all contextual state a tool needs to run safely for a - given documentation-generation session/module. -- `EditTool` (+ helpers `Filemap`, `WindowExpander`) and the `str_replace_editor` tool function β€” - a sandboxed file-viewing/editing tool (modeled after SWE-agent's editor) that lets an agent - inspect repository source code (read-only) and create/edit documentation markdown files - (read-write), with automatic Mermaid diagram validation on every markdown write. - -This module is consumed by two different agent runtime backends: - -- The **pydantic-ai** backend (`PydanticAIBackend` in - [Backend LLM & Documentation Services](Backend_LLM_&_Documentation_Services.md)), which registers - `str_replace_editor_tool` (a `pydantic_ai.Tool` wrapper around the `str_replace_editor` - function) directly. -- The **caw** backend (`CawBackend` / `CawToolKit`, also in - [Backend LLM & Documentation Services](Backend_LLM_&_Documentation_Services.md)), whose - `CawToolKit.str_replace_editor` MCP tool re-uses the very same `EditTool` implementation and - Mermaid validator from this module, adding extra path-confinement checks appropriate for an - MCP tool-server context. - -## Architecture Overview - -```mermaid -flowchart TB - subgraph Orchestration["Backend LLM & Documentation Services"] - PAB["PydanticAIBackend"] - CB["CawBackend / CawToolKit"] - DG["DocumentationGenerator"] - end - - subgraph AgentTools["Backend_Agent_Tools (this module)"] - Deps["CodeWikiDeps\n(deps.py)"] - SRE["str_replace_editor()\n+ str_replace_editor_tool\n(str_replace_editor.py)"] - ET["EditTool"] - FM["Filemap"] - WE["WindowExpander"] - SRE --> ET - ET --> FM - ET --> WE - end - - subgraph Support["Supporting modules"] - Node["Node\n(Dependency_Analyzer_Core)"] - Config["Config\n(Core_Config_&_Utils)"] - MermaidVal["validate_mermaid_diagrams()\n(be/utils.py)"] - end - - DG --> PAB - DG --> CB - PAB -->|registers Tool| SRE - CB -->|delegates to| ET - Deps -.uses.-> Node - Deps -.uses.-> Config - SRE -->|on .md write| MermaidVal - - PAB -- "RunContext[CodeWikiDeps]" --> Deps - CB -- "self._deps: CodeWikiDeps" --> Deps -``` - -### Two working directories, one tool - -The editor tool always operates against exactly one of two root directories, selected per call via -the `working_dir` parameter: - -| `working_dir` | Root path | Allowed commands | Purpose | -|----------------|-----------------------------------|-----------------------------|--------------------------------------------| -| `"repo"` | `CodeWikiDeps.absolute_repo_path` | `view` only | Inspect the target repository's source code | -| `"docs"` | `CodeWikiDeps.absolute_docs_path` | `view`, `create`, `str_replace`, `insert`, `undo_edit` | Read/write the generated documentation tree | - -This split enforces a hard invariant: **agents can never mutate the source repository**, only the -documentation output. Any attempt to run a mutating command against `"repo"` is rejected before -the underlying `EditTool` is even invoked. - -```mermaid -sequenceDiagram - participant Agent as LLM Agent - participant Tool as str_replace_editor() - participant Edit as EditTool - participant FS as Filesystem - participant Val as validate_mermaid_diagrams() - - Agent->>Tool: command, working_dir, path, ... - Tool->>Tool: resolve absolute_path via CodeWikiDeps - alt working_dir == "repo" and command != "view" - Tool-->>Agent: error: only `view` allowed on repo - else valid request - Tool->>Edit: validate_path(command, path) - Edit->>FS: read/write/list as needed - Edit-->>Tool: log messages (result/errors) - opt command != "view" and path endswith .md - Tool->>Val: validate_mermaid_diagrams(path) - Val-->>Tool: validation report - end - Tool-->>Agent: combined result string - end -``` - -## Core Components - -### `CodeWikiDeps` (`deps.py`) - -A plain dataclass acting as the **dependency-injection context** passed to every tool call. It is -constructed once per module-documentation task and threaded through the agent runtime as -`RunContext[CodeWikiDeps].deps` (pydantic-ai) or `self._deps` (caw's `CawToolKit`). - -| Field | Type | Description | -|---|---|---| -| `absolute_docs_path` | `str` | Root directory for generated documentation (the `"docs"` working dir root). | -| `absolute_repo_path` | `str` | Root directory of the analyzed repository (the `"repo"` working dir root). | -| `registry` | `dict` | A mutable, per-session key/value store (e.g. used by `EditTool` to persist `file_history` for `undo_edit`). | -| `components` | `dict[str, Node]` | Map of component id β†’ `Node` (from [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)), the source-of-truth for `read_code_components`. | -| `path_to_current_module` | `list[str]` | Breadcrumb path in the module tree identifying the module currently being documented (used for recursive sub-module generation). | -| `current_module_name` | `str` | Name of the module currently being documented. | -| `module_tree` | `dict[str, any]` | The in-memory hierarchical module tree being built up as documentation is generated. | -| `max_depth` / `current_depth` | `int` | Guards recursion depth for sub-module documentation generation. | -| `config` | `Config` | LLM/runtime configuration (see [Core_Config_&_Utils](Core_Config_&_Utils.md)). | -| `custom_instructions` | `str \| None` | Optional user-supplied custom instructions injected into agent prompts. | - -`CodeWikiDeps` itself contains no logic β€” it is intentionally inert so that both the pydantic-ai -and caw backends can share the exact same context shape. - -### `str_replace_editor` tool function & `EditTool` (`str_replace_editor.py`) - -This is the heart of the module: a sandboxed file editor exposing the classic -view/create/str_replace/insert/undo_edit command set (a design borrowed from -[SWE-agent's editor tool](https://github.com/SWE-agent/SWE-agent/blob/main/tools/edit_anthropic/bin/str_replace_editor)). - -**Public entry points:** - -- `str_replace_editor(ctx, working_dir, command, path, ...)` β€” the async tool function registered - with pydantic-ai. Resolves `working_dir` + `path` into an absolute path scoped to either the repo - or docs root, enforces the repo-is-read-only rule, delegates to `EditTool`, and β€” for any - non-`view` write to a `.md` file β€” runs `validate_mermaid_diagrams` on the result and appends the - validation report to the tool output so the agent immediately sees Mermaid syntax errors. -- `str_replace_editor_tool` β€” a `pydantic_ai.Tool` wrapping the function above, registered by - `PydanticAIBackend`. -- `EditTool` β€” the actual command implementation, reusable outside of pydantic-ai (this is exactly - what `CawToolKit.str_replace_editor` does, adding its own path-confinement checks for the MCP - context β€” see [Backend LLM & Documentation Services](Backend_LLM_&_Documentation_Services.md)). - -**Commands implemented by `EditTool`:** - -| Command | Behavior | -|---|---| -| `view` | For directories: lists non-hidden entries up to 2 levels deep. For files: shows `cat -n`-style numbered output, optionally scoped to a `view_range`, with the viewport auto-expanded to whole function/class boundaries via `WindowExpander`. Long files can be summarized with `Filemap` (currently gated by `USE_FILEMAP`). | -| `create` | Creates a new file; fails if the file already exists. | -| `str_replace` | Replaces a unique occurrence of `old_str` with `new_str`; fails loudly if `old_str` is missing or ambiguous (multiple matches). Optionally runs `flake8` before/after the edit and reports newly introduced lint errors (gated by `USE_LINTER`). | -| `insert` | Inserts `new_str` after a given 1-based `insert_line`. | -| `undo_edit` | Pops and restores the previous version of a file from an in-`registry` edit history. | - -All results are accumulated as human-readable log strings in `EditTool.logs`, which the tool -function joins and returns to the agent β€” there are no raised exceptions for expected error -conditions (invalid path, ambiguous replace, etc.), keeping the agent loop resilient to bad tool -calls. - -**Helper classes:** - -- **`Filemap`** β€” uses `tree_sitter_languages` to parse Python source and produce an "abbreviated" - view of a file where long function bodies (β‰₯ 5 lines) are elided with a placeholder line, - keeping large-file previews compact. Only used when a file exceeds `MAX_RESPONSE_LEN` and - `USE_FILEMAP` is enabled. -- **`WindowExpander`** β€” given a requested `[start, stop]` line range, tries to "snap" the viewport - boundaries to natural breakpoints (blank lines, `def`/`class`/decorator lines for `.py` files, or - file start/end) so that `view` and edit-confirmation snippets show whole logical blocks instead - of arbitrarily truncated code. Expansion amount is bounded by module-level constants - (`MAX_WINDOW_EXPANSION_VIEW`, `MAX_WINDOW_EXPANSION_EDIT_CONFIRM`), both currently set to `0` - (i.e. expansion is disabled by default but the mechanism remains in place). - -**Safety/robustness features baked into the tool:** - -- Strict path validation (`validate_path`): must be absolute, must exist unless creating, cannot - overwrite an existing file with `create`, only `view` is allowed on directories. -- `_coerce_json_string` (via a Pydantic `BeforeValidator`) transparently parses list/int arguments - that arrive as JSON-encoded strings β€” a compatibility shim for OpenAI-compatible endpoints - (LiteLLM, vLLM, Ollama, etc.) that don't always emit strictly-typed tool arguments the way the - native Anthropic API does. -- Output truncation (`maybe_truncate` / `MAX_RESPONSE_LEN` / `TRUNCATED_MESSAGE`) prevents any - single tool call from flooding the agent's context window; the truncation message explicitly - instructs the agent to retry with `grep -n` + `view_range`. -- Robust file I/O: `read_file` tries a sequence of encodings (`None` β†’ `utf-8` β†’ `latin-1` β†’ - `utf-8` with `errors="replace"`) to gracefully handle non-UTF-8 source files (e.g. Windows/GBK - paths), and `view`/`flake8` subprocess output decoding also uses `errors="replace"`. -- Automatic **Mermaid diagram validation**: any non-`view` write to a `.md` file triggers - `validate_mermaid_diagrams` (from `codewiki/src/be/utils.py`), and its report β€” including - precise error locations β€” is appended to the tool result so the documentation agent can - self-correct malformed diagrams in the same turn. - -## Relationship to Other Modules - -```mermaid -flowchart LR - Deps["CodeWikiDeps"] --> Node["Node\n(Dependency_Analyzer_Core)"] - Deps --> Config["Config\n(Core_Config_&_Utils)"] - - subgraph BE["Backend LLM & Documentation Services"] - PAB["PydanticAIBackend"] - CB["CawBackend"] - Toolkit["CawToolKit"] - end - - PAB --> SRE_Tool["str_replace_editor_tool"] - SRE_Tool --> SRE_Fn["str_replace_editor()"] - SRE_Fn --> Deps - - Toolkit --> ET["EditTool (reused)"] - Toolkit --> Deps - ET --> Deps -``` - -- **[Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)**: Supplies the `Node` model that - populates `CodeWikiDeps.components` β€” the registry that both `read_code_components` (in - `CawToolKit`) and the editor's repo-view path ultimately reason about. -- **[Core_Config_&_Utils](Core_Config_&_Utils.md)**: Supplies the `Config` object stored in - `CodeWikiDeps.config`, carrying LLM/model/provider settings and doc-generation options - (`max_depth`, `agent_instructions`, etc.) that flow into agent prompts alongside these tools. - `FileManager` in the same module handles broader file-system utilities used elsewhere in the - pipeline. -- **[Backend LLM & Documentation Services](Backend_LLM_&_Documentation_Services.md)**: The primary - consumer of this module. `PydanticAIBackend` registers `str_replace_editor_tool` for its agent - runs; `CawBackend`/`CawToolKit` reuse `EditTool` and the Mermaid validator directly inside an MCP - tool server, and drive the recursive sub-module documentation flow (`generate_sub_module_documentation`) - that ultimately writes files through this same editor. -- **[MCP_Session_Management](MCP_Session_Management.md)**: Manages the session/workspace lifecycle - (`SessionStore`, `SessionWorkspace`) within which `CawToolKit`'s tool calls β€” including the reused - `EditTool` β€” execute over MCP. diff --git a/docs/Backend_LLM_&_Documentation_Services.md b/docs/Backend_LLM_&_Documentation_Services.md deleted file mode 100644 index 63d278d4..00000000 --- a/docs/Backend_LLM_&_Documentation_Services.md +++ /dev/null @@ -1,218 +0,0 @@ -# Backend LLM & Documentation Services - -## Purpose - -This module is the **engine room of CodeWiki's documentation generation**. It -owns: - -1. **The LLM backend abstraction** β€” a single interface (`LLMBackend`) that - lets the rest of the system call an LLM without caring whether the call - goes through an API key (OpenAI-compatible / Anthropic / Bedrock / - Azure-OpenAI via pydantic-ai) or through the user's Claude/Codex CLI - subscription (via the `caw` library). -2. **The top-level orchestrator** (`DocumentationGenerator`) that turns a - dependency graph + module tree into a finished set of markdown pages β€” - clustering modules, walking the tree leaves-first, running the per-module - agent loop, and stitching parent/repo overviews on top. - -Everything upstream of this module (dependency graph construction, module -clustering input, agent tool implementations) is documented elsewhere and -linked below; this module is the piece that actually *drives the agents* and -decides *which backend* runs them. - -## How this module fits in the system - -```mermaid -flowchart TD - subgraph Entry["Entry points"] - CLI["CLI\n(Backend_LLM_&_Documentation_Services is invoked via CLIDocumentationGenerator)"] - FE["Frontend Web App\n(background_worker.py)"] - end - - subgraph ThisModule["Backend_LLM_&_Documentation_Services"] - DG["DocumentationGenerator"] - BK["LLMBackend (interface)\nget_backend()"] - PA["PydanticAIBackend"] - CB["CawBackend"] - CT["CawToolKit (MCP server)"] - LS["llm_services\n(CompatibleOpenAIModel, CachingOpenAIModel)"] - end - - subgraph Deps["Depended-on modules"] - DAC["Dependency_Analyzer_Core\n(DependencyGraphBuilder, Node, AnalysisResult)"] - DAS["Dependency_Analysis_Service\n(AnalysisService, RepoAnalyzer)"] - AT["Backend_Agent_Tools\n(CodeWikiDeps, EditTool, str_replace_editor)"] - CFG["Core_Config_&_Utils\n(Config, FileManager)"] - end - - CLI --> DG - FE --> DG - DG --> DAC - DAC --> DAS - DG --> BK - BK --> PA - BK --> CB - PA --> LS - PA --> AT - CB --> CT - CT --> AT - DG --> CFG - PA --> CFG - CB --> CFG -``` - -* [CLI](CLI.md) invokes documentation generation through - `CLIDocumentationGenerator`, which ultimately constructs and runs a - `DocumentationGenerator` from this module. -* [Frontend_Web_App](Frontend_Web_App.md) does the same from - `background_worker.py` for web-submitted jobs. -* [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) supplies the - `DependencyGraphBuilder`, `Node`/`Repository` models, and the module-tree - JSON files (`module_tree.json`, `first_module_tree.json`) this module reads - and writes. -* [Dependency_Analysis_Service](Dependency_Analysis_Service.md) and - [Language_Analyzers](Language_Analyzers.md) sit underneath the graph - builder and are not called directly from here. -* [Backend_Agent_Tools](Backend_Agent_Tools.md) provides `CodeWikiDeps` (the - per-agent-run state object) and the `EditTool`/`str_replace_editor` - implementation that both backends reuse for file writes and Mermaid - validation. -* [Core_Config_&_Utils](Core_Config_&_Utils.md) provides the `Config` object - (provider, model names, thresholds, paths) and `FileManager` for JSON/text - I/O, used throughout this module. -* [MCP_Session_Management](MCP_Session_Management.md) is unrelated to LLM - calls; it manages per-session workspaces for the MCP server front-end and - is not a dependency of this module. - -## Sub-modules - -| Sub-module | Documentation | Responsibility | -|---|---|---| -| API-key backend & model layer | [Backend_LLM_&_Documentation_Services_pydantic_ai_backend.md](Backend_LLM_&_Documentation_Services_pydantic_ai_backend.md) | `LLMBackend` interface, provider selection (`get_backend`), `PydanticAIBackend` (pydantic-ai `Agent` + tool functions), and the `llm_services` model layer (`CompatibleOpenAIModel`, `CachingOpenAIModel`, fallback-model construction) | -| Subscription (caw) backend | [Backend_LLM_&_Documentation_Services_caw_backend.md](Backend_LLM_&_Documentation_Services_caw_backend.md) | `CawBackend` (routes through the `claude`/`codex` CLI) and `CawToolKit` (the MCP tool server exposing CodeWiki's tools to a caw agent) | -| Documentation orchestration | [Backend_LLM_&_Documentation_Services_documentation_generator.md](Backend_LLM_&_Documentation_Services_documentation_generator.md) | `DocumentationGenerator`: clustering trigger, leaf-first processing order, per-module agent dispatch, parent/repo overview assembly, and post-run validation | - -## Architecture overview - -### Backend selection - -`get_backend(config)` is the single seam where provider choice becomes a -concrete class. Everything else in the codebase (the orchestrator, the -clustering step) talks only to the abstract `LLMBackend` interface. - -```mermaid -classDiagram - class LLMBackend { - <> - +complete(prompt, model=None) str - +run_module_agent(module_name, components, core_component_ids, module_path, working_dir) dict - } - class PydanticAIBackend { - -_fallback_models: FallbackModel - +complete(prompt, model=None) str - +run_module_agent(...) dict - } - class CawBackend { - -_caw_provider: str - -_model: str - +complete(prompt, model=None) str - +run_module_agent(...) dict - -_run_module_agent_sync(...) dict - } - LLMBackend <|-- PydanticAIBackend - LLMBackend <|-- CawBackend - - class get_backend { - <> - } - get_backend --> LLMBackend : returns -``` - -* `provider in {"claude-code", "codex"}` (`is_caw_provider`) β†’ `CawBackend` -* every other provider value (`openai-compatible`, `anthropic`, `bedrock`, - `azure-openai`) β†’ `PydanticAIBackend` - -See [Backend_LLM_&_Documentation_Services_pydantic_ai_backend.md](Backend_LLM_&_Documentation_Services_pydantic_ai_backend.md) -and [Backend_LLM_&_Documentation_Services_caw_backend.md](Backend_LLM_&_Documentation_Services_caw_backend.md) -for the two implementations. - -### End-to-end generation flow - -```mermaid -sequenceDiagram - participant Caller as CLI / Web worker - participant DG as DocumentationGenerator - participant CM as cluster_modules - participant Backend as LLMBackend - participant FS as FileManager (module_tree.json, *.md) - - Caller->>DG: run() - DG->>DG: graph_builder.build_dependency_graph() - alt no cached module tree - DG->>CM: cluster_modules(leaf_nodes, components, completer=backend.complete) - CM-->>DG: module_tree - DG->>FS: save first_module_tree.json / module_tree.json - end - DG->>DG: get_processing_order() (leaf modules first) - loop each module, leaves before parents - alt leaf module - DG->>Backend: run_module_agent(module_name, core_component_ids, ...) - Backend-->>FS: writes {module_name}.md, updates module_tree.json - else parent module - DG->>Backend: complete(MODULE_OVERVIEW_PROMPT) - Backend-->>FS: writes {module_name}.md - end - end - DG->>Backend: complete(REPO_OVERVIEW_PROMPT) - Backend-->>FS: writes overview.md - DG->>DG: validate_generated_docs() -> raise IncompleteDocumentationError if any .md missing -``` - -Full detail on this flow lives in -[Backend_LLM_&_Documentation_Services_documentation_generator.md](Backend_LLM_&_Documentation_Services_documentation_generator.md). - -### Per-module agent loop, both backends - -Both backends implement the same contract (`run_module_agent`) but drive it -with different agent runtimes and different tool-call surfaces: - -```mermaid -flowchart LR - subgraph PydanticAIBackend - A1["pydantic_ai.Agent\n+ CachingOpenAIModel / FallbackModel"] --> A2["tools: read_code_components_tool,\nstr_replace_editor_tool,\ngenerate_sub_module_documentation_tool"] - end - subgraph CawBackend - B1["caw.Agent\n(claude / codex CLI)"] --> B2["CawToolKit (MCP server):\nread_code_components,\nstr_replace_editor,\ngenerate_sub_module_documentation"] - end - A2 -. same tool contract .- B2 -``` - -Both tool surfaces ultimately call into -[Backend_Agent_Tools](Backend_Agent_Tools.md) (`CodeWikiDeps`, `EditTool`) -and recurse into sub-modules using the same `is_complex_module` / -`max_token_per_leaf_module` / `max_depth` gating logic, so a module produces -equivalent documentation regardless of which backend generated it. - -## Key cross-cutting concerns - -- **Module tree as shared state**: `module_tree.json` (and the initial - `first_module_tree.json` snapshot from clustering) is the single source of - truth for hierarchy. Both backends load/mutate/save it, and sub-agent - delegation (`generate_sub_module_documentation`) adds new branches to it - in-memory before persisting. Name collisions across the (flat) docs - directory are resolved by `module_naming.normalize_sub_module_specs` / - `dedupe_module_tree_names`. -- **Recursion budget**: `config.max_depth` and `config.max_token_per_leaf_module` - gate whether a module can delegate to sub-agents (`is_complex_module` - + token count), preventing runaway fan-out on deeply nested repos. -- **Idempotency**: every entry point checks for an existing `overview.md` or - `{module_name}.md` before doing any work, so a crashed run can be resumed - by re-invoking generation over the same `docs_dir`. -- **Validation**: `DocumentationGenerator.validate_generated_docs` / - `IncompleteDocumentationError` guarantee that a "successful" run actually - produced every promised `.md` file, not just an updated tree in memory. - -Configuration (`Config`, provider/model fields, thresholds) is defined in -[Core_Config_&_Utils](Core_Config_&_Utils.md); the underlying source-analysis -data structures (`Node`, `Repository`, `AnalysisResult`) come from -[Dependency_Analyzer_Core](Dependency_Analyzer_Core.md). diff --git a/docs/Backend_LLM_&_Documentation_Services_caw_backend.md b/docs/Backend_LLM_&_Documentation_Services_caw_backend.md deleted file mode 100644 index 254d9348..00000000 --- a/docs/Backend_LLM_&_Documentation_Services_caw_backend.md +++ /dev/null @@ -1,458 +0,0 @@ -# Backend LLM & Documentation Services β€” `caw_backend` - -## Introduction - -This module implements **subscription-mode LLM execution** for CodeWiki via the `caw` -library, which wraps the official **Claude Code** and **Codex** CLI binaries. Instead of -calling a hosted chat-completions API with a metered API key, `CawBackend` authenticates -using the developer's existing OAuth CLI login (`claude login` / `codex login`) and drives -the CLI's own agent loop β€” including its native file-editing, tool-calling, and MCP -capabilities β€” to perform documentation generation. - -The module consists of two tightly coupled components: - -- **`CawBackend`** (`codewiki/src/be/caw_backend.py`) β€” the `LLMBackend` implementation - that owns provider resolution, single-shot completions, and the per-module agent - run/recursion driver. -- **`CawToolKit`** (`codewiki/src/be/caw_toolkit.py`) β€” an MCP tool server (subclass of - `caw.ToolKit`) exposing CodeWiki's three agent tools (`read_code_components`, - `str_replace_editor`, `generate_sub_module_documentation`) to the CLI-driven agent. - -Together they are a **sibling implementation** of -[`Backend_LLM_&_Documentation_Services_pydantic_ai_backend`](Backend_LLM_&_Documentation_Services_pydantic_ai_backend.md), -which instead drives a hosted LLM through `pydantic-ai`. Both backends implement the same -abstract contract, `LLMBackend`, and are invoked identically by -[`DocumentationGenerator`](Backend_LLM_&_Documentation_Services_documentation_generator.md). -Selecting which one runs at a given invocation is a matter of `Config.provider` β€” this -module is chosen when `provider` is `"claude-code"` or `"codex"`. - ---- - -## Position in the System - -```mermaid -flowchart TB - subgraph CLI_and_Config["Entry Points"] - CLI["CLI Documentation Generation
(CLIDocumentationGenerator)"] - Config["Core Config & Utils
(Config)"] - end - - subgraph DocGen["Backend_LLM_&_Documentation_Services_documentation_generator"] - DG[DocumentationGenerator] - end - - subgraph Backends["LLMBackend implementations"] - CB[CawBackend] - PA["PydanticAIBackend
(sibling module)"] - end - - subgraph ThisModule["This module: caw_backend"] - CTK[CawToolKit] - end - - subgraph AgentDeps["Backend_Agent_Tools"] - Deps[CodeWikiDeps] - Editor[EditTool] - end - - subgraph CawLib["caw (external library)"] - CawAgent[CawAgent] - ClaudeSession[ClaudeCodeSession] - CodexSession[CodexSession] - end - - CLI --> Config --> DG - DG -->|"config.provider ∈ {claude-code, codex}"| CB - DG -.->|"config.provider = openai-compatible / anthropic / ..."| PA - CB -->|creates per module| CTK - CTK -->|reads/mutates| Deps - CTK -->|delegates edits| Editor - CB --> CawAgent - CawAgent --> ClaudeSession - CawAgent --> CodexSession - CTK -.->|registered as tool_servers| CawAgent - - style ThisModule fill:#eef,stroke:#448 -``` - -`CawBackend` is instantiated by the backend factory used inside -`DocumentationGenerator.__init__` (`get_backend(config)`), based on `Config.provider`. -It depends on: - -- [`LLMBackend`](Backend_LLM_&_Documentation_Services_pydantic_ai_backend.md) β€” the abstract - base class it implements. -- [`CodeWikiDeps` and `EditTool`](Backend_Agent_Tools.md) β€” shared agent-tool state and the - file-editing/Mermaid-validation implementation reused from the pydantic-ai path. -- `codewiki/src/be/module_naming.py::normalize_sub_module_specs` β€” sub-module name - collision resolution, shared with the pydantic-ai backend's equivalent tool. -- `codewiki/src/be/prompt_template.py` β€” prompt formatting functions - (`format_system_prompt`, `format_leaf_system_prompt`, `format_user_prompt`). -- `codewiki/src/be/cluster_modules.py::format_potential_core_components` and - `codewiki/src/be/utils.py` (`count_tokens`, `is_complex_module`, `set_main_loop`, - `validate_mermaid_diagrams`) β€” shared heuristics/utilities also used by the pydantic-ai - backend, so both backends decide leaf-vs-delegate module handling identically. -- `Config` (from [`Core_Config_&_Utils`](Core_Config_&_Utils.md)) β€” carries provider, - model, depth, and token-threshold settings. -- The external `caw` package β€” `Agent`, `ToolGroup`, `ToolKit`/`tool` decorator, and - provider session classes (`ClaudeCodeSession`, `CodexSession`). - ---- - -## `CawBackend` - -### Responsibilities - -1. **Provider resolution** β€” maps CodeWiki's `provider` config value - (`"claude-code"` / `"codex"`) to caw's internal provider key (`"claude_code"` / - `"codex"`) and to the CLI binary name (`claude` / `codex`) used for a PATH sanity check. -2. **Single-shot completion** (`complete`) β€” used for clustering prompts and parent/repo - overview generation, where no tool-calling agent loop is needed. -3. **Per-module agent orchestration** (`run_module_agent` / `_run_module_agent_sync`) β€” - builds a `CodeWikiDeps`, decides whether the module can delegate to sub-agents, builds - a `CawToolKit`, and drives a `caw.Agent` completion for the module. -4. **Recursive sub-module delegation** β€” `_run_module_agent_sync` is re-entered directly - (bypassing the async entry point) by `CawToolKit._run_sub_modules` when a module's - agent decides to fan out documentation to child modules. -5. **Environment/process hardening** β€” several module-level monkeypatches address gaps - in the upstream `caw` library (see [Stopgap Patches](#stopgap-patches-applied-at-import-time)). - -### Class diagram - -```mermaid -classDiagram - class LLMBackend { - <> - +complete(prompt, model) str - +run_module_agent(...) dict - } - - class CawBackend { - -_config: Config - -_caw_provider: str - -_model: str | None - -_repo_root: str - +__init__(config) - +complete(prompt, model) str - +run_module_agent(module_name, components, core_component_ids, module_path, working_dir) dict - -_run_module_agent_sync(module_name, components, core_component_ids, module_path, working_dir, start_depth, module_tree) dict - } - - class CawToolKit { - -_deps: CodeWikiDeps - -_backend: CawBackend - -_allow_subagent: bool - +read_code_components(component_ids) str - +str_replace_editor(working_dir, command, ...) str - +generate_sub_module_documentation(sub_module_specs, ctx) str - -_run_sub_modules(sub_module_specs) str - } - - class CodeWikiDeps { - +absolute_docs_path - +absolute_repo_path - +components - +module_tree - +current_module_name - +path_to_current_module - +current_depth - +max_depth - } - - LLMBackend <|-- CawBackend - CawBackend "1" *-- "per module" CawToolKit : creates - CawToolKit --> CodeWikiDeps : reads/mutates - CawToolKit --> CawBackend : recursion callback (_run_module_agent_sync) -``` - -### Provider & tool-group mapping - -| CodeWiki `provider` | caw provider key | CLI binary | Agent tool group | -|---|---|---|---| -| `claude-code` | `claude_code` | `claude` | `READER \| PARALLEL` | -| `codex` | `codex` | `codex` | `READER \| PARALLEL \| EXEC` | - -`ToolGroup.WRITER` (Write/Edit/NotebookEdit) and `ToolGroup.INTERACTION` -(AskUserQuestion) and `ToolGroup.WEB` are always excluded β€” the agent is forced to use -CodeWiki's own `str_replace_editor` tool so that every markdown write goes through the -same Mermaid-diagram validation path as the pydantic-ai backend. Codex additionally gets -`ToolGroup.EXEC` because Codex's non-interactive `exec` mode otherwise cancels MCP tool -calls unless sandboxed with `--dangerously-bypass-approvals-and-sandbox`. - -### `complete()` β€” single-shot completions - -Used by `DocumentationGenerator` for: -- Module clustering prompts (`cluster_modules`, via a `completer` lambda bound to - `cluster_model`). -- Parent/repository overview generation (`generate_parent_module_docs`). - -```mermaid -sequenceDiagram - participant DG as DocumentationGenerator - participant CB as CawBackend - participant Agent as caw.Agent - participant CLI as claude / codex CLI - - DG->>CB: complete(prompt, model=cluster_model) - CB->>Agent: CawAgent(provider, model, tools=READER) - Agent->>CLI: spawn subprocess, send prompt - CLI-->>Agent: trajectory result - Agent-->>CB: traj.result - CB-->>DG: text -``` - -This call **blocks the calling thread** for the life of the CLI subprocess. Callers from -async contexts (like clustering inside `DocumentationGenerator.run`) accept this since no -concurrent work needs to happen during clustering. - -### `run_module_agent()` / `_run_module_agent_sync()` β€” per-module documentation - -This is the core agentic entry point, called once per module in -`DocumentationGenerator.generate_module_documentation`'s processing loop (leaf modules -first, then parents β€” see -[`Backend_LLM_&_Documentation_Services_documentation_generator`](Backend_LLM_&_Documentation_Services_documentation_generator.md)). - -```mermaid -flowchart TD - Start([run_module_agent async]) --> SetLoop["set_main_loop(current loop)
(for Mermaid validator thread hand-off)"] - SetLoop --> ToThread["asyncio.to_thread(_run_module_agent_sync, ...)"] - ToThread --> Sync[_run_module_agent_sync] - - Sync --> LoadTree{module_tree given?} - LoadTree -->|no| LoadJSON["load module_tree.json from disk"] - LoadTree -->|yes| UseGiven["use in-memory tree (recursion case)"] - LoadJSON --> CheckExisting - UseGiven --> CheckExisting - - CheckExisting{overview.md or
module_name.md exists?} - CheckExisting -->|yes| ReturnTree["return module_tree unchanged"] - CheckExisting -->|no| Gate - - Gate["Compute can_delegate:
is_complex_module AND
start_depth < max_depth AND
num_tokens β‰₯ max_token_per_leaf_module"] - Gate --> PromptChoice{can_delegate?} - PromptChoice -->|yes| SysPrompt["format_system_prompt
(recursive prompt + delegation tool)"] - PromptChoice -->|no| LeafPrompt["format_leaf_system_prompt
(single-file write prompt)"] - - SysPrompt --> BuildDeps - LeafPrompt --> BuildDeps - BuildDeps["Build CodeWikiDeps
(paths, components, depth, config)"] - BuildDeps --> BuildToolkit["CawToolKit(deps, backend=self, allow_subagent=can_delegate)"] - BuildToolkit --> BuildAgent["CawAgent(provider, model, system_prompt,
tools=tool_group, tool_servers=[toolkit])"] - BuildAgent --> Chdir["chdir to run_cwd
(repo_root for claude, working_dir for codex)"] - Chdir --> Complete["agent.completion(user_prompt)"] - Complete --> Restore["restore original cwd"] - Restore --> Save["file_manager.save_json(module_tree, module_tree_path)"] - Save --> Return([return updated module_tree]) -``` - -Key implementation details: - -- **`start_depth` / `module_tree` parameters** exist purely to support recursion: when - `CawToolKit` triggers a sub-module run, it calls `_run_module_agent_sync` directly - (not the async `run_module_agent`), passing the parent's `current_depth` as - `start_depth` and the **in-memory** `module_tree` (not yet flushed to disk) so newly - staged sub-module branches are visible to the child. -- **Delegation gate (`can_delegate`)** mirrors the equivalent gate in - `PydanticAIBackend` (see - [`Backend_LLM_&_Documentation_Services_pydantic_ai_backend`](Backend_LLM_&_Documentation_Services_pydantic_ai_backend.md)): - a module must span multiple files, have enough content - (`num_tokens >= max_token_per_leaf_module`), and remaining recursion budget - (`start_depth < max_depth`) before the recursive system prompt and - `generate_sub_module_documentation` tool are offered. Otherwise the *leaf* system - prompt is used and the toolkit disables `generate_sub_module_documentation`. -- **Working-directory pinning around `agent.completion`** is provider-specific: - - For **Codex**, cwd is pinned to `working_dir` (the docs output dir) because Codex's - native `file_change` tool resolves relative paths against the process cwd. - - For **Claude Code**, cwd is pinned to `self._repo_root` because Claude writes only - through CodeWiki's own `str_replace_editor` (absolute paths via `deps`), but Claude's - `acceptEdits` permission mode (which orgs may force even when - `--dangerously-skip-permissions` is requested) auto-approves reads/edits only *inside* - the working directory β€” so the repo root must be the cwd to keep source reads - in-scope. - - The original cwd is always restored in a `finally` block. This mutation is safe because - `DocumentationGenerator` processes modules **sequentially**, and nested - `_run_module_agent_sync` recursive calls chdir to the same absolute paths. - -### Stopgap patches applied at import time - -Three module-level patches work around gaps/behavioral quirks in the upstream `caw` -library. They are applied once (idempotently, via a module-level "applied" flag) the -first time `codewiki.src.be.caw_backend` is imported: - -```mermaid -flowchart LR - subgraph Patch1["_patch_codex_tool_timeout()"] - A1["Monkeypatches CodexSession._mcp_config_args"] - A2["Injects '-c mcp_servers.NAME.tool_timeout_sec=86400'
per MCP server"] - A1 --> A2 - end - subgraph Patch2["_patch_claude_allowed_tools()"] - B1["Replaces caw.providers.claude_code.subprocess
with _SubprocessProxy"] - B2["Proxy.Popen rewrites cmd via _with_allowed_tools()"] - B3["Appends --allowedTools mcp__server,... when
--mcp-config present and no allow-list set"] - B1 --> B2 --> B3 - end - subgraph Patch3["MCP_TOOL_TIMEOUT / MCP_TIMEOUT env"] - C1["os.environ.setdefault in __init__
(claude_code provider only)"] - end -``` - -| Patch | Problem it solves | Scope | -|---|---|---| -| `_patch_codex_tool_timeout` | Upstream `CodexSession` emits no per-server `tool_timeout_sec`, so Codex cancels MCP tool calls during long sub-module recursion. | Applied globally once; monkeypatches `CodexSession._mcp_config_args`. | -| `_patch_claude_allowed_tools` | Custom MCP-server tools aren't auto-approved under `acceptEdits`, and orgs can disable `bypassPermissions`; without an explicit `--allowedTools mcp__` flag the agent's tool calls are silently denied and docs come out empty. | Wraps `subprocess.Popen` calls made *inside* `caw.providers.claude_code` only β€” process-wide `subprocess` is untouched. | -| `MCP_TOOL_TIMEOUT` / `MCP_TIMEOUT` env defaults | Prevents claude-code CLI from cancelling long sub-module recursion. | Set via `os.environ.setdefault` in `CawBackend.__init__`, only for the `claude_code` provider; a user-supplied override always wins. | - -All three are defensive stopgaps documented in code comments as candidates for removal -once the corresponding capability lands upstream in `caw`. - ---- - -## `CawToolKit` - -`CawToolKit` is a `caw.ToolKit` subclass (`server_name="codewiki_tools"`) instantiated -fresh **per agent session** (once per top-level module, and again for every recursively -delegated sub-module). It is registered with the `CawAgent` via `tool_servers=[toolkit]`, -exposing three `@tool`-decorated methods over MCP to the underlying Claude Code / Codex -CLI. - -### Tools exposed - -```mermaid -classDiagram - class CawToolKit { - +read_code_components(component_ids: list[str]) str - +str_replace_editor(working_dir, command, path, file_text, view_range, old_str, new_str, insert_line) str - +generate_sub_module_documentation(sub_module_specs, ctx) str - } - note for CawToolKit "MCP tool server (caw.ToolKit)\nregistered per-agent-session" -``` - -1. **`read_code_components(component_ids)`** β€” looks up each `"path::name"` id in - `deps.components` (populated once for the whole run by - [`DependencyGraphBuilder`](Dependency_Analyzer_Core.md)) and returns concatenated - source code, or a "not found" marker per missing id. - -2. **`str_replace_editor(working_dir, command, path, ...)`** β€” thin MCP wrapper delegating - to the shared `EditTool` implementation from - [`Backend_Agent_Tools`](Backend_Agent_Tools.md), ensuring byte-for-byte identical - editing/view/undo semantics as the pydantic-ai backend. Adds: - - **Working-dir enum enforcement** (`"repo"` / `"docs"`) done manually at call time - rather than via `Literal` types, because `from __future__ import annotations` turns - `Literal` into unresolved forward refs that FastMCP's schema builder can't rebuild. - - **`view`-only restriction on `working_dir="repo"`** β€” the agent may inspect source - but never mutate it. - - **Absolute-path rejection** and **`..`-escape containment check** (`Path.resolve()` + - `relative_to`) so a malicious/careless agent path can never write outside - `absolute_docs_path` / `absolute_repo_path`. - - **JSON-string coercion** (`_coerce_json_arg`) for `view_range` / `insert_line`, since - some MCP/CLI bridges serialize list/int arguments as JSON strings. - - **Post-write Mermaid validation** β€” after any non-`view` command on a `.md` path, it - calls `validate_mermaid_diagrams` (shared with the pydantic-ai backend via - `codewiki.src.be.utils`) and appends the validation report to the tool result. - -3. **`generate_sub_module_documentation(sub_module_specs, ctx)`** β€” the recursion trigger. - Rejected outright (returns a corrective error string, no exception) if - `self._allow_subagent` is `False` (i.e., the module was deemed a leaf by - `CawBackend`'s delegation gate). Otherwise: - - Runs `_run_sub_modules` in a worker thread via `asyncio.to_thread` so the MCP - server's event loop isn't blocked while children complete. - - Concurrently runs a `_heartbeat` task that emits MCP progress notifications every - 10 seconds so the calling CLI doesn't treat the long tool call as stalled/cancelled. - -### Sub-module recursion flow (`_run_sub_modules`) - -```mermaid -sequenceDiagram - participant Agent as caw.Agent (parent module) - participant CTK as CawToolKit - participant NM as normalize_sub_module_specs - participant Tree as module_tree (in-memory) - participant CB as CawBackend._run_module_agent_sync - participant Disk as docs dir (*.md) - - Agent->>CTK: generate_sub_module_documentation(sub_module_specs) - CTK->>NM: normalize_sub_module_specs(specs, parent_name, module_tree, docs_path) - NM-->>CTK: name_map (requested β†’ final, collision-safe) - CTK->>Tree: insert {final_name: {components, children: {}}} under current path - loop for each (sub_name, core_ids) in final_specs - CTK->>CTK: deps.current_module_name = sub_name
deps.path_to_current_module.append(sub_name)
deps.current_depth += 1 - CTK->>CB: _run_module_agent_sync(sub_name, components, core_ids,
module_path, working_dir, start_depth, module_tree) - CB-->>Disk: writes sub_name.md via str_replace_editor - CB-->>CTK: returns (possibly further-extended) module_tree - CTK->>CTK: pop path segment, current_depth -= 1 - end - CTK->>Disk: check existence of each final_name.md - CTK-->>Agent: report "Saved documentations: ... MISSING: ..." (if any) -``` - -Notable behaviors: - -- **Name collision resolution** happens *before* any tree mutation, via - `normalize_sub_module_specs` (shared utility, also used by the pydantic-ai backend's - equivalent tool) β€” because docs are saved into one **flat** directory, a sub-module name - that collides with an existing tree entry or an on-disk `.md` stem is automatically - renamed (typically prefixed with the parent module name). -- **Direct sync recursion** β€” `_run_sub_modules` calls - `self._backend._run_module_agent_sync(...)` directly rather than going through the async - `run_module_agent` wrapper, since it is already executing inside a worker thread spawned - by the parent tool call; this avoids double-wrapping in `asyncio.to_thread`. -- **Depth bookkeeping** β€” `deps.current_depth` is incremented/decremented around each - child call and passed as that child's `start_depth`, so `CawBackend`'s - `can_delegate` gate correctly enforces `max_depth` across the whole recursive tree, not - just per-session. -- **Failure visibility** β€” the final report distinguishes files that exist on disk after - generation (`saved`) from those that don't (`missing`), and logs a warning for the - latter. This directly feeds `DocumentationGenerator.validate_generated_docs`, which - raises `IncompleteDocumentationError` if any expected `.md` file never landed (see - [`Backend_LLM_&_Documentation_Services_documentation_generator`](Backend_LLM_&_Documentation_Services_documentation_generator.md)). - ---- - -## Relationship to the pydantic-ai backend - -Both backends satisfy identical goals and the same abstract `LLMBackend` contract but -differ in execution substrate: - -| Aspect | `CawBackend` (this module) | [`PydanticAIBackend`](Backend_LLM_&_Documentation_Services_pydantic_ai_backend.md) | -|---|---|---| -| Auth | Existing `claude` / `codex` CLI OAuth subscription | API key via `llm_base_url` / `llm_api_key` | -| Execution engine | Official Claude Code / Codex CLI processes (subprocess) | In-process `pydantic-ai` `Agent` over an OpenAI-compatible HTTP model | -| Tool exposure | MCP `ToolKit` (`CawToolKit`) registered as `tool_servers` | Native pydantic-ai tool functions | -| File editing | Shared `EditTool` (via `str_replace_editor` MCP tool) | Shared `EditTool` (via native tool) | -| Delegation gate | `is_complex_module` + token/depth thresholds (identical heuristic) | Same heuristic, implemented in `generate_sub_module_documentation_tool` | -| Fallback model | Ignored (`config.fallback_model` unused β€” caw has no fallback chain) | Honored via `CompatibleOpenAIModel`/fallback logic | -| Blocking behavior | `complete()`/`agent.completion()` block the calling thread (offloaded via `asyncio.to_thread` for module agents) | Fully async throughout | - -Because both share `CodeWikiDeps`, `EditTool`, `normalize_sub_module_specs`, and the -module-complexity heuristics, module authors extending CodeWiki's agent tools generally -only need to touch [`Backend_Agent_Tools`](Backend_Agent_Tools.md) once for both backends -to pick up the change. - ---- - -## Where this module is invoked from - -```mermaid -sequenceDiagram - participant CLI as CLI_Documentation_Generation - participant Cfg as Core_Config_&_Utils (Config) - participant DG as DocumentationGenerator - participant CB as CawBackend - - CLI->>Cfg: Config.from_cli(..., provider="claude-code"|"codex") - CLI->>DG: DocumentationGenerator(config) - DG->>DG: backend = get_backend(config) - DG->>CB: CawBackend(config) (construction: validates CLI on PATH, applies patches) - DG->>CB: complete(prompt, model=cluster_model) [clustering] - loop per module (leaf-first, then parents) - DG->>CB: run_module_agent(module_name, components, core_ids, module_path, working_dir) - CB-->>DG: updated module_tree - end - DG->>CB: complete(prompt) [parent / repo overview] -``` - -See [`Backend_LLM_&_Documentation_Services_documentation_generator`](Backend_LLM_&_Documentation_Services_documentation_generator.md) -for the full orchestration pipeline (dependency graph construction, module clustering, -topological processing order, metadata and validation), and -[`CLI_Documentation_Generation`](CLI_Documentation_Generation.md) for how `Config` (and -hence `provider`) is populated from CLI arguments / job definitions. diff --git a/docs/Backend_LLM_&_Documentation_Services_documentation_generator.md b/docs/Backend_LLM_&_Documentation_Services_documentation_generator.md deleted file mode 100644 index c3e70384..00000000 --- a/docs/Backend_LLM_&_Documentation_Services_documentation_generator.md +++ /dev/null @@ -1,286 +0,0 @@ -# Documentation Generator (`Backend_LLM_&_Documentation_Services_documentation_generator`) - -## Introduction - -The **Documentation Generator** module is the top-level orchestrator of CodeWiki's documentation pipeline. It is the single entry point (`DocumentationGenerator.run()`) that turns a parsed source repository into a complete, hierarchical set of Markdown documentation files. It coordinates dependency analysis, module clustering, bottom-up per-module documentation generation via LLM agents, and top-down overview synthesis β€” while ensuring the whole process is resumable, idempotent, and validated for completeness before it reports success. - -This module sits at the center of the `Backend_LLM_&_Documentation_Services` parent module and delegates the actual "thinking" work to two sibling modules: - -- [Backend_LLM_&_Documentation_Services_pydantic_ai_backend.md](Backend_LLM_&_Documentation_Services_pydantic_ai_backend.md) β€” API-key based LLM backend (`PydanticAIBackend`) built on `pydantic-ai` agents. -- [Backend_LLM_&_Documentation_Services_caw_backend.md](Backend_LLM_&_Documentation_Services_caw_backend.md) β€” subscription-CLI backend (`CawBackend`) that drives Claude Code / Codex CLIs. - -Both backends implement the same `LLMBackend` abstract interface, which is the seam this module programs against β€” it never needs to know which concrete backend is in use. - -## Responsibilities - -`DocumentationGenerator` (in `codewiki/src/be/documentation_generator.py`) is responsible for: - -1. **Kicking off dependency analysis** via [Dependency_Analysis_Service.md](Dependency_Analysis_Service.md) / [Dependency_Analyzer_Core.md](Dependency_Analyzer_Core.md) (`DependencyGraphBuilder`) to obtain the full component graph and its leaf nodes (documentable code units). -2. **Clustering leaf components into a module tree** (via `cluster_modules`), either through an LLM call or by staying flat when the repo is small enough to fit in one context window. -3. **Computing a bottom-up processing order** (leaf modules β†’ parent modules β†’ repository overview) using a dynamic-programming / topological-sort style traversal so that parent overviews are always written *after* all their children's docs exist. -4. **Delegating actual content generation** to an `LLMBackend` implementation: - - Leaf/complex modules β†’ `backend.run_module_agent(...)` (agentic, tool-using loop). - - Parent modules & the repo overview β†’ `backend.complete(prompt)` (single-shot completion over already-generated children docs). -5. **Persisting and reloading state** (`module_tree.json`, `first_module_tree.json`) so that generation can be resumed after partial failures without re-clustering or re-processing already-completed modules. -6. **Validating completeness** at the end of the run β€” every module in the final tree must have a corresponding `.md` file on disk (falling back to sanitized filename variants), otherwise an `IncompleteDocumentationError` is raised. -7. **Writing a metadata.json** file describing the generation run (model used, commit id, statistics, list of generated files). - -## Architecture - -```mermaid -graph TB - subgraph "Backend_LLM_&_Documentation_Services_documentation_generator" - DG[DocumentationGenerator] - IDE[IncompleteDocumentationError] - end - - subgraph "Dependency_Analysis_Service / Dependency_Analyzer_Core" - DGB[DependencyGraphBuilder] - end - - subgraph "Backend_LLM_&_Documentation_Services (siblings)" - BE[LLMBackend get_backend] - PAB[PydanticAIBackend] - CAW[CawBackend] - CM[cluster_modules / get_clustering_input_token_count] - end - - subgraph "Core_Config_&_Utils" - CFG[Config] - FM[file_manager / FileManager] - end - - subgraph "prompt_template & module_naming (internal helpers)" - PT[REPO_OVERVIEW_PROMPT / MODULE_OVERVIEW_PROMPT] - MN[dedupe_module_tree_names / find_missing_module_docs / resolve_module_doc_path] - end - - DG -->|build_dependency_graph| DGB - DG -->|cluster leaf nodes| CM - DG -->|get_backend config| BE - BE --> PAB - BE --> CAW - DG -->|run_module_agent / complete| PAB - DG -->|run_module_agent / complete| CAW - DG --> CFG - DG --> FM - DG --> PT - DG --> MN - DG -.raises.-> IDE -``` - -## Dependency Overview - -```mermaid -flowchart LR - DocGen[DocumentationGenerator] --> DGBuilder[DependencyGraphBuilder\nDependency_Analyzer_Core] - DocGen --> Backend[LLMBackend\nget_backend] - Backend --> PydanticAI[PydanticAIBackend] - Backend --> Caw[CawBackend] - DocGen --> ClusterModules[cluster_modules] - DocGen --> Config[Config\nCore_Config_&_Utils] - DocGen --> FileManager[file_manager\nCore_Config_&_Utils] - DocGen --> ModuleNaming[module_naming helpers] - DocGen --> PromptTemplate[prompt_template constants] - - CLI[CLIDocumentationGenerator\nCLI_Documentation_Generation] --> DocGen -``` - -The `DocumentationGenerator` is instantiated and driven by the CLI layer (`CLIDocumentationGenerator`, see [CLI_Documentation_Generation.md](CLI_Documentation_Generation.md)), which supplies a `Config` object (see [Core_Config_&_Utils.md](Core_Config_&_Utils.md)) and optionally a pre-built `LLMBackend`. - -## Core Data Structures - -| File | Purpose | -|---|---| -| `first_module_tree.json` | The module tree exactly as produced by clustering (`cluster_modules`), before any sub-agent hierarchical modifications. Used to compute the leaf-first processing order so it's stable across resumed runs. | -| `module_tree.json` | The live, evolving module tree. Sub-agents can add nested sub-modules (`generate_sub_module_documentation_tool`) while processing a module, so this file is reloaded from disk before every module is processed. | -| `.md` | Generated documentation for a single module (leaf or parent). Its existence is treated as a completion marker β€” if present, that module is skipped entirely on rerun. | -| `overview.md` | The top-level, whole-repository documentation, generated last. | -| `metadata.json` | Run metadata: timestamp, model, commit id, statistics, list of generated markdown files. | - -Module tree entries follow this shape (see `AnalysisResult` / `NodeSelection` in [Dependency_Analyzer_Core.md](Dependency_Analyzer_Core.md) for the underlying component model): - -```json -{ - "ModuleName": { - "components": ["path/to/file.py::ClassName", "..."], - "children": { - "SubModuleName": { "components": [], "children": {} } - } - } -} -``` - -## Process Flow: `run()` - -```mermaid -sequenceDiagram - participant Caller as CLIDocumentationGenerator - participant DG as DocumentationGenerator - participant DGB as DependencyGraphBuilder - participant CM as cluster_modules - participant Backend as LLMBackend - participant FM as file_manager - - Caller->>DG: run() - DG->>DGB: build_dependency_graph() - DGB-->>DG: components, leaf_nodes - - alt first_module_tree.json exists - DG->>FM: load_json(first_module_tree.json) - else - DG->>CM: cluster_modules(leaf_nodes, components, config, completer=backend.complete) - CM-->>DG: module_tree (possibly empty if repo fits in one context window) - DG->>DG: dedupe_module_tree_names(module_tree) - DG->>FM: save_json(first_module_tree.json) - end - DG->>FM: save_json(module_tree.json) - - DG->>DG: generate_module_documentation(components, leaf_nodes) - Note over DG: see detailed flow below - - DG->>DG: create_documentation_metadata() - DG->>DG: validate_generated_docs() - alt any docs missing - DG-->>Caller: raise IncompleteDocumentationError - else - DG-->>Caller: success - end -``` - -### `generate_module_documentation` β€” the dynamic-programming core - -```mermaid -flowchart TD - Start([generate_module_documentation]) --> LoadTrees[Load module_tree.json and first_module_tree.json] - LoadTrees --> Order[get_processing_order over first_module_tree] - Order --> HasModules{module_tree non-empty?} - - HasModules -- No --> WholeRepo[run_module_agent on entire repo as one leaf; rename repo_name.md to overview.md] - WholeRepo --> Done([return working_dir]) - - HasModules -- Yes --> Loop{for each module_path, module_name in processing order} - Loop --> Reload[Reload module_tree.json - sub-agents may have mutated it] - Reload --> Lookup[Navigate to module_info via module_path] - Lookup --> Skip{already processed?} - Skip -- Yes --> Loop - Skip -- No --> IsLeaf{is_leaf_module?} - - IsLeaf -- Yes --> RunAgent[backend.run_module_agent: module_name, core_component_ids, module_path, working_dir] - IsLeaf -- No --> RunParent[generate_parent_module_docs: module_path, working_dir] - - RunAgent --> MarkDone[mark module_key processed] - RunParent --> MarkDone - MarkDone --> Loop - - Loop -- exhausted --> Overview[generate_parent_module_docs with module_path=empty -> overview.md] - Overview --> Done -``` - -Key points: - -- **Processing order** (`get_processing_order`) is a depth-first, post-order traversal: children are appended to the order list before their parent, so leaf modules are always generated first β€” a form of bottom-up dynamic programming where each parent's generation reuses ("memoizes") its children's already-written docs. -- **Leaf modules** (`is_leaf_module` β€” no children, or empty children dict) are handed to `backend.run_module_agent`, which runs a tool-using agent loop (`read_code_components`, `str_replace_editor`, and possibly `generate_sub_module_documentation_tool` for complex modules) against the concrete source code. See [Backend_Agent_Tools.md](Backend_Agent_Tools.md) for the tool implementations and [Backend_LLM_&_Documentation_Services_pydantic_ai_backend.md](Backend_LLM_&_Documentation_Services_pydantic_ai_backend.md) / [Backend_LLM_&_Documentation_Services_caw_backend.md](Backend_LLM_&_Documentation_Services_caw_backend.md) for how each backend implements this. -- **Parent modules** never touch source code directly β€” they synthesize an overview purely from their direct children's already-generated Markdown (`build_overview_structure`), via a single `backend.complete(prompt)` call. -- Both leaf and parent processing **short-circuit if the target `.md` already exists** (checked inside `run_module_agent` implementations and in `generate_parent_module_docs`), making the whole pipeline safely resumable after crashes, rate limits, or manual interruption. -- **Whole-repo mode**: if `cluster_modules` returns an empty tree (the entire component set fits under `max_token_per_module`), the generator skips clustering/hierarchy entirely and calls `run_module_agent` once for the whole repository, then renames the resulting `.md` to `overview.md`. - -### `generate_parent_module_docs` β€” overview synthesis - -```mermaid -flowchart TD - A([generate_parent_module_docs]) --> B{overview.md exists?} - B -- Yes --> Z[return module_tree unchanged] - B -- No --> C{module_name.md exists? overview.md for root} - C -- Yes --> Z - C -- No --> D[build_overview_structure: deepcopy tree, mark target, attach children's md content] - D --> E{module_path empty?} - E -- Yes --> F[REPO_OVERVIEW_PROMPT] - E -- No --> G[MODULE_OVERVIEW_PROMPT] - F --> H[backend.complete prompt] - G --> H - H --> I{OVERVIEW tags present?} - I -- Yes --> J[extract content between tags] - I -- No --> K[use raw response - subscription-CLI backends may omit wrapper] - J --> L[save_text to module_name.md] - K --> L - L --> Z -``` - -`build_overview_structure` is the key data-shaping step: it deep-copies the module tree, walks down to the target module (marking it with `is_target_for_overview_generation: true`), then attaches each direct child's rendered Markdown under `child_info["docs"]` β€” resolved via `resolve_module_doc_path` (from `module_naming`, alongside `find_missing_module_docs`) to tolerate filename sanitization drift between the tree's module names and what sub-agents actually wrote to disk. This assembled JSON structure is embedded directly into the overview/repo prompt so the LLM only ever sees prose, not raw source. - -## Validation & Error Handling - -```mermaid -flowchart LR - A[run completes module generation] --> B[validate_generated_docs] - B --> C[load module_tree.json] - C --> D[find_missing_module_docs] - D --> E{missing list empty?} - E -- Yes --> F[log success] - E -- No --> G[log each missing module] - G --> H[raise IncompleteDocumentationError with missing_modules] -``` - -- `IncompleteDocumentationError` is a custom exception carrying the list of module names whose `.md` file could not be found (including `"overview"` if `overview.md` is missing). This closes a gap where a sub-agent silently failing (e.g., name-collision overwrite, tool error swallowed inside the agent loop) would otherwise go unnoticed and be reported as a successful run. -- Every per-module exception inside the main loop is logged (with traceback) and the loop `continue`s to the next module rather than aborting the whole run β€” partial failures are surfaced later via `validate_generated_docs`, not by crashing mid-loop. -- Failures in `generate_parent_module_docs` (LLM call itself) are re-raised, since a missing overview always indicates a hard failure worth stopping for at that point in the call stack (though `run()` still funnels everything through the top-level `try/except` for logging). - -## Integration with `LLMBackend` - -`DocumentationGenerator` depends only on the `LLMBackend` abstract interface (`codewiki/src/be/backend.py`), obtained via `get_backend(config)` unless a backend instance is injected directly (used by the CLI/tests): - -```python -class LLMBackend(abc.ABC): - def complete(self, prompt: str, *, model: str | None = None) -> str: ... - async def run_module_agent(self, module_name, components, core_component_ids, - module_path, working_dir) -> Dict[str, Any]: ... -``` - -- `complete()` is used for clustering (via `cluster_modules(..., completer=backend.complete)`) and for parent/repo overview synthesis. -- `run_module_agent()` is used for leaf/complex module generation β€” it runs an agentic loop with tools and returns the (possibly-mutated) module tree, since sub-agents can add newly-discovered sub-modules to it. - -Concrete backend selection (`get_backend`) branches on `config.provider`: - -| Provider | Backend | Documentation | -|---|---|---| -| `openai-compatible`, `atlas-cloud`, `anthropic`, `bedrock`, `azure-openai` (API key based) | `PydanticAIBackend` | [Backend_LLM_&_Documentation_Services_pydantic_ai_backend.md](Backend_LLM_&_Documentation_Services_pydantic_ai_backend.md) | -| `claude_code`, `codex` (subscription CLI) | `CawBackend` | [Backend_LLM_&_Documentation_Services_caw_backend.md](Backend_LLM_&_Documentation_Services_caw_backend.md) | - -This module never needs backend-specific branches itself β€” the abstract interface fully isolates it from prompt formatting, tool wiring, or subprocess management differences between the two implementations. - -## Module Clustering - -Before per-module generation begins, `run()` calls `cluster_modules` (from `codewiki/src/be/cluster_modules.py`) to group the flat set of leaf components discovered by dependency analysis into a hierarchical module tree: - -- If the total token count of all leaf components is within `config.max_token_per_module`, clustering is **skipped** and an empty tree (`{}`) is used β€” triggering whole-repository documentation mode in `generate_module_documentation`. -- Otherwise, an LLM prompt (`format_cluster_prompt`) is sent through the backend's `complete()` (bound to `config.cluster_model` when set) to propose a grouping, recursively refining each cluster until it fits the token budget. -- The resulting tree is deduplicated (`dedupe_module_tree_names`) to avoid name collisions between sibling/cousin modules that would otherwise overwrite each other's `.md` files β€” this is only done for a freshly clustered tree, never for one reloaded from `first_module_tree.json` (renaming a cached key whose doc already exists on disk would orphan that file). - -Both `first_module_tree.json` (immutable snapshot used for processing order) and `module_tree.json` (live, agent-mutable copy) are persisted immediately so that a rerun after failure/interruption reuses the same clustering result rather than re-invoking the LLM. - -## Metadata Generation - -`create_documentation_metadata` writes a `metadata.json` describing the run: timestamp, `main_model`, generator version, `repo_path`, `commit_id` (passed in at construction time β€” typically supplied by [CLI_Git_Integration.md](CLI_Git_Integration.md)'s `GitManager`), and statistics (`total_components`, `leaf_nodes`, `max_depth`). It also scans `working_dir` for any `.md` files not already listed and appends them to `files_generated`. This file is consumed by the CLI/HTML layers (see [CLI_HTML_Viewer.md](CLI_HTML_Viewer.md)) to display generation provenance. - -## Relationship to the CLI - -```mermaid -graph LR - A[CLI entrypoint] --> B[ConfigManager\nCLI_Configuration] - B --> C[Config] - A --> D[CLIDocumentationGenerator\nCLI_Documentation_Generation] - D --> E[DocumentationGenerator] - E --> F[LLMBackend] - E --> G[working_dir with md files, module_tree.json, metadata.json] - G --> H[HTMLGenerator\nCLI_HTML_Viewer] - A --> I[GitManager\nCLI_Git_Integration - commit_id] - I --> E - A --> J[ProgressTracker / CLILogger\nCLI_Utilities] -``` - -`DocumentationGenerator` is deliberately UI/CLI-agnostic β€” it has no knowledge of progress bars, logging formatting, or job status models (`JobStatus`, `DocumentationJob`, etc., defined in [CLI_Documentation_Generation.md](CLI_Documentation_Generation.md)). Those concerns are layered on top by `CLIDocumentationGenerator`, which wraps `run()` with progress reporting, job lifecycle tracking, and error surfacing suitable for both terminal and web-facing consumers (see [Frontend_Web_App.md](Frontend_Web_App.md) for the web job runner that also drives this class). - -## Summary - -`DocumentationGenerator` is the glue that turns raw dependency-graph output into a navigable, hierarchical documentation tree, using a leaf-first dynamic-programming traversal so that every overview is written strictly after its dependencies. Its design goals β€” idempotent resumability via on-disk completion markers, backend-agnostic LLM delegation through `LLMBackend`, and end-of-run completeness validation β€” make it robust to partial failures, LLM formatting quirks (missing `` tags), and filename drift introduced by sub-agents. diff --git a/docs/Backend_LLM_&_Documentation_Services_pydantic_ai_backend.md b/docs/Backend_LLM_&_Documentation_Services_pydantic_ai_backend.md deleted file mode 100644 index ebff3eec..00000000 --- a/docs/Backend_LLM_&_Documentation_Services_pydantic_ai_backend.md +++ /dev/null @@ -1,435 +0,0 @@ -# Backend LLM & Documentation Services β€” pydantic-ai Backend - -## Purpose - -This sub-module is the **API-key based LLM path** of CodeWiki. It is one of -the two concrete implementations of the `LLMBackend` interface defined in the -parent module (see [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) -for the full picture), and it is the *default* backend β€” used whenever -`config.provider` is anything other than `claude-code` / `codex` (the -subscription-CLI providers handled by -[Backend_LLM_&_Documentation_Services_caw_backend](Backend_LLM_&_Documentation_Services_caw_backend.md)). - -Concretely, this file group provides: - -- **`LLMBackend`** (`backend.py`) β€” the abstract base class both concrete - backends implement, plus `get_backend(config)` / `is_caw_provider(provider)`, - the single seam where provider choice turns into a concrete backend - instance. -- **`PydanticAIBackend`** (`pydantic_ai_backend.py`) β€” the concrete backend - that drives [pydantic-ai](https://ai.pydantic.dev/)'s `Agent` machinery for - the per-module documentation loop, and reuses a simple synchronous - `call_llm` helper for one-shot completions (clustering, parent/repo - overviews). -- **`llm_services.py`** (`CompatibleOpenAIModel`, `CachingOpenAIModel`, model - factories, `call_llm`) β€” the model/client construction layer that adapts - pydantic-ai's `OpenAIChatModel` to CodeWiki's multi-provider needs - (OpenAI-compatible, Anthropic, Bedrock, Azure OpenAI, all routed through - litellm-compatible proxies where needed) and adds resilience features: - non-standard response patching, prompt-cache breakpoint injection with - automatic fallback, and token-parameter auto-detection. - -## Where this sits in the system - -```mermaid -flowchart TD - subgraph Callers - DG["DocumentationGenerator\n(Backend_LLM_&_Documentation_Services_documentation_generator)"] - end - - subgraph ThisModule["Backend_LLM_&_Documentation_Services_pydantic_ai_backend"] - GB["get_backend(config)"] - LB["LLMBackend (ABC)"] - PAB["PydanticAIBackend"] - LS["llm_services.py"] - CALL["call_llm()"] - CFM["create_fallback_models()\ncreate_main_model()\ncreate_fallback_model()"] - COM["CompatibleOpenAIModel"] - CAM["CachingOpenAIModel"] - end - - subgraph Siblings["Sibling backend"] - CAW["CawBackend\n(Backend_LLM_&_Documentation_Services_caw_backend)"] - end - - subgraph External["External / other modules"] - AGT["pydantic_ai.Agent"] - TOOLS["Backend_Agent_Tools\n(CodeWikiDeps, str_replace_editor_tool)"] - CFG["Core_Config_&_Utils\n(Config)"] - NODE["Dependency_Analyzer_Core\n(Node)"] - OPENAI["openai / litellm SDKs"] - end - - DG --> GB - GB -->|provider in CAW_PROVIDERS| CAW - GB -->|otherwise| PAB - PAB -.implements.-> LB - CAW -.implements.-> LB - PAB --> CALL - PAB --> CFM - PAB --> AGT - PAB --> TOOLS - CFM --> CAM - CAM --|inherits|--> COM - CALL --> OPENAI - PAB --> CFG - TOOLS --> NODE -``` - -* [Backend_LLM_&_Documentation_Services_documentation_generator](Backend_LLM_&_Documentation_Services_documentation_generator.md) - is the sole caller of `get_backend`/`LLMBackend` in normal operation β€” - `DocumentationGenerator.__init__` calls `get_backend(config)` unless a - backend instance is injected explicitly (used in tests). -- [Backend_LLM_&_Documentation_Services_caw_backend](Backend_LLM_&_Documentation_Services_caw_backend.md) - is the sibling implementation selected when `config.provider` is a caw - provider; both share the exact same `LLMBackend` contract so the - orchestrator never needs to branch on backend type. -- [Backend_Agent_Tools](Backend_Agent_Tools.md) supplies `CodeWikiDeps` (the - per-run context object) and `str_replace_editor_tool` / - `read_code_components_tool`, which `PydanticAIBackend.run_module_agent` - registers as pydantic-ai `Tool`s. -- [Core_Config_&_Utils](Core_Config_&_Utils.md) supplies `Config`, from which - provider, model names, token limits, and prompt-caching flags are read. -- [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) supplies the `Node` - model that makes up `components: Dict[str, Node]`. - -## Component reference - -### `backend.py` β€” the `LLMBackend` contract - -```mermaid -classDiagram - class LLMBackend { - <> - +complete(prompt, model=None)* str - +run_module_agent(module_name, components, core_component_ids, module_path, working_dir)* dict - } - class is_caw_provider { - <> - provider: str - } - class get_backend { - <> - config - } - get_backend ..> is_caw_provider : uses - get_backend --> LLMBackend : returns instance -``` - -- **`CAW_PROVIDERS = {"claude-code", "codex"}`** β€” the module-level constant - that defines which `config.provider` values route to the subscription CLI - path instead of the API-key path. -- **`is_caw_provider(provider)`** β€” trivial membership check against - `CAW_PROVIDERS`. -- **`LLMBackend`** β€” an `abc.ABC` with two abstract methods: - - `complete(prompt, *, model=None) -> str` β€” synchronous single-shot - completion, used for module clustering and parent/repo overview - generation (no tools, no multi-turn state). - - `async run_module_agent(module_name, components, core_component_ids, - module_path, working_dir) -> Dict[str, Any]` β€” the full per-module - agentic documentation loop; returns the (possibly mutated) module tree - dict so the caller can persist/inspect new sub-module branches added - during the run. -- **`get_backend(config)`** β€” reads `config.provider` (default - `"openai-compatible"`), does a **local import** of either `CawBackend` or - `PydanticAIBackend` (avoiding a hard dependency / import cycle between the - two backend modules), and returns the constructed instance. - -### `pydantic_ai_backend.py` β€” `PydanticAIBackend` - -`PydanticAIBackend` is a thin adapter: `complete()` simply forwards to -`llm_services.call_llm`, while `run_module_agent()` builds and runs a -`pydantic_ai.Agent` configured with CodeWiki's own tool functions. - -```mermaid -classDiagram - class PydanticAIBackend { - -_config: Config - -_fallback_models: FallbackModel - -_custom_instructions: str - +__init__(config) - +complete(prompt, model=None) str - +run_module_agent(module_name, components, core_component_ids, module_path, working_dir) dict - } - LLMBackend <|-- PydanticAIBackend - PydanticAIBackend --> "1" FallbackModel : _fallback_models - PydanticAIBackend ..> call_llm : complete() delegates - PydanticAIBackend ..> Agent : constructs per run_module_agent call -``` - -**Construction (`__init__`)** - -- Stores `config`. -- Eagerly builds `self._fallback_models = create_fallback_models(config)` β€” a - `pydantic_ai.models.fallback.FallbackModel` chaining `config.main_model` - then `config.fallback_model`, so a single model outage mid-run degrades - gracefully instead of failing the whole module. -- Precomputes `self._custom_instructions = config.get_prompt_addition()` once - (derived from `config.agent_instructions` β€” doc type, focus modules, free - text β€” see [Core_Config_&_Utils](Core_Config_&_Utils.md)), reused for every - agent run this backend instance performs. - -**`complete(prompt, *, model=None)`** - -Pure delegation: `return call_llm(prompt, self._config, model=model)`. No -agent, no tools β€” used by the orchestrator for clustering and -parent/repo-overview prompts where a single completion suffices. - -**`run_module_agent(...)`** β€” the per-module agent loop: - -```mermaid -sequenceDiagram - participant Orchestrator as DocumentationGenerator - participant Backend as PydanticAIBackend - participant Agent as pydantic_ai.Agent - participant Tools as read_code_components_tool /\nstr_replace_editor_tool /\ngenerate_sub_module_documentation_tool - participant FS as file_manager - - Orchestrator->>Backend: run_module_agent(module_name, components, core_component_ids, module_path, working_dir) - Backend->>FS: load module_tree.json - alt overview.md or {module_name}.md already exists - Backend-->>Orchestrator: return module_tree unchanged (idempotent skip) - else needs generation - Backend->>Backend: is_complex_module(components, core_component_ids)? - alt complex (spans >1 file) - Backend->>Agent: new Agent(tools=[read_code_components_tool,\nstr_replace_editor_tool,\ngenerate_sub_module_documentation_tool],\nsystem_prompt=format_system_prompt(...)) - else simple / leaf - Backend->>Agent: new Agent(tools=[read_code_components_tool,\nstr_replace_editor_tool],\nsystem_prompt=format_leaf_system_prompt(...)) - end - Backend->>Backend: build CodeWikiDeps(...) - Backend->>Agent: agent.run(format_user_prompt(...), deps=deps) - Agent->>Tools: (multi-turn tool calls) - Tools-->>Agent: tool results - Agent-->>Backend: run complete - Backend->>FS: save_json(deps.module_tree, module_tree_path) - Backend-->>Orchestrator: return deps.module_tree - end -``` - -Key implementation details: - -1. **Idempotency guards** β€” before doing any work it checks for - `overview.md` (means the whole run is finished) and `{module_name}.md` - (means this specific module was already documented, e.g. by a previous - crashed run being resumed). Both cases return the module tree unchanged - without invoking the LLM. -2. **Complexity-based tool selection** β€” `is_complex_module(components, - core_component_ids)` (from `codewiki/src/be/utils.py`) checks whether the - module's core components span more than one source file. If so, the - agent additionally gets `generate_sub_module_documentation_tool`, - allowing it to recursively delegate parts of a large module to - sub-agents, and is given the recursive `format_system_prompt`. Otherwise - it's treated as a leaf module and given `format_leaf_system_prompt` - (no delegation tool). -3. **`CodeWikiDeps` construction** β€” bundles everything a tool call needs: - absolute repo/docs paths, the full `components` registry, the - `path_to_current_module` breadcrumb, the in-memory `module_tree`, - `max_depth`/`current_depth` recursion guards, `config`, and the - precomputed `custom_instructions`. See - [Backend_Agent_Tools](Backend_Agent_Tools.md) for the full field - reference β€” this is the exact same dataclass shared with the caw backend. -4. **Agent execution** β€” `agent.run(user_prompt, deps=deps)` drives the - multi-turn tool-calling loop (pydantic-ai internals: message history, - tool dispatch, model fallback via `FallbackModel`). On success, the - (potentially agent-mutated, e.g. via sub-module delegation) - `deps.module_tree` is persisted back to `module_tree.json` and returned. -5. **Error handling** β€” any exception during `agent.run` is logged with - full traceback and re-raised, letting the orchestrator's own - try/except (in `generate_module_documentation`) decide whether to skip - the module and continue with the rest of the tree. - -### `llm_services.py` β€” model & client layer - -This file is the lowest layer: it knows nothing about agents or tool -calling, only about constructing correctly-configured pydantic-ai `Model` -objects and OpenAI-SDK clients, and about making raw single-shot LLM calls -for every supported provider. - -```mermaid -classDiagram - class OpenAIChatModel { - <> - } - class CompatibleOpenAIModel { - +_validate_completion(response) ChatCompletion - } - class CachingOpenAIModel { - -_prompt_caching_enabled: bool - -_cache_registry_key: tuple - +_prompt_caching_active bool - +_map_messages(messages, ...) list - +_completions_create(messages, stream, ...) response - } - OpenAIChatModel <|-- CompatibleOpenAIModel - CompatibleOpenAIModel <|-- CachingOpenAIModel - - class FallbackModel { - <> - } - CachingOpenAIModel --> FallbackModel : combined by create_fallback_models() -``` - -#### `CompatibleOpenAIModel` - -A minimal subclass of pydantic-ai's `OpenAIChatModel` that patches a single -known incompatibility: some OpenAI-compatible proxies return -`choices[].index = None` instead of a sequential integer, which fails -pydantic validation. `_validate_completion` back-fills the index -(`0, 1, 2, ...`) before delegating to the parent implementation. - -#### `CachingOpenAIModel` - -Extends `CompatibleOpenAIModel` to inject **Anthropic-style prompt-cache -breakpoints** into outgoing requests β€” important for the multi-turn agent -loop in `run_module_agent`, where the system prompt + tool definitions + -conversation prefix are repeated on every turn and caching meaningfully cuts -cost/latency on Anthropic-backed proxies (e.g. via LiteLLM). - -```mermaid -flowchart TD - A["_map_messages()"] --> B{prompt_caching_active?} - B -- no --> C[return messages unchanged] - B -- yes --> D["breakpoint 1:\nlast system/developer message\n(covers tools + system prompt)"] - D --> E["breakpoint 2:\nfinal message\n(covers whole conversation prefix,\nincremental across turns)"] - E --> F[return annotated messages] - - G["_completions_create()"] --> H{prompt_caching_active?} - H -- no --> I[call underlying API normally] - H -- yes --> J[call underlying API with cache markers] - J --> K{ModelHTTPError\nstatus 400/422?} - K -- no error --> L[return response] - K -- yes --> M["add (base_url, model) to\n_CACHE_UNSUPPORTED\nretry once WITHOUT markers"] - M --> N{retry also errors?} - N -- yes --> O["discard from _CACHE_UNSUPPORTED\n(failure wasn't about caching)\nre-raise"] - N -- no --> P["return retry response\n(caching now disabled for this\nprovider/model going forward)"] -``` - -Design notes: - -- **Two cache breakpoints** β€” the last system/developer message (caches - the system prompt + tool schema, which never changes within a module run) - and the final message (extends the cached prefix incrementally each - turn). Tool-role messages get the marker at message level (not nested in - a content part) because OpenAI-compatible proxies map that onto - Anthropic's `tool_result` block shape; other roles get it on the last - content part. -- **Module-level `_CACHE_UNSUPPORTED` set** β€” keyed by `(base_url, - model_name)`, shared across all `CachingOpenAIModel` instances process-wide. - This matters because sub-agent delegation (`generate_sub_module_documentation`) - recreates model instances per tool call; the "does this provider reject - cache_control?" probe should happen once per provider/model, not once per - sub-module invocation. -- **Graceful degradation** β€” a `ModelHTTPError` with status 400/422 is - interpreted as "provider rejects cache markers" (not a hard failure): the - pair is remembered, the request retried once without markers, and future - calls to the same provider/model skip cache-marker injection entirely. If - the retry *also* fails, the pair is un-remembered (the failure wasn't - about caching) and the original error propagates. - -#### Model & client factories - -| Function | Returns | Purpose | -|---|---|---| -| `create_main_model(config)` | `CachingOpenAIModel` | Wraps `config.main_model` with an `OpenAIProvider` pointed at `config.llm_base_url`/`llm_api_key`, prompt caching per `config.prompt_caching`. | -| `create_fallback_model(config)` | `CachingOpenAIModel` | Same, for `config.fallback_model`. | -| `create_fallback_models(config)` | `FallbackModel` | `FallbackModel(main, fallback)` β€” the object `PydanticAIBackend` passes to `Agent(...)`, so a failure on the main model automatically retries on the fallback. | -| `create_openai_client(config)` | `openai.OpenAI` | Plain OpenAI SDK client for `call_llm`'s default (openai-compatible) path. | -| `_create_litellm_openai_client(config)` | `openai.OpenAI` | An OpenAI-compatible client pointed at a litellm proxy; sets AWS env defaults for Bedrock. (Currently unused by `call_llm`'s litellm path, which calls `litellm.completion` directly β€” kept for completeness/future use.) | - -#### Token-parameter and settings helpers - -- **`_should_use_max_completion_tokens(model_name, base_url)`** β€” returns - `True` for model families that require OpenAI's newer - `max_completion_tokens` parameter instead of `max_tokens` (`o1`, `o3`, - `o4`, `gpt-4o`, `gpt-4-turbo`, `gpt-5` patterns, or any model called - directly against `api.openai.com`). -- **`_build_model_settings(config, model_name)`** β€” returns an - `OpenAIChatModelSettings` with whichever token parameter is appropriate, - and **deliberately omits `temperature`** β€” some reasoning models only - accept the default temperature and reject explicit values. -- **`_get_litellm_model_name(model_name, provider)`** β€” prefixes the model - name with `bedrock/` or `anthropic/` as required by litellm's model - naming convention, if not already prefixed. - -#### `call_llm` β€” the synchronous one-shot completion path - -```mermaid -flowchart TD - Start["call_llm(prompt, config, model=None)"] --> P{config.provider} - P -- "bedrock / anthropic" --> LiteLLM["_call_llm_via_litellm()\nlitellm.completion(...)"] - P -- "azure-openai" --> Azure["_call_llm_via_azure()\nAzureOpenAI client"] - P -- "openai-compatible (default)" --> OAI["create_openai_client(config)\nclient.chat.completions.create(...)"] - OAI --> TokenTry{"BadRequestError:\nunsupported_parameter?"} - TokenTry -- yes --> Retry["retry once with the\nOTHER token kwarg\n(max_tokens <-> max_completion_tokens)"] - TokenTry -- no / success --> Result["return response.choices[0].message.content"] - Retry --> Result - LiteLLM --> Result - Azure --> Result -``` - -This is the function `PydanticAIBackend.complete()` delegates to, and it is -also called directly by the module-clustering step and by -`DocumentationGenerator.generate_parent_module_docs` (via -`backend.complete`) for parent/repo overview prompts β€” see -[Backend_LLM_&_Documentation_Services_documentation_generator](Backend_LLM_&_Documentation_Services_documentation_generator.md). - -- **`openai-compatible` (default)** β€” builds a request with either - `max_tokens` or `max_completion_tokens` based on - `_should_use_max_completion_tokens`; if the server rejects that parameter - with an `unsupported_parameter` `BadRequestError` - (`_is_unsupported_token_param_error` inspects the structured error body, - falling back to a message-string sniff for proxies that don't preserve - structure), it retries once with the other parameter name. -- **`bedrock` / `anthropic`** β€” delegates to `_call_llm_via_litellm`, which - prefixes the model name appropriately, sets AWS region env vars for - Bedrock, and calls `litellm.completion(...)` directly (bypassing the - OpenAI SDK entirely for this path). -- **`azure-openai`** β€” delegates to `_call_llm_via_azure`, which builds an - `openai.AzureOpenAI` client from `config.llm_api_key`, - `config.api_version`, and `config.llm_base_url`, using - `config.azure_deployment` (falling back to `model`) as the deployment - name. -- No `temperature` is ever sent, matching the reasoning-model constraint - noted above. - -## How the pieces cooperate at runtime - -```mermaid -sequenceDiagram - participant Cfg as Config - participant GB as get_backend() - participant PAB as PydanticAIBackend - participant LS as llm_services - participant Agent as pydantic_ai.Agent - - Cfg->>GB: get_backend(config) - GB->>GB: is_caw_provider(config.provider)? - GB->>PAB: PydanticAIBackend(config) (not a caw provider) - PAB->>LS: create_fallback_models(config) - LS->>LS: create_main_model() + create_fallback_model() - LS-->>PAB: FallbackModel(main, fallback) - Note over PAB: complete() -> LS.call_llm() (sync, no agent) - Note over PAB: run_module_agent() -> builds pydantic_ai.Agent(model=fallback_models, tools=[...]) - PAB->>Agent: agent.run(user_prompt, deps=CodeWikiDeps(...)) - Agent-->>PAB: mutated deps.module_tree -``` - -## Cross-cutting notes specific to this sub-module - -- **Provider dispatch lives entirely in `get_backend`/`is_caw_provider`** β€” - no other code in this sub-module (or the caw sub-module) needs to branch - on provider type again; `PydanticAIBackend` itself is provider-agnostic at - the `Agent`/`run_module_agent` level, with all provider-specific request - shaping isolated inside `llm_services.py`. -- **Two independent "fallback" concepts** β€” don't confuse - `config.fallback_model` (a *different model name* used when the main model - errors, via pydantic-ai's `FallbackModel`) with the *token-parameter retry* - in `call_llm` (same model, different request parameter) or the - *prompt-caching retry* in `CachingOpenAIModel` (same model/request, cache - markers stripped). All three are separate resilience mechanisms operating - at different layers. -- **Shared `CodeWikiDeps` contract** β€” the deps object built in - `run_module_agent` has exactly the same shape as the one built by - `CawBackend._run_module_agent_sync` in the sibling module, which is what - lets [Backend_Agent_Tools](Backend_Agent_Tools.md)'s tool implementations - stay backend-agnostic. diff --git a/docs/C-Family_Tree-sitter_Analyzers.md b/docs/C-Family_Tree-sitter_Analyzers.md deleted file mode 100644 index c882eb38..00000000 --- a/docs/C-Family_Tree-sitter_Analyzers.md +++ /dev/null @@ -1,209 +0,0 @@ -# C-Family Tree-sitter Analyzers - -## Purpose - -This module provides the **static-analysis front end** for the C-family of -programming languages β€” **C, C++, C#, Java, and Kotlin** β€” inside CodeWiki's -[Dependency Analysis Service](Dependency_Analysis_Service.md). Each analyzer -parses a single source file with a [tree-sitter](https://tree-sitter.github.io/) -grammar and produces two things that the rest of the pipeline consumes: - -1. **`Node` records** β€” one per top-level declaration (class, struct, - interface, function, method, global variable, type alias, …) representing - a documentable "component". -2. **`CallRelationship` records** β€” directed edges describing how those - components reference each other (calls, inheritance, field/property - types, object creation, …). - -These analyzers do **not** attempt full semantic resolution (that would -require a real compiler front end). Instead, each one performs the -best-effort, file-local resolution that is possible from syntax alone, and -emits **unresolved** relationships (`is_resolved=False`) whenever a target -cannot be pinned down within the file. The heavy lifting of matching those -unresolved edges to real components *anywhere in the repository* β€” and of -deciding which un-matched edges are truly external (standard library, -third-party) rather than real gaps β€” is centralized in -[`CallGraphAnalyzer`](Dependency_Analysis_Service.md), which every analyzer in -this module is designed to feed. - -## Where this module sits in the system - -```mermaid -graph TD - RA["RepoAnalyzer
(file discovery)"] --> AS["AnalysisService"] - AS --> CGA["CallGraphAnalyzer"] - CGA -->|"routes by file extension/language"| ThisModule["C-Family Tree-sitter Analyzers
(this module)"] - CGA -->|"routes by file extension/language"| JSTS["JavaScript_TypeScript_Analyzers.md"] - CGA -->|"routes by file extension/language"| PHP["PHP_Analyzer.md"] - CGA -->|"routes by file extension/language"| PY["Python_Analyzer.md"] - ThisModule -->|"Node + CallRelationship lists"| CGA - CGA -->|"cross-file resolution + external filtering"| DP["DependencyParser"] - DP --> DGB["DependencyGraphBuilder"] - DGB --> Docs["Documentation Generator"] - - click AS "Dependency_Analysis_Service.md" - click CGA "Dependency_Analysis_Service.md" - click DP "Dependency_Analyzer_Core.md" - click DGB "Dependency_Analyzer_Core.md" - click Docs "Backend_LLM_&_Documentation_Services_documentation_generator.md" -``` - -* [`Dependency_Analysis_Service`](Dependency_Analysis_Service.md) owns - `CallGraphAnalyzer`, which discovers source files, dispatches each file to - the language-appropriate analyzer (including the ones documented here), - and then performs **cross-file symbol resolution** and **external-symbol - filtering** over the combined output of *all* language analyzers. -* [`Dependency_Analyzer_Core`](Dependency_Analyzer_Core.md) defines the shared - data models (`Node`, `CallRelationship`) that every analyzer β€” in this - module and its sibling language modules β€” must produce, plus the - `DependencyParser` and `DependencyGraphBuilder` that turn the resolved call - graph into the dependency graph used for documentation generation. -* Sibling language front ends live in - [`JavaScript_TypeScript_Analyzers`](JavaScript_TypeScript_Analyzers.md), - [`PHP_Analyzer`](PHP_Analyzer.md), and - [`Python_Analyzer`](Python_Analyzer.md) β€” architecturally identical in - role, just for different grammars. - -## Shared data contract - -Every analyzer in this module builds instances of the same two Pydantic -models (defined in `Dependency_Analyzer_Core`): - -```mermaid -classDiagram - class Node { - +str id - +str name - +str component_type - +str file_path - +str relative_path - +str source_code - +int start_line - +int end_line - +str docstring - +str node_type - +str class_name - +str display_name - +str component_id - +str language - +str qualified_name - +Set~str~ depends_on - } - class CallRelationship { - +str caller - +str callee - +int call_line - +bool is_resolved - } - Node "1" --> "*" CallRelationship : caller/callee reference Node.id -``` - -* **`Node.id` / `Node.component_id`** are built as - `"{relative_path_from_repo_root}::{qualified_name}"`, e.g. - `src/Foo.cpp::Logger.write`. This is the canonical identifier every other - module in CodeWiki (documentation generator, HTML viewer, MCP tools) uses - to refer to a piece of code. -* **`CallRelationship.is_resolved`** is the key coordination flag with - `CallGraphAnalyzer`: - * `True` means the analyzer is confident the `callee` is an exact `Node.id` - (usually a same-file resolution). - * `False` means the analyzer only knows a *name* β€” simple, qualified, or - dotted β€” and is delegating final resolution to `CallGraphAnalyzer`'s - repository-wide indexes (`_resolve_call_relationships`, - `_build_resolution_indexes`) and its external-symbol classifier - (`_is_external_callee`). - -## Common analyzer architecture - -Despite covering five different languages with very different grammars, all -five analyzers in this module follow the **same three-phase pipeline**: - -```mermaid -sequenceDiagram - participant CGA as CallGraphAnalyzer - participant AN as Tree-sitter Analyzer - participant TS as tree-sitter grammar - participant Model as Node / CallRelationship - - CGA->>AN: analyze__file(file_path, content, repo_path) - AN->>TS: Parser(Language).parse(content) - TS-->>AN: syntax tree (root node) - AN->>AN: _extract_nodes(root) β€” walk tree, build top_level_nodes map - AN->>Model: construct Node per declaration - AN->>AN: _extract_relationships(root, top_level_nodes) - AN->>Model: construct CallRelationship per reference - AN-->>CGA: (nodes, call_relationships) -``` - -1. **Parse** β€” each analyzer instantiates its own `tree_sitter.Language` - binding (`tree_sitter_c`, `tree_sitter_cpp`, `tree_sitter_c_sharp`, - `tree_sitter_java`, `tree_sitter_kotlin`) and parses the file content into - a syntax tree. -2. **`_extract_nodes`** β€” a recursive tree walk that recognizes - language-specific declaration node types (`function_definition`, - `class_declaration`, `method_declaration`, …), builds a `Node` for each, - and populates a `top_level_nodes` lookup dict (by simple name, qualified - name, and/or component id) used later for local resolution. -3. **`_extract_relationships`** β€” a second recursive walk that recognizes - reference sites (calls, `new`/object-creation, inheritance clauses, field - / property type annotations) and emits a `CallRelationship` for each, - resolving locally when possible and leaving `is_resolved=False` otherwise. - -Every analyzer also implements the same pair of path helpers so that -`Node.id` is consistent across languages: - -* `_get_relative_path()` β€” path of the file relative to `repo_path`. -* `_get_component_id(name, parent_class=None)` β€” `"{relative_path}::{name}"`, - or `"{relative_path}::{parent_class}.{name}"` for members. - -## Sub-modules - -Because the five languages split naturally into families that share -resolution strategy and complexity level, this module's detailed -documentation is organized into three sub-modules: - -| Sub-module | Languages | Focus | -|---|---|---| -| [C-Family_Tree-sitter_Analyzers_C_Cpp](C-Family_Tree-sitter_Analyzers_C_Cpp.md) | C, C++ | Positional/textual analysis, macro-tolerant parsing recovery for C++, no import/namespace system to resolve against | -| [C-Family_Tree-sitter_Analyzers_JVM](C-Family_Tree-sitter_Analyzers_JVM.md) | Java, Kotlin | Package/import-aware resolution, JDK filtering, variable-type tracking for member-call resolution | -| [C-Family_Tree-sitter_Analyzers_CSharp](C-Family_Tree-sitter_Analyzers_CSharp.md) | C# | `using`/alias-aware resolution, namespace declarations (block and file-scoped), static-import fallback | - -Each sub-module page documents its analyzer(s) in depth: which AST node -types are recognized, how names are qualified, how member/variable types are -tracked for call resolution, and language-specific edge cases (macros, -partial classes, generics, primary constructors, etc.). - -## How output feeds the rest of the pipeline - -```mermaid -flowchart LR - subgraph "This module" - A1["TreeSitterCAnalyzer"] - A2["TreeSitterCppAnalyzer"] - A3["TreeSitterCSharpAnalyzer"] - A4["TreeSitterJavaAnalyzer"] - A5["TreeSitterKotlinAnalyzer"] - end - A1 & A2 & A3 & A4 & A5 --> Funcs["functions: List[Node]"] - A1 & A2 & A3 & A4 & A5 --> Rels["relationships: List[CallRelationship]"] - Funcs --> Resolve["CallGraphAnalyzer._resolve_call_relationships"] - Rels --> Resolve - Resolve --> Filter["CallGraphAnalyzer._is_external_callee
(drops stdlib / third-party edges)"] - Filter --> Graph["Complete call graph
(functions + resolved relationships)"] - Graph --> DP["DependencyParser._build_components_from_analysis"] - DP --> DGB["DependencyGraphBuilder"] - DGB --> Gen["DocumentationGenerator"] -``` - -`CallGraphAnalyzer` dispatches to this module's analyzers based on file -language (`_analyze_c_file`, `_analyze_cpp_file`, `_analyze_csharp_file`, -`_analyze_java_file`, `_analyze_kotlin_file`), including a special routing -step (`_route_contextual_headers`) that decides whether an ambiguous `.h` -header should be parsed as C or C++ based on content signals and the -repository's overall file mix. See -[Dependency_Analysis_Service](Dependency_Analysis_Service.md) for full detail -on cross-file resolution and external-symbol filtering, and -[Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) for the `Node` / -`CallRelationship` schema and how the resolved graph becomes the final -dependency graph used by -[documentation generation](Backend_LLM_&_Documentation_Services_documentation_generator.md). diff --git a/docs/C-Family_Tree-sitter_Analyzers_CSharp.md b/docs/C-Family_Tree-sitter_Analyzers_CSharp.md deleted file mode 100644 index 1c79f789..00000000 --- a/docs/C-Family_Tree-sitter_Analyzers_CSharp.md +++ /dev/null @@ -1,294 +0,0 @@ -# C-Family Tree-sitter Analyzers: C# - -## Introduction - -The **C-Family_Tree-sitter_Analyzers_CSharp** module implements the C# language analyzer for CodeWiki's [Dependency_Analysis_Service](Dependency_Analysis_Service.md). It parses `.cs` source files with [tree-sitter](https://tree-sitter.github.io/tree-sitter/) grammars, extracts structural components (classes, interfaces, structs, enums, records, delegates, methods) as graph `Node`s, and emits unresolved `CallRelationship` edges for inheritance, field/property typing, object creation, and method invocations. These raw, per-file artifacts are then handed to the shared, language-agnostic [`CallGraphAnalyzer`](Dependency_Analysis_Service.md) for cross-file symbol resolution. - -This module is a sibling of the other C-family analyzers β€” [C/C++](C-Family_Tree-sitter_Analyzers_C_Cpp.md) and [Java/Kotlin](C-Family_Tree-sitter_Analyzers_JVM.md) β€” and was explicitly "ported" from the Java analyzer so that C# reaches feature parity: methods are first-class components, names are namespace-qualified, `using` directives drive symbol resolution, and every cross-reference is emitted *unresolved*, deferring the actual linking decision to the shared resolver. - -It contains a single core component: - -| Component | File | Responsibility | -|---|---|---| -| `TreeSitterCSharpAnalyzer` | `codewiki/src/be/dependency_analyzer/analyzers/csharp.py` | Parses one C# file into `Node` and `CallRelationship` objects | -| `analyze_csharp_file` | same file | Thin functional wrapper instantiating the analyzer and returning its results | - ---- - -## Position in the System - -```mermaid -graph TD - subgraph Dependency_Analysis_Service["Dependency_Analysis_Service"] - AS[AnalysisService] - RA[RepoAnalyzer] - CGA[CallGraphAnalyzer] - end - - subgraph Language_Analyzers["Language_Analyzers"] - CS["C-Family_Tree-sitter_Analyzers_CSharp
TreeSitterCSharpAnalyzer"] - JVM["C-Family_Tree-sitter_Analyzers_JVM
(Java/Kotlin)"] - CFAM["C-Family_Tree-sitter_Analyzers_C_Cpp
(C/C++)"] - JS["JavaScript_TypeScript_Analyzers"] - PHP["PHP_Analyzer"] - PY["Python_Analyzer"] - end - - subgraph Core["Dependency_Analyzer_Core"] - DP[DependencyParser] - Node["models.core.Node"] - CR["models.core.CallRelationship"] - end - - RA -->|file tree| AS - AS -->|files| CGA - CGA -->|"routes .cs files"| CS - CGA -.-> JVM - CGA -.-> CFAM - CGA -.-> JS - CGA -.-> PHP - CGA -.-> PY - - CS -->|produces| Node - CS -->|produces| CR - CGA -->|cross-file resolution| CR - DP -->|wraps| AS - DP -->|builds| Node - - style CS fill:#dff,stroke:#333,stroke-width:2px -``` - -The analyzer is invoked exclusively by `CallGraphAnalyzer._analyze_csharp_file` (see [Dependency_Analysis_Service](Dependency_Analysis_Service.md)), which: -1. Reads file content and routes it based on extension/language detection. -2. Calls `analyze_csharp_file(file_path, content, repo_path)`. -3. Merges the returned `Node`s into its global function map and `CallRelationship`s into its global relationship list. -4. Later runs `_resolve_call_relationships` to turn the analyzer's *unresolved* edges into resolved, cross-file links (or drops them as external/noise). - -The resulting `Node`/`CallRelationship` graph feeds the [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) (`DependencyParser`, `DependencyGraphBuilder`) and ultimately the [Backend LLM & Documentation Services](Backend_LLM_&_Documentation_Services.md) that generate the final wiki. - ---- - -## Design Philosophy: "Resolve First, Filter Second" - -A defining principle of this analyzer (and its Java/Kotlin siblings) is that **all** cross-references are emitted as unresolved `CallRelationship` candidates with `is_resolved=False`, deferring both linking and external-symbol filtering to `CallGraphAnalyzer`: - -- Framework types (`List`, `Console`, `Task`, …) are **not** filtered at extraction time β€” doing so would silently drop a real edge whenever a project type shadows a framework name. -- Only true language primitives (`int`, `string`, `var`, …) and generic type parameters in scope are excluded early via `_skip_type`. -- The shared resolver (`CallGraphAnalyzer._is_external_callee`) later classifies any still-unresolved dotted callee as external if its namespace has no prefix relationship to any known project namespace. - -This keeps the analyzer intentionally "dumb" about what is a real project symbol, pushing that decision to a stage with global visibility across all parsed files. - ---- - -## Architecture - -```mermaid -classDiagram - class TreeSitterCSharpAnalyzer { - +file_path: Path - +content: str - +repo_path: str - +nodes: List~Node~ - +call_relationships: List~CallRelationship~ - +alias_map: dict - +using_namespaces: list - +static_usings: list - +file_scoped_namespace: str - -_analyze() - -_extract_usings(node) - -_namespace_for(node) str - -_qualify(node, *names) str - -_extract_nodes(node, top_level_nodes, lines) - -_extract_doc_comment(node) Tuple - -_extract_relationships(node, top_level_nodes) - -_emit_type_use(type_node, context_node, top_level_nodes) - -_handle_invocation(node, top_level_nodes) - -_add_edge(caller, callee, node) - -_resolve_cs_type(type_name, context_node, top_level_nodes) str - -_resolve_cs_member(member_name, context_node, top_level_nodes, target_type) str - -_find_variable_type(node, variable_name) str - -_skip_type(type_name, context_node) bool - } - - class Node { - +id: str - +name: str - +component_type: str - +qualified_name: str - +language: str - ... - } - - class CallRelationship { - +caller: str - +callee: str - +call_line: int - +is_resolved: bool - } - - TreeSitterCSharpAnalyzer ..> Node : creates - TreeSitterCSharpAnalyzer ..> CallRelationship : creates -``` - -`Node` and `CallRelationship` are the shared pydantic models defined in [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) (`codewiki/src/be/dependency_analyzer/models/core.py`), used uniformly across all language analyzers. - ---- - -## Processing Pipeline - -```mermaid -flowchart TD - A["__init__(file_path, content, repo_path)"] --> B["_analyze()"] - B --> C["Parse file with tree_sitter_c_sharp grammar"] - C --> D["_extract_usings(root)
collect using/using static/using alias
+ file-scoped namespace"] - D --> E["_extract_nodes(root, top_level_nodes, lines)
walk AST, build Node objects"] - E --> F["_extract_relationships(root, top_level_nodes)
walk AST again, emit CallRelationship edges"] - F --> G["analyzer.nodes / analyzer.call_relationships"] - G --> H["Returned to CallGraphAnalyzer"] - H --> I["Merged into global functions/relationships"] - I --> J["_resolve_call_relationships()
(cross-file, in CallGraphAnalyzer)"] -``` - -### 1. Using-Directive Extraction (`_extract_usings`) - -A full AST walk (not regex) collects three forms of `using`: - -- **Plain**: `using MyApp.Models;` β†’ appended to `using_namespaces`. -- **Static**: `using static MyApp.Helpers;` β†’ appended to `static_usings`. -- **Alias**: `using S = System.Text;` β†’ recorded in `alias_map["S"] = "System.Text"`. - -It also records the `file_scoped_namespace` (C# 10+ `namespace Foo;` syntax), which combines with any nested block `namespace_declaration`s (see `_namespace_for`) to compute the fully qualified namespace at any AST location. - -### 2. Node Extraction (`_extract_nodes`) - -Recursively walks the tree, recognizing these declaration types and assigning a `component_type`: - -| AST Node Type | `component_type` | -|---|---| -| `class_declaration` | `class` / `static class` / `abstract class` | -| `interface_declaration` | `interface` | -| `struct_declaration` | `struct` | -| `enum_declaration` | `enum` | -| `record_declaration` | `record` / `record struct` | -| `delegate_declaration` | `delegate` | -| `method_declaration` | `method` (named `ClassName.MethodName`) | - -For each recognized declaration: -- `qualified_name` is computed via `_qualify` = namespace + enclosing type names + own name (dot-joined). -- `component_id` = `relative_file_path::name` (via `_get_component_id`). -- XML doc comments (`///`) immediately preceding the node are captured via `_extract_doc_comment`, skipping over attribute lists (`[Attr]`). -- The resulting `Node` is indexed in `top_level_nodes` under multiple keys β€” its simple name, its component id, its fully qualified name, and the last segment of the qualified name β€” so later relationship resolution can match declarations found anywhere in the same file by several naming conventions. - -### 3. Relationship Extraction (`_extract_relationships`) - -A second AST walk detects four categories of cross-references, always emitted with `is_resolved=False`: - -```mermaid -flowchart LR - subgraph Relationship_Sources - Base["Base list
(extends/implements)"] - Field["Field / property / event
type usage"] - PrimaryCtor["Primary constructor
parameters (C# 12 / records)"] - Invoke["Method invocations"] - NewObj["Object creation
(new T())"] - end - Base --> Emit["CallRelationship(caller, callee, is_resolved=False)"] - Field --> Emit - PrimaryCtor --> Emit - Invoke --> Emit - NewObj --> Emit -``` - -- **Base list**: `class Foo : Bar, IBaz` β†’ edges `Foo -> Bar`, `Foo -> IBaz` (C# doesn't distinguish base class from interfaces syntactically). -- **Field / property / event declarations**: the declared type is resolved and linked from the containing class. -- **Primary constructor parameters**: C# 12 primary constructors and record parameter lists are treated like field type usages. -- **Invocation expressions** (`_handle_invocation`): the most complex case β€” see below. -- **Object creation expressions**: `new Foo()` inside a method links the containing class to `Foo`. - -#### Invocation Resolution Logic (`_handle_invocation`) - -```mermaid -flowchart TD - Start["invocation_expression node"] --> Func{"function child type?"} - Func -->|identifier| Bare["bare=True
(local/inherited member call)"] - Func -->|member_access_expression| Receiver{"receiver expression?"} - Receiver -->|this| Bare - Receiver -->|base| BaseType["target_type = first base type"] - Receiver -->|identifier X| Lookup["target_type = variable type of X,
or X itself if it's a known type/PascalCase"] - Receiver -->|chained/qualified| Skip["return (not modelled)"] - - Bare --> EnclosingCheck["Try enclosing_member_candidates
(walk outward through containing types)"] - EnclosingCheck -->|found in file| Edge1["emit edge to local candidate"] - EnclosingCheck -->|not found| StaticGuess["emit one edge per
using-static class as a guess"] - - BaseType --> ResolveMember["_resolve_cs_member: Type.method"] - Lookup --> ResolveMember - ResolveMember --> ObjCheck{"unresolved & method is
System.Object method?"} - ObjCheck -->|yes| Drop["drop (never a project edge)"] - ObjCheck -->|no| Edge2["emit edge"] -``` - -Key heuristics: -- **`this.Method()`** and bare `Method()` calls are attributed to the enclosing type chain (`_enclosing_member_candidates` walks outward from innermost to outermost containing type). -- **`base.Method()`** resolves to the first listed base type. -- **Identifier receivers** (`obj.Method()`) use `_find_variable_type` to look up the declared type of a local variable, parameter, field, or property β€” including `var x = new T()` inference β€” falling back to treating a PascalCase identifier as a static type reference (all-caps identifiers are treated as constants, not types). -- **Chained/qualified receivers** (`a.B().C()`, `Outer.Inner.M()`) are explicitly *not* modelled and skipped β€” a known, documented limitation. -- **`using static`** ambiguity: when a bare call can't be matched to any enclosing member, the analyzer emits one *candidate* edge per statically-imported class, since it cannot determine at parse time which one actually contains the member. Only the correct guess will resolve downstream; the rest are pruned by the shared resolver as external/unmatched. -- Calls resolving to a name in `CSHARP_OBJECT_METHODS` (from `codewiki/src/be/dependency_analyzer/utils/external_symbols.py`) that don't match a real project node are dropped, since they represent inherited `System.Object` members (`ToString`, `Equals`, `GetHashCode`, …) rather than project code. - -### 4. Type Resolution Helpers - -- **`_unwrap_type`**: strips `nullable_type`, `array_type`, `pointer_type`, and `generic_name` wrappers down to a bare type identifier (e.g., `List?[]` β†’ `List`). -- **`_skip_type`**: filters out C# primitives (`int`, `string`, `var`, `dynamic`, …) and any generic type parameter currently in scope (walked up through enclosing type/method declarations via `_find_type_parameters`). -- **`_resolve_cs_type`**: attempts to qualify a bare type name against, in order: alias map, enclosing type nesting (nested-type shadowing), then each `using` namespace β€” returning the first match found in `top_level_nodes` (same-file symbols). If nothing matches, it returns the bare simple name, deliberately *not* fabricating a namespace, so that: - - A genuine project type in another file can still match by tail/simple name in the cross-file resolver. - - A third-party type from an external library correctly stays unqualified, allowing `CallGraphAnalyzer`'s namespace-origin rule to classify it as external instead of confusing it with the current file's own namespace. -- **`_resolve_cs_member`**: builds a `Type.member` candidate string from a resolved receiver type, preferring an exact match in `top_level_nodes`, falling back to the simple (non-namespaced) type name. - ---- - -## Data Model Mapping - -Every extracted declaration becomes a `Node` (shared model, see [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)): - -```mermaid -graph LR - AST["Tree-sitter AST node
(class_declaration, method_declaration, ...)"] --> Node - Node -->|id| ID["relative_path::name"] - Node -->|qualified_name| QN["Namespace.Outer.Inner.Member"] - Node -->|component_type / node_type| CT["class / interface / struct /
enum / record / delegate / method"] - Node -->|source_code| SRC["verbatim lines start_line..end_line"] - Node -->|docstring| DOC["///-comment block, cleaned"] - Node -->|language| L["'csharp'"] -``` - -Every cross-reference becomes a `CallRelationship` (`caller`, `callee`, `call_line`, `is_resolved=False`), always pointing from a component id (or a best-effort candidate string) to another. The `caller` is either: -- the containing type's `component_id` (for base lists, field types, object creation without a specific method context), or -- the containing method's `component_id` when available (for invocations inside a method body). - -The `callee` may be a fully resolved candidate (`Namespace.Type.Method`) or, in the "using static" guess case, one candidate string per static-import target β€” several unresolved edges from a single call site, of which at most one is expected to eventually resolve. - ---- - -## Known Limitations - -As documented directly in the source module docstring, these gaps are deliberate trade-offs rather than bugs: - -1. **Partial classes** across multiple files each produce their own `Node` sharing the same qualified name; a bare reference is never arbitrarily bound to one half, so it may remain an honest unresolved gap. -2. **Top-level statements** (`global_statement`, C# 9+ top-level `Main`) have no containing type, so calls made there are not attributed to any caller. -3. **Cross-file `global using` visibility** is not modelled β€” visibility of `global using` directives declared in one file but used in another is not tracked. -4. **`new()` implicit object creation** (target-typed `new`) is not resolved to a concrete type. -5. **Tuple types** are not modelled as type references. -6. **Chained-receiver typing** (`a.B().C()`) is not resolved β€” the analyzer explicitly bails out on such invocation chains. - -These limitations mean some real C# call edges will simply not appear in the dependency graph rather than being mis-attributed β€” consistent with the module's "resolve first, filter second" philosophy of preferring an honest gap over a false edge. - ---- - -## Related Modules - -- [Dependency_Analysis_Service](Dependency_Analysis_Service.md) β€” orchestrates repository-wide analysis; `CallGraphAnalyzer` is the sole caller of this module and performs cross-file resolution and external-symbol filtering. -- [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) β€” defines the shared `Node`/`CallRelationship` models and the `DependencyParser`/`DependencyGraphBuilder` that consume the aggregated graph. -- [C-Family_Tree-sitter_Analyzers_JVM](C-Family_Tree-sitter_Analyzers_JVM.md) β€” the Java analyzer this C# analyzer was ported from; shares the namespace/package-origin resolution rule in `CallGraphAnalyzer`. -- [C-Family_Tree-sitter_Analyzers_C_Cpp](C-Family_Tree-sitter_Analyzers_C_Cpp.md) β€” sibling C-family analyzer for C/C++. -- [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) β€” consumes the final dependency graph to generate module documentation such as this file. diff --git a/docs/C-Family_Tree-sitter_Analyzers_C_Cpp.md b/docs/C-Family_Tree-sitter_Analyzers_C_Cpp.md deleted file mode 100644 index eb1aecd5..00000000 --- a/docs/C-Family_Tree-sitter_Analyzers_C_Cpp.md +++ /dev/null @@ -1,397 +0,0 @@ -# C-Family Tree-sitter Analyzers: C & C++ - -## Introduction - -The **C-Family Tree-sitter Analyzers (C/C++)** module provides static-analysis capabilities for C and C++ source files within the CodeWiki dependency-analysis pipeline. It is implemented as two sibling analyzers β€” `TreeSitterCAnalyzer` and `TreeSitterCppAnalyzer` β€” that each parse a single source file with [tree-sitter](https://tree-sitter.github.io/tree-sitter/) grammars (`tree_sitter_c` / `tree_sitter_cpp`), extract structural code components (functions, structs, classes, methods, global variables, type aliases, namespaces), and record call/usage relationships between them. - -These analyzers are one of several language-specific plugins invoked by the [Dependency_Analysis_Service](Dependency_Analysis_Service.md)'s `CallGraphAnalyzer`, which is responsible for orchestrating multi-language repository analysis, cross-file/cross-language relationship resolution, and external-symbol filtering. The analyzers in this module only perform **single-file, language-specific extraction** β€” all cross-file resolution and unresolved-call filtering happens centrally afterward. - -This module is a sibling to the other Tree-sitter-based language analyzer families: -- [C-Family_Tree-sitter_Analyzers_JVM](C-Family_Tree-sitter_Analyzers_JVM.md) (Java, Kotlin) -- [C-Family_Tree-sitter_Analyzers_CSharp](C-Family_Tree-sitter_Analyzers_CSharp.md) (C#) -- [JavaScript_TypeScript_Analyzers](JavaScript_TypeScript_Analyzers.md) -- [PHP_Analyzer](PHP_Analyzer.md) -- [Python_Analyzer](Python_Analyzer.md) - -All of these plug into the same [Dependency_Analysis_Service](Dependency_Analysis_Service.md) and produce the same `Node` / `CallRelationship` data model defined in [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md). - ---- - -## Module Position in the System - -```mermaid -graph TB - subgraph "Dependency_Analysis_Service" - AS[AnalysisService] - RA[RepoAnalyzer] - CGA[CallGraphAnalyzer] - end - - subgraph "Language_Analyzers" - subgraph "C-Family_Tree-sitter_Analyzers_C_Cpp (this module)" - CA[TreeSitterCAnalyzer
c.py] - CPPA[TreeSitterCppAnalyzer
cpp.py] - end - JVM[C-Family_Tree-sitter_Analyzers_JVM] - CS[C-Family_Tree-sitter_Analyzers_CSharp] - JSTS[JavaScript_TypeScript_Analyzers] - PHP[PHP_Analyzer] - PY[Python_Analyzer] - end - - subgraph "Dependency_Analyzer_Core" - Node[Node model] - CR[CallRelationship model] - DP[DependencyParser] - DGB[DependencyGraphBuilder] - end - - RA --> AS - AS --> CGA - CGA -->|routes .c files| CA - CGA -->|routes .cpp/.hpp/ambiguous .h files| CPPA - CGA --> JVM - CGA --> CS - CGA --> JSTS - CGA --> PHP - CGA --> PY - - CA -->|produces| Node - CA -->|produces| CR - CPPA -->|produces| Node - CPPA -->|produces| CR - - CGA -->|resolves & filters| CR - DP -->|consumes AnalysisService output| AS - DP --> Node - DGB --> Node -``` - -The `CallGraphAnalyzer` (see [Dependency_Analysis_Service](Dependency_Analysis_Service.md)) decides, per file, which analyzer to invoke: -- `.c` files β†’ `TreeSitterCAnalyzer` -- `.cpp`, `.cc`, `.cxx`, `.c++`, `.hpp`, `.hxx`, `.h++` β†’ `TreeSitterCppAnalyzer` -- Ambiguous `.h` headers β†’ routed to C++ if the header content shows C++ signals (namespaces, classes, templates, `::`, or C++ standard headers) **or** if the repository contains only C++ files and no C files (`_route_contextual_headers` / `_header_has_cpp_signal` in `CallGraphAnalyzer`). - ---- - -## Component Overview - -```mermaid -classDiagram - class TreeSitterCAnalyzer { - +file_path: Path - +content: str - +repo_path: str - +nodes: List~Node~ - +call_relationships: List~CallRelationship~ - -_analyze() - -_extract_nodes(node, top_level_nodes, lines) - -_extract_relationships(node, top_level_nodes) - -_is_global_variable(node) bool - -_find_containing_function(node, top_level_nodes) - -_get_component_id(name) str - -_get_relative_path() str - } - - class TreeSitterCppAnalyzer { - +file_path: Path - +content: str - +repo_path: str - +nodes: List~Node~ - +call_relationships: List~CallRelationship~ - -_analyze() - -_parse_with_macro_recovery(parser) - -_normalize_for_parser(content) str - -_extract_nodes(node, top_level_nodes, lines) - -_extract_relationships(node, top_level_nodes) - -_find_variable_type(node, name) str - -_find_method_component(name, nodes, class_name) str - -_find_class_containing_method(name, nodes) str - -_is_system_function(name) bool - -_get_component_id(name, parent_class) str - } - - class Node { - <> - id: str - name: str - component_type: str - file_path: str - relative_path: str - source_code: str - start_line: int - end_line: int - node_type: str - class_name: str - display_name: str - component_id: str - language: str - qualified_name: str - } - - class CallRelationship { - <> - caller: str - callee: str - call_line: int - is_resolved: bool - } - - TreeSitterCAnalyzer --> Node : creates - TreeSitterCAnalyzer --> CallRelationship : creates - TreeSitterCppAnalyzer --> Node : creates - TreeSitterCppAnalyzer --> CallRelationship : creates -``` - -See [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) for the full `Node` and `CallRelationship` model definitions used throughout all language analyzers. - ---- - -## `TreeSitterCAnalyzer` (c.py) - -### Purpose -Parses a single `.c`/`.h` file using the `tree_sitter_c` grammar and extracts: -- **Functions** (`function_definition`) -- **Structs** (`struct_specifier`, and `typedef struct { ... } Name;` via `type_definition`) -- **Global variables** (top-level `declaration` nodes not nested inside a function) - -It also records two kinds of relationships: -1. **Function β†’ function calls** (`call_expression` inside a function body) -2. **Function β†’ global variable usage** (identifier reference to a known global variable) - -### Construction & Entry Point - -```python -TreeSitterCAnalyzer(file_path, content, repo_path=None) -``` -On construction, `_analyze()` runs immediately, populating `self.nodes` and `self.call_relationships`. The convenience function: - -```python -analyze_c_file(file_path, content, repo_path=None) -> (List[Node], List[CallRelationship]) -``` - -is the module-level entry point used by `CallGraphAnalyzer._analyze_c_file`. - -### ID Scheme -- **`component_id`**: `"::"` (e.g. `src/utils.c::compute_sum`) -- **module path** (`_get_module_path`): dotted path with `.c`/`.h` extension stripped, used for module grouping. - -### Processing Flow - -```mermaid -flowchart TD - A[Source content] --> B[tree_sitter_c parser] - B --> C[Root AST node] - C --> D["_extract_nodes(root)"] - D --> D1[Recursive traversal] - D1 --> D2{Node type?} - D2 -->|function_definition| E1[Create 'function' Node] - D2 -->|struct_specifier / typedef struct| E2[Create 'struct' Node] - D2 -->|declaration at file scope| E3[Create 'variable' Node
tracked but not emitted to .nodes] - E1 --> F[top_level_nodes map] - E2 --> F - E3 --> F - C --> G["_extract_relationships(root, top_level_nodes)"] - G --> G1{Node type?} - G1 -->|call_expression| H1[Resolve containing function
Emit unresolved CallRelationship
with simple callee name] - G1 -->|identifier referencing global var| H2[Emit resolved CallRelationship
caller→variable] - H1 --> I[self.call_relationships] - H2 --> I - F --> J[self.nodes: functions + structs only] -``` - -### Key Behaviors -- **Global variable detection** (`_is_global_variable`): walks up the parent chain; if any ancestor is a `function_definition`, the declaration is local, not global. -- **Struct name extraction** handles both direct `struct Name {}` and `typedef struct {} Name;` forms. -- **Call resolution deferral**: called function names are recorded as **simple names** with `is_resolved=False`. Filtering out libc/standard-library calls (e.g. `printf`, `malloc`) is intentionally **not** done here — it is deferred to `CallGraphAnalyzer` after cross-file resolution, so a project function that happens to shadow a libc name is not incorrectly dropped. -- Global variables are tracked in `top_level_nodes` for relationship resolution but are **not** added to `self.nodes` (only `function` and `struct` types are emitted as first-class components). - ---- - -## `TreeSitterCppAnalyzer` (cpp.py) - -### Purpose -A significantly more sophisticated analyzer for C++ that extracts: -- **Classes** (`class_specifier`) -- **Structs** (`struct_specifier`) -- **Functions** and **methods** (`function_definition`, disambiguated by whether a containing class is found) -- **Global variables** (top-level `declaration`) -- **Type aliases** (`using X = Y;` via `alias_declaration`, and `typedef` via `type_definition`) -- **Namespaces** (`namespace_definition`) — tracked structurally but not added to `self.nodes` - -It records relationships for: -1. Function/method → function/method **calls** (including member calls via `field_expression`, e.g. `obj.method()` / `ptr->method()`) -2. Class → **base class** inheritance (`base_class_clause`) -3. Function/method → **object instantiation** (`new_expression`) -4. Function/method → **global variable usage** - -### Construction & Entry Point - -```python -TreeSitterCppAnalyzer(file_path, content, repo_path=None) -analyze_cpp_file(file_path, content, repo_path=None) -> (List[Node], List[CallRelationship]) -``` -Used by `CallGraphAnalyzer._analyze_cpp_file`. - -### ID Scheme -- Free functions/classes/structs/type aliases: `"::"` -- Methods: `"::."` (qualified with parent class via `_get_component_id(name, parent_class)`) -- `qualified_name` on the `Node` mirrors this: `"."` for methods, plain `name` otherwise. - -### Macro-Tolerant Parsing - -A distinctive feature of this analyzer is **macro recovery parsing**, designed to keep tree-sitter's C++ grammar from choking on export/visibility macros commonly found in real-world C++ codebases (e.g. `EXPORT_API void foo()`, `class LIB_API Logger {`, `LIB_BEGIN_NAMESPACE`). - -```mermaid -flowchart TD - A[Raw file content] --> B["parser.parse(content)"] - B --> C{tree.root_node.has_error?} - C -->|No| Z[Use original AST] - C -->|Yes| D["_normalize_for_parser(content)"] - D --> E{normalized == original?} - E -->|Yes, no macros found| Z - E -->|No| F["parser.parse(normalized)"] - F --> G["Compare error counts:
original vs normalized parse"] - G -->|normalized has fewer errors| H[Use normalized AST] - G -->|otherwise| Z -``` - -Normalization strategy (`_normalize_for_parser`, driven by regexes): -- `_STANDALONE_MACRO_RE`: blanks lines that are *only* an ALL_CAPS macro (optionally macro-call style), e.g. `LIB_BEGIN_NAMESPACE` β€” preserves line numbers by replacing with an empty line rather than deleting it. -- `_SPECIFIER_MACRO_RE` / `_SPECIFIER_MACRO_CALL_RE`: strips an ALL_CAPS specifier macro (plain or function-call-like, e.g. `VISIBILITY("default")`) sitting directly before a declaration, at the start of a line or after a structural delimiter (`{`, `}`, `;`, `>`, `,`). -- `_KEYWORD_MACRO_RE`: strips an ALL_CAPS macro sitting between a `class`/`struct`/`union`/`enum` keyword and the real type name (e.g. `class LIB_API Logger` β†’ `class Logger`). - -All of these gate on `is_macro_name(...)` from `codewiki.src.be.dependency_analyzer.utils.external_symbols`, which relies on the **ALL_CAPS naming convention** rather than any hardcoded library-specific macro list β€” keeping the heuristic name-agnostic and safe for arbitrary codebases. Crucially, the self-correcting error-count comparison means normalization is a no-op for clean code (files with e.g. Win32-style ALL_CAPS *type* names like `HANDLE`/`DWORD` are never touched unless normalization measurably reduces parse errors). - -### Node Extraction Flow - -```mermaid -flowchart TD - Root[AST root] --> Rec["_extract_nodes(node)"] - Rec --> T{node.type} - T -->|class_specifier| Class[Extract class name β†’ 'class' Node] - T -->|struct_specifier| Struct[Extract struct name β†’ 'struct' Node] - T -->|function_definition| FuncCheck["_find_containing_class_for_method()"] - FuncCheck -->|class found or qualified_identifier parent::method| Method['method' Node
keyed by ClassName.method] - FuncCheck -->|no class found| Func['function' Node] - T -->|declaration + containing class + function_declarator| MethodDecl['method' Node
declaration-only, e.g. header] - T -->|declaration, file scope, non-method| GlobalVar['variable' Node
tracked, not emitted] - T -->|alias_declaration 'using X = Y'| Alias['type_alias' Node] - T -->|type_definition 'typedef ... Name'| Alias - T -->|namespace_definition| NS['namespace' Node
tracked, not emitted] - Class --> Map[top_level_nodes] - Struct --> Map - Method --> Map - Func --> Map - MethodDecl --> Map - GlobalVar --> Map - Alias --> Map - NS --> Map - Map --> Emit["self.nodes
(class, struct, function, method, type_alias)"] -``` - -`top_level_nodes` is populated with multiple keys per method (component_id, `ClassName.method`, and bare method name as fallback) to make later relationship resolution robust regardless of how the call site refers to it. - -### Relationship Extraction Flow - -```mermaid -flowchart TD - Root[AST root] --> Rec["_extract_relationships(node)"] - Rec --> T{node.type} - - T -->|call_expression| CE[Identify caller via
_find_containing_function_or_method] - CE --> CE1{Simple identifier
or field_expression?} - CE1 -->|field_expression e.g. obj.method| Recv["_get_field_call_parts:
receiver_name, method_name"] - Recv --> Type["_find_variable_type(receiver)
via local decl / parameter scan"] - Type --> Resolve1["_find_method_component(method, class=type)"] - CE1 -->|plain identifier| Resolve2["_find_method_component(name)
or top_level_nodes[name]"] - Resolve1 -->|found| Rel1[Resolved CallRelationship: caller→method.id] - Resolve2 -->|found| Rel1 - Resolve1 -->|not found| ClassGuess["_find_class_containing_method
(heuristic source-scan)"] - ClassGuess -->|found| Rel2[Resolved CallRelationship: caller→class.id] - ClassGuess -->|not found, has receiver| Filter1{"_is_system_function?
(external_symbols or ALL_CAPS macro)"} - Filter1 -->|no| Rel3[Unresolved CallRelationship: caller→method name] - Filter1 -->|yes| Drop1[Dropped] - ClassGuess -->|not found, no receiver, not macro/template param| Rel4[Unresolved CallRelationship:
caller→simple name
for cross-file resolution] - - T -->|base_class_clause| BC["Extract base class type_identifier
(excluding template params & macros)"] - BC --> Rel5[Unresolved CallRelationship: class→base_class name] - - T -->|new_expression| NE["Extract instantiated type_identifier"] - NE -->|known class| Rel6[Resolved CallRelationship: caller→class.id] - - T -->|identifier referencing global var| GV[Resolved CallRelationship: caller→var name] -``` - -### Notable Resolution Helpers - -| Helper | Purpose | -|---|---| -| `_find_variable_type` | Scans enclosing scopes (`compound_statement`, `field_declaration_list`, function parameters) to infer the declared type of a receiver variable used in `obj.method()` calls, enabling precise method resolution. | -| `_find_method_component` | Looks up a method by `ClassName.method` key first, then falls back to any method with a matching simple name across the file. | -| `_find_class_containing_method` | Heuristic fallback: scans a class's raw `source_code` text for a line containing `method_name(` combined with common return-type tokens (`void`, `int`, `bool`, or the class name itself) — used when the method wasn't independently extracted as a node (e.g., inline-defined in a header without separate declaration). | -| `_find_template_parameters` | Walks up to enclosing `template_declaration` nodes to collect in-scope type parameter names (e.g. `T`), preventing them from being misreported as unresolved project symbols or spurious base classes. | -| `_is_system_function` | Combines `is_external_symbol("cpp", name)` (curated stdlib/STL name check from `external_symbols`) with `is_macro_name(name)` (ALL_CAPS convention) to decide whether an unresolved member call should be suppressed rather than emitted as noise. | -| `_get_qualified_declarator_parts` | Extracts the parts of a `qualified_identifier` declarator (e.g. `Namespace::Class::method`) to recover the containing class even in out-of-class method definitions (`ReturnType ClassName::method() { ... }`). | - ---- - -## Shared Design Patterns Across Both Analyzers - -Both analyzers follow the same overall contract expected by `CallGraphAnalyzer` and `DependencyParser` (see [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)): - -1. **Single-file, self-contained analysis** — no cross-file lookups are performed inside the analyzer itself. -2. **Two-pass traversal** — first pass (`_extract_nodes`) builds a `top_level_nodes` dictionary of all extractable symbols in the file; second pass (`_extract_relationships`) walks the tree again to record calls/usages, using the dictionary built in pass one for local resolution. -3. **Deferred resolution / filtering** — calls to symbols not found locally are emitted as `CallRelationship(is_resolved=False, callee=)`. The heavy lifting of matching these across files/languages and filtering out genuinely external calls is centralized in `CallGraphAnalyzer._resolve_call_relationships` and `_is_external_callee` (see [Dependency_Analysis_Service](Dependency_Analysis_Service.md)). -4. **Component ID convention** — `"::"`, with methods further qualified by `.` prefix on the name portion in C++. -5. **`Node` / `CallRelationship` models** are shared Pydantic models from [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md), ensuring uniform downstream consumption (dependency graph building, LLM documentation generation) regardless of source language. - ---- - -## Data Flow: From Repository File to Call Graph - -```mermaid -sequenceDiagram - participant RA as RepoAnalyzer - participant AS as AnalysisService - participant CGA as CallGraphAnalyzer - participant CA as TreeSitterCAnalyzer - participant CPPA as TreeSitterCppAnalyzer - participant CORE as Dependency_Analyzer_Core - - RA->>AS: file tree (filtered by gitignore/patterns) - AS->>CGA: analyze_code_files(code_files, base_dir) - CGA->>CGA: _route_contextual_headers() (.h to c or cpp) - loop for each source file - alt language == "c" - CGA->>CA: analyze_c_file(path, content, repo_path) - CA-->>CGA: (nodes, call_relationships) - else language == "cpp" - CGA->>CPPA: analyze_cpp_file(path, content, repo_path) - CPPA-->>CGA: (nodes, call_relationships) - end - end - CGA->>CGA: _resolve_call_relationships()
(cross-file/language matching, macro & stdlib filtering) - CGA->>CGA: _deduplicate_relationships() - CGA-->>CORE: functions[], relationships[] (as dicts) - CORE->>CORE: DependencyParser builds Node graph
DependencyGraphBuilder assembles final structure -``` - ---- - -## Extension Points & Limitations - -- **Language coverage**: Only standard C/C++ constructs are handled. Preprocessor directives (`#ifdef`, `#define` expansions beyond the macro-name heuristic) are not evaluated β€” the analyzer works purely on tree-sitter's syntactic parse. -- **Type resolution for calls** is best-effort (`_find_variable_type` only looks at local declarations/parameters in enclosing scopes, not full type inference), so complex call chains (e.g. through container elements or lambda captures) may resolve as unresolved calls, which is by design deferred to cross-file resolution or safely dropped as external. -- **Macro normalization** is purposely conservative (error-count comparison) to avoid corrupting legitimately macro-styled type names. -- Both analyzers rely on `codewiki.src.be.dependency_analyzer.utils.external_symbols` for the `is_external_symbol` / `is_macro_name` heuristics shared with the central `CallGraphAnalyzer` filtering step β€” keeping the external-vs-project distinction consistent across the whole pipeline (see [Dependency_Analysis_Service](Dependency_Analysis_Service.md) for the centralized filtering logic in `_is_external_callee`). - ---- - -## Related Documentation - -- [Dependency_Analysis_Service](Dependency_Analysis_Service.md) β€” orchestrates repository scanning, invokes these analyzers via `CallGraphAnalyzer`, and performs cross-file/language relationship resolution and external-symbol filtering. -- [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) β€” defines the shared `Node`, `CallRelationship` models, `DependencyParser`, and `DependencyGraphBuilder` that consume this module's output. -- [C-Family_Tree-sitter_Analyzers_JVM](C-Family_Tree-sitter_Analyzers_JVM.md) β€” sibling analyzers for Java/Kotlin using the same architectural pattern. -- [C-Family_Tree-sitter_Analyzers_CSharp](C-Family_Tree-sitter_Analyzers_CSharp.md) β€” sibling analyzer for C#. -- [JavaScript_TypeScript_Analyzers](JavaScript_TypeScript_Analyzers.md), [PHP_Analyzer](PHP_Analyzer.md), [Python_Analyzer](Python_Analyzer.md) β€” other language-specific analyzer families in the [Language_Analyzers](Dependency_Analysis_Service.md) group. diff --git a/docs/C-Family_Tree-sitter_Analyzers_JVM.md b/docs/C-Family_Tree-sitter_Analyzers_JVM.md deleted file mode 100644 index 0771656b..00000000 --- a/docs/C-Family_Tree-sitter_Analyzers_JVM.md +++ /dev/null @@ -1,444 +0,0 @@ -# C-Family Tree-sitter Analyzers: JVM (Java & Kotlin) - -## Introduction - -The **C-Family Tree-sitter Analyzers (JVM)** module provides static-analysis capabilities for Java and Kotlin source files within the CodeWiki dependency-analysis pipeline. It is implemented as two sibling analyzers β€” `TreeSitterJavaAnalyzer` and `TreeSitterKotlinAnalyzer` β€” that each parse a single source file with [tree-sitter](https://tree-sitter.github.io/tree-sitter/) grammars (`tree_sitter_java` / `tree_sitter_kotlin`), extract structural code components (classes, interfaces, enums, records, annotations, objects, methods, functions), and record inheritance/usage/call relationships between them. - -Compared to the [C-Family_Tree-sitter_Analyzers_C_Cpp](C-Family_Tree-sitter_Analyzers_C_Cpp.md) sibling, the JVM analyzers are distinguished by **package/import-aware name resolution**: Java code is organized around `package` declarations and explicit `import` statements (including wildcard imports and static imports), which the Java analyzer parses and uses to qualify every type reference it encounters. This lets it resolve simple names like `Logger` to their fully-qualified form (`com.example.util.Logger`) and to reliably distinguish project types from JDK/runtime types using the shared [`is_external_symbol`](Dependency_Analyzer_Core.md) classifier. The Kotlin analyzer is comparatively lighter-weight (no import-table construction) and relies on a curated built-in/primitive-type set plus local variable/parameter scanning to avoid false-positive edges to standard-library types. - -These analyzers are two of several language-specific plugins invoked by the [Dependency_Analysis_Service](Dependency_Analysis_Service.md)'s `CallGraphAnalyzer`, which orchestrates multi-language repository analysis, cross-file/cross-language relationship resolution, and external-symbol filtering. The analyzers documented here perform only **single-file, language-specific extraction** β€” all cross-file resolution and unresolved-call filtering happens centrally afterward in `CallGraphAnalyzer`. - -This module is a sibling to the other Tree-sitter-based language analyzer families under [Language_Analyzers](C-Family_Tree-sitter_Analyzers.md): -- [C-Family_Tree-sitter_Analyzers_C_Cpp](C-Family_Tree-sitter_Analyzers_C_Cpp.md) (C, C++) -- [C-Family_Tree-sitter_Analyzers_CSharp](C-Family_Tree-sitter_Analyzers_CSharp.md) (C#) -- [JavaScript_TypeScript_Analyzers](JavaScript_TypeScript_Analyzers.md) -- [PHP_Analyzer](PHP_Analyzer.md) -- [Python_Analyzer](Python_Analyzer.md) - -All of these plug into the same [Dependency_Analysis_Service](Dependency_Analysis_Service.md) and produce the same `Node` / `CallRelationship` data model defined in [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md). - ---- - -## Module Position in the System - -```mermaid -graph TB - subgraph "Dependency_Analysis_Service" - AS[AnalysisService] - RA[RepoAnalyzer] - CGA[CallGraphAnalyzer] - end - - subgraph "Language_Analyzers" - subgraph "C-Family_Tree-sitter_Analyzers_JVM (this module)" - JA[TreeSitterJavaAnalyzer
java.py] - KA[TreeSitterKotlinAnalyzer
kotlin.py] - end - CCPP[C-Family_Tree-sitter_Analyzers_C_Cpp] - CS[C-Family_Tree-sitter_Analyzers_CSharp] - JSTS[JavaScript_TypeScript_Analyzers] - PHP[PHP_Analyzer] - PY[Python_Analyzer] - end - - subgraph "Dependency_Analyzer_Core" - Node[Node model] - CR[CallRelationship model] - DP[DependencyParser] - DGB[DependencyGraphBuilder] - end - - subgraph "Shared Utilities" - ES[is_external_symbol
external_symbols.py] - end - - RA --> AS - AS --> CGA - CGA -->|routes .java files| JA - CGA -->|routes .kt / .kts files| KA - CGA --> CCPP - CGA --> CS - CGA --> JSTS - CGA --> PHP - CGA --> PY - - JA -->|produces| Node - JA -->|produces| CR - JA -->|consults| ES - KA -->|produces| Node - KA -->|produces| CR - - CGA -->|resolves & filters| CR - DP -->|consumes AnalysisService output| AS - DP --> Node - DGB --> Node -``` - -The `CallGraphAnalyzer` (see [Dependency_Analysis_Service](Dependency_Analysis_Service.md)) dispatches per file: -- `.java` files β†’ `TreeSitterJavaAnalyzer` (via `_analyze_java_file`) -- `.kt` / `.kts` files β†’ `TreeSitterKotlinAnalyzer` (via `_analyze_kotlin_file`) - -Both analyzers emit `Node` and `CallRelationship` lists that flow, unmodified in shape, into `CallGraphAnalyzer`'s repository-wide resolution indexes and external-symbol filter, and from there into [`DependencyParser`](Dependency_Analyzer_Core.md) and [`DependencyGraphBuilder`](Dependency_Analyzer_Core.md). - ---- - -## Component Overview - -```mermaid -classDiagram - class TreeSitterJavaAnalyzer { - +file_path: Path - +content: str - +repo_path: str - +nodes: List~Node~ - +call_relationships: List~CallRelationship~ - +package_name: str - +import_map: dict~str,str~ - +wildcard_imports: list~str~ - -_analyze() - -_extract_nodes(node, top_level_nodes, lines) - -_extract_relationships(node, top_level_nodes) - -_extract_package_name() str - -_extract_imports() tuple - -_resolve_java_type(type_name, context_node, top_level_nodes) str - -_resolve_java_member(member_name, context_node, top_level_nodes, target_type) str - -_is_primitive_type(type_name) bool - -_skip_type(type_name, context_node) bool - -_find_variable_type(node, variable_name, top_level_nodes) str - -_find_containing_class(node, top_level_nodes) str - -_find_containing_method(node) str - -_get_component_id(name, parent_class) str - } - - class TreeSitterKotlinAnalyzer { - +file_path: Path - +content: str - +repo_path: str - +nodes: List~Node~ - +call_relationships: List~CallRelationship~ - -_analyze() - -_extract_nodes(node, top_level_nodes, lines) - -_extract_relationships(node, top_level_nodes) - -_get_class_modifiers(class_node) set - -_is_primitive_type(type_name) bool - -_find_variable_type(node, variable_name, top_level_nodes) str - -_find_containing_class(node, top_level_nodes) str - -_find_containing_method(node) str - -_get_component_id(name, parent_class) str - } - - class Node { - <> - id: str - name: str - component_type: str - file_path: str - relative_path: str - source_code: str - start_line: int - end_line: int - node_type: str - class_name: str - display_name: str - component_id: str - language: str - qualified_name: str - } - - class CallRelationship { - <> - caller: str - callee: str - call_line: int - is_resolved: bool - } - - class is_external_symbol { - <> - +is_external_symbol(language, symbol) bool - } - - TreeSitterJavaAnalyzer --> Node : creates - TreeSitterJavaAnalyzer --> CallRelationship : creates - TreeSitterJavaAnalyzer --> is_external_symbol : uses for JDK filtering - TreeSitterKotlinAnalyzer --> Node : creates - TreeSitterKotlinAnalyzer --> CallRelationship : creates -``` - -See [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) for the full `Node` and `CallRelationship` model definitions used throughout all language analyzers. - ---- - -## `TreeSitterJavaAnalyzer` (java.py) - -### Purpose - -Parses a single `.java` file using the `tree_sitter_java` grammar and extracts: -- **Classes** (`class_declaration`), further distinguished as `class` vs `abstract class` via modifier inspection -- **Interfaces** (`interface_declaration`) -- **Enums** (`enum_declaration`) -- **Records** (`record_declaration`) -- **Annotations** (`annotation_type_declaration`) -- **Methods** (`method_declaration`), qualified with their containing type as `ClassName.methodName` - -It records relationships for: -1. **Inheritance** β€” `class X extends Y` (`superclass` clause) -2. **Interface implementation** β€” `class/enum/record X implements Y, Z` (`super_interfaces` clause) -3. **Field type usage** β€” a field's declared type referencing another project type -4. **Method calls** β€” both bare calls (`foo()`) and calls on a receiver (`obj.foo()`), with receiver-type inference -5. **Object creation** β€” `new SomeType(...)` - -### Construction & Entry Point - -```python -TreeSitterJavaAnalyzer(file_path, content, repo_path=None) -``` -On construction, `__init__` immediately extracts the package name and import table, then runs `_analyze()`, populating `self.nodes` and `self.call_relationships`. The module-level convenience function: - -```python -analyze_java_file(file_path, content, repo_path=None) -> (List[Node], List[CallRelationship]) -``` -is the entry point used by `CallGraphAnalyzer._analyze_java_file`. - -### Package & Import Awareness - -Unlike the C/C++ analyzers, Java's ID scheme must account for a real module/namespace system. On construction the analyzer: - -1. **`_extract_package_name()`** β€” regex-matches the `package a.b.c;` statement (if any). -2. **`_extract_imports()`** β€” regex-scans every `import [static] a.b.C[.*];` statement, building: - - `import_map: dict[str, str]` β€” simple name β†’ fully-qualified name (e.g. `{"List": "java.util.List"}`), including static imports (`{"checkNotNull": "com.google.common.base.Preconditions.checkNotNull"}`). - - `wildcard_imports: list[str]` β€” package prefixes from `import a.b.*;` statements, used only as a fallback signal for JDK-package detection (a project's own wildcard imports fall through to normal resolution). - -These two structures power the "qualify a bare type/member name" logic in `_resolve_java_type` / `_resolve_java_member`, described below. - -### ID Scheme - -- **`component_id`** (via `_get_component_id`): `"::"`, where `` for a method is already `ClassName.methodName` (nested classes are **not** further nested in the component_id path β€” only `qualified_name` reflects full nesting). -- **`qualified_name`** (via `_qualified_type_name` / `_qualified_member_name`): the fully package-and-outer-class-qualified name, e.g. `com.example.Outer.Inner.method`, built by walking `_find_containing_type_names` (all enclosing class/interface/enum/record/annotation declarations) and prefixing the file's `package_name`. - -This dual scheme means `component_id` is used for the graph key (matching the `::` convention shared by all analyzers), while `qualified_name` is the semantically precise, package-qualified name used to resolve cross-references that mention the fully-qualified or partially-qualified form. - -### Processing Flow - -```mermaid -flowchart TD - A[Source content] --> PKG["_extract_package_name()"] - A --> IMP["_extract_imports()
import_map + wildcard_imports"] - PKG --> B[tree_sitter_java parser] - IMP --> B - B --> C[Root AST node] - C --> D["_extract_nodes(root)"] - D --> D1[Recursive traversal] - D1 --> D2{Node type?} - D2 -->|class_declaration| E1["'class'/'abstract class' Node"] - D2 -->|interface_declaration| E2["'interface' Node"] - D2 -->|enum_declaration| E3["'enum' Node"] - D2 -->|record_declaration| E4["'record' Node"] - D2 -->|annotation_type_declaration| E5["'annotation' Node"] - D2 -->|method_declaration| E6["'method' Node
qualified_name via containing types"] - E1 & E2 & E3 & E4 & E5 & E6 --> F["top_level_nodes map
(keyed by name, component_id, qualified_name, simple qualified suffix)"] - C --> G["_extract_relationships(root, top_level_nodes)"] - G --> G1{Node type?} - G1 -->|superclass| H1[Resolve base class via _resolve_java_type
Emit unresolved CallRelationship] - G1 -->|super_interfaces| H2[Resolve interface's
Emit unresolved CallRelationship per interface] - G1 -->|field_declaration| H3[Resolve field type
Emit unresolved CallRelationship] - G1 -->|method_invocation| H4["Infer receiver type
_resolve_java_member
Emit unresolved CallRelationship"] - G1 -->|object_creation_expression| H5[Resolve created type
Emit unresolved CallRelationship] - H1 & H2 & H3 & H4 & H5 --> I[self.call_relationships] - F --> J[self.nodes] -``` - -### Type & Member Resolution - -The core resolution logic lives in two cooperating methods: - -```mermaid -flowchart TD - subgraph resolve_type["_resolve_java_type(type_name, context_node, top_level_nodes)"] - T0[Strip generics via _simple_type_name] --> T1{Already dotted?} - T1 -->|yes| T2[Return as-is] - T1 -->|no| T3{In import_map?} - T3 -->|yes| T4[Return imported FQN] - T3 -->|no| T5["Walk containing_types outward:
try package.Outer.Inner.Type"] - T5 -->|match in top_level_nodes| T6[Return nested-qualified candidate] - T5 -->|no match| T7{package_name set?} - T7 -->|yes| T8[Return package.Type] - T7 -->|no| T9[Return bare Type] - end - - subgraph resolve_member["_resolve_java_member(member_name, context_node, top_level_nodes, target_type)"] - M0{target_type given?} -->|yes| M1["_resolve_java_type target β†’ qualified_type.member"] - M1 --> M2{candidate in top_level_nodes?} - M2 -->|yes| M3[Return candidate] - M2 -->|no| M4["Try simple_type.member fallback"] - M0 -->|no, bare call| M5[Walk containing_types outward:
try Type.member for each enclosing type] - M5 -->|found| M6[Return candidate] - M5 -->|not found| M7{member_name in import_map?
static import} - M7 -->|yes| M8[Return imported FQN] - M7 -->|no| M9[Return package.member] - end -``` - -### JDK / External-Type Filtering - -`_is_primitive_type` and `_skip_type` decide, at relationship-extraction time, whether a referenced type name can *ever* be a project component β€” avoiding emitting noisy edges to JDK/runtime types or generic type parameters: - -- **Java primitives / keywords**: `boolean, byte, char, double, float, int, long, short, void, var` β€” always skipped. -- **Generic type parameters in scope** (`_find_type_parameters`): walks up through enclosing `class_declaration` / `interface_declaration` / `record_declaration` / `method_declaration` nodes collecting `type_parameters` (e.g. the `K`, `V` of `class Cache`), so a field of type `K` isn't misclassified as an external or unresolved project reference. -- **JDK/runtime detection**: the simple type name is resolved through `import_map` (or, for wildcard imports, checked as `wildcard.SimpleName`) to its best-guess fully-qualified form, which is then passed to the shared [`is_external_symbol("java", qualified)`](Dependency_Analyzer_Core.md) classifier. This generalizes JDK filtering to *any* repository without hardcoding a type list β€” only the `java./javax./jdk./sun.` namespace-prefix rule and the curated `java.lang` set (which has no import statement to consult) are hardcoded. - -```mermaid -flowchart LR - TypeName[type_name] --> Simple["_simple_type_name
strip generics"] - Simple --> Prim{in primitives set?} - Prim -->|yes| Skip[Skip: not a component] - Prim -->|no| Lookup["import_map.get(simple)"] - Lookup -->|found| Qualified[qualified FQN] - Lookup -->|not found| Wild{matches a wildcard
import package?} - Wild -->|yes, is_external_symbol true| Skip - Wild -->|no| Qualified2[qualified = simple] - Qualified --> ExtCheck["is_external_symbol java qualified"] - Qualified2 --> ExtCheck - ExtCheck -->|True| Skip - ExtCheck -->|False| Keep[Treat as potential project type
emit CallRelationship] -``` - -### Method-Call Receiver-Type Inference - -For `method_invocation` nodes (`obj.method()` or bare `method()`), the analyzer must guess what `obj`'s static type is in order to resolve `method` to a specific class member: - -1. If the receiver identifier starts with an uppercase letter and is itself a known top-level type name β†’ treat as a **static call** on that type. -2. Otherwise, call `_find_variable_type` β€” scans the enclosing method/constructor body (`local_variable_declaration`s, recursively through nested `block`s) and its parameter list, falling back to the enclosing class's `field_declaration`s, to find where `obj` was declared and what type annotation it carries. -3. If no declaration is found but the receiver is CamelCase (and not `ALL_CAPS`, which reads as a constant) β†’ assume it's still a type reference (e.g. an imported class used for a static call CodeWiki didn't track as a local variable). -4. Bare calls with no receiver either resolve against enclosing types (walking outward through nested classes) or, if the callee corresponds to a static import, resolve directly via `import_map`. - -A special guard: if the finally-resolved callee isn't a known project component and the method name is one of the well-known `Object` methods (`JAVA_OBJECT_METHODS`, e.g. `toString`, `equals`, `hashCode`), the call is dropped entirely rather than emitted as an unresolved edge β€” since an inherited `Object` method with no local override is never a meaningful project-internal edge to surface. - ---- - -## `TreeSitterKotlinAnalyzer` (kotlin.py) - -### Purpose - -Parses a single `.kt`/`.kts` file using the `tree_sitter_kotlin` grammar and extracts: -- **Classes** (`class_declaration`), refined by modifier inspection into `class`, `abstract class`, `data class`, `enum class`, or `annotation class` -- **Interfaces** (`class_declaration` containing an `interface` child token) -- **Objects** (`object_declaration`) β€” Kotlin's singleton declaration form -- **Functions and Methods** (`function_declaration`) β€” qualified as `ClassName.methodName` when nested in a class/object, otherwise a free `function` - -It records relationships for: -1. **Inheritance / interface implementation** via `delegation_specifiers` (Kotlin's unified `: Base(), Interface1, Interface2` syntax, including delegated constructor invocations) -2. **Property type usage** (`property_declaration` with an explicit `user_type` annotation) -3. **Constructor parameter type usage** (`class_parameter` in a primary constructor) -4. **Function/method calls** (`call_expression`), including receiver-qualified calls via `navigation_expression` (`obj.method()`) - -Unlike the Java analyzer, Kotlin's analyzer does **not** build a package/import table β€” Kotlin source commonly omits explicit imports for same-package types, and the analyzer instead relies on simple-name matching against `top_level_nodes` plus a curated primitive/built-in filter. - -### Construction & Entry Point - -```python -TreeSitterKotlinAnalyzer(file_path, content, repo_path=None) -analyze_kotlin_file(file_path, content, repo_path=None) -> (List[Node], List[CallRelationship]) -``` -`_analyze()` wraps parsing in a `try/except`, logging and continuing gracefully (producing empty `nodes`/`call_relationships`) if the Kotlin grammar cannot parse the file β€” a defensive measure the Java analyzer does not need since Java's grammar is generally more forgiving of this codebase's inputs. - -### ID Scheme - -- **`component_id`** (`_get_component_id`): `"::"`, where a method's `` is already `ClassName.methodName` (mirrors the Java analyzer's flat, non-nested scheme). -- Unlike Java, Kotlin `Node` objects do **not** populate `qualified_name` or `language` β€” relationship targets are simple/qualified-simple names, left for `CallGraphAnalyzer` to resolve against the repository-wide `component_id`/name indexes. - -### Class Modifier Refinement - -`_get_class_modifiers` walks a `class_declaration`'s `modifiers` child, collecting inner tokens from `class_modifier` / `inheritance_modifier` / `visibility_modifier` groups (e.g. `abstract`, `data`, `enum`, `annotation`). `_extract_nodes` uses this set β€” together with a direct check for an `interface` child token β€” to assign the most specific `node_type`: - -```mermaid -flowchart TD - CD[class_declaration] --> HasIface{has 'interface' child?} - HasIface -->|yes| Iface["'interface'"] - HasIface -->|no| Mods["_get_class_modifiers"] - Mods --> M1{'abstract' in modifiers?} - M1 -->|yes| Abs["'abstract class'"] - M1 -->|no| M2{'data' in modifiers?} - M2 -->|yes| Data["'data class'"] - M2 -->|no| M3{'enum' in modifiers?} - M3 -->|yes| Enum["'enum class'"] - M3 -->|no| M4{'annotation' in modifiers?} - M4 -->|yes| Anno["'annotation class'"] - M4 -->|no| Plain["'class'"] -``` - -### Processing Flow - -```mermaid -flowchart TD - A[Source content] --> B["tree_sitter_kotlin parser
wrapped in try/except"] - B --> C[Root AST node] - C --> D["_extract_nodes(root)"] - D --> D1{Node type?} - D1 -->|class_declaration| E1["class/interface/abstract/data/enum/annotation Node"] - D1 -->|object_declaration| E2["'object' Node"] - D1 -->|function_declaration| E3["'method' or 'function' Node
+ docstring from preceding comment sibling"] - E1 & E2 & E3 --> F[top_level_nodes map
keyed by simple name] - C --> G["_extract_relationships(root, top_level_nodes)"] - G --> G1{Node type?} - G1 -->|class_declaration| H1["delegation_specifiers to base/interface CallRelationship's"] - G1 -->|property_declaration| H2["user_type field to CallRelationship"] - G1 -->|class_parameter| H3["constructor param type to CallRelationship"] - G1 -->|call_expression| H4["identifier or navigation_expression
receiver-type inference to CallRelationship"] - H1 & H2 & H3 & H4 --> I[self.call_relationships] - F --> J[self.nodes] -``` - -### Call-Expression Resolution - -`call_expression` handling branches on the shape of the invoked target: - -```mermaid -flowchart TD - CE[call_expression] --> Target{target: identifier
or navigation_expression?} - Target -->|"identifier, e.g. Foo()"| Simple{First letter uppercase?} - Simple -->|yes| ClassCtor["Treat as class instantiation
CallRelationship caller to component_id Name"] - Simple -->|"no, e.g. topLevelFn()"| FreeFn["CallRelationship caller to name
left for CallGraphAnalyzer to resolve"] - - Target -->|"navigation_expression, e.g. obj.method()"| NavParse["Collect identifiers in expression:
2+ identifiers to object, method
1 identifier + nested nav via _get_root_identifier"] - NavParse --> HasObj{object + method both found?} - HasObj -->|yes| TypeGuess["object_name in top_level_nodes?
else _find_variable_type"] - TypeGuess -->|resolved, non-primitive| Rel1["CallRelationship caller to component_id target_type"] - HasObj -->|no, method only| Rel2["CallRelationship caller to method_name"] -``` - -`_find_variable_type` mirrors the Java analyzer's scope-walking strategy, but adapted to Kotlin constructs: -1. **Function parameters** (`function_value_parameters` β†’ `parameter` nodes with a `user_type`/`nullable_type` annotation). -2. **Local variable declarations** inside the function body (`_search_variable_declaration`, recursing through nested `block`s) β€” including a light type-inference fallback: if a `property_declaration` has no explicit type but its initializer is a `call_expression` to an uppercase-named function, that name is inferred as the type (covers `val x = Foo()` constructor-call idiom). -3. **Primary constructor parameters** (`primary_constructor` β†’ `class_parameters` β†’ `class_parameter`). -4. **Class-body properties** (`class_body`/`enum_class_body` β†’ `property_declaration`). - -### Built-in Type Filtering - -`_is_primitive_type` uses a curated, hardcoded set of Kotlin primitive and standard-collection type names (`Boolean, Byte, ..., String, Unit, Nothing, Any, List, Set, Map, MutableList, ..., Array, IntArray, ..., Pair, Triple`) to suppress edges to obvious built-ins. This is simpler than the Java analyzer's import-aware `is_external_symbol` approach β€” Kotlin's analyzer does not currently attempt to resolve arbitrary `kotlin.*`/`kotlinx.*` stdlib types beyond this fixed list, so uncommon stdlib types may still produce unresolved edges that `CallGraphAnalyzer`'s downstream filtering must catch. - ---- - -## Java vs. Kotlin: Design Comparison - -| Aspect | `TreeSitterJavaAnalyzer` | `TreeSitterKotlinAnalyzer` | -|---|---|---| -| Package/import table | Yes β€” `package_name`, `import_map`, `wildcard_imports` parsed via regex | No β€” resolution is purely structural/local | -| Type qualification | `qualified_name` field set on every `Node`, package + outer-class qualified | Not set (`None`) β€” relies on simple names | -| External-symbol filtering | Delegates to shared `is_external_symbol("java", ...)` after import-based qualification | Curated fixed primitive/collection set only | -| Generic type parameters | Explicitly tracked and excluded (`_find_type_parameters`) | Not explicitly tracked | -| Inheritance/implements syntax | Separate `superclass` and `super_interfaces` clauses | Unified `delegation_specifiers` (Kotlin has one syntax for both) | -| Class variants | `class`, `abstract class`, `interface`, `enum`, `record`, `annotation` | `class`, `abstract class`, `data class`, `enum class`, `annotation class`, `interface`, `object` | -| Parse-failure handling | No explicit guard (grammar assumed to succeed) | Wrapped in `try/except`, logs and continues with empty results | -| Docstrings | Not captured (`has_docstring=False` always) | Captured from an immediately preceding `line_comment`/`block_comment` sibling | - -Both analyzers, despite these differences, converge on the same `Node`/`CallRelationship` output contract described in [C-Family_Tree-sitter_Analyzers](C-Family_Tree-sitter_Analyzers.md) and [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md), which is what allows `CallGraphAnalyzer` to treat all five C-family analyzers uniformly during cross-file resolution. - ---- - -## Integration Points - -- **Invocation**: `CallGraphAnalyzer._analyze_java_file` / `_analyze_kotlin_file` (see [Dependency_Analysis_Service](Dependency_Analysis_Service.md)) call `analyze_java_file` / `analyze_kotlin_file` per discovered source file (file discovery itself is handled by `RepoAnalyzer`). -- **Output consumption**: the returned `(nodes, call_relationships)` tuples are merged with every other language analyzer's output into `CallGraphAnalyzer`'s repository-wide indexes, where unresolved (`is_resolved=False`) edges are matched against known component IDs/qualified names, and any edge that still can't be matched is checked against `_is_external_callee` before being classified as either a real cross-file dependency or discarded as external/unknown. -- **Downstream**: resolved `Node`/`CallRelationship` data feeds [`DependencyParser`](Dependency_Analyzer_Core.md) and [`DependencyGraphBuilder`](Dependency_Analyzer_Core.md), which produce the dependency graph consumed by [documentation generation](Backend_LLM_&_Documentation_Services_documentation_generator.md). -- **Shared utility dependency**: `TreeSitterJavaAnalyzer` imports `JAVA_OBJECT_METHODS` and `is_external_symbol` from `codewiki.src.be.dependency_analyzer.utils.external_symbols` β€” the same module the C/C++ analyzers use for their own language-specific external-symbol sets (see [C-Family_Tree-sitter_Analyzers_C_Cpp](C-Family_Tree-sitter_Analyzers_C_Cpp.md) for that module's parallel usage). diff --git a/docs/CLI.md b/docs/CLI.md deleted file mode 100644 index 51438ad2..00000000 --- a/docs/CLI.md +++ /dev/null @@ -1,94 +0,0 @@ -# CLI Module - -## Introduction - -The **CLI module** (`codewiki/cli/`) is the command-line entry point for CodeWiki. It provides the user-facing surface that developers interact with directly from a terminal to configure credentials, run repository analysis, generate documentation, produce a static HTML viewer, and optionally commit the results to a git branch. - -The CLI module itself does not implement dependency analysis or LLM orchestration β€” it is a thin, user-experience-focused **adapter layer** that: - -- Persists and validates user configuration (LLM provider, models, tokens, credentials) β€” see [CLI_Configuration](CLI_Configuration.md) -- Drives the backend documentation pipeline and tracks job state β€” see [CLI_Documentation_Generation](CLI_Documentation_Generation.md) -- Interacts with the local git repository (branch creation, commits, remote/PR URL detection) β€” see [CLI_Git_Integration](CLI_Git_Integration.md) -- Renders a self-contained static HTML viewer for GitHub Pages β€” see [CLI_HTML_Viewer](CLI_HTML_Viewer.md) -- Provides shared terminal UX primitives (colored logging, staged progress bars) β€” see [CLI_Utilities](CLI_Utilities.md) - -For the actual dependency-graph analysis and LLM-driven documentation generation logic invoked by this module, see [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) and [Dependency_Analysis_Service](Dependency_Analysis_Service.md). Shared runtime configuration primitives (`Config`, `FileManager`) used to bridge CLI settings into the backend are documented in [Core_Config_&_Utils](Core_Config_&_Utils.md). - -## Architecture Overview - -The CLI module sits between the terminal user and the backend generation pipeline. It translates persistent user preferences and command-line flags into a backend `Config` object, runs the pipeline with progress feedback, and optionally wraps the run with git operations and static-site generation. - -```mermaid -graph TB - User["Terminal User"] -->|"codewiki configure / generate"| CLIEntry["CLI Commands\n(click-based entry points)"] - - subgraph CLI["CLI Module"] - CLIEntry --> ConfigMgr["ConfigManager\n(CLI_Configuration)"] - CLIEntry --> DocGenAdapter["CLIDocumentationGenerator\n(CLI_Documentation_Generation)"] - CLIEntry --> GitMgr["GitManager\n(CLI_Git_Integration)"] - DocGenAdapter --> HTMLGen["HTMLGenerator\n(CLI_HTML_Viewer)"] - DocGenAdapter --> ProgressUtils["ProgressTracker / CLILogger\n(CLI_Utilities)"] - ConfigMgr --> ConfigModel["Configuration / AgentInstructions\n(CLI_Configuration)"] - DocGenAdapter --> JobModel["DocumentationJob\n(CLI_Documentation_Generation)"] - end - - ConfigMgr -->|"keyring / ~/.codewiki"| OSStore["OS Keychain /\nFallback JSON files"] - DocGenAdapter -->|"BackendConfig.from_cli(...)"| BackendCfg["Config\n(Core_Config_&_Utils)"] - DocGenAdapter -->|"drives"| BackendGen["DocumentationGenerator\n(Backend_LLM_&_Documentation_Services)"] - BackendGen --> DepAnalysis["AnalysisService / DependencyGraphBuilder\n(Dependency_Analysis_Service)"] - GitMgr -->|"reads/writes"| LocalRepo["Local Git Repository"] - - style CLI fill:#eef,stroke:#336 -``` - -### Request Flow: `codewiki generate` - -```mermaid -sequenceDiagram - participant U as User - participant CLI as CLI Command - participant CM as ConfigManager - participant GM as GitManager - participant Adapter as CLIDocumentationGenerator - participant BE as Backend DocumentationGenerator - participant HG as HTMLGenerator - - U->>CLI: codewiki generate --repo . --create-branch - CLI->>CM: load config and API key - CM-->>CLI: Configuration plus API key - CLI->>GM: check clean working directory - GM-->>CLI: status - opt create-branch flag set - CLI->>GM: create documentation branch - end - CLI->>Adapter: instantiate CLIDocumentationGenerator and call generate - Adapter->>Adapter: set CLI context, build BackendConfig - Adapter->>BE: instantiate DocumentationGenerator - BE-->>Adapter: components and leaf_nodes dependency graph - Adapter->>BE: cluster_modules then generate_module_documentation - BE-->>Adapter: generated md files and metadata - opt github-pages flag set - Adapter->>HG: generate index.html - end - Adapter-->>CLI: DocumentationJob completed or failed - opt create-branch flag set - CLI->>GM: commit_documentation for docs path - end - CLI-->>U: success summary and PR URL -``` - -## Sub-modules - -| Sub-module | Responsibility | -|---|---| -| [CLI_Configuration](CLI_Configuration.md) | Persistent user settings (`Configuration`, `AgentInstructions`) and secure credential storage (`ConfigManager`) using OS keyring with file fallback. | -| [CLI_Documentation_Generation](CLI_Documentation_Generation.md) | `CLIDocumentationGenerator` adapter that drives the backend pipeline stage-by-stage, and the `DocumentationJob`/`JobStatistics`/`LLMConfig`/`GenerationOptions` job-tracking models. | -| [CLI_Git_Integration](CLI_Git_Integration.md) | `GitManager` for working-directory checks, documentation branch creation, commits, and GitHub remote/PR URL derivation. | -| [CLI_HTML_Viewer](CLI_HTML_Viewer.md) | `HTMLGenerator` that renders a static, self-contained `index.html` documentation viewer suitable for GitHub Pages. | -| [CLI_Utilities](CLI_Utilities.md) | Shared terminal UX helpers: `CLILogger` (colored console logging) and `ProgressTracker`/`ModuleProgressBar` (staged progress and ETA reporting). | - -## How the CLI Relates to the Rest of the System - -- The CLI is one of two primary front-ends to the documentation pipeline; the other is the [Frontend_Web_App](Frontend_Web_App.md), which exposes the same backend capabilities via a web UI and background jobs, and the [MCP_Session_Management](MCP_Session_Management.md) module, which exposes it to MCP-compatible AI assistants. -- All three front-ends ultimately construct a `codewiki.src.config.Config` object (see [Core_Config_&_Utils](Core_Config_&_Utils.md)) and hand off to [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) for LLM orchestration, which in turn depends on [Dependency_Analysis_Service](Dependency_Analysis_Service.md) and the [Language_Analyzers](Language_Analyzers.md) for source-code parsing, and [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) for the underlying graph model. -- Backend agentic tool calls (file editing, dependency lookups) used during documentation generation are defined in [Backend_Agent_Tools](Backend_Agent_Tools.md). diff --git a/docs/CLI_Configuration.md b/docs/CLI_Configuration.md deleted file mode 100644 index da051e7e..00000000 --- a/docs/CLI_Configuration.md +++ /dev/null @@ -1,227 +0,0 @@ -# CLI Configuration - -## Introduction - -The **CLI Configuration** module is responsible for managing all persistent, user-level settings for the CodeWiki command-line interface. It defines the data models that represent a user's LLM provider settings and documentation preferences (`Configuration`, `AgentInstructions`), and provides the `ConfigManager` service that reads, writes, validates, and securely stores these settings on disk. - -This module acts as the bridge between what a user configures once (via `codewiki config` commands or an interactive setup wizard) and the runtime configuration (`Config`, see [Core_Config_&_Utils](Core_Config_&_Utils.md)) consumed by the documentation generation pipeline for each individual job. It is a foundational dependency for [CLI_Documentation_Generation](CLI_Documentation_Generation.md), which uses the loaded `Configuration` to build backend jobs. - ---- - -## Purpose & Core Functionality - -The module has three main responsibilities: - -1. **Data Modeling** β€” Define the shape of persisted configuration (`Configuration`) and optional documentation-customization instructions (`AgentInstructions`). -2. **Secure Persistence** β€” Read/write configuration to `~/.codewiki/config.json`, and securely store the sensitive LLM API key using the OS keyring (with an encrypted-permission file fallback for headless/keyring-less environments). -3. **Validation & Translation** β€” Validate configuration completeness/correctness per LLM provider type, and translate the CLI-level `Configuration` into the backend's `Config` object (`to_backend_config`) used by the actual documentation generation engine. - ---- - -## Architecture Overview - -```mermaid -graph TB - subgraph "CLI_Configuration" - CM[ConfigManager] - CFG[Configuration] - AI[AgentInstructions] - end - - subgraph "Storage" - JSON["~/.codewiki/config.json"] - KEYRING["OS Keyring
(macOS Keychain / Windows Credential Manager / Linux Secret Service)"] - CREDFILE["~/.codewiki/credentials.json
(fallback, chmod 600)"] - end - - subgraph "CLI_Utilities helpers" - ERR[errors.ConfigurationError] - FS[fs.ensure_directory / safe_read / safe_write] - VAL[validation.validate_url / validate_model_name / validate_api_key] - end - - subgraph "Downstream Consumers" - BACKEND_CFG["Config
(Core_Config_&_Utils)"] - DOCGEN["CLIDocumentationGenerator
(CLI_Documentation_Generation)"] - BACKEND["LLMBackend / is_caw_provider
(Backend_LLM_&_Documentation_Services)"] - end - - CM -->|reads/writes| JSON - CM -->|reads/writes| KEYRING - CM -->|fallback reads/writes| CREDFILE - CM --> CFG - CFG --> AI - CM --> FS - CM --> ERR - CFG --> VAL - CFG -->|"is_caw_provider check"| BACKEND - CFG -->|"to_backend_config()"| BACKEND_CFG - DOCGEN -->|uses| CM - DOCGEN -->|uses| CFG -``` - ---- - -## Component Reference - -### `Configuration` (codewiki/cli/models/config.py) - -A dataclass representing the full set of persistent settings a user configures once. Fields cover: - -- **LLM connection**: `base_url`, `main_model`, `cluster_model`, `fallback_model`, `provider` -- **Provider-specific extras**: `aws_region` (Bedrock), `api_version` / `azure_deployment` (Azure OpenAI) -- **Generation tuning**: `max_tokens`, `max_token_per_module`, `max_token_per_leaf_module`, `max_depth`, `prompt_caching`, `use_gitignore` -- **Output**: `default_output` -- **Customization**: `agent_instructions` (an embedded `AgentInstructions` instance) - -Key behaviors: - -| Method | Purpose | -|---|---| -| `validate()` | Raises `ConfigurationError` if required fields are missing/invalid. Delegates to `is_caw_provider()` (see [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md)) to determine whether subscription-mode providers (`claude-code`, `codex`) skip URL/cluster/fallback-model checks, since they authenticate via CLI OAuth instead of an API key. | -| `is_complete()` | Lightweight completeness check (no exception), used by `ConfigManager.is_configured()`. Same caw-provider short-circuit as `validate()`. | -| `to_dict()` / `from_dict()` | Serialize/deserialize to/from the JSON structure persisted on disk. Omits empty `agent_instructions`. | -| `to_backend_config()` | **The critical bridge method.** Converts this persistent `Configuration` (plus a target `repo_path`, `output_dir`, resolved `api_key`, and optional per-run `runtime_instructions`) into a `Config` instance from `codewiki/src/config.py` (see [Core_Config_&_Utils](Core_Config_&_Utils.md)) via `Config.from_cli(...)`. Runtime instructions override persistent `agent_instructions` field-by-field. | - -### `AgentInstructions` (codewiki/cli/models/config.py) - -A dataclass capturing optional customization for the documentation agent: - -- `include_patterns` / `exclude_patterns` β€” file filtering globs -- `focus_modules` β€” modules to document in more detail -- `doc_type` β€” one of `api`, `architecture`, `user-guide`, `developer`, or free-form -- `custom_instructions` β€” free-form text appended to the agent prompt - -`get_prompt_addition()` renders these into natural-language prompt text consumed by the backend documentation agents (see [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) and [Dependency_Analysis_Service](Dependency_Analysis_Service.md) for where component/module context is supplied alongside this prompt). - -`is_empty()` lets callers (e.g. `Configuration.to_backend_config`) decide whether to keep the persistent instructions or override them with per-invocation runtime instructions. - -### `ConfigManager` (codewiki/cli/config_manager.py) - -Stateful service class that owns the lifecycle of a `Configuration` object plus the associated secret API key. - -**Storage locations:** - -| Data | Primary Store | Fallback Store | -|---|---|---| -| API key | OS Keyring (service=`codewiki`, account=`api_key`) | `~/.codewiki/credentials.json` (mode `0600`, plaintext) | -| All other settings | `~/.codewiki/config.json` | β€” | - -Fallback is triggered automatically when: -- `CODEWIKI_NO_KEYRING` environment variable is set to `1`/`true`/`yes`, or -- The system keyring raises a `KeyringError` (or any other exception) at check-time or at runtime (e.g. headless containers, RHEL without Secret Service). - -**Public API:** - -| Method | Description | -|---|---| -| `load()` | Loads `config.json` into `self._config`, then resolves the API key from keyring or fallback file. Returns `False` if no config file exists yet. | -| `save(**fields)` | Upserts any provided fields into the in-memory `Configuration` (loading existing config first if needed, or creating sensible defaults), validates once enough fields are present (provider-aware), persists the API key (keyring or file fallback with automatic downgrade + warning on keyring failure), then writes `config.json`. | -| `get_api_key()` | Lazily resolves and caches the API key (keyring first, then file). | -| `get_config()` | Returns the currently loaded/saved `Configuration`, or `None`. | -| `is_configured()` | `True` if a `Configuration` exists, is complete (`Configuration.is_complete()`), and β€” for non-caw providers β€” an API key is present. | -| `delete_api_key()` | Removes the key from both keyring and fallback file. | -| `clear()` | Full reset: deletes API key and `config.json`, clears in-memory state. | -| `keyring_available` (property) | Whether the OS keyring backend is usable in the current environment. | -| `config_file_path` (property) | Path to `~/.codewiki/config.json`. | - ---- - -## Data Flow: Saving Configuration - -```mermaid -sequenceDiagram - participant User as CLI Command
(e.g. `codewiki config set`) - participant CM as ConfigManager - participant Cfg as Configuration - participant KR as OS Keyring - participant File as credentials.json / config.json - - User->>CM: save(api_key=..., base_url=..., main_model=..., ...) - alt No config loaded yet - CM->>File: load() existing config.json (if any) - CM->>Cfg: create default Configuration if none exists - end - CM->>Cfg: update provided fields - CM->>Cfg: validate() (provider-aware, via is_caw_provider) - alt api_key provided - CM->>KR: keyring.set_password(...) - alt Keyring fails - CM->>File: write credentials.json (chmod 600) - CM-->>User: log warning (plaintext fallback) - end - end - CM->>File: write config.json (version + Configuration.to_dict()) - CM-->>User: success -``` - ---- - -## Data Flow: Resolving Configuration for a Documentation Job - -```mermaid -sequenceDiagram - participant Job as CLI Job Runner
(CLI_Documentation_Generation) - participant CM as ConfigManager - participant Cfg as Configuration - participant Backend as Config
(Core_Config_&_Utils) - participant Gen as DocumentationGenerator
(Backend_LLM_&_Documentation_Services) - - Job->>CM: load() - CM-->>Job: True/False - Job->>CM: is_configured() - CM-->>Job: True (proceed) / False (prompt user to run setup) - Job->>CM: get_config() - CM-->>Job: Configuration instance - Job->>CM: get_api_key() - CM-->>Job: api_key (or None for caw providers) - Job->>Cfg: to_backend_config(repo_path, output_dir, api_key, runtime_instructions) - Cfg->>Backend: Config.from_cli(...) - Backend-->>Job: Config instance - Job->>Gen: run documentation generation with Config -``` - ---- - -## Provider-Aware Validation Logic - -`Configuration` supports multiple LLM providers, some of which are "subscription-mode" (caw) providers that authenticate through an external CLI's OAuth flow rather than an API key + base URL. `is_caw_provider()` (defined in [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md), `codewiki/src/be/backend.py`) determines this branching for `claude-code` and `codex` providers. - -```mermaid -flowchart TD - Start([validate / is_complete]) --> Check{"is_caw_provider(provider)?"} - Check -->|Yes: claude-code, codex| CawPath["Only require main_model.
Skip base_url / cluster_model /
fallback_model / API key checks"] - Check -->|No: openai-compatible,
anthropic, bedrock,
azure-openai, ...| ApiPath["Require base_url, main_model,
cluster_model, fallback_model,
and API key"] - CawPath --> Result([Valid / Complete]) - ApiPath --> Result -``` - -This same branching is used in both `ConfigManager.save()` (to decide when enough fields exist to trigger validation) and `ConfigManager.is_configured()` (to decide whether an API key is required). - ---- - -## Dependencies - -| Dependency | Module | Usage | -|---|---|---| -| `ConfigurationError`, `FileSystemError` | [CLI_Utilities](CLI_Utilities.md) (`codewiki/cli/utils/errors.py`) | Raised on invalid config or filesystem failures | -| `ensure_directory`, `safe_read`, `safe_write` | [CLI_Utilities](CLI_Utilities.md) (`codewiki/cli/utils/fs.py`) | Safe filesystem I/O for config/credentials files | -| `validate_url`, `validate_model_name`, `validate_api_key` | [CLI_Utilities](CLI_Utilities.md) (`codewiki/cli/utils/validation.py`) | Field-level validation used inside `Configuration.validate()` | -| `is_caw_provider` | [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) (`codewiki/src/be/backend.py`) | Determines subscription-mode vs. API-key-mode provider behavior | -| `Config.from_cli` | [Core_Config_&_Utils](Core_Config_&_Utils.md) (`codewiki/src/config.py`) | Target type produced by `Configuration.to_backend_config()` | -| `keyring` (third-party) | β€” | OS-native secret storage backend | - -## Consumers - -| Consumer | Module | Usage | -|---|---|---| -| `CLIDocumentationGenerator` | [CLI_Documentation_Generation](CLI_Documentation_Generation.md) | Loads `Configuration` via `ConfigManager`, resolves the API key, and calls `to_backend_config()` to construct the runtime `Config` for a `DocumentationJob` | -| CLI setup/config commands (`codewiki config ...`) | CLI entry points | Drive `ConfigManager.save()` / `.load()` / `.clear()` to manage user settings interactively | - ---- - -## Key Design Notes - -- **Security-first API key handling**: The module prefers OS-level secret storage and only falls back to a plaintext file with restrictive permissions (`0600`) when no keyring backend is available, always logging a warning in that case. -- **Separation of persistent vs. runtime config**: `Configuration` is user-level and long-lived; `Config` (backend) is job-specific and ephemeral, built fresh for every documentation run via `to_backend_config()`. This separation allows CLI defaults to be overridden per-invocation (e.g., different `repo_path`, `output_dir`, or one-off `AgentInstructions`) without mutating stored settings. -- **Progressive/partial validation**: `ConfigManager.save()` only invokes `Configuration.validate()` once enough fields are populated to make validation meaningful, allowing multi-step configuration workflows (e.g., an interactive wizard prompting for one field at a time) without premature failures. diff --git a/docs/CLI_Documentation_Generation.md b/docs/CLI_Documentation_Generation.md deleted file mode 100644 index c71b9ca0..00000000 --- a/docs/CLI_Documentation_Generation.md +++ /dev/null @@ -1,330 +0,0 @@ -# CLI Documentation Generation - -## Introduction - -The **CLI Documentation Generation** module is the orchestration layer that drives a single `codewiki generate` run from the command line. It bridges the user-facing CLI experience with the framework-agnostic backend documentation pipeline ([Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md)), adding CLI-specific concerns such as staged progress reporting, structured job tracking, colored logging, and optional HTML viewer generation. - -The module is composed of two main responsibilities: - -- **`CLIDocumentationGenerator`** (`codewiki/cli/adapters/doc_generator.py`) β€” an adapter that wraps the backend's `DocumentationGenerator` and `DependencyGraphBuilder`, exposing a single `generate()` entry point that runs the full pipeline (dependency analysis β†’ module clustering β†’ documentation generation β†’ optional HTML generation β†’ finalization) while emitting progress updates. -- **Job data models** (`codewiki/cli/models/job.py`) β€” `DocumentationJob`, `JobStatus`, `LLMConfig`, `GenerationOptions`, and `JobStatistics`, which together capture the full lifecycle and metadata of a documentation generation run in a serializable form (used for `metadata.json` and for reporting job outcomes back to the CLI/user). - -This module sits at the center of the CLI subsystem, consuming configuration from [CLI_Configuration](CLI_Configuration.md), progress/logging primitives from [CLI_Utilities](CLI_Utilities.md), optional HTML rendering from [CLI_HTML_Viewer](CLI_HTML_Viewer.md), and git metadata from [CLI_Git_Integration](CLI_Git_Integration.md) (commit id, branch, etc., typically supplied by the calling CLI command). Underneath, it delegates the actual dependency analysis and LLM-driven writing to the [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md), [Dependency_Analysis_Service](Dependency_Analysis_Service.md), and [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) modules. - ---- - -## Module Position in the System - -```mermaid -graph TB - subgraph CLI["CLI (Top-Level)"] - CFG["CLI_Configuration
ConfigManager, Configuration"] - GIT["CLI_Git_Integration
GitManager"] - HTML["CLI_HTML_Viewer
HTMLGenerator"] - UTIL["CLI_Utilities
ProgressTracker, CLILogger"] - DOCGEN["CLI_Documentation_Generation
(this module)"] - end - - subgraph BE["Backend Services"] - DG["Backend_LLM_&_Documentation_Services
DocumentationGenerator, LLMBackend"] - DAS["Dependency_Analysis_Service
AnalysisService, RepoAnalyzer"] - DAC["Dependency_Analyzer_Core
DependencyGraphBuilder"] - CFGCORE["Core_Config_&_Utils
Config, FileManager"] - end - - CFG -->|"LLM/agent config dict"| DOCGEN - GIT -->|"commit_id"| DOCGEN - UTIL -->|"ProgressTracker"| DOCGEN - DOCGEN -->|"optional generate_html"| HTML - DOCGEN -->|"builds BackendConfig via"| CFGCORE - DOCGEN -->|"instantiates & drives"| DG - DG --> DAC - DAC --> DAS -``` - ---- - -## Component Overview - -### `CLIDocumentationGenerator` - -`CLIDocumentationGenerator` is the CLI-side facade over the backend pipeline. It is instantiated once per `generate` invocation and is responsible for: - -1. **Bootstrapping job state** β€” creates a `DocumentationJob`, populates repository/output metadata, and stores an `LLMConfig` snapshot. -2. **Configuring backend logging** β€” attaches a `ColoredFormatter` (from [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)) to the `codewiki.src.be` logger tree, routing INFO-level logs to stdout in verbose mode or suppressing to WARNING+ on stderr otherwise, and disabling propagation to avoid duplicate output. -3. **Translating CLI config β†’ backend `Config`** β€” builds a `BackendConfig` (`codewiki.src.config.Config`, see [Core_Config_&_Utils](Core_Config_&_Utils.md)) via `Config.from_cli(...)`, forwarding LLM connection details, provider selection, token budgets, agent instructions, and gitignore/prompt-caching flags. -4. **Driving the 5-stage pipeline** with `ProgressTracker` (see [CLI_Utilities](CLI_Utilities.md)): - - Stage 1 β€” Dependency Analysis - - Stage 2 β€” Module Clustering - - Stage 3 β€” Documentation Generation - - Stage 4 β€” HTML Generation (optional) - - Stage 5 β€” Finalization -5. **Validating completeness** β€” after generation, calls `doc_generator.validate_generated_docs()` and raises `IncompleteGenerationError` if any expected module `.md` files are missing, preventing a "false success" (addresses silent failures from name collisions or failed sub-agents). -6. **Returning a completed/failed `DocumentationJob`** for the CLI command layer to render results or errors. - -#### Class Responsibilities Diagram - -```mermaid -classDiagram - class CLIDocumentationGenerator { - +Path repo_path - +Path output_dir - +Dict config - +bool verbose - +bool generate_html - +str commit_id - +ProgressTracker progress_tracker - +DocumentationJob job - +generate() DocumentationJob - -_configure_backend_logging() - -_run_backend_generation(backend_config) async - -_run_html_generation() - -_finalize_job() - } - - class DocumentationJob { - +str job_id - +str repository_path - +str repository_name - +str output_directory - +str commit_hash - +JobStatus status - +List~str~ files_generated - +int module_count - +LLMConfig llm_config - +JobStatistics statistics - +start() - +complete() - +fail(error_message) - +to_dict() Dict - +to_json() str - +from_dict(data)$ DocumentationJob - } - - class LLMConfig { - +str main_model - +str cluster_model - +str base_url - } - - class JobStatistics { - +int total_files_analyzed - +int leaf_nodes - +int max_depth - +int total_tokens_used - } - - class GenerationOptions { - +bool create_branch - +bool github_pages - +bool no_cache - +Optional custom_output - } - - class JobStatus { - <> - PENDING - RUNNING - COMPLETED - FAILED - } - - class DocumentationGenerator { - <> - +graph_builder - +backend - +generate_module_documentation() - +create_documentation_metadata() - +validate_generated_docs() - } - - class ProgressTracker { - <> - +start_stage(stage, description) - +update_stage(progress, message) - +complete_stage(message) - } - - class HTMLGenerator { - <> - +detect_repository_info(repo_path) - +generate(output_path, title, ...) - } - - CLIDocumentationGenerator "1" *-- "1" DocumentationJob : owns - CLIDocumentationGenerator "1" *-- "1" ProgressTracker : owns - CLIDocumentationGenerator ..> DocumentationGenerator : creates & drives - CLIDocumentationGenerator ..> HTMLGenerator : creates (optional) - DocumentationJob "1" *-- "1" LLMConfig - DocumentationJob "1" *-- "1" JobStatistics - DocumentationJob "1" *-- "1" GenerationOptions - DocumentationJob "1" *-- "1" JobStatus -``` - ---- - -### Job Data Models (`codewiki/cli/models/job.py`) - -These dataclasses define the serializable state of a documentation generation job: - -| Model | Purpose | -|---|---| -| `JobStatus` | String enum: `pending`, `running`, `completed`, `failed`. | -| `LLMConfig` | Snapshot of the LLM settings used for the run (`main_model`, `cluster_model`, `base_url`). | -| `GenerationOptions` | User-selected CLI flags: branch creation, GitHub Pages mode, cache bypass, custom output path. | -| `JobStatistics` | Run metrics: files analyzed, leaf node count, max depth, total tokens used. | -| `DocumentationJob` | The aggregate job record β€” identity (`job_id`, UUID), repo/output paths, git info, timestamps, `status`, `error_message`, generated file list, module count, and nested `LLMConfig`/`GenerationOptions`/`JobStatistics`. Provides `start()`, `complete()`, `fail()` lifecycle transitions, plus `to_dict()`/`to_json()`/`from_dict()` for persistence (e.g., written as `metadata.json` fallback, or consumed by other tooling that inspects run results). | - -`DocumentationJob` is intentionally backend-agnostic β€” it does not import from `codewiki.src.be`, keeping the CLI's job-tracking model decoupled from backend internals. - ---- - -## Documentation Generation Pipeline - -### End-to-End Sequence - -```mermaid -sequenceDiagram - participant CLI as CLI Command - participant Gen as CLIDocumentationGenerator - participant PT as ProgressTracker - participant Job as DocumentationJob - participant BE as DocumentationGenerator (Backend) - participant GB as DependencyGraphBuilder - participant CM as cluster_modules() - participant HTML as HTMLGenerator - - CLI->>Gen: __init__(repo_path, output_dir, config, verbose, generate_html, commit_id) - Gen->>Job: new DocumentationJob() + set metadata - Gen->>Gen: _configure_backend_logging() - CLI->>Gen: generate() - Gen->>Job: start() - Gen->>Gen: BackendConfig.from_cli(...) - - Gen->>Gen: _run_backend_generation(backend_config) [async] - Note over Gen,BE: Stage 1: Dependency Analysis - Gen->>PT: start_stage(1, "Dependency Analysis") - Gen->>BE: new DocumentationGenerator(backend_config, commit_id) - Gen->>GB: build_dependency_graph() - GB-->>Gen: components, leaf_nodes - Gen->>Job: statistics.total_files_analyzed / leaf_nodes - Gen->>PT: complete_stage() - - Note over Gen,CM: Stage 2: Module Clustering - Gen->>PT: start_stage(2, "Module Clustering") - alt cached first_module_tree.json exists - Gen->>Gen: load cached module tree - else - Gen->>CM: cluster_modules(leaf_nodes, components, backend_config, completer=backend.complete) - CM-->>Gen: module_tree - Gen->>Gen: dedupe_module_tree_names(module_tree) - Gen->>Gen: save first_module_tree.json - end - Gen->>Gen: save module_tree.json - Gen->>Job: module_count = len(module_tree) - Gen->>PT: complete_stage() - - Note over Gen,BE: Stage 3: Documentation Generation - Gen->>PT: start_stage(3, "Documentation Generation") - Gen->>BE: generate_module_documentation(components, leaf_nodes) - BE-->>Gen: (writes .md files per module, bottom-up) - Gen->>BE: create_documentation_metadata(working_dir, components, len(leaf_nodes)) - Gen->>Job: files_generated += *.md, *.json - Gen->>BE: validate_generated_docs(working_dir) - alt missing docs - Gen-->>CLI: raise IncompleteGenerationError - end - Gen->>PT: complete_stage() - - opt generate_html = True - Note over Gen,HTML: Stage 4: HTML Generation - Gen->>PT: start_stage(4, "HTML Generation") - Gen->>HTML: detect_repository_info(repo_path) - Gen->>HTML: generate(output_path=index.html, docs_dir=output_dir) - Gen->>Job: files_generated += index.html - Gen->>PT: complete_stage() - end - - Note over Gen: Stage 5: Finalization - Gen->>Gen: _finalize_job() (ensure metadata.json exists) - Gen->>Job: complete() - Gen-->>CLI: return DocumentationJob - - alt APIError / Exception raised anywhere - Gen->>Job: fail(error_message) - Gen-->>CLI: re-raise exception - end -``` - -### Stage Breakdown - -| Stage | Weight* | Responsibility | Key Collaborators | -|---|---|---|---| -| 1. Dependency Analysis | 40% | Parse repository source into a component graph and identify leaf (entry-point) nodes | `DependencyGraphBuilder` ([Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)), language analyzers ([Language_Analyzers](Language_Analyzers.md)) | -| 2. Module Clustering | 20% | Group leaf nodes into a hierarchical module tree, using cached `first_module_tree.json` if present, else LLM-based clustering | `cluster_modules()`, `dedupe_module_tree_names()` (Backend_LLM_&_Documentation_Services) | -| 3. Documentation Generation | 30% | Bottom-up generation of per-module `.md` docs, repository overview, and `metadata.json`; validates no docs are missing | `DocumentationGenerator.generate_module_documentation`, `validate_generated_docs` | -| 4. HTML Generation (optional) | 5% | Render a static `index.html` viewer embedding the module tree and metadata | `HTMLGenerator` ([CLI_HTML_Viewer](CLI_HTML_Viewer.md)) | -| 5. Finalization | 5% | Confirm `metadata.json` exists; mark job complete | `DocumentationJob.complete()` | - -\* Weights defined in `ProgressTracker.STAGE_WEIGHTS`, used for ETA estimation β€” see [CLI_Utilities](CLI_Utilities.md). - ---- - -## Configuration Flow - -`CLIDocumentationGenerator` does not read configuration files directly β€” it receives a plain `config: Dict[str, Any]` (typically assembled by the CLI command layer from [CLI_Configuration](CLI_Configuration.md)'s `ConfigManager`/`Configuration`) and translates it into the backend's typed `Config` object. - -```mermaid -graph LR - A["Configuration
(CLI_Configuration)"] -->|"as dict"| B["config: Dict[str, Any]
passed to CLIDocumentationGenerator"] - B --> C["CLIDocumentationGenerator.__init__
builds job.llm_config: LLMConfig"] - B --> D["Config.from_cli(...)
Core_Config_&_Utils"] - D --> E["BackendConfig
used by DocumentationGenerator,
DependencyGraphBuilder,
cluster_modules"] -``` - -Fields forwarded to `Config.from_cli(...)` include: `base_url`, `api_key`, `main_model`, `cluster_model`, `fallback_model`, `provider`, `aws_region`, `max_tokens`, `max_token_per_module`, `max_token_per_leaf_module`, `max_depth`, `agent_instructions` (see `AgentInstructions` in [CLI_Configuration](CLI_Configuration.md)), `use_gitignore`, and `prompt_caching`. - ---- - -## Error Handling - -```mermaid -flowchart TD - A["generate() called"] --> B{"Exception during
backend generation?"} - B -- "APIError" --> C["job.fail(str(e))"] - C --> D["re-raise APIError"] - B -- "IncompleteGenerationError
(missing module docs)"--> E["propagates directly
(raised outside try/except)"] - B -- "other Exception" --> F["job.fail(str(e))"] - F --> G["re-raise Exception"] - B -- "no exception" --> H["job.complete()"] - H --> I["return DocumentationJob"] -``` - -- **`APIError`** β€” raised when dependency analysis, module clustering, or documentation generation calls fail (e.g., LLM API failures); wraps the underlying exception with a descriptive message and a dedicated CLI exit code. -- **`IncompleteGenerationError`** β€” raised specifically when `validate_generated_docs()` detects module `.md` files expected by the final `module_tree.json` but absent on disk. This check is placed outside the stage's `try/except` block so it is never masked as a generic `APIError`; it carries `missing_modules` for precise CLI reporting. -- Both error types derive from the CLI's shared `CodeWikiError` hierarchy (`codewiki/cli/utils/errors.py`), each mapping to a specific process exit code. - ---- - -## Relationship to Other Modules - -| Module | Relationship | -|---|---| -| [CLI_Configuration](CLI_Configuration.md) | Supplies the `Configuration`/`AgentInstructions` data that the CLI command layer flattens into the `config` dict consumed by `CLIDocumentationGenerator`. | -| [CLI_Git_Integration](CLI_Git_Integration.md) | Supplies `commit_id` (via `GitManager.get_commit_hash()`) used for incremental-update tracking and embedded in generated metadata. | -| [CLI_HTML_Viewer](CLI_HTML_Viewer.md) | Invoked in Stage 4 when `generate_html=True`; consumes `module_tree.json`/`metadata.json` written by Stage 3 to render `index.html`. | -| [CLI_Utilities](CLI_Utilities.md) | Provides `ProgressTracker` (stage/ETA reporting) and `CLILogger` (general CLI logging), plus `ColoredFormatter` reuse for consistent terminal output. | -| [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) | Provides `DocumentationGenerator`, the core orchestrator for dependency-graph-driven, bottom-up module documentation generation and the `LLMBackend` abstraction used for completions. | -| [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) | Provides `DependencyGraphBuilder` (invoked via `doc_generator.graph_builder`) and `ColoredFormatter` for logging. | -| [Dependency_Analysis_Service](Dependency_Analysis_Service.md) / [Language_Analyzers](Language_Analyzers.md) | Perform the actual per-language parsing underlying Stage 1. | -| [Core_Config_&_Utils](Core_Config_&_Utils.md) | Supplies `Config` (backend configuration dataclass, `Config.from_cli`) and `FileManager`/`file_manager` used for reading/writing module trees and generated files. | - ---- - -## Key Design Notes - -- **Adapter pattern, not reimplementation**: `CLIDocumentationGenerator` deliberately delegates all heavy lifting (graph building, clustering, LLM completions, file writes) to the backend `DocumentationGenerator`; its own logic is limited to config translation, progress reporting, and CLI-specific error/job bookkeeping. -- **Caching-aware clustering**: Stage 2 checks for a previously persisted `first_module_tree.json` before invoking LLM-based clustering, allowing repeated runs (e.g., incremental docs) to skip expensive clustering calls. -- **Whole-repository fallback**: if clustering yields zero top-level modules (repo small enough to fit context), the pipeline still completes correctly β€” logged clearly in verbose mode ("continuing in whole-repository documentation mode"). -- **Strict completeness validation**: the module treats a successful LLM run that nonetheless fails to write all expected `.md` files as a failure (`IncompleteGenerationError`), guarding against silent partial documentation (a known failure mode with module name collisions or crashed sub-agents). -- **Logging isolation**: backend loggers (`codewiki.src.be`) are explicitly configured and detached from root-logger propagation to keep CLI console output clean and controllable via `--verbose`. diff --git a/docs/CLI_Git_Integration.md b/docs/CLI_Git_Integration.md deleted file mode 100644 index d8876e8d..00000000 --- a/docs/CLI_Git_Integration.md +++ /dev/null @@ -1,241 +0,0 @@ -# CLI Git Integration - -## Introduction - -The **CLI Git Integration** module provides the `GitManager` class (`codewiki/cli/git_manager.py`), a thin, focused wrapper around [GitPython](https://gitpython.readthedocs.io/) that gives the CodeWiki CLI everything it needs to safely interact with a local git repository during a documentation run. - -Its responsibilities are narrow but essential to the `codewiki generate --create-branch` workflow: - -- Verifying that a target directory is actually a git repository. -- Checking whether the working directory is clean before making changes. -- Creating a dedicated, timestamped documentation branch. -- Committing generated documentation artifacts. -- Reading repository metadata (current branch, commit hash, remote URL). -- Deriving a GitHub "compare/PR" URL for the documentation branch, when the remote is GitHub. - -This module has no knowledge of *what* documentation is generated β€” that is the responsibility of [CLI_Documentation_Generation](CLI_Documentation_Generation.md). `GitManager` is invoked directly by the CLI command layer (the `codewiki generate` entry point), which orchestrates it alongside [CLI_Configuration](CLI_Configuration.md) and [CLI_Documentation_Generation](CLI_Documentation_Generation.md) as described in the parent [CLI](CLI.md) module documentation. - ---- - -## Purpose & Core Functionality - -`GitManager` exists to answer three questions the CLI needs answered around every "generate documentation and open a PR" workflow: - -1. **Is it safe to proceed?** β€” Is this a git repository, and is the working directory clean enough to create a new branch without losing uncommitted work? -2. **Where should the output go?** β€” Create (or reuse) a uniquely-named `docs/codewiki-` branch to isolate generated documentation from the user's working branch. -3. **How do I finish and let the user act on the result?** β€” Commit the generated docs, and produce a ready-to-click GitHub compare/PR URL so the user (or CI) can review and merge the change. - -All git interaction is funneled through GitPython's `git.Repo` object, and all failure modes are normalized into the CLI's shared `RepositoryError` exception (see [CLI_Utilities](CLI_Utilities.md)) so that the CLI's top-level error handler can present a consistent, actionable message and exit code. - ---- - -## Architecture Overview - -```mermaid -graph TB - subgraph CLI_Git_Integration - GM["GitManager"] - end - - subgraph "Third-Party" - GITPY["GitPython (git.Repo)"] - end - - subgraph "Local Filesystem" - REPO[".git repository
on disk"] - end - - subgraph "CLI_Utilities" - ERR["RepositoryError
(codewiki/cli/utils/errors.py)"] - end - - subgraph "Consumers" - CLICMD["CLI Command Layer
(codewiki generate)"] - DOCGEN["CLIDocumentationGenerator
(CLI_Documentation_Generation)"] - end - - CLICMD -->|"instantiates"| GM - GM -->|"wraps"| GITPY - GITPY -->|"reads/writes"| REPO - GM -->|"raises on failure"| ERR - CLICMD -->|"get_commit_hash()"| GM - GM -->|"commit_id"| DOCGEN - CLICMD -->|"create_documentation_branch() /
commit_documentation() /
get_github_pr_url()"| GM - - style CLI_Git_Integration fill:#eef,stroke:#336 -``` - -### Where `GitManager` fits in the `codewiki generate` command - -`GitManager` is never invoked by the documentation-generation pipeline itself; it is orchestrated *around* it by the CLI command layer. The command layer: - -1. Uses `GitManager` to validate repository state and (optionally) create a branch **before** calling into [CLI_Documentation_Generation](CLI_Documentation_Generation.md). -2. Passes `GitManager.get_commit_hash()` into `CLIDocumentationGenerator` as `commit_id`, which is embedded in generated metadata for incremental-update tracking. -3. Uses `GitManager` again **after** generation completes to commit the output and surface a PR URL. - -```mermaid -graph LR - A["CLI Command Layer"] --> B["GitManager.check_clean_working_directory()"] - B --> C{"--create-branch flag?"} - C -- yes --> D["GitManager.create_documentation_branch()"] - C -- no --> E["proceed on current branch"] - D --> F["GitManager.get_commit_hash()"] - E --> F - F --> G["CLIDocumentationGenerator.generate()
(CLI_Documentation_Generation)"] - G --> H{"--create-branch flag?"} - H -- yes --> I["GitManager.commit_documentation(output_dir)"] - I --> J["GitManager.get_github_pr_url(branch_name)"] - J --> K["Print PR URL to user"] - H -- no --> L["Print completion summary"] -``` - ---- - -## Component Reference - -### `GitManager` (`codewiki/cli/git_manager.py`) - -Constructed with the path to a repository; internally opens a `git.Repo` handle with `search_parent_directories=True` so it works correctly even when `repo_path` is a subdirectory of the git root. - -```mermaid -classDiagram - class GitManager { - +Path repo_path - +git.Repo repo - +__init__(repo_path) - +check_clean_working_directory() Tuple~bool, str~ - +create_documentation_branch(force) str - +commit_documentation(docs_path, message) str - +get_remote_url(remote_name) Optional~str~ - +get_current_branch() str - +get_commit_hash() str - +branch_exists(branch_name) bool - +get_github_pr_url(branch_name) Optional~str~ - } - class RepositoryError { - <> - +message - +exit_code - } - GitManager ..> RepositoryError : raises -``` - -#### Public API - -| Method | Description | Failure Behavior | -|---|---|---| -| `__init__(repo_path)` | Resolves `repo_path` and opens the repository via `git.Repo(repo_path, search_parent_directories=True)`. | Raises `RepositoryError` if `git.InvalidGitRepositoryError` is caught, with a hint to run `git init`. | -| `check_clean_working_directory()` | Checks `repo.is_dirty(untracked_files=True)`; if dirty, builds a human-readable summary of modified files (`repo.index.diff(None)`) and untracked files (`repo.untracked_files`), truncated to the first 3 entries each. | Never raises; returns `(bool, str)`. | -| `create_documentation_branch(force=False)` | Unless `force=True`, calls `check_clean_working_directory()` and raises if dirty. Generates a branch name `docs/codewiki-`, disambiguating with a numeric suffix if it collides with an existing branch (defensive; unlikely given timestamp granularity). Creates and checks out the new branch via `repo.create_head(...)` / `.checkout()`. | Raises `RepositoryError` on dirty working directory (with a detailed remediation message) or on `GitCommandError` during branch creation. | -| `commit_documentation(docs_path, message=None)` | Stages `docs_path` (`repo.index.add([...])`) and commits (`repo.index.commit(message)`), defaulting to `"Add generated documentation\n\nGenerated by CodeWiki CLI"`. Returns the new commit's `hexsha`. | Raises `RepositoryError` on `GitCommandError`. | -| `get_remote_url(remote_name="origin")` | Returns the URL of the named remote, or `None` if it doesn't exist. | Catches `ValueError` internally; never raises. | -| `get_current_branch()` | Returns `repo.active_branch.name`, or the literal string `"HEAD"` if in detached-HEAD state. | Catches `TypeError` internally; never raises. | -| `get_commit_hash()` | Returns `repo.head.commit.hexsha` β€” the current `HEAD` commit SHA. | β€” | -| `branch_exists(branch_name)` | Returns whether `branch_name` is among `repo.branches`. | β€” | -| `get_github_pr_url(branch_name)` | Resolves the `origin` remote URL, normalizes SSH (`git@github.com:...`) and `.git`-suffixed URLs to an `https://github.com/...` form, and returns `/compare/`. Returns `None` if there's no remote or it's not a `github.com` URL. | Never raises. | - ---- - -## Data Flow: Creating a Documentation Branch - -```mermaid -sequenceDiagram - participant CLI as CLI Command - participant GM as GitManager - participant Repo as git.Repo - - CLI->>GM: create_documentation_branch(force=False) - GM->>GM: check_clean_working_directory() - alt working directory dirty - GM-->>CLI: raise RepositoryError
(with git status / commit / stash guidance) - else clean - GM->>GM: branch_name = f"docs/codewiki-{timestamp}" - GM->>Repo: branches (check for name collision) - alt name collision (rare) - GM->>GM: append -1, -2, ... suffix - end - GM->>Repo: create_head(branch_name) - GM->>Repo: new_branch.checkout() - Repo-->>GM: OK - GM-->>CLI: branch_name - end -``` - -## Data Flow: Committing Documentation & Deriving a PR URL - -```mermaid -sequenceDiagram - participant CLI as CLI Command - participant GM as GitManager - participant Repo as git.Repo - - Note over CLI: After CLIDocumentationGenerator.generate()
completes successfully (CLI_Documentation_Generation) - CLI->>GM: commit_documentation(output_dir, message=None) - GM->>Repo: index.add([output_dir]) - GM->>Repo: index.commit("Add generated documentation...") - Repo-->>GM: commit.hexsha - GM-->>CLI: commit_hash - - CLI->>GM: get_current_branch() - GM-->>CLI: branch_name - - CLI->>GM: get_github_pr_url(branch_name) - GM->>GM: get_remote_url("origin") - alt remote is github.com - GM->>GM: normalize SSH -> HTTPS, strip .git - GM-->>CLI: "https://github.com///compare/" - else no remote / not GitHub - GM-->>CLI: None - end - CLI-->>CLI: Print commit hash and, if available, PR URL -``` - ---- - -## Error Handling - -`GitManager` deliberately converts all GitPython-specific exceptions into the CLI's shared `RepositoryError` (defined in [CLI_Utilities](CLI_Utilities.md), `codewiki/cli/utils/errors.py`), which derives from `CodeWikiError` and carries an `EXIT_REPOSITORY_ERROR` exit code. This keeps git-specific exception types out of the rest of the CLI, allowing the top-level command handler to catch a single, consistent error hierarchy regardless of whether a failure originated in configuration, documentation generation, or git operations. - -```mermaid -flowchart TD - A["GitManager method called"] --> B{"Exception type?"} - B -- "git.InvalidGitRepositoryError
(constructor)" --> C["RepositoryError:
'Not a git repository...
run git init'"] - B -- "Dirty working directory
(create_documentation_branch)" --> D["RepositoryError:
detailed status + remediation
(git status / commit / stash)"] - B -- "git.GitCommandError
(branch creation or commit)" --> E["RepositoryError:
'Failed to create branch / commit: ...'"] - B -- "ValueError / TypeError
(remote lookup, detached HEAD)" --> F["Handled internally,
returns None / 'HEAD'"] - C --> G["Propagates to CLI command layer
-> printed with exit_code"] - D --> G - E --> G -``` - -Key design point: `check_clean_working_directory()` is intentionally **non-raising** β€” it returns a `(bool, str)` tuple so callers can decide how to react (e.g., the CLI command may want to show the status and prompt the user, rather than immediately failing). The raising behavior only kicks in inside `create_documentation_branch()`, where dirtiness is treated as a hard precondition (unless explicitly bypassed with `force=True`). - ---- - -## Dependencies - -| Dependency | Source | Usage | -|---|---|---| -| `git.Repo`, `git.InvalidGitRepositoryError`, `git.exc.GitCommandError` | GitPython (third-party) | Underlying implementation for all repository inspection and mutation operations. | -| `RepositoryError` | [CLI_Utilities](CLI_Utilities.md) (`codewiki/cli/utils/errors.py`) | Normalized exception type raised on all git failure paths. | - -`GitManager` has no dependency on any backend module ([Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md), [Dependency_Analysis_Service](Dependency_Analysis_Service.md), etc.) β€” it operates purely on the local filesystem/git state and is safe to use independently of any documentation-generation run. - ---- - -## Consumers - -| Consumer | Relationship | -|---|---| -| CLI command layer (`codewiki generate`) | Primary caller. Instantiates `GitManager` for the target `repo_path`, uses `check_clean_working_directory()` / `create_documentation_branch()` before generation, and `commit_documentation()` / `get_github_pr_url()` after generation, per the `--create-branch` flag. | -| [CLI_Documentation_Generation](CLI_Documentation_Generation.md) (`CLIDocumentationGenerator`) | Indirect consumer β€” receives `commit_id` as a constructor argument, which the CLI command layer typically obtains via `GitManager.get_commit_hash()`. This value is embedded in generated `metadata.json` to support incremental-update tracking across runs. `CLIDocumentationGenerator` does not instantiate or call `GitManager` itself. | - ---- - -## Key Design Notes - -- **Single Responsibility**: `GitManager` only performs git operations β€” no documentation logic, no LLM calls, no HTML rendering. This keeps it trivially testable and reusable outside the `generate` command (e.g., for future commands that need branch/PR metadata). -- **Timestamped, collision-resistant branch naming**: Using a `YYYYmmdd-HHMMSS` timestamp for branch names (`docs/codewiki-`) makes repeated runs safe and traceable, while the numeric-suffix fallback guards against the edge case of two runs within the same second. -- **Fail-safe defaults, explicit escape hatches**: Working-directory-dirty checks are enforced by default to protect user work, but `force=True` is available for automated/CI contexts where the caller has already made an informed decision to proceed. -- **GitHub-aware, but not GitHub-dependent**: `get_github_pr_url()` degrades gracefully (returns `None`) for non-GitHub remotes or repositories without a configured remote, so the rest of the CLI can treat the PR URL as an optional convenience rather than a hard requirement. -- **Consistent error surface**: By funneling every git failure through `RepositoryError`, the module ensures git-related problems are reported to the user with the same tone, formatting, and exit-code conventions as configuration or generation errors β€” see the CLI-wide error handling conventions in [CLI_Documentation_Generation](CLI_Documentation_Generation.md#error-handling) and [CLI_Utilities](CLI_Utilities.md). diff --git a/docs/CLI_HTML_Viewer.md b/docs/CLI_HTML_Viewer.md deleted file mode 100644 index e8bccfe8..00000000 --- a/docs/CLI_HTML_Viewer.md +++ /dev/null @@ -1,272 +0,0 @@ -# CLI HTML Viewer - -## Introduction - -The **CLI HTML Viewer** module is responsible for turning the raw Markdown-based documentation artifacts produced by CodeWiki (`*.md`, `module_tree.json`, `metadata.json`) into a **single self-contained, static `index.html` file** that can be published directly to GitHub Pages (or any static host) and browsed offline without a build step. - -It is a small, focused module consisting of a single class β€” `HTMLGenerator` β€” that: - -- Loads the generated documentation's `module_tree.json` and `metadata.json`. -- Injects that data, along with repository metadata (name, URL, GitHub Pages URL), into a pre-built HTML template (`viewer_template.html`). -- Writes the final HTML file to disk using safe, atomic file operations. -- Detects git repository information (remote URL, computed GitHub Pages URL) to enrich the generated page with a "View Repository" link and generation metadata panel. - -This module is a leaf component of the [CLI module](CLI.md) family and is invoked as an optional final stage of the documentation generation pipeline implemented by [CLI_Documentation_Generation](CLI_Documentation_Generation.md). - ---- - -## Purpose & Core Functionality - -| Responsibility | Description | -|---|---| -| **Template-based HTML generation** | Reads a static HTML template with placeholder tokens and performs string substitution to embed configuration and content. | -| **Module tree & metadata loading** | Reads `module_tree.json` and `metadata.json` from the documentation output directory produced by the backend [Backend_LLM_&_Documentation_Services](Backend_LLM_%26_Documentation_Services.md). | -| **Repository info detection** | Uses `GitPython` to inspect the local git repository and derive the remote URL and the expected GitHub Pages URL. | -| **Info panel construction** | Builds a small HTML fragment summarizing generation info (model used, timestamp, commit, component/module statistics) for display in the viewer sidebar. | -| **Safe file I/O** | Delegates all file reads/writes to shared CLI utilities (`safe_read`/`safe_write`) that provide atomic writes and consistent error handling (`FileSystemError`). | - -The generated `index.html` is fully client-side: it embeds the module tree and metadata as inline JSON and relies on client-side JavaScript (bundled in the template) using `marked.js` for Markdown rendering and `mermaid.js` for diagram rendering. No server-side processing or build tooling is required at view time β€” the browser fetches the referenced `.md` files relative to `index.html` and renders them dynamically. - ---- - -## Architecture - -```mermaid -graph TB - subgraph CLI_HTML_Viewer["CLI HTML Viewer Module"] - HTMLGenerator["HTMLGenerator"] - end - - subgraph Utils["CLI Utilities (shared)"] - SafeIO["fs.safe_read / fs.safe_write"] - Errors["errors.FileSystemError"] - end - - subgraph Template["Static Template Assets"] - TemplateFile["templates/github_pages/viewer_template.html"] - end - - subgraph DocsOutput["Documentation Output Directory"] - ModuleTree["module_tree.json"] - Metadata["metadata.json"] - MDFiles["*.md files"] - end - - subgraph GitLib["External: GitPython"] - GitRepo["git.Repo"] - end - - HTMLGenerator -->|reads| TemplateFile - HTMLGenerator -->|reads| ModuleTree - HTMLGenerator -->|reads| Metadata - HTMLGenerator -->|uses| SafeIO - SafeIO -->|raises on failure| Errors - HTMLGenerator -->|inspects repo| GitRepo - HTMLGenerator -->|writes| IndexHTML["index.html (output)"] - - IndexHTML -.->|references at runtime| MDFiles -``` - -### Class Diagram - -```mermaid -classDiagram - class HTMLGenerator { - +Path template_dir - +__init__(template_dir: Optional~Path~) - +load_module_tree(docs_dir: Path) Dict - +load_metadata(docs_dir: Path) Optional~Dict~ - +generate(output_path, title, module_tree, repository_url, github_pages_url, config, docs_dir, metadata) void - +detect_repository_info(repo_path: Path) Dict - -_build_info_content(metadata: Optional~Dict~) str - -_escape_html(text: str) str - } - - class FileSystemError { - <> - } - - HTMLGenerator ..> FileSystemError : raises - HTMLGenerator ..> SafeIO : uses - - class SafeIO { - <> - +safe_read() - +safe_write() - } -``` - ---- - -## Component Details - -### `HTMLGenerator` - -**File:** `codewiki/cli/html_generator.py` - -The single public class in this module. It has no persistent state beyond the resolved `template_dir`; all generation logic is stateless and driven by method arguments. - -#### `__init__(template_dir: Optional[Path] = None)` -Resolves the template directory. If not explicitly provided, defaults to the package-bundled template at `codewiki/templates/github_pages/` (two levels up from `html_generator.py`, then into `templates/github_pages`). - -#### `load_module_tree(docs_dir: Path) -> Dict[str, Any]` -Loads `module_tree.json` from the documentation directory produced by the backend clustering/generation pipeline (see [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) and [Backend_LLM_&_Documentation_Services](Backend_LLM_%26_Documentation_Services.md)). If the file is missing, falls back to a minimal single-node "Overview" tree so the viewer never fails to render entirely. Parsing errors are wrapped in `FileSystemError`. - -#### `load_metadata(docs_dir: Path) -> Optional[Dict[str, Any]]` -Loads `metadata.json`, which contains `generation_info` (model, timestamp, commit id) and `statistics` (total components, max depth) written by the documentation generator. This file is optional β€” the viewer degrades gracefully (hides the info panel) if it is absent or unparsable. - -#### `generate(...)` -The main entry point. Performs the following steps: - -1. **Auto-load** `module_tree` and `metadata` from `docs_dir` if not explicitly supplied. -2. **Load the HTML template** (`viewer_template.html`); raises `FileSystemError` if missing. -3. **Build the info panel** HTML fragment via `_build_info_content`. -4. **Build the repository link** HTML anchor if a `repository_url` is given. -5. **Compute `docs_base_path`** β€” the relative path from the output HTML file to the docs directory containing the `.md` files, so the client-side JS can fetch them correctly. -6. **Serialize** `config`, `module_tree`, and `metadata` to indented JSON strings for embedding. -7. **Token substitution** β€” replace all `{{PLACEHOLDER}}` tokens in the template with the computed values (see [Template Placeholders](#template-placeholders) below). -8. **Write** the resulting HTML to `output_path` using `safe_write` (atomic write via temp file + rename), creating parent directories as needed. - -#### `_build_info_content(metadata) -> str` -Constructs a series of `
` HTML snippets summarizing: -- Model used (`generation_info.main_model`) -- Generation date (parsed from ISO `generation_info.timestamp`) -- Short commit hash (`generation_info.commit_id[:8]`) -- Total components (`statistics.total_components`, comma-formatted) -- Max hierarchy depth (`statistics.max_depth`) - -Returns an empty string if no `generation_info` is present, which causes the sidebar info panel to be hidden (`{{SHOW_INFO}} = "none"`). - -#### `_escape_html(text) -> str` -Simple HTML entity escaping (`& < > " '`) applied to any user/repo-derived string (e.g., title, model name) before embedding into the template to avoid HTML injection/breakage. - -#### `detect_repository_info(repo_path: Path) -> Dict[str, Optional[str]]` -Uses `GitPython` (`git.Repo`) to: -- Read the repository name from the path. -- Read the `origin` remote URL, normalizing SSH (`git@github.com:...`) to HTTPS and stripping `.git` suffix. -- If the remote is a GitHub URL, compute the expected GitHub Pages URL as `https://{owner}.github.io/{repo}/`. - -All git errors are swallowed (`except Exception: pass`), so this method always returns a dict with at least `name` populated β€” it never raises, ensuring HTML generation can proceed even outside a git repository or without a configured remote. - ---- - -## Template Placeholders - -The `HTMLGenerator` performs literal string replacement against `viewer_template.html` (bundled at `codewiki/templates/github_pages/viewer_template.html`). The template is a fully self-contained HTML page using CDN-hosted `marked.js` (Markdown rendering) and `mermaid.js` (diagram rendering), plus embedded CSS/JS for sidebar navigation and dynamic content loading. - -| Placeholder | Source | Description | -|---|---|---| -| `{{TITLE}}` | `title` arg (escaped) | Page `` and sidebar logo text | -| `{{REPO_LINK}}` | `repository_url` arg | Anchor tag linking to the GitHub repo, or empty string | -| `{{SHOW_INFO}}` | Computed | `"block"` or `"none"` β€” controls visibility of the info panel | -| `{{INFO_CONTENT}}` | `_build_info_content()` | HTML rows with generation statistics | -| `{{CONFIG_JSON}}` | `config` arg | Arbitrary JSON config embedded as a JS constant `CONFIG` | -| `{{MODULE_TREE_JSON}}` | `module_tree` arg/loaded | JS constant `MODULE_TREE` β€” drives sidebar navigation tree | -| `{{METADATA_JSON}}` | `metadata` arg/loaded | JS constant `METADATA` (or `null`) | -| `{{DOCS_BASE_PATH}}` | Computed | Relative path prefix used by client JS to fetch `.md` files | - -At runtime in the browser, the embedded JavaScript uses `MODULE_TREE` to render a collapsible sidebar navigation, fetches the corresponding `.md` file (relative to `DOCS_BASE_PATH`) when a nav item is clicked, converts it with `marked.js`, and renders any ```mermaid fenced code blocks using `mermaid.js`. - ---- - -## Integration with the Documentation Generation Pipeline - -`HTMLGenerator` is not invoked directly by end users; it is orchestrated by `CLIDocumentationGenerator` (part of [CLI_Documentation_Generation](CLI_Documentation_Generation.md)) as an optional **Stage 4** step, only when the user passes `--github-pages` to the `codewiki generate` CLI command. - -```mermaid -sequenceDiagram - participant User - participant GenerateCmd as generate_command (CLI) - participant CLIDocGen as CLIDocumentationGenerator - participant Backend as DocumentationGenerator (Backend) - participant HTMLGen as HTMLGenerator - participant FS as Filesystem - - User->>GenerateCmd: codewiki generate --github-pages - GenerateCmd->>CLIDocGen: generate() - CLIDocGen->>Backend: build_dependency_graph(), generate_module_documentation() - Backend->>FS: write *.md, module_tree.json, metadata.json - CLIDocGen->>CLIDocGen: _run_html_generation() [Stage 4, only if generate_html=True] - CLIDocGen->>HTMLGen: detect_repository_info(repo_path) - HTMLGen-->>CLIDocGen: {name, url, github_pages_url} - CLIDocGen->>HTMLGen: generate(output_path=docs/index.html, docs_dir=docs/, title=repo_name, repository_url=url) - HTMLGen->>FS: load_module_tree(docs_dir) -> module_tree.json - HTMLGen->>FS: load_metadata(docs_dir) -> metadata.json - HTMLGen->>FS: safe_read(viewer_template.html) - HTMLGen->>HTMLGen: substitute placeholders - HTMLGen->>FS: safe_write(index.html) - HTMLGen-->>CLIDocGen: (void) - CLIDocGen-->>User: job.files_generated += "index.html" -``` - -Relevant excerpt from `CLIDocumentationGenerator._run_html_generation`: - -```python -def _run_html_generation(self): - self.progress_tracker.start_stage(4, "HTML Generation") - from codewiki.cli.html_generator import HTMLGenerator - html_generator = HTMLGenerator() - repo_info = html_generator.detect_repository_info(self.repo_path) - output_path = self.output_dir / "index.html" - html_generator.generate( - output_path=output_path, - title=repo_info['name'], - repository_url=repo_info['url'], - github_pages_url=repo_info['github_pages_url'], - docs_dir=self.output_dir # auto-loads module_tree.json & metadata.json - ) - self.job.files_generated.append("index.html") - self.progress_tracker.complete_stage() -``` - -See [CLI_Documentation_Generation](CLI_Documentation_Generation.md) for the full 5-stage pipeline (Dependency Analysis β†’ Module Clustering β†’ Documentation Generation β†’ **HTML Generation** β†’ Finalization) and the `DocumentationJob` model that tracks `files_generated`. - ---- - -## Data Flow - -```mermaid -flowchart LR - A[Repository source code] --> B["Dependency Analysis<br/>(Dependency_Analysis_Service)"] - B --> C["Module Clustering<br/>module_tree.json"] - C --> D["LLM Documentation Generation<br/>*.md files + metadata.json"] - D --> E{generate_html flag?} - E -- yes --> F[HTMLGenerator.generate] - E -- no --> G[Skip HTML stage] - F --> H[index.html] - H --> I["Static hosting<br/>(GitHub Pages / local file)"] - D -.->|.md files referenced at runtime| I -``` - ---- - -## Error Handling - -`HTMLGenerator` relies on the shared CLI error hierarchy defined in `codewiki/cli/utils/errors.py`: - -- **`FileSystemError`** (subclass of `CodeWikiError`) is raised when: - - The template file (`viewer_template.html`) cannot be found. - - `safe_read`/`safe_write` encounter I/O failures (missing file, permission errors, disk failures) while loading `module_tree.json` or writing `index.html`. -- **Non-critical failures** (e.g., malformed `metadata.json`, git detection errors) are intentionally swallowed and degrade gracefully β€” the viewer will simply omit the info panel or repository link rather than failing the entire documentation generation run. - -This mirrors the fail-soft philosophy used elsewhere in the CLI: optional enhancements (HTML viewer, info panel, repo link) should never block the core documentation output. - ---- - -## Dependencies on Other Modules - -| Dependency | Module | Usage | -|---|---|---| -| `safe_read`, `safe_write` | [CLI_Utilities](CLI_Utilities.md) (`codewiki/cli/utils/fs.py`) | Atomic, error-wrapped file I/O | -| `FileSystemError` | [CLI_Utilities](CLI_Utilities.md) (`codewiki/cli/utils/errors.py`) | Standardized error signaling | -| `CLIDocumentationGenerator` | [CLI_Documentation_Generation](CLI_Documentation_Generation.md) | Orchestrates invocation of `HTMLGenerator` as pipeline Stage 4 | -| `module_tree.json`, `metadata.json` | [Backend_LLM_&_Documentation_Services](Backend_LLM_%26_Documentation_Services.md) / [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) | Produced upstream; consumed for embedding in the viewer | -| `GitManager` (indirectly, via `git.Repo`) | [CLI_Git_Integration](CLI_Git_Integration.md) | Both use `GitPython`, but `HTMLGenerator.detect_repository_info` operates independently and does not share state with `GitManager` | - -No other module depends on `HTMLGenerator` β€” it is a terminal, presentation-only leaf in the CLI documentation pipeline. - ---- - -## Summary - -The CLI HTML Viewer module provides a lightweight, dependency-free (at runtime) way to package generated Markdown documentation into a browsable static site. It cleanly separates concerns from the documentation generation backend by only consuming already-generated artifacts (`module_tree.json`, `metadata.json`, `.md` files) and a static HTML template, making it easy to test, template-swap, or extend (e.g., custom themes) without touching the LLM-driven generation logic in [Backend_LLM_&_Documentation_Services](Backend_LLM_%26_Documentation_Services.md). diff --git a/docs/CLI_Utilities.md b/docs/CLI_Utilities.md deleted file mode 100644 index 608de96b..00000000 --- a/docs/CLI_Utilities.md +++ /dev/null @@ -1,265 +0,0 @@ -# CLI Utilities - -## Introduction - -The **CLI Utilities** module provides the foundational presentation-layer building blocks used throughout the CodeWiki command-line interface. It contains two lightweight, dependency-free helper classes: - -- **`CLILogger`** β€” a colored, timestamp-aware console logger with distinct semantics for debug, info, success, warning, and error output. -- **`ProgressTracker`** / **`ModuleProgressBar`** β€” stage-based and per-module progress reporting utilities that estimate ETA and render progress bars or verbose step logs. - -These utilities have no knowledge of documentation generation, git, or configuration logic. Instead, they are consumed by higher-level CLI components β€” most notably [CLI_Documentation_Generation](CLI_Documentation_Generation.md) β€” to surface human-readable feedback while the CLI orchestrates dependency analysis, module clustering, and documentation generation. Because they are pure UI/output helpers, they can be reused by any CLI command (e.g., `generate`, `update`, `serve`) without introducing coupling to business logic. - -This document describes the internal design of these utilities, how they interact with each other and with consuming modules, and where they fit within the broader CLI architecture. - ---- - -## Module Purpose & Scope - -| Concern | Handled by CLI_Utilities? | Notes | -|---|---|---| -| Colored/leveled console output | βœ… `CLILogger` | Uses `click.secho`/`click.echo` | -| Elapsed time tracking | βœ… `CLILogger.elapsed_time()` | Simple wall-clock delta since logger creation | -| Multi-stage progress with ETA | βœ… `ProgressTracker` | Weighted stages (Dependency Analysis, Clustering, Doc Gen, HTML Gen, Finalization) | -| Per-module progress (bar or verbose list) | βœ… `ModuleProgressBar` | Wraps `click.progressbar` or verbose per-module log lines | -| Documentation generation orchestration | ❌ | See [CLI_Documentation_Generation](CLI_Documentation_Generation.md) | -| Git branch/commit operations | ❌ | See [CLI_Git_Integration](CLI_Git_Integration.md) | -| Static HTML viewer generation | ❌ | See [CLI_HTML_Viewer](CLI_HTML_Viewer.md) | -| CLI configuration loading/validation | ❌ | See [CLI_Configuration](CLI_Configuration.md) | - ---- - -## Component Overview - -### `CLILogger` - -A minimal, stateful logger designed for CLI ergonomics rather than structured application logging (compare with the backend's `ColoredFormatter` in [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md), which formats Python `logging` records instead of ad-hoc CLI messages). - -Key characteristics: - -- **Verbose gating**: `debug()` messages are only emitted when `verbose=True`; all other levels are always shown. -- **Semantic coloring**: `success` (green, `βœ“`), `warning` (yellow, `⚠️`), `error` (red, `βœ—`, written to `stderr`), `step` (blue/bold, optional `[n/total]` prefix). -- **Session timing**: `start_time` is captured at construction; `elapsed_time()` returns a human-friendly `Xm Ys` or `Ys` string. -- **Factory function**: `create_logger(verbose)` is a thin convenience wrapper for constructing a `CLILogger`. - -```python -logger = create_logger(verbose=True) -logger.step("Starting analysis", step=1, total=5) -logger.debug("Parsing file foo.py") # only shown when verbose -logger.success("Analysis complete") -logger.warning("No .gitignore found") -logger.error("API request failed") -``` - -### `ProgressTracker` - -Tracks progress across the five conceptual phases of a documentation generation run, using fixed **stage weights** to compute an overall completion percentage and estimate time remaining (ETA). - -| Stage | Name | Weight | -|---|---|---| -| 1 | Dependency Analysis | 40% | -| 2 | Module Clustering | 20% | -| 3 | Documentation Generation | 30% | -| 4 | HTML Generation (optional) | 5% | -| 5 | Finalization | 5% | - -Core lifecycle methods: - -- `start_stage(stage, description=None)` β€” begins a stage, printing either a verbose timestamped header (`[MM:SS] Phase n/N: ...`) or a compact non-verbose banner (`[n/N] ...`). -- `update_stage(progress, message=None)` β€” records sub-stage progress (0.0–1.0); in verbose mode also prints an indented status line. -- `complete_stage(message=None)` β€” marks the stage 100% complete; in verbose mode prints stage duration and an optional completion message. -- `get_overall_progress()` β€” sums the weights of fully completed stages plus the weighted partial progress of the current stage. -- `get_eta()` β€” linearly extrapolates total time from elapsed time and overall progress (`elapsed / progress - elapsed`), formatted as `Xh Ym`, `Xm Ys`, or `Ys`. -- `_format_elapsed()` β€” internal helper producing `MM:SS` timestamps used in verbose headers/messages. - -### `ModuleProgressBar` - -A companion utility specifically for the "N modules to document" sub-task inside Stage 3 (Documentation Generation). It supports two mutually exclusive display modes selected at construction time: - -- **Non-verbose**: wraps `click.progressbar` (context-manager style, entered in `__init__` via `__enter__()` and exited via `finish()`), showing ETA and percentage. -- **Verbose**: suppresses the bar and instead prints one line per module via `update()`, indicating whether the module was `βœ“ (cached)` or `⟳ (generating)`. - -```python -bar = ModuleProgressBar(total_modules=12, verbose=False) -for module in modules: - ... # generate documentation for module - bar.update(module.name, cached=module.was_cached) -bar.finish() -``` - ---- - -## Architecture - -```mermaid -classDiagram - class CLILogger { - +bool verbose - +datetime start_time - +debug(message) - +info(message) - +success(message) - +warning(message) - +error(message) - +step(message, step, total) - +elapsed_time() str - } - - class ProgressTracker { - +int total_stages - +int current_stage - +float stage_progress - +float start_time - +bool verbose - +STAGE_WEIGHTS: dict - +STAGE_NAMES: dict - +start_stage(stage, description) - +update_stage(progress, message) - +complete_stage(message) - +get_overall_progress() float - +get_eta() str - -_format_elapsed() str - } - - class ModuleProgressBar { - +int total_modules - +int current_module - +bool verbose - +bar - +update(module_name, cached) - +finish() - } - - create_logger ..> CLILogger : constructs - - CLIDocumentationGenerator --> ProgressTracker : owns / drives stages - CLIDocumentationGenerator --> ModuleProgressBar : owns during Stage 3 - CLIDocumentationGenerator --> CLILogger : uses for output (via CLI command layer) -``` - ---- - -## Position Within the CLI Module - -`CLI_Utilities` is a leaf/support module in the CLI subsystem. It is depended upon by orchestration components but has no outgoing dependencies on other CLI or backend modules. - -```mermaid -graph TD - subgraph CLI - Config[CLI_Configuration] - GitMod[CLI_Git_Integration] - HTMLMod[CLI_HTML_Viewer] - DocGen[CLI_Documentation_Generation] - Utils[CLI_Utilities] - end - - DocGen -->|progress reporting| Utils - DocGen -->|reads settings| Config - DocGen -->|optional HTML step| HTMLMod - DocGen -.->|invoked separately by CLI commands| GitMod - - Utils --> click[[click library]] -``` - -**Consumers:** - -- **[CLI_Documentation_Generation](CLI_Documentation_Generation.md)** β€” `CLIDocumentationGenerator` instantiates a `ProgressTracker(total_stages=5, verbose=verbose)` in its constructor and drives it through all five stages (`start_stage` β†’ `update_stage` β†’ `complete_stage`) as it delegates to the backend `DocumentationGenerator` (see [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md)) for dependency analysis, module clustering, and per-module doc generation. `ModuleProgressBar` is used inside Stage 3 to report per-module completion (cached vs. freshly generated). -- **CLI command entry points** (Click commands, not shown in the provided component set) typically construct a `CLILogger` via `create_logger(verbose)` to print step-by-step status, warnings, and final success/error messages surrounding calls into `CLIDocumentationGenerator`, [CLI_Git_Integration](CLI_Git_Integration.md) (branch/commit operations), and [CLI_HTML_Viewer](CLI_HTML_Viewer.md). - ---- - -## Data & Control Flow - -### Stage-Weighted Progress Calculation - -```mermaid -flowchart TD - A["start_stage(n)"] --> B["stage_progress = 0.0"] - B --> C["update_stage(progress, message)"] - C --> D{"verbose?"} - D -->|yes| E["print timestamped message"] - D -->|no| F["no per-update output"] - C --> G["complete_stage()"] - G --> H["stage_progress = 1.0"] - H --> I["get_overall_progress"] - I --> J["sum(STAGE_WEIGHTS 1..current-1) + STAGE_WEIGHTS(current) * stage_progress"] - J --> K["get_eta"] - K --> L["remaining = elapsed / progress - elapsed"] -``` - -### Documentation Generation Run β€” Progress Touchpoints - -This sequence illustrates how `CLIDocumentationGenerator` (from [CLI_Documentation_Generation](CLI_Documentation_Generation.md)) drives `ProgressTracker` and `ModuleProgressBar` across the run. - -```mermaid -sequenceDiagram - participant CLI as CLI Command - participant Gen as CLIDocumentationGenerator - participant PT as ProgressTracker - participant Backend as DocumentationGenerator (backend) - participant MPB as ModuleProgressBar - - CLI->>Gen: generate() - Gen->>PT: start_stage(1, "Dependency Analysis") - Gen->>Backend: graph_builder.build_dependency_graph() - Backend-->>Gen: components, leaf_nodes - Gen->>PT: update_stage(...)/complete_stage() - - Gen->>PT: start_stage(2, "Module Clustering") - Gen->>Backend: cluster_modules(...) - Backend-->>Gen: module_tree - Gen->>PT: update_stage(...)/complete_stage() - - Gen->>PT: start_stage(3, "Documentation Generation") - Gen->>MPB: new ModuleProgressBar(total_modules) - loop for each module - Gen->>Backend: generate_module_documentation(module) - Backend-->>Gen: doc (cached or generated) - Gen->>MPB: update(module_name, cached) - end - Gen->>MPB: finish() - Gen->>PT: complete_stage() - - opt generate_html - Gen->>PT: start_stage(4, "HTML Generation") - Gen->>PT: complete_stage() - end - - Gen->>PT: start_stage(5, "Finalization") - Gen->>PT: complete_stage() - Gen-->>CLI: DocumentationJob -``` - -### Logger Output Levels - -```mermaid -flowchart LR - M[CLILogger method call] --> D{verbose enabled?} - D -->|debug & verbose=False| Skip[suppressed] - D -->|debug & verbose=True| Cyan[cyan dim, timestamped] - M --> Info[info: plain echo] - M --> Success[success: green 'βœ“'] - M --> Warn[warning: yellow '⚠️'] - M --> Err[error: red 'βœ—', stderr] - M --> Step[step: blue/bold, optional 'n/total' prefix] -``` - ---- - -## Design Notes - -- **No business logic**: Both `CLILogger` and `ProgressTracker`/`ModuleProgressBar` are intentionally free of any awareness of repositories, LLM configuration, or documentation content. This keeps them trivially testable and reusable across every CLI subcommand. -- **`click` as the only dependency**: All rendering is delegated to `click.secho`/`click.echo`/`click.progressbar`, ensuring consistent terminal behavior (color detection, TTY handling, Windows compatibility) without reimplementing terminal logic. -- **Verbose vs. non-verbose duality**: Every utility in this module exposes two output modes β€” a terse, bar/banner-based mode for normal runs and a detailed, timestamped, line-by-line mode for debugging (`--verbose` flag). This mirrors the same duality found in `CLIDocumentationGenerator._configure_backend_logging()`, which also branches on verbosity to control backend log levels via `ColoredFormatter` (see [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)). -- **ETA estimation is linear/naive**: `ProgressTracker.get_eta()` assumes uniform progress velocity (`total_estimated = elapsed / progress`). This is intentionally simple β€” sufficient for a CLI progress indicator, not intended for precise scheduling. -- **Stateless composability**: Because these classes carry no global or singleton state, multiple `CLILogger`/`ProgressTracker` instances can coexist (e.g., for parallel or nested CLI operations) without interference. - ---- - -## Related Modules - -- [CLI_Documentation_Generation](CLI_Documentation_Generation.md) β€” primary consumer; orchestrates the 5-stage pipeline using `ProgressTracker` and `ModuleProgressBar`, and produces the `DocumentationJob` result. -- [CLI_Configuration](CLI_Configuration.md) β€” supplies the `Configuration`/`LLMConfig` values that `CLIDocumentationGenerator` passes into the backend during the stages tracked by `ProgressTracker`. -- [CLI_Git_Integration](CLI_Git_Integration.md) β€” handles branch creation and commits around a documentation run; typically reports status through a `CLILogger` instance owned by the CLI command layer. -- [CLI_HTML_Viewer](CLI_HTML_Viewer.md) β€” invoked as the optional Stage 4 ("HTML Generation") tracked by `ProgressTracker`. -- [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) β€” the underlying `DocumentationGenerator` whose dependency analysis, clustering, and per-module generation steps are what `ProgressTracker`/`ModuleProgressBar` visualize. -- [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) β€” contains `ColoredFormatter`, the backend-log analog to this module's CLI-facing colored output. diff --git a/docs/Code_Analysis_Engine.md b/docs/Code_Analysis_Engine.md deleted file mode 100644 index 59577afe..00000000 --- a/docs/Code_Analysis_Engine.md +++ /dev/null @@ -1,76 +0,0 @@ -# Code Analysis Engine - -## Purpose - -The **Code_Analysis_Engine** subsystem is CodeWiki's static-analysis front half: everything that turns a raw source repository into a fully-resolved, language-agnostic dependency graph, ready for LLM-driven documentation generation. It answers the question *"what components exist in this codebase, and how do they depend on each other?"* β€” without invoking a single LLM call. - -The subsystem is organized as a three-layer pipeline: - -1. **[Language_Analyzers](Language_Analyzers.md)** β€” per-language "front ends" (Python `ast`, tree-sitter grammars for JS/TS, C-family, PHP) that parse individual source files into `Node` (component) and `CallRelationship` (edge) records. -2. **[Dependency_Analysis_Service](Dependency_Analysis_Service.md)** β€” the orchestration layer (`AnalysisService`, `RepoAnalyzer`, `CallGraphAnalyzer`) that discovers files, dispatches them to the right analyzer, resolves cross-file references, and filters out external/stdlib symbols. -3. **[Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)** β€” the shared data models (`Node`, `CallRelationship`, `Repository`, `AnalysisResult`) plus `DependencyParser` and `DependencyGraphBuilder`, which assemble the final project-wide dependency graph and select the "leaf" components that documentation generation starts from. - -The engine's single output β€” a dependency graph of components keyed by `"{relative_path}::{qualified_name}"` β€” is consumed by the [Documentation_Generation_Engine](Documentation_Generation_Engine.md). - -## Architecture - -```mermaid -flowchart TB - Repo["Source repository"] --> RA["RepoAnalyzer<br/>(file discovery, .gitignore filtering)"] - - subgraph DAS["Dependency_Analysis_Service"] - RA --> AS["AnalysisService"] - AS --> CGA["CallGraphAnalyzer"] - end - - subgraph LANG["Language_Analyzers"] - PY["Python Analyzer<br/>(native ast)"] - JSTS["JavaScript / TypeScript<br/>(tree-sitter)"] - CFAM["C-Family: C, C++, C#, Java, Kotlin<br/>(tree-sitter)"] - PHP["PHP Analyzer<br/>(tree-sitter)"] - end - - CGA -->|"routes by file extension"| PY & JSTS & CFAM & PHP - PY & JSTS & CFAM & PHP -->|"Node + CallRelationship lists"| CGA - - subgraph DAC["Dependency_Analyzer_Core"] - DP["DependencyParser<br/>(cross-file resolution)"] - DGB["DependencyGraphBuilder<br/>(graph assembly + leaf selection)"] - Models["Shared models:<br/>Node, CallRelationship,<br/>Repository, AnalysisResult"] - end - - CGA --> DP - DP --> DGB - Models -.->|"data contract"| LANG - Models -.->|"data contract"| DAS - - DGB -->|"dependency graph + leaf nodes"| Out["Documentation_Generation_Engine"] - - click AS "Dependency_Analysis_Service.md" - click CGA "Dependency_Analysis_Service.md" - click RA "Dependency_Analysis_Service.md" - click DP "Dependency_Analyzer_Core.md" - click DGB "Dependency_Analyzer_Core.md" - click Models "Dependency_Analyzer_Core.md" - click Out "Documentation_Generation_Engine.md" -``` - -Key design decisions: - -* **Best-effort, file-local parsing.** Individual analyzers never attempt compiler-grade resolution; they mark each reference `is_resolved=True/False` and defer repository-wide matching to `CallGraphAnalyzer`'s indexes. This keeps per-language analyzers simple and uniform. -* **One shared data contract.** All analyzers emit the same Pydantic models owned by `Dependency_Analyzer_Core`, so the rest of the system is language-agnostic. -* **Deterministic and LLM-free.** The whole subsystem is pure static analysis; its output is cached to `temp/dependency_graphs/` so repeated documentation runs skip re-parsing. - -## Modules - -| Module | Responsibility | Documentation | -|---|---|---| -| **Dependency_Analyzer_Core** | Shared `Node`/`CallRelationship` models, `DependencyParser`, `DependencyGraphBuilder`, leaf-node selection | [Dependency_Analyzer_Core.md](Dependency_Analyzer_Core.md) | -| **Dependency_Analysis_Service** | Repository discovery, per-language dispatch, cross-file symbol resolution, external-symbol filtering | [Dependency_Analysis_Service.md](Dependency_Analysis_Service.md) | -| **Language_Analyzers** | Per-language extraction of components and relationships (Python, JS/TS, C-family, PHP) | [Language_Analyzers.md](Language_Analyzers.md) | - -## Related Modules - -* [Documentation_Generation_Engine](Documentation_Generation_Engine.md) β€” consumes the dependency graph produced here to cluster modules and generate documentation. -* [Core_Config_&_Utils](Core_Config_&_Utils.md) β€” provides the `Config` object (include/exclude patterns, repo path) and `FileManager` used for graph caching. -* [User_Interfaces](User_Interfaces.md) β€” the CLI, web app, and MCP server that trigger analysis runs. diff --git a/docs/Core_Config_&_Utils.md b/docs/Core_Config_&_Utils.md deleted file mode 100644 index 0e1240df..00000000 --- a/docs/Core_Config_&_Utils.md +++ /dev/null @@ -1,170 +0,0 @@ -# Core Config & Utils - -## Introduction - -The **Core Config & Utils** module is the foundational, dependency-free layer of CodeWiki. It provides two small but critical building blocks that are consumed by virtually every other module in the system: - -1. **`Config`** (`codewiki/src/config.py`) β€” a single, canonical dataclass that captures all runtime configuration for a documentation-generation run: repository location, output paths, LLM provider/model selection, token budgets, and agent customization instructions. -2. **`FileManager`** (`codewiki/src/utils.py`) β€” a minimal, static-method utility class that centralizes all JSON/text file I/O so that the rest of the codebase never has to duplicate `open()`/`json.dump()` boilerplate. - -Because these components have no dependencies on any other CodeWiki module, they sit at the very bottom of the dependency graph and are safe to import from anywhere β€” CLI entry points, the FastAPI-based web frontend, the backend LLM/documentation services, and the dependency-analysis pipeline all import from this module directly or indirectly. - -## Why this module exists - -CodeWiki runs in two distinct contexts: - -- **CLI context** β€” a developer runs `codewiki` locally against a repo path, with credentials pulled from `~/.codewiki/config.json` + OS keyring (see [CLI](CLI.md)). -- **Web-app context** β€” a hosted service processes GitHub repository submissions asynchronously, with credentials from environment variables (see [Frontend_Web_App](Frontend_Web_App.md)). - -`Config` unifies these two invocation styles behind one dataclass and two factory constructors (`from_args` for CLI argparse namespaces, `from_cli` for programmatic CLI use), so that all downstream services (dependency analyzers, LLM backends, documentation generators) only ever need to reason about a single `Config` object, regardless of how the run was triggered. - -`FileManager` exists to keep file-system side effects consistent (UTF-8 encoding, pretty-printed JSON, directory auto-creation) across the many places in the system that persist intermediate artifacts β€” dependency graphs, module trees, generated docs, cache entries, job state, etc. - -## Architecture Overview - -```mermaid -graph TB - subgraph "Core Config & Utils (this module)" - Config["Config\n(dataclass)"] - FileManager["FileManager\n(static I/O helpers)"] - end - - subgraph "Entry Points" - CLI["CLI\n(ConfigManager, adapters)"] - FE["Frontend_Web_App\n(WebAppConfig, GitHubRepoProcessor)"] - end - - subgraph "Analysis & Generation Pipeline" - DAS["Dependency_Analysis_Service\n(AnalysisService, RepoAnalyzer)"] - DAC["Dependency_Analyzer_Core\n(DependencyParser, DependencyGraphBuilder)"] - BE["Backend_LLM_&_Documentation_Services\n(DocumentationGenerator, LLMBackend, PydanticAIBackend)"] - end - - subgraph "Session/Job State" - MCP["MCP_Session_Management\n(SessionStore, SessionWorkspace)"] - end - - CLI -->|"builds via from_args / from_cli"| Config - FE -->|"builds via from_cli"| Config - - Config --> DAS - Config --> DAC - Config --> BE - - FileManager -.->|"JSON/text persistence"| DAS - FileManager -.->|"JSON/text persistence"| DAC - FileManager -.->|"JSON/text persistence"| BE - FileManager -.->|"JSON/text persistence"| MCP - FileManager -.->|"JSON/text persistence"| CLI -``` - -### Data flow: from invocation to a fully-populated `Config` - -```mermaid -sequenceDiagram - participant User - participant CLI as CLI (argparse / ConfigManager) - participant WebApp as Frontend_Web_App (GitHubRepoProcessor) - participant Config - participant Pipeline as Dependency Analysis / LLM Backend - - alt CLI invocation - User->>CLI: codewiki --repo-path ... --model ... - CLI->>Config: Config.from_args(args) or Config.from_cli(...) - else Web submission - User->>WebApp: submit GitHub repo URL - WebApp->>Config: Config.from_cli(repo_path, output_dir, llm_*, ...) - end - Config-->>Pipeline: fully-populated Config instance - Pipeline->>Pipeline: read repo_path, dependency_graph_dir,\nmax_tokens, provider, agent_instructions... -``` - -## Sub-modules - -This module is intentionally small and cohesive; the two components below are documented together in a single reference rather than split into separate files, since they have no internal sub-structure of their own and are best understood as a pair. - -### `Config` β€” Runtime Configuration - -`Config` is a `@dataclass` holding everything a documentation-generation run needs: - -- **Paths**: `repo_path`, `output_dir`, `dependency_graph_dir`, `docs_dir`. -- **Decomposition control**: `max_depth` (hierarchical module-tree depth, default `MAX_DEPTH = 2`). -- **LLM selection**: `llm_base_url`, `llm_api_key`, `main_model`, `cluster_model`, `fallback_model`, and `provider` (one of `openai-compatible`, `atlas-cloud`, `anthropic`, `bedrock`, `azure-openai`), plus provider-specific fields `aws_region`, `api_version`, `azure_deployment`. -- **Token budgets**: `max_tokens`, `max_token_per_module`, `max_token_per_leaf_module` β€” these bound how much content is generated per LLM call and per module in the documentation tree. -- **Prompt caching**: `prompt_caching` flag, consumed by [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md)'s `CachingOpenAIModel` to decide whether to inject `cache_control` breakpoints. -- **Customization**: `agent_instructions` β€” an optional dict surfaced through convenience properties (`include_patterns`, `exclude_patterns`, `focus_modules`, `doc_type`, `custom_instructions`) and the `get_prompt_addition()` method, which renders these into natural-language instructions appended to LLM prompts. This dict is typically populated by `AgentInstructions` in the [CLI](CLI.md) module's `codewiki/cli/models/config.py`. -- **Repo hygiene**: `use_gitignore` β€” passed through to `RepoAnalyzer`/`GitIgnoreFilter` in the [Dependency_Analysis_Service](Dependency_Analysis_Service.md) to decide whether `.gitignore` rules are applied before analysis. - -Two module-level helpers manage a global CLI/web-app switch: - -- `set_cli_context(enabled)` / `is_cli_context()` β€” a process-wide flag letting shared code (e.g., credential loading) branch between reading `~/.codewiki/config.json` + keyring (CLI) versus environment variables (web app), without threading a context object through every call. - -Module-level constants (`OUTPUT_BASE_DIR`, `DEPENDENCY_GRAPHS_DIR`, `DOCS_DIR`, `FIRST_MODULE_TREE_FILENAME`, `MODULE_TREE_FILENAME`, `OVERVIEW_FILENAME`, default token limits, default model names via `MAIN_MODEL`/`FALLBACK_MODEL_1`/`CLUSTER_MODEL`, and `LLM_BASE_URL`/`LLM_API_KEY` env-var defaults) define the system-wide defaults referenced by both CLI and web-app configuration builders. - -#### Construction paths - -```mermaid -graph LR - A["argparse.Namespace\n(CLI script args)"] -->|"Config.from_args"| C[Config] - B["Explicit params\n(repo_path, output_dir,\nllm_base_url, model names,\nprovider, agent_instructions, ...)"] -->|"Config.from_cli"| C - C --> D["Consumed by:\nRepoAnalyzer, AnalysisService,\nDependencyGraphBuilder,\nLLMBackend / PydanticAIBackend / CawBackend,\nDocumentationGenerator"] -``` - -- **`Config.from_args(args)`**: derives a sanitized `docs_dir` from the repo folder name and uses global env-var-derived defaults for LLM settings. Used by the legacy/simple CLI code path. -- **`Config.from_cli(...)`**: the richer constructor used by [CLI](CLI.md)'s `ConfigManager`/`CLIDocumentationGenerator` and by [Frontend_Web_App](Frontend_Web_App.md)'s `GitHubRepoProcessor`/`BackgroundWorker`. It accepts explicit provider, token-budget, and `agent_instructions` parameters and lays out a `temp/` working directory under `output_dir` for intermediate dependency-graph artifacts, keeping the user-facing `docs_dir` separate and clean. - -### `FileManager` β€” Static File I/O Helpers - -`FileManager` (and its module-level singleton instance `file_manager`) provides five static methods, all consistently using UTF-8 encoding: - -| Method | Purpose | -|---|---| -| `ensure_directory(path)` | `os.makedirs(path, exist_ok=True)` β€” idempotent directory creation | -| `save_json(data, filepath)` | Pretty-printed (`indent=4`), non-ASCII-safe JSON write | -| `load_json(filepath)` | Returns parsed JSON, or `None` if the file doesn't exist (graceful missing-file handling) | -| `save_text(content, filepath)` | Plain UTF-8 text write | -| `load_text(filepath)` | Plain UTF-8 text read | - -Because it has no state and no external dependencies, `FileManager` is used as a shared utility across nearly every other module: - -- [Dependency_Analysis_Service](Dependency_Analysis_Service.md) and [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) use it to persist `module_tree.json`, `first_module_tree.json`, and dependency-graph JSON artifacts under `Config.dependency_graph_dir`. -- [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md)'s `DocumentationGenerator` uses it to write generated Markdown files (e.g., `overview.md`) into `Config.docs_dir`. -- [MCP_Session_Management](MCP_Session_Management.md) and [Frontend_Web_App](Frontend_Web_App.md) rely on the same JSON helpers for session/job state and cache persistence. -- [CLI](CLI.md)'s `ConfigManager` uses the same load/save JSON pattern (conceptually) for `~/.codewiki/config.json`. - -## How this module fits into the overall system - -```mermaid -graph TD - subgraph Consumers - CLI["CLI"] - FE["Frontend_Web_App"] - MCP["MCP_Session_Management"] - BE["Backend_LLM_&_Documentation_Services"] - DAS["Dependency_Analysis_Service"] - DAC["Dependency_Analyzer_Core"] - LANG["Language_Analyzers"] - end - - Core["Core_Config_&_Utils\n(Config, FileManager)"] - - CLI --> Core - FE --> Core - MCP --> Core - BE --> Core - DAS --> Core - DAC --> Core - LANG -.-> DAS - - Core:::base - classDef base fill:#f9f2c4,stroke:#b8a600; -``` - -Because neither `Config` nor `FileManager` import from any other CodeWiki module, this module has **zero internal dependencies** β€” it is purely a foundation layer. All architectural detail about *how* `Config` values are produced from user input, or *how* file artifacts are consumed downstream, lives in the respective consumer module docs: - -- [CLI](CLI.md) β€” builds `Config` from command-line arguments and manages persistent user configuration (`ConfigManager`), credentials, and progress reporting. -- [Frontend_Web_App](Frontend_Web_App.md) β€” builds `Config` per submitted GitHub repository and drives background job processing. -- [MCP_Session_Management](MCP_Session_Management.md) β€” manages session/workspace state for the MCP server, persisting state via JSON. -- [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) β€” consumes `Config`'s LLM/provider/token settings to drive documentation generation. -- [Dependency_Analysis_Service](Dependency_Analysis_Service.md) and [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) β€” consume `Config`'s repo/output paths and `use_gitignore` flag, and use `FileManager` to persist dependency graphs and module trees. -- [Language_Analyzers](Language_Analyzers.md) β€” per-language AST analyzers invoked by the dependency analysis service. diff --git a/docs/Dependency_Analysis_Service.md b/docs/Dependency_Analysis_Service.md deleted file mode 100644 index dc8ae3f8..00000000 --- a/docs/Dependency_Analysis_Service.md +++ /dev/null @@ -1,270 +0,0 @@ -# Dependency Analysis Service - -## Purpose - -The **Dependency Analysis Service** is the orchestration layer that turns a raw repository (local folder or a -GitHub URL) into a structured, language-aware **call graph**: a set of `Node` objects (functions, methods, -classes, ...) and `CallRelationship` edges between them. It is the entry point used by higher-level components -β€”most notably `DependencyParser` in [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) and the -[Backend_LLM_&_Documentation_Services](Backend_LLM_%26_Documentation_Services.md) documentation pipelineβ€”to -obtain the data that ultimately feeds LLM-driven documentation generation. - -The module has three responsibilities, each owned by one component: - -| Component | File | Responsibility | -|---|---|---| -| `AnalysisService` | `analysis/analysis_service.py` | Top-level orchestrator: clone/locate a repo, drive structure analysis, drive call-graph analysis, assemble the final `AnalysisResult`, and clean up temporary state. | -| `RepoAnalyzer` / `GitIgnoreFilter` | `analysis/repo_analyzer.py` | Walk the file system, build a filtered file tree (include/exclude glob patterns + Git ignore semantics), and compute summary statistics. | -| `CallGraphAnalyzer` | `analysis/call_graph_analyzer.py` | Dispatch each discovered source file to the appropriate per-language analyzer (see [Language_Analyzers](Language_Analyzers.md)), collect functions/relationships, resolve cross-file/cross-language calls, and produce visualization-ready data. | - -## Architecture Overview - -```mermaid -flowchart TB - subgraph Consumers - DP["DependencyParser<br/>(Dependency_Analyzer_Core)"] - DG["DocumentationGenerator<br/>(Backend_LLM_&_Documentation_Services)"] - end - - subgraph DAS["Dependency Analysis Service"] - AS["AnalysisService<br/>(orchestrator)"] - RA["RepoAnalyzer / GitIgnoreFilter<br/>(file tree + filtering)"] - CGA["CallGraphAnalyzer<br/>(call graph construction)"] - end - - subgraph LA["Language_Analyzers"] - PY["PythonASTAnalyzer"] - JS["TreeSitterJSAnalyzer / TS"] - JVM["Java / Kotlin / C# analyzers"] - CFAM["C / C++ analyzers"] - PHP["PHP analyzer"] - end - - Cloning["cloning.py<br/>clone_repository / parse_github_url"] - - DP --> AS - DG -.-> DP - AS --> Cloning - AS --> RA - AS --> CGA - CGA --> PY - CGA --> JS - CGA --> JVM - CGA --> CFAM - CGA --> PHP - - AS --> Result["AnalysisResult<br/>(Dependency_Analyzer_Core models)"] -``` - -## Data Flow: Full Repository Analysis - -`AnalysisService.analyze_repository_full` is the richest entry point. It performs cloning, structure discovery, -call-graph construction, and packages everything into an `AnalysisResult` (defined in -[Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)). - -```mermaid -sequenceDiagram - participant Caller - participant AS as AnalysisService - participant Clone as cloning.py - participant RA as RepoAnalyzer - participant CGA as CallGraphAnalyzer - participant LangA as Language Analyzer - - Caller->>AS: analyze_repository_full(github_url) - AS->>Clone: clone_repository(github_url) - Clone-->>AS: temp_dir - AS->>RA: analyze_repository_structure(temp_dir) - RA-->>AS: file_tree + summary - AS->>CGA: extract_code_files(file_tree) - CGA-->>AS: code_files (filtered by extension) - AS->>CGA: analyze_code_files(code_files, temp_dir) - loop for each source file - CGA->>LangA: analyze_<language>_file(path, content) - LangA-->>CGA: (functions, relationships) - end - CGA->>CGA: resolve_call_relationships() - CGA->>CGA: deduplicate_relationships() - CGA-->>AS: functions, relationships, visualization - AS->>AS: read README, build Repository + AnalysisResult - AS->>Clone: cleanup_repository(temp_dir) - AS-->>Caller: AnalysisResult -``` - -## Component Details - -### `AnalysisService` - -Central faΓ§ade exposing three analysis modes: - -- **`analyze_repository_full(github_url, ...)`** β€” clones a remote repository, runs structure + call-graph - analysis, reads the README, and returns a fully populated `AnalysisResult` (functions, relationships, file - tree, summary, Cytoscape visualization data). Cleans up the temporary clone directory afterward (also - tracked in `_temp_directories` and cleaned via `cleanup_all()` / `__del__` as a safety net). -- **`analyze_repository_structure_only(github_url, ...)`** β€” lightweight variant that skips call-graph - generation, useful for quick previews of repository layout. -- **`analyze_local_repository(repo_path, ...)`** β€” analyzes a folder already present on disk (no cloning), - used for local/offline workflows; returns a simplified dict (`nodes`, `relationships`, `summary`) rather - than a full `AnalysisResult`. - -Internally it composes a `RepoAnalyzer` (structure) and a `CallGraphAnalyzer` (call graph), and delegates -repository acquisition to `cloning.py` helpers (`clone_repository`, `cleanup_repository`, `parse_github_url`). -It also filters files down to the set of currently supported languages (Python, JavaScript, TypeScript, Java, -C#, C, C++, PHP, Kotlin) before invoking the call-graph analyzer. - -Two module-level functions, `analyze_repository` and `analyze_repository_structure_only`, are kept as -backward-compatible wrappers around a freshly constructed `AnalysisService`. - -```mermaid -classDiagram - class AnalysisService { - +call_graph_analyzer: CallGraphAnalyzer - +analyze_local_repository(repo_path, max_files, languages, use_gitignore) - +analyze_repository_full(github_url, include_patterns, exclude_patterns, use_gitignore) AnalysisResult - +analyze_repository_structure_only(github_url, ...) Dict - -_clone_repository(github_url) str - -_analyze_structure(repo_dir, ...) Dict - -_analyze_call_graph(file_tree, repo_dir) Dict - -_filter_supported_languages(code_files) List - -_cleanup_repository(temp_dir) - +cleanup_all() - } - class RepoAnalyzer - class CallGraphAnalyzer - AnalysisService --> RepoAnalyzer : uses - AnalysisService --> CallGraphAnalyzer : uses -``` - -### `RepoAnalyzer` and `GitIgnoreFilter` - -`RepoAnalyzer.analyze_repository_structure(repo_dir)` recursively walks a directory into a nested `file_tree` -dict (`type`, `name`, `path`, `extension`/`children`), applying: - -- **Include patterns** (`fnmatch`-style globs) β€” if provided, they *replace* the defaults - (`DEFAULT_INCLUDE_PATTERNS`); otherwise all files are eligible for inclusion. -- **Exclude patterns** β€” merged with `DEFAULT_IGNORE_PATTERNS`; matched against full relative path, filename, - and path segments. -- **Git ignore semantics** via `GitIgnoreFilter`, which prefers shelling out to `git ls-files --others - --ignored --exclude-standard` (so nested `.gitignore` files, global excludes, and tracked-file rules behave - exactly like Git) and falls back to a `pathspec`-based scan of every `.gitignore` file in the tree when Git - is unavailable or the folder isn't a Git worktree. - -Symlinks and paths that resolve outside the repository root are rejected defensively while building the tree. -The result also includes a summary (`total_files`, `total_size_kb`). - -```mermaid -flowchart LR - Start["analyze_repository_structure(repo_dir)"] --> Filter["Build GitIgnoreFilter\n(git ls-files or pathspec fallback)"] - Filter --> Walk["Recursively walk directory"] - Walk --> Exclude{"_should_exclude_path?\n(exclude patterns / gitignore / symlink)"} - Exclude -- yes --> Skip["Drop node"] - Exclude -- no --> Include{"file? _should_include_file?"} - Include -- file & matches --> Leaf["Add file node"] - Include -- directory --> Recurse["Recurse into children"] - Leaf --> Tree["file_tree"] - Recurse --> Tree - Tree --> Summary["total_files / total_size_kb"] -``` - -### `CallGraphAnalyzer` - -The multi-language orchestrator. Given a list of code files (already filtered to supported extensions via -`extract_code_files`), it: - -1. **Routes ambiguous `.h` headers** (`_route_contextual_headers`) to either C or C++ based on content signals - (namespaces, classes, templates, `::`, or known C++ standard headers) and repository composition. -2. **Collects Python module names** up front (`_collect_python_modules`) to support accurate project-vs-external - import classification later. -3. **Dispatches each file** to the language-specific analyzer function based on `file_info["language"]`, - delegating to the implementations documented in [Language_Analyzers](Language_Analyzers.md): - - `python` β†’ `analyzers/python.py::analyze_python_file` - - `javascript` / `typescript` β†’ tree-sitter analyzers in `analyzers/javascript.py` / `typescript.py` - - `java`, `kotlin`, `csharp`, `c`, `cpp`, `php` β†’ respective tree-sitter analyzers - Each file is analyzed under a 30-second timeout guard (`timeout` context manager, POSIX `SIGALRM`-based, - no-op on Windows) so a pathological file cannot stall the whole run. -4. **Resolves call relationships** (`_resolve_call_relationships`): builds global and per-language exact/ - simple-name lookup indexes (`_build_resolution_indexes`) from `id`, `component_id`, `qualified_name`, and - `name`, then attempts to match each unresolved `CallRelationship.callee` β€” preferring matches within the - caller's own language, falling back to language-qualified/simple-name matching, and finally dropping - relationships that are provably external (standard library calls, C/C++ macros, or third-party - package/module calls) via `is_external_symbol`/`is_macro_name` and dotted-package/module heuristics. -5. **Deduplicates** relationships on `(caller, callee)` pairs. -6. **Generates visualization data**: a Cytoscape.js-compatible `{elements: [...]}` structure with per-language - CSS classes (`lang-python`, `lang-cpp`, ...) and node/edge classification, plus a resolution summary - (`total_nodes`, `total_edges`, `unresolved_calls`). - -It also exposes `generate_llm_format()` (a compact, LLM-friendly functions/relationships view) and -`_select_most_connected_nodes(target_count)` (degree-centrality-based pruning for very large graphs). - -```mermaid -flowchart TB - Files["code_files (filtered by language)"] --> Route["_route_contextual_headers\n(.h -> c/cpp)"] - Route --> PyMods["_collect_python_modules"] - PyMods --> Loop["For each file: _analyze_code_file\n(30s timeout guard)"] - Loop -->|python| PyA["analyzers.python"] - Loop -->|js/ts| JsA["analyzers.javascript / typescript"] - Loop -->|java/kotlin/csharp| JvmA["analyzers.java / kotlin / csharp"] - Loop -->|c/cpp| CA["analyzers.c / cpp"] - Loop -->|php| PhpA["analyzers.php"] - PyA & JsA & JvmA & CA & PhpA --> Collect["functions{} + call_relationships[]"] - Collect --> Resolve["_resolve_call_relationships\n(exact/simple name indexes,\nlanguage-aware, external filtering)"] - Resolve --> Dedup["_deduplicate_relationships"] - Dedup --> Viz["_generate_visualization_data\n(Cytoscape elements)"] - Viz --> Out["{call_graph, functions, relationships, visualization}"] -``` - -## Key Data Structures - -The service produces/consumes model types defined in -[Dependency_Analyzer_Core](Dependency_Analyzer_Core.md#models): - -- **`Node`** β€” a single code component (function, method, class, ...) with identity (`id`, `component_id`, - `qualified_name`), location (`file_path`, `relative_path`, `start_line`/`end_line`), documentation - (`docstring`), and its outgoing `depends_on` set. -- **`CallRelationship`** β€” a directed edge `caller -> callee`, with `call_line` and an `is_resolved` flag set - once `CallGraphAnalyzer` matches the callee to a concrete `Node`. -- **`Repository`** β€” metadata about the analyzed repo (`url`, `name`, `clone_path`, `analysis_id`). -- **`AnalysisResult`** β€” the full output bundle: `repository`, `functions` (list of `Node`), `relationships` - (list of `CallRelationship`), `file_tree`, `summary`, `visualization`, and optional `readme_content`. - -## Position in the Overall System - -```mermaid -flowchart LR - User["End user / API request"] --> DG["DocumentationGenerator<br/>(Backend_LLM_&_Documentation_Services)"] - DG --> DP["DependencyParser + DependencyGraphBuilder<br/>(Dependency_Analyzer_Core)"] - DP --> DAS["Dependency Analysis Service<br/>(this module)"] - DAS --> LA["Language_Analyzers"] - DAS -->|Node / CallRelationship models| DP - DP -->|leaf-node components + graph| DG - DG -->|documentation content| FE["Frontend_Web_App / CLI"] -``` - -- **[Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)** consumes this service directly: - `DependencyParser.parse_repository()` instantiates an `AnalysisService`, calls its private - `_analyze_structure` / `_analyze_call_graph` helpers, and converts the resulting functions/relationships - dicts into `Node` objects with `depends_on` edges, which `DependencyGraphBuilder` then turns into a - traversable dependency graph and a set of "leaf" components. -- **[Language_Analyzers](Language_Analyzers.md)** supplies every per-language `analyze_*_file` function that - `CallGraphAnalyzer` dispatches to; this module is language-agnostic and treats each analyzer as a pluggable - strategy returning `(functions, relationships[, extra])`. -- **[Backend_LLM_&_Documentation_Services](Backend_LLM_%26_Documentation_Services.md)** sits above - `Dependency_Analyzer_Core` and uses the resulting component graph as the substrate for LLM-driven - documentation generation (see `DocumentationGenerator`). -- Repository acquisition (`git clone`, URL parsing) is handled by `analysis/cloning.py`, a small internal - helper module used exclusively by `AnalysisService`. - -## Design Notes - -- **Fail-safe cleanup**: every cloning path is wrapped in try/except blocks that clean up the temporary - directory on failure, and `AnalysisService` also tracks all created temp dirs for a final `cleanup_all()` / - `__del__` safety net. -- **Security-conscious file reads**: file content and README lookups go through `safe_open_text` / - `assert_safe_path` to guard against path traversal outside the repository root. -- **Language extensibility**: adding a new language mainly requires (a) a new `analyze_<lang>_file` function - in [Language_Analyzers](Language_Analyzers.md), (b) a dispatch branch in - `CallGraphAnalyzer._analyze_code_file`, and (c) adding the language to - `AnalysisService._filter_supported_languages` / `_get_supported_languages`. -- **Resolution favors precision over recall**: relationships that cannot be confidently resolved to a known - project `Node` β€” and are provably external (stdlib, macros, third-party imports) β€” are dropped rather than - kept as noisy unresolved edges, keeping the resulting call graph focused on in-repository architecture. diff --git a/docs/Dependency_Analyzer_Core.md b/docs/Dependency_Analyzer_Core.md deleted file mode 100644 index f9dee7f9..00000000 --- a/docs/Dependency_Analyzer_Core.md +++ /dev/null @@ -1,107 +0,0 @@ -# Dependency Analyzer Core - -## Purpose - -`Dependency_Analyzer_Core` is the structural backbone of CodeWiki's static-analysis pipeline. It defines the **shared data models** (`Node`, `CallRelationship`, `Repository`, `AnalysisResult`, `NodeSelection`) used across the whole dependency-analysis subsystem, and provides the **orchestration layer** that turns raw, language-specific analysis output into a normalized dependency graph ready for hierarchical documentation generation. - -Concretely, this module is responsible for: - -- Driving a full-repository parse via `DependencyParser`, converting the output of [Dependency_Analysis_Service](Dependency_Analysis_Service.md) into a unified map of `Node` objects keyed by component id. -- Building and persisting the dependency graph, and computing the set of "leaf" components (via `DependencyGraphBuilder`) that seed the bottom-up, hierarchical documentation process used by [Backend_LLM_&_Documentation_Services](Backend_LLM_%26_Documentation_Services.md). -- Defining the canonical Pydantic models (`Node`, `CallRelationship`, `Repository`, `AnalysisResult`, `NodeSelection`) shared by nearly every other backend module β€” the analysis service, the language analyzers, and the documentation generator all read/write these types. -- Supplying a small logging utility (`ColoredFormatter`) used to make CLI/console output readable during long-running analysis jobs. - -This module sits **below** [Dependency_Analysis_Service](Dependency_Analysis_Service.md) and the [Language_Analyzers](Language_Analyzers.md) in the sense that it consumes their raw output, but **above** them architecturally in that it defines the data contracts (`Node`, `CallRelationship`, `Repository`) that those services must produce. It is, in turn, consumed by [Backend_LLM_&_Documentation_Services](Backend_LLM_%26_Documentation_Services.md), which uses the components/leaf-nodes produced here to drive hierarchical LLM-based documentation generation, and by [Core_Config_&_Utils](Core_Config_%26_Utils.md), which supplies the `Config` object consumed by `DependencyGraphBuilder`. - -## Architecture Overview - -```mermaid -flowchart TB - subgraph Callers - DG[DocumentationGenerator<br/>Backend_LLM_&_Documentation_Services] - end - - subgraph Dependency_Analyzer_Core["Dependency_Analyzer_Core"] - DGB[DependencyGraphBuilder] - DP[DependencyParser] - TS[topo_sort helpers<br/>build_graph_from_components / get_leaf_nodes] - LS[leaf_selection helpers<br/>compute_valid_leaf_types / filter_leaf_nodes] - MC[models/core.py<br/>Node, CallRelationship, Repository] - MA[models/analysis.py<br/>AnalysisResult, NodeSelection] - LC[utils/logging_config.py<br/>ColoredFormatter] - end - - subgraph External["External Modules"] - AS[AnalysisService<br/>Dependency_Analysis_Service] - LA[Language Analyzers<br/>Language_Analyzers] - CFG[Config / FileManager<br/>Core_Config_&_Utils] - end - - DG -->|"build_dependency_graph()"| DGB - DGB --> DP - DGB --> TS - DGB --> LS - DGB --> CFG - DP --> AS - AS --> LA - AS -.produces.-> MC - AS -.produces.-> MA - DP -.builds.-> MC - TS -.consumes.-> MC - LS -.consumes.-> MC - - style Dependency_Analyzer_Core fill:#eef6ff,stroke:#3366cc -``` - -## Sub-modules - -| Sub-module | Description | Documentation | -|---|---|---| -| Parsing & Graph Building | Turns raw multi-language analysis results into `Node` maps, builds the dependency graph, resolves cycles, and selects the leaf components that seed hierarchical documentation. | [Dependency_Analyzer_Core_parsing.md](Dependency_Analyzer_Core_parsing.md) | -| Data Models | The Pydantic model layer (`Node`, `CallRelationship`, `Repository`, `AnalysisResult`, `NodeSelection`) shared across the dependency-analysis subsystem. | [Dependency_Analyzer_Core_models.md](Dependency_Analyzer_Core_models.md) | - -### Logging Utility - -`codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter` is a small, standalone `logging.Formatter` subclass used to colorize console output (log level, timestamp) for readability during CLI/analysis runs. It is applied via `setup_logging()` / `setup_module_logging()` helpers in the same file and has no dependencies on the rest of the module β€” it is documented here directly rather than as a separate sub-module. - -```mermaid -classDiagram - class ColoredFormatter { - +COLORS: dict - +COMPONENT_COLORS: dict - +format(record) str - } - logging.Formatter <|-- ColoredFormatter -``` - -## How This Module Fits Into the System - -```mermaid -sequenceDiagram - participant DocGen as DocumentationGenerator - participant DGB as DependencyGraphBuilder - participant DP as DependencyParser - participant AS as AnalysisService - participant LA as Language Analyzers - participant Models as Node / CallRelationship / Repository - - DocGen->>DGB: build_dependency_graph() - DGB->>DP: parse_repository() - DP->>AS: _analyze_structure() / _analyze_call_graph() - AS->>LA: per-language AST/tree-sitter parsing - LA-->>AS: functions, relationships (dicts) - AS-->>DP: call_graph_result - DP->>Models: build Node objects, populate depends_on - DP-->>DGB: components: Dict[str, Node] - DGB->>DGB: build_graph_from_components / get_leaf_nodes / filter_leaf_nodes - DGB-->>DocGen: (components, leaf_nodes) -``` - -Downstream, `DocumentationGenerator` (see [Backend_LLM_&_Documentation_Services](Backend_LLM_%26_Documentation_Services.md)) uses the `components` map and `leaf_nodes` list to drive a bottom-up documentation pass: leaf components (typically classes/functions with no further internal dependencies) are documented first, then progressively rolled up into higher-level module documentation. - -## Key Design Notes - -- **Language-agnostic contract**: `Node` and `CallRelationship` are intentionally generic (string ids, sets of dependency ids) so that any of the [Language_Analyzers](Language_Analyzers.md) (Python, JS/TS, C-family, PHP) can populate them uniformly β€” `DependencyParser` never needs to know which language produced a given function dict. -- **Two ID reconciliation strategies**: `DependencyParser._build_components_from_analysis` reconciles caller/callee references both via an exact `component_id_mapping` and, as a fallback, by scanning components for name-only matches β€” this compensates for analyzers that don't always emit fully qualified callee ids. -- **Leaf-node heuristics**: `compute_valid_leaf_types` / `filter_leaf_nodes` (used by `DependencyGraphBuilder` and internally by the graph traversal) adapt to the codebase's style β€” OOP-heavy repositories restrict leaves to class/interface/struct types, while function-oriented or mixed-paradigm codebases (e.g. plain C, or C/C++ with minimal OOP) also allow free functions to qualify as leaves so that the resulting documentation tree stays meaningfully bounded in size. -- **Persistence**: `DependencyParser.save_dependency_graph` serializes the full component map (including `depends_on` sets converted to lists) to JSON, giving a durable, inspectable artifact of each analysis run under `Config.dependency_graph_dir`. diff --git a/docs/Dependency_Analyzer_Core_models.md b/docs/Dependency_Analyzer_Core_models.md deleted file mode 100644 index b13bf323..00000000 --- a/docs/Dependency_Analyzer_Core_models.md +++ /dev/null @@ -1,308 +0,0 @@ -# Dependency Analyzer Core Models - -## Introduction - -The **Dependency_Analyzer_Core_models** module defines the foundational Pydantic data models used throughout the CodeWiki dependency-analysis pipeline. It provides the canonical, strongly-typed representations for: - -- **Repository** β€” metadata about the analyzed source repository -- **Node** β€” a single code component (function, class, method, interface, etc.) discovered by language-specific analyzers -- **CallRelationship** β€” a directed edge representing a call/usage relationship between two `Node`s -- **AnalysisResult** β€” the aggregate output of a full repository analysis run -- **NodeSelection** β€” a user/consumer-facing selection of nodes for partial export or documentation generation - -These models act as the **shared data contract** between the language analyzers, the call-graph/dependency-graph builders, the analysis orchestration service, and downstream consumers such as the documentation generator and frontend/CLI layers. Because every other component in the dependency-analysis subsystem consumes or produces these models, this module has no internal business logic of its own β€” it is purely a schema/data-model layer, making it a stable, low-churn dependency for the rest of the system. - ---- - -## Module Location & Relationships - -This module is a child of [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md), sitting alongside its sibling [Dependency_Analyzer_Core_parsing](Dependency_Analyzer_Core_parsing.md) (which contains `DependencyParser` and `DependencyGraphBuilder`). - -```mermaid -graph TB - subgraph Dependency_Analyzer_Core["Dependency_Analyzer_Core"] - subgraph Models["Dependency_Analyzer_Core_models (this module)"] - Node["Node"] - CallRel["CallRelationship"] - Repo["Repository"] - AnalysisResult["AnalysisResult"] - NodeSelection["NodeSelection"] - end - subgraph Parsing["Dependency_Analyzer_Core_parsing"] - DP["DependencyParser"] - DGB["DependencyGraphBuilder"] - end - end - - LangAnalyzers["Language_Analyzers\n(Python/JS/TS/Java/C/C++/C#/PHP/Kotlin)"] - AnalysisSvc["Dependency_Analysis_Service\n(AnalysisService, CallGraphAnalyzer, RepoAnalyzer)"] - DocGen["Backend_LLM_&_Documentation_Services\n(DocumentationGenerator)"] - - LangAnalyzers -->|produces raw dicts| AnalysisSvc - AnalysisSvc -->|constructs| AnalysisResult - AnalysisResult -->|contains| Node - AnalysisResult -->|contains| CallRel - AnalysisResult -->|contains| Repo - DP -->|constructs| Node - DP -->|calls| AnalysisSvc - DGB -->|uses| DP - DGB -->|consumes| Node - NodeSelection -->|references ids of| Node - DocGen -->|consumes| AnalysisResult - DocGen -->|consumes| NodeSelection -``` - -See also: [Language_Analyzers](Language_Analyzers.md), [Dependency_Analysis_Service](Dependency_Analysis_Service.md), and [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) for the components that produce or consume these models. - ---- - -## Core Components - -### 1. `Node` (`models/core.py`) - -Represents a single analyzable code component (function, method, class, interface, struct, etc.) extracted by any of the language-specific analyzers. - -| Field | Type | Description | -|---|---|---| -| `id` | `str` | Globally unique identifier for the node (often `file_path::qualified_name`) | -| `name` | `str` | Simple/short name of the component | -| `component_type` | `str` | Kind of component (e.g., `function`, `method`, `class`) | -| `file_path` | `str` | Absolute path to the source file | -| `relative_path` | `str` | Path relative to repository root | -| `depends_on` | `Set[str]` | IDs of other `Node`s this node calls/depends on (populated from `CallRelationship`s) | -| `source_code` | `Optional[str]` | Raw source snippet for the component | -| `start_line` / `end_line` | `int` | Location within the file | -| `has_docstring` / `docstring` | `bool` / `str` | Documentation metadata | -| `parameters` | `Optional[List[str]]` | Function/method parameter names | -| `node_type` | `Optional[str]` | Finer-grained type (e.g., `class`, `interface`, `struct`, `enum`, `record`) | -| `base_classes` | `Optional[List[str]]` | Parent classes/interfaces, if applicable | -| `class_name` | `Optional[str]` | Enclosing class name (for methods) | -| `display_name` | `Optional[str]` | Human-friendly name for UI/docs | -| `component_id` | `Optional[str]` | Redundant/legacy identifier, mirrors `id` | -| `language` | `Optional[str]` | Source language (e.g., `python`, `java`) | -| `qualified_name` | `Optional[str]` | Fully qualified name (namespace/module aware) | - -**Method:** -- `get_display_name() -> str`: Returns `display_name` if set, otherwise falls back to `name`. Used by rendering layers (docs, HTML generator) to present a consistent human-readable label without needing to check for `None`. - -`Node.depends_on` is the backbone of dependency-graph traversal performed in [Dependency_Analyzer_Core_parsing](Dependency_Analyzer_Core_parsing.md) (`DependencyGraphBuilder.build_dependency_graph`, leaf-node computation, etc.). - -### 2. `CallRelationship` (`models/core.py`) - -Represents a directed call/usage edge between two nodes, as detected by the [Language_Analyzers](Language_Analyzers.md) and consolidated by `CallGraphAnalyzer` in the [Dependency_Analysis_Service](Dependency_Analysis_Service.md). - -| Field | Type | Description | -|---|---|---| -| `caller` | `str` | ID of the calling node | -| `callee` | `str` | ID (or name, if unresolved) of the called node | -| `call_line` | `Optional[int]` | Line number where the call occurs | -| `is_resolved` | `bool` | Whether `callee` was successfully matched to a known `Node.id` | - -Relationships are consumed by `DependencyParser._build_components_from_analysis` to populate each `Node.depends_on` set β€” resolving legacy/raw IDs into canonical component IDs, and falling back to name-matching when the direct ID lookup fails. - -### 3. `Repository` (`models/core.py`) - -Lightweight metadata describing the repository under analysis. - -| Field | Type | Description | -|---|---|---| -| `url` | `str` | Source URL (e.g., GitHub repo URL) | -| `name` | `str` | Repository name | -| `clone_path` | `str` | Local filesystem path where the repo was cloned/checked out | -| `analysis_id` | `str` | Unique identifier for this analysis run (typically `{owner}-{name}`) | - -Produced by `AnalysisService.analyze_repository_full` (in [Dependency_Analysis_Service](Dependency_Analysis_Service.md)) using data from `parse_github_url` and the cloning step, and embedded into `AnalysisResult.repository`. - -### 4. `AnalysisResult` (`models/analysis.py`) - -The top-level aggregate model returned by a **full repository analysis**. It composes `Repository`, `Node`, and `CallRelationship` together with supplementary metadata. - -| Field | Type | Description | -|---|---|---| -| `repository` | `Repository` | Metadata about the analyzed repo | -| `functions` | `List[Node]` | All discovered components (functions, classes, methods, etc.) | -| `relationships` | `List[CallRelationship]` | All discovered call/usage edges | -| `file_tree` | `Dict[str, Any]` | Hierarchical representation of the repository's files/directories | -| `summary` | `Dict[str, Any]` | Aggregate statistics (file counts, function counts, languages found, etc.) | -| `visualization` | `Dict[str, Any]` | Precomputed visualization payload (e.g., for graph rendering), defaults to `{}` | -| `readme_content` | `Optional[str]` | Raw contents of the repository's README file, if found | - -`AnalysisResult` is constructed exclusively inside `AnalysisService.analyze_repository_full` (see [Dependency_Analysis_Service](Dependency_Analysis_Service.md)) and subsequently consumed by downstream documentation generation (`DocumentationGenerator` in [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md)) and any API/CLI layer that needs a complete snapshot of the analysis. - -### 5. `NodeSelection` (`models/analysis.py`) - -A lightweight model representing a **user-driven subset** of nodes β€” e.g., for exporting only part of a dependency graph, or scoping documentation generation to specific components. - -| Field | Type | Description | -|---|---|---| -| `selected_nodes` | `List[str]` | IDs of `Node`s selected for export/processing (default: empty list) | -| `include_relationships` | `bool` | Whether to include `CallRelationship` edges between selected nodes (default: `True`) | -| `custom_names` | `Dict[str, str]` | Optional mapping of node ID β†’ user-supplied display name override | - -This model decouples the "full" analysis output (`AnalysisResult`) from partial/filtered views requested by consumers, without requiring changes to the core graph models. - ---- - -## Data Flow - -The diagram below shows how raw analyzer output flows through these models to become the final `AnalysisResult`, and how a subset can later be captured via `NodeSelection`. - -```mermaid -flowchart LR - A["Language Analyzers - python.py, java.py, javascript.py, ..."] -->|raw dicts: functions, relationships| B[CallGraphAnalyzer] - B --> C[AnalysisService._analyze_call_graph] - C -->|functions, relationships| D[AnalysisService.analyze_repository_full] - D -->|constructs| E((AnalysisResult)) - E --> F[Repository] - E --> G["List[Node]"] - E --> H["List[CallRelationship]"] - - C2[AnalysisService._analyze_structure] --> D - C2 --> I[file_tree] - I --> E - - subgraph ParserPath["DependencyParser (parsing submodule)"] - J[DependencyParser.parse_repository] --> K[_build_components_from_analysis] - K -->|constructs| G2["Dict[id, Node]"] - K -->|populates| L["Node.depends_on"] - end - - D -.->|also drives| J - - G2 --> M[DependencyGraphBuilder.build_dependency_graph] - M --> N[leaf_nodes / graph traversal] - - E --> O[NodeSelection] - O -->|selected_nodes reference| G -``` - ---- - -## Component Interaction: Building `Node.depends_on` - -`DependencyParser` (in [Dependency_Analyzer_Core_parsing](Dependency_Analyzer_Core_parsing.md)) is the primary consumer that transforms raw analysis dicts into strongly-typed `Node` objects and resolves relationships into the `depends_on` set. - -```mermaid -sequenceDiagram - participant DP as DependencyParser - participant AS as AnalysisService - participant CG as CallGraphAnalyzer - participant N as Node (model) - participant CR as CallRelationship (data) - - DP->>AS: _analyze_structure(repo_path) - AS-->>DP: file_tree, summary - DP->>AS: _analyze_call_graph(file_tree, repo_path) - AS->>CG: analyze_code_files(files) - CG-->>AS: functions[], relationships[] - AS-->>DP: call_graph_result{functions, relationships} - - loop for each function dict - DP->>N: Node(id=..., name=..., component_type=..., ...) - DP->>DP: components[id] = node - end - - loop for each relationship dict - DP->>DP: resolve caller_id / callee_id via component_id_mapping - DP->>N: components[caller_id].depends_on.add(callee_id) - end - - DP->>DP: save_dependency_graph(output_path) -``` - -Key resolution logic in `_build_components_from_analysis`: -1. Each function dict is mapped 1:1 to a `Node`, keyed by its `id` (with a legacy `file_path:name` alias also tracked in `component_id_mapping`). -2. Each `CallRelationship`-like dict's `caller`/`callee` values are resolved through `component_id_mapping`; if `callee` is not found by ID, a fallback name-match against existing `Node.name` values is attempted. -3. Successfully resolved edges are folded directly into `Node.depends_on` β€” meaning explicit `CallRelationship` objects are primarily used at the `AnalysisResult`/`AnalysisService` layer, while the parser's internal graph representation flattens them into the node's own dependency set for efficient graph traversal. - ---- - -## Model Relationships (Class Diagram) - -```mermaid -classDiagram - class Repository { - +str url - +str name - +str clone_path - +str analysis_id - } - - class Node { - +str id - +str name - +str component_type - +str file_path - +str relative_path - +Set~str~ depends_on - +Optional~str~ source_code - +int start_line - +int end_line - +bool has_docstring - +str docstring - +Optional~List~str~~ parameters - +Optional~str~ node_type - +Optional~List~str~~ base_classes - +Optional~str~ class_name - +Optional~str~ display_name - +Optional~str~ component_id - +Optional~str~ language - +Optional~str~ qualified_name - +get_display_name() str - } - - class CallRelationship { - +str caller - +str callee - +Optional~int~ call_line - +bool is_resolved - } - - class AnalysisResult { - +Repository repository - +List~Node~ functions - +List~CallRelationship~ relationships - +Dict file_tree - +Dict summary - +Dict visualization - +Optional~str~ readme_content - } - - class NodeSelection { - +List~str~ selected_nodes - +bool include_relationships - +Dict~str,str~ custom_names - } - - AnalysisResult "1" --> "1" Repository : repository - AnalysisResult "1" --> "*" Node : functions - AnalysisResult "1" --> "*" CallRelationship : relationships - CallRelationship "1" --> "1" Node : caller (by id) - CallRelationship "1" --> "1" Node : callee (by id) - Node "1" --> "*" Node : depends_on (by id) - NodeSelection "1" --> "*" Node : selected_nodes (by id) -``` - ---- - -## Usage Across the System - -| Consumer | How it uses these models | -|---|---| -| [Dependency_Analyzer_Core_parsing](Dependency_Analyzer_Core_parsing.md) β€” `DependencyParser` | Constructs `Node` instances from raw analyzer output; resolves `CallRelationship`-style dicts into `Node.depends_on`; serializes `Node`s to JSON via `save_dependency_graph` | -| [Dependency_Analyzer_Core_parsing](Dependency_Analyzer_Core_parsing.md) β€” `DependencyGraphBuilder` | Consumes the `Dict[str, Node]` produced by `DependencyParser` to build a traversable graph and compute leaf nodes for documentation scoping | -| [Dependency_Analysis_Service](Dependency_Analysis_Service.md) β€” `AnalysisService` | Constructs the full `AnalysisResult` (with `Repository`, `Node` list, `CallRelationship` list) from cloned repository analysis; also returns lighter-weight dicts for structure-only analysis | -| [Dependency_Analysis_Service](Dependency_Analysis_Service.md) β€” `CallGraphAnalyzer` | Produces the raw function/relationship dictionaries later hydrated into `Node`/`CallRelationship` | -| [Language_Analyzers](Language_Analyzers.md) (Python, JS/TS, C-family, PHP, Kotlin) | Emit language-specific raw component and call data that conforms to the shape expected by `Node`/`CallRelationship` construction | -| [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) β€” `DocumentationGenerator` | Consumes `AnalysisResult` (and `NodeSelection` for scoped/partial doc generation) to drive LLM-based documentation generation | -| [Frontend_Web_App](Frontend_Web_App.md) / CLI layers | Indirectly rely on the JSON-serialized form of these models (e.g., dependency graph JSON files, job statistics) for status reporting and visualization | - ---- - -## Design Notes - -- **Pydantic-based validation**: All models subclass `pydantic.BaseModel`, giving automatic validation, JSON (de)serialization, and default value handling β€” critical since data flows through multiple layers (analyzers β†’ service β†’ parser β†’ graph builder β†’ doc generator) often crossing process/file boundaries (e.g., `save_dependency_graph` writes JSON to disk). -- **`depends_on` as `Set[str]`**: Using a set avoids duplicate edges and enables efficient membership checks during graph traversal (used by `DependencyGraphBuilder` for leaf-node computation and cycle-safe traversal). -- **Loose coupling via IDs**: Relationships between models (`Node.depends_on`, `CallRelationship.caller/callee`, `NodeSelection.selected_nodes`) are expressed as string IDs rather than embedded object references, keeping the models serialization-friendly and avoiding circular references in JSON output. -- **Backward compatibility**: `Node.component_id` duplicates `Node.id` for legacy consumers, and `DependencyParser` maintains a `component_id_mapping` to bridge older `file_path:name`-style identifiers with the newer canonical `id` scheme. -- **Separation of concerns**: This module intentionally contains **no business logic** β€” parsing, graph-building, and orchestration logic live in [Dependency_Analyzer_Core_parsing](Dependency_Analyzer_Core_parsing.md) and [Dependency_Analysis_Service](Dependency_Analysis_Service.md), keeping the data contracts stable and independently testable. diff --git a/docs/Dependency_Analyzer_Core_parsing.md b/docs/Dependency_Analyzer_Core_parsing.md deleted file mode 100644 index 17cc610e..00000000 --- a/docs/Dependency_Analyzer_Core_parsing.md +++ /dev/null @@ -1,310 +0,0 @@ -# Dependency Analyzer Core: Parsing - -## Introduction - -The **Dependency Analyzer Core: Parsing** module is the orchestration layer that turns a raw source repository into a *dependency graph* of code components (functions, classes, methods, etc.) ready for downstream documentation generation. It sits at the boundary between low-level, language-specific static analysis (performed by the [Dependency_Analysis_Service](Dependency_Analysis_Service.md) and its [Language_Analyzers](Language_Analyzers.md)) and the higher-level clustering/LLM documentation pipeline (see [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md)). - -It has two responsibilities: - -1. **Parsing** (`DependencyParser` in `ast_parser.py`) β€” walk a repository, run structure + call-graph analysis, and normalize the results into a flat dictionary of typed `Node` objects with resolved `depends_on` edges. -2. **Graph building** (`DependencyGraphBuilder` in `dependency_graphs_builder.py`) β€” wrap the parser, persist the resulting graph to disk, and reduce the (typically huge) component graph down to a manageable set of **leaf nodes** that later drive bottom-up documentation generation. - -This module is a child of [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md), sitting alongside its sibling [Dependency_Analyzer_Core_models](Dependency_Analyzer_Core_models.md), which defines the `Node`, `CallRelationship`, `Repository`, and `AnalysisResult` data models consumed and produced here. - ---- - -## Module Position in the System - -```mermaid -graph TB - subgraph FE["Frontend / CLI Entry Points"] - CLI[CLI Adapter] - DG["DocumentationGenerator<br/>(Backend_LLM_&_Documentation_Services)"] - end - - subgraph THIS["Dependency_Analyzer_Core_parsing (this module)"] - DGB[DependencyGraphBuilder] - DP[DependencyParser] - end - - subgraph SVC["Dependency_Analysis_Service"] - AS[AnalysisService] - RA[RepoAnalyzer] - CGA[CallGraphAnalyzer] - end - - subgraph LANG["Language_Analyzers"] - PY[PythonASTAnalyzer] - TS[TreeSitter* Analyzers] - end - - subgraph MODELS["Dependency_Analyzer_Core_models"] - Node[Node] - CR[CallRelationship] - AR[AnalysisResult] - end - - subgraph SIB["Sibling helpers (Dependency_Analyzer_Core)"] - TOPO[topo_sort.py] - LEAF[leaf_selection.py] - end - - subgraph CFG["Core_Config_&_Utils"] - Config[Config] - FM[FileManager] - end - - CLI --> DG - DG -->|"build_dependency_graph()"| DGB - DGB -->|uses| Config - DGB -->|uses| FM - DGB --> DP - DP --> AS - AS --> RA - AS --> CGA - CGA --> LANG - LANG --> CR - DP -->|constructs| Node - DGB --> TOPO - DGB --> LEAF - DP -->|"components, leaf_nodes"| DG -``` - ---- - -## Component Overview - -### `DependencyParser` (`ast_parser.py`) - -`DependencyParser` is the entry point for turning a repository path into a dictionary of `Node` objects (`Dict[str, Node]`), keyed by a unique component id (e.g. `path/to/file.py::ClassName.method_name`). - -**Responsibilities:** - -- Accepts a `repo_path`, optional `include_patterns` / `exclude_patterns` file filters, and a `use_gitignore` flag. -- Delegates all heavy lifting (file discovery, filtering, AST/tree-sitter parsing per language) to an internal `AnalysisService` instance from [Dependency_Analysis_Service](Dependency_Analysis_Service.md). -- Normalizes the raw dict-based analysis output into strongly-typed `Node` instances (see [Dependency_Analyzer_Core_models](Dependency_Analyzer_Core_models.md)). -- Resolves caller β†’ callee relationships into each `Node.depends_on` set, using both exact component-id matches and a fallback by-name lookup. -- Persists the graph to JSON via `save_dependency_graph`. - -**Key methods:** - -| Method | Purpose | -|---|---| -| `__init__(repo_path, include_patterns, exclude_patterns, use_gitignore)` | Configure the parser and instantiate an `AnalysisService`. | -| `parse_repository(filtered_folders=None)` | Orchestrates structure analysis β†’ call-graph analysis β†’ component/edge construction. Returns `self.components`. | -| `_build_components_from_analysis(call_graph_result)` | Converts raw `functions`/`relationships` dicts into `Node` objects and populates `depends_on` edges. | -| `_determine_component_type(func_dict)` | Maps raw analyzer output to a normalized component type (`method`, `class`, `interface`, `function`, etc.). | -| `_file_to_module_path(file_path)` | Converts a file path into a dotted module path (used for module bookkeeping). | -| `save_dependency_graph(output_path)` | Serializes all components (with `depends_on` sets converted to lists) to a JSON file. | - -#### Parsing sequence - -```mermaid -sequenceDiagram - participant Caller as DependencyGraphBuilder - participant DP as DependencyParser - participant AS as AnalysisService - participant RA as RepoAnalyzer - participant CGA as CallGraphAnalyzer - participant LANG as Language Analyzers - - Caller->>DP: parse_repository(filtered_folders) - DP->>AS: _analyze_structure(repo_path, include, exclude, use_gitignore) - AS->>RA: analyze_repository_structure(repo_dir) - RA-->>AS: file_tree, summary - AS-->>DP: structure_result - - DP->>AS: _analyze_call_graph(file_tree, repo_path) - AS->>CGA: extract_code_files(file_tree) - CGA->>LANG: analyze per language (Python AST / Tree-sitter) - LANG-->>CGA: functions, relationships - CGA-->>AS: call_graph_result - AS-->>DP: call_graph_result - - DP->>DP: _build_components_from_analysis(call_graph_result) - Note over DP: Builds Node objects,<br/>resolves depends_on edges - DP-->>Caller: components: Dict[str, Node] -``` - -#### Component construction & relationship resolution - -`_build_components_from_analysis` performs two passes: - -1. **Node construction pass** β€” for every function/class entry returned by the call-graph analyzer, a `Node` (see [Dependency_Analyzer_Core_models](Dependency_Analyzer_Core_models.md)) is created with fields like `id`, `component_type`, `file_path`, `source_code`, `docstring`, `parameters`, `base_classes`, etc. A `component_id_mapping` is built to support both the canonical id and a legacy `file_path:name` id format. Module paths are also collected into `self.modules`. -2. **Relationship resolution pass** β€” for each `CallRelationship`-like dict (`caller`, `callee`, `is_resolved`), the parser resolves both ends to canonical component ids (falling back to a name-based scan of `self.components` if the callee id isn't directly found) and adds the callee id into the caller `Node.depends_on` set. - -```mermaid -flowchart LR - A[Raw functions list] --> B{For each function} - B --> C[Create Node] - C --> D[components dict] - C --> E[component_id_mapping] - C --> F[modules set] - - G[Raw relationships list] --> H{For each relationship} - H --> I[Resolve caller id via mapping] - H --> J[Resolve callee id via mapping<br/>or name fallback scan] - I --> K{caller found in components?} - J --> K - K -->|yes| L[Add callee to caller.depends_on] -``` - ---- - -### `DependencyGraphBuilder` (`dependency_graphs_builder.py`) - -`DependencyGraphBuilder` is a thin orchestration wrapper used directly by `DocumentationGenerator` (see [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md)). It wires together `DependencyParser`, disk persistence, and leaf-node computation to produce the two artifacts the documentation pipeline needs: the full `components` map and a curated list of `leaf_nodes`. - -**Key method β€” `build_dependency_graph()`:** - -1. Ensures the configured `dependency_graph_dir` exists (via `FileManager`, [Core_Config_&_Utils](Core_Config_&_Utils.md)). -2. Computes a sanitized output path `{repo_name}_dependency_graph.json` for the serialized graph. -3. Reads `include_patterns` / `exclude_patterns` / `use_gitignore` from `Config`. -4. Instantiates a `DependencyParser` and calls `parse_repository()` to get `components`. -5. Persists the graph via `parser.save_dependency_graph(...)`. -6. Builds an in-memory adjacency graph with `build_graph_from_components(components)` (from `topo_sort.py`). -7. Computes leaf nodes with `get_leaf_nodes(graph, components)`. -8. Filters leaf nodes down to valid types using `compute_valid_leaf_types` + `filter_leaf_nodes` (from `leaf_selection.py`), ensuring only real, well-typed components (classes/interfaces/structs, or functions in function-heavy codebases) are kept. -9. Returns `(components, keep_leaf_nodes)`. - -```mermaid -flowchart TD - A[build_dependency_graph] --> B[ensure_directory: dependency_graph_dir] - B --> C[Compute dependency_graph_path] - C --> D["DependencyParser(repo_path, include, exclude, use_gitignore)"] - D --> E["parser.parse_repository()"] - E --> F[components: Dict-str-Node] - F --> G["parser.save_dependency_graph(path)"] - F --> H["build_graph_from_components(components)"] - H --> I["get_leaf_nodes(graph, components)"] - I --> J["compute_valid_leaf_types(components)"] - J --> K["filter_leaf_nodes(leaf_nodes, components, valid_types)"] - K --> L["return (components, keep_leaf_nodes)"] -``` - -#### Why "leaf nodes" matter - -The documentation pipeline ([Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md)) processes the codebase bottom-up: it needs a manageable, semantically meaningful set of "atomic" components β€” classes, interfaces, structs, or (in function-heavy / non-OOP codebases) standalone functions β€” to seed clustering and per-module documentation generation. Leaf nodes are nodes in the dependency graph that nothing else depends on (i.e., not referenced as a dependency by any other node), representing top-level entry points of the dependency chain. `topo_sort.py` and `leaf_selection.py` (siblings within [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)) implement: - -- **Cycle resolution** β€” the raw call graph may contain cycles (e.g., mutual recursion); `get_leaf_nodes` first resolves cycles into a DAG. -- **Conciseness** β€” `__init__` methods are collapsed to their owning class name so constructors don't appear as separate leaves. -- **Leaf reduction** β€” if too many leaf nodes are found (`LEAF_REDUCTION_THRESHOLD`), nodes that are dependencies of others are pruned from the leaf set to keep it a manageable size. -- **Type filtering** β€” `compute_valid_leaf_types` decides whether standalone functions should be treated as valid leaves (e.g. for C-style procedural codebases) or whether only class/interface/struct-like types should count (`OOP_TYPES`), based on the ratio of OOP vs. function components in the repo. - ---- - -## Data Model Dependencies - -This module produces and consumes types defined in [Dependency_Analyzer_Core_models](Dependency_Analyzer_Core_models.md): - -- **`Node`** β€” the canonical in-memory representation of a parsed code component (function, method, class, etc.), including `depends_on: Set[str]` for outgoing dependency edges. -- **`CallRelationship`** β€” the raw caller/callee shape produced by language analyzers before being folded into `Node.depends_on`. -- **`Repository` / `AnalysisResult`** β€” used further upstream by `AnalysisService.analyze_repository_full` (see [Dependency_Analysis_Service](Dependency_Analysis_Service.md)), though `DependencyParser` itself only uses the lower-level `_analyze_structure` / `_analyze_call_graph` primitives rather than the full `AnalysisResult` wrapper. - -```mermaid -classDiagram - class Node { - +str id - +str name - +str component_type - +str file_path - +str relative_path - +Set~str~ depends_on - +Optional~str~ source_code - +int start_line - +int end_line - +bool has_docstring - +str docstring - +Optional~List~str~~ parameters - +Optional~str~ node_type - +Optional~List~str~~ base_classes - +Optional~str~ class_name - +Optional~str~ display_name - +Optional~str~ component_id - +get_display_name() str - } - - class CallRelationship { - +str caller - +str callee - +Optional~int~ call_line - +bool is_resolved - } - - class DependencyParser { - +str repo_path - +Dict~str,Node~ components - +Set~str~ modules - +AnalysisService analysis_service - +parse_repository(filtered_folders) Dict~str,Node~ - +save_dependency_graph(output_path) - } - - class DependencyGraphBuilder { - +Config config - +build_dependency_graph() tuple - } - - class AnalysisService { - <<Dependency_Analysis_Service>> - } - - DependencyGraphBuilder --> DependencyParser : creates and drives - DependencyParser --> Node : constructs - DependencyParser ..> CallRelationship : consumes as dicts - DependencyParser --> AnalysisService : delegates parsing -``` - ---- - -## Configuration & Utilities Used - -- **`Config`** (see [Core_Config_&_Utils](Core_Config_&_Utils.md)) supplies `repo_path`, `dependency_graph_dir`, `include_patterns`, `exclude_patterns`, and `use_gitignore` to `DependencyGraphBuilder`. -- **`FileManager`** (see [Core_Config_&_Utils](Core_Config_&_Utils.md)) is used by `DependencyGraphBuilder` to ensure output directories exist (JSON persistence of the graph itself is done directly by `DependencyParser.save_dependency_graph`, using standard file I/O rather than `FileManager`). - ---- - -## Typical Usage Flow (End-to-End) - -```mermaid -sequenceDiagram - participant DocGen as DocumentationGenerator - participant DGB as DependencyGraphBuilder - participant DP as DependencyParser - participant Topo as topo_sort.py - participant Leaf as leaf_selection.py - participant Disk as Filesystem (JSON) - - DocGen->>DGB: build_dependency_graph() - DGB->>DP: DependencyParser(repo_path, patterns, use_gitignore) - DGB->>DP: parse_repository() - DP-->>DGB: components: Dict[str, Node] - DGB->>DP: save_dependency_graph(path) - DP->>Disk: write {repo}_dependency_graph.json - DGB->>Topo: build_graph_from_components(components) - Topo-->>DGB: graph: Dict[str, Set[str]] - DGB->>Topo: get_leaf_nodes(graph, components) - Topo-->>DGB: leaf_nodes - DGB->>Leaf: compute_valid_leaf_types(components) - Leaf-->>DGB: valid_types - DGB->>Leaf: filter_leaf_nodes(leaf_nodes, components, valid_types) - Leaf-->>DGB: keep_leaf_nodes - DGB-->>DocGen: (components, keep_leaf_nodes) - Note over DocGen: Proceeds to module clustering<br/>and per-module LLM documentation -``` - -`DocumentationGenerator.run()` (in [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md)) calls `self.graph_builder.build_dependency_graph()` as its very first step, then uses the returned `components` and `leaf_nodes` to drive module clustering and bottom-up, per-module LLM documentation generation. - ---- - -## Summary - -| Aspect | Details | -|---|---| -| **Primary role** | Convert a raw repository into a normalized, typed dependency graph and extract a curated set of leaf components. | -| **Key classes** | `DependencyParser`, `DependencyGraphBuilder` | -| **Upstream dependency** | [Dependency_Analysis_Service](Dependency_Analysis_Service.md) (`AnalysisService`, `RepoAnalyzer`, `CallGraphAnalyzer`) and [Language_Analyzers](Language_Analyzers.md) for actual per-language parsing. | -| **Sibling dependency** | [Dependency_Analyzer_Core_models](Dependency_Analyzer_Core_models.md) for `Node`/`CallRelationship` types; `topo_sort.py` and `leaf_selection.py` helpers within [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) for graph traversal and leaf filtering. | -| **Downstream consumer** | [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) (`DocumentationGenerator`), which uses the produced `components`/`leaf_nodes` to drive clustering and documentation generation. | -| **Configuration source** | [Core_Config_&_Utils](Core_Config_&_Utils.md) (`Config`, `FileManager`). | -| **Persisted artifact** | `{sanitized_repo_name}_dependency_graph.json` under `Config.dependency_graph_dir`. | diff --git a/docs/Documentation_Generation_Engine.md b/docs/Documentation_Generation_Engine.md deleted file mode 100644 index 8c579b8d..00000000 --- a/docs/Documentation_Generation_Engine.md +++ /dev/null @@ -1,102 +0,0 @@ -# Documentation Generation Engine - -## Purpose - -The **Documentation_Generation_Engine** subsystem is CodeWiki's LLM-driven back half: it takes the dependency graph produced by the [Code_Analysis_Engine](Code_Analysis_Engine.md) and turns it into the finished documentation set β€” per-module Markdown files with validated Mermaid diagrams, parent-module overviews, and the repository-level `overview.md`. - -It consists of two tightly-coupled modules: - -1. **[Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md)** β€” the orchestration core. `DocumentationGenerator` drives the end-to-end flow (module clustering β†’ super-grouping β†’ leaf-first traversal β†’ parent overviews β†’ metadata/validation), while the `LLMBackend` abstraction provides two interchangeable execution engines: `PydanticAIBackend` (API-key based, via `pydantic-ai` with prompt-caching-aware OpenAI-compatible models) and `CawBackend` (subscription-based, driving the Claude Agent SDK / `caw` CLI). -2. **[Backend_Agent_Tools](Backend_Agent_Tools.md)** β€” the sandboxed tools handed to documentation agents: `EditTool` / `str_replace_editor` (file viewing and editing with built-in Mermaid diagram validation), the `CodeWikiDeps` shared context object, and the sub-module documentation spawner that lets an agent recursively decompose a large module into child modules at generation time. - -The engine works **bottom-up**: leaf modules are documented first by autonomous agents that read real source code through their tools; parent modules and the repository overview are then synthesized from their children's finished Markdown. - -## Architecture - -```mermaid -flowchart TB - In["Dependency graph + leaf nodes<br/>(from Code_Analysis_Engine)"] --> DG - - subgraph BLDS["Backend_LLM_&_Documentation_Services"] - DG["DocumentationGenerator"] - CL["cluster_modules +<br/>super_group_modules<br/>(LLM clustering passes)"] - BE["LLMBackend"] - PAI["PydanticAIBackend<br/>(API key, pydantic-ai)"] - CAW["CawBackend<br/>(subscription, Claude Agent SDK)"] - LS["CompatibleOpenAIModel /<br/>CachingOpenAIModel"] - - DG --> CL - DG --> BE - BE --> PAI - BE --> CAW - PAI --> LS - end - - subgraph TOOLS["Backend_Agent_Tools"] - DEPS["CodeWikiDeps<br/>(shared agent context)"] - EDIT["EditTool / str_replace_editor<br/>(file I/O + Mermaid validation)"] - SUB["generate_sub_module_documentation<br/>(recursive decomposition)"] - end - - PAI -->|"tool calls"| EDIT - PAI -->|"tool calls"| SUB - PAI --- DEPS - SUB -->|"inserts children into module_tree"| DG - - DG --> Out["module_tree.json + first_module_tree.json<br/>per-module *.md + overview.md<br/>metadata.json"] - - click DG "Backend_LLM_&_Documentation_Services.md" - click BE "Backend_LLM_&_Documentation_Services.md" - click PAI "Backend_LLM_&_Documentation_Services_pydantic_ai_backend.md" - click CAW "Backend_LLM_&_Documentation_Services_caw_backend.md" - click DEPS "Backend_Agent_Tools.md" - click EDIT "Backend_Agent_Tools.md" - click In "Code_Analysis_Engine.md" -``` - -### Generation flow - -```mermaid -sequenceDiagram - participant DG as DocumentationGenerator - participant CL as cluster_modules / super_group_modules - participant Agent as Module Agent (LLMBackend) - participant Tools as Backend_Agent_Tools - - DG->>CL: cluster components into module tree - CL-->>DG: hierarchical module_tree (super-grouped) - loop leaf modules, post-order - DG->>Agent: run_module_agent(module, components) - Agent->>Tools: read_code_components / str_replace_editor - opt module too large - Agent->>Tools: generate_sub_module_documentation - Tools-->>DG: new children added to module_tree - end - Agent-->>DG: {module}.md written - end - loop parent modules, then repo root - DG->>Agent: MODULE_OVERVIEW / REPO_OVERVIEW prompt<br/>(children's markdown as context) - Agent-->>DG: parent .md / overview.md - end - DG->>DG: create metadata.json + validate docs -``` - -Key design decisions: - -* **Two backends, one contract.** `LLMBackend` isolates the generator from how agents actually run, so API-key users (`PydanticAIBackend`) and subscription users (`CawBackend`) share the same pipeline. -* **Agents write files themselves.** Documentation isn't returned as chat text; agents use `str_replace_editor` to write Markdown directly, and every embedded Mermaid diagram is validated before the write is accepted. -* **Dynamic hierarchy.** The module tree is not fixed after clustering: agents can split oversized modules into sub-modules at runtime, and the tree (persisted to `module_tree.json`) grows accordingly. -* **Resumability.** An existing `{module}.md` short-circuits regeneration, making interrupted or incremental runs cheap. - -## Modules - -| Module | Responsibility | Documentation | -|---|---|---| -| **Backend_LLM_&_Documentation_Services** | Pipeline orchestration, module clustering/super-grouping, LLM backend abstraction (API-key and subscription) | [Backend_LLM_&_Documentation_Services.md](Backend_LLM_&_Documentation_Services.md) | -| **Backend_Agent_Tools** | Agent-facing sandboxed tools: file viewer/editor with Mermaid validation, shared `CodeWikiDeps` context, sub-module spawner | [Backend_Agent_Tools.md](Backend_Agent_Tools.md) | - -## Related Modules - -* [Code_Analysis_Engine](Code_Analysis_Engine.md) β€” produces the dependency graph and leaf nodes this engine documents. -* [Core_Config_&_Utils](Core_Config_&_Utils.md) β€” `Config` (models, token budgets, depth limits) and `FileManager` (tree/metadata persistence) used throughout the pipeline. -* [User_Interfaces](User_Interfaces.md) β€” the CLI, web app, and MCP server that invoke this engine and present its output. diff --git a/docs/Frontend_Web_App.md b/docs/Frontend_Web_App.md deleted file mode 100644 index 1a086a74..00000000 --- a/docs/Frontend_Web_App.md +++ /dev/null @@ -1,162 +0,0 @@ -# Frontend Web App - -## Introduction - -The **Frontend Web App** module is the user-facing HTTP layer of CodeWiki. It exposes a FastAPI-based -web interface that lets a user submit a GitHub repository URL, tracks the asynchronous documentation -generation job for that repository, serves the generated markdown documentation as browsable HTML pages, -and caches completed results so repeated requests for the same repository are served instantly. - -This module acts as the orchestration glue between the outside world (browser/API clients) and the -backend documentation-generation pipeline. It does not perform dependency analysis or LLM calls itself; -instead it delegates the heavy lifting to [Backend_LLM_&_Documentation_Services](Backend_LLM_%26_Documentation_Services.md) -(specifically `DocumentationGenerator`) and to [Core_Config_&_Utils](Core_Config_%26_Utils.md) for shared -configuration (`Config`) and file I/O (`FileManager`). - -## Purpose & Responsibilities - -- Provide a simple web form to submit a GitHub repository for documentation generation. -- Validate and normalize submitted GitHub URLs. -- Queue and asynchronously process documentation-generation jobs in a background thread, without - blocking the FastAPI request/response cycle. -- Persist job state and a documentation cache to disk so results survive process restarts and repeated - submissions are served from cache instead of re-running the (expensive) generation pipeline. -- Render generated markdown documentation as navigable HTML pages using Jinja2 templates. -- Expose a small JSON API for polling job status. - -## Architecture Overview - -```mermaid -flowchart TB - subgraph Client - Browser["Browser / API client"] - end - - subgraph Frontend_Web_App["Frontend Web App"] - Routes["WebRoutes\n(routes.py)"] - Templates["StringTemplateLoader / render_template\n(template_utils.py)"] - Worker["BackgroundWorker\n(background_worker.py)"] - Cache["CacheManager\n(cache_manager.py)"] - GH["GitHubRepoProcessor\n(github_processor.py)"] - Cfg["WebAppConfig\n(config.py)"] - Models["Data Models\n(models.py)"] - end - - subgraph Backend["Backend services"] - DocGen["DocumentationGenerator"] - CoreCfg["Config (Core_Config_&_Utils)"] - FM["FileManager (Core_Config_&_Utils)"] - end - - Disk[("Local disk\noutput/cache, output/temp, generated docs")] - - Browser -->|"HTTP form / API calls"| Routes - Routes --> Templates - Routes --> Worker - Routes --> Cache - Routes --> GH - Worker --> Cache - Worker --> GH - Worker --> DocGen - Worker --> CoreCfg - Cache --> FM - Worker --> FM - Routes --> Models - Worker --> Models - Cache --> Models - Cfg -.->|"static settings"| Routes - Cfg -.-> Worker - Cfg -.-> Cache - Cfg -.-> GH - Cache <--> Disk - Worker <--> Disk - DocGen --> Disk -``` - -## Sub-modules - -The Frontend Web App is organized into three functional areas, each documented in detail in its own file: - -| Sub-module | Description | Documentation | -|---|---|---| -| **Job Processing & Caching** | Owns the job lifecycle (queueing, background processing, persistence) and the documentation cache used to avoid re-generating docs for the same repository/commit. | [Frontend_Web_App_job_processing.md](Frontend_Web_App_job_processing.md) | -| **Web Routes & Rendering** | FastAPI route handlers for the submission form, job-status API, and documentation viewer, plus the Jinja2-based template rendering utilities. | [Frontend_Web_App_web_routes.md](Frontend_Web_App_web_routes.md) | -| **GitHub Integration & App Configuration** | Validates GitHub URLs, extracts repo metadata, clones repositories, and centralizes all web-app configuration constants (directories, timeouts, ports). | [Frontend_Web_App_github_config.md](Frontend_Web_App_github_config.md) | - -## End-to-End Request Flow - -The following sequence illustrates how a repository submission flows through the module and into the -backend documentation pipeline: - -```mermaid -sequenceDiagram - participant U as User (Browser) - participant R as WebRoutes - participant C as CacheManager - participant GH as GitHubRepoProcessor - participant W as BackgroundWorker - participant DG as DocumentationGenerator (Backend) - - U->>R: POST / (repo_url, commit_id) - R->>GH: is_valid_github_url() / get_repo_info() - R->>C: get_cached_docs(repo_url) - alt Cache hit - R-->>U: "Found in cache" + link to /docs/{job_id} - else Cache miss - R->>W: add_job(job_id, JobStatus(queued)) - R-->>U: "Added to queue" + Job ID - Note over W: Worker thread picks up job from queue - W->>GH: clone_repository(clone_url, temp_dir, commit_id) - W->>DG: DocumentationGenerator(config, commit_id).run() - DG-->>W: docs written to config.docs_dir - W->>C: add_to_cache(repo_url, docs_path) - W->>W: save_job_statuses() (persist to jobs.json) - end - U->>R: GET /api/jobs/{job_id} - R->>W: get_job_status(job_id) - R-->>U: JobStatusResponse (status, progress, ...) - U->>R: GET /docs/{job_id} - R->>W: get_job_status(job_id) - R-->>U: 302 redirect to /static-docs/{job_id}/ - U->>R: GET /static-docs/{job_id}/{filename} - R->>R: render markdown -> HTML via templates - R-->>U: Rendered documentation page -``` - -## Key Data Models - -All shared data structures used across the module live in `codewiki/src/fe/models.py`: - -- **`RepositorySubmission`** β€” Pydantic model validating the submitted repository URL (`HttpUrl`). -- **`JobStatus`** β€” Dataclass tracking a documentation job's lifecycle (`queued` β†’ `processing` β†’ - `completed`/`failed`), including timestamps, progress text, error messages, and the resulting - `docs_path`. -- **`JobStatusResponse`** β€” Pydantic response model mirroring `JobStatus` for the JSON status API. -- **`CacheEntry`** β€” Dataclass representing a cached documentation result keyed by a hash of the - repository URL. - -These models are consumed by all three sub-modules; see [Frontend_Web_App_job_processing.md](Frontend_Web_App_job_processing.md) -for how `JobStatus`/`CacheEntry` are persisted, and [Frontend_Web_App_web_routes.md](Frontend_Web_App_web_routes.md) -for how they are serialized in HTTP responses. - -## Relationship to Other Modules - -- **[Backend_LLM_&_Documentation_Services](Backend_LLM_%26_Documentation_Services.md)** β€” `BackgroundWorker` - instantiates `DocumentationGenerator` to run the actual analysis + LLM documentation pipeline for a - cloned repository. -- **[Core_Config_&_Utils](Core_Config_%26_Utils.md)** β€” `Config.from_args` builds the pipeline configuration - consumed by `DocumentationGenerator`, and the shared `file_manager` (`FileManager`) singleton is used - throughout the Frontend Web App for reading/writing JSON and text files (job state, cache index, - generated markdown). -- **[Dependency_Analysis_Service](Dependency_Analysis_Service.md) / [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)** β€” - invoked indirectly via `DocumentationGenerator`; the Frontend Web App has no direct dependency on them. -- **[CLI](CLI.md)** β€” an alternative entry point into the same backend documentation-generation - pipeline; the Frontend Web App provides the equivalent capability through a browser/HTTP interface - instead of a command line. - -## Typical Deployment - -`WebAppConfig` (see [Frontend_Web_App_github_config.md](Frontend_Web_App_github_config.md)) defines -directories (`./output/cache`, `./output/temp`, `./output/`) and server defaults (host `127.0.0.1`, -port `8000`) used when wiring up the FastAPI application (routes + background worker + cache manager) -in the application entry point. diff --git a/docs/Frontend_Web_App_github_config.md b/docs/Frontend_Web_App_github_config.md deleted file mode 100644 index d8c12aa2..00000000 --- a/docs/Frontend_Web_App_github_config.md +++ /dev/null @@ -1,259 +0,0 @@ -# Frontend Web App β€” GitHub & Config - -## Introduction - -The **Frontend_Web_App_github_config** module provides two foundational, low-level services used throughout the [Frontend_Web_App](Frontend_Web_App.md) module family: - -1. **`WebAppConfig`** (`codewiki/src/fe/config.py`) β€” a centralized, static configuration class that defines directory locations, queue sizes, cache expiry policies, job cleanup rules, server defaults, and git cloning parameters for the web application. -2. **`GitHubRepoProcessor`** (`codewiki/src/fe/github_processor.py`) β€” a stateless utility class responsible for validating GitHub repository URLs, extracting repository metadata, and cloning repositories to local disk (optionally at a specific commit). - -These two components have no business logic of their own beyond validation, parsing, and cloning β€” they act as **shared infrastructure** that other Frontend Web App submodules (job processing, web routes) depend on. This module sits at the bottom of the Frontend Web App dependency stack: almost every other component in the frontend imports from it, but it imports from nothing else in the frontend. - ---- - -## Module Purpose & Responsibilities - -| Component | Responsibility | -|---|---| -| `WebAppConfig` | Single source of truth for all configurable constants (paths, timeouts, limits) used by the frontend web application. | -| `GitHubRepoProcessor` | Validates GitHub URLs, parses owner/repo/clone-url metadata, and performs `git clone` (shallow or full + checkout) operations into temporary directories. | - -### Why this module exists - -Documentation generation begins with a user submitting a GitHub URL. Before any expensive analysis or LLM-based documentation work can start (see [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) and [Dependency_Analysis_Service](Dependency_Analysis_Service.md)), the system must: - -- Confirm the URL is actually a GitHub repository URL. -- Derive a canonical, URL-safe identifier for the repository (used as job IDs, cache keys, and temp directory names). -- Physically clone the repository's source code onto local disk for analysis. - -`GitHubRepoProcessor` encapsulates all of this, while `WebAppConfig` supplies the directory paths, timeouts, and clone-depth settings it needs. - ---- - -## Architecture - -```mermaid -graph TB - subgraph "Frontend_Web_App_github_config (this module)" - Config["WebAppConfig<br/>(static config class)"] - Processor["GitHubRepoProcessor<br/>(static utility class)"] - end - - subgraph "Frontend_Web_App_job_processing" - Worker["BackgroundWorker"] - Cache["CacheManager"] - end - - subgraph "Frontend_Web_App_web_routes" - Routes["WebRoutes"] - end - - subgraph "Backend_LLM_&_Documentation_Services" - DocGen["DocumentationGenerator"] - end - - subgraph "Core_Config_&_Utils" - CoreConfig["Config"] - FM["FileManager"] - end - - Processor -->|reads CLONE_TIMEOUT, CLONE_DEPTH| Config - Worker -->|reads TEMP_DIR, QUEUE_SIZE, CACHE_DIR| Config - Cache -->|reads CACHE_DIR, CACHE_EXPIRY_DAYS| Config - Routes -->|reads RETRY_COOLDOWN_MINUTES, JOB_CLEANUP_HOURS| Config - - Worker -->|calls get_repo_info / clone_repository| Processor - Routes -->|calls is_valid_github_url / get_repo_info| Processor - - Worker -->|invokes with cloned repo path| DocGen - Worker -.->|uses| FM - Worker -.->|builds| CoreConfig - - style Config fill:#e1f0ff - style Processor fill:#e1f0ff -``` - ---- - -## Component Details - -### `WebAppConfig` - -A pure static-configuration class (no instantiation required, all attributes are class-level). It groups settings into logical categories: - -```mermaid -classDiagram - class WebAppConfig { - <<static config>> - +CACHE_DIR: str = "./output/cache" - +TEMP_DIR: str = "./output/temp" - +OUTPUT_DIR: str = "./output" - +QUEUE_SIZE: int = 100 - +CACHE_EXPIRY_DAYS: int = 365 - +JOB_CLEANUP_HOURS: int = 24000 - +RETRY_COOLDOWN_MINUTES: int = 3 - +DEFAULT_HOST: str = "127.0.0.1" - +DEFAULT_PORT: int = 8000 - +CLONE_TIMEOUT: int = 300 - +CLONE_DEPTH: int = 1 - +ensure_directories() void - +get_absolute_path(path) str - } -``` - -**Key settings and their consumers:** - -| Setting | Used By | Purpose | -|---|---|---| -| `CACHE_DIR` | `CacheManager`, `BackgroundWorker` (jobs.json location) | Where cached documentation index/entries are stored | -| `TEMP_DIR` | `BackgroundWorker` | Where repositories are cloned during processing | -| `OUTPUT_DIR` | `WebAppConfig.ensure_directories` | Root output directory for generated docs | -| `QUEUE_SIZE` | `BackgroundWorker` | Max size of the in-memory job processing `Queue` | -| `CACHE_EXPIRY_DAYS` | `CacheManager` | TTL for cached documentation entries | -| `JOB_CLEANUP_HOURS` | `WebRoutes.cleanup_old_jobs` | How long completed/failed jobs are retained before removal | -| `RETRY_COOLDOWN_MINUTES` | `WebRoutes.index_post` | Cooldown before a previously-failed job can be resubmitted | -| `DEFAULT_HOST` / `DEFAULT_PORT` | Web server bootstrap (ASGI app entrypoint) | Default bind address/port | -| `CLONE_TIMEOUT` | `GitHubRepoProcessor.clone_repository` | Max seconds allowed for `git clone` subprocess | -| `CLONE_DEPTH` | `GitHubRepoProcessor.clone_repository` | Shallow clone depth for the default (no-commit) case | - -**Utility methods:** - -- `ensure_directories()` β€” idempotently creates `CACHE_DIR`, `TEMP_DIR`, and `OUTPUT_DIR` on disk (called at application startup). -- `get_absolute_path(path)` β€” thin wrapper around `os.path.abspath` for consistent path resolution. - ---- - -### `GitHubRepoProcessor` - -A collection of `@staticmethod`s β€” no instance state β€” that handles all GitHub-URL-related concerns. - -```mermaid -classDiagram - class GitHubRepoProcessor { - <<static utility>> - +is_valid_github_url(url) bool - +get_repo_info(url) Dict~str,str~ - +clone_repository(clone_url, target_dir, commit_id) bool - } -``` - -#### `is_valid_github_url(url) -> bool` -Validates that a URL: -- Has a `github.com` / `www.github.com` netloc. -- Has at least two non-empty path segments (`owner/repo`). - -Used by `WebRoutes.index_post` (see [Frontend_Web_App_web_routes](Frontend_Web_App_web_routes.md)) as a form-submission guard before any job is queued. - -#### `get_repo_info(url) -> Dict[str, str]` -Parses a validated URL into a structured dict: - -```json -{ - "owner": "owner-name", - "repo": "repo-name", - "full_name": "owner-name/repo-name", - "clone_url": "https://github.com/owner-name/repo-name.git" -} -``` - -This `full_name` value (with `/` replaced by `--`) becomes the canonical **job ID** used across the system by `BackgroundWorker` and `WebRoutes` for: -- Job status tracking (`JobStatus.job_id`) -- Temp clone directory naming (`TEMP_DIR/{job_id}`) -- Documentation output directory naming (`{job_id}-docs`) -- URL normalization for cache lookups (`CacheManager.get_repo_hash`) - -#### `clone_repository(clone_url, target_dir, commit_id=None) -> bool` -Performs the actual `git clone` via `subprocess.run`: - -- **Default path (no `commit_id`)**: shallow clone using `--depth WebAppConfig.CLONE_DEPTH`, bounded by `WebAppConfig.CLONE_TIMEOUT`. -- **Commit-pinned path**: full clone (no `--depth`, since arbitrary commits may not be reachable in a shallow clone) followed by `git checkout <commit_id>`. -- Ensures parent directory of `target_dir` exists before cloning. -- Returns `False` and logs to stdout on any subprocess failure or exception β€” callers (`BackgroundWorker`) treat this as a job failure. - -```mermaid -flowchart TD - Start([clone_repository called]) --> MkDir[Ensure parent dir exists] - MkDir --> HasCommit{commit_id provided?} - HasCommit -- Yes --> FullClone[git clone full repo] - FullClone --> CloneOK1{clone succeeded?} - CloneOK1 -- No --> Fail1[Return False] - CloneOK1 -- Yes --> Checkout[git checkout commit_id] - Checkout --> CheckoutOK{checkout succeeded?} - CheckoutOK -- No --> Fail2[Return False] - CheckoutOK -- Yes --> Success[Return True] - HasCommit -- No --> ShallowClone["git clone --depth CLONE_DEPTH"] - ShallowClone --> CloneOK2{clone succeeded?} - CloneOK2 -- No --> Fail3[Return False] - CloneOK2 -- Yes --> Success -``` - ---- - -## Data Flow: From URL Submission to Cloned Repository - -```mermaid -sequenceDiagram - participant User - participant Routes as WebRoutes - participant Processor as GitHubRepoProcessor - participant Config as WebAppConfig - participant Worker as BackgroundWorker - participant Git as "git (subprocess)" - - User->>Routes: POST / (repo_url, commit_id) - Routes->>Processor: is_valid_github_url(repo_url) - Processor-->>Routes: true/false - alt invalid URL - Routes-->>User: error message - else valid URL - Routes->>Processor: get_repo_info(repo_url) - Processor-->>Routes: {owner, repo, full_name, clone_url} - Routes->>Worker: add_job(job_id, JobStatus(...)) - Note over Worker: async processing in worker thread - Worker->>Processor: get_repo_info(job.repo_url) - Worker->>Config: read TEMP_DIR, CLONE_TIMEOUT, CLONE_DEPTH - Worker->>Processor: clone_repository(clone_url, temp_dir, commit_id) - Processor->>Git: git clone [--depth N | full] - alt commit_id set - Processor->>Git: git checkout commit_id - end - Git-->>Processor: exit code - Processor-->>Worker: true/false - alt clone failed - Worker-->>Worker: mark job 'failed' - else clone succeeded - Worker->>Worker: proceed to DocumentationGenerator.run() - end - end -``` - ---- - -## Relationships to Other Modules - -```mermaid -graph LR - A[Frontend_Web_App_github_config] --> B[Frontend_Web_App_job_processing] - A --> C[Frontend_Web_App_web_routes] - B --> D[Backend_LLM_&_Documentation_Services] - B --> E[Core_Config_&_Utils] - - click B "Frontend_Web_App_job_processing.md" - click C "Frontend_Web_App_web_routes.md" - click D "Backend_LLM_&_Documentation_Services.md" - click E "Core_Config_&_Utils.md" -``` - -- **[Frontend_Web_App_job_processing](Frontend_Web_App_job_processing.md)**: `BackgroundWorker` is the primary consumer of both `WebAppConfig` (for `TEMP_DIR`, `QUEUE_SIZE`, `CACHE_DIR`) and `GitHubRepoProcessor` (for `get_repo_info` and `clone_repository`) during its job-processing lifecycle. `CacheManager` also depends on `WebAppConfig` for cache directory and expiry settings. -- **[Frontend_Web_App_web_routes](Frontend_Web_App_web_routes.md)**: `WebRoutes` uses `GitHubRepoProcessor.is_valid_github_url` and `get_repo_info` to validate and normalize user-submitted URLs before creating jobs, and reads `WebAppConfig.RETRY_COOLDOWN_MINUTES` / `JOB_CLEANUP_HOURS` for retry and cleanup policy. -- **[Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md)**: Once `GitHubRepoProcessor` clones a repository, the resulting local path is handed to `DocumentationGenerator` (built with a `Config` from [Core_Config_&_Utils](Core_Config_&_Utils.md)) to perform the actual analysis and documentation generation. -- **[Core_Config_&_Utils](Core_Config_&_Utils.md)**: Distinct from `WebAppConfig` β€” `Config` (in `codewiki/src/config.py`) governs backend/analysis settings, while `WebAppConfig` governs only frontend web-app concerns. `FileManager` is used by sibling frontend components (`BackgroundWorker`, `CacheManager`) for JSON persistence, not directly by this module. - ---- - -## Design Notes - -- **Statelessness**: Both `WebAppConfig` and `GitHubRepoProcessor` are designed as static/class-level utilities with no instance state, making them safe to use anywhere without dependency injection or lifecycle management. -- **Fail-safe validation**: `is_valid_github_url` wraps all parsing in a broad `try/except`, returning `False` on any malformed input rather than raising β€” this keeps the web form handler (`WebRoutes.index_post`) simple and robust against arbitrary user input. -- **Shallow vs. full clone tradeoff**: The shallow-clone default (`CLONE_DEPTH = 1`) minimizes clone time and disk usage for the common case (latest `HEAD`), while the commit-pinned path trades this efficiency for the ability to check out arbitrary historical commits. -- **Centralized tunables**: By keeping all frontend-specific constants in `WebAppConfig`, operators can adjust queue sizes, cache TTLs, and clone behavior without touching business logic in `BackgroundWorker` or `WebRoutes`. diff --git a/docs/Frontend_Web_App_job_processing.md b/docs/Frontend_Web_App_job_processing.md deleted file mode 100644 index f5b758f8..00000000 --- a/docs/Frontend_Web_App_job_processing.md +++ /dev/null @@ -1,291 +0,0 @@ -# Frontend Web App β€” Job Processing - -## Introduction - -The **Job Processing** module is the asynchronous execution engine behind CodeWiki's web application. It receives repository documentation requests submitted through the [Web Routes](Frontend_Web_App_web_routes.md) layer, queues them, clones the target repository, drives the full documentation-generation pipeline, and persists both the job's lifecycle state and the resulting docs so subsequent requests can be served instantly from cache. - -This module is composed of three tightly-coupled components, all living under `codewiki/src/fe/`: - -| Component | File | Responsibility | -|---|---|---| -| `BackgroundWorker` | `background_worker.py` | Owns the job queue, worker thread, and orchestrates clone β†’ generate β†’ cache for each job | -| `CacheManager` | `cache_manager.py` | Maps repository URLs to previously generated documentation directories, with expiry | -| `JobStatus` / `CacheEntry` | `models.py` | Plain dataclasses describing a job's lifecycle and a cache record | - -It sits between the user-facing [Frontend_Web_App_web_routes](Frontend_Web_App_web_routes.md) module (which enqueues jobs and polls status) and the [Backend_LLM_&_Documentation_Services](Backend_LLM_%26_Documentation_Services.md) module (which performs the actual dependency analysis + LLM-driven doc generation via `DocumentationGenerator`). It also depends on [Frontend_Web_App_github_config](Frontend_Web_App_github_config.md) for repo validation/cloning and app-wide settings, and on [Core_Config_&_Utils](Core_Config_%26_Utils.md) for filesystem helpers and generation `Config`. - ---- - -## Position in the System - -```mermaid -graph TB - subgraph "Client" - Browser["Browser / API client"] - end - - subgraph "Frontend_Web_App" - Routes["WebRoutes\n(Frontend_Web_App_web_routes)"] - subgraph "Frontend_Web_App_job_processing (this module)" - Worker["BackgroundWorker"] - Cache["CacheManager"] - Models["JobStatus / CacheEntry"] - end - GHConfig["GitHubRepoProcessor / WebAppConfig\n(Frontend_Web_App_github_config)"] - end - - subgraph "Backend" - DocGen["DocumentationGenerator\n(Backend_LLM_&_Documentation_Services)"] - DepGraph["DependencyGraphBuilder\n(Dependency_Analyzer_Core)"] - end - - Utils["FileManager, Config\n(Core_Config_&_Utils)"] - - Browser -->|"POST repo_url"| Routes - Routes -->|"add_job / get_job_status"| Worker - Routes -->|"get_cached_docs"| Cache - Worker -->|"uses"| GHConfig - Worker -->|"instantiates & runs"| DocGen - DocGen --> DepGraph - Worker -->|"add_to_cache / get_cached_docs"| Cache - Worker -.->|"reads job_id -> repo_url"| GHConfig - Worker --> Models - Cache --> Models - Worker --> Utils - Cache --> Utils -``` - ---- - -## Data Models - -`models.py` defines the plain-data contracts used throughout this module (and consumed by [Frontend_Web_App_web_routes](Frontend_Web_App_web_routes.md) for API responses). - -```mermaid -classDiagram - class JobStatus { - +str job_id - +str repo_url - +str status "queued|processing|completed|failed" - +datetime created_at - +datetime started_at - +datetime completed_at - +str error_message - +str progress - +str docs_path - +str main_model - +str commit_id - } - - class CacheEntry { - +str repo_url - +str repo_url_hash - +str docs_path - +datetime created_at - +datetime last_accessed - } - - class JobStatusResponse { - <<pydantic, defined in models.py>> - job_id, repo_url, status, timestamps, progress, docs_path, main_model, commit_id - } - - JobStatusResponse ..|> JobStatus : API projection (asdict) -``` - -- `JobStatus` is a mutable dataclass held in-memory (`BackgroundWorker.job_status`) and mirrored to disk as `jobs.json`. -- `CacheEntry` maps a hashed repository URL to a documentation directory and tracks freshness (`created_at`) and usage (`last_accessed`). -- `JobStatusResponse` (used by the routes module) is built via `JobStatusResponse(**asdict(job))`, so this module's `JobStatus` is the single source of truth for job state exposed over the API. - ---- - -## CacheManager - -`CacheManager` provides a simple, file-backed key/value cache keyed by a SHA-256 hash (truncated to 16 chars) of the repository URL. It avoids re-running the (expensive, LLM-driven) documentation pipeline for repositories that were already processed within the configured expiry window. - -### Responsibilities -- Persist/reload a `cache_index.json` (dict of hash β†’ `CacheEntry`) under `WebAppConfig.CACHE_DIR`. -- Compute deterministic hashes for repo URLs (`get_repo_hash`). -- Serve cached docs paths only if within `CACHE_EXPIRY_DAYS`, otherwise evict. -- Bump `last_accessed` on cache hits. -- Support manual removal and bulk expiry cleanup. - -```mermaid -sequenceDiagram - participant Caller as BackgroundWorker / WebRoutes - participant Cache as CacheManager - participant Disk as cache_index.json - - Caller->>Cache: get_cached_docs(repo_url) - Cache->>Cache: get_repo_hash(repo_url) - alt hash found & not expired - Cache->>Cache: update last_accessed - Cache->>Disk: save_cache_index() - Cache-->>Caller: docs_path - else expired - Cache->>Cache: remove_from_cache(repo_url) - Cache-->>Caller: None - else not found - Cache-->>Caller: None - end - - Caller->>Cache: add_to_cache(repo_url, docs_path) - Cache->>Cache: build CacheEntry(now, now) - Cache->>Disk: save_cache_index() -``` - -Key methods: -- `load_cache_index()` / `save_cache_index()` β€” serialize `CacheEntry` objects to/from JSON via [`FileManager`](Core_Config_%26_Utils.md) (`file_manager.load_json` / `save_json`). -- `get_repo_hash(repo_url)` β€” `sha256(repo_url)[:16]`. -- `get_cached_docs(repo_url)` β€” returns a valid docs path or `None`, evicting expired entries as a side effect. -- `add_to_cache(repo_url, docs_path)` β€” inserts/overwrites an entry with fresh timestamps. -- `remove_from_cache(repo_url)` β€” deletes a single entry. -- `cleanup_expired_cache()` β€” bulk-removes entries older than `cache_expiry_days`. - -Configuration (`CACHE_DIR`, `CACHE_EXPIRY_DAYS`) comes from `WebAppConfig`, documented in [Frontend_Web_App_github_config](Frontend_Web_App_github_config.md). - ---- - -## BackgroundWorker - -`BackgroundWorker` is the orchestration core: a single background thread that consumes a bounded `Queue` of job IDs and drives each job through cloning, dependency analysis + LLM documentation generation, and caching β€” while keeping an in-memory + on-disk record of job status for the UI/API to poll. - -### Construction & Lifecycle - -```mermaid -stateDiagram-v2 - [*] --> Constructed: __init__(cache_manager, temp_dir) - Constructed --> Constructed: load_job_statuses() (from jobs.json or cache reconstruction) - Constructed --> Running: start() spawns daemon thread(_worker_loop) - Running --> Running: poll queue every 1s - Running --> [*]: stop() sets running=False -``` - -- `__init__` wires in a `CacheManager`, resolves `temp_dir` (default `WebAppConfig.TEMP_DIR`), creates a bounded `Queue(maxsize=WebAppConfig.QUEUE_SIZE)`, and eagerly loads any known job statuses from `jobs.json`. -- `start()` / `stop()` control a single daemon `threading.Thread` running `_worker_loop`, so the worker survives independently of request-handling threads in the ASGI app. -- `add_job(job_id, job)` is the public entry point used by [WebRoutes](Frontend_Web_App_web_routes.md) to register a new `JobStatus` and enqueue its ID. -- `get_job_status(job_id)` / `get_all_jobs()` expose read access for the status API and index page. - -### Persistence & Recovery - -Because job state lives in memory, `BackgroundWorker` mirrors it to `jobs.json` (under `WebAppConfig.CACHE_DIR`) so that: -- A server restart doesn't lose the history of **completed** jobs (only `completed` jobs are reloaded from `jobs.json` β€” in-flight jobs are intentionally dropped to avoid resuming into an inconsistent state). -- If `jobs.json` is missing entirely (e.g., first run after a cache-only deployment), `_reconstruct_jobs_from_cache()` rebuilds synthetic `completed` `JobStatus` entries directly from `CacheManager.cache_index`, using [`GitHubRepoProcessor.get_repo_info`](Frontend_Web_App_github_config.md) to derive a stable `job_id` (`owner--repo`). - -```mermaid -flowchart TD - Start([BackgroundWorker.__init__]) --> CheckFile{jobs.json exists?} - CheckFile -- No --> Reconstruct[_reconstruct_jobs_from_cache] - Reconstruct --> UseCacheIndex[Iterate cache_manager.cache_index] - UseCacheIndex --> DeriveJobId["job_id = full_name.replace('/', '--')"] - DeriveJobId --> BuildStatus[Create completed JobStatus] - BuildStatus --> SaveBack[save_job_statuses] - - CheckFile -- Yes --> LoadJson[file_manager.load_json] - LoadJson --> FilterCompleted{status == 'completed'?} - FilterCompleted -- Yes --> Populate[Populate job_status dict] - FilterCompleted -- No --> Skip[Skip entry] -``` - -### The Worker Loop and Job Processing Pipeline - -`_worker_loop` runs continuously while `self.running`, pulling one `job_id` at a time from the queue (1s poll interval when idle) and delegating to `_process_job`. - -`_process_job(job_id)` is the heart of this module β€” it implements the full documentation pipeline for one repository: - -```mermaid -sequenceDiagram - participant Q as processing_queue - participant W as BackgroundWorker - participant Cache as CacheManager - participant GH as GitHubRepoProcessor - participant Cfg as Config (Core_Config_&_Utils) - participant DG as DocumentationGenerator - participant FS as jobs.json / temp dir - - Q->>W: job_id - W->>W: job.status='processing', started_at=now - W->>Cache: get_cached_docs(job.repo_url) - alt cache hit - Cache-->>W: docs_path - W->>W: job.status='completed', docs_path set - W->>FS: save_job_statuses() - else cache miss - W->>GH: get_repo_info(repo_url) - W->>GH: clone_repository(clone_url, temp_repo_dir, commit_id) - alt clone fails - GH-->>W: False - W->>W: raise Exception - else clone ok - W->>Cfg: Config.from_args(repo_path=temp_repo_dir) - W->>W: override config.docs_dir = output/docs/{job_id}-docs - W->>DG: DocumentationGenerator(config, commit_id) - W->>DG: run() (new asyncio event loop) - DG-->>W: docs generated on disk - W->>Cache: add_to_cache(repo_url, docs_path) - W->>W: job.status='completed', docs_path set - W->>FS: save_job_statuses() - end - end - W->>FS: rm -rf temp_repo_dir (finally block) -``` - -Step-by-step: - -1. **Status transition** β€” mark job `processing`, record `started_at`, tag `main_model` from `codewiki.src.config.MAIN_MODEL`. -2. **Cache check** β€” `CacheManager.get_cached_docs(job.repo_url)`; on hit, short-circuit straight to `completed` without touching git or the LLM backend. -3. **Repo resolution & clone** β€” `GitHubRepoProcessor.get_repo_info` (see [Frontend_Web_App_github_config](Frontend_Web_App_github_config.md)) extracts `full_name`/`clone_url`; the repo is cloned into `temp_dir/{job_id}` (optionally checking out `job.commit_id`) via `GitHubRepoProcessor.clone_repository`. -4. **Config construction** β€” builds a documentation-generation `Config` via `Config.from_args` (see [Core_Config_&_Utils](Core_Config_%26_Utils.md)), then overrides `docs_dir` to a job-scoped path (`output/docs/{job_id}-docs`) so concurrent jobs never collide. -5. **Documentation generation** β€” instantiates `DocumentationGenerator(config, job.commit_id)` (see [Backend_LLM_&_Documentation_Services](Backend_LLM_%26_Documentation_Services.md)) and drives its async `run()` coroutine on a fresh event loop created specifically for this worker-thread invocation (since `_process_job` executes outside any existing asyncio context). -6. **Cache write-back** β€” on success, the absolute `docs_dir` path is registered in the `CacheManager` so future requests for the same `repo_url` are served instantly. -7. **Status finalization** β€” `completed` (with `docs_path`) or `failed` (with `error_message`/`progress` describing the exception) is written back to `job_status` and flushed via `save_job_statuses()`. -8. **Cleanup** β€” regardless of outcome, the temporary clone directory is removed with `rm -rf` in a `finally` block. - -### Persistence Format - -`save_job_statuses()` / `load_job_statuses()` serialize the `job_status` dict to `jobs.json` (ISO-formatted timestamps, `None`-safe) using [`FileManager`](Core_Config_%26_Utils.md). This file is the durable record consulted on process restart and is what powers the "recent jobs" list rendered by [WebRoutes.index_get](Frontend_Web_App_web_routes.md). - ---- - -## Component Interactions - -```mermaid -graph LR - subgraph "Job Processing Module" - BW["BackgroundWorker"] - CM["CacheManager"] - JS["JobStatus"] - CE["CacheEntry"] - end - - WR["WebRoutes\n(web_routes module)"] -->|"add_job(job_id, JobStatus)"| BW - WR -->|"get_job_status(job_id)"| BW - WR -->|"get_cached_docs(repo_url)"| CM - - BW --> JS - BW -->|"get_cached_docs / add_to_cache"| CM - CM --> CE - - BW -->|"get_repo_info / clone_repository"| GHP["GitHubRepoProcessor\n(github_config module)"] - BW -->|"Config.from_args"| CFG["Config\n(Core_Config_&_Utils)"] - BW -->|"run()"| DG["DocumentationGenerator\n(Backend_LLM_&_Documentation_Services)"] - BW -->|"load_json/save_json/load_text"| FM["FileManager\n(Core_Config_&_Utils)"] - CM -->|"load_json/save_json"| FM -``` - ---- - -## Design Notes - -- **Single-threaded worker, thread-safe enough for a single-process web app**: only one worker thread mutates `job_status`, avoiding explicit locking; the `Queue` provides safe hand-off from request-handling threads (which call `add_job`) to the worker thread. -- **Idempotent event loop management**: because `_process_job` runs in a plain background thread (not inside FastAPI/Starlette's event loop), it explicitly creates and tears down its own `asyncio` event loop per job to invoke `DocumentationGenerator.run()`. -- **Cache-first design**: the cache check happens before any git/network/LLM work, making repeated requests for the same repository (common during demos or re-visits) essentially free after the first successful generation. -- **Graceful degradation on restart**: rather than trusting potentially-corrupt in-flight state after a crash, only `completed` jobs are restored from `jobs.json`; if that file is absent, cache contents alone are enough to reconstruct a usable job history. -- **Job ID scheme**: `job_id` is always derived as `owner--repo` (slash replaced with double-dash) so it is filesystem- and URL-safe; both this module and [WebRoutes](Frontend_Web_App_web_routes.md) rely on this convention for constructing paths and reverse-mapping IDs back to repo URLs. - -## Related Modules - -- [Frontend_Web_App_web_routes](Frontend_Web_App_web_routes.md) β€” HTTP layer that submits jobs to and polls status from this module, and serves the generated docs it produces. -- [Frontend_Web_App_github_config](Frontend_Web_App_github_config.md) β€” `GitHubRepoProcessor` (URL validation, cloning) and `WebAppConfig` (directories, timeouts, cache expiry) consumed throughout this module. -- [Backend_LLM_&_Documentation_Services](Backend_LLM_%26_Documentation_Services.md) β€” `DocumentationGenerator`, the async pipeline this module invokes to actually produce documentation. -- [Core_Config_&_Utils](Core_Config_%26_Utils.md) β€” `Config` (generation configuration) and `FileManager` (JSON/text I/O helpers) used for persistence and pipeline setup. diff --git a/docs/Frontend_Web_App_web_routes.md b/docs/Frontend_Web_App_web_routes.md deleted file mode 100644 index d1f9e706..00000000 --- a/docs/Frontend_Web_App_web_routes.md +++ /dev/null @@ -1,291 +0,0 @@ -# Frontend Web App β€” Web Routes - -## Introduction - -The **Frontend_Web_App_web_routes** module is the HTTP-facing layer of the CodeWiki Frontend Web App. It defines the FastAPI route handlers (`WebRoutes`), the request/response data contracts (`JobStatusResponse`, `RepositorySubmission`), and a lightweight Jinja2 rendering utility (`StringTemplateLoader` / `render_template`) used to turn in-code HTML template strings into rendered pages. - -This module is the entry point that end users and API clients interact with: it accepts GitHub repository submissions, shows job/queue status, and serves the generated Markdown documentation as HTML pages. It orchestrates β€” but does not implement β€” the actual job queueing, caching, and documentation generation logic, which live in the sibling [Frontend_Web_App_job_processing](Frontend_Web_App_job_processing.md) and [Frontend_Web_App_github_config](Frontend_Web_App_github_config.md) modules. - ---- - -## Module Responsibilities - -| Responsibility | Component | -|---|---| -| Render the main submission form and job list | `WebRoutes.index_get` | -| Validate and accept new repository submissions | `WebRoutes.index_post` | -| Expose job status as JSON (API) | `WebRoutes.get_job_status` | -| Redirect to a completed job's docs | `WebRoutes.view_docs` | -| Serve individual documentation pages (Markdown β†’ HTML) | `WebRoutes.serve_generated_docs` | -| Normalize GitHub URLs / derive job IDs | `WebRoutes._normalize_github_url`, `_repo_full_name_to_job_id`, `_job_id_to_repo_full_name` | -| Periodic cleanup of stale job records | `WebRoutes.cleanup_old_jobs` | -| Render Jinja2 string templates without file-based template loading | `template_utils.StringTemplateLoader`, `render_template`, `render_navigation`, `render_job_list` | -| Typed contracts for API responses and form submissions | `models.JobStatusResponse`, `models.RepositorySubmission` | - ---- - -## Architecture Overview - -`WebRoutes` is a thin controller class. It is constructed with references to a `BackgroundWorker` (job queue/processing) and a `CacheManager` (docs cache lookup) β€” both defined in [Frontend_Web_App_job_processing](Frontend_Web_App_job_processing.md). It also depends on `GitHubRepoProcessor` and `WebAppConfig` from [Frontend_Web_App_github_config](Frontend_Web_App_github_config.md), and the shared `file_manager` utility from [Core_Config_&_Utils](Core_Config_&_Utils.md). - -```mermaid -graph TD - subgraph "Frontend_Web_App_web_routes (this module)" - WR[WebRoutes] - TU[template_utils.render_template] - SL[StringTemplateLoader] - M1[models.JobStatusResponse] - M2[models.RepositorySubmission] - end - - subgraph "Frontend_Web_App_job_processing" - BW[BackgroundWorker] - CM[CacheManager] - JS[models.JobStatus] - end - - subgraph "Frontend_Web_App_github_config" - GP[GitHubRepoProcessor] - CFG[WebAppConfig] - end - - subgraph "Core_Config_&_Utils" - FM[FileManager / file_manager] - end - - WR --> BW - WR --> CM - WR --> GP - WR --> CFG - WR --> M1 - WR --> JS - WR --> FM - WR --> TU - TU --> SL - - Client[Browser / API Client] -->|HTTP requests| WR - BW --> CM -``` - ---- - -## Component Details - -### `WebRoutes` - -`WebRoutes` groups all FastAPI-facing endpoint handlers for the application. It is instantiated once at app startup with shared singleton instances of `BackgroundWorker` and `CacheManager`, then its bound methods are registered against FastAPI route paths (e.g. `/`, `/api/jobs/{job_id}`, `/docs/{job_id}`, `/static-docs/{job_id}/{filename}`) by the application bootstrap code. - -```mermaid -classDiagram - class WebRoutes { - -BackgroundWorker background_worker - -CacheManager cache_manager - +index_get(request) HTMLResponse - +index_post(request, repo_url, commit_id) HTMLResponse - +get_job_status(job_id) JobStatusResponse - +view_docs(job_id) RedirectResponse - +serve_generated_docs(job_id, filename) HTMLResponse - -_normalize_github_url(url) str - -_repo_full_name_to_job_id(full_name) str - -_job_id_to_repo_full_name(job_id) str - +cleanup_old_jobs() - } - class BackgroundWorker - class CacheManager - class GitHubRepoProcessor - class JobStatus - class JobStatusResponse - - WebRoutes --> BackgroundWorker - WebRoutes --> CacheManager - WebRoutes ..> GitHubRepoProcessor : uses (static) - WebRoutes ..> JobStatus : creates - WebRoutes ..> JobStatusResponse : returns -``` - -#### Endpoint behaviors - -**`index_get(request)`** -Renders the main landing page. Pulls all known jobs from `BackgroundWorker.get_all_jobs()`, sorts them newest-first, takes the top 100, and renders `WEB_INTERFACE_TEMPLATE` with an empty form and the job list. - -**`index_post(request, repo_url, commit_id)`** -Handles the submission form (`multipart/form-data`): -1. Calls `cleanup_old_jobs()` first. -2. Validates `repo_url` is non-empty and a valid GitHub URL via `GitHubRepoProcessor.is_valid_github_url`. -3. Normalizes the URL (`_normalize_github_url`) and derives a URL-safe `job_id` from `owner--repo`. -4. Checks for an existing job in `queue`/`processing` state, or a `failed` job within the retry cooldown window (`WebAppConfig.RETRY_COOLDOWN_MINUTES`) β€” if found, blocks resubmission with an informative message. -5. Otherwise checks the `CacheManager` for previously generated docs; if cached, synthesizes a `completed` `JobStatus` immediately (no processing needed). -6. Otherwise creates a new `queued` `JobStatus` and enqueues it via `BackgroundWorker.add_job`. -7. Re-renders the index page with a success/error message and the refreshed job list. - -**`get_job_status(job_id)`** -Simple JSON API: looks up `BackgroundWorker.get_job_status(job_id)`, raises `404` if missing, otherwise converts the `JobStatus` dataclass to a `JobStatusResponse` pydantic model via `asdict(job)`. - -**`view_docs(job_id)`** -Validates the job is `completed` and its `docs_path` exists on disk, then issues an HTTP 302 redirect to the static docs mount point (`/static-docs/{job_id}/`). - -**`serve_generated_docs(job_id, filename)`** -The core documentation viewer: -1. Looks up the job; if missing, attempts to reconstruct it by reverse-mapping `job_id` β†’ `owner/repo` (`_job_id_to_repo_full_name`) and checking the `CacheManager` directly β€” supporting deep-linking to docs whose original job record has been cleaned up. -2. Loads `module_tree.json` and `metadata.json` sidecar files from the docs directory if present (used for navigation and page metadata). -3. Reads the requested Markdown `filename`, converts it to HTML via `visualise_docs.markdown_to_html`, derives a page title via `get_file_title`, and renders it inside `DOCS_VIEW_TEMPLATE`. - -**`cleanup_old_jobs()`** -Removes `completed`/`failed` job records older than `WebAppConfig.JOB_CLEANUP_HOURS` from the in-memory `job_status` dict (does not touch the cache or on-disk docs). - -#### Data flow: Submitting a repository - -```mermaid -sequenceDiagram - participant U as User (Browser) - participant WR as WebRoutes - participant GP as GitHubRepoProcessor - participant CM as CacheManager - participant BW as BackgroundWorker - - U->>WR: POST / (repo_url, commit_id) - WR->>WR: cleanup_old_jobs() - WR->>GP: is_valid_github_url(repo_url) - GP-->>WR: true/false - alt invalid URL - WR-->>U: render index with error - else valid URL - WR->>GP: get_repo_info(url) - GP-->>WR: {owner, repo, full_name, clone_url} - WR->>WR: derive job_id - WR->>BW: get_job_status(job_id) - alt job active or recently failed - WR-->>U: render index with "already processing" error - else - WR->>CM: get_cached_docs(normalized_url) - alt cache hit - WR->>BW: job_status[job_id] = completed JobStatus - WR-->>U: render index with "found in cache" success - else cache miss - WR->>BW: add_job(job_id, queued JobStatus) - WR-->>U: render index with "added to queue" success - end - end - end -``` - -#### Data flow: Viewing documentation - -```mermaid -sequenceDiagram - participant U as User (Browser) - participant WR as WebRoutes - participant BW as BackgroundWorker - participant CM as CacheManager - participant FS as Filesystem - - U->>WR: GET /static-docs/{job_id}/{filename} - WR->>BW: get_job_status(job_id) - alt job found & completed - WR->>FS: check docs_path exists - else job not found - WR->>WR: _job_id_to_repo_full_name(job_id) - WR->>CM: get_cached_docs(potential_repo_url) - CM-->>WR: docs_path (or None) - WR->>BW: recreate JobStatus + save_job_statuses() - end - WR->>FS: load module_tree.json / metadata.json (optional) - WR->>FS: load_text(filename) - WR->>WR: markdown_to_html(content) - WR-->>U: render DOCS_VIEW_TEMPLATE (HTML) -``` - ---- - -### `template_utils.py` β€” String-based Jinja2 Rendering - -Because the web app embeds its HTML templates directly as Python string constants (in the `templates` module, e.g. `WEB_INTERFACE_TEMPLATE`, `DOCS_VIEW_TEMPLATE`) rather than loading them from `.html` files, this module provides a minimal Jinja2 integration that renders from in-memory strings. - -- **`StringTemplateLoader(BaseLoader)`** β€” a custom Jinja2 loader whose `get_source` simply returns the stored template string, bypassing filesystem template resolution. The `uptodate` callback always returns `True` since templates are immutable strings for the lifetime of the process. -- **`render_template(template, context)`** β€” builds a fresh `Environment` per call (autoescaping `html`/`xml`, with `trim_blocks`/`lstrip_blocks` enabled for cleaner output), loads the anonymous template (empty name `''`), and renders it with the given context dict. Used by every `WebRoutes` handler that returns `HTMLResponse`. -- **`render_navigation(module_tree, current_page)`** β€” helper that renders a documentation sidebar/nav from a hierarchical `module_tree` dict (as produced by the [Dependency_Analysis_Service](Dependency_Analysis_Service.md) / [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) pipeline and persisted as `module_tree.json`). Currently invoked ad hoc rather than wired directly into `serve_generated_docs` (which instead passes the raw `module_tree` dict into the page template's context for in-template iteration). -- **`render_job_list(jobs)`** β€” helper for rendering a list of `JobStatus`/`JobStatusResponse`-like objects as HTML job cards with status badges and "View Documentation" links. - -```mermaid -graph LR - A[Template string constant<br/>e.g. WEB_INTERFACE_TEMPLATE] --> B[StringTemplateLoader] - B --> C[Jinja2 Environment] - D[context dict] --> C - C --> E[render_template] --> F[Rendered HTML string] - F --> G[HTMLResponse to client] -``` - ---- - -### `models.py` (route-relevant subset) β€” `JobStatusResponse` & `RepositorySubmission` - -While the full `models.py` file also defines `JobStatus` and `CacheEntry` (owned conceptually by [Frontend_Web_App_job_processing](Frontend_Web_App_job_processing.md)), this module's routes specifically depend on two Pydantic models that define the **external API contract**: - -- **`RepositorySubmission`** β€” a Pydantic `BaseModel` with a single validated `repo_url: HttpUrl` field. This represents the strict/typed shape of a repository submission (useful for JSON API clients), complementing the looser `Form(...)`-based parsing used directly in `index_post` for the HTML form flow. -- **`JobStatusResponse`** β€” the Pydantic response model returned by `get_job_status`. It mirrors the internal `JobStatus` dataclass field-for-field (`job_id`, `repo_url`, `status`, timestamps, `progress`, `docs_path`, `main_model`, `commit_id`), but as a `BaseModel` it gets automatic JSON serialization, OpenAPI schema generation, and datetime encoding β€” decoupling the internal job-tracking representation from the public API shape. - -```mermaid -classDiagram - class JobStatus { - <<dataclass (job_processing)>> - job_id: str - repo_url: str - status: str - created_at: datetime - started_at: datetime? - completed_at: datetime? - error_message: str? - progress: str - docs_path: str? - main_model: str? - commit_id: str? - } - class JobStatusResponse { - <<pydantic BaseModel>> - job_id: str - repo_url: str - status: str - created_at: datetime - started_at: datetime? - completed_at: datetime? - error_message: str? - progress: str - docs_path: str? - main_model: str? - commit_id: str? - } - class RepositorySubmission { - <<pydantic BaseModel>> - repo_url: HttpUrl - } - - JobStatus ..> JobStatusResponse : asdict() β†’ **kwargs -``` - ---- - -## External Dependencies - -| Dependency | Module | Role | -|---|---|---| -| `BackgroundWorker` | [Frontend_Web_App_job_processing](Frontend_Web_App_job_processing.md) | Job queue, in-memory job status store, async documentation generation orchestration | -| `CacheManager` | [Frontend_Web_App_job_processing](Frontend_Web_App_job_processing.md) | Lookup/storage of previously generated docs keyed by hashed repo URL | -| `JobStatus` | [Frontend_Web_App_job_processing](Frontend_Web_App_job_processing.md) (`models.py`) | Internal dataclass representing a job's lifecycle state | -| `GitHubRepoProcessor` | [Frontend_Web_App_github_config](Frontend_Web_App_github_config.md) | URL validation, repo info extraction, repository cloning | -| `WebAppConfig` | [Frontend_Web_App_github_config](Frontend_Web_App_github_config.md) | Central configuration (cache dirs, cleanup thresholds, retry cooldowns) | -| `file_manager` (`FileManager`) | [Core_Config_&_Utils](Core_Config_&_Utils.md) | JSON/text file I/O (`module_tree.json`, `metadata.json`, markdown content) | -| `visualise_docs.markdown_to_html`, `get_file_title` | Frontend Web App (sibling utility, not in this module's core components) | Converts generated Markdown documentation into displayable HTML with title extraction | -| `templates.WEB_INTERFACE_TEMPLATE`, `templates.DOCS_VIEW_TEMPLATE` | Frontend Web App templates | String-based HTML templates rendered via `template_utils.render_template` | - ---- - -## How This Module Fits the System - -The overall CodeWiki pipeline flows roughly as: - -1. A user submits a GitHub repo through **Frontend_Web_App_web_routes** (`WebRoutes.index_post`). -2. The job is queued via **Frontend_Web_App_job_processing** (`BackgroundWorker`), which clones the repo (**Frontend_Web_App_github_config**), invokes the **[Dependency_Analysis_Service](Dependency_Analysis_Service.md)** and **[Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)** to build a dependency/call graph using the appropriate **[Language_Analyzers](Language_Analyzers.md)**, then hands off to **[Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md)** (`DocumentationGenerator`) to produce Markdown documentation files on disk. -3. Results are cached (`CacheManager`) and job state is persisted (`BackgroundWorker.save_job_statuses`). -4. Users poll or view results back through **Frontend_Web_App_web_routes** β€” `get_job_status` for programmatic polling, `view_docs`/`serve_generated_docs` for the rendered documentation viewer. - -This module is therefore the **presentation and API boundary** of the Frontend Web App: it never performs cloning, analysis, or generation itself, delegating all heavy lifting to the job-processing and backend service layers while focusing purely on HTTP request handling, validation, and HTML rendering. diff --git a/docs/JavaScript_TypeScript_Analyzers.md b/docs/JavaScript_TypeScript_Analyzers.md deleted file mode 100644 index 3514d28f..00000000 --- a/docs/JavaScript_TypeScript_Analyzers.md +++ /dev/null @@ -1,134 +0,0 @@ -# JavaScript & TypeScript Analyzers - -## Purpose - -The `JavaScript_TypeScript_Analyzers` module provides static source-code analysis for JavaScript and TypeScript files within CodeWiki's dependency analysis pipeline. It parses source files using [tree-sitter](https://tree-sitter.github.io/tree-sitter/) grammars, extracts structural "components" (functions, classes, methods, interfaces, enums, type aliases, etc.), and infers **call/inheritance/type relationships** between them. The output feeds directly into the system-wide dependency graph that powers CodeWiki's documentation generation and code navigation features. - -This module is a sibling of the other language-specific analyzers documented under [Language_Analyzers.md](Language_Analyzers.md), and its outputs conform to the shared data model defined in [Dependency_Analyzer_Core.md](Dependency_Analyzer_Core.md) (`Node` and `CallRelationship`). It is invoked by the orchestration layer described in [Dependency_Analysis_Service.md](Dependency_Analysis_Service.md). - -## Module Position in the System - -```mermaid -flowchart TB - subgraph Orchestration["Dependency Analysis Service"] - RA[RepoAnalyzer] - AS[AnalysisService] - end - - subgraph Core["Dependency Analyzer Core"] - DP[DependencyParser] - DGB[DependencyGraphBuilder] - Node[Node model] - CR[CallRelationship model] - end - - subgraph ThisModule["JavaScript_TypeScript_Analyzers"] - JS[TreeSitterJSAnalyzer] - TS[TreeSitterTSAnalyzer] - end - - subgraph Siblings["Other Language_Analyzers"] - PY[PythonASTAnalyzer] - PHP[TreeSitterPHPAnalyzer] - CFAM[C-Family Tree-sitter Analyzers] - end - - RA --> DP - DP -->|per-file dispatch by extension| JS - DP -->|per-file dispatch by extension| TS - DP -->|per-file dispatch| PY - DP -->|per-file dispatch| PHP - DP -->|per-file dispatch| CFAM - - JS -->|produces| Node - JS -->|produces| CR - TS -->|produces| Node - TS -->|produces| CR - - Node --> DGB - CR --> DGB - DGB --> AS -``` - -The two analyzers in this module are functionally independent (no shared base class), but they follow an identical **contract**: - -1. Accept a file path, its raw text content, and the repository root path. -2. Parse the content into a tree-sitter AST. -3. Walk the AST to extract top-level declarations as `Node` objects. -4. Walk the AST again (or in the same pass) to extract `CallRelationship` objects describing calls, instantiations, inheritance, and type references between those declarations. -5. Expose the results either via analyzer instance attributes (`.nodes`, `.call_relationships`) or via a module-level convenience function (`analyze_javascript_file_treesitter` / `analyze_typescript_file_treesitter`). - -## Sub-modules - -| Sub-module | Description | Documentation | -|---|---|---| -| JavaScript Analyzer | Parses `.js`/`.jsx`/`.mjs`/`.cjs` files with the tree-sitter JavaScript grammar; single-pass declaration + call extraction; JSDoc-based type dependency mining. | [JavaScript_TypeScript_Analyzers_javascript.md](JavaScript_TypeScript_Analyzers_javascript.md) | -| TypeScript Analyzer | Parses `.ts`/`.tsx` files with the tree-sitter TypeScript grammar; two-phase "collect all entities, then filter to top-level" extraction; native TS type-annotation and generics resolution. | [JavaScript_TypeScript_Analyzers_typescript.md](JavaScript_TypeScript_Analyzers_typescript.md) | - -## Shared Design Concepts - -Although implemented separately, both analyzers share the following design patterns, which are useful to understand before reading the sub-module docs: - -### 1. Component Identity - -Every extracted declaration becomes a `Node` (defined in [Dependency_Analyzer_Core.md](Dependency_Analyzer_Core.md)) whose `id`/`component_id` follows the pattern: - -``` -<relative_file_path>::<name> -<relative_file_path>::<ClassName>.<methodName> (for methods) -``` - -This id scheme lets the global `DependencyGraphBuilder` merge per-file results into one project-wide graph without collisions. - -### 2. Receiver-First Call Resolution - -Both analyzers resolve `expr.method()` call expressions by inspecting the **receiver** of the member expression before falling back to a bare (unresolved) name: - -- `this.method()` / `super.method()` β†’ resolved against the enclosing class (and, for `super`, its declared base classes). -- `identifier.method()` where `identifier` is itself a top-level class name β†’ resolved as a static/qualified call. -- `identifier.method()` where `identifier` is a local variable β†’ resolved by scanning the enclosing scope for a `new ClassName(...)` initializer or (TypeScript only) a type annotation. -- Dotted chains (`a.b.c()`) with no resolvable root, or calls on composite/literal receivers β†’ recorded as an **unresolved bare name**, unless the tail is a well-known built-in prototype method (e.g. `Array.prototype.map`), in which case the call is dropped entirely to avoid noise. - -This resolution strategy is what allows CodeWiki's later graph-merging phase to stitch together cross-file relationships (an unresolved callee name gets matched against other files' top-level names by the global resolver in `DependencyGraphBuilder`). - -### 3. Relationship De-duplication - -Both analyzers maintain a `seen_relationships` set keyed by `(caller, callee, call_line)` (JS) or `(caller_id, callee_id)` (TS) to avoid emitting duplicate `CallRelationship` entries when the same call site is visited more than once during traversal. - -### 4. Resolved vs. Unresolved Callees - -`CallRelationship.is_resolved` is `True` only when the callee could be matched to a `Node` already known within the *same file*. Unresolved relationships carry a bare logical name (e.g. `"Foo.bar"` instead of `"src/foo.ts::Foo.bar"`) which is left for the cross-file resolution stage in [Dependency_Analyzer_Core.md](Dependency_Analyzer_Core.md) / [Dependency_Analysis_Service.md](Dependency_Analysis_Service.md). - -## High-Level Processing Flow - -```mermaid -sequenceDiagram - participant Caller as RepoAnalyzer / DependencyParser - participant Analyzer as TreeSitterJSAnalyzer / TreeSitterTSAnalyzer - participant TS as tree-sitter Parser - participant Graph as DependencyGraphBuilder - - Caller->>Analyzer: __init__(file_path, content, repo_path) - Analyzer->>TS: parse(content) - TS-->>Analyzer: AST root_node - Caller->>Analyzer: analyze() - Analyzer->>Analyzer: extract top-level Nodes (functions, classes, methods, ...) - Analyzer->>Analyzer: traverse AST for call/inheritance/type relationships - Analyzer-->>Caller: self.nodes, self.call_relationships - Caller->>Graph: merge Nodes + CallRelationships from all files - Graph-->>Graph: resolve cross-file unresolved callees -``` - -## Relevant External Dependencies - -- **tree-sitter / tree_sitter_javascript / tree_sitter_typescript** β€” the underlying parsing libraries. -- `codewiki/src/be/dependency_analyzer/models/core.py` (`Node`, `CallRelationship`) β€” the shared output schema, documented in [Dependency_Analyzer_Core.md](Dependency_Analyzer_Core.md). -- `codewiki/src/be/dependency_analyzer/utils/external_symbols.py` (`JS_TS_PROTOTYPE_METHODS`) β€” a shared list of known built-in prototype method names used by both analyzers to suppress false-positive unresolved relationships. -- `codewiki/src/be/dependency_analyzer/ast_parser.py` (`DependencyParser`) β€” dispatches files to the correct analyzer by extension; see [Dependency_Analyzer_Core.md](Dependency_Analyzer_Core.md). -- `codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py` (`RepoAnalyzer`) β€” walks the repository tree and invokes the parser per file; see [Dependency_Analysis_Service.md](Dependency_Analysis_Service.md). - -## See Also - -- [Language_Analyzers.md](Language_Analyzers.md) β€” parent module overview covering all language analyzers (C-family, PHP, Python, JS/TS). -- [Dependency_Analyzer_Core.md](Dependency_Analyzer_Core.md) β€” the `Node`/`CallRelationship` models and the graph builder that consumes this module's output. -- [Dependency_Analysis_Service.md](Dependency_Analysis_Service.md) β€” the orchestrating service that walks a repository and invokes analyzers file-by-file. diff --git a/docs/JavaScript_TypeScript_Analyzers_javascript.md b/docs/JavaScript_TypeScript_Analyzers_javascript.md deleted file mode 100644 index f8fb9732..00000000 --- a/docs/JavaScript_TypeScript_Analyzers_javascript.md +++ /dev/null @@ -1,256 +0,0 @@ -# JavaScript Analyzer (`JavaScript_TypeScript_Analyzers_javascript`) - -## Introduction - -The **JavaScript Analyzer** module is a language-specific static analysis component of CodeWiki's [Dependency Analysis Service](Dependency_Analysis_Service.md). It parses `.js` / `.jsx` / `.mjs` / `.cjs` source files using [tree-sitter](https://tree-sitter.github.io/tree-sitter/) grammars, extracts structural entities (functions, classes, methods) as `Node` objects, and infers call/inheritance/type relationships between them as `CallRelationship` objects. - -Its output feeds directly into the [Dependency Analyzer Core](Dependency_Analyzer_Core.md), where per-file resolved and unresolved relationships from all languages are merged into a single project-wide dependency graph. This graph is the foundation for the documentation generation pipeline (see [Backend LLM & Documentation Services](Backend_LLM_&_Documentation_Services.md)). - -The module is a sibling of the [TypeScript Analyzer](JavaScript_TypeScript_Analyzers_typescript.md) β€” the two share nearly identical extraction/resolution strategies (TypeScript's analyzer is effectively a superset that additionally understands type annotations, interfaces, and generics), and both share the parent grouping `JavaScript_TypeScript_Analyzers`. - ---- - -## Purpose & Scope - -`TreeSitterJSAnalyzer` (in `codewiki/src/be/dependency_analyzer/analyzers/javascript.py`) is responsible for: - -1. **Parsing** a single JavaScript source file into an AST using `tree_sitter_javascript`. -2. **Extracting top-level components**: classes (and abstract classes/interfaces, which JS syntax trees can contain when mixed with `.jsx`/ambient constructs), standalone functions (including generators and arrow functions assigned to `const`/`let`/`var`), and class methods (including arrow-function class fields). -3. **Building intra-file relationships**: function/method calls, `new` expression construction, class inheritance (`extends`), and JSDoc-derived type dependencies (`@param`, `@returns`, `@type`, `@typedef`, `@interface`). -4. **Emitting `Node` and `CallRelationship` objects** that conform to the shared [Dependency Analyzer Core](Dependency_Analyzer_Core.md) data models, ready for cross-file/cross-language resolution by `CallGraphAnalyzer`. - -The module purposefully does **not** attempt project-wide (cross-file) symbol resolution β€” that responsibility belongs to `CallGraphAnalyzer._resolve_call_relationships`, which merges per-file `is_resolved=False` "bare name" callees against a global index built from every analyzed file. - ---- - -## Architecture Overview - -```mermaid -graph TB - subgraph "Language_Analyzers Parent" - JS[TreeSitterJSAnalyzer<br/>javascript.py] - TS[TreeSitterTSAnalyzer<br/>typescript.py] - end - - subgraph "Dependency_Analysis_Service" - CGA[CallGraphAnalyzer] - AS[AnalysisService] - RA[RepoAnalyzer] - end - - subgraph "Dependency_Analyzer_Core" - DP[DependencyParser] - Node[Node model] - CallRel[CallRelationship model] - end - - RA -->|file tree| AS - AS -->|"code_files list"| CGA - CGA -->|".js/.jsx/.mjs/.cjs files"| JS - CGA -->|".ts/.tsx files"| TS - JS -->|"analyze_javascript_file_treesitter()"| CGA - JS -.produces.-> Node - JS -.produces.-> CallRel - CGA -->|"functions, relationships"| DP - DP -->|"components dict"| Downstream[Documentation Generator] - - style JS fill:#f9d77e,stroke:#333,stroke-width:2px -``` - -- **Entry point**: `analyze_javascript_file_treesitter(file_path, content, repo_path)` β€” a module-level function wrapping `TreeSitterJSAnalyzer`, called by `CallGraphAnalyzer._analyze_javascript_file` (see [Dependency Analysis Service](Dependency_Analysis_Service.md)). -- **Output consumption**: Returned `(nodes, relationships)` tuples are merged into `CallGraphAnalyzer.functions` / `call_relationships`, later cross-resolved and deduplicated, then converted into the final `components` dictionary by `DependencyParser` in [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md). - ---- - -## Component Diagram - -```mermaid -classDiagram - class TreeSitterJSAnalyzer { - +file_path: Path - +content: str - +repo_path: str - +nodes: List~Node~ - +call_relationships: List~CallRelationship~ - +top_level_nodes: dict - +seen_relationships: set - +analyze() void - -_extract_functions(node) void - -_traverse_for_functions(node) void - -_extract_methods_from_class(class_node, class_name) void - -_extract_class_declaration(node) Node - -_extract_function_declaration(node) Node - -_extract_exported_function(node) Node - -_extract_arrow_function_from_declaration(node) Node - -_create_method_node(node, method_name, class_name) Node - -_extract_call_relationships(node) void - -_traverse_for_calls(node, current_top_level) void - -_extract_call_from_node(node, caller_name) CallRelationship - -_receiver_class(call_node, identifier) str - -_extract_jsdoc_type_dependencies(node, caller_name) void - -_parse_jsdoc_types(comment_text, caller_name, line) void - -_get_component_id(name, class_name, is_method) str - } - - class Node { - <<pydantic model>> - +id: str - +name: str - +component_type: str - +depends_on: Set~str~ - +source_code: str - +base_classes: List~str~ - +class_name: str - +qualified_name: str - } - - class CallRelationship { - <<pydantic model>> - +caller: str - +callee: str - +call_line: int - +is_resolved: bool - } - - TreeSitterJSAnalyzer --> Node : creates - TreeSitterJSAnalyzer --> CallRelationship : creates -``` - -Refer to [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) for the full `Node` / `CallRelationship` model definitions shared across all language analyzers. - ---- - -## Analysis Pipeline (Process Flow) - -```mermaid -sequenceDiagram - participant CGA as CallGraphAnalyzer - participant Fn as analyze_javascript_file_treesitter() - participant TSA as TreeSitterJSAnalyzer - participant TS as tree-sitter parser - - CGA->>Fn: file_path, content, repo_path - Fn->>TSA: __init__() - TSA->>TS: Parser(js_language) - Fn->>TSA: analyze() - TSA->>TS: parser.parse(content) - TS-->>TSA: AST root_node - TSA->>TSA: _extract_functions(root_node) - Note over TSA: Pass 1 - Structural extraction<br/>classes, functions, methods - TSA->>TSA: _extract_call_relationships(root_node) - Note over TSA: Pass 2 - Relationship extraction<br/>calls, new, inheritance, JSDoc types - TSA-->>Fn: nodes, call_relationships - Fn-->>CGA: (nodes, call_relationships) - Note over CGA: Merged into global functions/relationships<br/>then cross-file resolved -``` - -### Two-Pass Design - -The analyzer performs **two independent tree traversals**: - -1. **Structural pass** (`_extract_functions` β†’ `_traverse_for_functions`): Walks the AST once to discover all declaration-like nodes and populate `self.nodes` and `self.top_level_nodes` (a name β†’ `Node` lookup used later for resolution). This pass must complete before relationship extraction, since resolution needs to know which names are legitimate top-level/method components in this file. -2. **Relationship pass** (`_extract_call_relationships` β†’ `_traverse_for_calls`): Walks the AST again, tracking a `current_top_level` "scope" (the enclosing function/method/class name) as it descends, and emitting a `CallRelationship` whenever it encounters a `call_expression`, `await_expression` wrapping a call, `new_expression`, class `extends` heritage, or a JSDoc comment with type annotations. - ---- - -## Entity Extraction Details - -| AST Node Type | Extraction Method | Resulting `component_type` | -|---|---|---| -| `class_declaration` / `abstract_class_declaration` / `interface_declaration` | `_extract_class_declaration` | `class` / `abstract class` / `interface` | -| `method_definition` (inside `class_body`) | `_create_method_node` | `method` (constructor excluded from output, but tracked in `top_level_nodes`) | -| `field_definition` with arrow-function value | `_create_method_node` | `method` | -| `function_declaration` / `generator_function_declaration` (not nested in a class) | `_extract_function_declaration` | `function` | -| `export_statement` wrapping a function | `_extract_exported_function` | `function` (renamed to `"default"` for `export default function (...)`) | -| `lexical_declaration` (`const`/`let` assigned an arrow/function expression) | `_extract_arrow_function_from_declaration` | `function` | - -Component IDs follow the pattern `"{relative_path}::{name}"` for top-level entities and `"{relative_path}::{ClassName}.{methodName}"` for methods, generated by `_get_component_id`. - -```mermaid -flowchart LR - A[AST root_node] --> B{node.type} - B -->|class_declaration| C[_extract_class_declaration] - C --> D[_extract_methods_from_class] - D --> E[method_definition -> _create_method_node] - D --> F[field_definition arrow fn -> _create_method_node] - B -->|function_declaration| G[_extract_function_declaration] - B -->|export_statement| H[_extract_exported_function] - B -->|lexical_declaration| I[_extract_arrow_function_from_declaration] - C & G & H & I & E & F --> J[nodes list + top_level_nodes map] -``` - ---- - -## Relationship Resolution Strategy - -Unlike languages with static typing, JavaScript calls must be resolved heuristically. The analyzer classifies each `call_expression`'s callee node and applies receiver-specific logic in `_extract_call_from_node`: - -```mermaid -flowchart TD - Start[call_expression / new_expression] --> Kind{callee node type} - Kind -->|identifier| Plain[Look up name in top_level_nodes] - Kind -->|member_expression: this/super| ThisSuper[Resolve against enclosing class<br/>+ its base_classes chain] - Kind -->|member_expression: identifier receiver| Receiver["Check if receiver is a known class name,<br/>else search enclosing scope for<br/>new X initializer via _receiver_class"] - Kind -->|member_expression: chained identifiers| Chain[Flatten dotted chain via _identifier_chain<br/>emit unresolved dotted name] - Kind -->|composite/literal receiver| Builtin{tail in JS_TS_PROTOTYPE_METHODS?} - Builtin -->|yes| Drop[No relationship emitted<br/>known JS builtin method] - Builtin -->|no| Emit[Emit unresolved bare name] - - Plain --> Resolved[is_resolved = name in top_level_nodes] - ThisSuper --> Resolved2[is_resolved = ClassName.method found] - Receiver --> Resolved3[is_resolved = Class.method found] - Chain --> Unresolved[is_resolved = False] -``` - -Key design principles (shared with the [TypeScript Analyzer](JavaScript_TypeScript_Analyzers_typescript.md)): - -- **Never file-prefix unresolved names.** An unresolved callee (e.g. a call to a function defined in another file, or an external library call) is emitted as a bare logical name (`"someFunc"` or `"Class.method"`), *not* `"path::someFunc"`. This lets `CallGraphAnalyzer._resolve_call_relationships` attempt project-wide resolution using its global name indexes, and lets it correctly classify genuinely external calls (see `_is_external_callee` in [Dependency_Analysis_Service](Dependency_Analysis_Service.md)). -- **Receiver-first resolution for member calls.** `this.foo()` / `super.foo()` resolve against the enclosing class and its declared base classes; `obj.foo()` resolves against `obj`'s inferred class (either because `obj` itself is a known top-level class, or because a `new ClassName()` initializer for that identifier is found in an enclosing scope via `_receiver_class`/`_find_new_initializer`). -- **Prototype-method filtering.** Calls like `array.map(...)` or `str.trim()` on receivers whose type cannot be determined are checked against `JS_TS_PROTOTYPE_METHODS` (a shared built-in method name set) and silently dropped rather than emitted as spurious unresolved relationships. -- **Deduplication.** `_add_relationship` uses a `(caller, callee, call_line)` tuple in `seen_relationships` to avoid duplicate edges from repeated traversal paths (e.g. `await` wrapping a `call_expression`). - -### JSDoc Type Dependencies - -Because plain JavaScript lacks static types, the analyzer additionally mines **JSDoc comments** for type references via `_extract_jsdoc_type_dependencies` β†’ `_parse_jsdoc_types`, recognizing `@param {Type}`, `@returns {Type}`, `@type {Type}`, `@typedef {Object} Name`, and `@interface Name` patterns. Extracted type names are filtered against a built-in-type blocklist (`_is_builtin_type_js`) before being emitted as relationships β€” this lets JSDoc-annotated JS codebases participate in the same dependency graph as strongly-typed languages. - ---- - -## Data Model Reference - -The analyzer produces instances of two Pydantic models defined centrally in [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md): - -- **`Node`** β€” one row per structural component (function/class/method), including `source_code`, `start_line`/`end_line`, `base_classes`, `class_name`, `display_name`, and the crucial `component_id` used as a graph key. -- **`CallRelationship`** β€” a directed edge `caller -> callee`, with `call_line` and `is_resolved` (whether `callee` is a fully-qualified component id vs. a bare logical name awaiting global resolution). - -These models are language-agnostic; the JS analyzer is only responsible for populating them correctly from tree-sitter's JavaScript grammar output. - ---- - -## Integration Points - -| Consumer | How it uses this module | -|---|---| -| [`CallGraphAnalyzer`](Dependency_Analysis_Service.md) | Calls `analyze_javascript_file_treesitter()` per `.js`/`.jsx`/`.mjs`/`.cjs` file found by `RepoAnalyzer`, merges results into the global function/relationship pools, then performs cross-file/cross-language resolution and external-call filtering. | -| [`DependencyParser`](Dependency_Analyzer_Core.md) | Consumes the final merged `functions`/`relationships` output (after `CallGraphAnalyzer` processing) to build the `components: Dict[str, Node]` graph with populated `depends_on` sets. | -| [Documentation Generator](Backend_LLM_&_Documentation_Services.md) | Uses the resulting dependency graph (nodes + edges) as grounding context when generating module/component documentation via LLM prompts. | - -```mermaid -graph LR - Repo[Repository .js/.jsx files] --> RA[RepoAnalyzer] - RA --> CGA[CallGraphAnalyzer] - CGA --> JSA[TreeSitterJSAnalyzer] - JSA --> CGA - CGA -->|resolved graph| DP[DependencyParser] - DP --> DG[DocumentationGenerator] - DG --> Docs[Generated Markdown Docs] -``` - ---- - -## Related Documentation - -- [Language_Analyzers](Language_Analyzers.md) β€” parent grouping covering all per-language tree-sitter/AST analyzers. -- [JavaScript_TypeScript_Analyzers_typescript](JavaScript_TypeScript_Analyzers_typescript.md) β€” the TypeScript sibling analyzer; shares the same resolution philosophy with added type-annotation awareness. -- [Dependency_Analysis_Service](Dependency_Analysis_Service.md) β€” orchestrates `RepoAnalyzer` (file discovery) and `CallGraphAnalyzer` (per-file dispatch + cross-file resolution). -- [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) β€” shared `Node`/`CallRelationship` models and the `DependencyParser` that assembles the final component graph. -- [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) β€” downstream consumer that turns the dependency graph into generated documentation. diff --git a/docs/JavaScript_TypeScript_Analyzers_typescript.md b/docs/JavaScript_TypeScript_Analyzers_typescript.md deleted file mode 100644 index 550fc139..00000000 --- a/docs/JavaScript_TypeScript_Analyzers_typescript.md +++ /dev/null @@ -1,321 +0,0 @@ -# JavaScript_TypeScript_Analyzers_typescript - -## Introduction - -The `JavaScript_TypeScript_Analyzers_typescript` module implements **`TreeSitterTSAnalyzer`**, the TypeScript-specific static-analysis engine used by CodeWiki's [Dependency Analysis Service](Dependency_Analysis_Service.md) to build a language-agnostic dependency/call graph. - -Given the raw source text of a `.ts`/`.tsx` file, the analyzer parses it with [`tree-sitter`](https://tree-sitter.github.io/) (via the `tree_sitter_typescript` grammar), extracts all **top-level components** (functions, classes, interfaces, type aliases, enums, exported constants, ambient/namespace declarations, class methods), and infers the **call/inheritance/type relationships** between them. The output is a pair of framework-neutral model objects β€” `List[Node]` and `List[CallRelationship]` (defined in [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)) β€” that feed into the cross-file, cross-language resolution step performed by `CallGraphAnalyzer`. - -This module is the TypeScript counterpart to [`JavaScript_TypeScript_Analyzers_javascript`](JavaScript_TypeScript_Analyzers_javascript.md) (`TreeSitterJSAnalyzer`). Both share the parent grouping [`JavaScript_TypeScript_Analyzers`](JavaScript_TypeScript_Analyzers.md) and largely mirror each other's design, with the TypeScript analyzer additionally understanding TS-only syntax: interfaces, type aliases, enums, `type_annotation`/`type_arguments`, `implements_clause`, ambient/namespace declarations, and generics. - ---- - -## Module Position in the System - -```mermaid -graph TB - subgraph "Dependency_Analysis_Service" - AS[AnalysisService] - CGA[CallGraphAnalyzer] - RA[RepoAnalyzer] - end - - subgraph "Dependency_Analyzer_Core" - DP[DependencyParser] - Node[Node model] - CR[CallRelationship model] - end - - subgraph "Language_Analyzers" - subgraph "JavaScript_TypeScript_Analyzers" - subgraph "JavaScript_TypeScript_Analyzers_typescript (this module)" - TSA[TreeSitterTSAnalyzer] - FN[analyze_typescript_file_treesitter] - end - JSA[TreeSitterJSAnalyzer] - end - PY[PythonASTAnalyzer] - JAVA[TreeSitterJavaAnalyzer] - OTHER[C / C++ / C# / Kotlin / PHP analyzers] - end - - DP --> AS - AS --> CGA - CGA -->|"language == 'typescript'"| FN - FN --> TSA - TSA -->|produces| Node - TSA -->|produces| CR - CGA -->|resolves cross-file/global| CR - CGA -.similar interface.-> JSA - CGA -.similar interface.-> PY - CGA -.similar interface.-> JAVA - CGA -.similar interface.-> OTHER -``` - -The entry point `analyze_typescript_file_treesitter(file_path, content, repo_path)` is invoked by `CallGraphAnalyzer._analyze_typescript_file` (see [Dependency_Analysis_Service](Dependency_Analysis_Service.md)) for every source file whose detected language is `typescript`. The analyzer never talks to disk directly (besides implicitly through the path it is given) and never performs cross-file resolution β€” that responsibility belongs entirely to `CallGraphAnalyzer`, which merges nodes/relationships from all files and files across all supported languages. - ---- - -## Responsibilities - -| Responsibility | Description | -|---|---| -| **Parsing** | Initializes a `tree_sitter.Parser` bound to the `tree_sitter_typescript` TypeScript grammar and parses file content into an AST. | -| **Entity extraction** | Walks the whole AST once, capturing *every* named declaration (functions, arrow functions, methods, classes, interfaces, type aliases, enums, variables, export statements, ambient/namespace declarations) into a flat `all_entities` dict keyed by name, tagging each with its AST node, depth, and parent context. | -| **Top-level filtering** | Re-examines each captured entity and keeps only those that are truly top-level (module scope, exported, or declared in an ambient/namespace `module`/`statement_block`), discarding anything nested inside a function body. | -| **Node construction** | Converts each qualifying top-level entity into a `Node` (from [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)) with a stable `component_id` of the form `<relative_path>::<name>`. | -| **Relationship extraction** | Performs a second AST traversal, tracking "current top-level" context, to emit `CallRelationship` records for: function/method calls, `new` expressions, type annotations, generic type arguments, and `extends`/`implements` clauses. | -| **Local resolution** | Resolves receiver types (`this`, `super`, typed variables, `new X()` inference) to same-file component ids whenever possible; anything it cannot resolve is emitted as a bare logical name for the global resolver in `CallGraphAnalyzer` to attempt cross-file resolution. | - ---- - -## Core Component: `TreeSitterTSAnalyzer` - -### Construction & Initialization - -```mermaid -sequenceDiagram - participant Caller as analyze_typescript_file_treesitter - participant TSA as TreeSitterTSAnalyzer - participant TS as tree_sitter_typescript - - Caller->>TSA: __init__(file_path, content, repo_path) - TSA->>TS: language_typescript() - TS-->>TSA: language capsule - TSA->>TSA: Language(capsule) / Parser(language) - alt init fails - TSA->>TSA: parser = None (analysis becomes a no-op) - end - Caller->>TSA: analyze() - TSA-->>Caller: (nodes, call_relationships) via analyzer.nodes / .call_relationships -``` - -Key instance state: -- `nodes: List[Node]` β€” final top-level components discovered in the file. -- `call_relationships: List[CallRelationship]` β€” all relationships discovered. -- `seen_relationships: Set[Tuple[str,str]]` β€” de-duplication key (`caller_id`, `callee_id`). -- `top_level_nodes: Dict[str, Node]` β€” name β†’ `Node` lookup used throughout resolution to check "is this name defined in this file?". - -If the tree-sitter grammar fails to load, `self.parser` is `None` and `analyze()` becomes a safe no-op (logged at debug level), so a broken native binding never crashes the wider analysis pipeline. - -### High-Level Pipeline (`analyze()`) - -```mermaid -flowchart TD - A[analyze] --> B[parser.parse content β†’ AST root_node] - B --> C["_extract_all_entities(root_node, all_entities)"] - C --> D["_filter_top_level_declarations(all_entities)"] - D --> E["_extract_all_relationships(root_node, all_entities)"] - E --> F[self.nodes / self.call_relationships populated] - - subgraph "Pass 1: Entity Collection" - C - end - subgraph "Pass 2: Top-level Filtering + Node creation" - D - end - subgraph "Pass 3: Relationship Extraction" - E - end -``` - -The analyzer makes **three full passes** over the AST: - -1. **`_extract_all_entities`** – recursively visits every node, dispatching by `node.type` to one of the `_extract_*_entity` helper methods (see table below). Each recognized declaration becomes a dict entry in `all_entities[name]`, annotated with `depth`, `node` (raw AST node reference), and `parent_context`. -2. **`_filter_top_level_declarations`** – for every captured entity, calls `_is_actually_top_level` to decide whether it belongs at module/export/ambient scope (as opposed to being nested inside a function body). Qualifying entities become `Node` objects via `_create_node_from_entity`, subject to an exclusion filter (`_should_include_node`) that drops variables and names like `constructor`/`__proto__`/`prototype`. Class/abstract-class entities additionally trigger `_extract_constructor_dependencies` to capture constructor-parameter type dependencies (dependency-injection style wiring). -3. **`_extract_all_relationships`** – re-walks the AST maintaining a "current top-level" name as it descends, and emits relationships whenever it encounters call expressions, `new` expressions, type annotations, generic type arguments, or inheritance clauses. - -### Entity Types Recognized - -| AST node type | Extraction method | Resulting `Node.component_type` | Notes | -|---|---|---|---| -| `function_declaration` | `_extract_function_entity` | `function` | detects `async` | -| `generator_function_declaration` | `_extract_function_entity` | `function` | subtype `generator_function` | -| `arrow_function` (via `variable_declarator`) | `_extract_arrow_function_entity` | `function` | subtype `arrow_function` | -| `method_definition` | `_extract_method_entity` | `function` | name qualified as `Class.method`; detects `async`/`static` | -| `class_declaration` / `abstract_class_declaration` | `_extract_class_entity` | `class` | captures `extends`/`implements` as `base_classes` | -| `interface_declaration` | `_extract_interface_entity` | `interface` | captures `extends` | -| `type_alias_declaration` | `_extract_type_alias_entity` | `type` | | -| `enum_declaration` | `_extract_enum_entity` | `enum` | | -| `variable_declarator` / `lexical_declaration` / `variable_declaration` | `_extract_variable_entity` / `_extract_lexical_declaration_entity` / `_extract_variable_declaration_entity` | `variable` | excluded from final `nodes` list (see `_should_include_node`), but still tracked in `all_entities` for relationship resolution | -| `export_statement` | `_extract_export_statement_entity` | `function` / `class` / `interface` | unwraps the exported function/class/interface/const-arrow-function/default-call-export | -| `ambient_declaration` | `_extract_ambient_declaration_entity` | `ambient_declaration` | handles `declare module "x"` / `declare namespace X` | - -### Top-Level Determination - -```mermaid -flowchart TD - N[Entity AST node] --> Q1{Inside a function body?<br/>_is_inside_function_body} - Q1 -- yes --> NotTop[Not top-level] - Q1 -- no --> Walk[Walk up node.parent chain] - Walk --> P1{parent.type == 'program'} - P1 -- yes --> Top[Top-level = True] - Walk --> P2{parent.type == 'export_statement'} - P2 -- yes --> Top - Walk --> P3{parent.type == 'ambient_declaration'} - P3 -- yes --> Top - Walk --> P4{parent.type == 'module'} - P4 -- yes --> Top - Walk --> P5{parent.type == 'statement_block'<br/>whose grandparent is 'module'/'ambient_declaration'} - P5 -- yes --> Top - Walk --> More[continue upward] - More --> Walk - Walk -->|reached root without match| NotTop -``` - -This logic lets the analyzer correctly treat code inside `declare module "foo" { ... }` or `declare namespace Bar { ... }` blocks as top-level, while still rejecting helper functions/classes declared inside another function's body. - -### Relationship Extraction - -The second traversal (`_traverse_for_relationships`) maintains a "current top-level" name that changes whenever it re-enters one of the "new top-level" node types (`_is_new_top_level`): function/class/interface/type-alias/enum declarations, `export_statement`, or `method_definition`. While inside a known top-level scope, the following node types trigger relationship emission: - -```mermaid -flowchart LR - subgraph "Node types inspected during traversal" - CE[call_expression] --> ExtractCall["_extract_call_relationship"] - NE[new_expression] --> ExtractNew["_extract_new_relationship"] - TA[type_annotation] --> ExtractType["_extract_type_relationship"] - TArgs[type_arguments] --> ExtractTypeArgs["_extract_type_arguments_relationship"] - EC[extends_clause] --> ExtractInherit["_extract_inheritance_relationship"] - IC[implements_clause] --> ExtractInherit - end - ExtractCall --> AddRel["_add_relationship(caller, callee, line, resolved)"] - ExtractNew --> AddRel - ExtractType --> AddRel - ExtractTypeArgs --> AddRel - ExtractInherit --> AddRel - AddRel --> Dedup["seen_relationships de-dup"] - Dedup --> Out[self.call_relationships] -``` - -#### Call Resolution Strategy (`_extract_call_relationship`) - -Call resolution is *receiver-aware* β€” it classifies the callee expression before deciding how to resolve it: - -```mermaid -flowchart TD - Start["call_expression node"] --> Kind{func_node.type} - Kind -- identifier --> Plain["Plain call: name in top_level_nodes?"] - Plain -- yes --> ResPlain["resolved=True, callee=file-local component id"] - Plain -- "in all_entities but nested" --> Skip["Ignore nested/local call"] - Plain -- no --> UnresPlain["resolved=False, callee=bare name"] - - Kind -- member_expression --> Parts["_member_call_parts β†’ (receiver_kind, receiver_text, tail)"] - Parts --> RK{receiver_kind} - RK -- "this / super" --> Inst["_emit_instance_method_call<br/>(resolve against enclosing class + base_classes)"] - RK -- identifier --> Recv["_emit_receiver_method_call<br/>(known component, else _infer_identifier_type)"] - RK -- chain --> Chain["bare 'a.b.c' name, resolved=False"] - RK -- composite --> Comp{"tail in JS_TS_PROTOTYPE_METHODS?"} - Comp -- no --> CompEmit["bare tail name, resolved=False"] - Comp -- yes --> CompDrop["dropped β€” cannot be a project component"] - RK -- literal --> LitDrop["dropped"] -``` - -Key resolution helpers: - -- **`_member_call_parts`** classifies the object of a member expression into `this`, `super`, `identifier`, `chain` (pure dotted identifier chain), `composite` (call result / subscript / parenthesized / `new` expression), or `literal`. -- **`_emit_instance_method_call`** resolves `this.m()` against the enclosing class (by splitting `caller_name` at the first `.`) and `super.m()` against its `base_classes`; falls back to emitting the qualified-but-unresolved name (`Class.method`) so the global resolver in `CallGraphAnalyzer` can find it if it's defined in another file. -- **`_emit_receiver_method_call`** first checks if the receiver identifier is itself a top-level component (e.g., a static call `SomeClass.method()` or namespace/enum access); otherwise calls **`_infer_identifier_type`**, which walks up enclosing scopes (`method_definition`, `function_declaration`, `arrow_function`, `class_declaration`, `program`, etc.) and looks for a `new X()` initializer or a TypeScript type annotation (`_find_declared_type`) matching the identifier, to infer its class and then resolve `<InferredType>.<method>`. -- Anything that cannot be locally resolved is still emitted, but as a **bare logical name** β€” the module deliberately never invents a fake file-qualified id for a name it hasn't actually found in `top_level_nodes`. This matters because `CallGraphAnalyzer._resolve_callee` (see [Dependency_Analysis_Service](Dependency_Analysis_Service.md)) performs the authoritative, project-wide (and cross-language) resolution pass afterward, using exact/simple-name indexes; only names that stay unresolved after that stage are ultimately classified as external via `is_external_symbol` / `JS_TS_PROTOTYPE_METHODS`. - -#### Type & Inheritance Relationships - -- **`_extract_type_relationship`** / **`_extract_type_arguments_relationship`** walk `type_annotation` / `type_arguments` subtrees, collecting all `type_identifier` nodes, filtering out TS built-ins (`_is_builtin_type`: `string`, `number`, `boolean`, `object`, `undefined`, `null`, `void`, `never`, `any`, `unknown`), and emitting a relationship (resolved if the type is a known top-level node in the same file, else a bare unresolved name). -- **`_extract_inheritance_relationship`** handles both `extends_clause` and `implements_clause`, emitting relationships to each base identifier β€” resolved when defined in the same file, otherwise bare. -- **`_extract_constructor_dependencies`** (invoked once per class during Pass 2) inspects the class's `constructor` method's `formal_parameters`, extracting each parameter's TypeScript type annotation as a dependency edge from the class to that type β€” capturing common dependency-injection patterns. - -### Node Construction (`_create_node_from_entity`) - -Each qualifying entity dict is converted into a `Node` (schema defined in [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)): - -```mermaid -classDiagram - class EntityDict { - +name: str - +type: str - +subtype: str - +code_snippet: str - +display_name: str - +start_line: int - +end_line: int - +parameters: List~str~ - +base_classes: List~str~ - +class_name: str - } - class Node { - +id: str - +name: str - +component_type: str - +file_path: str - +relative_path: str - +source_code: str - +start_line: int - +end_line: int - +parameters: List~str~ - +node_type: str - +base_classes: List~str~ - +class_name: str - +display_name: str - +component_id: str - +language: str - +qualified_name: str - +depends_on: Set~str~ - } - EntityDict --> Node : _create_node_from_entity() -``` - -Component ids follow the convention **`<relative_path>::<name>`** (see `_get_component_id` / `_get_relative_path`), where `name` for methods is already qualified as `ClassName.methodName`. `language` is hard-coded to `"typescript"`. The `depends_on` field on `Node` is left empty here β€” dependency edges live exclusively in the separate `CallRelationship` list; it is `DependencyParser` (in [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)) that later folds resolved relationships back into each `Node.depends_on` set. - -### Filtering Rules (`_should_include_node`) - -- All `variable` component types are dropped from the final node list (they exist only to support relationship resolution, e.g., `const x = new Foo()`). -- Names whose last dot-segment is `constructor`, `__proto__`, or `prototype` are excluded β€” these are structural JS/TS artifacts, not meaningful documentable components. - ---- - -## Data Flow Summary - -```mermaid -flowchart LR - Src["TypeScript source file (.ts/.tsx)"] --> Parser["tree_sitter_typescript Parser"] - Parser --> AST["AST (root_node)"] - AST --> Pass1["Pass 1: _extract_all_entities β†’ all_entities dict"] - Pass1 --> Pass2["Pass 2: _filter_top_level_declarations"] - Pass2 --> Nodes["List[Node] (top_level_nodes)"] - AST --> Pass3["Pass 3: _extract_all_relationships"] - Nodes -.lookup for resolution.-> Pass3 - Pass3 --> Rels["List[CallRelationship]"] - Nodes --> Output["(nodes, call_relationships)"] - Rels --> Output - Output --> CGA["CallGraphAnalyzer.analyze_code_files"] - CGA --> GlobalResolve["Cross-file / cross-language resolution<br/>_resolve_call_relationships"] - GlobalResolve --> FinalGraph["Consolidated dependency graph<br/>(consumed by DependencyParser, DocumentationGenerator)"] -``` - -Downstream consumers: -- **`CallGraphAnalyzer`** ([Dependency_Analysis_Service](Dependency_Analysis_Service.md)) merges the analyzer's output with every other language analyzer's output, then performs global relationship resolution (exact/simple-name indexes, external-symbol filtering) and visualization-data generation. -- **`DependencyParser`** ([Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)) consumes the fully-resolved function/relationship dictionaries to build the final `Dict[str, Node]` component map (populating each `Node.depends_on`) and can serialize it to disk via `save_dependency_graph`. -- That component map ultimately feeds the [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) documentation generation pipeline, where each `Node`'s `source_code`, `display_name`, and dependency edges are used to prompt the LLM for per-module documentation (see [Backend_LLM_&_Documentation_Services_documentation_generator](Backend_LLM_&_Documentation_Services_documentation_generator.md)). - ---- - -## Comparison with `TreeSitterJSAnalyzer` - -Both analyzers in [JavaScript_TypeScript_Analyzers](JavaScript_TypeScript_Analyzers.md) share the same architectural shape (multi-pass AST traversal, `top_level_nodes` lookup table, receiver-aware call resolution, bare-name emission for unresolved callees), differing mainly in grammar coverage: - -| Aspect | `TreeSitterTSAnalyzer` (this module) | `TreeSitterJSAnalyzer` ([sibling](JavaScript_TypeScript_Analyzers_javascript.md)) | -|---|---|---| -| Grammar | `tree_sitter_typescript.language_typescript()` | `tree_sitter_javascript.language()` | -| Entity collection strategy | Single flat-map pass (`_extract_all_entities`) then top-level filter | Direct recursive traversal appending straight into `self.nodes` | -| TS-only constructs | interfaces, type aliases, enums, ambient/namespace declarations, type annotations/arguments, `implements_clause` | not applicable | -| Type-dependency source | native TS type annotations (`type_annotation`, `type_arguments`) | JSDoc comment parsing (`@param {Type}`, `@returns {Type}`, etc.) | -| Constructor DI extraction | yes, via typed constructor parameters | not present | -| Local type inference for `recv.method()` | `_infer_identifier_type` uses `new X()` **and** TS type annotations | `_receiver_class` uses only `new X()` initializers | - ---- - -## Error Handling & Robustness - -- Parser initialization failures are caught and logged; `analyze()` becomes a no-op rather than raising, so a single bad file cannot abort the whole-repository analysis run performed by `CallGraphAnalyzer.analyze_code_files` (which itself wraps each file analysis in a try/except and a 30-second timeout β€” see [Dependency_Analysis_Service](Dependency_Analysis_Service.md)). -- Every extraction/relationship helper method is wrapped in its own `try/except`, logging at `debug` level and returning `None`/skipping β€” a malformed or unusual AST shape in one construct never prevents extraction of the rest of the file. -- The top-level `analyze_typescript_file_treesitter` function itself catches all exceptions and returns `([], [])` on failure, guaranteeing a well-typed (if empty) result to its caller. diff --git a/docs/Language_Analyzers.md b/docs/Language_Analyzers.md deleted file mode 100644 index 9984f432..00000000 --- a/docs/Language_Analyzers.md +++ /dev/null @@ -1,137 +0,0 @@ -# Language Analyzers - -## Purpose - -The **Language_Analyzers** module is the collection of language-specific static analysis "front ends" that power CodeWiki's [Dependency_Analysis_Service](Dependency_Analysis_Service.md). For each supported programming language, an analyzer parses a single source file β€” using either [tree-sitter](https://tree-sitter.github.io/) grammars or, for Python, the native `ast` module β€” and extracts: - -1. **`Node` records** β€” one per top-level declaration (class, struct, interface, function, method, trait, enum, global variable, type alias, …), representing a documentable "component". -2. **`CallRelationship` records** β€” directed edges describing how those components reference each other (calls, inheritance, interface implementation, instantiation, field/property types, imports, …). - -None of these analyzers attempt full semantic/compiler-grade resolution. Instead, each performs the best-effort, file-local resolution possible from syntax alone, marking relationships `is_resolved=True` when the target is confidently known within the same file, and `is_resolved=False` (a best-effort qualified/dotted name) otherwise. The heavy lifting of matching unresolved edges to real components anywhere in the repository β€” and filtering out edges to genuinely external/third-party/stdlib symbols β€” is centralized in `CallGraphAnalyzer`, part of [Dependency_Analysis_Service](Dependency_Analysis_Service.md). The resulting resolved call graph is then transformed into the project-wide dependency graph by [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md), which ultimately feeds [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) for documentation generation. - -Currently supported languages/analyzers: - -| Language(s) | Analyzer(s) | Parsing technology | -|---|---|---| -| C, C++, C#, Java, Kotlin | `TreeSitterCAnalyzer`, `TreeSitterCppAnalyzer`, `TreeSitterCSharpAnalyzer`, `TreeSitterJavaAnalyzer`, `TreeSitterKotlinAnalyzer` | tree-sitter | -| JavaScript, TypeScript | `TreeSitterJSAnalyzer`, `TreeSitterTSAnalyzer` | tree-sitter | -| PHP | `TreeSitterPHPAnalyzer` (+ `NamespaceResolver`) | tree-sitter | -| Python | `PythonASTAnalyzer` | native `ast` | - -## Architecture - -### Position in the system - -```mermaid -graph TD - RA["RepoAnalyzer<br/>(file discovery)"] --> AS["AnalysisService"] - AS --> CGA["CallGraphAnalyzer"] - CGA -->|routes by file extension| CFAM["C-Family Tree-sitter Analyzers<br/>(C, C++, C#, Java, Kotlin)"] - CGA -->|routes by file extension| JSTS["JavaScript & TypeScript Analyzers"] - CGA -->|routes by file extension| PHP["PHP Analyzer"] - CGA -->|routes by file extension| PY["Python Analyzer"] - CFAM -->|Node + CallRelationship lists| CGA - JSTS -->|Node + CallRelationship lists| CGA - PHP -->|Node + CallRelationship lists| CGA - PY -->|Node + CallRelationship lists + external roots| CGA - CGA -->|cross-file resolution + external filtering| DP["DependencyParser"] - DP --> DGB["DependencyGraphBuilder"] - DGB --> Docs["DocumentationGenerator"] - - click AS "Dependency_Analysis_Service.md" - click CGA "Dependency_Analysis_Service.md" - click DP "Dependency_Analyzer_Core.md" - click DGB "Dependency_Analyzer_Core.md" - click Docs "Backend_LLM_&_Documentation_Services.md" -``` - -### Shared data contract - -Every analyzer in this module builds instances of the same two Pydantic models, owned by [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md): - -```mermaid -classDiagram - class Node { - +str id - +str name - +str component_type - +str file_path - +str relative_path - +str source_code - +int start_line - +int end_line - +str docstring - +str class_name - +str display_name - +str component_id - +str qualified_name - +Set~str~ depends_on - } - class CallRelationship { - +str caller - +str callee - +int call_line - +bool is_resolved - } - Node "1" --> "*" CallRelationship : caller/callee reference Node.id -``` - -* **`Node.id` / `component_id`**: `"{relative_path_from_repo_root}::{qualified_name}"`, e.g. `src/Foo.cpp::Logger.write` β€” the canonical identifier used across CodeWiki. -* **`CallRelationship.is_resolved`**: `True` when the callee is a confirmed same-file `Node.id`; `False` when only a name (simple, qualified, or dotted) is known, deferring final resolution to `CallGraphAnalyzer`'s repository-wide indexes and external-symbol classifier. - -### Common analyzer pipeline - -Despite covering very different languages/grammars, all analyzers follow the same three-phase pattern: - -```mermaid -sequenceDiagram - participant CGA as CallGraphAnalyzer - participant AN as Language Analyzer - participant Parser as Grammar (tree-sitter / ast) - participant Model as Node / CallRelationship - - CGA->>AN: analyze_<lang>_file(file_path, content, repo_path) - AN->>Parser: parse(content) - Parser-->>AN: syntax tree - AN->>AN: extract declarations (Node candidates) - AN->>Model: construct Node per declaration - AN->>AN: extract references (calls, inheritance, imports, types) - AN->>Model: construct CallRelationship per reference - AN-->>CGA: (nodes, call_relationships) -``` - -### Output flow - -```mermaid -flowchart LR - subgraph "Language_Analyzers" - CF["C-Family Analyzers"] - JT["JS/TS Analyzers"] - PH["PHP Analyzer"] - PY["Python Analyzer"] - end - CF & JT & PH & PY --> Funcs["Nodes"] - CF & JT & PH & PY --> Rels["CallRelationships"] - Funcs --> Resolve["CallGraphAnalyzer._resolve_call_relationships"] - Rels --> Resolve - Resolve --> Filter["_is_external_callee<br/>(drops stdlib/third-party edges)"] - Filter --> Graph["Complete call graph"] - Graph --> DP["DependencyParser"] - DP --> DGB["DependencyGraphBuilder"] - DGB --> Gen["DocumentationGenerator"] -``` - -## Sub-modules & Core Components - -| Sub-module | Languages | Key Components | Documentation | -|---|---|---|---| -| **C-Family Tree-sitter Analyzers** | C, C++, C#, Java, Kotlin | `TreeSitterCAnalyzer`, `TreeSitterCppAnalyzer`, `TreeSitterCSharpAnalyzer`, `TreeSitterJavaAnalyzer`, `TreeSitterKotlinAnalyzer` | [C-Family_Tree-sitter_Analyzers.md](C-Family_Tree-sitter_Analyzers.md) | -| **JavaScript & TypeScript Analyzers** | JavaScript, TypeScript | `TreeSitterJSAnalyzer`, `TreeSitterTSAnalyzer` | [JavaScript_TypeScript_Analyzers.md](JavaScript_TypeScript_Analyzers.md) | -| **PHP Analyzer** | PHP | `TreeSitterPHPAnalyzer`, `NamespaceResolver` | [PHP_Analyzer.md](PHP_Analyzer.md) | -| **Python Analyzer** | Python | `PythonASTAnalyzer` | [Python_Analyzer.md](Python_Analyzer.md) | - -## Related Modules - -* [Dependency_Analysis_Service](Dependency_Analysis_Service.md) β€” owns `CallGraphAnalyzer`, which discovers files, dispatches them to the appropriate analyzer in this module, and performs cross-file symbol resolution and external-symbol filtering. -* [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) β€” defines the shared `Node`/`CallRelationship` models and the `DependencyParser`/`DependencyGraphBuilder` that turn resolved call graphs into the final dependency graph. -* [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) β€” consumes the dependency graph to generate human-readable documentation. \ No newline at end of file diff --git a/docs/MCP_Session_Management.md b/docs/MCP_Session_Management.md deleted file mode 100644 index 4af5291c..00000000 --- a/docs/MCP_Session_Management.md +++ /dev/null @@ -1,307 +0,0 @@ -# MCP Session Management - -## 1. Purpose - -The **MCP Session Management** module is the stateful backbone of the CodeWiki -**Model Context Protocol (MCP) Server**. When an IDE agent (e.g. an AI coding -assistant) calls the `analyze_repo` MCP tool, this module: - -1. Creates a new **session** that caches the results of repository analysis - (parsed components, leaf nodes, module tree, etc.) in memory, keyed by a - unique `session_id`. -2. Provisions an **on-disk workspace** where bulky analysis artifacts (source - code snippets, JSON indexes) are written, so that large payloads never - need to be streamed through the narrow MCP stdio channel. -3. Tracks session lifecycle β€” expiration, eviction, and cleanup β€” so that - long-running MCP servers don't leak memory or disk space across many - client interactions. - -Every subsequent MCP tool call (read code, write documentation, edit files, -inspect/modify the module tree, close the session) looks up the session by -its `session_id` to operate on the cached analysis state without -re-parsing the repository from scratch. - -This module sits between: -- **Dependency_Analysis_Service** / **Dependency_Analyzer_Core** β€” which - produce the `Node` objects, leaf-node lists, and dependency graphs that a - session caches (see [Dependency_Analysis_Service.md](Dependency_Analysis_Service.md) - and [Dependency_Analyzer_Core.md](Dependency_Analyzer_Core.md)). -- **Backend_Agent_Tools** β€” whose editing tools (e.g. `EditTool`, - `Filemap`) operate on files inside the session's repo/workspace path (see - [Backend_Agent_Tools.md](Backend_Agent_Tools.md)). -- **Backend_LLM_&_Documentation_Services** β€” which use session-cached - components/leaf nodes as input to drive documentation generation (see - [Backend_LLM_&_Documentation_Services.md](Backend_LLM_&_Documentation_Services.md)). - -## 2. Architecture Overview - -The module consists of two tightly-coupled files: - -| File | Responsibility | -|---|---| -| `codewiki/mcp/session.py` | In-memory session registry: creation, lookup, TTL-based expiry, LRU-style eviction, and thread-safety. | -| `codewiki/mcp/workspace.py` | Per-session on-disk directory management: writing/reading JSON artifacts and component source files, and cleanup. | - -```mermaid -classDiagram - class SessionStore { - -Dict~str, SessionState~ _sessions - -Lock _lock - +create(repo_path, output_dir, components, leaf_nodes, workspace) SessionState - +get(session_id) Optional~SessionState~ - +remove(session_id) bool - -_purge_expired_locked() - } - - class SessionState { - +str session_id - +str repo_path - +str output_dir - +Dict~str, Node~ components - +List~str~ leaf_nodes - +Dict module_tree - +Dict registry - +Optional~SessionWorkspace~ workspace - +Optional~str~ analyzed_commit - +int docs_written - +float created_at - +float last_accessed - +touch() - +is_expired : bool - } - - class SessionWorkspace { - +Path root - +write_json(name, data) Path - +write_component_source(component_id, source, language) Path - +read_json(name) Any - +cleanup() - } - - class Node { - <<pydantic model>> - +str id - +str name - +Set~str~ depends_on - +Optional~str~ source_code - } - - SessionStore "1" o-- "many" SessionState : manages - SessionState "1" o-- "0..1" SessionWorkspace : owns - SessionState "1" o-- "many" Node : caches (components) -``` - -### 2.1 Session Lifecycle Flow - -```mermaid -sequenceDiagram - participant Agent as IDE Agent (MCP Client) - participant Server as MCP Server (tool handlers) - participant Store as SessionStore - participant WS as SessionWorkspace - participant FS as Repo Filesystem - - Agent->>Server: analyze_repo(repo_path, output_dir) - Server->>Server: run dependency analysis -> components, leaf_nodes - Server->>WS: new SessionWorkspace(repo_path, session_id) - WS->>FS: mkdir .codewiki/sessions/{session_id}/(sources/) - Server->>Store: create(repo_path, output_dir, components, leaf_nodes, workspace) - Store-->>Server: SessionState(session_id=...) - Server-->>Agent: session_id - - Agent->>Server: read_code / write_doc_file / edit_doc_file (session_id, ...) - Server->>Store: get(session_id) - Store-->>Server: SessionState (touch() updates last_accessed) - Server->>WS: write_json/read_json/write_component_source - Server-->>Agent: result - - Agent->>Server: close_session(session_id) - Server->>Store: remove(session_id) - Server->>WS: cleanup() - WS->>FS: rmtree session dir, prune empty parents -``` - -### 2.2 Data Flow: Avoiding Large stdio Payloads - -```mermaid -flowchart LR - A["Dependency Analysis (Node objects, leaf nodes)"] --> B["SessionState (in-memory cache)"] - B --> C[SessionWorkspace] - C --> D[component_index.json] - C --> E[leaf_nodes.json] - C --> F[sources/*.src] - C --> G[processing_order.json / summary.json / changes.json] - D & E & F & G --> H[IDE Agent reads files\ndirectly from disk] - H -.stdio only carries session_id + small control messages.-> I[MCP Server] -``` - -## 3. Core Concepts - -### 3.1 `SessionState` (session.py) - -`SessionState` is a plain dataclass holding everything a session needs -across tool calls: - -- **Identity & paths**: `session_id`, `repo_path`, `output_dir`. -- **Analysis cache**: `components` (a `Dict[str, Node]` β€” see - [Dependency_Analyzer_Core.md](Dependency_Analyzer_Core.md) for the `Node` - model), `leaf_nodes`, `module_tree`, and a generic `registry` dict for - ad-hoc session-scoped data. -- **Workspace handle**: an optional `SessionWorkspace` for on-disk artifact - storage (`None` if the session doesn't need one). -- **Incremental-update baseline**: `analyzed_commit` records the git `HEAD` - commit *at analyze_repo time*. This is deliberately **not** updated to the - HEAD at close time, because commits made mid-session (e.g. by the agent - editing files) must still be considered part of the diff the next - `analyze_repo` call needs to pick up β€” baselining to close-time HEAD would - silently skip documenting those changes. -- **Bookkeeping**: `docs_written` (skips a metadata baseline update if no - docs were written this session), `created_at`, `last_accessed`. -- **`touch()`**: refreshes `last_accessed`, called on every successful - `get()`. -- **`is_expired`**: `True` once `last_accessed` is older than the TTL - (`_SESSION_TTL_SECONDS = 2 hours`). - -### 3.2 `SessionStore` (session.py) - -A thread-safe (`threading.Lock`-guarded), in-memory registry of all active -`SessionState` objects, keyed by `session_id`. - -Key behaviors: - -- **`create(...)`**: - 1. Purges expired sessions first (`_purge_expired_locked`). - 2. If at capacity (`_MAX_SESSIONS = 10`), evicts the least-recently-used - session (oldest `last_accessed`), cleaning up its workspace on disk. - 3. Generates a collision-free 12-character hex `session_id` - (`uuid.uuid4().hex[:12]`). - 4. Stores and returns the new `SessionState`. -- **`get(session_id)`**: Returns the session if present and not expired - (calling `touch()` to extend its life); otherwise cleans up and returns - `None`. This lazy-expiry check means expired sessions are also removed - opportunistically on lookup, not just during `create`. -- **`remove(session_id)`**: Explicit removal (used by an MCP `close_session` - tool), returns whether the session existed. Note: unlike `get()`/`create()`, - `remove()` does **not** call `workspace.cleanup()` itself β€” the caller - (typically the `close_session` tool handler) is responsible for invoking - cleanup after removing the session, or accessing the returned state before - removal to do so. -- **`_purge_expired_locked()`**: Internal helper (must be called while - holding `_lock`) that sweeps all expired sessions and cleans up their - workspaces. - -This design bounds both **memory** (max 10 concurrent sessions, TTL-based -expiry) and **disk usage** (workspace cleanup on eviction/expiry) for a -long-lived MCP server process. - -### 3.3 `SessionWorkspace` (workspace.py) - -Manages a per-session directory tree used to persist analysis artifacts -that are too large or unwieldy to pass through the MCP stdio transport. - -Directory layout (relative to `repo_path`): - -``` -.codewiki/sessions/{session_id}/ - component_index.json - leaf_nodes.json - languages.json - changes.json - summary.json - processing_order.json - sources/ - {sanitized_component_id}.src -``` - -Key methods: - -- **`write_json(name, data)`**: Pretty-prints arbitrary JSON-serializable - data to `root/{name}`. -- **`write_component_source(component_id, source, language)`**: Writes a - single component's source code (e.g. a `Node.source_code` value) into - `sources/`, prefixed with a small header comment identifying the - component and language. Filenames are sanitized via `_safe_filename`, - which: - - Replaces any character outside `[\w\-.]` with `__`. - - Truncates to 180 chars (to stay under common 255-byte `NAME_MAX` - limits, since sanitization can expand path separators). - - Appends an 8-character SHA-1 hash suffix of the *original* component ID - to guarantee uniqueness even when different IDs sanitize to the same - string. -- **`read_json(name)`**: Reads back a JSON artifact, returning `None` if the - file doesn't exist (used by tool handlers to check for previously - computed results, e.g. `changes.json` from an incremental update). -- **`cleanup()`**: Recursively removes the session's directory - (`shutil.rmtree`, ignoring errors), then walks up to prune the now-empty - `.codewiki/sessions/` and `.codewiki/` directories if applicable β€” keeping - the target repository tidy after a session ends. - -```mermaid -flowchart TD - subgraph SessionWorkspace root - A[component_index.json] - B[leaf_nodes.json] - C[languages.json] - D[changes.json] - E[summary.json] - F[processing_order.json] - G[sources/] - G --> G1["{sanitized_id_1}.src"] - G --> G2["{sanitized_id_2}.src"] - end -``` - -## 4. Relationship to Other Modules - -```mermaid -flowchart TB - subgraph MCP_Session_Management - SS[SessionStore / SessionState] - SW[SessionWorkspace] - end - - DAC["Dependency_Analyzer_Core (Node, AnalysisResult)"] -->|produces components, leaf_nodes| SS - DAS["Dependency_Analysis_Service (AnalysisService, RepoAnalyzer)"] -->|drives analyze_repo| SS - SS --> SW - BAT["Backend_Agent_Tools (EditTool, Filemap)"] -->|reads/edits files under repo_path| SW - BLDS["Backend_LLM_and_Documentation_Services (DocumentationGenerator)"] -->|consumes cached components/leaf_nodes| SS -``` - -- **Producers of session data**: The [Dependency_Analysis_Service](Dependency_Analysis_Service.md) - (via `AnalysisService`/`RepoAnalyzer`) and [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) - (via `Node`, `AnalysisResult`) supply the `components` and `leaf_nodes` - that populate a new `SessionState` when `analyze_repo` runs. -- **Consumers of session data**: [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) - (e.g. `DocumentationGenerator`) and MCP tool handlers read the cached - `SessionState.components`/`module_tree` to drive documentation - generation without re-analyzing the repo. -- **File operations**: [Backend_Agent_Tools](Backend_Agent_Tools.md) (e.g. - `EditTool`, `Filemap`) operate on files within `repo_path` and may read - artifacts written into the `SessionWorkspace` directory. -- **CLI vs. MCP**: The [CLI](CLI_Documentation_Generation.md) module - provides a batch/one-shot alternative entry point - (`CLIDocumentationGenerator`) that does not use session management at - all β€” it runs analysis and generation end-to-end in a single process - invocation. MCP Session Management exists specifically to support - **interactive, multi-step** IDE-agent workflows where state must persist - across many small tool calls. - -## 5. Design Notes & Invariants - -- **Thread safety**: All mutations to the session dictionary happen under - `SessionStore._lock`, making `SessionStore` safe for concurrent MCP tool - invocations (the MCP server may handle multiple in-flight requests). -- **Bounded resource usage**: The combination of TTL expiry - (`_SESSION_TTL_SECONDS`) and max-session eviction (`_MAX_SESSIONS`) - ensures the server doesn't accumulate unbounded memory or leftover - `.codewiki/sessions/*` directories across long-running deployments. -- **`analyzed_commit` baseline correctness**: This is a subtle but important - invariant β€” the baseline commit for the *next* incremental analysis must - be the commit at the time analysis was performed, not at session close. - Any code that finalizes a session (e.g. a `close_session` tool handler) - must persist `analyzed_commit`, not `HEAD` at close time. -- **Workspace cleanup ownership**: `SessionStore.get()` and `create()` - (via internal eviction/expiry paths) clean up workspaces automatically. - However, `SessionStore.remove()` does not β€” callers must handle - `workspace.cleanup()` explicitly when doing an intentional - `close_session`. diff --git a/docs/PHP_Analyzer.md b/docs/PHP_Analyzer.md deleted file mode 100644 index 2e80a714..00000000 --- a/docs/PHP_Analyzer.md +++ /dev/null @@ -1,243 +0,0 @@ -# PHP Analyzer - -## Introduction - -The **PHP Analyzer** module is a language-specific static analysis component within the [Language_Analyzers](Language_Analyzers.md) family. It is responsible for parsing PHP source files, extracting structural code entities (classes, interfaces, traits, enums, functions, and methods), and identifying dependency relationships between them (inheritance, interface implementation, object instantiation, static calls, and constructor property promotion). - -The module is invoked by the [Dependency_Analysis_Service](Dependency_Analysis_Service.md)'s `CallGraphAnalyzer` whenever a `.php` (or `.phtml`/`.inc`) file is encountered during repository analysis, and its output feeds directly into the [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) data models (`Node`, `CallRelationship`) that power the rest of the CodeWiki documentation-generation pipeline. - -It consists of two core components defined in `codewiki/src/be/dependency_analyzer/analyzers/php.py`: - -| Component | Responsibility | -|---|---| -| `NamespaceResolver` | Tracks PHP `namespace` declarations and `use` statements to resolve short/aliased class names to fully-qualified names (FQNs). | -| `TreeSitterPHPAnalyzer` | Drives a `tree-sitter-php` parse of a single file, walking the AST to build `Node` and `CallRelationship` objects. | - -A module-level convenience function, `analyze_php_file(file_path, content, repo_path)`, wraps the analyzer class and is the single entry point used by the rest of the system. - ---- - -## Architecture Overview - -The PHP Analyzer follows the same "parse β†’ extract nodes β†’ extract relationships" pattern used by its sibling language analyzers (see [C-Family_Tree-sitter_Analyzers](C-Family_Tree-sitter_Analyzers.md), [JavaScript_TypeScript_Analyzers](JavaScript_TypeScript_Analyzers.md), and [Python_Analyzer](Python_Analyzer.md)), but is tailored to PHP-specific syntax such as namespaces, traits, enums, and constructor property promotion. - -```mermaid -graph TD - subgraph "PHP_Analyzer module" - A[analyze_php_file] --> B[TreeSitterPHPAnalyzer] - B --> C[NamespaceResolver] - B --> D["tree-sitter-php Parser"] - B --> E["Node list"] - B --> F["CallRelationship list"] - end - - G["Dependency_Analysis_Service.CallGraphAnalyzer"] -->|"_analyze_php_file()"| A - E --> H["Node model (Dependency_Analyzer_Core)"] - F --> I["CallRelationship model (Dependency_Analyzer_Core)"] - - style A fill:#dff,stroke:#333 - style B fill:#dff,stroke:#333 - style C fill:#dff,stroke:#333 -``` - -### Component Relationships - -```mermaid -classDiagram - class NamespaceResolver { - -str current_namespace - -Dict~str,str~ use_map - +register_namespace(ns) - +register_use(fqn, alias) - +resolve(name) str - } - - class TreeSitterPHPAnalyzer { - -Path file_path - -str content - -str repo_path - -List~Node~ nodes - -List~CallRelationship~ call_relationships - -NamespaceResolver namespace_resolver - -Dict~str,Node~ _top_level_nodes - +__init__(file_path, content, repo_path) - -_analyze() - -_extract_namespace_info(node, depth) - -_extract_use_statement(node) - -_extract_nodes(node, lines, depth, parent_class) - -_extract_relationships(node, depth) - -_add_use_relationships(node) - -_is_template_file() bool - -_is_primitive(type_name) bool - } - - class Node { - <<Pydantic model - Dependency_Analyzer_Core>> - } - - class CallRelationship { - <<Pydantic model - Dependency_Analyzer_Core>> - } - - TreeSitterPHPAnalyzer --> NamespaceResolver : uses - TreeSitterPHPAnalyzer --> Node : produces - TreeSitterPHPAnalyzer --> CallRelationship : produces -``` - ---- - -## Core Components - -### `NamespaceResolver` - -PHP allows classes to be referenced by short names, aliases, or fully-qualified names depending on the current `namespace` and any `use` import statements in scope. `NamespaceResolver` centralizes this logic so the analyzer can always emit a consistent, fully-qualified dependency target. - -**Responsibilities:** -- `register_namespace(ns)` β€” records the file's current namespace (from a `namespace_definition` AST node). -- `register_use(fqn, alias=None)` β€” records an imported class, keyed by its alias (or its own short name if no alias is given). Supports both simple (`use App\User;`) and grouped (`use App\{User, Post};`) use-statement forms. -- `resolve(name)` β€” given any class-name reference encountered in the code, returns its fully-qualified form by: - 1. Returning as-is if already fully qualified (leading `\`). - 2. Looking up the exact name in the alias map. - 3. Looking up the first namespace segment in the alias map (for partially-qualified names). - 4. Falling back to prefixing with the current namespace. - 5. Returning the name unchanged if no namespace context exists. - -```mermaid -flowchart LR - Start([name to resolve]) --> Q1{Starts with backslash?} - Q1 -- yes --> R1[Strip leading backslash, return] - Q1 -- no --> Q2{Full name in use_map?} - Q2 -- yes --> R2[Return mapped FQN] - Q2 -- no --> Q3{First segment in use_map?} - Q3 -- yes --> R3["Return mapped_base + remaining segments"] - Q3 -- no --> Q4{current_namespace set?} - Q4 -- yes --> R4["Return current_namespace + '\\' + name"] - Q4 -- no --> R5[Return name unchanged] -``` - -### `TreeSitterPHPAnalyzer` - -The main analyzer class. It wraps `tree_sitter_php.language_php()` (the mixed PHP/HTML grammar, chosen because it is the most common real-world case) and performs a three-pass analysis of the file's AST. - -**Constructor behavior (`__init__`)** -- Stores `file_path`, `content`, and `repo_path`. -- Initializes empty `nodes`, `call_relationships`, a fresh `NamespaceResolver`, and a `_top_level_nodes` lookup dict. -- Checks `_is_template_file()` β€” if the file matches known template patterns/directories (`.blade.php`, `.phtml`, `.twig.php`, or paths containing `views`/`templates`/`resources/views`), analysis is skipped entirely (templates are typically embedded HTML+PHP with little structural code value). -- Otherwise calls `_analyze()`. - -**`_analyze()` β€” three-pass pipeline** - -```mermaid -sequenceDiagram - participant Caller as analyze_php_file() - participant TA as TreeSitterPHPAnalyzer - participant TS as tree-sitter-php Parser - participant NR as NamespaceResolver - - Caller->>TA: __init__(file_path, content, repo_path) - TA->>TA: _is_template_file()? - alt is template - TA-->>Caller: nodes=[], relationships=[] - else not template - TA->>TS: parser.parse(content) - TS-->>TA: AST root - TA->>TA: Pass 1: _extract_namespace_info(root) - TA->>NR: register_namespace() / register_use() - TA->>TA: Pass 2: _extract_nodes(root, lines) - Note over TA: builds Node objects for classes,<br/>interfaces, traits, enums, functions, methods - TA->>TA: Pass 3: _extract_relationships(root) - TA->>NR: resolve(name) for each type reference - Note over TA: builds CallRelationship objects for<br/>extends, implements, new, static calls,<br/>constructor promotion, use imports - TA-->>Caller: nodes, call_relationships - end -``` - -1. **Namespace/Use extraction (`_extract_namespace_info`)** β€” recursively walks the tree looking for `namespace_definition` and `namespace_use_declaration` nodes, populating the `NamespaceResolver` before any name resolution is needed. - -2. **Node extraction (`_extract_nodes`)** β€” recursively walks the tree recognizing these AST node types and mapping them to a `component_type`: - - | AST node type | component_type | Notes | - |---|---|---| - | `class_declaration` | `class` or `abstract class` | Detects `abstract` modifier | - | `interface_declaration` | `interface` | | - | `trait_declaration` | `trait` | | - | `enum_declaration` | `enum` | | - | `function_definition` | `function` | Top-level function | - | `method_declaration` | `method` | Name qualified as `ClassName.methodName` | - - For each recognized node it builds a `Node` (from [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)) populated with: `id`/`component_id` (computed via `_get_component_id`, format `relative/path.php::Name` or `relative/path.php::Class.method`), `source_code` slice, `start_line`/`end_line`, PHPDoc `docstring` (via `_get_preceding_docstring`), `parameters` (via `_extract_parameters`), and `base_classes` (via `_extract_base_classes`). The current enclosing class name is threaded through recursion via the `parent_class` argument so that methods are correctly attributed and named. - -3. **Relationship extraction (`_extract_relationships`)** β€” a second recursive walk that emits `CallRelationship` objects for the following dependency kinds: - - | Trigger AST node | Relationship meaning | Notes | - |---|---|---| - | `namespace_use_declaration` | file β†’ imported class | via `_add_use_relationships`, caller is the file's relative path | - | `class_declaration` with `base_clause` | class β†’ parent class (`extends`) | | - | `class_declaration` / `enum_declaration` with `class_interface_clause` | class/enum β†’ interface (`implements`) | | - | `object_creation_expression` | containing class β†’ instantiated type (`new`) | | - | `scoped_call_expression` | containing class β†’ target class (`::` static call) | | - | `property_promotion_parameter` | containing class β†’ promoted property's type (PHP 8+ constructor promotion) | | - - Every extracted type name is passed through `NamespaceResolver.resolve()` and filtered via `_is_primitive()` (which excludes PHP scalar types and common built-ins such as `Exception`, `Closure`, `DateTime`, etc., listed in `PHP_PRIMITIVES`). Resolved names have their namespace separator (`\`) converted to `.` to match the dotted component-ID convention used elsewhere in the system. All relationships are emitted with `is_resolved=False`; final resolution to actual component IDs happens later in `CallGraphAnalyzer._resolve_call_relationships` (see [Dependency_Analysis_Service](Dependency_Analysis_Service.md)). - -**Supporting helpers** -- `_get_module_path` / `_get_relative_path` / `_get_component_id` β€” compute file-relative paths and component identifiers, stripping `.php`/`.phtml`/`.inc` extensions. -- `_find_child_by_type`, `_get_name_from_node`, `_get_type_from_clause`, `_extract_type_name`, `_find_containing_class_name` β€” low-level tree-sitter node traversal utilities. -- `_get_preceding_docstring` β€” scans backward from a node for a `/** ... */` PHPDoc block, either via `prev_named_sibling` or raw line scanning. -- `_extract_parameters` β€” pulls parameter names (and types, if annotated) from `formal_parameters`, supporting simple, promoted, and variadic parameters. -- `_extract_base_classes` β€” collects both `extends` and `implements` targets into a single list for the `Node.base_classes` field. -- `MAX_RECURSION_DEPTH` (100) guards all recursive walks against pathological/deeply nested ASTs, raising a caught `RecursionError` if exceeded. - -### `analyze_php_file(file_path, content, repo_path=None)` - -The public functional entry point. Instantiates `TreeSitterPHPAnalyzer` and returns `(analyzer.nodes, analyzer.call_relationships)`. This is the exact signature expected by `CallGraphAnalyzer._analyze_php_file` in the [Dependency_Analysis_Service](Dependency_Analysis_Service.md). - ---- - -## Integration with the Wider System - -```mermaid -graph LR - subgraph "Repository Analysis Pipeline" - RA["RepoAnalyzer<br/>(file discovery)"] --> CGA["CallGraphAnalyzer<br/>(Dependency_Analysis_Service)"] - CGA -->|".php files"| PHP["PHP_Analyzer<br/>analyze_php_file()"] - CGA -->|".py files"| PY["Python_Analyzer"] - CGA -->|".ts/.js files"| TS["JavaScript_TypeScript_Analyzers"] - CGA -->|".c/.cpp/.java/.cs/.kt files"| CF["C-Family_Tree-sitter_Analyzers"] - PHP --> NODES["Node & CallRelationship objects"] - PY --> NODES - TS --> NODES - CF --> NODES - NODES --> RESOLVE["_resolve_call_relationships()<br/>cross-language callee resolution"] - RESOLVE --> DPB["DependencyGraphBuilder<br/>(Dependency_Analyzer_Core)"] - DPB --> DOC["DocumentationGenerator<br/>(Backend_LLM_&_Documentation_Services)"] - end -``` - -1. **Discovery**: `RepoAnalyzer` (in [Dependency_Analysis_Service](Dependency_Analysis_Service.md)) walks the repository and classifies `.php`/`.phtml`/`.inc` files by extension via `CODE_EXTENSIONS`. -2. **Dispatch**: `CallGraphAnalyzer.analyze_code_files` calls `_analyze_code_file`, which routes PHP files to `_analyze_php_file`, which in turn calls `analyze_php_file` from this module. -3. **Aggregation**: The returned `Node` objects are merged into `CallGraphAnalyzer.functions` (keyed by component ID) and `CallRelationship` objects appended to `CallGraphAnalyzer.call_relationships`. -4. **Cross-file/cross-language resolution**: `CallGraphAnalyzer._resolve_call_relationships` attempts to resolve each unresolved `CallRelationship.callee` (still expressed as a dotted/short type name from this analyzer) against the global and per-language indexes of all discovered components, marking matches `is_resolved=True` and rewriting `callee` to the actual component ID. Unresolved relationships pointing to external/library symbols are filtered out. -5. **Graph construction**: `DependencyParser` (in [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)) consumes the final function/relationship lists to build the `Node.depends_on` sets used throughout the rest of the documentation pipeline (module grouping, dependency graphs, LLM context assembly). -6. **Documentation generation**: Ultimately this structural/dependency data is consumed by [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) to generate human-readable module documentation β€” the same kind of document you are reading now. - ---- - -## Data Model Reference - -The PHP Analyzer produces instances of two Pydantic models owned by [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md): - -- **`Node`** β€” represents a single extracted PHP entity (class, interface, trait, enum, function, or method) with fields such as `id`, `name`, `component_type`, `file_path`, `relative_path`, `source_code`, `start_line`/`end_line`, `docstring`, `parameters`, `base_classes`, `class_name`, and `display_name`. -- **`CallRelationship`** β€” represents a directed dependency edge (`caller` β†’ `callee`) with an optional `call_line` and an `is_resolved` flag indicating whether `callee` has been matched to a concrete component ID. - -Refer to [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) for the full model definitions and how they are consumed downstream (dependency graph building, analysis result serialization). - ---- - -## Key Design Notes - -- **Template file skipping**: Files matching Blade/Twig/`.phtml` patterns or living in `views`/`templates`/`resources/views` directories are skipped entirely (`_is_template_file`), since these typically mix large amounts of HTML with minimal reusable PHP logic and would otherwise pollute the dependency graph. -- **Mixed PHP/HTML grammar**: The analyzer deliberately uses `tree_sitter_php.language_php()` rather than the pure-PHP grammar, since most real-world PHP files (including non-template ones) may contain embedded HTML. -- **Primitive/built-in filtering**: `PHP_PRIMITIVES` prevents noise from scalar types (`string`, `int`, etc.) and ubiquitous SPL/core classes (`Exception`, `Closure`, `DateTime`, etc.) from appearing as false dependency edges. -- **Namespace-aware resolution**: Unlike simpler language analyzers, PHP's namespace/use-import system requires the dedicated `NamespaceResolver` to correctly disambiguate short class names β€” this is unique among the analyzers in [Language_Analyzers](Language_Analyzers.md). -- **Deferred resolution**: Consistent with all other analyzers, this module does not resolve relationships to final component IDs itself β€” it only produces best-effort namespace-qualified names; the heavy lifting of matching across the whole repository is delegated to `CallGraphAnalyzer` in [Dependency_Analysis_Service](Dependency_Analysis_Service.md). diff --git a/docs/Python_Analyzer.md b/docs/Python_Analyzer.md deleted file mode 100644 index faf3ffdd..00000000 --- a/docs/Python_Analyzer.md +++ /dev/null @@ -1,291 +0,0 @@ -# Python Analyzer - -## Introduction - -The **Python Analyzer** is the language-specific static analysis engine responsible for extracting structural components (classes, functions, methods) and call/dependency relationships from Python source files. It is one of several per-language analyzers plugged into the [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) pipeline (alongside the [C-Family Tree-sitter Analyzers](C-Family_Tree-sitter_Analyzers.md), [JavaScript/TypeScript Analyzers](JavaScript_TypeScript_Analyzers.md), and [PHP Analyzer](PHP_Analyzer.md)), and its output feeds the repository-wide dependency graph that ultimately powers documentation generation in [Backend_LLM_&_Documentation_Services](Backend_LLM_%26_Documentation_Services.md). - -Unlike the other language analyzers, which are built on `tree-sitter` grammars, the Python analyzer is implemented directly on top of Python's native `ast` module (`ast.NodeVisitor`), giving it precise, first-party access to the language's semantics (scopes, imports, class hierarchies, etc.) without an external parsing dependency. - -Its single entry point, `analyze_python_file`, is called once per `.py`/`.pyx` file discovered during repository analysis and returns: - -1. A list of extracted **`Node`** components (classes, functions, methods). -2. A list of **`CallRelationship`** edges (calls, inheritance, imports) between components. -3. The set of third-party (non-project) import roots observed in the file, used elsewhere to build a picture of external dependencies. - ---- - -## Purpose & Responsibilities - -| Responsibility | Description | -|---|---| -| **Component extraction** | Walks the AST to identify top-level classes, top-level functions, and methods, producing a `Node` for each with metadata (docstring, parameters, source snippet, line ranges, qualified name). | -| **Scope tracking** | Maintains a scope stack (`class`/`function`) to distinguish top-level definitions from nested/local ones, so that functions nested inside functions are treated as implementation detail rather than independent components. | -| **Import resolution** | Tracks `import` and `from ... import` statements, mapping local aliases to canonical dotted module paths, and classifies each import root as project-internal or external/third-party. | -| **Call resolution** | Analyzes `ast.Call` nodes to determine, wherever possible, which component a call target refers to β€” resolving `self`/`cls`/`super()` calls, calls on typed variables, calls on known same-file classes, and calls through imported names. | -| **Inheritance resolution** | Extracts base classes for each class and attempts to resolve inherited methods (including across `super()` chains) so that overridden/inherited method calls still map to the correct defining class when possible. | -| **Shallow type inference** | Performs a light "receiver knowledge" pass on simple assignments (`x = SomeClass()`, `x = module.factory()`) so that later attribute calls on `x` can be attributed to the right class or import origin. | - ---- - -## Architecture - -### Position in the Dependency Analysis Pipeline - -```mermaid -flowchart TD - subgraph Dependency_Analysis_Service - RA[RepoAnalyzer] --> AS[AnalysisService] - AS --> CGA[CallGraphAnalyzer] - end - - CGA -->|dispatches by file extension| PY[PythonASTAnalyzer<br/>.py / .pyx] - CGA --> TSJ[TreeSitterJSAnalyzer] - CGA --> TSTS[TreeSitterTSAnalyzer] - CGA --> TSPHP[TreeSitterPHPAnalyzer] - CGA --> TSC["C / C++ / C# / Java / Kotlin Analyzers"] - - PY -->|Nodes + CallRelationships + external roots| CGA - CGA --> DPB[DependencyGraphBuilder] - DPB --> AR[AnalysisResult] - - AR --> DGB[DependencyParser] - DGB -->|Dict of Node components| DOC[DocumentationGenerator] - - click PY "Python_Analyzer.md" -``` - -See [Dependency_Analysis_Service](Dependency_Analysis_Service.md) for the orchestration layer (`AnalysisService`, `CallGraphAnalyzer`, `RepoAnalyzer`) that discovers files, dispatches them to the correct language analyzer, and aggregates results. See [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) for the `DependencyParser`, `DependencyGraphBuilder`, and shared models (`Node`, `CallRelationship`, `AnalysisResult`) that this module produces and consumes. - -### Internal Class Structure - -```mermaid -classDiagram - class PythonASTAnalyzer { - -file_path: str - -repo_path: str - -content: str - -project_modules: Set~str~ - -nodes: List~Node~ - -call_relationships: List~CallRelationship~ - -scope_stack: List~Tuple~ - -component_stack: List~str~ - -top_level_nodes: Dict~str, Node~ - -class_methods: Dict~str, Set~str~~ - -class_bases: Dict~str, List~str~~ - -module_imports: Dict~str, str~ - -from_imports: Dict~str, str~ - -external_import_roots: Set~str~ - -var_types: Dict~str, str~ - -var_origins: Dict~str, str~ - -local_function_names: List~Set~str~~ - +analyze() - +visit_Import(node) - +visit_ImportFrom(node) - +visit_ClassDef(node) - +visit_FunctionDef(node) - +visit_AsyncFunctionDef(node) - +visit_Assign(node) - +visit_AnnAssign(node) - +visit_Call(node) - -_classify_call(func) - -_resolve_name_reference(name) - -_resolve_method_on_class(class_dotted, method) - -_resolve_method_via_bases(class_dotted, method) - -_attribute_chain(node) - } - - class Node { - +id: str - +name: str - +component_type: str - +file_path: str - +relative_path: str - +depends_on: Set~str~ - +source_code: str - +qualified_name: str - +get_display_name() - } - - class CallRelationship { - +caller: str - +callee: str - +call_line: int - +is_resolved: bool - } - - PythonASTAnalyzer --> Node : produces - PythonASTAnalyzer --> CallRelationship : produces - PythonASTAnalyzer ..> ExternalSymbols : uses - - class ExternalSymbols { - PYTHON_OBJECT_METHODS - PYTHON_STDLIB_MODULES - } -``` - -`Node` and `CallRelationship` are shared Pydantic models defined in [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) (`codewiki/src/be/dependency_analyzer/models/core.py`) and used identically by every language analyzer, which keeps downstream consumers (graph builder, documentation generator) language-agnostic. - ---- - -## Component Extraction Model - -The analyzer distinguishes three kinds of definitions and only promotes two of them to first-class components: - -```mermaid -flowchart TD - A[ast.parse source] --> B{Definition type} - B -->|Top-level class| C[Extract class Node<br/>component_type=class] - B -->|Top-level function| D[Extract function Node<br/>component_type=function] - B -->|Method inside a top-level class| E[Extract method Node<br/>component_type=method] - B -->|Class/function nested inside a function| F[Traverse for calls only<br/>NOT extracted as a component] - C --> G[Registered in top_level_nodes] - D --> G - E --> H[Registered in class_methods for the enclosing class] -``` - -Key rules: -- **Component ID** format: `"{relative_path}::{dotted_name}"`, e.g. `services/user.py::UserService.create`. -- **Qualified name** format: dotted-module style, e.g. `services.user.UserService.create`, used for cross-file/global resolution by the graph builder. -- Functions whose bare name starts with `_test_` are filtered out (`_should_include_function`), avoiding noise from ad-hoc test helpers. -- Nested functions/classes (defined inside another function) are **not** extracted as separate nodes β€” calls made from within them are attributed to the enclosing extracted component via `component_stack`, and their names are recorded in `local_function_names` to avoid misclassifying self-recursive/local calls as external references. - ---- - -## Import & Third-Party Classification - -```mermaid -sequenceDiagram - participant AST as ast.Import / ast.ImportFrom - participant PA as PythonASTAnalyzer - participant PM as project_modules (Set[str]) - participant EXT as external_import_roots - - AST->>PA: visit_Import / visit_ImportFrom - PA->>PA: bind alias -> canonical dotted target - PA->>PA: _note_import_root(target) - PA->>PM: is_project_import(target, project_modules)? - alt root is stdlib - PA-->>PA: ignore (in PYTHON_STDLIB_MODULES) - else matches a project module (dotted-boundary match) - PA-->>PA: treated as internal, not added to external roots - else - PA->>EXT: add root to external_import_roots - end -``` - -- `project_modules` is a set of dotted module paths for every Python file in the repository, supplied by the caller (`analyze_python_file`) so the analyzer can tell project-internal imports apart from third-party packages even in **src-layout** repos (e.g. import `pkg.util` matching project module `src.pkg.util`) via `_dotted_contains`. -- `PYTHON_STDLIB_MODULES` and `PYTHON_OBJECT_METHODS` come from `codewiki/src/be/dependency_analyzer/utils/external_symbols.py` and are used to filter out standard-library imports and built-in object methods (e.g. `__init__`, `append`) that should never resolve to project components. -- The returned `external_import_roots` set is aggregated across files by the [Dependency_Analysis_Service](Dependency_Analysis_Service.md) to characterize the repository's third-party footprint. - ---- - -## Call Resolution Logic - -Call resolution is the most intricate part of the analyzer. `visit_Call` delegates to `_classify_call`, which decides how confidently a call target can be tied to a project component. - -```mermaid -flowchart TD - Start[ast.Call node.func] --> IsName{Is ast.Name?} - IsName -->|Yes| ResolveName[_resolve_name_reference] - IsName -->|No, is ast.Attribute| Chain[_attribute_chain] - - Chain --> Composite{Chain resolvable<br/>to simple name path?} - Composite -->|No - composite receiver| ObjMethod{attr in<br/>PYTHON_OBJECT_METHODS?} - ObjMethod -->|Yes| Drop[No relationship emitted] - ObjMethod -->|No| Unresolved1["(attr, False) unresolved"] - - Composite -->|Yes| Root{Root of chain} - Root -->|self / cls + 1 attr| SelfMethod[_resolve_method_on_class<br/>on current class] - Root -->|super() + 1 attr| SuperMethod[_resolve_method_via_bases] - Root -->|typed variable var_types| VarMethod[_resolve_method_on_class<br/>on inferred class] - Root -->|known same-file class| ClassMethod[_resolve_method_on_class] - Root -->|from_imports / module_imports| ImportedDotted["(imported.dotted.path, False)"] - Root -->|var_origins tracked| OriginDotted["(origin.dotted.path, False)"] - Root -->|none of the above| RawDotted["(full dotted chain, False)"] - - ResolveName --> NameLocal{Shadowed by<br/>local_function_names?} - NameLocal -->|Yes| Drop - NameLocal -->|No| NameLookup{In top_level_nodes?} - NameLookup -->|Yes| Resolved["(file::name, True) RESOLVED"] - NameLookup -->|No, in imports| ImportedName["(imported.dotted.path, False)"] - NameLookup -->|No| RawName["(name, False)"] -``` - -### Resolution Confidence: `is_resolved` - -- **`is_resolved=True`** β€” the callee is a definitively known component in the *same file* (top-level function/class, `self`/`cls` method match, or inherited method found via same-file base classes). The callee id is a full component id: `"{relative_path}::{dotted_name}"`. -- **`is_resolved=False`** β€” the callee is expressed as a best-effort dotted/qualified name (e.g. `module.Class.method` or a bare unqualified name). These are resolved later β€” at the repository level β€” by matching against `qualified_name` across all files, which is why every `Node` also carries a `qualified_name`. - -### Inheritance-Aware Method Resolution - -`_resolve_method_via_bases` performs a breadth-first search over `class_bases` (populated during `visit_ClassDef`) to find which ancestor class actually defines a method being called via `self.method()`, `cls.method()`, or `super().method()`. If a base class is itself defined in the same file, the search continues transitively; if a base is external/imported, the analyzer emits an unresolved dotted callee (`imported.Base.method`) so the global resolver has a chance to match it against another file's qualified name. - ---- - -## Shallow Type Inference for Attribute Calls - -To resolve calls like `service.do_work()` where `service` is a local variable, the analyzer performs a lightweight, single-assignment type inference: - -```mermaid -flowchart LR - A["x = SomeClass()"] -->|root is a same-file class,<br/>no further attrs| B[var_types[x] = SomeClass] - C["x = module.factory()"] -->|root is an import| D[var_origins[x] = module.factory] - B --> E["x.method() resolves via<br/>_resolve_method_on_class(SomeClass, method)"] - D --> F["x.method() resolves to<br/>module.factory.method (unresolved)"] -``` - -This tracking is intentionally shallow: it only considers single-target `Name = Call(...)` assignments (including annotated assignments), and only the most recent assignment to a name is remembered (no flow-sensitive reassignment tracking, no branch merging). - ---- - -## Public API - -### `analyze_python_file(file_path, content, repo_path=None, project_modules=None) -> Tuple[List[Node], List[CallRelationship], Set[str]]` - -The single function other modules should call. It instantiates `PythonASTAnalyzer`, runs `.analyze()`, and returns the accumulated nodes, relationships, and external import roots. This is invoked by the `CallGraphAnalyzer` in [Dependency_Analysis_Service](Dependency_Analysis_Service.md) as part of the multi-language repository scan orchestrated by `AnalysisService` and `RepoAnalyzer`. - -```mermaid -sequenceDiagram - participant CGA as CallGraphAnalyzer - participant Fn as analyze_python_file - participant PA as PythonASTAnalyzer - - CGA->>Fn: analyze_python_file(path, content, repo_path, project_modules) - Fn->>PA: new PythonASTAnalyzer(...) - Fn->>PA: analyzer.analyze() - PA->>PA: ast.parse(content) (SyntaxWarning suppressed) - PA->>PA: self.visit(tree) (NodeVisitor traversal) - Fn-->>CGA: (nodes, call_relationships, external_import_roots) -``` - -`analyze()` guards parsing with `warnings.catch_warnings()` to suppress `SyntaxWarning`s from regex-like escape sequences in analyzed source, and catches `SyntaxError`/generic exceptions so a single unparsable file does not abort the whole repository scan (logged and skipped instead). - ---- - -## Downstream Consumption - -The `(nodes, call_relationships, external_import_roots)` tuple produced per file is merged by the `CallGraphAnalyzer` with the results of all other language analyzers into a single repository-wide call graph. This flows into: - -- **`DependencyGraphBuilder`** / **`DependencyParser`** (see [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md)) β€” builds the final `depends_on` edges on each `Node` by matching unresolved `CallRelationship.callee` dotted names against every node's `qualified_name`, and resolved callees directly by component id. -- **`AnalysisResult`** β€” the top-level result object consumed by the [Backend_LLM_&_Documentation_Services](Backend_LLM_%26_Documentation_Services.md) module (`DocumentationGenerator`, `PydanticAIBackend`, etc.) to generate per-module and per-component documentation, including dependency-aware context for LLM prompts. - -```mermaid -flowchart LR - PY[PythonASTAnalyzer] --> CGA[CallGraphAnalyzer] - CGA --> DGB[DependencyGraphBuilder] - DGB --> AR[AnalysisResult] - AR --> DP[DependencyParser] - DP --> DG[DocumentationGenerator] - DG --> DOCS[Generated Markdown Docs] -``` - ---- - -## Related Modules - -| Module | Relationship | -|---|---| -| [Dependency_Analysis_Service](Dependency_Analysis_Service.md) | Orchestrates repository scanning and dispatches files to `PythonASTAnalyzer` (and sibling analyzers). | -| [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) | Defines the shared `Node`/`CallRelationship`/`AnalysisResult` models this analyzer emits, and builds the final dependency graph. | -| [C-Family_Tree-sitter_Analyzers](C-Family_Tree-sitter_Analyzers.md), [JavaScript_TypeScript_Analyzers](JavaScript_TypeScript_Analyzers.md), [PHP_Analyzer](PHP_Analyzer.md) | Sibling language analyzers producing the same `Node`/`CallRelationship` contract using tree-sitter grammars instead of Python's native `ast`. | -| [Backend_LLM_&_Documentation_Services](Backend_LLM_%26_Documentation_Services.md) | Consumes the aggregated dependency graph to generate documentation for each analyzed component. | diff --git a/docs/User_Interfaces.md b/docs/User_Interfaces.md deleted file mode 100644 index f3842a19..00000000 --- a/docs/User_Interfaces.md +++ /dev/null @@ -1,79 +0,0 @@ -# User Interfaces - -## Purpose - -The **User_Interfaces** subsystem is the set of interchangeable front-ends through which users drive CodeWiki. All three converge on the same underlying pipeline β€” [Code_Analysis_Engine](Code_Analysis_Engine.md) followed by [Documentation_Generation_Engine](Documentation_Generation_Engine.md) β€” but serve different workflows: - -1. **[CLI](CLI.md)** β€” the `codewiki` command-line tool for local, one-shot repository documentation: interactive configuration and credential management, incremental updates (`--update` / `--compare-to`), git branch/PR automation, static HTML viewer generation for GitHub Pages, and terminal progress UX. -2. **[Frontend_Web_App](Frontend_Web_App.md)** β€” a FastAPI web service that accepts GitHub repository URLs, clones and processes them asynchronously through a background worker with job tracking and caching, and serves the generated documentation as browsable HTML. -3. **[MCP_Session_Management](MCP_Session_Management.md)** β€” stateful session and on-disk workspace management for CodeWiki's MCP server, which exposes analysis and documentation tools to IDE-integrated AI assistants over the Model Context Protocol for interactive, multi-step workflows. - -## Architecture - -```mermaid -flowchart TB - UserCLI(["Terminal user"]) --> CLI - UserWeb(["Browser user"]) --> FE - UserIDE(["IDE AI assistant"]) --> MCP - - subgraph UI["User_Interfaces"] - subgraph CLI["CLI"] - CM["ConfigManager<br/>(config + keyring credentials)"] - DGA["CLIDocumentationGenerator<br/>(pipeline adapter)"] - GM["GitManager<br/>(branch / PR automation)"] - HG["HTMLGenerator<br/>(static viewer)"] - UX["CLILogger / ProgressTracker"] - end - subgraph FE["Frontend_Web_App"] - RT["WebRoutes<br/>(FastAPI endpoints)"] - BW["BackgroundWorker<br/>(async job queue)"] - GH["GitHubRepoProcessor"] - CACHE["CacheManager"] - end - subgraph MCP["MCP_Session_Management"] - SS["SessionStore / SessionState"] - WS["SessionWorkspace<br/>(on-disk isolation)"] - end - end - - DGA --> Pipeline["Code_Analysis_Engine β†’<br/>Documentation_Generation_Engine"] - BW --> Pipeline - SS --> Pipeline - - Pipeline --> MD["Markdown docs + module_tree.json"] - MD --> HG - MD --> RT - MD --> WS - - click CM "CLI_Configuration.md" - click DGA "CLI_Documentation_Generation.md" - click GM "CLI_Git_Integration.md" - click HG "CLI_HTML_Viewer.md" - click UX "CLI_Utilities.md" - click RT "Frontend_Web_App_web_routes.md" - click BW "Frontend_Web_App_job_processing.md" - click GH "Frontend_Web_App_github_config.md" - click SS "MCP_Session_Management.md" - click WS "MCP_Session_Management.md" - click Pipeline "Code_Analysis_Engine.md" -``` - -Key design decisions: - -* **Thin front-ends, shared backend.** Each interface only handles its own input/output concerns (argument parsing, HTTP, MCP protocol); documentation work is always delegated to the shared pipeline, so behavior stays consistent across entry points. -* **Different execution models.** The CLI runs synchronously in-process with terminal progress bars; the web app decouples request handling from processing via `BackgroundWorker` and job-status polling; the MCP server holds long-lived sessions whose state and artifacts live in isolated on-disk workspaces. -* **Output tailored per audience.** The CLI can emit a self-contained GitHub Pages viewer (`index.html`), the web app renders docs server-side for browsing, and the MCP server returns structured results for agent consumption. - -## Modules - -| Module | Responsibility | Documentation | -|---|---|---| -| **CLI** | Local command-line generation: configuration, git integration, HTML viewer, terminal UX | [CLI.md](CLI.md) | -| **Frontend_Web_App** | FastAPI service: GitHub repo submission, async job processing, caching, HTML rendering | [Frontend_Web_App.md](Frontend_Web_App.md) | -| **MCP_Session_Management** | Stateful sessions and workspaces for the MCP server / IDE agents | [MCP_Session_Management.md](MCP_Session_Management.md) | - -## Related Modules - -* [Documentation_Generation_Engine](Documentation_Generation_Engine.md) β€” the pipeline these interfaces invoke and whose output they present. -* [Code_Analysis_Engine](Code_Analysis_Engine.md) β€” the static-analysis stage triggered at the start of every run. -* [Core_Config_&_Utils](Core_Config_&_Utils.md) β€” the shared `Config` object each front-end constructs from its own input format. diff --git a/docs/codewiki-icon.png b/docs/codewiki-icon.png deleted file mode 100644 index 2ba03266..00000000 Binary files a/docs/codewiki-icon.png and /dev/null differ diff --git a/docs/first_module_tree.json b/docs/first_module_tree.json deleted file mode 100644 index 8fae3d4a..00000000 --- a/docs/first_module_tree.json +++ /dev/null @@ -1,230 +0,0 @@ -{ - "Code_Analysis_Engine": { - "path": "codewiki/src/be/dependency_analyzer", - "components": [ - "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser", - "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py::DependencyGraphBuilder", - "codewiki/src/be/dependency_analyzer/models/analysis.py::AnalysisResult", - "codewiki/src/be/dependency_analyzer/models/analysis.py::NodeSelection", - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "codewiki/src/be/dependency_analyzer/models/core.py::Repository", - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter", - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter", - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer" - ], - "children": { - "Dependency_Analyzer_Core": { - "path": "codewiki/src/be/dependency_analyzer", - "components": [ - "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser", - "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py::DependencyGraphBuilder", - "codewiki/src/be/dependency_analyzer/models/analysis.py::AnalysisResult", - "codewiki/src/be/dependency_analyzer/models/analysis.py::NodeSelection", - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "codewiki/src/be/dependency_analyzer/models/core.py::Repository", - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter" - ], - "children": {} - }, - "Dependency_Analysis_Service": { - "path": "codewiki/src/be/dependency_analyzer/analysis", - "components": [ - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter" - ], - "children": {} - }, - "Language_Analyzers": { - "path": "codewiki/src/be/dependency_analyzer/analyzers", - "components": [ - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer" - ], - "children": { - "C-Family_Tree-sitter_Analyzers": { - "components": [ - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer" - ], - "children": {} - }, - "JavaScript_TypeScript_Analyzers": { - "components": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer" - ], - "children": {} - }, - "PHP_Analyzer": { - "components": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver" - ], - "children": {} - }, - "Python_Analyzer": { - "components": [ - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer" - ], - "children": {} - } - } - } - } - }, - "Documentation_Generation_Engine": { - "path": "codewiki/src/be", - "components": [ - "codewiki/src/be/backend.py::LLMBackend", - "codewiki/src/be/caw_backend.py::CawBackend", - "codewiki/src/be/caw_toolkit.py::CawToolKit", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator", - "codewiki/src/be/llm_services.py::CompatibleOpenAIModel", - "codewiki/src/be/llm_services.py::CachingOpenAIModel", - "codewiki/src/be/pydantic_ai_backend.py::PydanticAIBackend", - "codewiki/src/be/agent_tools/deps.py::CodeWikiDeps", - "codewiki/src/be/agent_tools/str_replace_editor.py::Filemap", - "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool" - ], - "children": { - "Backend_LLM_&_Documentation_Services": { - "path": "codewiki/src/be", - "components": [ - "codewiki/src/be/backend.py::LLMBackend", - "codewiki/src/be/caw_backend.py::CawBackend", - "codewiki/src/be/caw_toolkit.py::CawToolKit", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator", - "codewiki/src/be/llm_services.py::CompatibleOpenAIModel", - "codewiki/src/be/llm_services.py::CachingOpenAIModel", - "codewiki/src/be/pydantic_ai_backend.py::PydanticAIBackend" - ], - "children": {} - }, - "Backend_Agent_Tools": { - "path": "codewiki/src/be/agent_tools", - "components": [ - "codewiki/src/be/agent_tools/deps.py::CodeWikiDeps", - "codewiki/src/be/agent_tools/str_replace_editor.py::Filemap", - "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool" - ], - "children": {} - } - } - }, - "User_Interfaces": { - "path": "codewiki", - "components": [ - "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator", - "codewiki/cli/config_manager.py::ConfigManager", - "codewiki/cli/git_manager.py::GitManager", - "codewiki/cli/html_generator.py::HTMLGenerator", - "codewiki/cli/models/config.py::Configuration", - "codewiki/cli/models/config.py::AgentInstructions", - "codewiki/cli/models/job.py::JobStatus", - "codewiki/cli/models/job.py::LLMConfig", - "codewiki/cli/models/job.py::DocumentationJob", - "codewiki/cli/models/job.py::GenerationOptions", - "codewiki/cli/models/job.py::JobStatistics", - "codewiki/cli/utils/logging.py::CLILogger", - "codewiki/cli/utils/progress.py::ProgressTracker", - "codewiki/cli/utils/progress.py::ModuleProgressBar", - "codewiki/src/fe/background_worker.py::BackgroundWorker", - "codewiki/src/fe/cache_manager.py::CacheManager", - "codewiki/src/fe/config.py::WebAppConfig", - "codewiki/src/fe/github_processor.py::GitHubRepoProcessor", - "codewiki/src/fe/models.py::CacheEntry", - "codewiki/src/fe/models.py::JobStatusResponse", - "codewiki/src/fe/models.py::RepositorySubmission", - "codewiki/src/fe/models.py::JobStatus", - "codewiki/src/fe/routes.py::WebRoutes", - "codewiki/src/fe/template_utils.py::StringTemplateLoader", - "codewiki/mcp/session.py::SessionStore", - "codewiki/mcp/session.py::SessionState", - "codewiki/mcp/workspace.py::SessionWorkspace" - ], - "children": { - "CLI": { - "path": "codewiki/cli", - "components": [ - "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator", - "codewiki/cli/config_manager.py::ConfigManager", - "codewiki/cli/git_manager.py::GitManager", - "codewiki/cli/html_generator.py::HTMLGenerator", - "codewiki/cli/models/config.py::Configuration", - "codewiki/cli/models/config.py::AgentInstructions", - "codewiki/cli/models/job.py::JobStatus", - "codewiki/cli/models/job.py::LLMConfig", - "codewiki/cli/models/job.py::DocumentationJob", - "codewiki/cli/models/job.py::GenerationOptions", - "codewiki/cli/models/job.py::JobStatistics", - "codewiki/cli/utils/logging.py::CLILogger", - "codewiki/cli/utils/progress.py::ProgressTracker", - "codewiki/cli/utils/progress.py::ModuleProgressBar" - ], - "children": {} - }, - "Frontend_Web_App": { - "path": "codewiki/src/fe", - "components": [ - "codewiki/src/fe/background_worker.py::BackgroundWorker", - "codewiki/src/fe/cache_manager.py::CacheManager", - "codewiki/src/fe/config.py::WebAppConfig", - "codewiki/src/fe/github_processor.py::GitHubRepoProcessor", - "codewiki/src/fe/models.py::CacheEntry", - "codewiki/src/fe/models.py::JobStatusResponse", - "codewiki/src/fe/models.py::RepositorySubmission", - "codewiki/src/fe/models.py::JobStatus", - "codewiki/src/fe/routes.py::WebRoutes", - "codewiki/src/fe/template_utils.py::StringTemplateLoader" - ], - "children": {} - }, - "MCP_Session_Management": { - "path": "codewiki/mcp", - "components": [ - "codewiki/mcp/session.py::SessionStore", - "codewiki/mcp/session.py::SessionState", - "codewiki/mcp/workspace.py::SessionWorkspace" - ], - "children": {} - } - } - }, - "Core_Config_&_Utils": { - "path": "codewiki/src", - "components": [ - "codewiki/src/config.py::Config", - "codewiki/src/utils.py::FileManager" - ], - "children": {} - } -} diff --git a/docs/index.html b/docs/index.html deleted file mode 100644 index d8273a38..00000000 --- a/docs/index.html +++ /dev/null @@ -1,2193 +0,0 @@ -<!DOCTYPE html> -<html lang="en"> -<head> - <meta charset="UTF-8"> - <meta name="viewport" content="width=device-width, initial-scale=1.0"> - <title>CodeWiki - - - - - - - - - - - - -
- -
- - -
-
-
-
-
-

Loading documentation...

-
- - - - -
- - -
-
-
- - - - diff --git a/docs/metadata.json b/docs/metadata.json deleted file mode 100644 index 34158510..00000000 --- a/docs/metadata.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "generation_info": { - "timestamp": "2026-08-06T15:09:29.618082", - "main_model": "claude-sonnet-4", - "generator_version": "1.0.1", - "repo_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki", - "commit_id": "3c4b4c244a94848d7ceacbc2a8efd31184b0ed16" - }, - "statistics": { - "total_components": 768, - "leaf_nodes": 62, - "max_depth": 4 - }, - "files_generated": [ - "overview.md", - "module_tree.json", - "first_module_tree.json", - "Code_Analysis_Engine.md", - "Documentation_Generation_Engine.md", - "User_Interfaces.md", - "Backend_LLM_&_Documentation_Services_caw_backend.md", - "Dependency_Analyzer_Core_models.md", - "Backend_LLM_&_Documentation_Services_documentation_generator.md", - "Dependency_Analyzer_Core.md", - "Backend_LLM_&_Documentation_Services_pydantic_ai_backend.md", - "C-Family_Tree-sitter_Analyzers_CSharp.md", - "CLI_Documentation_Generation.md", - "CLI_Utilities.md", - "Frontend_Web_App_github_config.md", - "CLI_Git_Integration.md", - "Core_Config_&_Utils.md", - "C-Family_Tree-sitter_Analyzers.md", - "C-Family_Tree-sitter_Analyzers_JVM.md", - "JavaScript_TypeScript_Analyzers.md", - "Python_Analyzer.md", - "Language_Analyzers.md", - "CLI_HTML_Viewer.md", - "Backend_LLM_&_Documentation_Services.md", - "MCP_Session_Management.md", - "Frontend_Web_App_job_processing.md", - "Dependency_Analysis_Service.md", - "PHP_Analyzer.md", - "Backend_Agent_Tools.md", - "Dependency_Analyzer_Core_parsing.md", - "JavaScript_TypeScript_Analyzers_typescript.md", - "C-Family_Tree-sitter_Analyzers_C_Cpp.md", - "JavaScript_TypeScript_Analyzers_javascript.md", - "CLI.md", - "CLI_Configuration.md", - "Frontend_Web_App_web_routes.md", - "Frontend_Web_App.md" - ] -} \ No newline at end of file diff --git a/docs/module_tree.json b/docs/module_tree.json deleted file mode 100644 index 8da54c37..00000000 --- a/docs/module_tree.json +++ /dev/null @@ -1,371 +0,0 @@ -{ - "Code_Analysis_Engine": { - "path": "codewiki/src/be/dependency_analyzer", - "components": [ - "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser", - "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py::DependencyGraphBuilder", - "codewiki/src/be/dependency_analyzer/models/analysis.py::AnalysisResult", - "codewiki/src/be/dependency_analyzer/models/analysis.py::NodeSelection", - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "codewiki/src/be/dependency_analyzer/models/core.py::Repository", - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter", - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter", - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer" - ], - "children": { - "Dependency_Analyzer_Core": { - "path": "codewiki/src/be/dependency_analyzer", - "components": [ - "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser", - "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py::DependencyGraphBuilder", - "codewiki/src/be/dependency_analyzer/models/analysis.py::AnalysisResult", - "codewiki/src/be/dependency_analyzer/models/analysis.py::NodeSelection", - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "codewiki/src/be/dependency_analyzer/models/core.py::Repository", - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter" - ], - "children": { - "Dependency_Analyzer_Core_models": { - "components": [ - "codewiki/src/be/dependency_analyzer/models/analysis.py::AnalysisResult", - "codewiki/src/be/dependency_analyzer/models/analysis.py::NodeSelection", - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "codewiki/src/be/dependency_analyzer/models/core.py::Repository" - ], - "children": {} - }, - "Dependency_Analyzer_Core_parsing": { - "components": [ - "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser", - "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py::DependencyGraphBuilder" - ], - "children": {} - } - } - }, - "Dependency_Analysis_Service": { - "path": "codewiki/src/be/dependency_analyzer/analysis", - "components": [ - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter" - ], - "children": {} - }, - "Language_Analyzers": { - "path": "codewiki/src/be/dependency_analyzer/analyzers", - "components": [ - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer" - ], - "children": { - "C-Family_Tree-sitter_Analyzers": { - "components": [ - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer" - ], - "children": { - "C-Family_Tree-sitter_Analyzers_C_Cpp": { - "components": [ - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer" - ], - "children": {} - }, - "C-Family_Tree-sitter_Analyzers_CSharp": { - "components": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer" - ], - "children": {} - }, - "C-Family_Tree-sitter_Analyzers_JVM": { - "components": [ - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer" - ], - "children": {} - } - } - }, - "JavaScript_TypeScript_Analyzers": { - "components": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer" - ], - "children": { - "JavaScript_TypeScript_Analyzers_javascript": { - "components": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer" - ], - "children": {} - }, - "JavaScript_TypeScript_Analyzers_typescript": { - "components": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer" - ], - "children": {} - } - } - }, - "PHP_Analyzer": { - "components": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver" - ], - "children": {} - }, - "Python_Analyzer": { - "components": [ - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer" - ], - "children": {} - } - } - } - } - }, - "Documentation_Generation_Engine": { - "path": "codewiki/src/be", - "components": [ - "codewiki/src/be/backend.py::LLMBackend", - "codewiki/src/be/caw_backend.py::CawBackend", - "codewiki/src/be/caw_toolkit.py::CawToolKit", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator", - "codewiki/src/be/llm_services.py::CompatibleOpenAIModel", - "codewiki/src/be/llm_services.py::CachingOpenAIModel", - "codewiki/src/be/pydantic_ai_backend.py::PydanticAIBackend", - "codewiki/src/be/agent_tools/deps.py::CodeWikiDeps", - "codewiki/src/be/agent_tools/str_replace_editor.py::Filemap", - "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool" - ], - "children": { - "Backend_LLM_&_Documentation_Services": { - "path": "codewiki/src/be", - "components": [ - "codewiki/src/be/backend.py::LLMBackend", - "codewiki/src/be/caw_backend.py::CawBackend", - "codewiki/src/be/caw_toolkit.py::CawToolKit", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator", - "codewiki/src/be/llm_services.py::CompatibleOpenAIModel", - "codewiki/src/be/llm_services.py::CachingOpenAIModel", - "codewiki/src/be/pydantic_ai_backend.py::PydanticAIBackend" - ], - "children": { - "Backend_LLM_&_Documentation_Services_caw_backend": { - "components": [ - "codewiki/src/be/caw_backend.py::CawBackend", - "codewiki/src/be/caw_toolkit.py::CawToolKit" - ], - "children": {} - }, - "Backend_LLM_&_Documentation_Services_documentation_generator": { - "components": [ - "codewiki/src/be/documentation_generator.py::DocumentationGenerator" - ], - "children": {} - }, - "Backend_LLM_&_Documentation_Services_pydantic_ai_backend": { - "components": [ - "codewiki/src/be/pydantic_ai_backend.py::PydanticAIBackend", - "codewiki/src/be/backend.py::LLMBackend", - "codewiki/src/be/llm_services.py::CompatibleOpenAIModel", - "codewiki/src/be/llm_services.py::CachingOpenAIModel" - ], - "children": {} - } - } - }, - "Backend_Agent_Tools": { - "path": "codewiki/src/be/agent_tools", - "components": [ - "codewiki/src/be/agent_tools/deps.py::CodeWikiDeps", - "codewiki/src/be/agent_tools/str_replace_editor.py::Filemap", - "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool" - ], - "children": {} - } - } - }, - "User_Interfaces": { - "path": "codewiki", - "components": [ - "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator", - "codewiki/cli/config_manager.py::ConfigManager", - "codewiki/cli/git_manager.py::GitManager", - "codewiki/cli/html_generator.py::HTMLGenerator", - "codewiki/cli/models/config.py::Configuration", - "codewiki/cli/models/config.py::AgentInstructions", - "codewiki/cli/models/job.py::JobStatus", - "codewiki/cli/models/job.py::LLMConfig", - "codewiki/cli/models/job.py::DocumentationJob", - "codewiki/cli/models/job.py::GenerationOptions", - "codewiki/cli/models/job.py::JobStatistics", - "codewiki/cli/utils/logging.py::CLILogger", - "codewiki/cli/utils/progress.py::ProgressTracker", - "codewiki/cli/utils/progress.py::ModuleProgressBar", - "codewiki/src/fe/background_worker.py::BackgroundWorker", - "codewiki/src/fe/cache_manager.py::CacheManager", - "codewiki/src/fe/config.py::WebAppConfig", - "codewiki/src/fe/github_processor.py::GitHubRepoProcessor", - "codewiki/src/fe/models.py::CacheEntry", - "codewiki/src/fe/models.py::JobStatusResponse", - "codewiki/src/fe/models.py::RepositorySubmission", - "codewiki/src/fe/models.py::JobStatus", - "codewiki/src/fe/routes.py::WebRoutes", - "codewiki/src/fe/template_utils.py::StringTemplateLoader", - "codewiki/mcp/session.py::SessionStore", - "codewiki/mcp/session.py::SessionState", - "codewiki/mcp/workspace.py::SessionWorkspace" - ], - "children": { - "CLI": { - "path": "codewiki/cli", - "components": [ - "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator", - "codewiki/cli/config_manager.py::ConfigManager", - "codewiki/cli/git_manager.py::GitManager", - "codewiki/cli/html_generator.py::HTMLGenerator", - "codewiki/cli/models/config.py::Configuration", - "codewiki/cli/models/config.py::AgentInstructions", - "codewiki/cli/models/job.py::JobStatus", - "codewiki/cli/models/job.py::LLMConfig", - "codewiki/cli/models/job.py::DocumentationJob", - "codewiki/cli/models/job.py::GenerationOptions", - "codewiki/cli/models/job.py::JobStatistics", - "codewiki/cli/utils/logging.py::CLILogger", - "codewiki/cli/utils/progress.py::ProgressTracker", - "codewiki/cli/utils/progress.py::ModuleProgressBar" - ], - "children": { - "CLI_Configuration": { - "components": [ - "codewiki/cli/config_manager.py::ConfigManager", - "codewiki/cli/models/config.py::Configuration", - "codewiki/cli/models/config.py::AgentInstructions" - ], - "children": {} - }, - "CLI_Documentation_Generation": { - "components": [ - "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator", - "codewiki/cli/models/job.py::JobStatus", - "codewiki/cli/models/job.py::LLMConfig", - "codewiki/cli/models/job.py::DocumentationJob", - "codewiki/cli/models/job.py::GenerationOptions", - "codewiki/cli/models/job.py::JobStatistics" - ], - "children": {} - }, - "CLI_Git_Integration": { - "components": [ - "codewiki/cli/git_manager.py::GitManager" - ], - "children": {} - }, - "CLI_HTML_Viewer": { - "components": [ - "codewiki/cli/html_generator.py::HTMLGenerator" - ], - "children": {} - }, - "CLI_Utilities": { - "components": [ - "codewiki/cli/utils/logging.py::CLILogger", - "codewiki/cli/utils/progress.py::ProgressTracker", - "codewiki/cli/utils/progress.py::ModuleProgressBar" - ], - "children": {} - } - } - }, - "Frontend_Web_App": { - "path": "codewiki/src/fe", - "components": [ - "codewiki/src/fe/background_worker.py::BackgroundWorker", - "codewiki/src/fe/cache_manager.py::CacheManager", - "codewiki/src/fe/config.py::WebAppConfig", - "codewiki/src/fe/github_processor.py::GitHubRepoProcessor", - "codewiki/src/fe/models.py::CacheEntry", - "codewiki/src/fe/models.py::JobStatusResponse", - "codewiki/src/fe/models.py::RepositorySubmission", - "codewiki/src/fe/models.py::JobStatus", - "codewiki/src/fe/routes.py::WebRoutes", - "codewiki/src/fe/template_utils.py::StringTemplateLoader" - ], - "children": { - "Frontend_Web_App_github_config": { - "components": [ - "codewiki/src/fe/github_processor.py::GitHubRepoProcessor", - "codewiki/src/fe/config.py::WebAppConfig" - ], - "children": {} - }, - "Frontend_Web_App_job_processing": { - "components": [ - "codewiki/src/fe/background_worker.py::BackgroundWorker", - "codewiki/src/fe/cache_manager.py::CacheManager", - "codewiki/src/fe/models.py::CacheEntry", - "codewiki/src/fe/models.py::JobStatus" - ], - "children": {} - }, - "Frontend_Web_App_web_routes": { - "components": [ - "codewiki/src/fe/routes.py::WebRoutes", - "codewiki/src/fe/template_utils.py::StringTemplateLoader", - "codewiki/src/fe/models.py::JobStatusResponse", - "codewiki/src/fe/models.py::RepositorySubmission" - ], - "children": {} - } - } - }, - "MCP_Session_Management": { - "path": "codewiki/mcp", - "components": [ - "codewiki/mcp/session.py::SessionStore", - "codewiki/mcp/session.py::SessionState", - "codewiki/mcp/workspace.py::SessionWorkspace" - ], - "children": {} - } - } - }, - "Core_Config_&_Utils": { - "path": "codewiki/src", - "components": [ - "codewiki/src/config.py::Config", - "codewiki/src/utils.py::FileManager" - ], - "children": {} - } -} diff --git a/docs/overview.md b/docs/overview.md deleted file mode 100644 index c1425838..00000000 --- a/docs/overview.md +++ /dev/null @@ -1,133 +0,0 @@ -# CodeWiki - -## Overview - -**CodeWiki** is an AI-powered documentation generation system that analyzes source code repositories across multiple programming languages and automatically produces structured, hierarchical, human-readable documentation. It combines static dependency analysis (via `tree-sitter` grammars and Python's native `ast`) with LLM-driven agents to understand code architecture, cluster related components into logical modules, and generate Markdown documentation β€” complete with Mermaid diagrams β€” bottom-up from leaf components to a full repository overview. - -CodeWiki exposes three interchangeable front-ends to the same underlying pipeline: - -- **CLI** β€” a command-line tool for local, one-shot repository documentation with optional git-branch/PR automation. -- **Frontend Web App** β€” a FastAPI-based web service that accepts GitHub repository URLs, processes them asynchronously, and serves the results as browsable HTML. -- **MCP Server** (via MCP Session Management) β€” exposes CodeWiki's analysis and documentation tools to IDE-integrated AI assistants over the Model Context Protocol, with stateful sessions for interactive, multi-step workflows. - -All three front-ends converge on a shared backend: dependency analysis β†’ module clustering β†’ LLM-driven per-module documentation β†’ validated output. - -## End-to-End Architecture - -```mermaid -flowchart TB - subgraph Entry["Entry Points"] - CLI["CLI\n(codewiki generate / configure)"] - FE["Frontend Web App\n(FastAPI + BackgroundWorker)"] - MCPServer["MCP Server\n(MCP_Session_Management)"] - end - - subgraph Core["Core_Config_&_Utils"] - Config["Config"] - FM["FileManager"] - end - - subgraph Analysis["Dependency Analysis Pipeline"] - DAC["Dependency_Analyzer_Core\n(DependencyParser, DependencyGraphBuilder,\nNode/CallRelationship models)"] - DAS["Dependency_Analysis_Service\n(AnalysisService, RepoAnalyzer, CallGraphAnalyzer)"] - LANG["Language_Analyzers\n(Python, JS/TS, C-family, PHP)"] - end - - subgraph Docs["Backend_LLM_&_Documentation_Services"] - DG["DocumentationGenerator"] - Backend["LLMBackend\n(PydanticAIBackend / CawBackend)"] - end - - Tools["Backend_Agent_Tools\n(CodeWikiDeps, EditTool, str_replace_editor)"] - - CLI --> Config - FE --> Config - MCPServer --> DAS - - Config --> DAC - Config --> Docs - DAC --> DAS - DAS --> LANG - - DG --> DAC - DG --> Backend - Backend --> Tools - - FM -.-> DAC - FM -.-> Docs - FM -.-> FE - FM -.-> CLI - - Docs --> Output["Generated Markdown Docs\n+ Mermaid diagrams"] - CLI --> Output - FE --> Output -``` - -### Documentation Generation Flow - -```mermaid -sequenceDiagram - participant User - participant Entry as CLI / Web / MCP - participant Cfg as Config - participant DGB as DependencyGraphBuilder - participant DAS as AnalysisService - participant DG as DocumentationGenerator - participant LLM as LLMBackend - - User->>Entry: submit repo (path or URL) - Entry->>Cfg: build Config (from_args / from_cli) - Entry->>DG: instantiate DocumentationGenerator(Config) - DG->>DGB: build_dependency_graph() - DGB->>DAS: parse_repository() (per-language analysis) - DAS-->>DGB: components (Node map), leaf_nodes - DGB-->>DG: components, leaf_nodes - DG->>DG: cluster_modules() -> module_tree - loop leaf-first traversal - DG->>LLM: run_module_agent(module, components) - LLM-->>DG: module_name.md written - end - DG->>LLM: complete(REPO_OVERVIEW_PROMPT) - LLM-->>DG: overview.md - DG-->>Entry: validated documentation set - Entry-->>User: rendered docs / job status -``` - -## Subsystems & Core Modules - -The system is organized into three architectural subsystems plus a shared foundation: - -### [Code_Analysis_Engine](Code_Analysis_Engine.md) - -The LLM-free static-analysis front half: turns a source repository into a fully-resolved dependency graph. - -| Module | Description | -|---|---| -| [Dependency_Analyzer_Core](Dependency_Analyzer_Core.md) | Shared data models (`Node`, `CallRelationship`, `Repository`, `AnalysisResult`) and the graph-building/leaf-selection logic. | -| [Dependency_Analysis_Service](Dependency_Analysis_Service.md) | Orchestrates repository cloning/discovery, per-language call-graph construction, and cross-file symbol resolution. | -| [Language_Analyzers](Language_Analyzers.md) | Per-language static analyzers (Python AST, tree-sitter for JS/TS, C-family, PHP) extracting components and relationships. | - -### [Documentation_Generation_Engine](Documentation_Generation_Engine.md) - -The LLM-driven back half: clusters components into a module hierarchy and generates the documentation set bottom-up. - -| Module | Description | -|---|---| -| [Backend_LLM_&_Documentation_Services](Backend_LLM_&_Documentation_Services.md) | The orchestration engine: LLM backend abstraction (API-key and subscription-based) and the `DocumentationGenerator` that drives end-to-end doc generation. | -| [Backend_Agent_Tools](Backend_Agent_Tools.md) | Sandboxed agent-facing tools (file viewer/editor with Mermaid validation) and the shared `CodeWikiDeps` context object. | - -### [User_Interfaces](User_Interfaces.md) - -The interchangeable front-ends that drive the shared pipeline. - -| Module | Description | -|---|---| -| [CLI](CLI.md) | Command-line entry point: configuration management, git integration, static HTML viewer generation, and terminal UX utilities driving the backend pipeline. | -| [Frontend_Web_App](Frontend_Web_App.md) | FastAPI web application for submitting GitHub repos, background job processing, caching, and rendering documentation as HTML. | -| [MCP_Session_Management](MCP_Session_Management.md) | Stateful session and on-disk workspace management for the MCP server, enabling interactive IDE-agent workflows. | - -### Shared foundation - -| Module | Description | -|---|---| -| [Core_Config_&_Utils](Core_Config_&_Utils.md) | Foundational, dependency-free configuration (`Config`) and file I/O (`FileManager`) utilities used throughout the system. | \ No newline at end of file diff --git a/docs/temp/dependency_graphs/CodeWiki_dependency_graph.json b/docs/temp/dependency_graphs/CodeWiki_dependency_graph.json deleted file mode 100644 index 0b8614d6..00000000 --- a/docs/temp/dependency_graphs/CodeWiki_dependency_graph.json +++ /dev/null @@ -1,20261 +0,0 @@ -{ - "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator": { - "id": "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator", - "name": "CLIDocumentationGenerator", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/adapters/doc_generator.py", - "relative_path": "codewiki/cli/adapters/doc_generator.py", - "depends_on": [], - "source_code": "class CLIDocumentationGenerator:\n \"\"\"\n CLI adapter for documentation generation with progress reporting.\n \n This class wraps the backend documentation generator and adds\n CLI-specific features like progress tracking and error handling.\n \"\"\"\n \n def __init__(\n self,\n repo_path: Path,\n output_dir: Path,\n config: Dict[str, Any],\n verbose: bool = False,\n generate_html: bool = False,\n commit_id: str = None,\n ):\n \"\"\"\n Initialize the CLI documentation generator.\n \n Args:\n repo_path: Repository path\n output_dir: Output directory\n config: LLM configuration\n verbose: Enable verbose output\n generate_html: Whether to generate HTML viewer\n commit_id: Git commit SHA for incremental update tracking\n \"\"\"\n self.repo_path = repo_path\n self.output_dir = output_dir\n self.config = config\n self.verbose = verbose\n self.generate_html = generate_html\n self.commit_id = commit_id\n self.progress_tracker = ProgressTracker(total_stages=5, verbose=verbose)\n self.job = DocumentationJob()\n \n # Setup job metadata\n self.job.repository_path = str(repo_path)\n self.job.repository_name = repo_path.name\n self.job.output_directory = str(output_dir)\n self.job.llm_config = LLMConfig(\n main_model=config.get('main_model', ''),\n cluster_model=config.get('cluster_model', ''),\n base_url=config.get('base_url', '')\n )\n \n # Configure backend logging\n self._configure_backend_logging()\n \n def _configure_backend_logging(self):\n \"\"\"Configure backend logger for CLI use with colored output.\"\"\"\n from codewiki.src.be.dependency_analyzer.utils.logging_config import ColoredFormatter\n \n # Get backend logger (parent of all backend modules)\n backend_logger = logging.getLogger('codewiki.src.be')\n \n # Remove existing handlers to avoid duplicates\n backend_logger.handlers.clear()\n \n if self.verbose:\n # In verbose mode, show INFO and above\n backend_logger.setLevel(logging.INFO)\n \n # Create console handler with formatting\n console_handler = logging.StreamHandler(sys.stdout)\n console_handler.setLevel(logging.INFO)\n \n # Use colored formatter for better readability\n colored_formatter = ColoredFormatter()\n console_handler.setFormatter(colored_formatter)\n \n # Add handler to logger\n backend_logger.addHandler(console_handler)\n else:\n # In non-verbose mode, suppress backend logs (use WARNING level to hide INFO/DEBUG)\n backend_logger.setLevel(logging.WARNING)\n \n # Create console handler for warnings and errors only\n console_handler = logging.StreamHandler(sys.stderr)\n console_handler.setLevel(logging.WARNING)\n \n # Use colored formatter even for warnings/errors\n colored_formatter = ColoredFormatter()\n console_handler.setFormatter(colored_formatter)\n \n backend_logger.addHandler(console_handler)\n \n # Prevent propagation to root logger to avoid duplicate messages\n backend_logger.propagate = False\n \n def generate(self) -> DocumentationJob:\n \"\"\"\n Generate documentation with progress tracking.\n \n Returns:\n Completed DocumentationJob\n \n Raises:\n APIError: If LLM API call fails\n \"\"\"\n self.job.start()\n start_time = time.time()\n \n try:\n # Set CLI context for backend\n set_cli_context(True)\n \n # Create backend config with CLI settings\n backend_config = BackendConfig.from_cli(\n repo_path=str(self.repo_path),\n output_dir=str(self.output_dir),\n llm_base_url=self.config.get('base_url'),\n llm_api_key=self.config.get('api_key'),\n main_model=self.config.get('main_model'),\n cluster_model=self.config.get('cluster_model'),\n fallback_model=self.config.get('fallback_model'),\n provider=self.config.get('provider', 'openai-compatible'),\n aws_region=self.config.get('aws_region', 'us-east-1'),\n max_tokens=self.config.get('max_tokens', 32768),\n max_token_per_module=self.config.get('max_token_per_module', 36369),\n max_token_per_leaf_module=self.config.get('max_token_per_leaf_module', 16000),\n max_depth=self.config.get('max_depth', 2),\n agent_instructions=self.config.get('agent_instructions'),\n use_gitignore=self.config.get('use_gitignore', True),\n prompt_caching=self.config.get('prompt_caching', True),\n )\n \n # Run backend documentation generation\n asyncio.run(self._run_backend_generation(backend_config))\n \n # Stage 4: HTML Generation (optional)\n if self.generate_html:\n self._run_html_generation()\n \n # Stage 5: Finalization (metadata already created by backend)\n self._finalize_job()\n \n # Complete job\n generation_time = time.time() - start_time\n self.job.complete()\n \n return self.job\n \n except APIError as e:\n self.job.fail(str(e))\n raise\n except Exception as e:\n self.job.fail(str(e))\n raise\n \n async def _run_backend_generation(self, backend_config: BackendConfig):\n \"\"\"Run the backend documentation generation with progress tracking.\"\"\"\n \n # Stage 1: Dependency Analysis\n self.progress_tracker.start_stage(1, \"Dependency Analysis\")\n if self.verbose:\n self.progress_tracker.update_stage(0.2, \"Initializing dependency analyzer...\")\n \n # Create documentation generator\n doc_generator = DocumentationGenerator(backend_config, commit_id=self.commit_id)\n \n if self.verbose:\n self.progress_tracker.update_stage(0.5, \"Parsing source files...\")\n \n # Build dependency graph\n try:\n components, leaf_nodes = doc_generator.graph_builder.build_dependency_graph()\n self.job.statistics.total_files_analyzed = len(components)\n self.job.statistics.leaf_nodes = len(leaf_nodes)\n\n if self.verbose:\n self.progress_tracker.update_stage(0.8, f\"Analyzed {len(components)} files, found {len(leaf_nodes)} leaf nodes\")\n # Log individual files analyzed\n for comp_name in sorted(components.keys())[:20]:\n self.progress_tracker.update_stage(0.9, f\" File: {comp_name}\")\n if len(components) > 20:\n self.progress_tracker.update_stage(0.9, f\" ... and {len(components) - 20} more files\")\n except Exception as e:\n raise APIError(f\"Dependency analysis failed: {e}\")\n \n self.progress_tracker.complete_stage()\n \n # Stage 2: Module Clustering\n self.progress_tracker.start_stage(2, \"Module Clustering\")\n if self.verbose:\n self.progress_tracker.update_stage(0.5, \"Clustering modules with LLM...\")\n \n # Import clustering function\n from codewiki.src.be.cluster_modules import (\n cluster_modules,\n get_clustering_input_token_count,\n )\n from codewiki.src.utils import file_manager\n from codewiki.src.config import FIRST_MODULE_TREE_FILENAME, MODULE_TREE_FILENAME\n\n working_dir = str(self.output_dir.absolute())\n file_manager.ensure_directory(working_dir)\n first_module_tree_path = os.path.join(working_dir, FIRST_MODULE_TREE_FILENAME)\n module_tree_path = os.path.join(working_dir, MODULE_TREE_FILENAME)\n\n try:\n if os.path.exists(first_module_tree_path):\n module_tree = file_manager.load_json(first_module_tree_path)\n if self.verbose:\n self.progress_tracker.update_stage(0.5, \"Loaded cached module tree\")\n else:\n if self.verbose:\n clustering_tokens = get_clustering_input_token_count(\n leaf_nodes, components\n )\n self.progress_tracker.update_stage(\n 0.3,\n (\n f\"Preparing {len(leaf_nodes)} leaf nodes for clustering \"\n f\"({clustering_tokens} tokens, threshold \"\n f\"{backend_config.max_token_per_module})\"\n ),\n )\n if clustering_tokens <= backend_config.max_token_per_module:\n self.progress_tracker.update_stage(\n 0.4,\n \"Skipping LLM clustering; selected leaf nodes fit within the module token threshold\",\n )\n else:\n self.progress_tracker.update_stage(\n 0.4,\n \"Clustering modules with LLM...\",\n )\n cluster_model = backend_config.cluster_model or None\n module_tree = cluster_modules(\n leaf_nodes,\n components,\n backend_config,\n completer=lambda p: doc_generator.backend.complete(p, model=cluster_model),\n )\n # Only freshly clustered trees are deduped: renaming a cached\n # key whose .md already exists would orphan the doc.\n from codewiki.src.be.module_naming import dedupe_module_tree_names\n module_tree = dedupe_module_tree_names(module_tree)\n file_manager.save_json(module_tree, first_module_tree_path)\n\n file_manager.save_json(module_tree, module_tree_path)\n self.job.module_count = len(module_tree)\n\n if self.verbose:\n if len(module_tree) == 0:\n self.progress_tracker.update_stage(\n 1.0,\n \"Created 0 modules; continuing in whole-repository documentation mode\",\n )\n else:\n self.progress_tracker.update_stage(\n 1.0,\n f\"Created {len(module_tree)} modules\",\n )\n for mod_name in sorted(module_tree.keys()):\n file_count = len(module_tree[mod_name]) if isinstance(module_tree[mod_name], list) else \"?\"\n self.progress_tracker.update_stage(1.0, f\" Module: {mod_name} ({file_count} files)\")\n except Exception as e:\n raise APIError(f\"Module clustering failed: {e}\")\n \n self.progress_tracker.complete_stage()\n \n # Stage 3: Documentation Generation\n self.progress_tracker.start_stage(3, \"Documentation Generation\")\n if self.verbose:\n self.progress_tracker.update_stage(0.1, \"Generating module documentation...\")\n \n try:\n if self.verbose:\n self.progress_tracker.update_stage(0.2, f\"Generating documentation for {self.job.module_count} modules...\")\n\n # Run the actual documentation generation\n await doc_generator.generate_module_documentation(components, leaf_nodes)\n\n if self.verbose:\n self.progress_tracker.update_stage(0.9, \"Creating repository overview...\")\n \n # Create metadata\n doc_generator.create_documentation_metadata(working_dir, components, len(leaf_nodes))\n \n # Collect generated files\n for file_path in os.listdir(working_dir):\n if file_path.endswith('.md') or file_path.endswith('.json'):\n self.job.files_generated.append(file_path)\n\n except Exception as e:\n raise APIError(f\"Documentation generation failed: {e}\")\n\n # Reconcile the final module tree against the docs on disk so name\n # collisions or failed sub-agents can't pass as success (issue #76).\n # Outside the try/except above so it is not reported as an API error.\n missing_docs = doc_generator.validate_generated_docs(working_dir)\n if missing_docs:\n raise IncompleteGenerationError(\n \"Documentation generation finished but these module docs are missing: \"\n + \", \".join(f\"{name}.md\" for name in missing_docs),\n missing_modules=missing_docs,\n )\n\n self.progress_tracker.complete_stage()\n \n def _run_html_generation(self):\n \"\"\"Run HTML generation stage.\"\"\"\n self.progress_tracker.start_stage(4, \"HTML Generation\")\n \n from codewiki.cli.html_generator import HTMLGenerator\n \n # Generate HTML\n html_generator = HTMLGenerator()\n \n if self.verbose:\n self.progress_tracker.update_stage(0.3, \"Loading module tree and metadata...\")\n \n repo_info = html_generator.detect_repository_info(self.repo_path)\n \n # Generate HTML with auto-loading of module_tree and metadata from docs_dir\n output_path = self.output_dir / \"index.html\"\n html_generator.generate(\n output_path=output_path,\n title=repo_info['name'],\n repository_url=repo_info['url'],\n github_pages_url=repo_info['github_pages_url'],\n docs_dir=self.output_dir # Auto-load module_tree and metadata from here\n )\n \n self.job.files_generated.append(\"index.html\")\n \n if self.verbose:\n self.progress_tracker.update_stage(1.0, \"Generated index.html\")\n \n self.progress_tracker.complete_stage()\n \n def _finalize_job(self):\n \"\"\"Finalize the job (metadata already created by backend).\"\"\"\n # Just verify metadata exists\n metadata_path = self.output_dir / \"metadata.json\"\n if not metadata_path.exists():\n # Create our own if backend didn't\n with open(metadata_path, 'w') as f:\n f.write(self.job.to_json())", - "start_line": 26, - "end_line": 367, - "has_docstring": true, - "docstring": "CLI adapter for documentation generation with progress reporting.\n\nThis class wraps the backend documentation generator and adds\nCLI-specific features like progress tracking and error handling.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class CLIDocumentationGenerator", - "component_id": "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator", - "language": null, - "qualified_name": null - }, - "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator.__init__": { - "id": "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator.__init__", - "name": "CLIDocumentationGenerator.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/adapters/doc_generator.py", - "relative_path": "codewiki/cli/adapters/doc_generator.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/cli/models/job.py::LLMConfig", - "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator._configure_backend_logging", - "codewiki/cli/utils/progress.py::ProgressTracker", - "codewiki/cli/models/job.py::DocumentationJob" - ], - "source_code": " def __init__(\n self,\n repo_path: Path,\n output_dir: Path,\n config: Dict[str, Any],\n verbose: bool = False,\n generate_html: bool = False,\n commit_id: str = None,\n ):\n \"\"\"\n Initialize the CLI documentation generator.\n \n Args:\n repo_path: Repository path\n output_dir: Output directory\n config: LLM configuration\n verbose: Enable verbose output\n generate_html: Whether to generate HTML viewer\n commit_id: Git commit SHA for incremental update tracking\n \"\"\"\n self.repo_path = repo_path\n self.output_dir = output_dir\n self.config = config\n self.verbose = verbose\n self.generate_html = generate_html\n self.commit_id = commit_id\n self.progress_tracker = ProgressTracker(total_stages=5, verbose=verbose)\n self.job = DocumentationJob()\n \n # Setup job metadata\n self.job.repository_path = str(repo_path)\n self.job.repository_name = repo_path.name\n self.job.output_directory = str(output_dir)\n self.job.llm_config = LLMConfig(\n main_model=config.get('main_model', ''),\n cluster_model=config.get('cluster_model', ''),\n base_url=config.get('base_url', '')\n )\n \n # Configure backend logging\n self._configure_backend_logging()", - "start_line": 34, - "end_line": 74, - "has_docstring": true, - "docstring": "Initialize the CLI documentation generator.\n\nArgs:\n repo_path: Repository path\n output_dir: Output directory\n config: LLM configuration\n verbose: Enable verbose output\n generate_html: Whether to generate HTML viewer\n commit_id: Git commit SHA for incremental update tracking", - "parameters": [ - "self", - "repo_path", - "output_dir", - "config", - "verbose", - "generate_html", - "commit_id" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CLIDocumentationGenerator", - "display_name": "method CLIDocumentationGenerator.__init__", - "component_id": "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator._configure_backend_logging": { - "id": "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator._configure_backend_logging", - "name": "CLIDocumentationGenerator._configure_backend_logging", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/adapters/doc_generator.py", - "relative_path": "codewiki/cli/adapters/doc_generator.py", - "depends_on": [ - "codewiki/cli/config_manager.py::ConfigManager.clear", - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter" - ], - "source_code": " def _configure_backend_logging(self):\n \"\"\"Configure backend logger for CLI use with colored output.\"\"\"\n from codewiki.src.be.dependency_analyzer.utils.logging_config import ColoredFormatter\n \n # Get backend logger (parent of all backend modules)\n backend_logger = logging.getLogger('codewiki.src.be')\n \n # Remove existing handlers to avoid duplicates\n backend_logger.handlers.clear()\n \n if self.verbose:\n # In verbose mode, show INFO and above\n backend_logger.setLevel(logging.INFO)\n \n # Create console handler with formatting\n console_handler = logging.StreamHandler(sys.stdout)\n console_handler.setLevel(logging.INFO)\n \n # Use colored formatter for better readability\n colored_formatter = ColoredFormatter()\n console_handler.setFormatter(colored_formatter)\n \n # Add handler to logger\n backend_logger.addHandler(console_handler)\n else:\n # In non-verbose mode, suppress backend logs (use WARNING level to hide INFO/DEBUG)\n backend_logger.setLevel(logging.WARNING)\n \n # Create console handler for warnings and errors only\n console_handler = logging.StreamHandler(sys.stderr)\n console_handler.setLevel(logging.WARNING)\n \n # Use colored formatter even for warnings/errors\n colored_formatter = ColoredFormatter()\n console_handler.setFormatter(colored_formatter)\n \n backend_logger.addHandler(console_handler)\n \n # Prevent propagation to root logger to avoid duplicate messages\n backend_logger.propagate = False", - "start_line": 76, - "end_line": 115, - "has_docstring": true, - "docstring": "Configure backend logger for CLI use with colored output.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CLIDocumentationGenerator", - "display_name": "method CLIDocumentationGenerator._configure_backend_logging", - "component_id": "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator._configure_backend_logging", - "language": null, - "qualified_name": null - }, - "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator.generate": { - "id": "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator.generate", - "name": "CLIDocumentationGenerator.generate", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/adapters/doc_generator.py", - "relative_path": "codewiki/cli/adapters/doc_generator.py", - "depends_on": [ - "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator._run_html_generation", - "codewiki/cli/models/job.py::DocumentationJob.fail", - "codewiki/src/config.py::Config.from_cli", - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.run", - "codewiki/src/config.py::set_cli_context", - "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator._finalize_job", - "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator._run_backend_generation" - ], - "source_code": " def generate(self) -> DocumentationJob:\n \"\"\"\n Generate documentation with progress tracking.\n \n Returns:\n Completed DocumentationJob\n \n Raises:\n APIError: If LLM API call fails\n \"\"\"\n self.job.start()\n start_time = time.time()\n \n try:\n # Set CLI context for backend\n set_cli_context(True)\n \n # Create backend config with CLI settings\n backend_config = BackendConfig.from_cli(\n repo_path=str(self.repo_path),\n output_dir=str(self.output_dir),\n llm_base_url=self.config.get('base_url'),\n llm_api_key=self.config.get('api_key'),\n main_model=self.config.get('main_model'),\n cluster_model=self.config.get('cluster_model'),\n fallback_model=self.config.get('fallback_model'),\n provider=self.config.get('provider', 'openai-compatible'),\n aws_region=self.config.get('aws_region', 'us-east-1'),\n max_tokens=self.config.get('max_tokens', 32768),\n max_token_per_module=self.config.get('max_token_per_module', 36369),\n max_token_per_leaf_module=self.config.get('max_token_per_leaf_module', 16000),\n max_depth=self.config.get('max_depth', 2),\n agent_instructions=self.config.get('agent_instructions'),\n use_gitignore=self.config.get('use_gitignore', True),\n prompt_caching=self.config.get('prompt_caching', True),\n )\n \n # Run backend documentation generation\n asyncio.run(self._run_backend_generation(backend_config))\n \n # Stage 4: HTML Generation (optional)\n if self.generate_html:\n self._run_html_generation()\n \n # Stage 5: Finalization (metadata already created by backend)\n self._finalize_job()\n \n # Complete job\n generation_time = time.time() - start_time\n self.job.complete()\n \n return self.job\n \n except APIError as e:\n self.job.fail(str(e))\n raise\n except Exception as e:\n self.job.fail(str(e))\n raise", - "start_line": 117, - "end_line": 175, - "has_docstring": true, - "docstring": "Generate documentation with progress tracking.\n\nReturns:\n Completed DocumentationJob\n \nRaises:\n APIError: If LLM API call fails", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CLIDocumentationGenerator", - "display_name": "method CLIDocumentationGenerator.generate", - "component_id": "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator.generate", - "language": null, - "qualified_name": null - }, - "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator._run_backend_generation": { - "id": "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator._run_backend_generation", - "name": "CLIDocumentationGenerator._run_backend_generation", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/adapters/doc_generator.py", - "relative_path": "codewiki/cli/adapters/doc_generator.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py::DependencyGraphBuilder.build_dependency_graph", - "codewiki/src/be/module_naming.py::dedupe_module_tree_names", - "codewiki/src/be/cluster_modules.py::cluster_modules", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.generate_module_documentation", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator", - "codewiki/cli/utils/errors.py::APIError", - "codewiki/src/utils.py::FileManager.load_json", - "codewiki/src/be/cluster_modules.py::get_clustering_input_token_count", - "codewiki/src/utils.py::FileManager.save_json", - "codewiki/cli/utils/progress.py::ProgressTracker.update_stage", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.create_documentation_metadata", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.validate_generated_docs", - "codewiki/cli/utils/errors.py::IncompleteGenerationError", - "codewiki/cli/utils/progress.py::ProgressTracker.complete_stage", - "codewiki/cli/utils/progress.py::ProgressTracker.start_stage" - ], - "source_code": " async def _run_backend_generation(self, backend_config: BackendConfig):\n \"\"\"Run the backend documentation generation with progress tracking.\"\"\"\n \n # Stage 1: Dependency Analysis\n self.progress_tracker.start_stage(1, \"Dependency Analysis\")\n if self.verbose:\n self.progress_tracker.update_stage(0.2, \"Initializing dependency analyzer...\")\n \n # Create documentation generator\n doc_generator = DocumentationGenerator(backend_config, commit_id=self.commit_id)\n \n if self.verbose:\n self.progress_tracker.update_stage(0.5, \"Parsing source files...\")\n \n # Build dependency graph\n try:\n components, leaf_nodes = doc_generator.graph_builder.build_dependency_graph()\n self.job.statistics.total_files_analyzed = len(components)\n self.job.statistics.leaf_nodes = len(leaf_nodes)\n\n if self.verbose:\n self.progress_tracker.update_stage(0.8, f\"Analyzed {len(components)} files, found {len(leaf_nodes)} leaf nodes\")\n # Log individual files analyzed\n for comp_name in sorted(components.keys())[:20]:\n self.progress_tracker.update_stage(0.9, f\" File: {comp_name}\")\n if len(components) > 20:\n self.progress_tracker.update_stage(0.9, f\" ... and {len(components) - 20} more files\")\n except Exception as e:\n raise APIError(f\"Dependency analysis failed: {e}\")\n \n self.progress_tracker.complete_stage()\n \n # Stage 2: Module Clustering\n self.progress_tracker.start_stage(2, \"Module Clustering\")\n if self.verbose:\n self.progress_tracker.update_stage(0.5, \"Clustering modules with LLM...\")\n \n # Import clustering function\n from codewiki.src.be.cluster_modules import (\n cluster_modules,\n get_clustering_input_token_count,\n )\n from codewiki.src.utils import file_manager\n from codewiki.src.config import FIRST_MODULE_TREE_FILENAME, MODULE_TREE_FILENAME\n\n working_dir = str(self.output_dir.absolute())\n file_manager.ensure_directory(working_dir)\n first_module_tree_path = os.path.join(working_dir, FIRST_MODULE_TREE_FILENAME)\n module_tree_path = os.path.join(working_dir, MODULE_TREE_FILENAME)\n\n try:\n if os.path.exists(first_module_tree_path):\n module_tree = file_manager.load_json(first_module_tree_path)\n if self.verbose:\n self.progress_tracker.update_stage(0.5, \"Loaded cached module tree\")\n else:\n if self.verbose:\n clustering_tokens = get_clustering_input_token_count(\n leaf_nodes, components\n )\n self.progress_tracker.update_stage(\n 0.3,\n (\n f\"Preparing {len(leaf_nodes)} leaf nodes for clustering \"\n f\"({clustering_tokens} tokens, threshold \"\n f\"{backend_config.max_token_per_module})\"\n ),\n )\n if clustering_tokens <= backend_config.max_token_per_module:\n self.progress_tracker.update_stage(\n 0.4,\n \"Skipping LLM clustering; selected leaf nodes fit within the module token threshold\",\n )\n else:\n self.progress_tracker.update_stage(\n 0.4,\n \"Clustering modules with LLM...\",\n )\n cluster_model = backend_config.cluster_model or None\n module_tree = cluster_modules(\n leaf_nodes,\n components,\n backend_config,\n completer=lambda p: doc_generator.backend.complete(p, model=cluster_model),\n )\n # Only freshly clustered trees are deduped: renaming a cached\n # key whose .md already exists would orphan the doc.\n from codewiki.src.be.module_naming import dedupe_module_tree_names\n module_tree = dedupe_module_tree_names(module_tree)\n file_manager.save_json(module_tree, first_module_tree_path)\n\n file_manager.save_json(module_tree, module_tree_path)\n self.job.module_count = len(module_tree)\n\n if self.verbose:\n if len(module_tree) == 0:\n self.progress_tracker.update_stage(\n 1.0,\n \"Created 0 modules; continuing in whole-repository documentation mode\",\n )\n else:\n self.progress_tracker.update_stage(\n 1.0,\n f\"Created {len(module_tree)} modules\",\n )\n for mod_name in sorted(module_tree.keys()):\n file_count = len(module_tree[mod_name]) if isinstance(module_tree[mod_name], list) else \"?\"\n self.progress_tracker.update_stage(1.0, f\" Module: {mod_name} ({file_count} files)\")\n except Exception as e:\n raise APIError(f\"Module clustering failed: {e}\")\n \n self.progress_tracker.complete_stage()\n \n # Stage 3: Documentation Generation\n self.progress_tracker.start_stage(3, \"Documentation Generation\")\n if self.verbose:\n self.progress_tracker.update_stage(0.1, \"Generating module documentation...\")\n \n try:\n if self.verbose:\n self.progress_tracker.update_stage(0.2, f\"Generating documentation for {self.job.module_count} modules...\")\n\n # Run the actual documentation generation\n await doc_generator.generate_module_documentation(components, leaf_nodes)\n\n if self.verbose:\n self.progress_tracker.update_stage(0.9, \"Creating repository overview...\")\n \n # Create metadata\n doc_generator.create_documentation_metadata(working_dir, components, len(leaf_nodes))\n \n # Collect generated files\n for file_path in os.listdir(working_dir):\n if file_path.endswith('.md') or file_path.endswith('.json'):\n self.job.files_generated.append(file_path)\n\n except Exception as e:\n raise APIError(f\"Documentation generation failed: {e}\")\n\n # Reconcile the final module tree against the docs on disk so name\n # collisions or failed sub-agents can't pass as success (issue #76).\n # Outside the try/except above so it is not reported as an API error.\n missing_docs = doc_generator.validate_generated_docs(working_dir)\n if missing_docs:\n raise IncompleteGenerationError(\n \"Documentation generation finished but these module docs are missing: \"\n + \", \".join(f\"{name}.md\" for name in missing_docs),\n missing_modules=missing_docs,\n )\n\n self.progress_tracker.complete_stage()", - "start_line": 177, - "end_line": 327, - "has_docstring": true, - "docstring": "Run the backend documentation generation with progress tracking.", - "parameters": [ - "self", - "backend_config" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CLIDocumentationGenerator", - "display_name": "method CLIDocumentationGenerator._run_backend_generation", - "component_id": "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator._run_backend_generation", - "language": null, - "qualified_name": null - }, - "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator._run_html_generation": { - "id": "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator._run_html_generation", - "name": "CLIDocumentationGenerator._run_html_generation", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/adapters/doc_generator.py", - "relative_path": "codewiki/cli/adapters/doc_generator.py", - "depends_on": [ - "codewiki/cli/html_generator.py::HTMLGenerator.detect_repository_info", - "codewiki/cli/html_generator.py::HTMLGenerator", - "codewiki/cli/utils/progress.py::ProgressTracker.update_stage", - "codewiki/cli/html_generator.py::HTMLGenerator.generate", - "codewiki/cli/utils/progress.py::ProgressTracker.complete_stage", - "codewiki/cli/utils/progress.py::ProgressTracker.start_stage" - ], - "source_code": " def _run_html_generation(self):\n \"\"\"Run HTML generation stage.\"\"\"\n self.progress_tracker.start_stage(4, \"HTML Generation\")\n \n from codewiki.cli.html_generator import HTMLGenerator\n \n # Generate HTML\n html_generator = HTMLGenerator()\n \n if self.verbose:\n self.progress_tracker.update_stage(0.3, \"Loading module tree and metadata...\")\n \n repo_info = html_generator.detect_repository_info(self.repo_path)\n \n # Generate HTML with auto-loading of module_tree and metadata from docs_dir\n output_path = self.output_dir / \"index.html\"\n html_generator.generate(\n output_path=output_path,\n title=repo_info['name'],\n repository_url=repo_info['url'],\n github_pages_url=repo_info['github_pages_url'],\n docs_dir=self.output_dir # Auto-load module_tree and metadata from here\n )\n \n self.job.files_generated.append(\"index.html\")\n \n if self.verbose:\n self.progress_tracker.update_stage(1.0, \"Generated index.html\")\n \n self.progress_tracker.complete_stage()", - "start_line": 329, - "end_line": 358, - "has_docstring": true, - "docstring": "Run HTML generation stage.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CLIDocumentationGenerator", - "display_name": "method CLIDocumentationGenerator._run_html_generation", - "component_id": "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator._run_html_generation", - "language": null, - "qualified_name": null - }, - "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator._finalize_job": { - "id": "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator._finalize_job", - "name": "CLIDocumentationGenerator._finalize_job", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/adapters/doc_generator.py", - "relative_path": "codewiki/cli/adapters/doc_generator.py", - "depends_on": [ - "codewiki/cli/models/job.py::DocumentationJob.to_json" - ], - "source_code": " def _finalize_job(self):\n \"\"\"Finalize the job (metadata already created by backend).\"\"\"\n # Just verify metadata exists\n metadata_path = self.output_dir / \"metadata.json\"\n if not metadata_path.exists():\n # Create our own if backend didn't\n with open(metadata_path, 'w') as f:\n f.write(self.job.to_json())", - "start_line": 360, - "end_line": 367, - "has_docstring": true, - "docstring": "Finalize the job (metadata already created by backend).", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CLIDocumentationGenerator", - "display_name": "method CLIDocumentationGenerator._finalize_job", - "component_id": "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator._finalize_job", - "language": null, - "qualified_name": null - }, - "codewiki/cli/commands/config.py::parse_patterns": { - "id": "codewiki/cli/commands/config.py::parse_patterns", - "name": "parse_patterns", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/commands/config.py", - "relative_path": "codewiki/cli/commands/config.py", - "depends_on": [], - "source_code": "def parse_patterns(patterns_str: str) -> List[str]:\n \"\"\"Parse comma-separated patterns into a list.\"\"\"\n if not patterns_str:\n return []\n return [p.strip() for p in patterns_str.split(',') if p.strip()]", - "start_line": 28, - "end_line": 32, - "has_docstring": true, - "docstring": "Parse comma-separated patterns into a list.", - "parameters": [ - "patterns_str" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function parse_patterns", - "component_id": "codewiki/cli/commands/config.py::parse_patterns", - "language": null, - "qualified_name": null - }, - "codewiki/cli/commands/config.py::config_group": { - "id": "codewiki/cli/commands/config.py::config_group", - "name": "config_group", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/commands/config.py", - "relative_path": "codewiki/cli/commands/config.py", - "depends_on": [], - "source_code": "def config_group():\n \"\"\"Manage CodeWiki configuration (API credentials and settings).\"\"\"\n pass", - "start_line": 36, - "end_line": 38, - "has_docstring": true, - "docstring": "Manage CodeWiki configuration (API credentials and settings).", - "parameters": [], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function config_group", - "component_id": "codewiki/cli/commands/config.py::config_group", - "language": null, - "qualified_name": null - }, - "codewiki/cli/commands/config.py::config_set": { - "id": "codewiki/cli/commands/config.py::config_set", - "name": "config_set", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/commands/config.py", - "relative_path": "codewiki/cli/commands/config.py", - "depends_on": [ - "codewiki/cli/utils/errors.py::ConfigurationError", - "codewiki/cli/config_manager.py::ConfigManager", - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/cli/utils/validation.py::validate_url", - "codewiki/cli/utils/errors.py::handle_error", - "codewiki/cli/utils/validation.py::validate_api_key", - "codewiki/cli/config_manager.py::ConfigManager.save", - "codewiki/cli/utils/validation.py::is_top_tier_model", - "codewiki/cli/utils/validation.py::validate_model_name", - "codewiki/cli/config_manager.py::ConfigManager.load" - ], - "source_code": "def config_set(\n api_key: Optional[str],\n base_url: Optional[str],\n main_model: Optional[str],\n cluster_model: Optional[str],\n fallback_model: Optional[str],\n max_tokens: Optional[int],\n max_token_per_module: Optional[int],\n max_token_per_leaf_module: Optional[int],\n max_depth: Optional[int],\n provider: Optional[str] = None,\n aws_region: Optional[str] = None,\n api_version: Optional[str] = None,\n azure_deployment: Optional[str] = None,\n use_gitignore: Optional[bool] = None,\n prompt_caching: Optional[bool] = None,\n):\n \"\"\"\n Set configuration values for CodeWiki.\n \n API keys are stored securely in your system keychain:\n β€’ macOS: Keychain Access\n β€’ Windows: Credential Manager \n β€’ Linux: Secret Service (GNOME Keyring, KWallet)\n \n Examples:\n\n \\b\n # Set all configuration (API mode)\n $ codewiki config set --api-key sk-abc123 --base-url https://api.anthropic.com \\\\\n --main-model claude-sonnet-4 --cluster-model claude-sonnet-4 --fallback-model glm-4p5\n\n \\b\n # Atlas Cloud (OpenAI-compatible) β€” base URL auto-set,\n # API key read from ATLASCLOUD_API_KEY if --api-key is omitted\n $ codewiki config set --provider atlas-cloud --main-model --cluster-model \n\n \\b\n # Subscription mode (Claude Code) β€” no API key needed,\n # authenticate via 'claude login' on the host first\n $ codewiki config set --provider claude-code --main-model claude-sonnet-4-5\n\n \\b\n # Subscription mode (Codex)\n $ codewiki config set --provider codex --main-model gpt-5.2-codex\n\n \\b\n # Update only API key\n $ codewiki config set --api-key sk-new-key\n\n \\b\n # Set max tokens for LLM response\n $ codewiki config set --max-tokens 16384\n\n \\b\n # Set all max token settings\n $ codewiki config set --max-tokens 32768 --max-token-per-module 40000 --max-token-per-leaf-module 20000\n\n \\b\n # Set max depth for hierarchical decomposition\n $ codewiki config set --max-depth 3\n\n \\b\n # Persistently disable Git ignore filtering\n $ codewiki config set --no-gitignore\n \"\"\"\n try:\n # Check if at least one option is provided\n if not any([api_key, base_url, main_model, cluster_model, fallback_model, max_tokens, max_token_per_module, max_token_per_leaf_module, max_depth, provider, aws_region, api_version, azure_deployment, use_gitignore is not None, prompt_caching is not None]):\n click.echo(\"No options provided. Use --help for usage information.\")\n sys.exit(EXIT_CONFIG_ERROR)\n\n # Atlas Cloud convenience defaults: it's an OpenAI-compatible endpoint, so\n # auto-fill its base URL and pull the API key from ATLASCLOUD_API_KEY when the\n # user does not pass them explicitly.\n if provider and provider.lower() == \"atlas-cloud\":\n from codewiki.src.config import ATLAS_CLOUD_BASE_URL\n if not base_url:\n base_url = ATLAS_CLOUD_BASE_URL\n if not api_key:\n api_key = os.getenv(\"ATLASCLOUD_API_KEY\")\n\n # Validate inputs before saving\n validated_data = {}\n \n if api_key:\n validated_data['api_key'] = validate_api_key(api_key)\n \n if base_url:\n validated_data['base_url'] = validate_url(base_url)\n \n if main_model:\n validated_data['main_model'] = validate_model_name(main_model)\n \n if cluster_model:\n validated_data['cluster_model'] = validate_model_name(cluster_model)\n \n if fallback_model:\n validated_data['fallback_model'] = validate_model_name(fallback_model)\n \n if max_tokens is not None:\n if max_tokens < 1:\n raise ConfigurationError(\"max_tokens must be a positive integer\")\n validated_data['max_tokens'] = max_tokens\n \n if max_token_per_module is not None:\n if max_token_per_module < 1:\n raise ConfigurationError(\"max_token_per_module must be a positive integer\")\n validated_data['max_token_per_module'] = max_token_per_module\n \n if max_token_per_leaf_module is not None:\n if max_token_per_leaf_module < 1:\n raise ConfigurationError(\"max_token_per_leaf_module must be a positive integer\")\n validated_data['max_token_per_leaf_module'] = max_token_per_leaf_module\n \n if max_depth is not None:\n if max_depth < 1:\n raise ConfigurationError(\"max_depth must be a positive integer\")\n validated_data['max_depth'] = max_depth\n\n if provider is not None:\n validated_data['provider'] = provider\n\n if aws_region is not None:\n validated_data['aws_region'] = aws_region\n\n if api_version is not None:\n validated_data['api_version'] = api_version\n\n if azure_deployment is not None:\n validated_data['azure_deployment'] = azure_deployment\n\n if use_gitignore is not None:\n validated_data['use_gitignore'] = use_gitignore\n\n if prompt_caching is not None:\n validated_data['prompt_caching'] = prompt_caching\n\n # Create config manager and save\n manager = ConfigManager()\n manager.load() # Load existing config if present\n\n manager.save(\n api_key=validated_data.get('api_key'),\n base_url=validated_data.get('base_url'),\n main_model=validated_data.get('main_model'),\n cluster_model=validated_data.get('cluster_model'),\n fallback_model=validated_data.get('fallback_model'),\n max_tokens=validated_data.get('max_tokens'),\n max_token_per_module=validated_data.get('max_token_per_module'),\n max_token_per_leaf_module=validated_data.get('max_token_per_leaf_module'),\n max_depth=validated_data.get('max_depth'),\n provider=validated_data.get('provider'),\n aws_region=validated_data.get('aws_region'),\n api_version=validated_data.get('api_version'),\n azure_deployment=validated_data.get('azure_deployment'),\n use_gitignore=validated_data.get('use_gitignore'),\n prompt_caching=validated_data.get('prompt_caching'),\n )\n \n # Display success messages\n click.echo()\n if api_key:\n if manager.keyring_available:\n click.secho(\"βœ“ API key saved to system keychain\", fg=\"green\")\n else:\n click.secho(\n \"⚠️ System keychain unavailable. API key stored in encrypted file.\",\n fg=\"yellow\"\n )\n \n if base_url:\n click.secho(f\"βœ“ Base URL: {base_url}\", fg=\"green\")\n \n if main_model:\n click.secho(f\"βœ“ Main model: {main_model}\", fg=\"green\")\n \n if cluster_model:\n click.secho(f\"βœ“ Cluster model: {cluster_model}\", fg=\"green\")\n \n # Warn if not using top-tier model for clustering\n if not is_top_tier_model(cluster_model):\n click.secho(\n \"\\n⚠️ Cluster model is not a top-tier LLM. \"\n \"Documentation quality may be suboptimal.\",\n fg=\"yellow\"\n )\n click.echo(\n \" Recommended models: claude-opus, claude-sonnet-4, gpt-4, gpt-4-turbo\"\n )\n \n if fallback_model:\n click.secho(f\"βœ“ Fallback model: {fallback_model}\", fg=\"green\")\n \n if max_tokens:\n click.secho(f\"βœ“ Max tokens: {max_tokens}\", fg=\"green\")\n \n if max_token_per_module:\n click.secho(f\"βœ“ Max token per module: {max_token_per_module}\", fg=\"green\")\n \n if max_token_per_leaf_module:\n click.secho(f\"βœ“ Max token per leaf module: {max_token_per_leaf_module}\", fg=\"green\")\n \n if max_depth:\n click.secho(f\"βœ“ Max depth: {max_depth}\", fg=\"green\")\n\n if provider:\n click.secho(f\"βœ“ Provider: {provider}\", fg=\"green\")\n\n if aws_region:\n click.secho(f\"βœ“ AWS Region: {aws_region}\", fg=\"green\")\n\n if api_version:\n click.secho(f\"βœ“ API Version: {api_version}\", fg=\"green\")\n\n if azure_deployment:\n click.secho(f\"βœ“ Azure Deployment: {azure_deployment}\", fg=\"green\")\n\n if use_gitignore is not None:\n click.secho(f\"βœ“ Use gitignore: {use_gitignore}\", fg=\"green\")\n\n if prompt_caching is not None:\n click.secho(f\"βœ“ Prompt caching: {prompt_caching}\", fg=\"green\")\n\n click.echo(\"\\n\" + click.style(\"Configuration updated successfully.\", fg=\"green\", bold=True))\n \n except ConfigurationError as e:\n click.secho(f\"\\nβœ— Configuration error: {e.message}\", fg=\"red\", err=True)\n sys.exit(e.exit_code)\n except Exception as e:\n sys.exit(handle_error(e))", - "start_line": 125, - "end_line": 355, - "has_docstring": true, - "docstring": "Set configuration values for CodeWiki.\n\nAPI keys are stored securely in your system keychain:\n β€’ macOS: Keychain Access\n β€’ Windows: Credential Manager \n β€’ Linux: Secret Service (GNOME Keyring, KWallet)\n\nExamples:\n\n\b\n# Set all configuration (API mode)\n$ codewiki config set --api-key sk-abc123 --base-url https://api.anthropic.com \\\n --main-model claude-sonnet-4 --cluster-model claude-sonnet-4 --fallback-model glm-4p5\n\n\b\n# Atlas Cloud (OpenAI-compatible) β€” base URL auto-set,\n# API key read from ATLASCLOUD_API_KEY if --api-key is omitted\n$ codewiki config set --provider atlas-cloud --main-model --cluster-model \n\n\b\n# Subscription mode (Claude Code) β€” no API key needed,\n# authenticate via 'claude login' on the host first\n$ codewiki config set --provider claude-code --main-model claude-sonnet-4-5\n\n\b\n# Subscription mode (Codex)\n$ codewiki config set --provider codex --main-model gpt-5.2-codex\n\n\b\n# Update only API key\n$ codewiki config set --api-key sk-new-key\n\n\b\n# Set max tokens for LLM response\n$ codewiki config set --max-tokens 16384\n\n\b\n# Set all max token settings\n$ codewiki config set --max-tokens 32768 --max-token-per-module 40000 --max-token-per-leaf-module 20000\n\n\b\n# Set max depth for hierarchical decomposition\n$ codewiki config set --max-depth 3\n\n\b\n# Persistently disable Git ignore filtering\n$ codewiki config set --no-gitignore", - "parameters": [ - "api_key", - "base_url", - "main_model", - "cluster_model", - "fallback_model", - "max_tokens", - "max_token_per_module", - "max_token_per_leaf_module", - "max_depth", - "provider", - "aws_region", - "api_version", - "azure_deployment", - "use_gitignore", - "prompt_caching" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function config_set", - "component_id": "codewiki/cli/commands/config.py::config_set", - "language": null, - "qualified_name": null - }, - "codewiki/cli/commands/config.py::config_show": { - "id": "codewiki/cli/commands/config.py::config_show", - "name": "config_show", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/commands/config.py", - "relative_path": "codewiki/cli/commands/config.py", - "depends_on": [ - "codewiki/cli/config_manager.py::ConfigManager", - "codewiki/cli/utils/validation.py::mask_api_key", - "codewiki/src/be/backend.py::is_caw_provider", - "codewiki/cli/config_manager.py::ConfigManager.get_config", - "codewiki/cli/models/config.py::AgentInstructions.is_empty", - "codewiki/cli/utils/errors.py::handle_error", - "codewiki/cli/config_manager.py::ConfigManager.get_api_key", - "codewiki/cli/config_manager.py::ConfigManager.load" - ], - "source_code": "def config_show(output_json: bool):\n \"\"\"\n Display current configuration.\n \n API keys are masked for security (showing only first and last 4 characters).\n \n Examples:\n \n \\b\n # Display configuration\n $ codewiki config show\n \n \\b\n # Display as JSON\n $ codewiki config show --json\n \"\"\"\n try:\n manager = ConfigManager()\n \n if not manager.load():\n click.secho(\"\\nβœ— Configuration not found.\", fg=\"red\", err=True)\n click.echo(\"\\nPlease run 'codewiki config set' to configure your API credentials:\")\n click.echo(\" codewiki config set --api-key --base-url \\\\\")\n click.echo(\" --main-model --cluster-model --fallback-model \")\n click.echo(\"\\nFor more help: codewiki config set --help\")\n sys.exit(EXIT_CONFIG_ERROR)\n \n config = manager.get_config()\n api_key = manager.get_api_key()\n \n if output_json:\n # JSON output\n output = {\n \"api_key\": mask_api_key(api_key) if api_key else \"Not set\",\n \"api_key_storage\": \"keychain\" if manager.keyring_available else \"encrypted_file\",\n \"base_url\": config.base_url if config else \"\",\n \"main_model\": config.main_model if config else \"\",\n \"cluster_model\": config.cluster_model if config else \"\",\n \"fallback_model\": config.fallback_model if config else \"glm-4p5\",\n \"default_output\": config.default_output if config else \"docs\",\n \"max_tokens\": config.max_tokens if config else 32768,\n \"max_token_per_module\": config.max_token_per_module if config else 36369,\n \"max_token_per_leaf_module\": config.max_token_per_leaf_module if config else 16000,\n \"max_depth\": config.max_depth if config else 2,\n \"use_gitignore\": config.use_gitignore if config else True,\n \"prompt_caching\": config.prompt_caching if config else True,\n \"agent_instructions\": config.agent_instructions.to_dict() if config and config.agent_instructions else {},\n \"config_file\": str(manager.config_file_path)\n }\n click.echo(json.dumps(output, indent=2))\n else:\n # Human-readable output\n click.echo()\n click.secho(\"CodeWiki Configuration\", fg=\"blue\", bold=True)\n click.echo(\"━\" * 40)\n click.echo()\n \n from codewiki.src.be.backend import is_caw_provider\n caw_mode = bool(config) and is_caw_provider(config.provider)\n\n click.secho(\"Credentials\", fg=\"cyan\", bold=True)\n if caw_mode:\n cli_name = \"claude\" if config.provider == \"claude-code\" else \"codex\"\n click.secho(\n f\" Subscription mode: authenticate via '{cli_name} login' (no API key needed)\",\n fg=\"cyan\",\n )\n elif api_key:\n storage = \"system keychain\" if manager.keyring_available else \"encrypted file\"\n click.echo(f\" API Key: {mask_api_key(api_key)} (in {storage})\")\n else:\n click.secho(\" API Key: Not set\", fg=\"yellow\")\n\n click.echo()\n click.secho(\"API Settings\", fg=\"cyan\", bold=True)\n if config:\n click.echo(f\" Provider: {config.provider}\")\n click.echo(f\" Main Model: {config.main_model or 'Not set'}\")\n if not caw_mode:\n click.echo(f\" Base URL: {config.base_url or 'Not set'}\")\n click.echo(f\" Cluster Model: {config.cluster_model or 'Not set'}\")\n click.echo(f\" Fallback Model: {config.fallback_model or 'Not set'}\")\n if config.provider == \"bedrock\":\n click.echo(f\" AWS Region: {config.aws_region}\")\n elif config.provider == \"azure-openai\":\n click.echo(f\" API Version: {config.api_version}\")\n click.echo(f\" Azure Deployment: {config.azure_deployment or 'Not set'}\")\n else:\n click.secho(\" Not configured\", fg=\"yellow\")\n \n click.echo()\n click.secho(\"Output Settings\", fg=\"cyan\", bold=True)\n if config:\n click.echo(f\" Default Output: {config.default_output}\")\n \n click.echo()\n click.secho(\"Token Settings\", fg=\"cyan\", bold=True)\n if config:\n click.echo(f\" Max Tokens: {config.max_tokens}\")\n click.echo(f\" Max Token/Module: {config.max_token_per_module}\")\n click.echo(f\" Max Token/Leaf Module: {config.max_token_per_leaf_module}\")\n click.echo(f\" Prompt Caching: {config.prompt_caching}\")\n \n click.echo()\n click.secho(\"Decomposition Settings\", fg=\"cyan\", bold=True)\n if config:\n click.echo(f\" Max Depth: {config.max_depth}\")\n click.echo(f\" Use Gitignore: {config.use_gitignore}\")\n \n click.echo()\n click.secho(\"Agent Instructions\", fg=\"cyan\", bold=True)\n if config and config.agent_instructions and not config.agent_instructions.is_empty():\n agent = config.agent_instructions\n if agent.include_patterns:\n click.echo(f\" Include patterns: {', '.join(agent.include_patterns)}\")\n if agent.exclude_patterns:\n click.echo(f\" Exclude patterns: {', '.join(agent.exclude_patterns)}\")\n if agent.focus_modules:\n click.echo(f\" Focus modules: {', '.join(agent.focus_modules)}\")\n if agent.doc_type:\n click.echo(f\" Doc type: {agent.doc_type}\")\n if agent.custom_instructions:\n click.echo(f\" Custom instructions: {agent.custom_instructions[:50]}...\")\n else:\n click.secho(\" Using defaults (no custom settings)\", fg=\"yellow\")\n \n click.echo()\n click.echo(f\"Configuration file: {manager.config_file_path}\")\n click.echo()\n \n except Exception as e:\n sys.exit(handle_error(e))", - "start_line": 365, - "end_line": 496, - "has_docstring": true, - "docstring": "Display current configuration.\n\nAPI keys are masked for security (showing only first and last 4 characters).\n\nExamples:\n\n\b\n# Display configuration\n$ codewiki config show\n\n\b\n# Display as JSON\n$ codewiki config show --json", - "parameters": [ - "output_json" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function config_show", - "component_id": "codewiki/cli/commands/config.py::config_show", - "language": null, - "qualified_name": null - }, - "codewiki/cli/commands/config.py::config_validate": { - "id": "codewiki/cli/commands/config.py::config_validate", - "name": "config_validate", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/commands/config.py", - "relative_path": "codewiki/cli/commands/config.py", - "depends_on": [ - "codewiki/cli/config_manager.py::ConfigManager", - "codewiki/src/be/backend.py::is_caw_provider", - "codewiki/cli/config_manager.py::ConfigManager.get_config", - "codewiki/cli/utils/errors.py::handle_error", - "codewiki/cli/utils/validation.py::is_top_tier_model", - "codewiki/cli/config_manager.py::ConfigManager.get_api_key", - "codewiki/cli/utils/validation.py::validate_url", - "codewiki/cli/config_manager.py::ConfigManager.load" - ], - "source_code": "def config_validate(quick: bool, verbose: bool):\n \"\"\"\n Validate configuration and test LLM API connectivity.\n \n Checks:\n β€’ Configuration file exists and is valid\n β€’ API key is present\n β€’ API settings are correctly formatted\n β€’ (Optional) API connectivity test\n \n Examples:\n \n \\b\n # Full validation with API test\n $ codewiki config validate\n \n \\b\n # Quick validation (config only)\n $ codewiki config validate --quick\n \n \\b\n # Verbose output\n $ codewiki config validate --verbose\n \"\"\"\n try:\n click.echo()\n click.secho(\"Validating configuration...\", fg=\"blue\", bold=True)\n click.echo()\n \n manager = ConfigManager()\n \n # Step 1: Check config file\n if verbose:\n click.echo(\"[1/5] Checking configuration file...\")\n click.echo(f\" Path: {manager.config_file_path}\")\n \n if not manager.load():\n click.secho(\"βœ— Configuration file not found\", fg=\"red\")\n click.echo()\n click.echo(\"Error: Configuration is incomplete. Run 'codewiki config set --help' for setup instructions.\")\n sys.exit(EXIT_CONFIG_ERROR)\n \n if verbose:\n click.secho(\" βœ“ File exists\", fg=\"green\")\n click.secho(\" βœ“ Valid JSON format\", fg=\"green\")\n else:\n click.secho(\"βœ“ Configuration file exists\", fg=\"green\")\n \n # Load config early so we know the provider for the rest of the checks.\n config = manager.get_config()\n from codewiki.src.be.backend import is_caw_provider\n caw_mode = bool(config) and is_caw_provider(config.provider)\n\n # Step 2: Check API key (skipped for subscription providers)\n if verbose:\n click.echo()\n click.echo(\"[2/5] Checking API key...\")\n\n if caw_mode:\n if verbose:\n click.secho(\" βœ“ API key not required (subscription mode)\", fg=\"green\")\n else:\n click.secho(\"βœ“ API key not required (subscription mode)\", fg=\"green\")\n else:\n if verbose:\n storage = \"system keychain\" if manager.keyring_available else \"encrypted file\"\n click.echo(f\" Storage: {storage}\")\n\n api_key = manager.get_api_key()\n if not api_key:\n click.secho(\"βœ— API key missing\", fg=\"red\")\n click.echo()\n click.echo(\"Error: API key not set. Run 'codewiki config set --api-key '\")\n sys.exit(EXIT_CONFIG_ERROR)\n\n if verbose:\n click.secho(f\" βœ“ API key retrieved\", fg=\"green\")\n click.secho(f\" βœ“ Length: {len(api_key)} characters\", fg=\"green\")\n else:\n click.secho(\"βœ“ API key present (stored in keychain)\", fg=\"green\")\n\n # Step 3: Check base URL (skipped for subscription providers)\n if verbose:\n click.echo()\n click.echo(\"[3/5] Checking base URL...\")\n\n if caw_mode:\n if verbose:\n click.secho(\" βœ“ Base URL not required (subscription mode)\", fg=\"green\")\n else:\n click.secho(\"βœ“ Base URL not required (subscription mode)\", fg=\"green\")\n else:\n if verbose:\n click.echo(f\" URL: {config.base_url}\")\n\n if not config.base_url:\n click.secho(\"βœ— Base URL not set\", fg=\"red\")\n sys.exit(EXIT_CONFIG_ERROR)\n\n try:\n validate_url(config.base_url)\n if verbose:\n click.secho(\" βœ“ Valid HTTPS URL\", fg=\"green\")\n else:\n click.secho(f\"βœ“ Base URL valid: {config.base_url}\", fg=\"green\")\n except ConfigurationError as e:\n click.secho(f\"βœ— Invalid base URL: {e.message}\", fg=\"red\")\n sys.exit(EXIT_CONFIG_ERROR)\n \n # Step 4: Check models\n if verbose:\n click.echo()\n click.echo(\"[4/5] Checking model configuration...\")\n click.echo(f\" Main model: {config.main_model}\")\n if not caw_mode:\n click.echo(f\" Cluster model: {config.cluster_model}\")\n click.echo(f\" Fallback model: {config.fallback_model}\")\n\n if caw_mode:\n if not config.main_model:\n click.secho(\"βœ— Main model not configured\", fg=\"red\")\n sys.exit(EXIT_CONFIG_ERROR)\n if verbose:\n click.secho(\" βœ“ Main model configured\", fg=\"green\")\n else:\n click.secho(f\"βœ“ Main model configured: {config.main_model}\", fg=\"green\")\n else:\n if not config.main_model or not config.cluster_model or not config.fallback_model:\n click.secho(\"βœ— Models not configured\", fg=\"red\")\n sys.exit(EXIT_CONFIG_ERROR)\n\n if verbose:\n click.secho(\" βœ“ Models configured\", fg=\"green\")\n else:\n click.secho(f\"βœ“ Main model configured: {config.main_model}\", fg=\"green\")\n click.secho(f\"βœ“ Cluster model configured: {config.cluster_model}\", fg=\"green\")\n click.secho(f\"βœ“ Fallback model configured: {config.fallback_model}\", fg=\"green\")\n\n # Warn about non-top-tier cluster model\n if not is_top_tier_model(config.cluster_model):\n click.secho(\n \"⚠️ Cluster model is not top-tier. Consider using claude-sonnet-4 or gpt-4.\",\n fg=\"yellow\"\n )\n\n # Step 5: API connectivity test (unless --quick)\n if caw_mode:\n if verbose:\n click.echo()\n click.echo(\"[5/5] Checking CLI availability...\")\n\n import shutil\n cli_name = \"claude\" if config.provider == \"claude-code\" else \"codex\"\n cli_path = shutil.which(cli_name)\n if not cli_path:\n click.secho(f\"βœ— {cli_name} CLI not found in PATH\", fg=\"red\")\n click.echo(\n f\"\\nInstall the {cli_name} CLI and run '{cli_name} login' \"\n f\"to authenticate, then re-run this command.\"\n )\n sys.exit(EXIT_CONFIG_ERROR)\n\n if verbose:\n click.secho(f\" βœ“ {cli_name} CLI found at {cli_path}\", fg=\"green\")\n click.secho(\n f\" ↳ Ensure '{cli_name} login' has been run on this host.\",\n fg=\"cyan\",\n )\n else:\n click.secho(f\"βœ“ {cli_name} CLI available (run '{cli_name} login' if not yet authenticated)\", fg=\"green\")\n elif not quick:\n if verbose:\n click.echo()\n click.echo(\"[5/5] Testing API connectivity...\")\n click.echo(f\" URL: {config.base_url}\")\n\n try:\n base_url_lower = (config.base_url or \"\").lower()\n provider = getattr(config, 'provider', 'openai-compatible')\n if provider == \"azure-openai\" or \".openai.azure.com\" in base_url_lower:\n # Use Azure OpenAI SDK\n from openai import AzureOpenAI\n client = AzureOpenAI(\n api_key=api_key,\n api_version=config.api_version,\n azure_endpoint=config.base_url,\n )\n client.models.list()\n elif \"api.anthropic.com\" in base_url_lower:\n # Use Anthropic SDK for native Anthropic endpoints\n import anthropic\n client = anthropic.Anthropic(api_key=api_key)\n client.models.list(limit=1)\n else:\n # Use OpenAI SDK for OpenAI-compatible endpoints\n from openai import OpenAI\n client = OpenAI(api_key=api_key, base_url=config.base_url)\n client.models.list()\n\n if verbose:\n click.secho(\" βœ“ API responded successfully\", fg=\"green\")\n else:\n click.secho(\"βœ“ API connectivity test successful\", fg=\"green\")\n except Exception as e:\n click.secho(\"βœ— API connectivity test failed\", fg=\"red\")\n if verbose:\n click.echo(f\" Error: {e}\")\n sys.exit(EXIT_CONFIG_ERROR)\n \n # Success\n click.echo()\n click.secho(\"βœ“ Configuration is valid!\", fg=\"green\", bold=True)\n click.echo()\n \n except ConfigurationError as e:\n click.secho(f\"\\nβœ— Configuration error: {e.message}\", fg=\"red\", err=True)\n sys.exit(e.exit_code)\n except Exception as e:\n sys.exit(handle_error(e, verbose=verbose))", - "start_line": 511, - "end_line": 729, - "has_docstring": true, - "docstring": "Validate configuration and test LLM API connectivity.\n\nChecks:\n β€’ Configuration file exists and is valid\n β€’ API key is present\n β€’ API settings are correctly formatted\n β€’ (Optional) API connectivity test\n\nExamples:\n\n\b\n# Full validation with API test\n$ codewiki config validate\n\n\b\n# Quick validation (config only)\n$ codewiki config validate --quick\n\n\b\n# Verbose output\n$ codewiki config validate --verbose", - "parameters": [ - "quick", - "verbose" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function config_validate", - "component_id": "codewiki/cli/commands/config.py::config_validate", - "language": null, - "qualified_name": null - }, - "codewiki/cli/commands/config.py::config_agent": { - "id": "codewiki/cli/commands/config.py::config_agent", - "name": "config_agent", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/commands/config.py", - "relative_path": "codewiki/cli/commands/config.py", - "depends_on": [ - "codewiki/cli/commands/config.py::parse_patterns", - "codewiki/cli/config_manager.py::ConfigManager", - "codewiki/cli/models/config.py::AgentInstructions", - "codewiki/cli/config_manager.py::ConfigManager.get_config", - "codewiki/cli/models/config.py::AgentInstructions.is_empty", - "codewiki/cli/utils/errors.py::handle_error", - "codewiki/cli/config_manager.py::ConfigManager.save", - "codewiki/cli/config_manager.py::ConfigManager.load" - ], - "source_code": "def config_agent(\n include: Optional[str],\n exclude: Optional[str],\n focus: Optional[str],\n doc_type: Optional[str],\n instructions: Optional[str],\n clear: bool\n):\n \"\"\"\n Configure default agent instructions for documentation generation.\n \n These settings are used as defaults when running 'codewiki generate'.\n Runtime options (--include, --exclude, etc.) override these defaults.\n \n Examples:\n \n \\b\n # Set include patterns for C# projects\n $ codewiki config agent --include \"*.cs\"\n \n \\b\n # Exclude test projects\n $ codewiki config agent --exclude \"*Tests*,*Specs*,test_*\"\n \n \\b\n # Focus on specific modules\n $ codewiki config agent --focus \"src/core,src/api\"\n \n \\b\n # Set default doc type\n $ codewiki config agent --doc-type architecture\n \n \\b\n # Add custom instructions\n $ codewiki config agent --instructions \"Focus on public APIs and include usage examples\"\n \n \\b\n # Clear all agent instructions\n $ codewiki config agent --clear\n \"\"\"\n try:\n manager = ConfigManager()\n \n if not manager.load():\n click.secho(\"\\nβœ— Configuration not found.\", fg=\"red\", err=True)\n click.echo(\"\\nPlease run 'codewiki config set' first to configure your API credentials.\")\n sys.exit(EXIT_CONFIG_ERROR)\n \n config = manager.get_config()\n \n if clear:\n # Clear all agent instructions\n config.agent_instructions = AgentInstructions()\n manager.save()\n click.echo()\n click.secho(\"βœ“ Agent instructions cleared\", fg=\"green\")\n click.echo()\n return\n \n # Check if at least one option is provided\n if not any([include, exclude, focus, doc_type, instructions]):\n # Display current settings\n click.echo()\n click.secho(\"Agent Instructions\", fg=\"blue\", bold=True)\n click.echo(\"━\" * 40)\n click.echo()\n \n agent = config.agent_instructions\n if agent and not agent.is_empty():\n if agent.include_patterns:\n click.echo(f\" Include patterns: {', '.join(agent.include_patterns)}\")\n if agent.exclude_patterns:\n click.echo(f\" Exclude patterns: {', '.join(agent.exclude_patterns)}\")\n if agent.focus_modules:\n click.echo(f\" Focus modules: {', '.join(agent.focus_modules)}\")\n if agent.doc_type:\n click.echo(f\" Doc type: {agent.doc_type}\")\n if agent.custom_instructions:\n click.echo(f\" Custom instructions: {agent.custom_instructions}\")\n else:\n click.secho(\" No agent instructions configured (using defaults)\", fg=\"yellow\")\n \n click.echo()\n click.echo(\"Use 'codewiki config agent --help' for usage information.\")\n click.echo()\n return\n \n # Update agent instructions\n current = config.agent_instructions or AgentInstructions()\n \n if include is not None:\n current.include_patterns = parse_patterns(include) if include else None\n if exclude is not None:\n current.exclude_patterns = parse_patterns(exclude) if exclude else None\n if focus is not None:\n current.focus_modules = parse_patterns(focus) if focus else None\n if doc_type is not None:\n current.doc_type = doc_type if doc_type else None\n if instructions is not None:\n current.custom_instructions = instructions if instructions else None\n \n config.agent_instructions = current\n manager.save()\n \n # Display success messages\n click.echo()\n if include:\n click.secho(f\"βœ“ Include patterns: {parse_patterns(include)}\", fg=\"green\")\n if exclude:\n click.secho(f\"βœ“ Exclude patterns: {parse_patterns(exclude)}\", fg=\"green\")\n if focus:\n click.secho(f\"βœ“ Focus modules: {parse_patterns(focus)}\", fg=\"green\")\n if doc_type:\n click.secho(f\"βœ“ Doc type: {doc_type}\", fg=\"green\")\n if instructions:\n click.secho(f\"βœ“ Custom instructions set\", fg=\"green\")\n \n click.echo(\"\\n\" + click.style(\"Agent instructions updated successfully.\", fg=\"green\", bold=True))\n click.echo()\n \n except ConfigurationError as e:\n click.secho(f\"\\nβœ— Configuration error: {e.message}\", fg=\"red\", err=True)\n sys.exit(e.exit_code)\n except Exception as e:\n sys.exit(handle_error(e))", - "start_line": 772, - "end_line": 896, - "has_docstring": true, - "docstring": "Configure default agent instructions for documentation generation.\n\nThese settings are used as defaults when running 'codewiki generate'.\nRuntime options (--include, --exclude, etc.) override these defaults.\n\nExamples:\n\n\b\n# Set include patterns for C# projects\n$ codewiki config agent --include \"*.cs\"\n\n\b\n# Exclude test projects\n$ codewiki config agent --exclude \"*Tests*,*Specs*,test_*\"\n\n\b\n# Focus on specific modules\n$ codewiki config agent --focus \"src/core,src/api\"\n\n\b\n# Set default doc type\n$ codewiki config agent --doc-type architecture\n\n\b\n# Add custom instructions\n$ codewiki config agent --instructions \"Focus on public APIs and include usage examples\"\n\n\b\n# Clear all agent instructions\n$ codewiki config agent --clear", - "parameters": [ - "include", - "exclude", - "focus", - "doc_type", - "instructions", - "clear" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function config_agent", - "component_id": "codewiki/cli/commands/config.py::config_agent", - "language": null, - "qualified_name": null - }, - "codewiki/cli/commands/generate.py::parse_patterns": { - "id": "codewiki/cli/commands/generate.py::parse_patterns", - "name": "parse_patterns", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/commands/generate.py", - "relative_path": "codewiki/cli/commands/generate.py", - "depends_on": [], - "source_code": "def parse_patterns(patterns_str: str) -> List[str]:\n \"\"\"Parse comma-separated patterns into a list.\"\"\"\n if not patterns_str:\n return []\n return [p.strip() for p in patterns_str.split(',') if p.strip()]", - "start_line": 36, - "end_line": 40, - "has_docstring": true, - "docstring": "Parse comma-separated patterns into a list.", - "parameters": [ - "patterns_str" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function parse_patterns", - "component_id": "codewiki/cli/commands/generate.py::parse_patterns", - "language": null, - "qualified_name": null - }, - "codewiki/cli/commands/generate.py::_detect_changed_files": { - "id": "codewiki/cli/commands/generate.py::_detect_changed_files", - "name": "_detect_changed_files", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/commands/generate.py", - "relative_path": "codewiki/cli/commands/generate.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": "def _detect_changed_files(\n repo_path: Path,\n output_dir: Path,\n logger,\n verbose: bool,\n compare_to: Optional[str] = None\n) -> Optional[List[str]]:\n \"\"\"\n Detect files changed since the last documentation generation.\n\n Reads the commit_id from metadata.json and compares with current HEAD\n using git diff. When running inside a subdirectory of a monorepo,\n only files under that subdirectory are returned.\n\n Returns list of changed file paths relative to repo_path, or None if\n unable to determine (e.g., no metadata, not a git repo).\n \"\"\"\n import json\n\n prev_commit = None\n if compare_to:\n prev_commit = compare_to\n else:\n metadata_path = output_dir / \"metadata.json\"\n if not metadata_path.exists():\n if verbose:\n logger.debug(\"No metadata.json found β€” cannot detect changes, running full generation.\")\n return None\n\n try:\n metadata = json.loads(metadata_path.read_text())\n prev_commit = metadata.get(\"generation_info\", {}).get(\"commit_id\")\n if not prev_commit:\n if verbose:\n logger.debug(\"No commit_id in metadata β€” running full generation.\")\n return None\n except (json.JSONDecodeError, OSError):\n return None\n\n # Get current HEAD commit\n try:\n import git\n repo = git.Repo(repo_path, search_parent_directories=True)\n current_commit = repo.head.commit.hexsha\n except Exception:\n if verbose:\n logger.debug(\"Cannot access git repo β€” running full generation.\")\n return None\n\n if prev_commit == current_commit:\n if verbose:\n logger.debug(f\"HEAD is still at {current_commit[:8]} β€” no changes.\")\n return []\n\n # Determine subdirectory prefix relative to the git root\n if repo.working_tree_dir is None:\n if verbose:\n logger.debug(\"Bare git repository β€” running full generation.\")\n return None\n git_root = Path(repo.working_tree_dir).resolve()\n repo_path_resolved = repo_path.resolve()\n try:\n subpath_prefix = repo_path_resolved.relative_to(git_root).as_posix()\n except ValueError:\n # repo_path is outside git root β€” shouldn't happen, but fall back to full generation\n if verbose:\n logger.debug(\"Repo path is outside git root β€” running full generation.\")\n return None\n\n # Get changed files between previous and current commit\n try:\n diff_index = repo.commit(prev_commit).diff(current_commit)\n changed = []\n for diff in diff_index:\n if diff.a_path:\n changed.append(diff.a_path)\n if diff.b_path and diff.b_path != diff.a_path:\n changed.append(diff.b_path)\n\n # Filter to files under the current subdirectory and strip the prefix\n # so paths align with module_tree.json component paths\n filtered = []\n if subpath_prefix == \".\":\n filtered = changed\n else:\n prefix = subpath_prefix + \"/\"\n for path in changed:\n if path.startswith(prefix):\n filtered.append(path[len(prefix):])\n\n if verbose:\n logger.debug(f\"Changes between {prev_commit[:8]} and {current_commit[:8]}:\")\n if subpath_prefix != \".\":\n logger.debug(f\" Scoped to subdirectory: {subpath_prefix}\")\n for f in filtered[:10]:\n logger.debug(f\" {f}\")\n if len(filtered) > 10:\n logger.debug(f\" ... and {len(filtered) - 10} more\")\n\n return filtered\n except Exception as e:\n if verbose:\n logger.debug(f\"Git diff failed: {e} β€” running full generation.\")\n return None", - "start_line": 43, - "end_line": 146, - "has_docstring": true, - "docstring": "Detect files changed since the last documentation generation.\n\nReads the commit_id from metadata.json and compares with current HEAD\nusing git diff. When running inside a subdirectory of a monorepo,\nonly files under that subdirectory are returned.\n\nReturns list of changed file paths relative to repo_path, or None if\nunable to determine (e.g., no metadata, not a git repo).", - "parameters": [ - "repo_path", - "output_dir", - "logger", - "verbose", - "compare_to" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _detect_changed_files", - "component_id": "codewiki/cli/commands/generate.py::_detect_changed_files", - "language": null, - "qualified_name": null - }, - "codewiki/cli/commands/generate.py::_invalidate_affected_modules": { - "id": "codewiki/cli/commands/generate.py::_invalidate_affected_modules", - "name": "_invalidate_affected_modules", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/commands/generate.py", - "relative_path": "codewiki/cli/commands/generate.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": "def _invalidate_affected_modules(\n output_dir: Path,\n changed_files: List[str],\n logger,\n verbose: bool\n):\n \"\"\"\n Remove cached module documentation for modules that contain changed files.\n\n Reads module_tree.json to find which modules contain changed files,\n then deletes their .md files so they get regenerated.\n \"\"\"\n import json\n\n module_tree_path = output_dir / \"module_tree.json\"\n if not module_tree_path.exists():\n return\n\n try:\n module_tree = json.loads(module_tree_path.read_text())\n except (json.JSONDecodeError, OSError):\n return\n\n changed_set = set(changed_files)\n modules_to_invalidate = set()\n\n def _find_affected(tree, parent_names=None):\n if parent_names is None:\n parent_names = []\n for mod_name, mod_info in tree.items():\n components = mod_info.get(\"components\", [])\n # Check if any component path overlaps with changed files\n for comp in components:\n # Component IDs may be class names, check if they match any changed file path\n if any(changed_file in comp or comp in changed_file for changed_file in changed_set):\n modules_to_invalidate.add(mod_name)\n # Also invalidate parent modules\n for parent in parent_names:\n modules_to_invalidate.add(parent)\n break\n\n children = mod_info.get(\"children\", {})\n if isinstance(children, dict) and children:\n _find_affected(children, parent_names + [mod_name])\n\n _find_affected(module_tree)\n\n # Also remove overview.md since it depends on child docs\n if modules_to_invalidate:\n modules_to_invalidate.add(\"overview\")\n\n # Delete affected module docs\n for mod_name in modules_to_invalidate:\n doc_path = output_dir / f\"{mod_name}.md\"\n if doc_path.exists():\n doc_path.unlink()\n if verbose:\n logger.debug(f\"Invalidated: {doc_path.name}\")\n\n if verbose:\n logger.debug(f\"Invalidated {len(modules_to_invalidate)} modules for regeneration.\")", - "start_line": 149, - "end_line": 209, - "has_docstring": true, - "docstring": "Remove cached module documentation for modules that contain changed files.\n\nReads module_tree.json to find which modules contain changed files,\nthen deletes their .md files so they get regenerated.", - "parameters": [ - "output_dir", - "changed_files", - "logger", - "verbose" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _invalidate_affected_modules", - "component_id": "codewiki/cli/commands/generate.py::_invalidate_affected_modules", - "language": null, - "qualified_name": null - }, - "codewiki/cli/commands/generate.py::generate_command": { - "id": "codewiki/cli/commands/generate.py::generate_command", - "name": "generate_command", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/commands/generate.py", - "relative_path": "codewiki/cli/commands/generate.py", - "depends_on": [ - "codewiki/cli/utils/errors.py::ConfigurationError", - "codewiki/cli/commands/generate.py::_detect_changed_files", - "codewiki/cli/git_manager.py::GitManager.check_clean_working_directory", - "codewiki/cli/git_manager.py::GitManager", - "codewiki/cli/utils/repo_validator.py::get_git_commit_hash", - "codewiki/cli/config_manager.py::ConfigManager.get_api_key", - "codewiki/cli/utils/repo_validator.py::is_git_repository", - "codewiki/cli/git_manager.py::GitManager.create_documentation_branch", - "codewiki/cli/models/job.py::GenerationOptions", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/cli/utils/logging.py::CLILogger.step", - "codewiki/cli/models/config.py::AgentInstructions.to_dict", - "codewiki/cli/config_manager.py::ConfigManager.get_config", - "codewiki/cli/utils/errors.py::handle_error", - "codewiki/cli/utils/repo_validator.py::check_writable_output", - "codewiki/cli/utils/logging.py::create_logger", - "codewiki/cli/utils/repo_validator.py::validate_repository", - "codewiki/cli/models/config.py::AgentInstructions", - "codewiki/cli/utils/errors.py::RepositoryError", - "codewiki/cli/config_manager.py::ConfigManager.is_configured", - "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/cli/config_manager.py::ConfigManager", - "codewiki/cli/adapters/doc_generator.py::CLIDocumentationGenerator.generate", - "codewiki/cli/utils/instructions.py::display_post_generation_instructions", - "codewiki/cli/models/config.py::AgentInstructions.is_empty", - "codewiki/cli/commands/generate.py::_invalidate_affected_modules", - "codewiki/cli/utils/repo_validator.py::get_git_branch", - "codewiki/cli/commands/generate.py::parse_patterns", - "codewiki/cli/utils/logging.py::CLILogger.error", - "codewiki/cli/config_manager.py::ConfigManager.load" - ], - "source_code": "def generate_command(\n ctx,\n output: str,\n create_branch: bool,\n github_pages: bool,\n no_cache: bool,\n include: Optional[str],\n exclude: Optional[str],\n focus: Optional[str],\n doc_type: Optional[str],\n instructions: Optional[str],\n use_gitignore: Optional[bool],\n verbose: bool,\n max_tokens: Optional[int],\n max_token_per_module: Optional[int],\n max_token_per_leaf_module: Optional[int],\n max_depth: Optional[int],\n prompt_caching: Optional[bool],\n update: bool = False,\n compare_to: Optional[str] = None\n):\n \"\"\"\n Generate comprehensive documentation for a code repository.\n \n Analyzes the current repository and generates documentation using LLM-powered\n analysis. Documentation is output to ./docs/ by default.\n \n Examples:\n \n \\b\n # Basic generation\n $ codewiki generate\n \n \\b\n # With git branch creation and GitHub Pages\n $ codewiki generate --create-branch --github-pages\n \n \\b\n # Force full regeneration\n $ codewiki generate --no-cache\n\n \\b\n # Analyze ignored files as well\n $ codewiki generate --no-gitignore\n \n \\b\n # C# project: only .cs files, exclude tests\n $ codewiki generate --include \"*.cs\" --exclude \"*Tests*,*Specs*\"\n \n \\b\n # Focus on specific modules with architecture docs\n $ codewiki generate --focus \"src/core,src/api\" --doc-type architecture\n \n \\b\n # Custom instructions\n $ codewiki generate --instructions \"Focus on public APIs and include usage examples\"\n \n \\b\n # Override max tokens for this generation\n $ codewiki generate --max-tokens 16384\n \n \\b\n # Set all max token limits\n $ codewiki generate --max-tokens 32768 --max-token-per-module 40000 --max-token-per-leaf-module 20000\n \n \\b\n # Override max depth for hierarchical decomposition\n $ codewiki generate --max-depth 3\n \"\"\"\n logger = create_logger(verbose=verbose)\n start_time = time.time()\n \n # Suppress httpx INFO logs\n logging.getLogger(\"httpx\").setLevel(logging.WARNING)\n \n try:\n # Pre-generation checks\n logger.step(\"Validating configuration...\", 1, 4)\n \n # Load configuration\n config_manager = ConfigManager()\n if not config_manager.load():\n raise ConfigurationError(\n \"Configuration not found or invalid.\\n\\n\"\n \"Please run 'codewiki config set' to configure your LLM API credentials:\\n\"\n \" codewiki config set --api-key --base-url \\\\\\n\"\n \" --main-model --cluster-model \\n\\n\"\n \"For more help: codewiki config --help\"\n )\n \n if not config_manager.is_configured():\n raise ConfigurationError(\n \"Configuration is incomplete. Please run 'codewiki config validate'\"\n )\n \n config = config_manager.get_config()\n api_key = config_manager.get_api_key()\n \n logger.success(\"Configuration valid\")\n \n # Validate repository\n logger.step(\"Validating repository...\", 2, 4)\n \n repo_path = Path.cwd()\n repo_path, languages = validate_repository(repo_path)\n \n logger.success(f\"Repository valid: {repo_path.name}\")\n if verbose:\n logger.debug(f\"Detected languages: {', '.join(f'{lang} ({count} files)' for lang, count in languages)}\")\n \n # Check git repository\n if not is_git_repository(repo_path):\n if create_branch:\n raise RepositoryError(\n \"Not a git repository.\\n\\n\"\n \"The --create-branch flag requires a git repository.\\n\\n\"\n \"To initialize a git repository: git init\"\n )\n else:\n logger.warning(\"Not a git repository. Git features unavailable.\")\n \n # Validate output directory\n output_dir = Path(output).expanduser().resolve()\n check_writable_output(output_dir.parent)\n \n logger.success(f\"Output directory: {output_dir}\")\n \n # If a base commit is specified to compare against, implicitly enable update\n if compare_to:\n update = True\n\n # Incremental update: detect changed files and selectively regenerate\n changed_files = None\n if update and output_dir.exists():\n changed_files = _detect_changed_files(repo_path, output_dir, logger, verbose, compare_to=compare_to)\n if changed_files is not None and len(changed_files) == 0:\n logger.success(\"No changes detected since last generation. Documentation is up to date.\")\n sys.exit(EXIT_SUCCESS)\n if changed_files is not None:\n logger.info(f\" Detected {len(changed_files)} changed files β€” regenerating affected modules.\")\n # Remove cached module docs for affected files so they get regenerated\n _invalidate_affected_modules(output_dir, changed_files, logger, verbose)\n\n # Check for existing documentation\n if not update and output_dir.exists() and list(output_dir.glob(\"*.md\")):\n if not click.confirm(\n f\"\\n{output_dir} already contains documentation. Overwrite?\",\n default=True\n ):\n logger.info(\"Generation cancelled by user.\")\n sys.exit(EXIT_SUCCESS)\n \n # Git branch creation (if requested)\n branch_name = None\n if create_branch:\n logger.step(\"Creating git branch...\", 3, 4)\n \n from codewiki.cli.git_manager import GitManager\n \n git_manager = GitManager(repo_path)\n \n # Check clean working directory\n is_clean, status_msg = git_manager.check_clean_working_directory()\n if not is_clean:\n raise RepositoryError(\n \"Working directory has uncommitted changes.\\n\\n\"\n f\"{status_msg}\\n\\n\"\n \"Cannot create documentation branch with uncommitted changes.\\n\"\n \"Please commit or stash your changes first:\\n\"\n \" git add -A && git commit -m \\\"Your message\\\"\\n\"\n \" # or\\n\"\n \" git stash\"\n )\n \n # Create branch\n branch_name = git_manager.create_documentation_branch()\n logger.success(f\"Created branch: {branch_name}\")\n \n # Generate documentation\n logger.step(\"Generating documentation...\", 4, 4)\n click.echo()\n \n # Create generation options\n generation_options = GenerationOptions(\n create_branch=create_branch,\n github_pages=github_pages,\n no_cache=no_cache,\n custom_output=output if output != \"docs\" else None\n )\n \n # Create runtime agent instructions from CLI options\n runtime_instructions = None\n if any([include, exclude, focus, doc_type, instructions]):\n runtime_instructions = AgentInstructions(\n include_patterns=parse_patterns(include) if include else None,\n exclude_patterns=parse_patterns(exclude) if exclude else None,\n focus_modules=parse_patterns(focus) if focus else None,\n doc_type=doc_type,\n custom_instructions=instructions,\n )\n \n if verbose:\n if include:\n logger.debug(f\"Include patterns: {parse_patterns(include)}\")\n if exclude:\n logger.debug(f\"Exclude patterns: {parse_patterns(exclude)}\")\n if focus:\n logger.debug(f\"Focus modules: {parse_patterns(focus)}\")\n if doc_type:\n logger.debug(f\"Doc type: {doc_type}\")\n if instructions:\n logger.debug(f\"Custom instructions: {instructions}\")\n \n # Log max token settings if verbose\n if verbose:\n effective_max_tokens = max_tokens if max_tokens is not None else config.max_tokens\n effective_max_token_per_module = max_token_per_module if max_token_per_module is not None else config.max_token_per_module\n effective_max_token_per_leaf = max_token_per_leaf_module if max_token_per_leaf_module is not None else config.max_token_per_leaf_module\n effective_max_depth = max_depth if max_depth is not None else config.max_depth\n effective_use_gitignore = use_gitignore if use_gitignore is not None else config.use_gitignore\n effective_prompt_caching = prompt_caching if prompt_caching is not None else config.prompt_caching\n logger.debug(f\"Max tokens: {effective_max_tokens}\")\n logger.debug(f\"Max token/module: {effective_max_token_per_module}\")\n logger.debug(f\"Max token/leaf module: {effective_max_token_per_leaf}\")\n logger.debug(f\"Max depth: {effective_max_depth}\")\n logger.debug(f\"Use gitignore: {effective_use_gitignore}\")\n logger.debug(f\"Prompt caching: {effective_prompt_caching}\")\n \n # Get agent instructions (merge runtime with persistent)\n agent_instructions_dict = None\n if runtime_instructions and not runtime_instructions.is_empty():\n # Merge with persistent settings\n merged = AgentInstructions(\n include_patterns=runtime_instructions.include_patterns or (config.agent_instructions.include_patterns if config.agent_instructions else None),\n exclude_patterns=runtime_instructions.exclude_patterns or (config.agent_instructions.exclude_patterns if config.agent_instructions else None),\n focus_modules=runtime_instructions.focus_modules or (config.agent_instructions.focus_modules if config.agent_instructions else None),\n doc_type=runtime_instructions.doc_type or (config.agent_instructions.doc_type if config.agent_instructions else None),\n custom_instructions=runtime_instructions.custom_instructions or (config.agent_instructions.custom_instructions if config.agent_instructions else None),\n )\n agent_instructions_dict = merged.to_dict()\n elif config.agent_instructions and not config.agent_instructions.is_empty():\n agent_instructions_dict = config.agent_instructions.to_dict()\n \n # Create generator\n # Get commit_id early so it can be stored in metadata.json for --update support\n commit_id = get_git_commit_hash(repo_path)\n generator = CLIDocumentationGenerator(\n repo_path=repo_path,\n output_dir=output_dir,\n config={\n 'main_model': config.main_model,\n 'cluster_model': config.cluster_model,\n 'fallback_model': config.fallback_model,\n 'base_url': config.base_url,\n 'api_key': api_key,\n 'provider': getattr(config, 'provider', 'openai-compatible'),\n 'aws_region': getattr(config, 'aws_region', 'us-east-1'),\n 'agent_instructions': agent_instructions_dict,\n # Max token settings (runtime overrides take precedence)\n 'max_tokens': max_tokens if max_tokens is not None else config.max_tokens,\n 'max_token_per_module': max_token_per_module if max_token_per_module is not None else config.max_token_per_module,\n 'max_token_per_leaf_module': max_token_per_leaf_module if max_token_per_leaf_module is not None else config.max_token_per_leaf_module,\n # Max depth setting (runtime override takes precedence)\n 'max_depth': max_depth if max_depth is not None else config.max_depth,\n # Gitignore setting (runtime override takes precedence)\n 'use_gitignore': use_gitignore if use_gitignore is not None else config.use_gitignore,\n # Prompt caching setting (runtime override takes precedence)\n 'prompt_caching': prompt_caching if prompt_caching is not None else config.prompt_caching,\n },\n verbose=verbose,\n generate_html=github_pages,\n commit_id=commit_id,\n )\n \n # Run generation\n job = generator.generate()\n \n # Post-generation\n generation_time = time.time() - start_time\n \n # Get repository info\n repo_url = None\n current_branch = get_git_branch(repo_path)\n \n if is_git_repository(repo_path):\n try:\n import git\n repo = git.Repo(repo_path)\n if repo.remotes:\n repo_url = repo.remotes.origin.url\n except:\n pass\n \n # Display instructions\n display_post_generation_instructions(\n output_dir=output_dir,\n repo_name=repo_path.name,\n repo_url=repo_url,\n branch_name=branch_name,\n github_pages=github_pages,\n files_generated=job.files_generated,\n statistics={\n 'module_count': job.module_count,\n 'total_files_analyzed': job.statistics.total_files_analyzed,\n 'generation_time': generation_time,\n 'total_tokens_used': job.statistics.total_tokens_used,\n }\n )\n \n except ConfigurationError as e:\n logger.error(e.message)\n logger.error(f\"Traceback: {traceback.format_exc()}\")\n sys.exit(e.exit_code)\n except RepositoryError as e:\n logger.error(e.message)\n logger.error(f\"Traceback: {traceback.format_exc()}\")\n sys.exit(e.exit_code)\n except APIError as e:\n logger.error(e.message)\n logger.error(f\"Traceback: {traceback.format_exc()}\")\n sys.exit(e.exit_code)\n except IncompleteGenerationError as e:\n click.secho(f\"\\nβœ— {e.message}\", fg=\"red\", err=True)\n for module_name in e.missing_modules:\n click.secho(f\" - {module_name}.md\", fg=\"red\", err=True)\n click.echo(\n \"Re-run the same command to resume generation for the missing modules.\",\n err=True,\n )\n sys.exit(e.exit_code)\n except KeyboardInterrupt:\n click.echo(\"\\n\\nInterrupted by user\")\n sys.exit(130)\n except Exception as e:\n sys.exit(handle_error(e, verbose=verbose))", - "start_line": 322, - "end_line": 656, - "has_docstring": true, - "docstring": "Generate comprehensive documentation for a code repository.\n\nAnalyzes the current repository and generates documentation using LLM-powered\nanalysis. Documentation is output to ./docs/ by default.\n\nExamples:\n\n\b\n# Basic generation\n$ codewiki generate\n\n\b\n# With git branch creation and GitHub Pages\n$ codewiki generate --create-branch --github-pages\n\n\b\n# Force full regeneration\n$ codewiki generate --no-cache\n\n\b\n# Analyze ignored files as well\n$ codewiki generate --no-gitignore\n\n\b\n# C# project: only .cs files, exclude tests\n$ codewiki generate --include \"*.cs\" --exclude \"*Tests*,*Specs*\"\n\n\b\n# Focus on specific modules with architecture docs\n$ codewiki generate --focus \"src/core,src/api\" --doc-type architecture\n\n\b\n# Custom instructions\n$ codewiki generate --instructions \"Focus on public APIs and include usage examples\"\n\n\b\n# Override max tokens for this generation\n$ codewiki generate --max-tokens 16384\n\n\b\n# Set all max token limits\n$ codewiki generate --max-tokens 32768 --max-token-per-module 40000 --max-token-per-leaf-module 20000\n\n\b\n# Override max depth for hierarchical decomposition\n$ codewiki generate --max-depth 3", - "parameters": [ - "ctx", - "output", - "create_branch", - "github_pages", - "no_cache", - "include", - "exclude", - "focus", - "doc_type", - "instructions", - "use_gitignore", - "verbose", - "max_tokens", - "max_token_per_module", - "max_token_per_leaf_module", - "max_depth", - "prompt_caching", - "update", - "compare_to" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function generate_command", - "component_id": "codewiki/cli/commands/generate.py::generate_command", - "language": null, - "qualified_name": null - }, - "codewiki/cli/config_manager.py::ConfigManager": { - "id": "codewiki/cli/config_manager.py::ConfigManager", - "name": "ConfigManager", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/config_manager.py", - "relative_path": "codewiki/cli/config_manager.py", - "depends_on": [], - "source_code": "class ConfigManager:\n \"\"\"\n Manages CodeWiki configuration with secure keyring storage for API keys.\n\n Storage:\n - API key: System keychain via keyring (macOS Keychain, Windows Credential Manager,\n Linux Secret Service)\n - Fallback: ~/.codewiki/credentials.json when keyring is unavailable\n - Other settings: ~/.codewiki/config.json\n\n Set CODEWIKI_NO_KEYRING=1 to skip keyring and use file-based storage.\n \"\"\"\n\n def __init__(self):\n \"\"\"Initialize the configuration manager.\"\"\"\n self._api_key: Optional[str] = None\n self._config: Optional[Configuration] = None\n self._force_no_keyring = os.environ.get(\"CODEWIKI_NO_KEYRING\", \"\").strip() in (\"1\", \"true\", \"yes\")\n self._keyring_available = self._check_keyring_available()\n\n def _check_keyring_available(self) -> bool:\n \"\"\"Check if system keyring is available.\"\"\"\n if self._force_no_keyring:\n logger.debug(\"Keyring disabled via CODEWIKI_NO_KEYRING\")\n return False\n try:\n # Try to get/set a test value\n keyring.get_password(KEYRING_SERVICE, \"__test__\")\n return True\n except (KeyringError, Exception):\n return False\n\n def _load_api_key_from_file(self) -> Optional[str]:\n \"\"\"Load API key from fallback credentials file.\"\"\"\n if not CREDENTIALS_FILE.exists():\n return None\n try:\n content = safe_read(CREDENTIALS_FILE)\n data = json.loads(content)\n return data.get(\"api_key\")\n except (json.JSONDecodeError, FileSystemError):\n return None\n\n def _save_api_key_to_file(self, api_key: str):\n \"\"\"Save API key to fallback credentials file (plaintext).\"\"\"\n ensure_directory(CONFIG_DIR)\n data = {\"api_key\": api_key}\n safe_write(CREDENTIALS_FILE, json.dumps(data, indent=2))\n # Restrict file permissions (owner read/write only)\n try:\n CREDENTIALS_FILE.chmod(0o600)\n except OSError:\n pass\n \n def load(self) -> bool:\n \"\"\"\n Load configuration from file and keyring.\n \n Returns:\n True if configuration exists, False otherwise\n \"\"\"\n # Load from JSON file\n if not CONFIG_FILE.exists():\n return False\n \n try:\n content = safe_read(CONFIG_FILE)\n data = json.loads(content)\n \n # Validate version\n if data.get('version') != CONFIG_VERSION:\n # Could implement migration here\n pass\n \n self._config = Configuration.from_dict(data)\n \n # Load API key from keyring, falling back to file\n if self._keyring_available:\n try:\n self._api_key = keyring.get_password(KEYRING_SERVICE, KEYRING_API_KEY_ACCOUNT)\n except (KeyringError, Exception):\n pass\n if self._api_key is None:\n self._api_key = self._load_api_key_from_file()\n \n return True\n except (json.JSONDecodeError, FileSystemError) as e:\n raise ConfigurationError(f\"Failed to load configuration: {e}\")\n \n def save(\n self,\n api_key: Optional[str] = None,\n base_url: Optional[str] = None,\n main_model: Optional[str] = None,\n cluster_model: Optional[str] = None,\n fallback_model: Optional[str] = None,\n default_output: Optional[str] = None,\n max_tokens: Optional[int] = None,\n max_token_per_module: Optional[int] = None,\n max_token_per_leaf_module: Optional[int] = None,\n max_depth: Optional[int] = None,\n provider: Optional[str] = None,\n aws_region: Optional[str] = None,\n api_version: Optional[str] = None,\n azure_deployment: Optional[str] = None,\n use_gitignore: Optional[bool] = None,\n prompt_caching: Optional[bool] = None,\n ):\n \"\"\"\n Save configuration to file and keyring.\n\n Args:\n api_key: API key (stored in keyring)\n base_url: LLM API base URL\n main_model: Primary model\n cluster_model: Clustering model\n fallback_model: Fallback model\n default_output: Default output directory\n max_tokens: Maximum tokens for LLM response\n max_token_per_module: Maximum tokens per module for clustering\n max_token_per_leaf_module: Maximum tokens per leaf module\n max_depth: Maximum depth for hierarchical decomposition\n provider: LLM provider type (openai-compatible, anthropic, bedrock, azure-openai)\n aws_region: AWS region for Bedrock provider\n api_version: Azure OpenAI API version\n azure_deployment: Azure OpenAI deployment name\n use_gitignore: Apply Git ignore rules during repository analysis\n prompt_caching: Add prompt-cache breakpoints to agentic LLM calls\n \"\"\"\n # Ensure config directory exists\n try:\n ensure_directory(CONFIG_DIR)\n except FileSystemError as e:\n raise ConfigurationError(f\"Cannot create config directory: {e}\")\n \n # Load existing config or create new\n if self._config is None:\n if CONFIG_FILE.exists():\n self.load()\n else:\n from codewiki.cli.models.config import AgentInstructions\n self._config = Configuration(\n base_url=\"\",\n main_model=\"\",\n cluster_model=\"\",\n fallback_model=\"glm-4p5\",\n default_output=\"docs\",\n agent_instructions=AgentInstructions()\n )\n \n # Update fields if provided\n if base_url is not None:\n self._config.base_url = base_url\n if main_model is not None:\n self._config.main_model = main_model\n if cluster_model is not None:\n self._config.cluster_model = cluster_model\n if fallback_model is not None:\n self._config.fallback_model = fallback_model\n if default_output is not None:\n self._config.default_output = default_output\n if max_tokens is not None:\n self._config.max_tokens = max_tokens\n if max_token_per_module is not None:\n self._config.max_token_per_module = max_token_per_module\n if max_token_per_leaf_module is not None:\n self._config.max_token_per_leaf_module = max_token_per_leaf_module\n if max_depth is not None:\n self._config.max_depth = max_depth\n if provider is not None:\n self._config.provider = provider\n if aws_region is not None:\n self._config.aws_region = aws_region\n if api_version is not None:\n self._config.api_version = api_version\n if azure_deployment is not None:\n self._config.azure_deployment = azure_deployment\n if use_gitignore is not None:\n self._config.use_gitignore = use_gitignore\n if prompt_caching is not None:\n self._config.prompt_caching = prompt_caching\n\n # Validate configuration whenever the minimum required fields are set.\n # Caw providers only need main_model; API providers need base_url +\n # cluster_model on top of that. The validate() method itself routes\n # by provider, so we only gate on whether enough is set to validate.\n from codewiki.src.be.backend import is_caw_provider\n if is_caw_provider(self._config.provider):\n if self._config.main_model:\n self._config.validate()\n elif self._config.base_url and self._config.main_model and self._config.cluster_model:\n self._config.validate()\n \n # Save API key to keyring, falling back to file\n if api_key is not None:\n self._api_key = api_key\n if self._keyring_available:\n try:\n keyring.set_password(KEYRING_SERVICE, KEYRING_API_KEY_ACCOUNT, api_key)\n except (KeyringError, Exception):\n # Keyring failed at runtime β€” fall back to file\n self._keyring_available = False\n self._save_api_key_to_file(api_key)\n logger.warning(\n \"System keychain unavailable. API key stored in %s \"\n \"(plaintext). Set CODEWIKI_NO_KEYRING=1 to suppress this warning.\",\n CREDENTIALS_FILE\n )\n else:\n self._save_api_key_to_file(api_key)\n \n # Save non-sensitive config to JSON\n config_data = {\n \"version\": CONFIG_VERSION,\n **self._config.to_dict()\n }\n \n try:\n safe_write(CONFIG_FILE, json.dumps(config_data, indent=2))\n except FileSystemError as e:\n raise ConfigurationError(f\"Failed to save configuration: {e}\")\n \n def get_api_key(self) -> Optional[str]:\n \"\"\"\n Get API key from keyring or fallback file.\n\n Returns:\n API key or None if not set\n \"\"\"\n if self._api_key is None:\n if self._keyring_available:\n try:\n self._api_key = keyring.get_password(KEYRING_SERVICE, KEYRING_API_KEY_ACCOUNT)\n except (KeyringError, Exception):\n pass\n if self._api_key is None:\n self._api_key = self._load_api_key_from_file()\n\n return self._api_key\n \n def get_config(self) -> Optional[Configuration]:\n \"\"\"\n Get current configuration.\n \n Returns:\n Configuration object or None if not loaded\n \"\"\"\n return self._config\n \n def is_configured(self) -> bool:\n \"\"\"\n Check if configuration is complete and valid.\n\n Subscription-mode providers (claude-code, codex) do not require an\n API key β€” they authenticate via the underlying CLI's OAuth.\n\n Returns:\n True if configured, False otherwise\n \"\"\"\n if self._config is None:\n return False\n\n from codewiki.src.be.backend import is_caw_provider\n if not is_caw_provider(self._config.provider):\n # Check if API key is set\n if self.get_api_key() is None:\n return False\n\n # Check if config is complete\n return self._config.is_complete()\n \n def delete_api_key(self):\n \"\"\"Delete API key from keyring and fallback file.\"\"\"\n if self._keyring_available:\n try:\n keyring.delete_password(KEYRING_SERVICE, KEYRING_API_KEY_ACCOUNT)\n except (KeyringError, Exception):\n pass\n # Also remove fallback credentials file\n if CREDENTIALS_FILE.exists():\n try:\n CREDENTIALS_FILE.unlink()\n except OSError:\n pass\n self._api_key = None\n \n def clear(self):\n \"\"\"Clear all configuration (file and keyring).\"\"\"\n # Delete API key from keyring\n self.delete_api_key()\n \n # Delete config file\n if CONFIG_FILE.exists():\n CONFIG_FILE.unlink()\n \n self._config = None\n self._api_key = None\n \n @property\n def keyring_available(self) -> bool:\n \"\"\"Check if keyring is available.\"\"\"\n return self._keyring_available\n \n @property\n def config_file_path(self) -> Path:\n \"\"\"Get configuration file path.\"\"\"\n return CONFIG_FILE", - "start_line": 34, - "end_line": 340, - "has_docstring": true, - "docstring": "Manages CodeWiki configuration with secure keyring storage for API keys.\n\nStorage:\n - API key: System keychain via keyring (macOS Keychain, Windows Credential Manager,\n Linux Secret Service)\n - Fallback: ~/.codewiki/credentials.json when keyring is unavailable\n - Other settings: ~/.codewiki/config.json\n\nSet CODEWIKI_NO_KEYRING=1 to skip keyring and use file-based storage.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class ConfigManager", - "component_id": "codewiki/cli/config_manager.py::ConfigManager", - "language": null, - "qualified_name": null - }, - "codewiki/cli/config_manager.py::ConfigManager.__init__": { - "id": "codewiki/cli/config_manager.py::ConfigManager.__init__", - "name": "ConfigManager.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/config_manager.py", - "relative_path": "codewiki/cli/config_manager.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/cli/config_manager.py::ConfigManager._check_keyring_available" - ], - "source_code": " def __init__(self):\n \"\"\"Initialize the configuration manager.\"\"\"\n self._api_key: Optional[str] = None\n self._config: Optional[Configuration] = None\n self._force_no_keyring = os.environ.get(\"CODEWIKI_NO_KEYRING\", \"\").strip() in (\"1\", \"true\", \"yes\")\n self._keyring_available = self._check_keyring_available()", - "start_line": 47, - "end_line": 52, - "has_docstring": true, - "docstring": "Initialize the configuration manager.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ConfigManager", - "display_name": "method ConfigManager.__init__", - "component_id": "codewiki/cli/config_manager.py::ConfigManager.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/cli/config_manager.py::ConfigManager._check_keyring_available": { - "id": "codewiki/cli/config_manager.py::ConfigManager._check_keyring_available", - "name": "ConfigManager._check_keyring_available", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/config_manager.py", - "relative_path": "codewiki/cli/config_manager.py", - "depends_on": [ - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": " def _check_keyring_available(self) -> bool:\n \"\"\"Check if system keyring is available.\"\"\"\n if self._force_no_keyring:\n logger.debug(\"Keyring disabled via CODEWIKI_NO_KEYRING\")\n return False\n try:\n # Try to get/set a test value\n keyring.get_password(KEYRING_SERVICE, \"__test__\")\n return True\n except (KeyringError, Exception):\n return False", - "start_line": 54, - "end_line": 64, - "has_docstring": true, - "docstring": "Check if system keyring is available.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ConfigManager", - "display_name": "method ConfigManager._check_keyring_available", - "component_id": "codewiki/cli/config_manager.py::ConfigManager._check_keyring_available", - "language": null, - "qualified_name": null - }, - "codewiki/cli/config_manager.py::ConfigManager._load_api_key_from_file": { - "id": "codewiki/cli/config_manager.py::ConfigManager._load_api_key_from_file", - "name": "ConfigManager._load_api_key_from_file", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/config_manager.py", - "relative_path": "codewiki/cli/config_manager.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/cli/utils/fs.py::safe_read" - ], - "source_code": " def _load_api_key_from_file(self) -> Optional[str]:\n \"\"\"Load API key from fallback credentials file.\"\"\"\n if not CREDENTIALS_FILE.exists():\n return None\n try:\n content = safe_read(CREDENTIALS_FILE)\n data = json.loads(content)\n return data.get(\"api_key\")\n except (json.JSONDecodeError, FileSystemError):\n return None", - "start_line": 66, - "end_line": 75, - "has_docstring": true, - "docstring": "Load API key from fallback credentials file.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ConfigManager", - "display_name": "method ConfigManager._load_api_key_from_file", - "component_id": "codewiki/cli/config_manager.py::ConfigManager._load_api_key_from_file", - "language": null, - "qualified_name": null - }, - "codewiki/cli/config_manager.py::ConfigManager._save_api_key_to_file": { - "id": "codewiki/cli/config_manager.py::ConfigManager._save_api_key_to_file", - "name": "ConfigManager._save_api_key_to_file", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/config_manager.py", - "relative_path": "codewiki/cli/config_manager.py", - "depends_on": [ - "codewiki/cli/utils/fs.py::safe_write", - "codewiki/cli/utils/fs.py::ensure_directory" - ], - "source_code": " def _save_api_key_to_file(self, api_key: str):\n \"\"\"Save API key to fallback credentials file (plaintext).\"\"\"\n ensure_directory(CONFIG_DIR)\n data = {\"api_key\": api_key}\n safe_write(CREDENTIALS_FILE, json.dumps(data, indent=2))\n # Restrict file permissions (owner read/write only)\n try:\n CREDENTIALS_FILE.chmod(0o600)\n except OSError:\n pass", - "start_line": 77, - "end_line": 86, - "has_docstring": true, - "docstring": "Save API key to fallback credentials file (plaintext).", - "parameters": [ - "self", - "api_key" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ConfigManager", - "display_name": "method ConfigManager._save_api_key_to_file", - "component_id": "codewiki/cli/config_manager.py::ConfigManager._save_api_key_to_file", - "language": null, - "qualified_name": null - }, - "codewiki/cli/config_manager.py::ConfigManager.load": { - "id": "codewiki/cli/config_manager.py::ConfigManager.load", - "name": "ConfigManager.load", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/config_manager.py", - "relative_path": "codewiki/cli/config_manager.py", - "depends_on": [ - "codewiki/cli/config_manager.py::ConfigManager._load_api_key_from_file", - "codewiki/cli/utils/fs.py::safe_read", - "codewiki/cli/utils/errors.py::ConfigurationError", - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/cli/models/config.py::Configuration.from_dict" - ], - "source_code": " def load(self) -> bool:\n \"\"\"\n Load configuration from file and keyring.\n \n Returns:\n True if configuration exists, False otherwise\n \"\"\"\n # Load from JSON file\n if not CONFIG_FILE.exists():\n return False\n \n try:\n content = safe_read(CONFIG_FILE)\n data = json.loads(content)\n \n # Validate version\n if data.get('version') != CONFIG_VERSION:\n # Could implement migration here\n pass\n \n self._config = Configuration.from_dict(data)\n \n # Load API key from keyring, falling back to file\n if self._keyring_available:\n try:\n self._api_key = keyring.get_password(KEYRING_SERVICE, KEYRING_API_KEY_ACCOUNT)\n except (KeyringError, Exception):\n pass\n if self._api_key is None:\n self._api_key = self._load_api_key_from_file()\n \n return True\n except (json.JSONDecodeError, FileSystemError) as e:\n raise ConfigurationError(f\"Failed to load configuration: {e}\")", - "start_line": 88, - "end_line": 121, - "has_docstring": true, - "docstring": "Load configuration from file and keyring.\n\nReturns:\n True if configuration exists, False otherwise", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ConfigManager", - "display_name": "method ConfigManager.load", - "component_id": "codewiki/cli/config_manager.py::ConfigManager.load", - "language": null, - "qualified_name": null - }, - "codewiki/cli/config_manager.py::ConfigManager.save": { - "id": "codewiki/cli/config_manager.py::ConfigManager.save", - "name": "ConfigManager.save", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/config_manager.py", - "relative_path": "codewiki/cli/config_manager.py", - "depends_on": [ - "codewiki/cli/utils/errors.py::ConfigurationError", - "codewiki/cli/config_manager.py::ConfigManager._save_api_key_to_file", - "codewiki/cli/models/config.py::AgentInstructions", - "codewiki/src/be/backend.py::is_caw_provider", - "codewiki/cli/utils/fs.py::safe_write", - "codewiki/cli/models/config.py::Configuration", - "codewiki/cli/utils/fs.py::ensure_directory", - "codewiki/cli/models/config.py::Configuration.validate", - "codewiki/cli/config_manager.py::ConfigManager.load" - ], - "source_code": " def save(\n self,\n api_key: Optional[str] = None,\n base_url: Optional[str] = None,\n main_model: Optional[str] = None,\n cluster_model: Optional[str] = None,\n fallback_model: Optional[str] = None,\n default_output: Optional[str] = None,\n max_tokens: Optional[int] = None,\n max_token_per_module: Optional[int] = None,\n max_token_per_leaf_module: Optional[int] = None,\n max_depth: Optional[int] = None,\n provider: Optional[str] = None,\n aws_region: Optional[str] = None,\n api_version: Optional[str] = None,\n azure_deployment: Optional[str] = None,\n use_gitignore: Optional[bool] = None,\n prompt_caching: Optional[bool] = None,\n ):\n \"\"\"\n Save configuration to file and keyring.\n\n Args:\n api_key: API key (stored in keyring)\n base_url: LLM API base URL\n main_model: Primary model\n cluster_model: Clustering model\n fallback_model: Fallback model\n default_output: Default output directory\n max_tokens: Maximum tokens for LLM response\n max_token_per_module: Maximum tokens per module for clustering\n max_token_per_leaf_module: Maximum tokens per leaf module\n max_depth: Maximum depth for hierarchical decomposition\n provider: LLM provider type (openai-compatible, anthropic, bedrock, azure-openai)\n aws_region: AWS region for Bedrock provider\n api_version: Azure OpenAI API version\n azure_deployment: Azure OpenAI deployment name\n use_gitignore: Apply Git ignore rules during repository analysis\n prompt_caching: Add prompt-cache breakpoints to agentic LLM calls\n \"\"\"\n # Ensure config directory exists\n try:\n ensure_directory(CONFIG_DIR)\n except FileSystemError as e:\n raise ConfigurationError(f\"Cannot create config directory: {e}\")\n \n # Load existing config or create new\n if self._config is None:\n if CONFIG_FILE.exists():\n self.load()\n else:\n from codewiki.cli.models.config import AgentInstructions\n self._config = Configuration(\n base_url=\"\",\n main_model=\"\",\n cluster_model=\"\",\n fallback_model=\"glm-4p5\",\n default_output=\"docs\",\n agent_instructions=AgentInstructions()\n )\n \n # Update fields if provided\n if base_url is not None:\n self._config.base_url = base_url\n if main_model is not None:\n self._config.main_model = main_model\n if cluster_model is not None:\n self._config.cluster_model = cluster_model\n if fallback_model is not None:\n self._config.fallback_model = fallback_model\n if default_output is not None:\n self._config.default_output = default_output\n if max_tokens is not None:\n self._config.max_tokens = max_tokens\n if max_token_per_module is not None:\n self._config.max_token_per_module = max_token_per_module\n if max_token_per_leaf_module is not None:\n self._config.max_token_per_leaf_module = max_token_per_leaf_module\n if max_depth is not None:\n self._config.max_depth = max_depth\n if provider is not None:\n self._config.provider = provider\n if aws_region is not None:\n self._config.aws_region = aws_region\n if api_version is not None:\n self._config.api_version = api_version\n if azure_deployment is not None:\n self._config.azure_deployment = azure_deployment\n if use_gitignore is not None:\n self._config.use_gitignore = use_gitignore\n if prompt_caching is not None:\n self._config.prompt_caching = prompt_caching\n\n # Validate configuration whenever the minimum required fields are set.\n # Caw providers only need main_model; API providers need base_url +\n # cluster_model on top of that. The validate() method itself routes\n # by provider, so we only gate on whether enough is set to validate.\n from codewiki.src.be.backend import is_caw_provider\n if is_caw_provider(self._config.provider):\n if self._config.main_model:\n self._config.validate()\n elif self._config.base_url and self._config.main_model and self._config.cluster_model:\n self._config.validate()\n \n # Save API key to keyring, falling back to file\n if api_key is not None:\n self._api_key = api_key\n if self._keyring_available:\n try:\n keyring.set_password(KEYRING_SERVICE, KEYRING_API_KEY_ACCOUNT, api_key)\n except (KeyringError, Exception):\n # Keyring failed at runtime β€” fall back to file\n self._keyring_available = False\n self._save_api_key_to_file(api_key)\n logger.warning(\n \"System keychain unavailable. API key stored in %s \"\n \"(plaintext). Set CODEWIKI_NO_KEYRING=1 to suppress this warning.\",\n CREDENTIALS_FILE\n )\n else:\n self._save_api_key_to_file(api_key)\n \n # Save non-sensitive config to JSON\n config_data = {\n \"version\": CONFIG_VERSION,\n **self._config.to_dict()\n }\n \n try:\n safe_write(CONFIG_FILE, json.dumps(config_data, indent=2))\n except FileSystemError as e:\n raise ConfigurationError(f\"Failed to save configuration: {e}\")", - "start_line": 123, - "end_line": 254, - "has_docstring": true, - "docstring": "Save configuration to file and keyring.\n\nArgs:\n api_key: API key (stored in keyring)\n base_url: LLM API base URL\n main_model: Primary model\n cluster_model: Clustering model\n fallback_model: Fallback model\n default_output: Default output directory\n max_tokens: Maximum tokens for LLM response\n max_token_per_module: Maximum tokens per module for clustering\n max_token_per_leaf_module: Maximum tokens per leaf module\n max_depth: Maximum depth for hierarchical decomposition\n provider: LLM provider type (openai-compatible, anthropic, bedrock, azure-openai)\n aws_region: AWS region for Bedrock provider\n api_version: Azure OpenAI API version\n azure_deployment: Azure OpenAI deployment name\n use_gitignore: Apply Git ignore rules during repository analysis\n prompt_caching: Add prompt-cache breakpoints to agentic LLM calls", - "parameters": [ - "self", - "api_key", - "base_url", - "main_model", - "cluster_model", - "fallback_model", - "default_output", - "max_tokens", - "max_token_per_module", - "max_token_per_leaf_module", - "max_depth", - "provider", - "aws_region", - "api_version", - "azure_deployment", - "use_gitignore", - "prompt_caching" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ConfigManager", - "display_name": "method ConfigManager.save", - "component_id": "codewiki/cli/config_manager.py::ConfigManager.save", - "language": null, - "qualified_name": null - }, - "codewiki/cli/config_manager.py::ConfigManager.get_api_key": { - "id": "codewiki/cli/config_manager.py::ConfigManager.get_api_key", - "name": "ConfigManager.get_api_key", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/config_manager.py", - "relative_path": "codewiki/cli/config_manager.py", - "depends_on": [ - "codewiki/cli/config_manager.py::ConfigManager._load_api_key_from_file" - ], - "source_code": " def get_api_key(self) -> Optional[str]:\n \"\"\"\n Get API key from keyring or fallback file.\n\n Returns:\n API key or None if not set\n \"\"\"\n if self._api_key is None:\n if self._keyring_available:\n try:\n self._api_key = keyring.get_password(KEYRING_SERVICE, KEYRING_API_KEY_ACCOUNT)\n except (KeyringError, Exception):\n pass\n if self._api_key is None:\n self._api_key = self._load_api_key_from_file()\n\n return self._api_key", - "start_line": 256, - "end_line": 272, - "has_docstring": true, - "docstring": "Get API key from keyring or fallback file.\n\nReturns:\n API key or None if not set", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ConfigManager", - "display_name": "method ConfigManager.get_api_key", - "component_id": "codewiki/cli/config_manager.py::ConfigManager.get_api_key", - "language": null, - "qualified_name": null - }, - "codewiki/cli/config_manager.py::ConfigManager.get_config": { - "id": "codewiki/cli/config_manager.py::ConfigManager.get_config", - "name": "ConfigManager.get_config", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/config_manager.py", - "relative_path": "codewiki/cli/config_manager.py", - "depends_on": [], - "source_code": " def get_config(self) -> Optional[Configuration]:\n \"\"\"\n Get current configuration.\n \n Returns:\n Configuration object or None if not loaded\n \"\"\"\n return self._config", - "start_line": 274, - "end_line": 281, - "has_docstring": true, - "docstring": "Get current configuration.\n\nReturns:\n Configuration object or None if not loaded", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ConfigManager", - "display_name": "method ConfigManager.get_config", - "component_id": "codewiki/cli/config_manager.py::ConfigManager.get_config", - "language": null, - "qualified_name": null - }, - "codewiki/cli/config_manager.py::ConfigManager.is_configured": { - "id": "codewiki/cli/config_manager.py::ConfigManager.is_configured", - "name": "ConfigManager.is_configured", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/config_manager.py", - "relative_path": "codewiki/cli/config_manager.py", - "depends_on": [ - "codewiki/cli/config_manager.py::ConfigManager.get_api_key", - "codewiki/cli/models/config.py::Configuration.is_complete", - "codewiki/src/be/backend.py::is_caw_provider" - ], - "source_code": " def is_configured(self) -> bool:\n \"\"\"\n Check if configuration is complete and valid.\n\n Subscription-mode providers (claude-code, codex) do not require an\n API key β€” they authenticate via the underlying CLI's OAuth.\n\n Returns:\n True if configured, False otherwise\n \"\"\"\n if self._config is None:\n return False\n\n from codewiki.src.be.backend import is_caw_provider\n if not is_caw_provider(self._config.provider):\n # Check if API key is set\n if self.get_api_key() is None:\n return False\n\n # Check if config is complete\n return self._config.is_complete()", - "start_line": 283, - "end_line": 303, - "has_docstring": true, - "docstring": "Check if configuration is complete and valid.\n\nSubscription-mode providers (claude-code, codex) do not require an\nAPI key β€” they authenticate via the underlying CLI's OAuth.\n\nReturns:\n True if configured, False otherwise", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ConfigManager", - "display_name": "method ConfigManager.is_configured", - "component_id": "codewiki/cli/config_manager.py::ConfigManager.is_configured", - "language": null, - "qualified_name": null - }, - "codewiki/cli/config_manager.py::ConfigManager.delete_api_key": { - "id": "codewiki/cli/config_manager.py::ConfigManager.delete_api_key", - "name": "ConfigManager.delete_api_key", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/config_manager.py", - "relative_path": "codewiki/cli/config_manager.py", - "depends_on": [], - "source_code": " def delete_api_key(self):\n \"\"\"Delete API key from keyring and fallback file.\"\"\"\n if self._keyring_available:\n try:\n keyring.delete_password(KEYRING_SERVICE, KEYRING_API_KEY_ACCOUNT)\n except (KeyringError, Exception):\n pass\n # Also remove fallback credentials file\n if CREDENTIALS_FILE.exists():\n try:\n CREDENTIALS_FILE.unlink()\n except OSError:\n pass\n self._api_key = None", - "start_line": 305, - "end_line": 318, - "has_docstring": true, - "docstring": "Delete API key from keyring and fallback file.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ConfigManager", - "display_name": "method ConfigManager.delete_api_key", - "component_id": "codewiki/cli/config_manager.py::ConfigManager.delete_api_key", - "language": null, - "qualified_name": null - }, - "codewiki/cli/config_manager.py::ConfigManager.clear": { - "id": "codewiki/cli/config_manager.py::ConfigManager.clear", - "name": "ConfigManager.clear", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/config_manager.py", - "relative_path": "codewiki/cli/config_manager.py", - "depends_on": [ - "codewiki/cli/config_manager.py::ConfigManager.delete_api_key" - ], - "source_code": " def clear(self):\n \"\"\"Clear all configuration (file and keyring).\"\"\"\n # Delete API key from keyring\n self.delete_api_key()\n \n # Delete config file\n if CONFIG_FILE.exists():\n CONFIG_FILE.unlink()\n \n self._config = None\n self._api_key = None", - "start_line": 320, - "end_line": 330, - "has_docstring": true, - "docstring": "Clear all configuration (file and keyring).", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ConfigManager", - "display_name": "method ConfigManager.clear", - "component_id": "codewiki/cli/config_manager.py::ConfigManager.clear", - "language": null, - "qualified_name": null - }, - "codewiki/cli/config_manager.py::ConfigManager.keyring_available": { - "id": "codewiki/cli/config_manager.py::ConfigManager.keyring_available", - "name": "ConfigManager.keyring_available", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/config_manager.py", - "relative_path": "codewiki/cli/config_manager.py", - "depends_on": [], - "source_code": " def keyring_available(self) -> bool:\n \"\"\"Check if keyring is available.\"\"\"\n return self._keyring_available", - "start_line": 333, - "end_line": 335, - "has_docstring": true, - "docstring": "Check if keyring is available.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ConfigManager", - "display_name": "method ConfigManager.keyring_available", - "component_id": "codewiki/cli/config_manager.py::ConfigManager.keyring_available", - "language": null, - "qualified_name": null - }, - "codewiki/cli/config_manager.py::ConfigManager.config_file_path": { - "id": "codewiki/cli/config_manager.py::ConfigManager.config_file_path", - "name": "ConfigManager.config_file_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/config_manager.py", - "relative_path": "codewiki/cli/config_manager.py", - "depends_on": [], - "source_code": " def config_file_path(self) -> Path:\n \"\"\"Get configuration file path.\"\"\"\n return CONFIG_FILE", - "start_line": 338, - "end_line": 340, - "has_docstring": true, - "docstring": "Get configuration file path.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ConfigManager", - "display_name": "method ConfigManager.config_file_path", - "component_id": "codewiki/cli/config_manager.py::ConfigManager.config_file_path", - "language": null, - "qualified_name": null - }, - "codewiki/cli/git_manager.py::GitManager": { - "id": "codewiki/cli/git_manager.py::GitManager", - "name": "GitManager", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/git_manager.py", - "relative_path": "codewiki/cli/git_manager.py", - "depends_on": [], - "source_code": "class GitManager:\n \"\"\"\n Manages git operations for documentation generation.\n \n Handles:\n - Status checking\n - Branch creation\n - Committing documentation\n - Remote detection\n \"\"\"\n \n def __init__(self, repo_path: Path):\n \"\"\"\n Initialize git manager.\n \n Args:\n repo_path: Path to git repository\n \n Raises:\n RepositoryError: If not a valid git repository\n \"\"\"\n self.repo_path = Path(repo_path).expanduser().resolve()\n \n try:\n self.repo = git.Repo(repo_path, search_parent_directories=True)\n except git.InvalidGitRepositoryError:\n raise RepositoryError(\n f\"Not a git repository: {repo_path}\\n\\n\"\n \"To initialize a git repository: git init\"\n )\n \n def check_clean_working_directory(self) -> Tuple[bool, str]:\n \"\"\"\n Check if working directory is clean (no uncommitted changes).\n \n Returns:\n Tuple of (is_clean, status_message)\n \"\"\"\n if self.repo.is_dirty(untracked_files=True):\n status_lines = []\n \n # Changed files\n changed = [item.a_path for item in self.repo.index.diff(None)]\n if changed:\n status_lines.append(f\"Modified: {', '.join(changed[:3])}\")\n if len(changed) > 3:\n status_lines.append(f\"... and {len(changed) - 3} more\")\n \n # Untracked files\n untracked = self.repo.untracked_files\n if untracked:\n status_lines.append(f\"Untracked: {', '.join(untracked[:3])}\")\n if len(untracked) > 3:\n status_lines.append(f\"... and {len(untracked) - 3} more\")\n \n return False, \"\\n\".join(status_lines)\n \n return True, \"Working directory is clean\"\n \n def create_documentation_branch(self, force: bool = False) -> str:\n \"\"\"\n Create a new documentation branch with timestamp.\n \n Args:\n force: Force creation even if dirty working directory\n \n Returns:\n Branch name\n \n Raises:\n RepositoryError: If working directory is dirty (unless force=True)\n \"\"\"\n # Check working directory\n if not force:\n is_clean, status_msg = self.check_clean_working_directory()\n if not is_clean:\n raise RepositoryError(\n \"Working directory has uncommitted changes.\\n\\n\"\n f\"{status_msg}\\n\\n\"\n \"Cannot create documentation branch with uncommitted changes.\\n\"\n \"Please commit or stash your changes first:\\n\"\n \" git status\\n\"\n \" git add -A && git commit -m \\\"Your message\\\"\\n\"\n \" # or\\n\"\n \" git stash\\n\\n\"\n \"Then re-run: codewiki generate --create-branch\"\n )\n \n # Generate branch name with timestamp\n timestamp = datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n branch_name = f\"docs/codewiki-{timestamp}\"\n \n # Check if branch already exists (shouldn't happen with timestamp)\n existing_branches = [b.name for b in self.repo.branches]\n if branch_name in existing_branches:\n # Append counter\n counter = 1\n while f\"{branch_name}-{counter}\" in existing_branches:\n counter += 1\n branch_name = f\"{branch_name}-{counter}\"\n \n try:\n # Create and checkout new branch\n new_branch = self.repo.create_head(branch_name)\n new_branch.checkout()\n return branch_name\n except GitCommandError as e:\n raise RepositoryError(f\"Failed to create branch: {e}\")\n \n def commit_documentation(\n self,\n docs_path: Path,\n message: Optional[str] = None\n ) -> str:\n \"\"\"\n Commit generated documentation.\n \n Args:\n docs_path: Path to documentation directory\n message: Commit message (optional)\n \n Returns:\n Commit hash\n \n Raises:\n RepositoryError: If commit fails\n \"\"\"\n if message is None:\n message = \"Add generated documentation\\n\\nGenerated by CodeWiki CLI\"\n \n try:\n # Add documentation files\n self.repo.index.add([str(docs_path)])\n \n # Commit\n commit = self.repo.index.commit(message)\n \n return commit.hexsha\n except GitCommandError as e:\n raise RepositoryError(f\"Failed to commit documentation: {e}\")\n \n def get_remote_url(self, remote_name: str = \"origin\") -> Optional[str]:\n \"\"\"\n Get remote repository URL.\n \n Args:\n remote_name: Name of remote (default: origin)\n \n Returns:\n Remote URL or None if no remote\n \"\"\"\n try:\n remote = self.repo.remote(remote_name)\n return remote.url\n except ValueError:\n return None\n \n def get_current_branch(self) -> str:\n \"\"\"\n Get current branch name.\n \n Returns:\n Branch name\n \"\"\"\n try:\n return self.repo.active_branch.name\n except TypeError:\n # Detached HEAD\n return \"HEAD\"\n \n def get_commit_hash(self) -> str:\n \"\"\"\n Get current commit hash.\n \n Returns:\n Commit hash\n \"\"\"\n return self.repo.head.commit.hexsha\n \n def branch_exists(self, branch_name: str) -> bool:\n \"\"\"\n Check if a branch exists.\n \n Args:\n branch_name: Branch name to check\n \n Returns:\n True if exists, False otherwise\n \"\"\"\n return branch_name in [b.name for b in self.repo.branches]\n \n def get_github_pr_url(self, branch_name: str) -> Optional[str]:\n \"\"\"\n Get GitHub PR creation URL for a branch.\n \n Args:\n branch_name: Branch name\n \n Returns:\n PR URL or None if not a GitHub repo\n \"\"\"\n remote_url = self.get_remote_url()\n if not remote_url or \"github.com\" not in remote_url:\n return None\n \n # Clean URL\n base_url = remote_url.rstrip('/').replace('.git', '')\n \n # Convert SSH to HTTPS\n if base_url.startswith('git@github.com:'):\n base_url = base_url.replace('git@github.com:', 'https://github.com/')\n \n return f\"{base_url}/compare/{branch_name}\"", - "start_line": 14, - "end_line": 226, - "has_docstring": true, - "docstring": "Manages git operations for documentation generation.\n\nHandles:\n- Status checking\n- Branch creation\n- Committing documentation\n- Remote detection", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class GitManager", - "component_id": "codewiki/cli/git_manager.py::GitManager", - "language": null, - "qualified_name": null - }, - "codewiki/cli/git_manager.py::GitManager.__init__": { - "id": "codewiki/cli/git_manager.py::GitManager.__init__", - "name": "GitManager.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/git_manager.py", - "relative_path": "codewiki/cli/git_manager.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/cli/utils/errors.py::RepositoryError" - ], - "source_code": " def __init__(self, repo_path: Path):\n \"\"\"\n Initialize git manager.\n \n Args:\n repo_path: Path to git repository\n \n Raises:\n RepositoryError: If not a valid git repository\n \"\"\"\n self.repo_path = Path(repo_path).expanduser().resolve()\n \n try:\n self.repo = git.Repo(repo_path, search_parent_directories=True)\n except git.InvalidGitRepositoryError:\n raise RepositoryError(\n f\"Not a git repository: {repo_path}\\n\\n\"\n \"To initialize a git repository: git init\"\n )", - "start_line": 25, - "end_line": 43, - "has_docstring": true, - "docstring": "Initialize git manager.\n\nArgs:\n repo_path: Path to git repository\n \nRaises:\n RepositoryError: If not a valid git repository", - "parameters": [ - "self", - "repo_path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "GitManager", - "display_name": "method GitManager.__init__", - "component_id": "codewiki/cli/git_manager.py::GitManager.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/cli/git_manager.py::GitManager.check_clean_working_directory": { - "id": "codewiki/cli/git_manager.py::GitManager.check_clean_working_directory", - "name": "GitManager.check_clean_working_directory", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/git_manager.py", - "relative_path": "codewiki/cli/git_manager.py", - "depends_on": [], - "source_code": " def check_clean_working_directory(self) -> Tuple[bool, str]:\n \"\"\"\n Check if working directory is clean (no uncommitted changes).\n \n Returns:\n Tuple of (is_clean, status_message)\n \"\"\"\n if self.repo.is_dirty(untracked_files=True):\n status_lines = []\n \n # Changed files\n changed = [item.a_path for item in self.repo.index.diff(None)]\n if changed:\n status_lines.append(f\"Modified: {', '.join(changed[:3])}\")\n if len(changed) > 3:\n status_lines.append(f\"... and {len(changed) - 3} more\")\n \n # Untracked files\n untracked = self.repo.untracked_files\n if untracked:\n status_lines.append(f\"Untracked: {', '.join(untracked[:3])}\")\n if len(untracked) > 3:\n status_lines.append(f\"... and {len(untracked) - 3} more\")\n \n return False, \"\\n\".join(status_lines)\n \n return True, \"Working directory is clean\"", - "start_line": 45, - "end_line": 71, - "has_docstring": true, - "docstring": "Check if working directory is clean (no uncommitted changes).\n\nReturns:\n Tuple of (is_clean, status_message)", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "GitManager", - "display_name": "method GitManager.check_clean_working_directory", - "component_id": "codewiki/cli/git_manager.py::GitManager.check_clean_working_directory", - "language": null, - "qualified_name": null - }, - "codewiki/cli/git_manager.py::GitManager.create_documentation_branch": { - "id": "codewiki/cli/git_manager.py::GitManager.create_documentation_branch", - "name": "GitManager.create_documentation_branch", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/git_manager.py", - "relative_path": "codewiki/cli/git_manager.py", - "depends_on": [ - "codewiki/cli/git_manager.py::GitManager.check_clean_working_directory", - "codewiki/cli/utils/errors.py::RepositoryError" - ], - "source_code": " def create_documentation_branch(self, force: bool = False) -> str:\n \"\"\"\n Create a new documentation branch with timestamp.\n \n Args:\n force: Force creation even if dirty working directory\n \n Returns:\n Branch name\n \n Raises:\n RepositoryError: If working directory is dirty (unless force=True)\n \"\"\"\n # Check working directory\n if not force:\n is_clean, status_msg = self.check_clean_working_directory()\n if not is_clean:\n raise RepositoryError(\n \"Working directory has uncommitted changes.\\n\\n\"\n f\"{status_msg}\\n\\n\"\n \"Cannot create documentation branch with uncommitted changes.\\n\"\n \"Please commit or stash your changes first:\\n\"\n \" git status\\n\"\n \" git add -A && git commit -m \\\"Your message\\\"\\n\"\n \" # or\\n\"\n \" git stash\\n\\n\"\n \"Then re-run: codewiki generate --create-branch\"\n )\n \n # Generate branch name with timestamp\n timestamp = datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n branch_name = f\"docs/codewiki-{timestamp}\"\n \n # Check if branch already exists (shouldn't happen with timestamp)\n existing_branches = [b.name for b in self.repo.branches]\n if branch_name in existing_branches:\n # Append counter\n counter = 1\n while f\"{branch_name}-{counter}\" in existing_branches:\n counter += 1\n branch_name = f\"{branch_name}-{counter}\"\n \n try:\n # Create and checkout new branch\n new_branch = self.repo.create_head(branch_name)\n new_branch.checkout()\n return branch_name\n except GitCommandError as e:\n raise RepositoryError(f\"Failed to create branch: {e}\")", - "start_line": 73, - "end_line": 121, - "has_docstring": true, - "docstring": "Create a new documentation branch with timestamp.\n\nArgs:\n force: Force creation even if dirty working directory\n \nReturns:\n Branch name\n \nRaises:\n RepositoryError: If working directory is dirty (unless force=True)", - "parameters": [ - "self", - "force" - ], - "node_type": "method", - "base_classes": null, - "class_name": "GitManager", - "display_name": "method GitManager.create_documentation_branch", - "component_id": "codewiki/cli/git_manager.py::GitManager.create_documentation_branch", - "language": null, - "qualified_name": null - }, - "codewiki/cli/git_manager.py::GitManager.commit_documentation": { - "id": "codewiki/cli/git_manager.py::GitManager.commit_documentation", - "name": "GitManager.commit_documentation", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/git_manager.py", - "relative_path": "codewiki/cli/git_manager.py", - "depends_on": [ - "codewiki/cli/utils/errors.py::RepositoryError" - ], - "source_code": " def commit_documentation(\n self,\n docs_path: Path,\n message: Optional[str] = None\n ) -> str:\n \"\"\"\n Commit generated documentation.\n \n Args:\n docs_path: Path to documentation directory\n message: Commit message (optional)\n \n Returns:\n Commit hash\n \n Raises:\n RepositoryError: If commit fails\n \"\"\"\n if message is None:\n message = \"Add generated documentation\\n\\nGenerated by CodeWiki CLI\"\n \n try:\n # Add documentation files\n self.repo.index.add([str(docs_path)])\n \n # Commit\n commit = self.repo.index.commit(message)\n \n return commit.hexsha\n except GitCommandError as e:\n raise RepositoryError(f\"Failed to commit documentation: {e}\")", - "start_line": 123, - "end_line": 153, - "has_docstring": true, - "docstring": "Commit generated documentation.\n\nArgs:\n docs_path: Path to documentation directory\n message: Commit message (optional)\n \nReturns:\n Commit hash\n \nRaises:\n RepositoryError: If commit fails", - "parameters": [ - "self", - "docs_path", - "message" - ], - "node_type": "method", - "base_classes": null, - "class_name": "GitManager", - "display_name": "method GitManager.commit_documentation", - "component_id": "codewiki/cli/git_manager.py::GitManager.commit_documentation", - "language": null, - "qualified_name": null - }, - "codewiki/cli/git_manager.py::GitManager.get_remote_url": { - "id": "codewiki/cli/git_manager.py::GitManager.get_remote_url", - "name": "GitManager.get_remote_url", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/git_manager.py", - "relative_path": "codewiki/cli/git_manager.py", - "depends_on": [], - "source_code": " def get_remote_url(self, remote_name: str = \"origin\") -> Optional[str]:\n \"\"\"\n Get remote repository URL.\n \n Args:\n remote_name: Name of remote (default: origin)\n \n Returns:\n Remote URL or None if no remote\n \"\"\"\n try:\n remote = self.repo.remote(remote_name)\n return remote.url\n except ValueError:\n return None", - "start_line": 155, - "end_line": 169, - "has_docstring": true, - "docstring": "Get remote repository URL.\n\nArgs:\n remote_name: Name of remote (default: origin)\n \nReturns:\n Remote URL or None if no remote", - "parameters": [ - "self", - "remote_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "GitManager", - "display_name": "method GitManager.get_remote_url", - "component_id": "codewiki/cli/git_manager.py::GitManager.get_remote_url", - "language": null, - "qualified_name": null - }, - "codewiki/cli/git_manager.py::GitManager.get_current_branch": { - "id": "codewiki/cli/git_manager.py::GitManager.get_current_branch", - "name": "GitManager.get_current_branch", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/git_manager.py", - "relative_path": "codewiki/cli/git_manager.py", - "depends_on": [], - "source_code": " def get_current_branch(self) -> str:\n \"\"\"\n Get current branch name.\n \n Returns:\n Branch name\n \"\"\"\n try:\n return self.repo.active_branch.name\n except TypeError:\n # Detached HEAD\n return \"HEAD\"", - "start_line": 171, - "end_line": 182, - "has_docstring": true, - "docstring": "Get current branch name.\n\nReturns:\n Branch name", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "GitManager", - "display_name": "method GitManager.get_current_branch", - "component_id": "codewiki/cli/git_manager.py::GitManager.get_current_branch", - "language": null, - "qualified_name": null - }, - "codewiki/cli/git_manager.py::GitManager.get_commit_hash": { - "id": "codewiki/cli/git_manager.py::GitManager.get_commit_hash", - "name": "GitManager.get_commit_hash", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/git_manager.py", - "relative_path": "codewiki/cli/git_manager.py", - "depends_on": [], - "source_code": " def get_commit_hash(self) -> str:\n \"\"\"\n Get current commit hash.\n \n Returns:\n Commit hash\n \"\"\"\n return self.repo.head.commit.hexsha", - "start_line": 184, - "end_line": 191, - "has_docstring": true, - "docstring": "Get current commit hash.\n\nReturns:\n Commit hash", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "GitManager", - "display_name": "method GitManager.get_commit_hash", - "component_id": "codewiki/cli/git_manager.py::GitManager.get_commit_hash", - "language": null, - "qualified_name": null - }, - "codewiki/cli/git_manager.py::GitManager.branch_exists": { - "id": "codewiki/cli/git_manager.py::GitManager.branch_exists", - "name": "GitManager.branch_exists", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/git_manager.py", - "relative_path": "codewiki/cli/git_manager.py", - "depends_on": [], - "source_code": " def branch_exists(self, branch_name: str) -> bool:\n \"\"\"\n Check if a branch exists.\n \n Args:\n branch_name: Branch name to check\n \n Returns:\n True if exists, False otherwise\n \"\"\"\n return branch_name in [b.name for b in self.repo.branches]", - "start_line": 193, - "end_line": 203, - "has_docstring": true, - "docstring": "Check if a branch exists.\n\nArgs:\n branch_name: Branch name to check\n \nReturns:\n True if exists, False otherwise", - "parameters": [ - "self", - "branch_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "GitManager", - "display_name": "method GitManager.branch_exists", - "component_id": "codewiki/cli/git_manager.py::GitManager.branch_exists", - "language": null, - "qualified_name": null - }, - "codewiki/cli/git_manager.py::GitManager.get_github_pr_url": { - "id": "codewiki/cli/git_manager.py::GitManager.get_github_pr_url", - "name": "GitManager.get_github_pr_url", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/git_manager.py", - "relative_path": "codewiki/cli/git_manager.py", - "depends_on": [ - "codewiki/cli/git_manager.py::GitManager.get_remote_url" - ], - "source_code": " def get_github_pr_url(self, branch_name: str) -> Optional[str]:\n \"\"\"\n Get GitHub PR creation URL for a branch.\n \n Args:\n branch_name: Branch name\n \n Returns:\n PR URL or None if not a GitHub repo\n \"\"\"\n remote_url = self.get_remote_url()\n if not remote_url or \"github.com\" not in remote_url:\n return None\n \n # Clean URL\n base_url = remote_url.rstrip('/').replace('.git', '')\n \n # Convert SSH to HTTPS\n if base_url.startswith('git@github.com:'):\n base_url = base_url.replace('git@github.com:', 'https://github.com/')\n \n return f\"{base_url}/compare/{branch_name}\"", - "start_line": 205, - "end_line": 226, - "has_docstring": true, - "docstring": "Get GitHub PR creation URL for a branch.\n\nArgs:\n branch_name: Branch name\n \nReturns:\n PR URL or None if not a GitHub repo", - "parameters": [ - "self", - "branch_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "GitManager", - "display_name": "method GitManager.get_github_pr_url", - "component_id": "codewiki/cli/git_manager.py::GitManager.get_github_pr_url", - "language": null, - "qualified_name": null - }, - "codewiki/cli/html_generator.py::HTMLGenerator": { - "id": "codewiki/cli/html_generator.py::HTMLGenerator", - "name": "HTMLGenerator", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/html_generator.py", - "relative_path": "codewiki/cli/html_generator.py", - "depends_on": [], - "source_code": "class HTMLGenerator:\n \"\"\"\n Generates static HTML documentation viewer for GitHub Pages.\n \n Creates a self-contained index.html with embedded styles, scripts,\n and configuration for client-side markdown rendering.\n \"\"\"\n \n def __init__(self, template_dir: Optional[Path] = None):\n \"\"\"\n Initialize HTML generator.\n \n Args:\n template_dir: Path to template directory (default: package templates)\n \"\"\"\n if template_dir is None:\n # Use package templates\n template_dir = Path(__file__).parent.parent / \"templates\" / \"github_pages\"\n \n self.template_dir = Path(template_dir)\n \n \n def load_module_tree(self, docs_dir: Path) -> Dict[str, Any]:\n \"\"\"\n Load module tree from documentation directory.\n \n Args:\n docs_dir: Documentation directory path\n \n Returns:\n Module tree structure\n \"\"\"\n module_tree_path = docs_dir / \"module_tree.json\"\n if not module_tree_path.exists():\n # Fallback to a simple structure\n return {\n \"Overview\": {\n \"description\": \"Repository overview\",\n \"components\": [],\n \"children\": {}\n }\n }\n \n try:\n content = safe_read(module_tree_path)\n return json.loads(content)\n except Exception as e:\n raise FileSystemError(f\"Failed to load module tree: {e}\")\n \n def load_metadata(self, docs_dir: Path) -> Optional[Dict[str, Any]]:\n \"\"\"\n Load metadata from documentation directory.\n \n Args:\n docs_dir: Documentation directory path\n \n Returns:\n Metadata dictionary or None if not found\n \"\"\"\n metadata_path = docs_dir / \"metadata.json\"\n if not metadata_path.exists():\n return None\n \n try:\n content = safe_read(metadata_path)\n return json.loads(content)\n except Exception:\n # Non-critical, return None\n return None\n \n def generate(\n self,\n output_path: Path,\n title: str,\n module_tree: Optional[Dict[str, Any]] = None,\n repository_url: Optional[str] = None,\n github_pages_url: Optional[str] = None,\n config: Optional[Dict[str, Any]] = None,\n docs_dir: Optional[Path] = None,\n metadata: Optional[Dict[str, Any]] = None\n ):\n \"\"\"\n Generate HTML documentation viewer.\n \n Args:\n output_path: Output file path (index.html)\n title: Documentation title\n module_tree: Module tree structure (auto-loaded from docs_dir if not provided)\n repository_url: GitHub repository URL\n github_pages_url: Expected GitHub Pages URL\n config: Additional configuration\n docs_dir: Documentation directory (for auto-loading module_tree and metadata)\n metadata: Metadata dictionary (auto-loaded from docs_dir if not provided)\n \"\"\"\n # Auto-load module_tree and metadata from docs_dir if not provided\n if docs_dir:\n if module_tree is None:\n module_tree = self.load_module_tree(docs_dir)\n if metadata is None:\n metadata = self.load_metadata(docs_dir)\n \n # Default values\n if module_tree is None:\n module_tree = {}\n if config is None:\n config = {}\n \n # Load template\n template_path = self.template_dir / \"viewer_template.html\"\n if not template_path.exists():\n raise FileSystemError(f\"Template not found: {template_path}\")\n \n template_content = safe_read(template_path)\n \n # Build info content HTML\n info_content = self._build_info_content(metadata)\n show_info = \"block\" if info_content else \"none\"\n \n # Build repository link\n repo_link = \"\"\n if repository_url:\n repo_link = f'πŸ”— View Repository'\n \n # Determine docs base path\n # For GitHub Pages: relative path to docs folder\n # For local: relative path to docs folder\n docs_base_path = \"\"\n if docs_dir and output_path.parent != docs_dir:\n # Calculate relative path from output to docs\n try:\n docs_base_path = Path(docs_dir.name).as_posix()\n except Exception:\n docs_base_path = \".\"\n \n # Prepare JSON data for embedding\n config_json = json.dumps(config, indent=2)\n module_tree_json = json.dumps(module_tree, indent=2)\n metadata_json = json.dumps(metadata, indent=2) if metadata else \"null\"\n \n # Replace placeholders\n html_content = template_content\n replacements = {\n \"{{TITLE}}\": self._escape_html(title),\n \"{{REPO_LINK}}\": repo_link,\n \"{{SHOW_INFO}}\": show_info,\n \"{{INFO_CONTENT}}\": info_content,\n \"{{CONFIG_JSON}}\": config_json,\n \"{{MODULE_TREE_JSON}}\": module_tree_json,\n \"{{METADATA_JSON}}\": metadata_json,\n \"{{DOCS_BASE_PATH}}\": docs_base_path,\n }\n \n for placeholder, value in replacements.items():\n html_content = html_content.replace(placeholder, value)\n \n # Write output\n output_path = Path(output_path)\n output_path.parent.mkdir(parents=True, exist_ok=True)\n safe_write(output_path, html_content)\n \n def _build_info_content(self, metadata: Optional[Dict[str, Any]]) -> str:\n \"\"\"\n Build HTML content for repo info section.\n \n Args:\n metadata: Metadata dictionary\n \n Returns:\n HTML string for info content\n \"\"\"\n if not metadata or not metadata.get('generation_info'):\n return \"\"\n \n info = metadata.get('generation_info', {})\n stats = metadata.get('statistics', {})\n \n html_parts = []\n \n if info.get('main_model'):\n html_parts.append(f'
Model: {self._escape_html(info[\"main_model\"])}
')\n \n if info.get('timestamp'):\n try:\n from datetime import datetime\n timestamp = info['timestamp']\n # Parse ISO format timestamp\n if isinstance(timestamp, str):\n dt = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))\n formatted_date = dt.strftime('%Y-%m-%d')\n html_parts.append(f'
Generated: {formatted_date}
')\n except Exception:\n pass\n \n if info.get('commit_id'):\n commit_short = info['commit_id'][:8]\n html_parts.append(f'
Commit: {commit_short}
')\n \n if stats.get('total_components'):\n components_str = f\"{stats['total_components']:,}\"\n html_parts.append(f'
Components: {components_str}
')\n \n if stats.get('max_depth'):\n html_parts.append(f'
Max Depth: {stats[\"max_depth\"]}
')\n \n return '\\n '.join(html_parts)\n \n def _escape_html(self, text: str) -> str:\n \"\"\"\n Escape HTML special characters.\n \n Args:\n text: Text to escape\n \n Returns:\n Escaped text\n \"\"\"\n return (text\n .replace('&', '&')\n .replace('<', '<')\n .replace('>', '>')\n .replace('\"', '"')\n .replace(\"'\", '''))\n \n\n \n def detect_repository_info(self, repo_path: Path) -> Dict[str, Optional[str]]:\n \"\"\"\n Detect repository information from git.\n \n Args:\n repo_path: Repository path\n \n Returns:\n Dictionary with 'name', 'url', 'github_pages_url'\n \"\"\"\n info = {\n 'name': repo_path.name,\n 'url': None,\n 'github_pages_url': None,\n }\n \n try:\n import git\n repo = git.Repo(repo_path)\n \n # Get repository name\n info['name'] = repo_path.name\n \n # Get remote URL\n if repo.remotes:\n remote_url = repo.remotes.origin.url\n \n # Clean URL\n if remote_url.startswith('git@github.com:'):\n remote_url = remote_url.replace('git@github.com:', 'https://github.com/')\n \n remote_url = remote_url.rstrip('/').replace('.git', '')\n info['url'] = remote_url\n \n # Compute GitHub Pages URL\n if 'github.com' in remote_url:\n parts = remote_url.split('/')\n if len(parts) >= 2:\n owner = parts[-2]\n repo = parts[-1]\n info['github_pages_url'] = f\"https://{owner}.github.io/{repo}/\"\n \n except Exception:\n pass\n \n return info", - "start_line": 13, - "end_line": 283, - "has_docstring": true, - "docstring": "Generates static HTML documentation viewer for GitHub Pages.\n\nCreates a self-contained index.html with embedded styles, scripts,\nand configuration for client-side markdown rendering.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class HTMLGenerator", - "component_id": "codewiki/cli/html_generator.py::HTMLGenerator", - "language": null, - "qualified_name": null - }, - "codewiki/cli/html_generator.py::HTMLGenerator.__init__": { - "id": "codewiki/cli/html_generator.py::HTMLGenerator.__init__", - "name": "HTMLGenerator.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/html_generator.py", - "relative_path": "codewiki/cli/html_generator.py", - "depends_on": [], - "source_code": " def __init__(self, template_dir: Optional[Path] = None):\n \"\"\"\n Initialize HTML generator.\n \n Args:\n template_dir: Path to template directory (default: package templates)\n \"\"\"\n if template_dir is None:\n # Use package templates\n template_dir = Path(__file__).parent.parent / \"templates\" / \"github_pages\"\n \n self.template_dir = Path(template_dir)", - "start_line": 21, - "end_line": 32, - "has_docstring": true, - "docstring": "Initialize HTML generator.\n\nArgs:\n template_dir: Path to template directory (default: package templates)", - "parameters": [ - "self", - "template_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "HTMLGenerator", - "display_name": "method HTMLGenerator.__init__", - "component_id": "codewiki/cli/html_generator.py::HTMLGenerator.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/cli/html_generator.py::HTMLGenerator.load_module_tree": { - "id": "codewiki/cli/html_generator.py::HTMLGenerator.load_module_tree", - "name": "HTMLGenerator.load_module_tree", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/html_generator.py", - "relative_path": "codewiki/cli/html_generator.py", - "depends_on": [ - "codewiki/cli/utils/fs.py::safe_read", - "codewiki/cli/utils/errors.py::FileSystemError" - ], - "source_code": " def load_module_tree(self, docs_dir: Path) -> Dict[str, Any]:\n \"\"\"\n Load module tree from documentation directory.\n \n Args:\n docs_dir: Documentation directory path\n \n Returns:\n Module tree structure\n \"\"\"\n module_tree_path = docs_dir / \"module_tree.json\"\n if not module_tree_path.exists():\n # Fallback to a simple structure\n return {\n \"Overview\": {\n \"description\": \"Repository overview\",\n \"components\": [],\n \"children\": {}\n }\n }\n \n try:\n content = safe_read(module_tree_path)\n return json.loads(content)\n except Exception as e:\n raise FileSystemError(f\"Failed to load module tree: {e}\")", - "start_line": 35, - "end_line": 60, - "has_docstring": true, - "docstring": "Load module tree from documentation directory.\n\nArgs:\n docs_dir: Documentation directory path\n \nReturns:\n Module tree structure", - "parameters": [ - "self", - "docs_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "HTMLGenerator", - "display_name": "method HTMLGenerator.load_module_tree", - "component_id": "codewiki/cli/html_generator.py::HTMLGenerator.load_module_tree", - "language": null, - "qualified_name": null - }, - "codewiki/cli/html_generator.py::HTMLGenerator.load_metadata": { - "id": "codewiki/cli/html_generator.py::HTMLGenerator.load_metadata", - "name": "HTMLGenerator.load_metadata", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/html_generator.py", - "relative_path": "codewiki/cli/html_generator.py", - "depends_on": [ - "codewiki/cli/utils/fs.py::safe_read" - ], - "source_code": " def load_metadata(self, docs_dir: Path) -> Optional[Dict[str, Any]]:\n \"\"\"\n Load metadata from documentation directory.\n \n Args:\n docs_dir: Documentation directory path\n \n Returns:\n Metadata dictionary or None if not found\n \"\"\"\n metadata_path = docs_dir / \"metadata.json\"\n if not metadata_path.exists():\n return None\n \n try:\n content = safe_read(metadata_path)\n return json.loads(content)\n except Exception:\n # Non-critical, return None\n return None", - "start_line": 62, - "end_line": 81, - "has_docstring": true, - "docstring": "Load metadata from documentation directory.\n\nArgs:\n docs_dir: Documentation directory path\n \nReturns:\n Metadata dictionary or None if not found", - "parameters": [ - "self", - "docs_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "HTMLGenerator", - "display_name": "method HTMLGenerator.load_metadata", - "component_id": "codewiki/cli/html_generator.py::HTMLGenerator.load_metadata", - "language": null, - "qualified_name": null - }, - "codewiki/cli/html_generator.py::HTMLGenerator.generate": { - "id": "codewiki/cli/html_generator.py::HTMLGenerator.generate", - "name": "HTMLGenerator.generate", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/html_generator.py", - "relative_path": "codewiki/cli/html_generator.py", - "depends_on": [ - "codewiki/cli/utils/fs.py::safe_read", - "codewiki/cli/html_generator.py::HTMLGenerator._escape_html", - "codewiki/cli/utils/errors.py::FileSystemError", - "codewiki/cli/utils/fs.py::safe_write", - "codewiki/cli/html_generator.py::HTMLGenerator._build_info_content", - "codewiki/cli/html_generator.py::HTMLGenerator.load_metadata", - "codewiki/cli/html_generator.py::HTMLGenerator.load_module_tree" - ], - "source_code": " def generate(\n self,\n output_path: Path,\n title: str,\n module_tree: Optional[Dict[str, Any]] = None,\n repository_url: Optional[str] = None,\n github_pages_url: Optional[str] = None,\n config: Optional[Dict[str, Any]] = None,\n docs_dir: Optional[Path] = None,\n metadata: Optional[Dict[str, Any]] = None\n ):\n \"\"\"\n Generate HTML documentation viewer.\n \n Args:\n output_path: Output file path (index.html)\n title: Documentation title\n module_tree: Module tree structure (auto-loaded from docs_dir if not provided)\n repository_url: GitHub repository URL\n github_pages_url: Expected GitHub Pages URL\n config: Additional configuration\n docs_dir: Documentation directory (for auto-loading module_tree and metadata)\n metadata: Metadata dictionary (auto-loaded from docs_dir if not provided)\n \"\"\"\n # Auto-load module_tree and metadata from docs_dir if not provided\n if docs_dir:\n if module_tree is None:\n module_tree = self.load_module_tree(docs_dir)\n if metadata is None:\n metadata = self.load_metadata(docs_dir)\n \n # Default values\n if module_tree is None:\n module_tree = {}\n if config is None:\n config = {}\n \n # Load template\n template_path = self.template_dir / \"viewer_template.html\"\n if not template_path.exists():\n raise FileSystemError(f\"Template not found: {template_path}\")\n \n template_content = safe_read(template_path)\n \n # Build info content HTML\n info_content = self._build_info_content(metadata)\n show_info = \"block\" if info_content else \"none\"\n \n # Build repository link\n repo_link = \"\"\n if repository_url:\n repo_link = f'πŸ”— View Repository'\n \n # Determine docs base path\n # For GitHub Pages: relative path to docs folder\n # For local: relative path to docs folder\n docs_base_path = \"\"\n if docs_dir and output_path.parent != docs_dir:\n # Calculate relative path from output to docs\n try:\n docs_base_path = Path(docs_dir.name).as_posix()\n except Exception:\n docs_base_path = \".\"\n \n # Prepare JSON data for embedding\n config_json = json.dumps(config, indent=2)\n module_tree_json = json.dumps(module_tree, indent=2)\n metadata_json = json.dumps(metadata, indent=2) if metadata else \"null\"\n \n # Replace placeholders\n html_content = template_content\n replacements = {\n \"{{TITLE}}\": self._escape_html(title),\n \"{{REPO_LINK}}\": repo_link,\n \"{{SHOW_INFO}}\": show_info,\n \"{{INFO_CONTENT}}\": info_content,\n \"{{CONFIG_JSON}}\": config_json,\n \"{{MODULE_TREE_JSON}}\": module_tree_json,\n \"{{METADATA_JSON}}\": metadata_json,\n \"{{DOCS_BASE_PATH}}\": docs_base_path,\n }\n \n for placeholder, value in replacements.items():\n html_content = html_content.replace(placeholder, value)\n \n # Write output\n output_path = Path(output_path)\n output_path.parent.mkdir(parents=True, exist_ok=True)\n safe_write(output_path, html_content)", - "start_line": 83, - "end_line": 171, - "has_docstring": true, - "docstring": "Generate HTML documentation viewer.\n\nArgs:\n output_path: Output file path (index.html)\n title: Documentation title\n module_tree: Module tree structure (auto-loaded from docs_dir if not provided)\n repository_url: GitHub repository URL\n github_pages_url: Expected GitHub Pages URL\n config: Additional configuration\n docs_dir: Documentation directory (for auto-loading module_tree and metadata)\n metadata: Metadata dictionary (auto-loaded from docs_dir if not provided)", - "parameters": [ - "self", - "output_path", - "title", - "module_tree", - "repository_url", - "github_pages_url", - "config", - "docs_dir", - "metadata" - ], - "node_type": "method", - "base_classes": null, - "class_name": "HTMLGenerator", - "display_name": "method HTMLGenerator.generate", - "component_id": "codewiki/cli/html_generator.py::HTMLGenerator.generate", - "language": null, - "qualified_name": null - }, - "codewiki/cli/html_generator.py::HTMLGenerator._build_info_content": { - "id": "codewiki/cli/html_generator.py::HTMLGenerator._build_info_content", - "name": "HTMLGenerator._build_info_content", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/html_generator.py", - "relative_path": "codewiki/cli/html_generator.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/cli/html_generator.py::HTMLGenerator._escape_html" - ], - "source_code": " def _build_info_content(self, metadata: Optional[Dict[str, Any]]) -> str:\n \"\"\"\n Build HTML content for repo info section.\n \n Args:\n metadata: Metadata dictionary\n \n Returns:\n HTML string for info content\n \"\"\"\n if not metadata or not metadata.get('generation_info'):\n return \"\"\n \n info = metadata.get('generation_info', {})\n stats = metadata.get('statistics', {})\n \n html_parts = []\n \n if info.get('main_model'):\n html_parts.append(f'
Model: {self._escape_html(info[\"main_model\"])}
')\n \n if info.get('timestamp'):\n try:\n from datetime import datetime\n timestamp = info['timestamp']\n # Parse ISO format timestamp\n if isinstance(timestamp, str):\n dt = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))\n formatted_date = dt.strftime('%Y-%m-%d')\n html_parts.append(f'
Generated: {formatted_date}
')\n except Exception:\n pass\n \n if info.get('commit_id'):\n commit_short = info['commit_id'][:8]\n html_parts.append(f'
Commit: {commit_short}
')\n \n if stats.get('total_components'):\n components_str = f\"{stats['total_components']:,}\"\n html_parts.append(f'
Components: {components_str}
')\n \n if stats.get('max_depth'):\n html_parts.append(f'
Max Depth: {stats[\"max_depth\"]}
')\n \n return '\\n '.join(html_parts)", - "start_line": 173, - "end_line": 217, - "has_docstring": true, - "docstring": "Build HTML content for repo info section.\n\nArgs:\n metadata: Metadata dictionary\n \nReturns:\n HTML string for info content", - "parameters": [ - "self", - "metadata" - ], - "node_type": "method", - "base_classes": null, - "class_name": "HTMLGenerator", - "display_name": "method HTMLGenerator._build_info_content", - "component_id": "codewiki/cli/html_generator.py::HTMLGenerator._build_info_content", - "language": null, - "qualified_name": null - }, - "codewiki/cli/html_generator.py::HTMLGenerator._escape_html": { - "id": "codewiki/cli/html_generator.py::HTMLGenerator._escape_html", - "name": "HTMLGenerator._escape_html", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/html_generator.py", - "relative_path": "codewiki/cli/html_generator.py", - "depends_on": [], - "source_code": " def _escape_html(self, text: str) -> str:\n \"\"\"\n Escape HTML special characters.\n \n Args:\n text: Text to escape\n \n Returns:\n Escaped text\n \"\"\"\n return (text\n .replace('&', '&')\n .replace('<', '<')\n .replace('>', '>')\n .replace('\"', '"')\n .replace(\"'\", '''))", - "start_line": 219, - "end_line": 234, - "has_docstring": true, - "docstring": "Escape HTML special characters.\n\nArgs:\n text: Text to escape\n \nReturns:\n Escaped text", - "parameters": [ - "self", - "text" - ], - "node_type": "method", - "base_classes": null, - "class_name": "HTMLGenerator", - "display_name": "method HTMLGenerator._escape_html", - "component_id": "codewiki/cli/html_generator.py::HTMLGenerator._escape_html", - "language": null, - "qualified_name": null - }, - "codewiki/cli/html_generator.py::HTMLGenerator.detect_repository_info": { - "id": "codewiki/cli/html_generator.py::HTMLGenerator.detect_repository_info", - "name": "HTMLGenerator.detect_repository_info", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/html_generator.py", - "relative_path": "codewiki/cli/html_generator.py", - "depends_on": [], - "source_code": " def detect_repository_info(self, repo_path: Path) -> Dict[str, Optional[str]]:\n \"\"\"\n Detect repository information from git.\n \n Args:\n repo_path: Repository path\n \n Returns:\n Dictionary with 'name', 'url', 'github_pages_url'\n \"\"\"\n info = {\n 'name': repo_path.name,\n 'url': None,\n 'github_pages_url': None,\n }\n \n try:\n import git\n repo = git.Repo(repo_path)\n \n # Get repository name\n info['name'] = repo_path.name\n \n # Get remote URL\n if repo.remotes:\n remote_url = repo.remotes.origin.url\n \n # Clean URL\n if remote_url.startswith('git@github.com:'):\n remote_url = remote_url.replace('git@github.com:', 'https://github.com/')\n \n remote_url = remote_url.rstrip('/').replace('.git', '')\n info['url'] = remote_url\n \n # Compute GitHub Pages URL\n if 'github.com' in remote_url:\n parts = remote_url.split('/')\n if len(parts) >= 2:\n owner = parts[-2]\n repo = parts[-1]\n info['github_pages_url'] = f\"https://{owner}.github.io/{repo}/\"\n \n except Exception:\n pass\n \n return info", - "start_line": 238, - "end_line": 283, - "has_docstring": true, - "docstring": "Detect repository information from git.\n\nArgs:\n repo_path: Repository path\n \nReturns:\n Dictionary with 'name', 'url', 'github_pages_url'", - "parameters": [ - "self", - "repo_path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "HTMLGenerator", - "display_name": "method HTMLGenerator.detect_repository_info", - "component_id": "codewiki/cli/html_generator.py::HTMLGenerator.detect_repository_info", - "language": null, - "qualified_name": null - }, - "codewiki/cli/main.py::cli": { - "id": "codewiki/cli/main.py::cli", - "name": "cli", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/main.py", - "relative_path": "codewiki/cli/main.py", - "depends_on": [], - "source_code": "def cli(ctx):\n \"\"\"\n CodeWiki: Transform codebases into comprehensive documentation.\n \n Generate AI-powered documentation for your code repositories with support\n for Python, Java, JavaScript, TypeScript, C, C++, and C#.\n \"\"\"\n # Ensure context object exists\n ctx.ensure_object(dict)", - "start_line": 15, - "end_line": 23, - "has_docstring": true, - "docstring": "CodeWiki: Transform codebases into comprehensive documentation.\n\nGenerate AI-powered documentation for your code repositories with support\nfor Python, Java, JavaScript, TypeScript, C, C++, and C#.", - "parameters": [ - "ctx" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function cli", - "component_id": "codewiki/cli/main.py::cli", - "language": null, - "qualified_name": null - }, - "codewiki/cli/main.py::version": { - "id": "codewiki/cli/main.py::version", - "name": "version", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/main.py", - "relative_path": "codewiki/cli/main.py", - "depends_on": [], - "source_code": "def version():\n \"\"\"Display version information.\"\"\"\n click.echo(f\"CodeWiki CLI v{__version__}\")\n click.echo(\"Python-based documentation generator using AI analysis\")", - "start_line": 27, - "end_line": 30, - "has_docstring": true, - "docstring": "Display version information.", - "parameters": [], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function version", - "component_id": "codewiki/cli/main.py::version", - "language": null, - "qualified_name": null - }, - "codewiki/cli/main.py::mcp_command": { - "id": "codewiki/cli/main.py::mcp_command", - "name": "mcp_command", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/main.py", - "relative_path": "codewiki/cli/main.py", - "depends_on": [ - "codewiki/mcp/server.py::main", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.run" - ], - "source_code": "def mcp_command():\n \"\"\"Start CodeWiki as an MCP (Model Context Protocol) server.\n\n Exposes documentation generation tools via MCP stdio transport.\n Configure in your MCP client (Claude, Cursor, etc.) as:\n\n \\b\n {\n \"mcpServers\": {\n \"codewiki\": {\n \"command\": \"codewiki\",\n \"args\": [\"mcp\"]\n }\n }\n }\n \"\"\"\n import asyncio\n from codewiki.mcp.server import main as mcp_main\n asyncio.run(mcp_main())", - "start_line": 43, - "end_line": 61, - "has_docstring": true, - "docstring": "Start CodeWiki as an MCP (Model Context Protocol) server.\n\nExposes documentation generation tools via MCP stdio transport.\nConfigure in your MCP client (Claude, Cursor, etc.) as:\n\n\b\n{\n \"mcpServers\": {\n \"codewiki\": {\n \"command\": \"codewiki\",\n \"args\": [\"mcp\"]\n }\n }\n}", - "parameters": [], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function mcp_command", - "component_id": "codewiki/cli/main.py::mcp_command", - "language": null, - "qualified_name": null - }, - "codewiki/cli/main.py::main": { - "id": "codewiki/cli/main.py::main", - "name": "main", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/main.py", - "relative_path": "codewiki/cli/main.py", - "depends_on": [ - "codewiki/cli/main.py::cli" - ], - "source_code": "def main():\n \"\"\"Entry point for the CLI.\"\"\"\n try:\n cli(obj={})\n except KeyboardInterrupt:\n click.echo(\"\\n\\nInterrupted by user\", err=True)\n sys.exit(130)\n except Exception as e:\n click.secho(f\"\\nβœ— Unexpected error: {e}\", fg=\"red\", err=True)\n sys.exit(1)", - "start_line": 64, - "end_line": 73, - "has_docstring": true, - "docstring": "Entry point for the CLI.", - "parameters": [], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function main", - "component_id": "codewiki/cli/main.py::main", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/config.py::AgentInstructions": { - "id": "codewiki/cli/models/config.py::AgentInstructions", - "name": "AgentInstructions", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/config.py", - "relative_path": "codewiki/cli/models/config.py", - "depends_on": [], - "source_code": "class AgentInstructions:\n \"\"\"\n Custom instructions for the documentation agent.\n \n Allows users to customize:\n - File filtering (include/exclude patterns)\n - Module focus (prioritize certain modules)\n - Documentation type (API docs, architecture docs, etc.)\n - Custom instructions for the LLM\n \n Attributes:\n include_patterns: File patterns to include (e.g., [\"*.cs\", \"*.py\"])\n exclude_patterns: File/directory patterns to exclude (e.g., [\"*Tests*\", \"*test*\"])\n focus_modules: Modules to document in more detail\n doc_type: Type of documentation to generate\n custom_instructions: Additional instructions for the documentation agent\n \"\"\"\n include_patterns: Optional[List[str]] = None # e.g., [\"*.cs\"] for C# projects\n exclude_patterns: Optional[List[str]] = None # e.g., [\"*Tests*\", \"*Specs*\"]\n focus_modules: Optional[List[str]] = None # e.g., [\"src/core\", \"src/api\"]\n doc_type: Optional[str] = None # e.g., \"api\", \"architecture\", \"user-guide\"\n custom_instructions: Optional[str] = None # Free-form instructions\n \n def to_dict(self) -> dict:\n \"\"\"Convert to dictionary, excluding None values.\"\"\"\n result = {}\n if self.include_patterns:\n result['include_patterns'] = self.include_patterns\n if self.exclude_patterns:\n result['exclude_patterns'] = self.exclude_patterns\n if self.focus_modules:\n result['focus_modules'] = self.focus_modules\n if self.doc_type:\n result['doc_type'] = self.doc_type\n if self.custom_instructions:\n result['custom_instructions'] = self.custom_instructions\n return result\n \n @classmethod\n def from_dict(cls, data: dict) -> 'AgentInstructions':\n \"\"\"Create AgentInstructions from dictionary.\"\"\"\n return cls(\n include_patterns=data.get('include_patterns'),\n exclude_patterns=data.get('exclude_patterns'),\n focus_modules=data.get('focus_modules'),\n doc_type=data.get('doc_type'),\n custom_instructions=data.get('custom_instructions'),\n )\n \n def is_empty(self) -> bool:\n \"\"\"Check if all fields are empty/None.\"\"\"\n return not any([\n self.include_patterns,\n self.exclude_patterns,\n self.focus_modules,\n self.doc_type,\n self.custom_instructions,\n ])\n \n def get_prompt_addition(self) -> str:\n \"\"\"Generate prompt additions based on instructions.\"\"\"\n additions = []\n \n if self.doc_type:\n doc_type_instructions = {\n 'api': \"Focus on API documentation: endpoints, parameters, return types, and usage examples.\",\n 'architecture': \"Focus on architecture documentation: system design, component relationships, and data flow.\",\n 'user-guide': \"Focus on user guide documentation: how to use features, step-by-step tutorials.\",\n 'developer': \"Focus on developer documentation: code structure, contribution guidelines, and implementation details.\",\n }\n if self.doc_type.lower() in doc_type_instructions:\n additions.append(doc_type_instructions[self.doc_type.lower()])\n else:\n additions.append(f\"Focus on generating {self.doc_type} documentation.\")\n \n if self.focus_modules:\n additions.append(f\"Pay special attention to and provide more detailed documentation for these modules: {', '.join(self.focus_modules)}\")\n \n if self.custom_instructions:\n additions.append(f\"Additional instructions: {self.custom_instructions}\")\n \n return \"\\n\".join(additions) if additions else \"\"", - "start_line": 21, - "end_line": 102, - "has_docstring": true, - "docstring": "Custom instructions for the documentation agent.\n\nAllows users to customize:\n- File filtering (include/exclude patterns)\n- Module focus (prioritize certain modules)\n- Documentation type (API docs, architecture docs, etc.)\n- Custom instructions for the LLM\n\nAttributes:\n include_patterns: File patterns to include (e.g., [\"*.cs\", \"*.py\"])\n exclude_patterns: File/directory patterns to exclude (e.g., [\"*Tests*\", \"*test*\"])\n focus_modules: Modules to document in more detail\n doc_type: Type of documentation to generate\n custom_instructions: Additional instructions for the documentation agent", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class AgentInstructions", - "component_id": "codewiki/cli/models/config.py::AgentInstructions", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/config.py::AgentInstructions.to_dict": { - "id": "codewiki/cli/models/config.py::AgentInstructions.to_dict", - "name": "AgentInstructions.to_dict", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/config.py", - "relative_path": "codewiki/cli/models/config.py", - "depends_on": [], - "source_code": " def to_dict(self) -> dict:\n \"\"\"Convert to dictionary, excluding None values.\"\"\"\n result = {}\n if self.include_patterns:\n result['include_patterns'] = self.include_patterns\n if self.exclude_patterns:\n result['exclude_patterns'] = self.exclude_patterns\n if self.focus_modules:\n result['focus_modules'] = self.focus_modules\n if self.doc_type:\n result['doc_type'] = self.doc_type\n if self.custom_instructions:\n result['custom_instructions'] = self.custom_instructions\n return result", - "start_line": 44, - "end_line": 57, - "has_docstring": true, - "docstring": "Convert to dictionary, excluding None values.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "AgentInstructions", - "display_name": "method AgentInstructions.to_dict", - "component_id": "codewiki/cli/models/config.py::AgentInstructions.to_dict", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/config.py::AgentInstructions.from_dict": { - "id": "codewiki/cli/models/config.py::AgentInstructions.from_dict", - "name": "AgentInstructions.from_dict", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/config.py", - "relative_path": "codewiki/cli/models/config.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def from_dict(cls, data: dict) -> 'AgentInstructions':\n \"\"\"Create AgentInstructions from dictionary.\"\"\"\n return cls(\n include_patterns=data.get('include_patterns'),\n exclude_patterns=data.get('exclude_patterns'),\n focus_modules=data.get('focus_modules'),\n doc_type=data.get('doc_type'),\n custom_instructions=data.get('custom_instructions'),\n )", - "start_line": 60, - "end_line": 68, - "has_docstring": true, - "docstring": "Create AgentInstructions from dictionary.", - "parameters": [ - "cls", - "data" - ], - "node_type": "method", - "base_classes": null, - "class_name": "AgentInstructions", - "display_name": "method AgentInstructions.from_dict", - "component_id": "codewiki/cli/models/config.py::AgentInstructions.from_dict", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/config.py::AgentInstructions.is_empty": { - "id": "codewiki/cli/models/config.py::AgentInstructions.is_empty", - "name": "AgentInstructions.is_empty", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/config.py", - "relative_path": "codewiki/cli/models/config.py", - "depends_on": [], - "source_code": " def is_empty(self) -> bool:\n \"\"\"Check if all fields are empty/None.\"\"\"\n return not any([\n self.include_patterns,\n self.exclude_patterns,\n self.focus_modules,\n self.doc_type,\n self.custom_instructions,\n ])", - "start_line": 70, - "end_line": 78, - "has_docstring": true, - "docstring": "Check if all fields are empty/None.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "AgentInstructions", - "display_name": "method AgentInstructions.is_empty", - "component_id": "codewiki/cli/models/config.py::AgentInstructions.is_empty", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/config.py::AgentInstructions.get_prompt_addition": { - "id": "codewiki/cli/models/config.py::AgentInstructions.get_prompt_addition", - "name": "AgentInstructions.get_prompt_addition", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/config.py", - "relative_path": "codewiki/cli/models/config.py", - "depends_on": [], - "source_code": " def get_prompt_addition(self) -> str:\n \"\"\"Generate prompt additions based on instructions.\"\"\"\n additions = []\n \n if self.doc_type:\n doc_type_instructions = {\n 'api': \"Focus on API documentation: endpoints, parameters, return types, and usage examples.\",\n 'architecture': \"Focus on architecture documentation: system design, component relationships, and data flow.\",\n 'user-guide': \"Focus on user guide documentation: how to use features, step-by-step tutorials.\",\n 'developer': \"Focus on developer documentation: code structure, contribution guidelines, and implementation details.\",\n }\n if self.doc_type.lower() in doc_type_instructions:\n additions.append(doc_type_instructions[self.doc_type.lower()])\n else:\n additions.append(f\"Focus on generating {self.doc_type} documentation.\")\n \n if self.focus_modules:\n additions.append(f\"Pay special attention to and provide more detailed documentation for these modules: {', '.join(self.focus_modules)}\")\n \n if self.custom_instructions:\n additions.append(f\"Additional instructions: {self.custom_instructions}\")\n \n return \"\\n\".join(additions) if additions else \"\"", - "start_line": 80, - "end_line": 102, - "has_docstring": true, - "docstring": "Generate prompt additions based on instructions.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "AgentInstructions", - "display_name": "method AgentInstructions.get_prompt_addition", - "component_id": "codewiki/cli/models/config.py::AgentInstructions.get_prompt_addition", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/config.py::Configuration": { - "id": "codewiki/cli/models/config.py::Configuration", - "name": "Configuration", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/config.py", - "relative_path": "codewiki/cli/models/config.py", - "depends_on": [], - "source_code": "class Configuration:\n \"\"\"\n CodeWiki configuration data model.\n\n Attributes:\n base_url: LLM API base URL\n main_model: Primary model for documentation generation\n cluster_model: Model for module clustering\n fallback_model: Fallback model for documentation generation\n default_output: Default output directory\n provider: LLM provider type (openai-compatible, atlas-cloud, anthropic, bedrock, azure-openai)\n aws_region: AWS region for Bedrock provider\n api_version: Azure OpenAI API version\n azure_deployment: Azure OpenAI deployment name\n max_tokens: Maximum tokens for LLM response (default: 32768)\n max_token_per_module: Maximum tokens per module for clustering (default: 36369)\n max_token_per_leaf_module: Maximum tokens per leaf module (default: 16000)\n max_depth: Maximum depth for hierarchical decomposition (default: 2)\n use_gitignore: Apply Git ignore rules during repository analysis\n prompt_caching: Add prompt-cache breakpoints to agentic LLM calls (default: True)\n agent_instructions: Custom agent instructions for documentation generation\n \"\"\"\n base_url: str\n main_model: str\n cluster_model: str\n fallback_model: str = \"glm-4p5\"\n default_output: str = \"docs\"\n provider: str = \"openai-compatible\"\n aws_region: str = \"us-east-1\"\n api_version: str = \"2024-12-01-preview\"\n azure_deployment: str = \"\"\n max_tokens: int = 32768\n max_token_per_module: int = 36369\n max_token_per_leaf_module: int = 16000\n max_depth: int = 2\n use_gitignore: bool = True\n prompt_caching: bool = True\n agent_instructions: AgentInstructions = field(default_factory=AgentInstructions)\n \n def validate(self):\n \"\"\"\n Validate all configuration fields.\n\n Subscription-mode providers (claude-code, codex) authenticate via the\n underlying CLI's OAuth and do not require a base URL or fallback model.\n\n Raises:\n ConfigurationError: If validation fails\n \"\"\"\n from codewiki.src.be.backend import is_caw_provider\n if is_caw_provider(self.provider):\n validate_model_name(self.main_model)\n return\n validate_url(self.base_url)\n validate_model_name(self.main_model)\n validate_model_name(self.cluster_model)\n validate_model_name(self.fallback_model)\n \n def to_dict(self) -> dict:\n \"\"\"Convert to dictionary.\"\"\"\n result = {\n 'base_url': self.base_url,\n 'main_model': self.main_model,\n 'cluster_model': self.cluster_model,\n 'default_output': self.default_output,\n 'provider': self.provider,\n 'aws_region': self.aws_region,\n 'api_version': self.api_version,\n 'azure_deployment': self.azure_deployment,\n 'max_tokens': self.max_tokens,\n 'max_token_per_module': self.max_token_per_module,\n 'max_token_per_leaf_module': self.max_token_per_leaf_module,\n 'max_depth': self.max_depth,\n 'use_gitignore': self.use_gitignore,\n 'prompt_caching': self.prompt_caching,\n 'fallback_model': self.fallback_model,\n }\n if self.agent_instructions and not self.agent_instructions.is_empty():\n result['agent_instructions'] = self.agent_instructions.to_dict()\n return result\n \n @classmethod\n def from_dict(cls, data: dict) -> 'Configuration':\n \"\"\"\n Create Configuration from dictionary.\n \n Args:\n data: Configuration dictionary\n \n Returns:\n Configuration instance\n \"\"\"\n agent_instructions = AgentInstructions()\n if 'agent_instructions' in data:\n agent_instructions = AgentInstructions.from_dict(data['agent_instructions'])\n \n return cls(\n base_url=data.get('base_url', ''),\n main_model=data.get('main_model', ''),\n cluster_model=data.get('cluster_model', ''),\n fallback_model=data.get('fallback_model', 'glm-4p5'),\n default_output=data.get('default_output', 'docs'),\n provider=data.get('provider', 'openai-compatible'),\n aws_region=data.get('aws_region', 'us-east-1'),\n api_version=data.get('api_version', '2024-12-01-preview'),\n azure_deployment=data.get('azure_deployment', ''),\n max_tokens=data.get('max_tokens', 32768),\n max_token_per_module=data.get('max_token_per_module', 36369),\n max_token_per_leaf_module=data.get('max_token_per_leaf_module', 16000),\n max_depth=data.get('max_depth', 2),\n use_gitignore=data.get('use_gitignore', True),\n prompt_caching=data.get('prompt_caching', True),\n agent_instructions=agent_instructions,\n )\n \n def is_complete(self) -> bool:\n \"\"\"Check if all required fields are set.\n\n Subscription-mode providers (claude-code, codex) only require\n ``main_model``; ``base_url``, ``cluster_model`` and ``fallback_model``\n are unused.\n \"\"\"\n from codewiki.src.be.backend import is_caw_provider\n if is_caw_provider(self.provider):\n return bool(self.main_model)\n return bool(\n self.base_url and\n self.main_model and\n self.cluster_model and\n self.fallback_model\n )\n \n def to_backend_config(self, repo_path: str, output_dir: str, api_key: str, runtime_instructions: AgentInstructions = None):\n \"\"\"\n Convert CLI Configuration to Backend Config.\n \n This method bridges the gap between persistent user settings (CLI Configuration)\n and runtime job configuration (Backend Config).\n \n Args:\n repo_path: Path to the repository to document\n output_dir: Output directory for generated documentation\n api_key: LLM API key (from keyring)\n runtime_instructions: Runtime agent instructions (override persistent settings)\n \n Returns:\n Backend Config instance ready for documentation generation\n \"\"\"\n from codewiki.src.config import Config\n \n # Merge runtime instructions with persistent settings\n # Runtime instructions take precedence\n final_instructions = self.agent_instructions\n if runtime_instructions and not runtime_instructions.is_empty():\n final_instructions = AgentInstructions(\n include_patterns=runtime_instructions.include_patterns or self.agent_instructions.include_patterns,\n exclude_patterns=runtime_instructions.exclude_patterns or self.agent_instructions.exclude_patterns,\n focus_modules=runtime_instructions.focus_modules or self.agent_instructions.focus_modules,\n doc_type=runtime_instructions.doc_type or self.agent_instructions.doc_type,\n custom_instructions=runtime_instructions.custom_instructions or self.agent_instructions.custom_instructions,\n )\n \n return Config.from_cli(\n repo_path=repo_path,\n output_dir=output_dir,\n llm_base_url=self.base_url,\n llm_api_key=api_key,\n main_model=self.main_model,\n cluster_model=self.cluster_model,\n fallback_model=self.fallback_model,\n provider=self.provider,\n aws_region=self.aws_region,\n api_version=self.api_version,\n azure_deployment=self.azure_deployment,\n max_tokens=self.max_tokens,\n max_token_per_module=self.max_token_per_module,\n max_token_per_leaf_module=self.max_token_per_leaf_module,\n max_depth=self.max_depth,\n agent_instructions=final_instructions.to_dict() if final_instructions else None,\n use_gitignore=self.use_gitignore,\n prompt_caching=self.prompt_caching,\n )", - "start_line": 106, - "end_line": 287, - "has_docstring": true, - "docstring": "CodeWiki configuration data model.\n\nAttributes:\n base_url: LLM API base URL\n main_model: Primary model for documentation generation\n cluster_model: Model for module clustering\n fallback_model: Fallback model for documentation generation\n default_output: Default output directory\n provider: LLM provider type (openai-compatible, atlas-cloud, anthropic, bedrock, azure-openai)\n aws_region: AWS region for Bedrock provider\n api_version: Azure OpenAI API version\n azure_deployment: Azure OpenAI deployment name\n max_tokens: Maximum tokens for LLM response (default: 32768)\n max_token_per_module: Maximum tokens per module for clustering (default: 36369)\n max_token_per_leaf_module: Maximum tokens per leaf module (default: 16000)\n max_depth: Maximum depth for hierarchical decomposition (default: 2)\n use_gitignore: Apply Git ignore rules during repository analysis\n prompt_caching: Add prompt-cache breakpoints to agentic LLM calls (default: True)\n agent_instructions: Custom agent instructions for documentation generation", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class Configuration", - "component_id": "codewiki/cli/models/config.py::Configuration", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/config.py::Configuration.validate": { - "id": "codewiki/cli/models/config.py::Configuration.validate", - "name": "Configuration.validate", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/config.py", - "relative_path": "codewiki/cli/models/config.py", - "depends_on": [ - "codewiki/cli/utils/validation.py::validate_url", - "codewiki/cli/utils/validation.py::validate_model_name", - "codewiki/src/be/backend.py::is_caw_provider" - ], - "source_code": " def validate(self):\n \"\"\"\n Validate all configuration fields.\n\n Subscription-mode providers (claude-code, codex) authenticate via the\n underlying CLI's OAuth and do not require a base URL or fallback model.\n\n Raises:\n ConfigurationError: If validation fails\n \"\"\"\n from codewiki.src.be.backend import is_caw_provider\n if is_caw_provider(self.provider):\n validate_model_name(self.main_model)\n return\n validate_url(self.base_url)\n validate_model_name(self.main_model)\n validate_model_name(self.cluster_model)\n validate_model_name(self.fallback_model)", - "start_line": 145, - "end_line": 162, - "has_docstring": true, - "docstring": "Validate all configuration fields.\n\nSubscription-mode providers (claude-code, codex) authenticate via the\nunderlying CLI's OAuth and do not require a base URL or fallback model.\n\nRaises:\n ConfigurationError: If validation fails", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "Configuration", - "display_name": "method Configuration.validate", - "component_id": "codewiki/cli/models/config.py::Configuration.validate", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/config.py::Configuration.to_dict": { - "id": "codewiki/cli/models/config.py::Configuration.to_dict", - "name": "Configuration.to_dict", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/config.py", - "relative_path": "codewiki/cli/models/config.py", - "depends_on": [ - "codewiki/cli/models/config.py::AgentInstructions.is_empty" - ], - "source_code": " def to_dict(self) -> dict:\n \"\"\"Convert to dictionary.\"\"\"\n result = {\n 'base_url': self.base_url,\n 'main_model': self.main_model,\n 'cluster_model': self.cluster_model,\n 'default_output': self.default_output,\n 'provider': self.provider,\n 'aws_region': self.aws_region,\n 'api_version': self.api_version,\n 'azure_deployment': self.azure_deployment,\n 'max_tokens': self.max_tokens,\n 'max_token_per_module': self.max_token_per_module,\n 'max_token_per_leaf_module': self.max_token_per_leaf_module,\n 'max_depth': self.max_depth,\n 'use_gitignore': self.use_gitignore,\n 'prompt_caching': self.prompt_caching,\n 'fallback_model': self.fallback_model,\n }\n if self.agent_instructions and not self.agent_instructions.is_empty():\n result['agent_instructions'] = self.agent_instructions.to_dict()\n return result", - "start_line": 164, - "end_line": 185, - "has_docstring": true, - "docstring": "Convert to dictionary.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "Configuration", - "display_name": "method Configuration.to_dict", - "component_id": "codewiki/cli/models/config.py::Configuration.to_dict", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/config.py::Configuration.from_dict": { - "id": "codewiki/cli/models/config.py::Configuration.from_dict", - "name": "Configuration.from_dict", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/config.py", - "relative_path": "codewiki/cli/models/config.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/cli/models/config.py::AgentInstructions", - "codewiki/cli/models/config.py::AgentInstructions.from_dict" - ], - "source_code": " def from_dict(cls, data: dict) -> 'Configuration':\n \"\"\"\n Create Configuration from dictionary.\n \n Args:\n data: Configuration dictionary\n \n Returns:\n Configuration instance\n \"\"\"\n agent_instructions = AgentInstructions()\n if 'agent_instructions' in data:\n agent_instructions = AgentInstructions.from_dict(data['agent_instructions'])\n \n return cls(\n base_url=data.get('base_url', ''),\n main_model=data.get('main_model', ''),\n cluster_model=data.get('cluster_model', ''),\n fallback_model=data.get('fallback_model', 'glm-4p5'),\n default_output=data.get('default_output', 'docs'),\n provider=data.get('provider', 'openai-compatible'),\n aws_region=data.get('aws_region', 'us-east-1'),\n api_version=data.get('api_version', '2024-12-01-preview'),\n azure_deployment=data.get('azure_deployment', ''),\n max_tokens=data.get('max_tokens', 32768),\n max_token_per_module=data.get('max_token_per_module', 36369),\n max_token_per_leaf_module=data.get('max_token_per_leaf_module', 16000),\n max_depth=data.get('max_depth', 2),\n use_gitignore=data.get('use_gitignore', True),\n prompt_caching=data.get('prompt_caching', True),\n agent_instructions=agent_instructions,\n )", - "start_line": 188, - "end_line": 219, - "has_docstring": true, - "docstring": "Create Configuration from dictionary.\n\nArgs:\n data: Configuration dictionary\n \nReturns:\n Configuration instance", - "parameters": [ - "cls", - "data" - ], - "node_type": "method", - "base_classes": null, - "class_name": "Configuration", - "display_name": "method Configuration.from_dict", - "component_id": "codewiki/cli/models/config.py::Configuration.from_dict", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/config.py::Configuration.is_complete": { - "id": "codewiki/cli/models/config.py::Configuration.is_complete", - "name": "Configuration.is_complete", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/config.py", - "relative_path": "codewiki/cli/models/config.py", - "depends_on": [ - "codewiki/src/be/backend.py::is_caw_provider" - ], - "source_code": " def is_complete(self) -> bool:\n \"\"\"Check if all required fields are set.\n\n Subscription-mode providers (claude-code, codex) only require\n ``main_model``; ``base_url``, ``cluster_model`` and ``fallback_model``\n are unused.\n \"\"\"\n from codewiki.src.be.backend import is_caw_provider\n if is_caw_provider(self.provider):\n return bool(self.main_model)\n return bool(\n self.base_url and\n self.main_model and\n self.cluster_model and\n self.fallback_model\n )", - "start_line": 221, - "end_line": 236, - "has_docstring": true, - "docstring": "Check if all required fields are set.\n\nSubscription-mode providers (claude-code, codex) only require\n``main_model``; ``base_url``, ``cluster_model`` and ``fallback_model``\nare unused.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "Configuration", - "display_name": "method Configuration.is_complete", - "component_id": "codewiki/cli/models/config.py::Configuration.is_complete", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/config.py::Configuration.to_backend_config": { - "id": "codewiki/cli/models/config.py::Configuration.to_backend_config", - "name": "Configuration.to_backend_config", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/config.py", - "relative_path": "codewiki/cli/models/config.py", - "depends_on": [ - "codewiki/cli/models/config.py::AgentInstructions.to_dict", - "codewiki/cli/models/config.py::AgentInstructions.is_empty", - "codewiki/cli/models/config.py::AgentInstructions", - "codewiki/src/config.py::Config.from_cli" - ], - "source_code": " def to_backend_config(self, repo_path: str, output_dir: str, api_key: str, runtime_instructions: AgentInstructions = None):\n \"\"\"\n Convert CLI Configuration to Backend Config.\n \n This method bridges the gap between persistent user settings (CLI Configuration)\n and runtime job configuration (Backend Config).\n \n Args:\n repo_path: Path to the repository to document\n output_dir: Output directory for generated documentation\n api_key: LLM API key (from keyring)\n runtime_instructions: Runtime agent instructions (override persistent settings)\n \n Returns:\n Backend Config instance ready for documentation generation\n \"\"\"\n from codewiki.src.config import Config\n \n # Merge runtime instructions with persistent settings\n # Runtime instructions take precedence\n final_instructions = self.agent_instructions\n if runtime_instructions and not runtime_instructions.is_empty():\n final_instructions = AgentInstructions(\n include_patterns=runtime_instructions.include_patterns or self.agent_instructions.include_patterns,\n exclude_patterns=runtime_instructions.exclude_patterns or self.agent_instructions.exclude_patterns,\n focus_modules=runtime_instructions.focus_modules or self.agent_instructions.focus_modules,\n doc_type=runtime_instructions.doc_type or self.agent_instructions.doc_type,\n custom_instructions=runtime_instructions.custom_instructions or self.agent_instructions.custom_instructions,\n )\n \n return Config.from_cli(\n repo_path=repo_path,\n output_dir=output_dir,\n llm_base_url=self.base_url,\n llm_api_key=api_key,\n main_model=self.main_model,\n cluster_model=self.cluster_model,\n fallback_model=self.fallback_model,\n provider=self.provider,\n aws_region=self.aws_region,\n api_version=self.api_version,\n azure_deployment=self.azure_deployment,\n max_tokens=self.max_tokens,\n max_token_per_module=self.max_token_per_module,\n max_token_per_leaf_module=self.max_token_per_leaf_module,\n max_depth=self.max_depth,\n agent_instructions=final_instructions.to_dict() if final_instructions else None,\n use_gitignore=self.use_gitignore,\n prompt_caching=self.prompt_caching,\n )", - "start_line": 238, - "end_line": 287, - "has_docstring": true, - "docstring": "Convert CLI Configuration to Backend Config.\n\nThis method bridges the gap between persistent user settings (CLI Configuration)\nand runtime job configuration (Backend Config).\n\nArgs:\n repo_path: Path to the repository to document\n output_dir: Output directory for generated documentation\n api_key: LLM API key (from keyring)\n runtime_instructions: Runtime agent instructions (override persistent settings)\n \nReturns:\n Backend Config instance ready for documentation generation", - "parameters": [ - "self", - "repo_path", - "output_dir", - "api_key", - "runtime_instructions" - ], - "node_type": "method", - "base_classes": null, - "class_name": "Configuration", - "display_name": "method Configuration.to_backend_config", - "component_id": "codewiki/cli/models/config.py::Configuration.to_backend_config", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/job.py::JobStatus": { - "id": "codewiki/cli/models/job.py::JobStatus", - "name": "JobStatus", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/job.py", - "relative_path": "codewiki/cli/models/job.py", - "depends_on": [], - "source_code": "class JobStatus(str, Enum):\n \"\"\"Documentation job status.\"\"\"\n PENDING = \"pending\"\n RUNNING = \"running\"\n COMPLETED = \"completed\"\n FAILED = \"failed\"", - "start_line": 13, - "end_line": 18, - "has_docstring": true, - "docstring": "Documentation job status.", - "parameters": null, - "node_type": "class", - "base_classes": [ - "str", - "Enum" - ], - "class_name": null, - "display_name": "class JobStatus", - "component_id": "codewiki/cli/models/job.py::JobStatus", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/job.py::GenerationOptions": { - "id": "codewiki/cli/models/job.py::GenerationOptions", - "name": "GenerationOptions", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/job.py", - "relative_path": "codewiki/cli/models/job.py", - "depends_on": [], - "source_code": "class GenerationOptions:\n \"\"\"Options for documentation generation.\"\"\"\n create_branch: bool = False\n github_pages: bool = False\n no_cache: bool = False\n custom_output: Optional[str] = None", - "start_line": 22, - "end_line": 27, - "has_docstring": true, - "docstring": "Options for documentation generation.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class GenerationOptions", - "component_id": "codewiki/cli/models/job.py::GenerationOptions", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/job.py::JobStatistics": { - "id": "codewiki/cli/models/job.py::JobStatistics", - "name": "JobStatistics", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/job.py", - "relative_path": "codewiki/cli/models/job.py", - "depends_on": [], - "source_code": "class JobStatistics:\n \"\"\"Statistics for a documentation job.\"\"\"\n total_files_analyzed: int = 0\n leaf_nodes: int = 0\n max_depth: int = 0\n total_tokens_used: int = 0", - "start_line": 31, - "end_line": 36, - "has_docstring": true, - "docstring": "Statistics for a documentation job.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class JobStatistics", - "component_id": "codewiki/cli/models/job.py::JobStatistics", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/job.py::LLMConfig": { - "id": "codewiki/cli/models/job.py::LLMConfig", - "name": "LLMConfig", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/job.py", - "relative_path": "codewiki/cli/models/job.py", - "depends_on": [], - "source_code": "class LLMConfig:\n \"\"\"LLM configuration for a job.\"\"\"\n main_model: str\n cluster_model: str\n base_url: str", - "start_line": 40, - "end_line": 44, - "has_docstring": true, - "docstring": "LLM configuration for a job.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class LLMConfig", - "component_id": "codewiki/cli/models/job.py::LLMConfig", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/job.py::DocumentationJob": { - "id": "codewiki/cli/models/job.py::DocumentationJob", - "name": "DocumentationJob", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/job.py", - "relative_path": "codewiki/cli/models/job.py", - "depends_on": [], - "source_code": "class DocumentationJob:\n \"\"\"\n Represents a documentation generation job.\n \n Attributes:\n job_id: Unique job identifier\n repository_path: Absolute path to repository\n repository_name: Repository name\n output_directory: Output directory path\n commit_hash: Git commit SHA\n branch_name: Git branch name (if applicable)\n timestamp_start: Job start time\n timestamp_end: Job end time (if completed)\n status: Current job status\n error_message: Error message (if failed)\n files_generated: List of generated files\n module_count: Number of modules documented\n generation_options: Generation options used\n llm_config: LLM configuration used\n statistics: Job statistics\n \"\"\"\n job_id: str = field(default_factory=lambda: str(uuid.uuid4()))\n repository_path: str = \"\"\n repository_name: str = \"\"\n output_directory: str = \"\"\n commit_hash: str = \"\"\n branch_name: Optional[str] = None\n timestamp_start: str = field(default_factory=lambda: datetime.now().isoformat())\n timestamp_end: Optional[str] = None\n status: JobStatus = JobStatus.PENDING\n error_message: Optional[str] = None\n files_generated: List[str] = field(default_factory=list)\n module_count: int = 0\n generation_options: GenerationOptions = field(default_factory=GenerationOptions)\n llm_config: Optional[LLMConfig] = None\n statistics: JobStatistics = field(default_factory=JobStatistics)\n \n def start(self):\n \"\"\"Mark job as started.\"\"\"\n self.status = JobStatus.RUNNING\n self.timestamp_start = datetime.now().isoformat()\n \n def complete(self):\n \"\"\"Mark job as completed.\"\"\"\n self.status = JobStatus.COMPLETED\n self.timestamp_end = datetime.now().isoformat()\n \n def fail(self, error_message: str):\n \"\"\"Mark job as failed.\"\"\"\n self.status = JobStatus.FAILED\n self.error_message = error_message\n self.timestamp_end = datetime.now().isoformat()\n \n def to_dict(self) -> Dict[str, Any]:\n \"\"\"Convert to dictionary for JSON serialization.\"\"\"\n data = {\n \"job_id\": self.job_id,\n \"repository_path\": self.repository_path,\n \"repository_name\": self.repository_name,\n \"output_directory\": self.output_directory,\n \"commit_hash\": self.commit_hash,\n \"branch_name\": self.branch_name,\n \"timestamp_start\": self.timestamp_start,\n \"timestamp_end\": self.timestamp_end,\n \"status\": self.status.value if isinstance(self.status, JobStatus) else self.status,\n \"error_message\": self.error_message,\n \"files_generated\": self.files_generated,\n \"module_count\": self.module_count,\n \"generation_options\": asdict(self.generation_options),\n \"llm_config\": asdict(self.llm_config) if self.llm_config else None,\n \"statistics\": asdict(self.statistics),\n }\n return data\n \n def to_json(self) -> str:\n \"\"\"Convert to JSON string.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n \n @classmethod\n def from_dict(cls, data: Dict[str, Any]) -> 'DocumentationJob':\n \"\"\"Create from dictionary.\"\"\"\n job = cls(\n job_id=data.get('job_id', str(uuid.uuid4())),\n repository_path=data.get('repository_path', ''),\n repository_name=data.get('repository_name', ''),\n output_directory=data.get('output_directory', ''),\n commit_hash=data.get('commit_hash', ''),\n branch_name=data.get('branch_name'),\n timestamp_start=data.get('timestamp_start', datetime.now().isoformat()),\n timestamp_end=data.get('timestamp_end'),\n status=JobStatus(data.get('status', 'pending')),\n error_message=data.get('error_message'),\n files_generated=data.get('files_generated', []),\n module_count=data.get('module_count', 0),\n )\n \n # Parse nested objects\n if 'generation_options' in data:\n opts = data['generation_options']\n job.generation_options = GenerationOptions(**opts)\n \n if 'llm_config' in data and data['llm_config']:\n job.llm_config = LLMConfig(**data['llm_config'])\n \n if 'statistics' in data:\n job.statistics = JobStatistics(**data['statistics'])\n \n return job", - "start_line": 48, - "end_line": 155, - "has_docstring": true, - "docstring": "Represents a documentation generation job.\n\nAttributes:\n job_id: Unique job identifier\n repository_path: Absolute path to repository\n repository_name: Repository name\n output_directory: Output directory path\n commit_hash: Git commit SHA\n branch_name: Git branch name (if applicable)\n timestamp_start: Job start time\n timestamp_end: Job end time (if completed)\n status: Current job status\n error_message: Error message (if failed)\n files_generated: List of generated files\n module_count: Number of modules documented\n generation_options: Generation options used\n llm_config: LLM configuration used\n statistics: Job statistics", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class DocumentationJob", - "component_id": "codewiki/cli/models/job.py::DocumentationJob", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/job.py::DocumentationJob.start": { - "id": "codewiki/cli/models/job.py::DocumentationJob.start", - "name": "DocumentationJob.start", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/job.py", - "relative_path": "codewiki/cli/models/job.py", - "depends_on": [], - "source_code": " def start(self):\n \"\"\"Mark job as started.\"\"\"\n self.status = JobStatus.RUNNING\n self.timestamp_start = datetime.now().isoformat()", - "start_line": 85, - "end_line": 88, - "has_docstring": true, - "docstring": "Mark job as started.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DocumentationJob", - "display_name": "method DocumentationJob.start", - "component_id": "codewiki/cli/models/job.py::DocumentationJob.start", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/job.py::DocumentationJob.complete": { - "id": "codewiki/cli/models/job.py::DocumentationJob.complete", - "name": "DocumentationJob.complete", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/job.py", - "relative_path": "codewiki/cli/models/job.py", - "depends_on": [], - "source_code": " def complete(self):\n \"\"\"Mark job as completed.\"\"\"\n self.status = JobStatus.COMPLETED\n self.timestamp_end = datetime.now().isoformat()", - "start_line": 90, - "end_line": 93, - "has_docstring": true, - "docstring": "Mark job as completed.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DocumentationJob", - "display_name": "method DocumentationJob.complete", - "component_id": "codewiki/cli/models/job.py::DocumentationJob.complete", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/job.py::DocumentationJob.fail": { - "id": "codewiki/cli/models/job.py::DocumentationJob.fail", - "name": "DocumentationJob.fail", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/job.py", - "relative_path": "codewiki/cli/models/job.py", - "depends_on": [], - "source_code": " def fail(self, error_message: str):\n \"\"\"Mark job as failed.\"\"\"\n self.status = JobStatus.FAILED\n self.error_message = error_message\n self.timestamp_end = datetime.now().isoformat()", - "start_line": 95, - "end_line": 99, - "has_docstring": true, - "docstring": "Mark job as failed.", - "parameters": [ - "self", - "error_message" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DocumentationJob", - "display_name": "method DocumentationJob.fail", - "component_id": "codewiki/cli/models/job.py::DocumentationJob.fail", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/job.py::DocumentationJob.to_dict": { - "id": "codewiki/cli/models/job.py::DocumentationJob.to_dict", - "name": "DocumentationJob.to_dict", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/job.py", - "relative_path": "codewiki/cli/models/job.py", - "depends_on": [], - "source_code": " def to_dict(self) -> Dict[str, Any]:\n \"\"\"Convert to dictionary for JSON serialization.\"\"\"\n data = {\n \"job_id\": self.job_id,\n \"repository_path\": self.repository_path,\n \"repository_name\": self.repository_name,\n \"output_directory\": self.output_directory,\n \"commit_hash\": self.commit_hash,\n \"branch_name\": self.branch_name,\n \"timestamp_start\": self.timestamp_start,\n \"timestamp_end\": self.timestamp_end,\n \"status\": self.status.value if isinstance(self.status, JobStatus) else self.status,\n \"error_message\": self.error_message,\n \"files_generated\": self.files_generated,\n \"module_count\": self.module_count,\n \"generation_options\": asdict(self.generation_options),\n \"llm_config\": asdict(self.llm_config) if self.llm_config else None,\n \"statistics\": asdict(self.statistics),\n }\n return data", - "start_line": 101, - "end_line": 120, - "has_docstring": true, - "docstring": "Convert to dictionary for JSON serialization.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DocumentationJob", - "display_name": "method DocumentationJob.to_dict", - "component_id": "codewiki/cli/models/job.py::DocumentationJob.to_dict", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/job.py::DocumentationJob.to_json": { - "id": "codewiki/cli/models/job.py::DocumentationJob.to_json", - "name": "DocumentationJob.to_json", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/job.py", - "relative_path": "codewiki/cli/models/job.py", - "depends_on": [ - "codewiki/cli/models/job.py::DocumentationJob.to_dict" - ], - "source_code": " def to_json(self) -> str:\n \"\"\"Convert to JSON string.\"\"\"\n return json.dumps(self.to_dict(), indent=2)", - "start_line": 122, - "end_line": 124, - "has_docstring": true, - "docstring": "Convert to JSON string.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DocumentationJob", - "display_name": "method DocumentationJob.to_json", - "component_id": "codewiki/cli/models/job.py::DocumentationJob.to_json", - "language": null, - "qualified_name": null - }, - "codewiki/cli/models/job.py::DocumentationJob.from_dict": { - "id": "codewiki/cli/models/job.py::DocumentationJob.from_dict", - "name": "DocumentationJob.from_dict", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/models/job.py", - "relative_path": "codewiki/cli/models/job.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/cli/models/job.py::LLMConfig", - "codewiki/cli/models/job.py::JobStatistics", - "codewiki/cli/models/job.py::JobStatus", - "codewiki/cli/models/job.py::GenerationOptions" - ], - "source_code": " def from_dict(cls, data: Dict[str, Any]) -> 'DocumentationJob':\n \"\"\"Create from dictionary.\"\"\"\n job = cls(\n job_id=data.get('job_id', str(uuid.uuid4())),\n repository_path=data.get('repository_path', ''),\n repository_name=data.get('repository_name', ''),\n output_directory=data.get('output_directory', ''),\n commit_hash=data.get('commit_hash', ''),\n branch_name=data.get('branch_name'),\n timestamp_start=data.get('timestamp_start', datetime.now().isoformat()),\n timestamp_end=data.get('timestamp_end'),\n status=JobStatus(data.get('status', 'pending')),\n error_message=data.get('error_message'),\n files_generated=data.get('files_generated', []),\n module_count=data.get('module_count', 0),\n )\n \n # Parse nested objects\n if 'generation_options' in data:\n opts = data['generation_options']\n job.generation_options = GenerationOptions(**opts)\n \n if 'llm_config' in data and data['llm_config']:\n job.llm_config = LLMConfig(**data['llm_config'])\n \n if 'statistics' in data:\n job.statistics = JobStatistics(**data['statistics'])\n \n return job", - "start_line": 127, - "end_line": 155, - "has_docstring": true, - "docstring": "Create from dictionary.", - "parameters": [ - "cls", - "data" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DocumentationJob", - "display_name": "method DocumentationJob.from_dict", - "component_id": "codewiki/cli/models/job.py::DocumentationJob.from_dict", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/api_errors.py::APIErrorHandler": { - "id": "codewiki/cli/utils/api_errors.py::APIErrorHandler", - "name": "APIErrorHandler", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/api_errors.py", - "relative_path": "codewiki/cli/utils/api_errors.py", - "depends_on": [], - "source_code": "class APIErrorHandler:\n \"\"\"Handler for LLM API errors with fail-fast behavior.\"\"\"\n \n @staticmethod\n def handle_api_error(\n error: Exception,\n context: Optional[str] = None,\n fail_fast: bool = True\n ) -> APIError:\n \"\"\"\n Handle LLM API error and convert to APIError.\n \n Args:\n error: The original exception\n context: Additional context (e.g., module name)\n fail_fast: Whether to fail immediately (default: True)\n \n Returns:\n APIError instance\n \"\"\"\n error_message = str(error)\n \n # Detect specific error types\n if \"429\" in error_message or \"rate limit\" in error_message.lower():\n message = (\n \"LLM API rate limit exceeded.\\n\\n\"\n \"The API returned a 429 error, indicating too many requests.\\n\\n\"\n \"Troubleshooting:\\n\"\n \" 1. Wait a few minutes before retrying\\n\"\n \" 2. Check your API quota at your provider's dashboard\\n\"\n \" 3. Consider upgrading your API plan\\n\"\n \" 4. For large repositories, generate during off-peak hours\"\n )\n elif \"401\" in error_message or \"authentication\" in error_message.lower():\n message = (\n \"LLM API authentication failed.\\n\\n\"\n \"Your API key appears to be invalid or expired.\\n\\n\"\n \"Troubleshooting:\\n\"\n \" 1. Verify your API key: codewiki config show\\n\"\n \" 2. Update your API key: codewiki config set --api-key \\n\"\n \" 3. Check that your API key is active in your provider's dashboard\"\n )\n elif \"timeout\" in error_message.lower():\n message = (\n \"LLM API request timed out.\\n\\n\"\n \"The API did not respond within the expected time.\\n\\n\"\n \"Troubleshooting:\\n\"\n \" 1. Check your internet connection\\n\"\n \" 2. Verify the API service is operational\\n\"\n \" 3. Try again in a few moments\\n\"\n \" 4. If the issue persists, contact your API provider\"\n )\n elif \"network\" in error_message.lower() or \"connection\" in error_message.lower():\n message = (\n \"Network error while connecting to LLM API.\\n\\n\"\n \"Could not establish connection to the API.\\n\\n\"\n \"Troubleshooting:\\n\"\n \" 1. Check your internet connection\\n\"\n \" 2. Verify the base URL: codewiki config show\\n\"\n \" 3. Check if you're behind a proxy or firewall\\n\"\n \" 4. Try: curl -I to test connectivity\"\n )\n else:\n message = (\n f\"LLM API error: {error_message}\\n\\n\"\n \"An unexpected error occurred while communicating with the LLM API.\\n\\n\"\n \"Troubleshooting:\\n\"\n \" 1. Check your configuration: codewiki config validate\\n\"\n \" 2. Verify API service status\\n\"\n \" 3. Review the error message above for specific details\"\n )\n \n if context:\n message = f\"Context: {context}\\n\\n{message}\"\n \n return APIError(message)\n \n @staticmethod\n def display_api_error(error: APIError, module_name: Optional[str] = None):\n \"\"\"\n Display API error with formatting.\n \n Args:\n error: The API error\n module_name: Optional module name for context\n \"\"\"\n click.echo()\n click.secho(\"βœ— LLM API Error\", fg=\"red\", bold=True)\n click.echo()\n \n if module_name:\n click.echo(f\"Module: {module_name}\")\n click.echo()\n \n click.echo(error.message)\n click.echo()\n click.secho(\n \"Documentation generation stopped. No partial results saved.\",\n fg=\"yellow\"\n )\n click.echo()", - "start_line": 11, - "end_line": 111, - "has_docstring": true, - "docstring": "Handler for LLM API errors with fail-fast behavior.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class APIErrorHandler", - "component_id": "codewiki/cli/utils/api_errors.py::APIErrorHandler", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/api_errors.py::APIErrorHandler.handle_api_error": { - "id": "codewiki/cli/utils/api_errors.py::APIErrorHandler.handle_api_error", - "name": "APIErrorHandler.handle_api_error", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/api_errors.py", - "relative_path": "codewiki/cli/utils/api_errors.py", - "depends_on": [ - "codewiki/cli/utils/errors.py::APIError" - ], - "source_code": " def handle_api_error(\n error: Exception,\n context: Optional[str] = None,\n fail_fast: bool = True\n ) -> APIError:\n \"\"\"\n Handle LLM API error and convert to APIError.\n \n Args:\n error: The original exception\n context: Additional context (e.g., module name)\n fail_fast: Whether to fail immediately (default: True)\n \n Returns:\n APIError instance\n \"\"\"\n error_message = str(error)\n \n # Detect specific error types\n if \"429\" in error_message or \"rate limit\" in error_message.lower():\n message = (\n \"LLM API rate limit exceeded.\\n\\n\"\n \"The API returned a 429 error, indicating too many requests.\\n\\n\"\n \"Troubleshooting:\\n\"\n \" 1. Wait a few minutes before retrying\\n\"\n \" 2. Check your API quota at your provider's dashboard\\n\"\n \" 3. Consider upgrading your API plan\\n\"\n \" 4. For large repositories, generate during off-peak hours\"\n )\n elif \"401\" in error_message or \"authentication\" in error_message.lower():\n message = (\n \"LLM API authentication failed.\\n\\n\"\n \"Your API key appears to be invalid or expired.\\n\\n\"\n \"Troubleshooting:\\n\"\n \" 1. Verify your API key: codewiki config show\\n\"\n \" 2. Update your API key: codewiki config set --api-key \\n\"\n \" 3. Check that your API key is active in your provider's dashboard\"\n )\n elif \"timeout\" in error_message.lower():\n message = (\n \"LLM API request timed out.\\n\\n\"\n \"The API did not respond within the expected time.\\n\\n\"\n \"Troubleshooting:\\n\"\n \" 1. Check your internet connection\\n\"\n \" 2. Verify the API service is operational\\n\"\n \" 3. Try again in a few moments\\n\"\n \" 4. If the issue persists, contact your API provider\"\n )\n elif \"network\" in error_message.lower() or \"connection\" in error_message.lower():\n message = (\n \"Network error while connecting to LLM API.\\n\\n\"\n \"Could not establish connection to the API.\\n\\n\"\n \"Troubleshooting:\\n\"\n \" 1. Check your internet connection\\n\"\n \" 2. Verify the base URL: codewiki config show\\n\"\n \" 3. Check if you're behind a proxy or firewall\\n\"\n \" 4. Try: curl -I to test connectivity\"\n )\n else:\n message = (\n f\"LLM API error: {error_message}\\n\\n\"\n \"An unexpected error occurred while communicating with the LLM API.\\n\\n\"\n \"Troubleshooting:\\n\"\n \" 1. Check your configuration: codewiki config validate\\n\"\n \" 2. Verify API service status\\n\"\n \" 3. Review the error message above for specific details\"\n )\n \n if context:\n message = f\"Context: {context}\\n\\n{message}\"\n \n return APIError(message)", - "start_line": 15, - "end_line": 86, - "has_docstring": true, - "docstring": "Handle LLM API error and convert to APIError.\n\nArgs:\n error: The original exception\n context: Additional context (e.g., module name)\n fail_fast: Whether to fail immediately (default: True)\n \nReturns:\n APIError instance", - "parameters": [ - "error", - "context", - "fail_fast" - ], - "node_type": "method", - "base_classes": null, - "class_name": "APIErrorHandler", - "display_name": "method APIErrorHandler.handle_api_error", - "component_id": "codewiki/cli/utils/api_errors.py::APIErrorHandler.handle_api_error", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/api_errors.py::APIErrorHandler.display_api_error": { - "id": "codewiki/cli/utils/api_errors.py::APIErrorHandler.display_api_error", - "name": "APIErrorHandler.display_api_error", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/api_errors.py", - "relative_path": "codewiki/cli/utils/api_errors.py", - "depends_on": [], - "source_code": " def display_api_error(error: APIError, module_name: Optional[str] = None):\n \"\"\"\n Display API error with formatting.\n \n Args:\n error: The API error\n module_name: Optional module name for context\n \"\"\"\n click.echo()\n click.secho(\"βœ— LLM API Error\", fg=\"red\", bold=True)\n click.echo()\n \n if module_name:\n click.echo(f\"Module: {module_name}\")\n click.echo()\n \n click.echo(error.message)\n click.echo()\n click.secho(\n \"Documentation generation stopped. No partial results saved.\",\n fg=\"yellow\"\n )\n click.echo()", - "start_line": 89, - "end_line": 111, - "has_docstring": true, - "docstring": "Display API error with formatting.\n\nArgs:\n error: The API error\n module_name: Optional module name for context", - "parameters": [ - "error", - "module_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "APIErrorHandler", - "display_name": "method APIErrorHandler.display_api_error", - "component_id": "codewiki/cli/utils/api_errors.py::APIErrorHandler.display_api_error", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/api_errors.py::wrap_api_call": { - "id": "codewiki/cli/utils/api_errors.py::wrap_api_call", - "name": "wrap_api_call", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/api_errors.py", - "relative_path": "codewiki/cli/utils/api_errors.py", - "depends_on": [ - "codewiki/cli/utils/api_errors.py::APIErrorHandler.display_api_error", - "codewiki/cli/utils/api_errors.py::APIErrorHandler.handle_api_error" - ], - "source_code": "def wrap_api_call(func, *args, fail_fast: bool = True, context: Optional[str] = None, **kwargs):\n \"\"\"\n Wrap an API call with error handling.\n \n Args:\n func: Function to call\n *args: Positional arguments\n fail_fast: Whether to raise on error (default: True)\n context: Optional context for error message\n **kwargs: Keyword arguments\n \n Returns:\n Function result\n \n Raises:\n APIError: If API call fails and fail_fast is True\n \"\"\"\n try:\n return func(*args, **kwargs)\n except Exception as e:\n api_error = APIErrorHandler.handle_api_error(e, context=context, fail_fast=fail_fast)\n if fail_fast:\n raise api_error\n else:\n APIErrorHandler.display_api_error(api_error)\n return None", - "start_line": 114, - "end_line": 139, - "has_docstring": true, - "docstring": "Wrap an API call with error handling.\n\nArgs:\n func: Function to call\n *args: Positional arguments\n fail_fast: Whether to raise on error (default: True)\n context: Optional context for error message\n **kwargs: Keyword arguments\n \nReturns:\n Function result\n \nRaises:\n APIError: If API call fails and fail_fast is True", - "parameters": [ - "func" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function wrap_api_call", - "component_id": "codewiki/cli/utils/api_errors.py::wrap_api_call", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/errors.py::CodeWikiError": { - "id": "codewiki/cli/utils/errors.py::CodeWikiError", - "name": "CodeWikiError", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/errors.py", - "relative_path": "codewiki/cli/utils/errors.py", - "depends_on": [], - "source_code": "class CodeWikiError(Exception):\n \"\"\"Base exception for CodeWiki CLI errors.\"\"\"\n \n def __init__(self, message: str, exit_code: int = EXIT_GENERAL_ERROR):\n self.message = message\n self.exit_code = exit_code\n super().__init__(self.message)", - "start_line": 27, - "end_line": 33, - "has_docstring": true, - "docstring": "Base exception for CodeWiki CLI errors.", - "parameters": null, - "node_type": "class", - "base_classes": [ - "Exception" - ], - "class_name": null, - "display_name": "class CodeWikiError", - "component_id": "codewiki/cli/utils/errors.py::CodeWikiError", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/errors.py::CodeWikiError.__init__": { - "id": "codewiki/cli/utils/errors.py::CodeWikiError.__init__", - "name": "CodeWikiError.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/errors.py", - "relative_path": "codewiki/cli/utils/errors.py", - "depends_on": [], - "source_code": " def __init__(self, message: str, exit_code: int = EXIT_GENERAL_ERROR):\n self.message = message\n self.exit_code = exit_code\n super().__init__(self.message)", - "start_line": 30, - "end_line": 33, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "message", - "exit_code" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CodeWikiError", - "display_name": "method CodeWikiError.__init__", - "component_id": "codewiki/cli/utils/errors.py::CodeWikiError.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/errors.py::ConfigurationError": { - "id": "codewiki/cli/utils/errors.py::ConfigurationError", - "name": "ConfigurationError", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/errors.py", - "relative_path": "codewiki/cli/utils/errors.py", - "depends_on": [ - "codewiki/cli/utils/errors.py::CodeWikiError" - ], - "source_code": "class ConfigurationError(CodeWikiError):\n \"\"\"Configuration-related errors.\"\"\"\n \n def __init__(self, message: str):\n super().__init__(message, EXIT_CONFIG_ERROR)", - "start_line": 36, - "end_line": 40, - "has_docstring": true, - "docstring": "Configuration-related errors.", - "parameters": null, - "node_type": "class", - "base_classes": [ - "CodeWikiError" - ], - "class_name": null, - "display_name": "class ConfigurationError", - "component_id": "codewiki/cli/utils/errors.py::ConfigurationError", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/errors.py::ConfigurationError.__init__": { - "id": "codewiki/cli/utils/errors.py::ConfigurationError.__init__", - "name": "ConfigurationError.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/errors.py", - "relative_path": "codewiki/cli/utils/errors.py", - "depends_on": [ - "codewiki/cli/utils/errors.py::CodeWikiError.__init__" - ], - "source_code": " def __init__(self, message: str):\n super().__init__(message, EXIT_CONFIG_ERROR)", - "start_line": 39, - "end_line": 40, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "message" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ConfigurationError", - "display_name": "method ConfigurationError.__init__", - "component_id": "codewiki/cli/utils/errors.py::ConfigurationError.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/errors.py::RepositoryError": { - "id": "codewiki/cli/utils/errors.py::RepositoryError", - "name": "RepositoryError", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/errors.py", - "relative_path": "codewiki/cli/utils/errors.py", - "depends_on": [ - "codewiki/cli/utils/errors.py::CodeWikiError" - ], - "source_code": "class RepositoryError(CodeWikiError):\n \"\"\"Repository-related errors.\"\"\"\n \n def __init__(self, message: str):\n super().__init__(message, EXIT_REPOSITORY_ERROR)", - "start_line": 43, - "end_line": 47, - "has_docstring": true, - "docstring": "Repository-related errors.", - "parameters": null, - "node_type": "class", - "base_classes": [ - "CodeWikiError" - ], - "class_name": null, - "display_name": "class RepositoryError", - "component_id": "codewiki/cli/utils/errors.py::RepositoryError", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/errors.py::RepositoryError.__init__": { - "id": "codewiki/cli/utils/errors.py::RepositoryError.__init__", - "name": "RepositoryError.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/errors.py", - "relative_path": "codewiki/cli/utils/errors.py", - "depends_on": [ - "codewiki/cli/utils/errors.py::CodeWikiError.__init__" - ], - "source_code": " def __init__(self, message: str):\n super().__init__(message, EXIT_REPOSITORY_ERROR)", - "start_line": 46, - "end_line": 47, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "message" - ], - "node_type": "method", - "base_classes": null, - "class_name": "RepositoryError", - "display_name": "method RepositoryError.__init__", - "component_id": "codewiki/cli/utils/errors.py::RepositoryError.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/errors.py::APIError": { - "id": "codewiki/cli/utils/errors.py::APIError", - "name": "APIError", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/errors.py", - "relative_path": "codewiki/cli/utils/errors.py", - "depends_on": [ - "codewiki/cli/utils/errors.py::CodeWikiError" - ], - "source_code": "class APIError(CodeWikiError):\n \"\"\"LLM API-related errors.\"\"\"\n \n def __init__(self, message: str):\n super().__init__(message, EXIT_API_ERROR)", - "start_line": 50, - "end_line": 54, - "has_docstring": true, - "docstring": "LLM API-related errors.", - "parameters": null, - "node_type": "class", - "base_classes": [ - "CodeWikiError" - ], - "class_name": null, - "display_name": "class APIError", - "component_id": "codewiki/cli/utils/errors.py::APIError", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/errors.py::APIError.__init__": { - "id": "codewiki/cli/utils/errors.py::APIError.__init__", - "name": "APIError.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/errors.py", - "relative_path": "codewiki/cli/utils/errors.py", - "depends_on": [ - "codewiki/cli/utils/errors.py::CodeWikiError.__init__" - ], - "source_code": " def __init__(self, message: str):\n super().__init__(message, EXIT_API_ERROR)", - "start_line": 53, - "end_line": 54, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "message" - ], - "node_type": "method", - "base_classes": null, - "class_name": "APIError", - "display_name": "method APIError.__init__", - "component_id": "codewiki/cli/utils/errors.py::APIError.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/errors.py::FileSystemError": { - "id": "codewiki/cli/utils/errors.py::FileSystemError", - "name": "FileSystemError", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/errors.py", - "relative_path": "codewiki/cli/utils/errors.py", - "depends_on": [ - "codewiki/cli/utils/errors.py::CodeWikiError" - ], - "source_code": "class FileSystemError(CodeWikiError):\n \"\"\"File system-related errors.\"\"\"\n\n def __init__(self, message: str):\n super().__init__(message, EXIT_FILESYSTEM_ERROR)", - "start_line": 57, - "end_line": 61, - "has_docstring": true, - "docstring": "File system-related errors.", - "parameters": null, - "node_type": "class", - "base_classes": [ - "CodeWikiError" - ], - "class_name": null, - "display_name": "class FileSystemError", - "component_id": "codewiki/cli/utils/errors.py::FileSystemError", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/errors.py::FileSystemError.__init__": { - "id": "codewiki/cli/utils/errors.py::FileSystemError.__init__", - "name": "FileSystemError.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/errors.py", - "relative_path": "codewiki/cli/utils/errors.py", - "depends_on": [ - "codewiki/cli/utils/errors.py::CodeWikiError.__init__" - ], - "source_code": " def __init__(self, message: str):\n super().__init__(message, EXIT_FILESYSTEM_ERROR)", - "start_line": 60, - "end_line": 61, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "message" - ], - "node_type": "method", - "base_classes": null, - "class_name": "FileSystemError", - "display_name": "method FileSystemError.__init__", - "component_id": "codewiki/cli/utils/errors.py::FileSystemError.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/errors.py::IncompleteGenerationError": { - "id": "codewiki/cli/utils/errors.py::IncompleteGenerationError", - "name": "IncompleteGenerationError", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/errors.py", - "relative_path": "codewiki/cli/utils/errors.py", - "depends_on": [ - "codewiki/cli/utils/errors.py::CodeWikiError" - ], - "source_code": "class IncompleteGenerationError(CodeWikiError):\n \"\"\"Generation finished but some module docs are missing on disk.\"\"\"\n\n def __init__(self, message: str, missing_modules: list = None):\n self.missing_modules = missing_modules or []\n super().__init__(message, EXIT_GENERAL_ERROR)", - "start_line": 64, - "end_line": 69, - "has_docstring": true, - "docstring": "Generation finished but some module docs are missing on disk.", - "parameters": null, - "node_type": "class", - "base_classes": [ - "CodeWikiError" - ], - "class_name": null, - "display_name": "class IncompleteGenerationError", - "component_id": "codewiki/cli/utils/errors.py::IncompleteGenerationError", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/errors.py::IncompleteGenerationError.__init__": { - "id": "codewiki/cli/utils/errors.py::IncompleteGenerationError.__init__", - "name": "IncompleteGenerationError.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/errors.py", - "relative_path": "codewiki/cli/utils/errors.py", - "depends_on": [ - "codewiki/cli/utils/errors.py::CodeWikiError.__init__" - ], - "source_code": " def __init__(self, message: str, missing_modules: list = None):\n self.missing_modules = missing_modules or []\n super().__init__(message, EXIT_GENERAL_ERROR)", - "start_line": 67, - "end_line": 69, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "message", - "missing_modules" - ], - "node_type": "method", - "base_classes": null, - "class_name": "IncompleteGenerationError", - "display_name": "method IncompleteGenerationError.__init__", - "component_id": "codewiki/cli/utils/errors.py::IncompleteGenerationError.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/errors.py::handle_error": { - "id": "codewiki/cli/utils/errors.py::handle_error", - "name": "handle_error", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/errors.py", - "relative_path": "codewiki/cli/utils/errors.py", - "depends_on": [], - "source_code": "def handle_error(error: Exception, verbose: bool = False) -> int:\n \"\"\"\n Handle errors and return appropriate exit code.\n \n Args:\n error: The exception to handle\n verbose: Whether to show detailed error information\n \n Returns:\n Exit code for the error\n \"\"\"\n if isinstance(error, CodeWikiError):\n click.secho(f\"\\nβœ— Error: {error.message}\", fg=\"red\", err=True)\n return error.exit_code\n else:\n click.secho(f\"\\nβœ— Unexpected error: {error}\", fg=\"red\", err=True)\n if verbose:\n import traceback\n click.echo(traceback.format_exc(), err=True)\n return EXIT_GENERAL_ERROR", - "start_line": 72, - "end_line": 91, - "has_docstring": true, - "docstring": "Handle errors and return appropriate exit code.\n\nArgs:\n error: The exception to handle\n verbose: Whether to show detailed error information\n \nReturns:\n Exit code for the error", - "parameters": [ - "error", - "verbose" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function handle_error", - "component_id": "codewiki/cli/utils/errors.py::handle_error", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/errors.py::error_with_suggestion": { - "id": "codewiki/cli/utils/errors.py::error_with_suggestion", - "name": "error_with_suggestion", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/errors.py", - "relative_path": "codewiki/cli/utils/errors.py", - "depends_on": [], - "source_code": "def error_with_suggestion(message: str, suggestion: str, exit_code: int = EXIT_GENERAL_ERROR):\n \"\"\"\n Display error message with actionable suggestion and exit.\n \n Args:\n message: The error message\n suggestion: Suggested action to resolve the error\n exit_code: Exit code to use\n \"\"\"\n click.secho(f\"\\nβœ— Error: {message}\", fg=\"red\", err=True)\n click.echo(f\"\\n{suggestion}\", err=True)\n sys.exit(exit_code)", - "start_line": 94, - "end_line": 105, - "has_docstring": true, - "docstring": "Display error message with actionable suggestion and exit.\n\nArgs:\n message: The error message\n suggestion: Suggested action to resolve the error\n exit_code: Exit code to use", - "parameters": [ - "message", - "suggestion", - "exit_code" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function error_with_suggestion", - "component_id": "codewiki/cli/utils/errors.py::error_with_suggestion", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/errors.py::warning": { - "id": "codewiki/cli/utils/errors.py::warning", - "name": "warning", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/errors.py", - "relative_path": "codewiki/cli/utils/errors.py", - "depends_on": [], - "source_code": "def warning(message: str):\n \"\"\"Display a warning message.\"\"\"\n click.secho(f\"⚠️ {message}\", fg=\"yellow\")", - "start_line": 108, - "end_line": 110, - "has_docstring": true, - "docstring": "Display a warning message.", - "parameters": [ - "message" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function warning", - "component_id": "codewiki/cli/utils/errors.py::warning", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/errors.py::success": { - "id": "codewiki/cli/utils/errors.py::success", - "name": "success", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/errors.py", - "relative_path": "codewiki/cli/utils/errors.py", - "depends_on": [], - "source_code": "def success(message: str):\n \"\"\"Display a success message.\"\"\"\n click.secho(f\"βœ“ {message}\", fg=\"green\")", - "start_line": 113, - "end_line": 115, - "has_docstring": true, - "docstring": "Display a success message.", - "parameters": [ - "message" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function success", - "component_id": "codewiki/cli/utils/errors.py::success", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/errors.py::info": { - "id": "codewiki/cli/utils/errors.py::info", - "name": "info", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/errors.py", - "relative_path": "codewiki/cli/utils/errors.py", - "depends_on": [], - "source_code": "def info(message: str):\n \"\"\"Display an info message.\"\"\"\n click.echo(message)", - "start_line": 118, - "end_line": 120, - "has_docstring": true, - "docstring": "Display an info message.", - "parameters": [ - "message" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function info", - "component_id": "codewiki/cli/utils/errors.py::info", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/fs.py::ensure_directory": { - "id": "codewiki/cli/utils/fs.py::ensure_directory", - "name": "ensure_directory", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/fs.py", - "relative_path": "codewiki/cli/utils/fs.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/cli/utils/errors.py::FileSystemError" - ], - "source_code": "def ensure_directory(path: Path, mode: int = 0o700) -> Path:\n \"\"\"\n Ensure directory exists, create if necessary.\n \n Args:\n path: Directory path\n mode: Directory permissions (default: 0o700 - user only)\n \n Returns:\n Path to the directory\n \n Raises:\n FileSystemError: If directory cannot be created\n \"\"\"\n try:\n path = Path(path).expanduser().resolve()\n path.mkdir(parents=True, exist_ok=True, mode=mode)\n return path\n except PermissionError:\n raise FileSystemError(\n f\"Permission denied: Cannot create directory {path}\\n\"\n f\"Try: chmod u+w {path.parent}\"\n )\n except OSError as e:\n raise FileSystemError(f\"Cannot create directory {path}: {e}\")", - "start_line": 13, - "end_line": 37, - "has_docstring": true, - "docstring": "Ensure directory exists, create if necessary.\n\nArgs:\n path: Directory path\n mode: Directory permissions (default: 0o700 - user only)\n \nReturns:\n Path to the directory\n \nRaises:\n FileSystemError: If directory cannot be created", - "parameters": [ - "path", - "mode" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function ensure_directory", - "component_id": "codewiki/cli/utils/fs.py::ensure_directory", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/fs.py::check_writable": { - "id": "codewiki/cli/utils/fs.py::check_writable", - "name": "check_writable", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/fs.py", - "relative_path": "codewiki/cli/utils/fs.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve" - ], - "source_code": "def check_writable(path: Path) -> bool:\n \"\"\"\n Check if a path is writable.\n \n Args:\n path: Path to check\n \n Returns:\n True if writable, False otherwise\n \"\"\"\n path = Path(path).expanduser().resolve()\n \n if path.exists():\n return os.access(path, os.W_OK)\n else:\n # Check parent directory if path doesn't exist\n parent = path.parent\n return parent.exists() and os.access(parent, os.W_OK)", - "start_line": 40, - "end_line": 57, - "has_docstring": true, - "docstring": "Check if a path is writable.\n\nArgs:\n path: Path to check\n \nReturns:\n True if writable, False otherwise", - "parameters": [ - "path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function check_writable", - "component_id": "codewiki/cli/utils/fs.py::check_writable", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/fs.py::safe_write": { - "id": "codewiki/cli/utils/fs.py::safe_write", - "name": "safe_write", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/fs.py", - "relative_path": "codewiki/cli/utils/fs.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/cli/utils/errors.py::FileSystemError" - ], - "source_code": "def safe_write(path: Path, content: str, encoding: str = \"utf-8\"):\n \"\"\"\n Safely write content to a file using atomic write (temp file + rename).\n \n Args:\n path: File path\n content: Content to write\n encoding: File encoding\n \n Raises:\n FileSystemError: If write fails\n \"\"\"\n path = Path(path).expanduser().resolve()\n temp_path = path.with_suffix(path.suffix + \".tmp\")\n \n try:\n # Write to temp file\n with open(temp_path, \"w\", encoding=encoding) as f:\n f.write(content)\n \n # Atomic rename\n temp_path.replace(path)\n except Exception as e:\n # Clean up temp file if it exists\n if temp_path.exists():\n temp_path.unlink()\n raise FileSystemError(f\"Cannot write to {path}: {e}\")", - "start_line": 60, - "end_line": 86, - "has_docstring": true, - "docstring": "Safely write content to a file using atomic write (temp file + rename).\n\nArgs:\n path: File path\n content: Content to write\n encoding: File encoding\n \nRaises:\n FileSystemError: If write fails", - "parameters": [ - "path", - "content", - "encoding" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function safe_write", - "component_id": "codewiki/cli/utils/fs.py::safe_write", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/fs.py::safe_read": { - "id": "codewiki/cli/utils/fs.py::safe_read", - "name": "safe_read", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/fs.py", - "relative_path": "codewiki/cli/utils/fs.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/cli/utils/errors.py::FileSystemError" - ], - "source_code": "def safe_read(path: Path, encoding: str = \"utf-8\") -> str:\n \"\"\"\n Safely read content from a file.\n \n Args:\n path: File path\n encoding: File encoding\n \n Returns:\n File content\n \n Raises:\n FileSystemError: If read fails\n \"\"\"\n path = Path(path).expanduser().resolve()\n \n try:\n with open(path, \"r\", encoding=encoding) as f:\n return f.read()\n except FileNotFoundError:\n raise FileSystemError(f\"File not found: {path}\")\n except PermissionError:\n raise FileSystemError(f\"Permission denied: Cannot read {path}\")\n except Exception as e:\n raise FileSystemError(f\"Cannot read {path}: {e}\")", - "start_line": 89, - "end_line": 113, - "has_docstring": true, - "docstring": "Safely read content from a file.\n\nArgs:\n path: File path\n encoding: File encoding\n \nReturns:\n File content\n \nRaises:\n FileSystemError: If read fails", - "parameters": [ - "path", - "encoding" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function safe_read", - "component_id": "codewiki/cli/utils/fs.py::safe_read", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/fs.py::get_file_size": { - "id": "codewiki/cli/utils/fs.py::get_file_size", - "name": "get_file_size", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/fs.py", - "relative_path": "codewiki/cli/utils/fs.py", - "depends_on": [], - "source_code": "def get_file_size(path: Path) -> int:\n \"\"\"\n Get file size in bytes.\n \n Args:\n path: File path\n \n Returns:\n File size in bytes\n \"\"\"\n return Path(path).stat().st_size", - "start_line": 116, - "end_line": 126, - "has_docstring": true, - "docstring": "Get file size in bytes.\n\nArgs:\n path: File path\n \nReturns:\n File size in bytes", - "parameters": [ - "path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function get_file_size", - "component_id": "codewiki/cli/utils/fs.py::get_file_size", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/fs.py::find_files": { - "id": "codewiki/cli/utils/fs.py::find_files", - "name": "find_files", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/fs.py", - "relative_path": "codewiki/cli/utils/fs.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve" - ], - "source_code": "def find_files(\n directory: Path,\n extensions: Optional[List[str]] = None,\n recursive: bool = True\n) -> List[Path]:\n \"\"\"\n Find files in directory matching extensions.\n \n Args:\n directory: Directory to search\n extensions: List of file extensions (e.g., ['.py', '.java'])\n recursive: Search recursively\n \n Returns:\n List of matching file paths\n \"\"\"\n directory = Path(directory).expanduser().resolve()\n \n if not directory.exists():\n return []\n \n pattern = \"**/*\" if recursive else \"*\"\n files = []\n \n for path in directory.glob(pattern):\n if not path.is_file():\n continue\n \n if extensions is None or path.suffix in extensions:\n files.append(path)\n \n return files", - "start_line": 129, - "end_line": 160, - "has_docstring": true, - "docstring": "Find files in directory matching extensions.\n\nArgs:\n directory: Directory to search\n extensions: List of file extensions (e.g., ['.py', '.java'])\n recursive: Search recursively\n \nReturns:\n List of matching file paths", - "parameters": [ - "directory", - "extensions", - "recursive" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function find_files", - "component_id": "codewiki/cli/utils/fs.py::find_files", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/fs.py::cleanup_directory": { - "id": "codewiki/cli/utils/fs.py::cleanup_directory", - "name": "cleanup_directory", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/fs.py", - "relative_path": "codewiki/cli/utils/fs.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/cli/utils/errors.py::FileSystemError" - ], - "source_code": "def cleanup_directory(path: Path, keep_hidden: bool = True):\n \"\"\"\n Clean up a directory by removing its contents.\n \n Args:\n path: Directory to clean\n keep_hidden: Keep hidden files/directories (starting with .)\n \n Raises:\n FileSystemError: If cleanup fails\n \"\"\"\n path = Path(path).expanduser().resolve()\n \n if not path.exists():\n return\n \n try:\n for item in path.iterdir():\n if keep_hidden and item.name.startswith('.'):\n continue\n \n if item.is_file():\n item.unlink()\n elif item.is_dir():\n shutil.rmtree(item)\n except Exception as e:\n raise FileSystemError(f\"Cannot clean directory {path}: {e}\")", - "start_line": 163, - "end_line": 189, - "has_docstring": true, - "docstring": "Clean up a directory by removing its contents.\n\nArgs:\n path: Directory to clean\n keep_hidden: Keep hidden files/directories (starting with .)\n \nRaises:\n FileSystemError: If cleanup fails", - "parameters": [ - "path", - "keep_hidden" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function cleanup_directory", - "component_id": "codewiki/cli/utils/fs.py::cleanup_directory", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/instructions.py::compute_github_pages_url": { - "id": "codewiki/cli/utils/instructions.py::compute_github_pages_url", - "name": "compute_github_pages_url", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/instructions.py", - "relative_path": "codewiki/cli/utils/instructions.py", - "depends_on": [], - "source_code": "def compute_github_pages_url(repo_url: str, repo_name: str) -> str:\n \"\"\"\n Compute expected GitHub Pages URL from repository URL.\n \n Args:\n repo_url: GitHub repository URL\n repo_name: Repository name\n \n Returns:\n Expected GitHub Pages URL\n \"\"\"\n # Extract owner from GitHub URL\n # e.g., \"https://github.com/owner/repo\" -> \"owner\"\n if \"github.com\" in repo_url:\n parts = repo_url.rstrip('/').split('/')\n if len(parts) >= 2:\n owner = parts[-2]\n repo = parts[-1].replace('.git', '')\n return f\"https://{owner}.github.io/{repo}/\"\n \n return f\"https://YOUR_USERNAME.github.io/{repo_name}/\"", - "start_line": 10, - "end_line": 30, - "has_docstring": true, - "docstring": "Compute expected GitHub Pages URL from repository URL.\n\nArgs:\n repo_url: GitHub repository URL\n repo_name: Repository name\n \nReturns:\n Expected GitHub Pages URL", - "parameters": [ - "repo_url", - "repo_name" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function compute_github_pages_url", - "component_id": "codewiki/cli/utils/instructions.py::compute_github_pages_url", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/instructions.py::get_pr_creation_url": { - "id": "codewiki/cli/utils/instructions.py::get_pr_creation_url", - "name": "get_pr_creation_url", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/instructions.py", - "relative_path": "codewiki/cli/utils/instructions.py", - "depends_on": [], - "source_code": "def get_pr_creation_url(repo_url: str, branch_name: str) -> str:\n \"\"\"\n Get PR creation URL for GitHub.\n \n Args:\n repo_url: GitHub repository URL\n branch_name: Branch name\n \n Returns:\n PR creation URL\n \"\"\"\n base_url = repo_url.rstrip('/').replace('.git', '')\n return f\"{base_url}/compare/{branch_name}\"", - "start_line": 33, - "end_line": 45, - "has_docstring": true, - "docstring": "Get PR creation URL for GitHub.\n\nArgs:\n repo_url: GitHub repository URL\n branch_name: Branch name\n \nReturns:\n PR creation URL", - "parameters": [ - "repo_url", - "branch_name" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function get_pr_creation_url", - "component_id": "codewiki/cli/utils/instructions.py::get_pr_creation_url", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/instructions.py::display_post_generation_instructions": { - "id": "codewiki/cli/utils/instructions.py::display_post_generation_instructions", - "name": "display_post_generation_instructions", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/instructions.py", - "relative_path": "codewiki/cli/utils/instructions.py", - "depends_on": [ - "codewiki/cli/utils/instructions.py::compute_github_pages_url", - "codewiki/cli/utils/instructions.py::get_pr_creation_url" - ], - "source_code": "def display_post_generation_instructions(\n output_dir: Path,\n repo_name: str,\n repo_url: Optional[str] = None,\n branch_name: Optional[str] = None,\n github_pages: bool = False,\n files_generated: list = None,\n statistics: dict = None\n):\n \"\"\"\n Display post-generation instructions.\n \n Args:\n output_dir: Output directory path\n repo_name: Repository name\n repo_url: GitHub repository URL (optional)\n branch_name: Git branch name (optional)\n github_pages: Whether GitHub Pages HTML was generated\n files_generated: List of generated files\n statistics: Generation statistics\n \"\"\"\n click.echo()\n click.secho(\"βœ“ Documentation generated successfully!\", fg=\"green\", bold=True)\n click.echo()\n \n # Output directory\n click.secho(\"Output directory:\", fg=\"cyan\", bold=True)\n click.echo(f\" {output_dir}\")\n click.echo()\n \n # Generated files\n if files_generated:\n click.secho(\"Generated files:\", fg=\"cyan\", bold=True)\n for file in files_generated[:10]: # Show first 10\n click.echo(f\" - {file}\")\n if len(files_generated) > 10:\n click.echo(f\" ... and {len(files_generated) - 10} more\")\n click.echo()\n \n # Statistics\n if statistics:\n click.secho(\"Statistics:\", fg=\"cyan\", bold=True)\n if 'module_count' in statistics:\n click.echo(f\" Total modules: {statistics['module_count']}\")\n if 'total_files_analyzed' in statistics:\n click.echo(f\" Files analyzed: {statistics['total_files_analyzed']}\")\n if 'generation_time' in statistics:\n minutes = int(statistics['generation_time'] // 60)\n seconds = int(statistics['generation_time'] % 60)\n click.echo(f\" Generation time: {minutes} minutes {seconds} seconds\")\n # if 'total_tokens_used' in statistics:\n # tokens = statistics['total_tokens_used']\n # click.echo(f\" Tokens used: ~{tokens:,}\")\n click.echo()\n \n # Next steps\n click.secho(\"Next steps:\", fg=\"cyan\", bold=True)\n click.echo()\n \n click.echo(\"1. Review the generated documentation:\")\n click.echo(f\" cat {output_dir}/overview.md\")\n if github_pages:\n click.echo(f\" open {output_dir}/index.html # View in browser\")\n click.echo()\n \n if branch_name:\n # Git workflow with branch\n click.echo(\"2. Push the documentation branch:\")\n click.secho(f\" git push origin {branch_name}\", fg=\"yellow\")\n click.echo()\n \n if repo_url:\n pr_url = get_pr_creation_url(repo_url, branch_name)\n click.echo(\"3. Create a Pull Request to merge documentation:\")\n click.secho(f\" {pr_url}\", fg=\"blue\")\n click.echo()\n \n click.echo(\"4. After merge, enable GitHub Pages:\")\n else:\n click.echo(\"3. Enable GitHub Pages:\")\n else:\n # Direct commit workflow\n click.echo(\"2. Commit the documentation:\")\n click.secho(\" git add docs/\", fg=\"yellow\")\n click.secho(' git commit -m \"Add generated documentation\"', fg=\"yellow\")\n click.echo()\n \n click.echo(\"3. Push to GitHub:\")\n click.secho(\" git push origin main\", fg=\"yellow\")\n click.echo()\n \n click.echo(\"4. Enable GitHub Pages:\")\n \n click.echo(\" - Go to repository Settings β†’ Pages\")\n click.echo(\" - Source: Deploy from a branch\")\n click.echo(\" - Branch: main, folder: /docs\")\n click.echo()\n \n if repo_url:\n github_pages_url = compute_github_pages_url(repo_url, repo_name)\n click.echo(\"5. Your documentation will be available at:\")\n click.secho(f\" {github_pages_url}\", fg=\"blue\", bold=True)\n click.echo()", - "start_line": 48, - "end_line": 150, - "has_docstring": true, - "docstring": "Display post-generation instructions.\n\nArgs:\n output_dir: Output directory path\n repo_name: Repository name\n repo_url: GitHub repository URL (optional)\n branch_name: Git branch name (optional)\n github_pages: Whether GitHub Pages HTML was generated\n files_generated: List of generated files\n statistics: Generation statistics", - "parameters": [ - "output_dir", - "repo_name", - "repo_url", - "branch_name", - "github_pages", - "files_generated", - "statistics" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function display_post_generation_instructions", - "component_id": "codewiki/cli/utils/instructions.py::display_post_generation_instructions", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/instructions.py::display_generation_summary": { - "id": "codewiki/cli/utils/instructions.py::display_generation_summary", - "name": "display_generation_summary", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/instructions.py", - "relative_path": "codewiki/cli/utils/instructions.py", - "depends_on": [], - "source_code": "def display_generation_summary(\n success: bool,\n error_message: Optional[str] = None,\n output_dir: Optional[Path] = None\n):\n \"\"\"\n Display generation summary (success or failure).\n \n Args:\n success: Whether generation was successful\n error_message: Error message if failed\n output_dir: Output directory if successful\n \"\"\"\n if success:\n click.echo()\n click.secho(\"βœ“ Generation completed successfully!\", fg=\"green\", bold=True)\n if output_dir:\n click.echo(f\"\\nDocumentation saved to: {output_dir}\")\n click.echo()\n else:\n click.echo()\n click.secho(\"βœ— Generation failed\", fg=\"red\", bold=True)\n if error_message:\n click.echo()\n click.echo(error_message)\n click.echo()", - "start_line": 153, - "end_line": 178, - "has_docstring": true, - "docstring": "Display generation summary (success or failure).\n\nArgs:\n success: Whether generation was successful\n error_message: Error message if failed\n output_dir: Output directory if successful", - "parameters": [ - "success", - "error_message", - "output_dir" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function display_generation_summary", - "component_id": "codewiki/cli/utils/instructions.py::display_generation_summary", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/logging.py::CLILogger": { - "id": "codewiki/cli/utils/logging.py::CLILogger", - "name": "CLILogger", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/logging.py", - "relative_path": "codewiki/cli/utils/logging.py", - "depends_on": [], - "source_code": "class CLILogger:\n \"\"\"Logger for CLI with support for verbose and normal modes.\"\"\"\n \n def __init__(self, verbose: bool = False):\n \"\"\"\n Initialize the logger.\n \n Args:\n verbose: Enable verbose output\n \"\"\"\n self.verbose = verbose\n self.start_time = datetime.now()\n \n def debug(self, message: str):\n \"\"\"Log debug message (only in verbose mode).\"\"\"\n if self.verbose:\n timestamp = datetime.now().strftime(\"%H:%M:%S\")\n click.secho(f\"[{timestamp}] {message}\", fg=\"cyan\", dim=True)\n \n def info(self, message: str):\n \"\"\"Log info message.\"\"\"\n click.echo(message)\n \n def success(self, message: str):\n \"\"\"Log success message in green.\"\"\"\n click.secho(f\"βœ“ {message}\", fg=\"green\")\n \n def warning(self, message: str):\n \"\"\"Log warning message in yellow.\"\"\"\n click.secho(f\"⚠️ {message}\", fg=\"yellow\")\n \n def error(self, message: str):\n \"\"\"Log error message in red.\"\"\"\n click.secho(f\"βœ— {message}\", fg=\"red\", err=True)\n \n def step(self, message: str, step: Optional[int] = None, total: Optional[int] = None):\n \"\"\"\n Log a processing step.\n \n Args:\n message: Step description\n step: Current step number\n total: Total number of steps\n \"\"\"\n if step is not None and total is not None:\n prefix = f\"[{step}/{total}]\"\n else:\n prefix = \"β†’\"\n \n click.secho(f\"{prefix} {message}\", fg=\"blue\", bold=True)\n \n def elapsed_time(self) -> str:\n \"\"\"Get elapsed time since logger was created.\"\"\"\n elapsed = datetime.now() - self.start_time\n minutes = int(elapsed.total_seconds() // 60)\n seconds = int(elapsed.total_seconds() % 60)\n \n if minutes > 0:\n return f\"{minutes}m {seconds}s\"\n else:\n return f\"{seconds}s\"", - "start_line": 11, - "end_line": 71, - "has_docstring": true, - "docstring": "Logger for CLI with support for verbose and normal modes.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class CLILogger", - "component_id": "codewiki/cli/utils/logging.py::CLILogger", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/logging.py::CLILogger.__init__": { - "id": "codewiki/cli/utils/logging.py::CLILogger.__init__", - "name": "CLILogger.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/logging.py", - "relative_path": "codewiki/cli/utils/logging.py", - "depends_on": [], - "source_code": " def __init__(self, verbose: bool = False):\n \"\"\"\n Initialize the logger.\n \n Args:\n verbose: Enable verbose output\n \"\"\"\n self.verbose = verbose\n self.start_time = datetime.now()", - "start_line": 14, - "end_line": 22, - "has_docstring": true, - "docstring": "Initialize the logger.\n\nArgs:\n verbose: Enable verbose output", - "parameters": [ - "self", - "verbose" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CLILogger", - "display_name": "method CLILogger.__init__", - "component_id": "codewiki/cli/utils/logging.py::CLILogger.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/logging.py::CLILogger.debug": { - "id": "codewiki/cli/utils/logging.py::CLILogger.debug", - "name": "CLILogger.debug", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/logging.py", - "relative_path": "codewiki/cli/utils/logging.py", - "depends_on": [], - "source_code": " def debug(self, message: str):\n \"\"\"Log debug message (only in verbose mode).\"\"\"\n if self.verbose:\n timestamp = datetime.now().strftime(\"%H:%M:%S\")\n click.secho(f\"[{timestamp}] {message}\", fg=\"cyan\", dim=True)", - "start_line": 24, - "end_line": 28, - "has_docstring": true, - "docstring": "Log debug message (only in verbose mode).", - "parameters": [ - "self", - "message" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CLILogger", - "display_name": "method CLILogger.debug", - "component_id": "codewiki/cli/utils/logging.py::CLILogger.debug", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/logging.py::CLILogger.info": { - "id": "codewiki/cli/utils/logging.py::CLILogger.info", - "name": "CLILogger.info", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/logging.py", - "relative_path": "codewiki/cli/utils/logging.py", - "depends_on": [], - "source_code": " def info(self, message: str):\n \"\"\"Log info message.\"\"\"\n click.echo(message)", - "start_line": 30, - "end_line": 32, - "has_docstring": true, - "docstring": "Log info message.", - "parameters": [ - "self", - "message" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CLILogger", - "display_name": "method CLILogger.info", - "component_id": "codewiki/cli/utils/logging.py::CLILogger.info", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/logging.py::CLILogger.success": { - "id": "codewiki/cli/utils/logging.py::CLILogger.success", - "name": "CLILogger.success", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/logging.py", - "relative_path": "codewiki/cli/utils/logging.py", - "depends_on": [], - "source_code": " def success(self, message: str):\n \"\"\"Log success message in green.\"\"\"\n click.secho(f\"βœ“ {message}\", fg=\"green\")", - "start_line": 34, - "end_line": 36, - "has_docstring": true, - "docstring": "Log success message in green.", - "parameters": [ - "self", - "message" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CLILogger", - "display_name": "method CLILogger.success", - "component_id": "codewiki/cli/utils/logging.py::CLILogger.success", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/logging.py::CLILogger.warning": { - "id": "codewiki/cli/utils/logging.py::CLILogger.warning", - "name": "CLILogger.warning", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/logging.py", - "relative_path": "codewiki/cli/utils/logging.py", - "depends_on": [], - "source_code": " def warning(self, message: str):\n \"\"\"Log warning message in yellow.\"\"\"\n click.secho(f\"⚠️ {message}\", fg=\"yellow\")", - "start_line": 38, - "end_line": 40, - "has_docstring": true, - "docstring": "Log warning message in yellow.", - "parameters": [ - "self", - "message" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CLILogger", - "display_name": "method CLILogger.warning", - "component_id": "codewiki/cli/utils/logging.py::CLILogger.warning", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/logging.py::CLILogger.error": { - "id": "codewiki/cli/utils/logging.py::CLILogger.error", - "name": "CLILogger.error", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/logging.py", - "relative_path": "codewiki/cli/utils/logging.py", - "depends_on": [], - "source_code": " def error(self, message: str):\n \"\"\"Log error message in red.\"\"\"\n click.secho(f\"βœ— {message}\", fg=\"red\", err=True)", - "start_line": 42, - "end_line": 44, - "has_docstring": true, - "docstring": "Log error message in red.", - "parameters": [ - "self", - "message" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CLILogger", - "display_name": "method CLILogger.error", - "component_id": "codewiki/cli/utils/logging.py::CLILogger.error", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/logging.py::CLILogger.step": { - "id": "codewiki/cli/utils/logging.py::CLILogger.step", - "name": "CLILogger.step", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/logging.py", - "relative_path": "codewiki/cli/utils/logging.py", - "depends_on": [], - "source_code": " def step(self, message: str, step: Optional[int] = None, total: Optional[int] = None):\n \"\"\"\n Log a processing step.\n \n Args:\n message: Step description\n step: Current step number\n total: Total number of steps\n \"\"\"\n if step is not None and total is not None:\n prefix = f\"[{step}/{total}]\"\n else:\n prefix = \"β†’\"\n \n click.secho(f\"{prefix} {message}\", fg=\"blue\", bold=True)", - "start_line": 46, - "end_line": 60, - "has_docstring": true, - "docstring": "Log a processing step.\n\nArgs:\n message: Step description\n step: Current step number\n total: Total number of steps", - "parameters": [ - "self", - "message", - "step", - "total" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CLILogger", - "display_name": "method CLILogger.step", - "component_id": "codewiki/cli/utils/logging.py::CLILogger.step", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/logging.py::CLILogger.elapsed_time": { - "id": "codewiki/cli/utils/logging.py::CLILogger.elapsed_time", - "name": "CLILogger.elapsed_time", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/logging.py", - "relative_path": "codewiki/cli/utils/logging.py", - "depends_on": [], - "source_code": " def elapsed_time(self) -> str:\n \"\"\"Get elapsed time since logger was created.\"\"\"\n elapsed = datetime.now() - self.start_time\n minutes = int(elapsed.total_seconds() // 60)\n seconds = int(elapsed.total_seconds() % 60)\n \n if minutes > 0:\n return f\"{minutes}m {seconds}s\"\n else:\n return f\"{seconds}s\"", - "start_line": 62, - "end_line": 71, - "has_docstring": true, - "docstring": "Get elapsed time since logger was created.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CLILogger", - "display_name": "method CLILogger.elapsed_time", - "component_id": "codewiki/cli/utils/logging.py::CLILogger.elapsed_time", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/logging.py::create_logger": { - "id": "codewiki/cli/utils/logging.py::create_logger", - "name": "create_logger", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/logging.py", - "relative_path": "codewiki/cli/utils/logging.py", - "depends_on": [ - "codewiki/cli/utils/logging.py::CLILogger" - ], - "source_code": "def create_logger(verbose: bool = False) -> CLILogger:\n \"\"\"\n Create and return a CLI logger.\n \n Args:\n verbose: Enable verbose output\n \n Returns:\n Configured CLILogger instance\n \"\"\"\n return CLILogger(verbose=verbose)", - "start_line": 74, - "end_line": 84, - "has_docstring": true, - "docstring": "Create and return a CLI logger.\n\nArgs:\n verbose: Enable verbose output\n \nReturns:\n Configured CLILogger instance", - "parameters": [ - "verbose" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function create_logger", - "component_id": "codewiki/cli/utils/logging.py::create_logger", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/progress.py::ProgressTracker": { - "id": "codewiki/cli/utils/progress.py::ProgressTracker", - "name": "ProgressTracker", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/progress.py", - "relative_path": "codewiki/cli/utils/progress.py", - "depends_on": [], - "source_code": "class ProgressTracker:\n \"\"\"\n Progress tracker with stages and ETA estimation.\n \n Stages:\n 1. Dependency Analysis (40% of time)\n 2. Module Clustering (20% of time)\n 3. Documentation Generation (30% of time)\n 4. HTML Generation (5% of time, optional)\n 5. Finalization (5% of time)\n \"\"\"\n \n # Stage weights (percentage of total time)\n STAGE_WEIGHTS = {\n 1: 0.40, # Dependency Analysis\n 2: 0.20, # Module Clustering\n 3: 0.30, # Documentation Generation\n 4: 0.05, # HTML Generation (optional)\n 5: 0.05, # Finalization\n }\n \n STAGE_NAMES = {\n 1: \"Dependency Analysis\",\n 2: \"Module Clustering\",\n 3: \"Documentation Generation\",\n 4: \"HTML Generation\",\n 5: \"Finalization\",\n }\n \n def __init__(self, total_stages: int = 5, verbose: bool = False):\n \"\"\"\n Initialize progress tracker.\n \n Args:\n total_stages: Number of stages\n verbose: Enable verbose output\n \"\"\"\n self.total_stages = total_stages\n self.current_stage = 0\n self.stage_progress = 0.0\n self.start_time = time.time()\n self.verbose = verbose\n self.current_stage_start = self.start_time\n \n def start_stage(self, stage: int, description: Optional[str] = None):\n \"\"\"\n Start a new stage.\n \n Args:\n stage: Stage number (1-5)\n description: Optional custom description\n \"\"\"\n self.current_stage = stage\n self.stage_progress = 0.0\n self.current_stage_start = time.time()\n \n stage_name = description or self.STAGE_NAMES.get(stage, f\"Stage {stage}\")\n \n if self.verbose:\n elapsed = self._format_elapsed()\n click.secho(\n f\"\\n[{elapsed}] Phase {stage}/{self.total_stages}: {stage_name}\",\n fg=\"blue\",\n bold=True\n )\n else:\n click.secho(\n f\"[{stage}/{self.total_stages}] {stage_name}\",\n fg=\"blue\",\n bold=True\n )\n \n def update_stage(self, progress: float, message: Optional[str] = None):\n \"\"\"\n Update progress within current stage.\n \n Args:\n progress: Progress percentage (0.0 to 1.0)\n message: Optional progress message\n \"\"\"\n self.stage_progress = min(1.0, max(0.0, progress))\n \n if self.verbose and message:\n elapsed = self._format_elapsed()\n click.echo(f\"[{elapsed}] {message}\")\n \n def complete_stage(self, message: Optional[str] = None):\n \"\"\"\n Complete current stage.\n \n Args:\n message: Optional completion message\n \"\"\"\n self.stage_progress = 1.0\n \n if self.verbose:\n elapsed = self._format_elapsed()\n stage_time = time.time() - self.current_stage_start\n stage_name = self.STAGE_NAMES.get(self.current_stage, f\"Stage {self.current_stage}\")\n click.secho(\n f\"[{elapsed}] {stage_name} complete ({stage_time:.1f}s)\",\n fg=\"green\"\n )\n if message:\n click.echo(f\"[{elapsed}] {message}\")\n \n def get_overall_progress(self) -> float:\n \"\"\"\n Get overall progress percentage.\n \n Returns:\n Progress (0.0 to 1.0)\n \"\"\"\n completed_weight = sum(\n self.STAGE_WEIGHTS.get(s, 0)\n for s in range(1, self.current_stage)\n )\n \n current_weight = self.STAGE_WEIGHTS.get(self.current_stage, 0) * self.stage_progress\n \n return completed_weight + current_weight\n \n def _format_elapsed(self) -> str:\n \"\"\"Format elapsed time.\"\"\"\n elapsed = time.time() - self.start_time\n minutes = int(elapsed // 60)\n seconds = int(elapsed % 60)\n \n if minutes > 0:\n return f\"{minutes:02d}:{seconds:02d}\"\n else:\n return f\"00:{seconds:02d}\"\n \n def get_eta(self) -> Optional[str]:\n \"\"\"\n Estimate time remaining.\n \n Returns:\n ETA string or None if cannot estimate\n \"\"\"\n elapsed = time.time() - self.start_time\n progress = self.get_overall_progress()\n \n if progress <= 0.0:\n return None\n \n total_estimated = elapsed / progress\n remaining = total_estimated - elapsed\n \n if remaining < 0:\n return \"< 1 min\"\n \n minutes = int(remaining // 60)\n seconds = int(remaining % 60)\n \n if minutes > 60:\n hours = minutes // 60\n minutes = minutes % 60\n return f\"{hours}h {minutes}m\"\n elif minutes > 0:\n return f\"{minutes}m {seconds}s\"\n else:\n return f\"{seconds}s\"", - "start_line": 11, - "end_line": 173, - "has_docstring": true, - "docstring": "Progress tracker with stages and ETA estimation.\n\nStages:\n1. Dependency Analysis (40% of time)\n2. Module Clustering (20% of time)\n3. Documentation Generation (30% of time)\n4. HTML Generation (5% of time, optional)\n5. Finalization (5% of time)", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class ProgressTracker", - "component_id": "codewiki/cli/utils/progress.py::ProgressTracker", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/progress.py::ProgressTracker.__init__": { - "id": "codewiki/cli/utils/progress.py::ProgressTracker.__init__", - "name": "ProgressTracker.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/progress.py", - "relative_path": "codewiki/cli/utils/progress.py", - "depends_on": [], - "source_code": " def __init__(self, total_stages: int = 5, verbose: bool = False):\n \"\"\"\n Initialize progress tracker.\n \n Args:\n total_stages: Number of stages\n verbose: Enable verbose output\n \"\"\"\n self.total_stages = total_stages\n self.current_stage = 0\n self.stage_progress = 0.0\n self.start_time = time.time()\n self.verbose = verbose\n self.current_stage_start = self.start_time", - "start_line": 40, - "end_line": 53, - "has_docstring": true, - "docstring": "Initialize progress tracker.\n\nArgs:\n total_stages: Number of stages\n verbose: Enable verbose output", - "parameters": [ - "self", - "total_stages", - "verbose" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ProgressTracker", - "display_name": "method ProgressTracker.__init__", - "component_id": "codewiki/cli/utils/progress.py::ProgressTracker.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/progress.py::ProgressTracker.start_stage": { - "id": "codewiki/cli/utils/progress.py::ProgressTracker.start_stage", - "name": "ProgressTracker.start_stage", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/progress.py", - "relative_path": "codewiki/cli/utils/progress.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/cli/utils/progress.py::ProgressTracker._format_elapsed" - ], - "source_code": " def start_stage(self, stage: int, description: Optional[str] = None):\n \"\"\"\n Start a new stage.\n \n Args:\n stage: Stage number (1-5)\n description: Optional custom description\n \"\"\"\n self.current_stage = stage\n self.stage_progress = 0.0\n self.current_stage_start = time.time()\n \n stage_name = description or self.STAGE_NAMES.get(stage, f\"Stage {stage}\")\n \n if self.verbose:\n elapsed = self._format_elapsed()\n click.secho(\n f\"\\n[{elapsed}] Phase {stage}/{self.total_stages}: {stage_name}\",\n fg=\"blue\",\n bold=True\n )\n else:\n click.secho(\n f\"[{stage}/{self.total_stages}] {stage_name}\",\n fg=\"blue\",\n bold=True\n )", - "start_line": 55, - "end_line": 81, - "has_docstring": true, - "docstring": "Start a new stage.\n\nArgs:\n stage: Stage number (1-5)\n description: Optional custom description", - "parameters": [ - "self", - "stage", - "description" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ProgressTracker", - "display_name": "method ProgressTracker.start_stage", - "component_id": "codewiki/cli/utils/progress.py::ProgressTracker.start_stage", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/progress.py::ProgressTracker.update_stage": { - "id": "codewiki/cli/utils/progress.py::ProgressTracker.update_stage", - "name": "ProgressTracker.update_stage", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/progress.py", - "relative_path": "codewiki/cli/utils/progress.py", - "depends_on": [ - "codewiki/cli/utils/progress.py::ProgressTracker._format_elapsed" - ], - "source_code": " def update_stage(self, progress: float, message: Optional[str] = None):\n \"\"\"\n Update progress within current stage.\n \n Args:\n progress: Progress percentage (0.0 to 1.0)\n message: Optional progress message\n \"\"\"\n self.stage_progress = min(1.0, max(0.0, progress))\n \n if self.verbose and message:\n elapsed = self._format_elapsed()\n click.echo(f\"[{elapsed}] {message}\")", - "start_line": 83, - "end_line": 95, - "has_docstring": true, - "docstring": "Update progress within current stage.\n\nArgs:\n progress: Progress percentage (0.0 to 1.0)\n message: Optional progress message", - "parameters": [ - "self", - "progress", - "message" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ProgressTracker", - "display_name": "method ProgressTracker.update_stage", - "component_id": "codewiki/cli/utils/progress.py::ProgressTracker.update_stage", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/progress.py::ProgressTracker.complete_stage": { - "id": "codewiki/cli/utils/progress.py::ProgressTracker.complete_stage", - "name": "ProgressTracker.complete_stage", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/progress.py", - "relative_path": "codewiki/cli/utils/progress.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/cli/utils/progress.py::ProgressTracker._format_elapsed" - ], - "source_code": " def complete_stage(self, message: Optional[str] = None):\n \"\"\"\n Complete current stage.\n \n Args:\n message: Optional completion message\n \"\"\"\n self.stage_progress = 1.0\n \n if self.verbose:\n elapsed = self._format_elapsed()\n stage_time = time.time() - self.current_stage_start\n stage_name = self.STAGE_NAMES.get(self.current_stage, f\"Stage {self.current_stage}\")\n click.secho(\n f\"[{elapsed}] {stage_name} complete ({stage_time:.1f}s)\",\n fg=\"green\"\n )\n if message:\n click.echo(f\"[{elapsed}] {message}\")", - "start_line": 97, - "end_line": 115, - "has_docstring": true, - "docstring": "Complete current stage.\n\nArgs:\n message: Optional completion message", - "parameters": [ - "self", - "message" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ProgressTracker", - "display_name": "method ProgressTracker.complete_stage", - "component_id": "codewiki/cli/utils/progress.py::ProgressTracker.complete_stage", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/progress.py::ProgressTracker.get_overall_progress": { - "id": "codewiki/cli/utils/progress.py::ProgressTracker.get_overall_progress", - "name": "ProgressTracker.get_overall_progress", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/progress.py", - "relative_path": "codewiki/cli/utils/progress.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def get_overall_progress(self) -> float:\n \"\"\"\n Get overall progress percentage.\n \n Returns:\n Progress (0.0 to 1.0)\n \"\"\"\n completed_weight = sum(\n self.STAGE_WEIGHTS.get(s, 0)\n for s in range(1, self.current_stage)\n )\n \n current_weight = self.STAGE_WEIGHTS.get(self.current_stage, 0) * self.stage_progress\n \n return completed_weight + current_weight", - "start_line": 117, - "end_line": 131, - "has_docstring": true, - "docstring": "Get overall progress percentage.\n\nReturns:\n Progress (0.0 to 1.0)", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ProgressTracker", - "display_name": "method ProgressTracker.get_overall_progress", - "component_id": "codewiki/cli/utils/progress.py::ProgressTracker.get_overall_progress", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/progress.py::ProgressTracker._format_elapsed": { - "id": "codewiki/cli/utils/progress.py::ProgressTracker._format_elapsed", - "name": "ProgressTracker._format_elapsed", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/progress.py", - "relative_path": "codewiki/cli/utils/progress.py", - "depends_on": [], - "source_code": " def _format_elapsed(self) -> str:\n \"\"\"Format elapsed time.\"\"\"\n elapsed = time.time() - self.start_time\n minutes = int(elapsed // 60)\n seconds = int(elapsed % 60)\n \n if minutes > 0:\n return f\"{minutes:02d}:{seconds:02d}\"\n else:\n return f\"00:{seconds:02d}\"", - "start_line": 133, - "end_line": 142, - "has_docstring": true, - "docstring": "Format elapsed time.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ProgressTracker", - "display_name": "method ProgressTracker._format_elapsed", - "component_id": "codewiki/cli/utils/progress.py::ProgressTracker._format_elapsed", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/progress.py::ProgressTracker.get_eta": { - "id": "codewiki/cli/utils/progress.py::ProgressTracker.get_eta", - "name": "ProgressTracker.get_eta", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/progress.py", - "relative_path": "codewiki/cli/utils/progress.py", - "depends_on": [ - "codewiki/cli/utils/progress.py::ProgressTracker.get_overall_progress" - ], - "source_code": " def get_eta(self) -> Optional[str]:\n \"\"\"\n Estimate time remaining.\n \n Returns:\n ETA string or None if cannot estimate\n \"\"\"\n elapsed = time.time() - self.start_time\n progress = self.get_overall_progress()\n \n if progress <= 0.0:\n return None\n \n total_estimated = elapsed / progress\n remaining = total_estimated - elapsed\n \n if remaining < 0:\n return \"< 1 min\"\n \n minutes = int(remaining // 60)\n seconds = int(remaining % 60)\n \n if minutes > 60:\n hours = minutes // 60\n minutes = minutes % 60\n return f\"{hours}h {minutes}m\"\n elif minutes > 0:\n return f\"{minutes}m {seconds}s\"\n else:\n return f\"{seconds}s\"", - "start_line": 144, - "end_line": 173, - "has_docstring": true, - "docstring": "Estimate time remaining.\n\nReturns:\n ETA string or None if cannot estimate", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ProgressTracker", - "display_name": "method ProgressTracker.get_eta", - "component_id": "codewiki/cli/utils/progress.py::ProgressTracker.get_eta", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/progress.py::ModuleProgressBar": { - "id": "codewiki/cli/utils/progress.py::ModuleProgressBar", - "name": "ModuleProgressBar", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/progress.py", - "relative_path": "codewiki/cli/utils/progress.py", - "depends_on": [], - "source_code": "class ModuleProgressBar:\n \"\"\"Progress bar for module-by-module generation.\"\"\"\n \n def __init__(self, total_modules: int, verbose: bool = False):\n \"\"\"\n Initialize module progress bar.\n \n Args:\n total_modules: Total number of modules to process\n verbose: Enable verbose output\n \"\"\"\n self.total_modules = total_modules\n self.current_module = 0\n self.verbose = verbose\n self.bar = None\n \n if not verbose:\n self.bar = click.progressbar(\n length=total_modules,\n label=\"Generating modules\",\n show_eta=True,\n show_percent=True,\n )\n self.bar.__enter__()\n \n def update(self, module_name: str, cached: bool = False):\n \"\"\"\n Update progress for a module.\n \n Args:\n module_name: Name of the module\n cached: Whether the module was loaded from cache\n \"\"\"\n self.current_module += 1\n \n if self.verbose:\n status = \"βœ“ (cached)\" if cached else \"⟳ (generating)\"\n click.echo(f\" [{self.current_module}/{self.total_modules}] {module_name}... {status}\")\n elif self.bar:\n self.bar.update(1)\n \n def finish(self):\n \"\"\"Finish progress bar.\"\"\"\n if self.bar:\n self.bar.__exit__(None, None, None)\n self.bar = None", - "start_line": 176, - "end_line": 221, - "has_docstring": true, - "docstring": "Progress bar for module-by-module generation.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class ModuleProgressBar", - "component_id": "codewiki/cli/utils/progress.py::ModuleProgressBar", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/progress.py::ModuleProgressBar.__init__": { - "id": "codewiki/cli/utils/progress.py::ModuleProgressBar.__init__", - "name": "ModuleProgressBar.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/progress.py", - "relative_path": "codewiki/cli/utils/progress.py", - "depends_on": [], - "source_code": " def __init__(self, total_modules: int, verbose: bool = False):\n \"\"\"\n Initialize module progress bar.\n \n Args:\n total_modules: Total number of modules to process\n verbose: Enable verbose output\n \"\"\"\n self.total_modules = total_modules\n self.current_module = 0\n self.verbose = verbose\n self.bar = None\n \n if not verbose:\n self.bar = click.progressbar(\n length=total_modules,\n label=\"Generating modules\",\n show_eta=True,\n show_percent=True,\n )\n self.bar.__enter__()", - "start_line": 179, - "end_line": 199, - "has_docstring": true, - "docstring": "Initialize module progress bar.\n\nArgs:\n total_modules: Total number of modules to process\n verbose: Enable verbose output", - "parameters": [ - "self", - "total_modules", - "verbose" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ModuleProgressBar", - "display_name": "method ModuleProgressBar.__init__", - "component_id": "codewiki/cli/utils/progress.py::ModuleProgressBar.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/progress.py::ModuleProgressBar.update": { - "id": "codewiki/cli/utils/progress.py::ModuleProgressBar.update", - "name": "ModuleProgressBar.update", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/progress.py", - "relative_path": "codewiki/cli/utils/progress.py", - "depends_on": [ - "codewiki/cli/utils/progress.py::ModuleProgressBar.update" - ], - "source_code": " def update(self, module_name: str, cached: bool = False):\n \"\"\"\n Update progress for a module.\n \n Args:\n module_name: Name of the module\n cached: Whether the module was loaded from cache\n \"\"\"\n self.current_module += 1\n \n if self.verbose:\n status = \"βœ“ (cached)\" if cached else \"⟳ (generating)\"\n click.echo(f\" [{self.current_module}/{self.total_modules}] {module_name}... {status}\")\n elif self.bar:\n self.bar.update(1)", - "start_line": 201, - "end_line": 215, - "has_docstring": true, - "docstring": "Update progress for a module.\n\nArgs:\n module_name: Name of the module\n cached: Whether the module was loaded from cache", - "parameters": [ - "self", - "module_name", - "cached" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ModuleProgressBar", - "display_name": "method ModuleProgressBar.update", - "component_id": "codewiki/cli/utils/progress.py::ModuleProgressBar.update", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/progress.py::ModuleProgressBar.finish": { - "id": "codewiki/cli/utils/progress.py::ModuleProgressBar.finish", - "name": "ModuleProgressBar.finish", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/progress.py", - "relative_path": "codewiki/cli/utils/progress.py", - "depends_on": [], - "source_code": " def finish(self):\n \"\"\"Finish progress bar.\"\"\"\n if self.bar:\n self.bar.__exit__(None, None, None)\n self.bar = None", - "start_line": 217, - "end_line": 221, - "has_docstring": true, - "docstring": "Finish progress bar.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ModuleProgressBar", - "display_name": "method ModuleProgressBar.finish", - "component_id": "codewiki/cli/utils/progress.py::ModuleProgressBar.finish", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/repo_validator.py::validate_repository": { - "id": "codewiki/cli/utils/repo_validator.py::validate_repository", - "name": "validate_repository", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/repo_validator.py", - "relative_path": "codewiki/cli/utils/repo_validator.py", - "depends_on": [ - "codewiki/cli/utils/validation.py::validate_repository_path", - "codewiki/cli/utils/validation.py::detect_supported_languages", - "codewiki/cli/utils/errors.py::RepositoryError" - ], - "source_code": "def validate_repository(repo_path: Path) -> Tuple[Path, List[Tuple[str, int]]]:\n \"\"\"\n Validate repository for documentation generation.\n \n Checks:\n - Path exists and is a directory\n - Contains supported code files\n - Has sufficient files for meaningful documentation\n \n Args:\n repo_path: Path to repository\n \n Returns:\n Tuple of (validated_path, language_counts)\n \n Raises:\n RepositoryError: If validation fails\n \"\"\"\n # Validate path exists\n repo_path = validate_repository_path(repo_path)\n \n # Detect languages\n languages = detect_supported_languages(repo_path)\n \n if not languages:\n raise RepositoryError(\n f\"No supported code files found in {repo_path}\\n\\n\"\n \"CodeWiki supports: Python, Java, JavaScript, TypeScript, C, C++, C#, PHP\\n\\n\"\n \"Please navigate to a code repository or specify a custom directory:\\n\"\n \" cd /path/to/your/project\\n\"\n \" codewiki generate\"\n )\n \n return repo_path, languages", - "start_line": 38, - "end_line": 71, - "has_docstring": true, - "docstring": "Validate repository for documentation generation.\n\nChecks:\n- Path exists and is a directory\n- Contains supported code files\n- Has sufficient files for meaningful documentation\n\nArgs:\n repo_path: Path to repository\n \nReturns:\n Tuple of (validated_path, language_counts)\n \nRaises:\n RepositoryError: If validation fails", - "parameters": [ - "repo_path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function validate_repository", - "component_id": "codewiki/cli/utils/repo_validator.py::validate_repository", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/repo_validator.py::check_writable_output": { - "id": "codewiki/cli/utils/repo_validator.py::check_writable_output", - "name": "check_writable_output", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/repo_validator.py", - "relative_path": "codewiki/cli/utils/repo_validator.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/cli/utils/errors.py::RepositoryError" - ], - "source_code": "def check_writable_output(output_dir: Path) -> Path:\n \"\"\"\n Check if output directory is writable.\n \n Args:\n output_dir: Output directory path\n \n Returns:\n Validated output directory path\n \n Raises:\n RepositoryError: If output directory is not writable\n \"\"\"\n output_dir = Path(output_dir).expanduser().resolve()\n \n # Check if output directory exists\n if output_dir.exists():\n if not output_dir.is_dir():\n raise RepositoryError(\n f\"Output path exists but is not a directory: {output_dir}\"\n )\n \n # Check if writable\n if not os.access(output_dir, os.W_OK):\n raise RepositoryError(\n f\"Output directory is not writable: {output_dir}\\n\\n\"\n f\"Try: chmod u+w {output_dir}\"\n )\n else:\n # Check if parent is writable\n parent = output_dir.parent\n if not parent.exists():\n raise RepositoryError(\n f\"Parent directory does not exist: {parent}\"\n )\n \n if not os.access(parent, os.W_OK):\n raise RepositoryError(\n f\"Cannot create output directory (parent not writable): {parent}\\n\\n\"\n f\"Try: chmod u+w {parent}\"\n )\n \n return output_dir", - "start_line": 74, - "end_line": 116, - "has_docstring": true, - "docstring": "Check if output directory is writable.\n\nArgs:\n output_dir: Output directory path\n \nReturns:\n Validated output directory path\n \nRaises:\n RepositoryError: If output directory is not writable", - "parameters": [ - "output_dir" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function check_writable_output", - "component_id": "codewiki/cli/utils/repo_validator.py::check_writable_output", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/repo_validator.py::_get_git_repo": { - "id": "codewiki/cli/utils/repo_validator.py::_get_git_repo", - "name": "_get_git_repo", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/repo_validator.py", - "relative_path": "codewiki/cli/utils/repo_validator.py", - "depends_on": [], - "source_code": "def _get_git_repo(repo_path: Path):\n \"\"\"\n Find a git repository starting at repo_path and searching parent directories.\n \n Args:\n repo_path: Path to start searching from\n \n Returns:\n git.Repo instance or None if no repository found\n \"\"\"\n try:\n import git\n return git.Repo(repo_path, search_parent_directories=True)\n except Exception:\n return None", - "start_line": 119, - "end_line": 133, - "has_docstring": true, - "docstring": "Find a git repository starting at repo_path and searching parent directories.\n\nArgs:\n repo_path: Path to start searching from\n \nReturns:\n git.Repo instance or None if no repository found", - "parameters": [ - "repo_path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _get_git_repo", - "component_id": "codewiki/cli/utils/repo_validator.py::_get_git_repo", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/repo_validator.py::is_git_repository": { - "id": "codewiki/cli/utils/repo_validator.py::is_git_repository", - "name": "is_git_repository", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/repo_validator.py", - "relative_path": "codewiki/cli/utils/repo_validator.py", - "depends_on": [ - "codewiki/cli/utils/repo_validator.py::_get_git_repo" - ], - "source_code": "def is_git_repository(repo_path: Path) -> bool:\n \"\"\"\n Check if path is inside a git repository.\n \n Searches parent directories if .git is not directly at repo_path,\n supporting monorepo subdirectories.\n \n Args:\n repo_path: Path to check\n \n Returns:\n True if inside a git repository, False otherwise\n \"\"\"\n return _get_git_repo(repo_path) is not None", - "start_line": 136, - "end_line": 149, - "has_docstring": true, - "docstring": "Check if path is inside a git repository.\n\nSearches parent directories if .git is not directly at repo_path,\nsupporting monorepo subdirectories.\n\nArgs:\n repo_path: Path to check\n \nReturns:\n True if inside a git repository, False otherwise", - "parameters": [ - "repo_path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function is_git_repository", - "component_id": "codewiki/cli/utils/repo_validator.py::is_git_repository", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/repo_validator.py::get_git_commit_hash": { - "id": "codewiki/cli/utils/repo_validator.py::get_git_commit_hash", - "name": "get_git_commit_hash", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/repo_validator.py", - "relative_path": "codewiki/cli/utils/repo_validator.py", - "depends_on": [ - "codewiki/cli/utils/repo_validator.py::_get_git_repo" - ], - "source_code": "def get_git_commit_hash(repo_path: Path) -> str:\n \"\"\"\n Get current git commit hash.\n \n Searches parent directories to support monorepo subdirectories.\n \n Args:\n repo_path: Path inside a git repository\n \n Returns:\n Commit hash or empty string if not in a git repo\n \"\"\"\n repo = _get_git_repo(repo_path)\n if repo is None:\n return \"\"\n \n try:\n return repo.head.commit.hexsha\n except Exception:\n return \"\"", - "start_line": 152, - "end_line": 171, - "has_docstring": true, - "docstring": "Get current git commit hash.\n\nSearches parent directories to support monorepo subdirectories.\n\nArgs:\n repo_path: Path inside a git repository\n \nReturns:\n Commit hash or empty string if not in a git repo", - "parameters": [ - "repo_path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function get_git_commit_hash", - "component_id": "codewiki/cli/utils/repo_validator.py::get_git_commit_hash", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/repo_validator.py::get_git_branch": { - "id": "codewiki/cli/utils/repo_validator.py::get_git_branch", - "name": "get_git_branch", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/repo_validator.py", - "relative_path": "codewiki/cli/utils/repo_validator.py", - "depends_on": [ - "codewiki/cli/utils/repo_validator.py::_get_git_repo" - ], - "source_code": "def get_git_branch(repo_path: Path) -> str:\n \"\"\"\n Get current git branch name.\n \n Searches parent directories to support monorepo subdirectories.\n \n Args:\n repo_path: Path inside a git repository\n \n Returns:\n Branch name or empty string if not in a git repo\n \"\"\"\n repo = _get_git_repo(repo_path)\n if repo is None:\n return \"\"\n \n try:\n return repo.active_branch.name\n except Exception:\n return \"\"", - "start_line": 174, - "end_line": 193, - "has_docstring": true, - "docstring": "Get current git branch name.\n\nSearches parent directories to support monorepo subdirectories.\n\nArgs:\n repo_path: Path inside a git repository\n \nReturns:\n Branch name or empty string if not in a git repo", - "parameters": [ - "repo_path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function get_git_branch", - "component_id": "codewiki/cli/utils/repo_validator.py::get_git_branch", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/repo_validator.py::count_code_files": { - "id": "codewiki/cli/utils/repo_validator.py::count_code_files", - "name": "count_code_files", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/repo_validator.py", - "relative_path": "codewiki/cli/utils/repo_validator.py", - "depends_on": [], - "source_code": "def count_code_files(repo_path: Path) -> int:\n \"\"\"\n Count supported code files in repository.\n \n Args:\n repo_path: Repository path\n \n Returns:\n Number of code files\n \"\"\"\n count = 0\n for ext in SUPPORTED_EXTENSIONS:\n count += len(list(repo_path.rglob(f\"*{ext}\")))\n return count", - "start_line": 196, - "end_line": 209, - "has_docstring": true, - "docstring": "Count supported code files in repository.\n\nArgs:\n repo_path: Repository path\n \nReturns:\n Number of code files", - "parameters": [ - "repo_path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function count_code_files", - "component_id": "codewiki/cli/utils/repo_validator.py::count_code_files", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/validation.py::validate_url": { - "id": "codewiki/cli/utils/validation.py::validate_url", - "name": "validate_url", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/validation.py", - "relative_path": "codewiki/cli/utils/validation.py", - "depends_on": [ - "codewiki/cli/utils/errors.py::ConfigurationError" - ], - "source_code": "def validate_url(url: str, require_https: bool = False, allow_localhost: bool = True) -> str:\n \"\"\"\n Validate URL format.\n \n Args:\n url: URL to validate\n require_https: Require HTTPS scheme (except localhost)\n allow_localhost: Allow localhost URLs\n \n Returns:\n Validated URL\n \n Raises:\n ConfigurationError: If URL is invalid\n \"\"\"\n try:\n parsed = urlparse(url)\n \n # Check scheme\n if not parsed.scheme:\n raise ConfigurationError(f\"Invalid URL (missing scheme): {url}\")\n \n # Check HTTPS requirement\n if require_https and parsed.scheme != 'https':\n # Allow HTTP for localhost\n if allow_localhost and parsed.hostname in ['localhost', '127.0.0.1', '::1']:\n pass\n else:\n raise ConfigurationError(\n f\"URL must use HTTPS: {url}\\n\"\n f\"HTTP is only allowed for localhost\"\n )\n \n # Check hostname\n if not parsed.hostname:\n raise ConfigurationError(f\"Invalid URL (missing hostname): {url}\")\n \n return url\n except ValueError as e:\n raise ConfigurationError(f\"Invalid URL format: {url}\\nError: {e}\")", - "start_line": 13, - "end_line": 52, - "has_docstring": true, - "docstring": "Validate URL format.\n\nArgs:\n url: URL to validate\n require_https: Require HTTPS scheme (except localhost)\n allow_localhost: Allow localhost URLs\n \nReturns:\n Validated URL\n \nRaises:\n ConfigurationError: If URL is invalid", - "parameters": [ - "url", - "require_https", - "allow_localhost" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function validate_url", - "component_id": "codewiki/cli/utils/validation.py::validate_url", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/validation.py::validate_api_key": { - "id": "codewiki/cli/utils/validation.py::validate_api_key", - "name": "validate_api_key", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/validation.py", - "relative_path": "codewiki/cli/utils/validation.py", - "depends_on": [ - "codewiki/cli/utils/errors.py::ConfigurationError" - ], - "source_code": "def validate_api_key(api_key: str, min_length: int = 10) -> str:\n \"\"\"\n Validate API key format.\n \n Args:\n api_key: API key to validate\n min_length: Minimum key length\n \n Returns:\n Validated API key\n \n Raises:\n ConfigurationError: If API key is invalid\n \"\"\"\n if not api_key or not api_key.strip():\n raise ConfigurationError(\"API key cannot be empty\")\n \n api_key = api_key.strip()\n \n if len(api_key) < min_length:\n raise ConfigurationError(\n f\"API key too short (minimum {min_length} characters)\"\n )\n \n return api_key", - "start_line": 55, - "end_line": 79, - "has_docstring": true, - "docstring": "Validate API key format.\n\nArgs:\n api_key: API key to validate\n min_length: Minimum key length\n \nReturns:\n Validated API key\n \nRaises:\n ConfigurationError: If API key is invalid", - "parameters": [ - "api_key", - "min_length" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function validate_api_key", - "component_id": "codewiki/cli/utils/validation.py::validate_api_key", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/validation.py::validate_model_name": { - "id": "codewiki/cli/utils/validation.py::validate_model_name", - "name": "validate_model_name", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/validation.py", - "relative_path": "codewiki/cli/utils/validation.py", - "depends_on": [ - "codewiki/cli/utils/errors.py::ConfigurationError" - ], - "source_code": "def validate_model_name(model: str) -> str:\n \"\"\"\n Validate model name format.\n \n Args:\n model: Model name to validate\n \n Returns:\n Validated model name\n \n Raises:\n ConfigurationError: If model name is invalid\n \"\"\"\n if not model or not model.strip():\n raise ConfigurationError(\"Model name cannot be empty\")\n \n return model.strip()", - "start_line": 82, - "end_line": 98, - "has_docstring": true, - "docstring": "Validate model name format.\n\nArgs:\n model: Model name to validate\n \nReturns:\n Validated model name\n \nRaises:\n ConfigurationError: If model name is invalid", - "parameters": [ - "model" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function validate_model_name", - "component_id": "codewiki/cli/utils/validation.py::validate_model_name", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/validation.py::validate_output_directory": { - "id": "codewiki/cli/utils/validation.py::validate_output_directory", - "name": "validate_output_directory", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/validation.py", - "relative_path": "codewiki/cli/utils/validation.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/cli/utils/errors.py::ConfigurationError" - ], - "source_code": "def validate_output_directory(path: str) -> Path:\n \"\"\"\n Validate output directory path.\n \n Args:\n path: Directory path to validate\n \n Returns:\n Validated Path object\n \n Raises:\n ConfigurationError: If path is invalid\n \"\"\"\n if not path or not path.strip():\n raise ConfigurationError(\"Output directory cannot be empty\")\n \n try:\n resolved_path = Path(path).expanduser().resolve()\n \n # Check if path is writable (or parent is writable if path doesn't exist)\n if resolved_path.exists():\n if not resolved_path.is_dir():\n raise ConfigurationError(\n f\"Output path exists but is not a directory: {path}\"\n )\n \n return resolved_path\n except Exception as e:\n raise ConfigurationError(f\"Invalid output directory path: {path}\\nError: {e}\")", - "start_line": 101, - "end_line": 129, - "has_docstring": true, - "docstring": "Validate output directory path.\n\nArgs:\n path: Directory path to validate\n \nReturns:\n Validated Path object\n \nRaises:\n ConfigurationError: If path is invalid", - "parameters": [ - "path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function validate_output_directory", - "component_id": "codewiki/cli/utils/validation.py::validate_output_directory", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/validation.py::validate_repository_path": { - "id": "codewiki/cli/utils/validation.py::validate_repository_path", - "name": "validate_repository_path", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/validation.py", - "relative_path": "codewiki/cli/utils/validation.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/cli/utils/errors.py::RepositoryError" - ], - "source_code": "def validate_repository_path(path: Path) -> Path:\n \"\"\"\n Validate repository path exists and contains code files.\n \n Args:\n path: Repository path to validate\n \n Returns:\n Validated Path object\n \n Raises:\n RepositoryError: If repository is invalid\n \"\"\"\n path = Path(path).expanduser().resolve()\n \n if not path.exists():\n raise RepositoryError(f\"Repository path does not exist: {path}\")\n \n if not path.is_dir():\n raise RepositoryError(f\"Repository path is not a directory: {path}\")\n \n return path", - "start_line": 132, - "end_line": 153, - "has_docstring": true, - "docstring": "Validate repository path exists and contains code files.\n\nArgs:\n path: Repository path to validate\n \nReturns:\n Validated Path object\n \nRaises:\n RepositoryError: If repository is invalid", - "parameters": [ - "path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function validate_repository_path", - "component_id": "codewiki/cli/utils/validation.py::validate_repository_path", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/validation.py::detect_supported_languages": { - "id": "codewiki/cli/utils/validation.py::detect_supported_languages", - "name": "detect_supported_languages", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/validation.py", - "relative_path": "codewiki/cli/utils/validation.py", - "depends_on": [], - "source_code": "def detect_supported_languages(directory: Path) -> List[Tuple[str, int]]:\n \"\"\"\n Detect supported programming languages in a directory.\n \n Args:\n directory: Directory to scan\n \n Returns:\n List of (language, file_count) tuples\n \"\"\"\n language_extensions = {\n 'Python': ['.py'],\n 'Java': ['.java'],\n 'JavaScript': ['.js', '.jsx'],\n 'TypeScript': ['.ts', '.tsx'],\n 'C': ['.c', '.h'],\n 'C++': ['.cpp', '.hpp', '.cc', '.hh', '.cxx', '.hxx'],\n 'C#': ['.cs'],\n 'PHP': ['.php', '.phtml', '.inc'],\n 'Kotlin': ['.kt', '.kts'],\n }\n \n # Directories to exclude from counting\n excluded_dirs = {\n 'node_modules', '__pycache__', '.git', 'build', 'dist', \n '.venv', 'venv', 'env', '.env', 'target', 'bin', 'obj',\n '.pytest_cache', '.mypy_cache', '.tox', 'coverage',\n 'htmlcov', '.eggs', '*.egg-info', 'vendor', 'bower_components',\n '.idea', '.vscode', '.gradle', '.mvn'\n }\n \n def should_exclude_file(file_path: Path) -> bool:\n \"\"\"Check if file is in an excluded directory.\"\"\"\n parts = file_path.parts\n return any(excluded_dir in parts for excluded_dir in excluded_dirs)\n \n language_counts = {}\n \n for language, extensions in language_extensions.items():\n count = 0\n for ext in extensions:\n # Filter out files in excluded directories\n count += sum(\n 1 for f in directory.rglob(f\"*{ext}\")\n if f.is_file() and not should_exclude_file(f)\n )\n \n if count > 0:\n language_counts[language] = count\n \n # Sort by count descending\n return sorted(language_counts.items(), key=lambda x: x[1], reverse=True)", - "start_line": 156, - "end_line": 207, - "has_docstring": true, - "docstring": "Detect supported programming languages in a directory.\n\nArgs:\n directory: Directory to scan\n \nReturns:\n List of (language, file_count) tuples", - "parameters": [ - "directory" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function detect_supported_languages", - "component_id": "codewiki/cli/utils/validation.py::detect_supported_languages", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/validation.py::is_top_tier_model": { - "id": "codewiki/cli/utils/validation.py::is_top_tier_model", - "name": "is_top_tier_model", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/validation.py", - "relative_path": "codewiki/cli/utils/validation.py", - "depends_on": [], - "source_code": "def is_top_tier_model(model: str) -> bool:\n \"\"\"\n Check if a model is considered top-tier for clustering.\n \n Args:\n model: Model name\n \n Returns:\n True if top-tier, False otherwise\n \"\"\"\n top_tier_models = [\n 'claude-opus',\n 'claude-sonnet',\n 'gpt-4',\n 'gpt-5',\n 'gemini-2.5',\n ]\n \n model_lower = model.lower()\n return any(tier in model_lower for tier in top_tier_models)", - "start_line": 210, - "end_line": 229, - "has_docstring": true, - "docstring": "Check if a model is considered top-tier for clustering.\n\nArgs:\n model: Model name\n \nReturns:\n True if top-tier, False otherwise", - "parameters": [ - "model" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function is_top_tier_model", - "component_id": "codewiki/cli/utils/validation.py::is_top_tier_model", - "language": null, - "qualified_name": null - }, - "codewiki/cli/utils/validation.py::mask_api_key": { - "id": "codewiki/cli/utils/validation.py::mask_api_key", - "name": "mask_api_key", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/cli/utils/validation.py", - "relative_path": "codewiki/cli/utils/validation.py", - "depends_on": [], - "source_code": "def mask_api_key(api_key: str, visible_chars: int = 4) -> str:\n \"\"\"\n Mask API key for display, showing only first and last few characters.\n \n Args:\n api_key: API key to mask\n visible_chars: Number of visible characters at start and end\n \n Returns:\n Masked API key (e.g., \"sk-1234...5678\")\n \"\"\"\n if not api_key:\n return \"Not set\"\n \n if len(api_key) <= visible_chars * 2:\n # Key too short, mask everything except edges\n return f\"{api_key[:2]}...{api_key[-2:]}\"\n \n return f\"{api_key[:visible_chars]}...{api_key[-visible_chars:]}\"", - "start_line": 232, - "end_line": 250, - "has_docstring": true, - "docstring": "Mask API key for display, showing only first and last few characters.\n\nArgs:\n api_key: API key to mask\n visible_chars: Number of visible characters at start and end\n \nReturns:\n Masked API key (e.g., \"sk-1234...5678\")", - "parameters": [ - "api_key", - "visible_chars" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function mask_api_key", - "component_id": "codewiki/cli/utils/validation.py::mask_api_key", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/server.py::_fine_grained_tools": { - "id": "codewiki/mcp/server.py::_fine_grained_tools", - "name": "_fine_grained_tools", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/server.py", - "relative_path": "codewiki/mcp/server.py", - "depends_on": [], - "source_code": "def _fine_grained_tools() -> list[Tool]:\n \"\"\"Return the zero-config, IDE-driven tool set.\"\"\"\n return [\n Tool(\n name=\"analyze_repo\",\n description=(\n \"Analyze a code repository's structure, dependencies, and components \"\n \"using Tree-sitter AST parsing. No LLM required. \"\n \"Writes the full component index, leaf nodes, and language stats to \"\n \"workspace files on disk, and returns file paths plus a compact summary. \"\n \"Read the workspace files for complete data. \"\n \"This is the entry point for the wiki generation pipeline. \"\n \"After calling this, use get_prompt('cluster') to learn clustering rules, \"\n \"then save_module_tree to persist your grouping. \"\n \"INCREMENTAL UPDATE: If docs already exist in output_dir (metadata.json + \"\n \"module_tree.json), the response includes a 'changes' field showing which \"\n \"files changed and which modules need updating.\"\n ),\n inputSchema={\n \"type\": \"object\",\n \"properties\": {\n \"repo_path\": {\n \"type\": \"string\",\n \"description\": \"Absolute path to the repository to analyze\",\n },\n \"output_dir\": {\n \"type\": \"string\",\n \"description\": \"Output directory for generated docs (default: /docs)\",\n },\n \"include_patterns\": {\n \"type\": \"string\",\n \"description\": \"Comma-separated file patterns to include (e.g., '*.py,*.js')\",\n },\n \"exclude_patterns\": {\n \"type\": \"string\",\n \"description\": \"Comma-separated patterns to exclude (e.g., '*test*,*spec*')\",\n },\n \"use_gitignore\": {\n \"type\": \"boolean\",\n \"description\": \"Apply Git ignore rules before analysis (default: true)\",\n \"default\": True,\n },\n },\n \"required\": [\"repo_path\"],\n },\n ),\n Tool(\n name=\"read_code_components\",\n description=(\n \"Write the source code for a list of component IDs to workspace files. \"\n \"Component IDs have the form 'file_path::ComponentName'. \"\n \"Each component's full source is written to an individual .src file \"\n \"in the session's sources/ directory. Returns file paths β€” no truncation.\"\n ),\n inputSchema={\n \"type\": \"object\",\n \"properties\": {\n \"session_id\": {\n \"type\": \"string\",\n \"description\": \"Session ID from analyze_repo\",\n },\n \"component_ids\": {\n \"type\": \"array\",\n \"items\": {\"type\": \"string\"},\n \"description\": \"List of component IDs to read\",\n },\n },\n \"required\": [\"session_id\", \"component_ids\"],\n },\n ),\n Tool(\n name=\"write_doc_file\",\n description=(\n \"Create a new markdown documentation file in the output directory. \"\n \"Automatically validates Mermaid diagrams after writing.\"\n ),\n inputSchema={\n \"type\": \"object\",\n \"properties\": {\n \"session_id\": {\n \"type\": \"string\",\n \"description\": \"Session ID from analyze_repo\",\n },\n \"filename\": {\n \"type\": \"string\",\n \"description\": \"Filename for the doc (e.g., 'auth_module.md')\",\n },\n \"content\": {\n \"type\": \"string\",\n \"description\": \"Markdown content to write\",\n },\n },\n \"required\": [\"session_id\", \"filename\", \"content\"],\n },\n ),\n Tool(\n name=\"edit_doc_file\",\n description=(\n \"Edit an existing documentation file. Supports str_replace (find-and-replace), \"\n \"insert (add text at a line), and undo (revert last edit). \"\n \"Automatically validates Mermaid diagrams after editing.\"\n ),\n inputSchema={\n \"type\": \"object\",\n \"properties\": {\n \"session_id\": {\n \"type\": \"string\",\n \"description\": \"Session ID from analyze_repo\",\n },\n \"filename\": {\n \"type\": \"string\",\n \"description\": \"Filename of the doc to edit\",\n },\n \"command\": {\n \"type\": \"string\",\n \"enum\": [\"str_replace\", \"insert\", \"undo\"],\n \"description\": \"Edit command to run\",\n },\n \"old_str\": {\n \"type\": \"string\",\n \"description\": \"String to find (required for str_replace)\",\n },\n \"new_str\": {\n \"type\": \"string\",\n \"description\": \"Replacement string (for str_replace/insert)\",\n },\n \"insert_line\": {\n \"type\": \"integer\",\n \"description\": \"Line number for insert (0-indexed)\",\n },\n },\n \"required\": [\"session_id\", \"filename\", \"command\"],\n },\n ),\n Tool(\n name=\"save_module_tree\",\n description=(\n \"Save the IDE agent's module clustering result. \"\n \"Accepts a JSON module tree and persists it to disk. \"\n \"Computes the leaf-first processing order and writes it to a workspace file. \"\n \"Returns the file path for the processing order.\"\n ),\n inputSchema={\n \"type\": \"object\",\n \"properties\": {\n \"session_id\": {\n \"type\": \"string\",\n \"description\": \"Session ID from analyze_repo\",\n },\n \"module_tree\": {\n \"type\": \"object\",\n \"description\": (\n \"Module tree dict. Each key is a module name with value \"\n \"{'components': [component_ids], 'children': {nested modules}}\"\n ),\n },\n },\n \"required\": [\"session_id\", \"module_tree\"],\n },\n ),\n Tool(\n name=\"get_processing_order\",\n description=(\n \"Compute and write the leaf-first processing order to a workspace file. \"\n \"Returns the file path. Process leaf modules (is_leaf=true) before parent modules.\"\n ),\n inputSchema={\n \"type\": \"object\",\n \"properties\": {\n \"session_id\": {\n \"type\": \"string\",\n \"description\": \"Session ID from analyze_repo\",\n },\n },\n \"required\": [\"session_id\"],\n },\n ),\n Tool(\n name=\"get_prompt\",\n description=(\n \"Retrieve CodeWiki's prompt templates for each pipeline stage. \"\n \"Available types: cluster, system_complex, system_leaf, user, \"\n \"overview_module, overview_repo. Optionally pass variables to \"\n \"fill in template placeholders.\"\n ),\n inputSchema={\n \"type\": \"object\",\n \"properties\": {\n \"prompt_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"cluster\",\n \"system_complex\",\n \"system_leaf\",\n \"user\",\n \"overview_module\",\n \"overview_repo\",\n ],\n \"description\": \"Which prompt template to retrieve\",\n },\n \"variables\": {\n \"type\": \"object\",\n \"description\": \"Optional template variables to fill in\",\n },\n },\n \"required\": [\"prompt_type\"],\n },\n ),\n Tool(\n name=\"close_session\",\n description=\"Close and clean up an analysis session to free memory.\",\n inputSchema={\n \"type\": \"object\",\n \"properties\": {\n \"session_id\": {\n \"type\": \"string\",\n \"description\": \"Session ID to close\",\n },\n },\n \"required\": [\"session_id\"],\n },\n ),\n ]", - "start_line": 68, - "end_line": 290, - "has_docstring": true, - "docstring": "Return the zero-config, IDE-driven tool set.", - "parameters": [], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _fine_grained_tools", - "component_id": "codewiki/mcp/server.py::_fine_grained_tools", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/server.py::_legacy_tools": { - "id": "codewiki/mcp/server.py::_legacy_tools", - "name": "_legacy_tools", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/server.py", - "relative_path": "codewiki/mcp/server.py", - "depends_on": [], - "source_code": "def _legacy_tools() -> list[Tool]:\n \"\"\"Return the legacy tools that require CodeWiki LLM configuration.\"\"\"\n return [\n Tool(\n name=\"generate_docs\",\n description=(\n \"[LEGACY β€” requires 'codewiki config set' first] \"\n \"Generate full documentation for a repository in one shot. \"\n \"For IDE-driven generation, use the fine-grained tools instead.\"\n ),\n inputSchema={\n \"type\": \"object\",\n \"properties\": {\n \"repo_path\": {\n \"type\": \"string\",\n \"description\": \"Absolute path to the repository to document\",\n },\n \"output_dir\": {\n \"type\": \"string\",\n \"description\": \"Output directory for generated docs (default: ./docs)\",\n \"default\": \"docs\",\n },\n \"doc_type\": {\n \"type\": \"string\",\n \"enum\": [\"api\", \"architecture\", \"user-guide\", \"developer\"],\n \"description\": \"Type of documentation to generate\",\n },\n \"include_patterns\": {\n \"type\": \"string\",\n \"description\": \"Comma-separated file patterns to include\",\n },\n \"exclude_patterns\": {\n \"type\": \"string\",\n \"description\": \"Comma-separated patterns to exclude\",\n },\n \"use_gitignore\": {\n \"type\": \"boolean\",\n \"description\": \"Apply Git ignore rules before analysis (default: true)\",\n \"default\": True,\n },\n },\n \"required\": [\"repo_path\"],\n },\n ),\n Tool(\n name=\"get_module_tree\",\n description=\"Get the existing module clustering tree for a repository.\",\n inputSchema={\n \"type\": \"object\",\n \"properties\": {\n \"repo_path\": {\n \"type\": \"string\",\n \"description\": \"Absolute path to the repository\",\n },\n \"output_dir\": {\n \"type\": \"string\",\n \"description\": \"Directory containing generated docs (default: ./docs)\",\n \"default\": \"docs\",\n },\n },\n \"required\": [\"repo_path\"],\n },\n ),\n ]", - "start_line": 293, - "end_line": 356, - "has_docstring": true, - "docstring": "Return the legacy tools that require CodeWiki LLM configuration.", - "parameters": [], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _legacy_tools", - "component_id": "codewiki/mcp/server.py::_legacy_tools", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/server.py::list_tools": { - "id": "codewiki/mcp/server.py::list_tools", - "name": "list_tools", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/server.py", - "relative_path": "codewiki/mcp/server.py", - "depends_on": [ - "codewiki/mcp/server.py::_fine_grained_tools", - "codewiki/mcp/server.py::_legacy_tools", - "codewiki/mcp/server.py::list_tools" - ], - "source_code": "async def list_tools() -> list[Tool]:\n \"\"\"List all available CodeWiki MCP tools.\"\"\"\n return _fine_grained_tools() + _legacy_tools()", - "start_line": 364, - "end_line": 366, - "has_docstring": true, - "docstring": "List all available CodeWiki MCP tools.", - "parameters": [], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function list_tools", - "component_id": "codewiki/mcp/server.py::list_tools", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/server.py::call_tool": { - "id": "codewiki/mcp/server.py::call_tool", - "name": "call_tool", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/server.py", - "relative_path": "codewiki/mcp/server.py", - "depends_on": [ - "codewiki/mcp/tools/doc_writer.py::handle_edit_doc_file", - "codewiki/mcp/tools/doc_writer.py::handle_write_doc_file", - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/mcp/tools/analysis.py::handle_analyze_repo", - "codewiki/mcp/server.py::_text", - "codewiki/cli/utils/logging.py::CLILogger.error", - "codewiki/mcp/server.py::_legacy_get_module_tree", - "codewiki/mcp/server.py::_legacy_generate_docs", - "codewiki/mcp/server.py::_write_generation_metadata", - "codewiki/mcp/server.py::call_tool", - "codewiki/mcp/workspace.py::SessionWorkspace.cleanup", - "codewiki/mcp/session.py::SessionStore.remove" - ], - "source_code": "async def call_tool(name: str, arguments: dict[str, Any]) -> list[TextContent]:\n \"\"\"Route tool calls to the appropriate handler.\"\"\"\n try:\n # --- Fine-grained tools (no LLM config needed) ---\n # Synchronous handlers run via asyncio.to_thread() so they never\n # block the event loop (which would hang the MCP stdio server).\n if name == \"analyze_repo\":\n from codewiki.mcp.tools.analysis import handle_analyze_repo\n # NOTE: Tree-sitter C extensions are not thread-safe, so this\n # must run on the main thread (blocking the event loop is\n # acceptable for this one-time heavy operation).\n return [_text(handle_analyze_repo(arguments, _store))]\n\n elif name == \"read_code_components\":\n from codewiki.mcp.tools.code_reader import handle_read_code_components\n return [_text(await asyncio.to_thread(handle_read_code_components, arguments, _store))]\n\n elif name == \"write_doc_file\":\n from codewiki.mcp.tools.doc_writer import handle_write_doc_file\n result = await handle_write_doc_file(arguments, _store)\n return [_text(result)]\n\n elif name == \"edit_doc_file\":\n from codewiki.mcp.tools.doc_writer import handle_edit_doc_file\n result = await handle_edit_doc_file(arguments, _store)\n return [_text(result)]\n\n elif name == \"save_module_tree\":\n from codewiki.mcp.tools.module_tree import handle_save_module_tree\n return [_text(await asyncio.to_thread(handle_save_module_tree, arguments, _store))]\n\n elif name == \"get_processing_order\":\n from codewiki.mcp.tools.module_tree import handle_get_processing_order\n return [_text(await asyncio.to_thread(handle_get_processing_order, arguments, _store))]\n\n elif name == \"get_prompt\":\n from codewiki.mcp.tools.prompt_server import handle_get_prompt\n return [_text(await asyncio.to_thread(handle_get_prompt, arguments, _store))]\n\n elif name == \"close_session\":\n sid = arguments[\"session_id\"]\n session = _store.get(sid)\n if session:\n # Only stamp the incremental-update baseline when this\n # session actually produced docs β€” otherwise an aborted\n # session would make the next analyze_repo report\n # \"Documentation is up to date\" over missing/stale docs.\n if session.docs_written > 0:\n _write_generation_metadata(session)\n else:\n logger.info(\n \"Session %s wrote no docs; skipping metadata.json baseline update\", sid\n )\n # Clean up workspace files on disk\n if session.workspace is not None:\n session.workspace.cleanup()\n removed = _store.remove(sid)\n return [_text(json.dumps({\n \"status\": \"closed\" if removed else \"not_found\",\n \"session_id\": sid,\n }))]\n\n # --- Legacy tools (require CodeWiki LLM config) ---\n elif name == \"generate_docs\":\n return await _legacy_generate_docs(arguments)\n\n elif name == \"get_module_tree\":\n return await _legacy_get_module_tree(arguments)\n\n else:\n return [_text(json.dumps({\"error\": f\"Unknown tool: {name}\"}))]\n\n except Exception as e:\n logger.error(\"Tool %s failed: %s\", name, e, exc_info=True)\n return [_text(json.dumps({\"error\": str(e)}))]", - "start_line": 370, - "end_line": 444, - "has_docstring": true, - "docstring": "Route tool calls to the appropriate handler.", - "parameters": [ - "name", - "arguments" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function call_tool", - "component_id": "codewiki/mcp/server.py::call_tool", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/server.py::_load_config": { - "id": "codewiki/mcp/server.py::_load_config", - "name": "_load_config", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/server.py", - "relative_path": "codewiki/mcp/server.py", - "depends_on": [ - "codewiki/cli/config_manager.py::ConfigManager", - "codewiki/cli/config_manager.py::ConfigManager.load" - ], - "source_code": "def _load_config():\n \"\"\"Load CodeWiki configuration from ~/.codewiki/config.json + keyring.\"\"\"\n from codewiki.cli.config_manager import ConfigManager\n manager = ConfigManager()\n if not manager.load():\n raise RuntimeError(\n \"CodeWiki not configured. Run 'codewiki config set' first.\"\n )\n return manager", - "start_line": 451, - "end_line": 459, - "has_docstring": true, - "docstring": "Load CodeWiki configuration from ~/.codewiki/config.json + keyring.", - "parameters": [], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _load_config", - "component_id": "codewiki/mcp/server.py::_load_config", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/server.py::_legacy_generate_docs": { - "id": "codewiki/mcp/server.py::_legacy_generate_docs", - "name": "_legacy_generate_docs", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/server.py", - "relative_path": "codewiki/mcp/server.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/src/config.py::Config.from_cli", - "codewiki/src/be/backend.py::is_caw_provider", - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/mcp/server.py::_text", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.run", - "codewiki/cli/config_manager.py::ConfigManager.get_config", - "codewiki/src/config.py::set_cli_context", - "codewiki/cli/utils/repo_validator.py::get_git_commit_hash", - "codewiki/cli/config_manager.py::ConfigManager.get_api_key", - "codewiki/mcp/server.py::_load_config" - ], - "source_code": "async def _legacy_generate_docs(arguments: dict[str, Any]) -> list[TextContent]:\n \"\"\"Legacy generate_docs β€” requires CodeWiki LLM configuration.\"\"\"\n repo_path = Path(arguments[\"repo_path\"]).expanduser().resolve()\n output_dir = Path(arguments.get(\"output_dir\", \"docs\")).expanduser().resolve()\n\n if not repo_path.exists():\n return [_text(json.dumps({\"error\": f\"Repository not found: {repo_path}\"}))]\n\n manager = _load_config()\n config = manager.get_config()\n api_key = manager.get_api_key()\n\n from codewiki.src.be.backend import is_caw_provider\n caw_mode = bool(config) and is_caw_provider(getattr(config, \"provider\", \"\"))\n if not api_key and not caw_mode:\n return [_text(json.dumps({\"error\": \"API key not configured. Run 'codewiki config set --api-key '\"}))]\n\n agent_instructions = {}\n if arguments.get(\"doc_type\"):\n agent_instructions[\"doc_type\"] = arguments[\"doc_type\"]\n if arguments.get(\"include_patterns\"):\n agent_instructions[\"include_patterns\"] = [p.strip() for p in arguments[\"include_patterns\"].split(\",\")]\n if arguments.get(\"exclude_patterns\"):\n agent_instructions[\"exclude_patterns\"] = [p.strip() for p in arguments[\"exclude_patterns\"].split(\",\")]\n\n from codewiki.src.config import Config as BackendConfig, set_cli_context\n set_cli_context(True)\n\n backend_config = BackendConfig.from_cli(\n repo_path=str(repo_path),\n output_dir=str(output_dir),\n llm_base_url=config.base_url,\n llm_api_key=api_key,\n main_model=config.main_model,\n cluster_model=config.cluster_model,\n fallback_model=config.fallback_model,\n provider=getattr(config, \"provider\", \"openai-compatible\"),\n aws_region=getattr(config, \"aws_region\", \"us-east-1\"),\n max_tokens=config.max_tokens,\n agent_instructions=agent_instructions or None,\n use_gitignore=arguments.get(\"use_gitignore\", True),\n )\n\n from codewiki.cli.utils.repo_validator import get_git_commit_hash\n from codewiki.src.be.documentation_generator import DocumentationGenerator\n doc_gen = DocumentationGenerator(backend_config, commit_id=get_git_commit_hash(repo_path) or None)\n await doc_gen.run()\n\n generated_files = []\n for f in output_dir.iterdir():\n if f.suffix in (\".md\", \".json\", \".html\"):\n generated_files.append(f.name)\n\n result = {\n \"status\": \"success\",\n \"output_dir\": str(output_dir),\n \"files_generated\": sorted(generated_files),\n \"file_count\": len(generated_files),\n }\n return [_text(json.dumps(result, indent=2))]", - "start_line": 462, - "end_line": 521, - "has_docstring": true, - "docstring": "Legacy generate_docs β€” requires CodeWiki LLM configuration.", - "parameters": [ - "arguments" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _legacy_generate_docs", - "component_id": "codewiki/mcp/server.py::_legacy_generate_docs", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/server.py::_legacy_get_module_tree": { - "id": "codewiki/mcp/server.py::_legacy_get_module_tree", - "name": "_legacy_get_module_tree", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/server.py", - "relative_path": "codewiki/mcp/server.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/mcp/server.py::_text" - ], - "source_code": "async def _legacy_get_module_tree(arguments: dict[str, Any]) -> list[TextContent]:\n \"\"\"Legacy get_module_tree.\"\"\"\n repo_path = Path(arguments[\"repo_path\"]).expanduser().resolve()\n output_dir = Path(arguments.get(\"output_dir\", \"docs\")).expanduser().resolve()\n\n module_tree_path = output_dir / \"module_tree.json\"\n if not module_tree_path.exists():\n return [_text(json.dumps({\n \"error\": f\"Module tree not found at {module_tree_path}. Run 'codewiki generate' first.\"\n }))]\n\n module_tree = json.loads(module_tree_path.read_text(encoding=\"utf-8\"))\n\n def _summarize_tree(tree, depth=0):\n lines = []\n for name, info in tree.items():\n indent = \" \" * depth\n comp_count = len(info.get(\"components\", []))\n children = info.get(\"children\", {})\n child_count = len(children) if isinstance(children, dict) else 0\n lines.append(f\"{indent}- {name} ({comp_count} components, {child_count} children)\")\n if isinstance(children, dict) and children:\n lines.extend(_summarize_tree(children, depth + 1))\n return lines\n\n summary = \"\\n\".join(_summarize_tree(module_tree))\n result = {\n \"status\": \"success\",\n \"module_tree_path\": str(module_tree_path),\n \"total_modules\": len(module_tree),\n \"tree_summary\": summary,\n }\n return [_text(json.dumps(result, indent=2))]", - "start_line": 524, - "end_line": 556, - "has_docstring": true, - "docstring": "Legacy get_module_tree.", - "parameters": [ - "arguments" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _legacy_get_module_tree", - "component_id": "codewiki/mcp/server.py::_legacy_get_module_tree", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/server.py::_text": { - "id": "codewiki/mcp/server.py::_text", - "name": "_text", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/server.py", - "relative_path": "codewiki/mcp/server.py", - "depends_on": [], - "source_code": "def _text(content: str) -> TextContent:\n return TextContent(type=\"text\", text=content)", - "start_line": 563, - "end_line": 564, - "has_docstring": false, - "docstring": "", - "parameters": [ - "content" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _text", - "component_id": "codewiki/mcp/server.py::_text", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/server.py::_write_generation_metadata": { - "id": "codewiki/mcp/server.py::_write_generation_metadata", - "name": "_write_generation_metadata", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/server.py", - "relative_path": "codewiki/mcp/server.py", - "depends_on": [ - "codewiki/cli/utils/repo_validator.py::get_git_commit_hash", - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": "def _write_generation_metadata(session: SessionState) -> None:\n \"\"\"Write ``metadata.json`` to the session's output directory.\n\n Merges the current git commit and timestamp into any existing metadata\n so that stats from other workflows (e.g. CLI ``generate_docs``) are\n preserved.\n \"\"\"\n try:\n output_dir = Path(session.output_dir)\n repo_path = Path(session.repo_path)\n\n # Baseline on the commit analyze_repo saw, NOT the current HEAD:\n # commits made mid-session were never analyzed, and recording HEAD\n # here would silently exclude them from the next incremental run.\n commit_id: str | None = session.analyzed_commit\n if not commit_id:\n from codewiki.cli.utils.repo_validator import get_git_commit_hash\n commit_id = get_git_commit_hash(repo_path) or None\n\n from datetime import datetime\n\n # Read existing metadata (if any) and merge\n metadata_path = output_dir / \"metadata.json\"\n existing: dict = {}\n if metadata_path.exists():\n try:\n existing = json.loads(metadata_path.read_text(encoding=\"utf-8\"))\n except (json.JSONDecodeError, OSError):\n pass\n\n existing[\"generation_info\"] = {\n **existing.get(\"generation_info\", {}),\n \"commit_id\": commit_id,\n \"timestamp\": datetime.now().isoformat(),\n }\n metadata_path.write_text(\n json.dumps(existing, indent=2, ensure_ascii=False),\n encoding=\"utf-8\",\n )\n except Exception as e:\n logger.warning(\"Failed to write metadata.json: %s\", e)", - "start_line": 567, - "end_line": 607, - "has_docstring": true, - "docstring": "Write ``metadata.json`` to the session's output directory.\n\nMerges the current git commit and timestamp into any existing metadata\nso that stats from other workflows (e.g. CLI ``generate_docs``) are\npreserved.", - "parameters": [ - "session" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _write_generation_metadata", - "component_id": "codewiki/mcp/server.py::_write_generation_metadata", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/server.py::main": { - "id": "codewiki/mcp/server.py::main", - "name": "main", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/server.py", - "relative_path": "codewiki/mcp/server.py", - "depends_on": [ - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.run" - ], - "source_code": "async def main():\n \"\"\"Run the MCP server with stdio transport.\"\"\"\n async with stdio_server() as (read_stream, write_stream):\n await server.run(\n read_stream,\n write_stream,\n server.create_initialization_options(),\n )", - "start_line": 614, - "end_line": 621, - "has_docstring": true, - "docstring": "Run the MCP server with stdio transport.", - "parameters": [], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function main", - "component_id": "codewiki/mcp/server.py::main", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/session.py::SessionState": { - "id": "codewiki/mcp/session.py::SessionState", - "name": "SessionState", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/session.py", - "relative_path": "codewiki/mcp/session.py", - "depends_on": [], - "source_code": "class SessionState:\n \"\"\"Mutable state shared across all MCP tool calls within a session.\"\"\"\n\n session_id: str\n repo_path: str\n output_dir: str\n components: Dict[str, Node]\n leaf_nodes: List[str]\n module_tree: Dict[str, Any] = field(default_factory=dict)\n registry: Dict[str, Any] = field(default_factory=dict)\n workspace: Optional[SessionWorkspace] = field(default=None)\n # HEAD commit at analyze_repo time β€” the incremental-update baseline.\n # close_session must record this commit (not the HEAD at close time),\n # otherwise commits made mid-session are baselined away undocumented.\n analyzed_commit: Optional[str] = None\n # Number of successful write_doc_file/edit_doc_file operations; used to\n # skip the metadata.json baseline update when a session wrote no docs.\n docs_written: int = 0\n created_at: float = field(default_factory=time.time)\n last_accessed: float = field(default_factory=time.time)\n\n def touch(self) -> None:\n \"\"\"Update the last-accessed timestamp.\"\"\"\n self.last_accessed = time.time()\n\n @property\n def is_expired(self) -> bool:\n return (time.time() - self.last_accessed) > _SESSION_TTL_SECONDS", - "start_line": 31, - "end_line": 58, - "has_docstring": true, - "docstring": "Mutable state shared across all MCP tool calls within a session.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class SessionState", - "component_id": "codewiki/mcp/session.py::SessionState", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/session.py::SessionState.touch": { - "id": "codewiki/mcp/session.py::SessionState.touch", - "name": "SessionState.touch", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/session.py", - "relative_path": "codewiki/mcp/session.py", - "depends_on": [], - "source_code": " def touch(self) -> None:\n \"\"\"Update the last-accessed timestamp.\"\"\"\n self.last_accessed = time.time()", - "start_line": 52, - "end_line": 54, - "has_docstring": true, - "docstring": "Update the last-accessed timestamp.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "SessionState", - "display_name": "method SessionState.touch", - "component_id": "codewiki/mcp/session.py::SessionState.touch", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/session.py::SessionState.is_expired": { - "id": "codewiki/mcp/session.py::SessionState.is_expired", - "name": "SessionState.is_expired", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/session.py", - "relative_path": "codewiki/mcp/session.py", - "depends_on": [], - "source_code": " def is_expired(self) -> bool:\n return (time.time() - self.last_accessed) > _SESSION_TTL_SECONDS", - "start_line": 57, - "end_line": 58, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "SessionState", - "display_name": "method SessionState.is_expired", - "component_id": "codewiki/mcp/session.py::SessionState.is_expired", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/session.py::SessionStore": { - "id": "codewiki/mcp/session.py::SessionStore", - "name": "SessionStore", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/session.py", - "relative_path": "codewiki/mcp/session.py", - "depends_on": [], - "source_code": "class SessionStore:\n \"\"\"In-memory store for all active MCP sessions (thread-safe).\"\"\"\n\n def __init__(self) -> None:\n self._sessions: Dict[str, SessionState] = {}\n self._lock = threading.Lock()\n\n def create(\n self,\n repo_path: str,\n output_dir: str,\n components: Dict[str, Node],\n leaf_nodes: List[str],\n workspace: Optional[SessionWorkspace] = None,\n ) -> SessionState:\n \"\"\"Create a new session and return it.\"\"\"\n with self._lock:\n self._purge_expired_locked()\n # Evict oldest if at capacity\n if len(self._sessions) >= _MAX_SESSIONS:\n oldest_id = min(\n self._sessions,\n key=lambda sid: self._sessions[sid].last_accessed,\n )\n evicted = self._sessions[oldest_id]\n if evicted.workspace is not None:\n evicted.workspace.cleanup()\n del self._sessions[oldest_id]\n session_id = uuid.uuid4().hex[:12]\n # Ensure no collision\n while session_id in self._sessions:\n session_id = uuid.uuid4().hex[:12]\n state = SessionState(\n session_id=session_id,\n repo_path=repo_path,\n output_dir=output_dir,\n components=components,\n leaf_nodes=leaf_nodes,\n workspace=workspace,\n )\n self._sessions[session_id] = state\n return state\n\n def get(self, session_id: str) -> Optional[SessionState]:\n \"\"\"Return the session or ``None`` if not found / expired.\"\"\"\n with self._lock:\n state = self._sessions.get(session_id)\n if state is None:\n return None\n if state.is_expired:\n if state.workspace is not None:\n state.workspace.cleanup()\n del self._sessions[session_id]\n return None\n state.touch()\n return state\n\n def remove(self, session_id: str) -> bool:\n \"\"\"Remove a session. Returns True if it existed.\"\"\"\n with self._lock:\n return self._sessions.pop(session_id, None) is not None\n\n def _purge_expired_locked(self) -> None:\n \"\"\"Remove all expired sessions. Caller must hold _lock.\"\"\"\n expired = [sid for sid, s in self._sessions.items() if s.is_expired]\n for sid in expired:\n state = self._sessions[sid]\n if state.workspace is not None:\n state.workspace.cleanup()\n del self._sessions[sid]", - "start_line": 61, - "end_line": 130, - "has_docstring": true, - "docstring": "In-memory store for all active MCP sessions (thread-safe).", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class SessionStore", - "component_id": "codewiki/mcp/session.py::SessionStore", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/session.py::SessionStore.__init__": { - "id": "codewiki/mcp/session.py::SessionStore.__init__", - "name": "SessionStore.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/session.py", - "relative_path": "codewiki/mcp/session.py", - "depends_on": [], - "source_code": " def __init__(self) -> None:\n self._sessions: Dict[str, SessionState] = {}\n self._lock = threading.Lock()", - "start_line": 64, - "end_line": 66, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "SessionStore", - "display_name": "method SessionStore.__init__", - "component_id": "codewiki/mcp/session.py::SessionStore.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/session.py::SessionStore.create": { - "id": "codewiki/mcp/session.py::SessionStore.create", - "name": "SessionStore.create", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/session.py", - "relative_path": "codewiki/mcp/session.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore._purge_expired_locked", - "codewiki/mcp/workspace.py::SessionWorkspace.cleanup", - "codewiki/mcp/session.py::SessionState" - ], - "source_code": " def create(\n self,\n repo_path: str,\n output_dir: str,\n components: Dict[str, Node],\n leaf_nodes: List[str],\n workspace: Optional[SessionWorkspace] = None,\n ) -> SessionState:\n \"\"\"Create a new session and return it.\"\"\"\n with self._lock:\n self._purge_expired_locked()\n # Evict oldest if at capacity\n if len(self._sessions) >= _MAX_SESSIONS:\n oldest_id = min(\n self._sessions,\n key=lambda sid: self._sessions[sid].last_accessed,\n )\n evicted = self._sessions[oldest_id]\n if evicted.workspace is not None:\n evicted.workspace.cleanup()\n del self._sessions[oldest_id]\n session_id = uuid.uuid4().hex[:12]\n # Ensure no collision\n while session_id in self._sessions:\n session_id = uuid.uuid4().hex[:12]\n state = SessionState(\n session_id=session_id,\n repo_path=repo_path,\n output_dir=output_dir,\n components=components,\n leaf_nodes=leaf_nodes,\n workspace=workspace,\n )\n self._sessions[session_id] = state\n return state", - "start_line": 68, - "end_line": 102, - "has_docstring": true, - "docstring": "Create a new session and return it.", - "parameters": [ - "self", - "repo_path", - "output_dir", - "components", - "leaf_nodes", - "workspace" - ], - "node_type": "method", - "base_classes": null, - "class_name": "SessionStore", - "display_name": "method SessionStore.create", - "component_id": "codewiki/mcp/session.py::SessionStore.create", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/session.py::SessionStore.get": { - "id": "codewiki/mcp/session.py::SessionStore.get", - "name": "SessionStore.get", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/session.py", - "relative_path": "codewiki/mcp/session.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/mcp/workspace.py::SessionWorkspace.cleanup", - "codewiki/mcp/session.py::SessionState.touch" - ], - "source_code": " def get(self, session_id: str) -> Optional[SessionState]:\n \"\"\"Return the session or ``None`` if not found / expired.\"\"\"\n with self._lock:\n state = self._sessions.get(session_id)\n if state is None:\n return None\n if state.is_expired:\n if state.workspace is not None:\n state.workspace.cleanup()\n del self._sessions[session_id]\n return None\n state.touch()\n return state", - "start_line": 104, - "end_line": 116, - "has_docstring": true, - "docstring": "Return the session or ``None`` if not found / expired.", - "parameters": [ - "self", - "session_id" - ], - "node_type": "method", - "base_classes": null, - "class_name": "SessionStore", - "display_name": "method SessionStore.get", - "component_id": "codewiki/mcp/session.py::SessionStore.get", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/session.py::SessionStore.remove": { - "id": "codewiki/mcp/session.py::SessionStore.remove", - "name": "SessionStore.remove", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/session.py", - "relative_path": "codewiki/mcp/session.py", - "depends_on": [], - "source_code": " def remove(self, session_id: str) -> bool:\n \"\"\"Remove a session. Returns True if it existed.\"\"\"\n with self._lock:\n return self._sessions.pop(session_id, None) is not None", - "start_line": 118, - "end_line": 121, - "has_docstring": true, - "docstring": "Remove a session. Returns True if it existed.", - "parameters": [ - "self", - "session_id" - ], - "node_type": "method", - "base_classes": null, - "class_name": "SessionStore", - "display_name": "method SessionStore.remove", - "component_id": "codewiki/mcp/session.py::SessionStore.remove", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/session.py::SessionStore._purge_expired_locked": { - "id": "codewiki/mcp/session.py::SessionStore._purge_expired_locked", - "name": "SessionStore._purge_expired_locked", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/session.py", - "relative_path": "codewiki/mcp/session.py", - "depends_on": [ - "codewiki/mcp/workspace.py::SessionWorkspace.cleanup" - ], - "source_code": " def _purge_expired_locked(self) -> None:\n \"\"\"Remove all expired sessions. Caller must hold _lock.\"\"\"\n expired = [sid for sid, s in self._sessions.items() if s.is_expired]\n for sid in expired:\n state = self._sessions[sid]\n if state.workspace is not None:\n state.workspace.cleanup()\n del self._sessions[sid]", - "start_line": 123, - "end_line": 130, - "has_docstring": true, - "docstring": "Remove all expired sessions. Caller must hold _lock.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "SessionStore", - "display_name": "method SessionStore._purge_expired_locked", - "component_id": "codewiki/mcp/session.py::SessionStore._purge_expired_locked", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/tools/analysis.py::_detect_changes": { - "id": "codewiki/mcp/tools/analysis.py::_detect_changes", - "name": "_detect_changes", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/tools/analysis.py", - "relative_path": "codewiki/mcp/tools/analysis.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/mcp/tools/analysis.py::_detect_via_mtime", - "codewiki/mcp/tools/analysis.py::_find_affected_modules", - "codewiki/mcp/tools/analysis.py::_detect_via_git" - ], - "source_code": "def _detect_changes(\n repo_path: Path,\n output_dir: Path,\n) -> Optional[Dict[str, Any]]:\n \"\"\"Detect changes since last documentation generation.\n\n Returns a changes dict with affected modules, or None if no previous\n generation exists (first run).\n\n Detection strategy:\n 1. Git-based: compare stored commit_id with current HEAD, plus check\n uncommitted changes via ``git status``.\n 2. Fallback: compare file mtime with stored ``timestamp`` in metadata.\n \"\"\"\n metadata_path = output_dir / \"metadata.json\"\n module_tree_path = output_dir / \"module_tree.json\"\n\n if not metadata_path.exists() or not module_tree_path.exists():\n return None\n\n try:\n metadata = json.loads(metadata_path.read_text(encoding=\"utf-8\"))\n module_tree = json.loads(module_tree_path.read_text(encoding=\"utf-8\"))\n except (json.JSONDecodeError, OSError, UnicodeDecodeError):\n return None\n\n # Try git-based detection first\n changes = _detect_via_git(repo_path, metadata, output_dir)\n\n # Fallback to mtime-based detection\n if changes is None:\n changes = _detect_via_mtime(repo_path, metadata)\n\n if changes is None:\n return None\n\n changed_files = changes[\"changed_files\"]\n if not changed_files:\n return {\n \"has_previous\": True,\n \"no_changes\": True,\n \"method\": changes.get(\"method\", \"unknown\"),\n \"message\": \"No changes detected since last generation. Documentation is up to date.\",\n }\n\n affected, cascade = _find_affected_modules(module_tree, changed_files)\n\n return {\n \"has_previous\": True,\n \"no_changes\": False,\n \"method\": changes.get(\"method\", \"unknown\"),\n \"changed_files\": changed_files,\n \"affected_modules\": sorted(affected),\n \"cascade_modules\": sorted(cascade),\n \"hint\": (\n f\"Only {len(affected)} module(s) need updating: {sorted(affected)}. \"\n f\"Parent modules to refresh: {sorted(cascade)}. \"\n \"Use edit_doc_file for targeted updates, write_doc_file for new modules.\"\n ),\n }", - "start_line": 28, - "end_line": 87, - "has_docstring": true, - "docstring": "Detect changes since last documentation generation.\n\nReturns a changes dict with affected modules, or None if no previous\ngeneration exists (first run).\n\nDetection strategy:\n 1. Git-based: compare stored commit_id with current HEAD, plus check\n uncommitted changes via ``git status``.\n 2. Fallback: compare file mtime with stored ``timestamp`` in metadata.", - "parameters": [ - "repo_path", - "output_dir" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _detect_changes", - "component_id": "codewiki/mcp/tools/analysis.py::_detect_changes", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/tools/analysis.py::_detect_via_git": { - "id": "codewiki/mcp/tools/analysis.py::_detect_via_git", - "name": "_detect_via_git", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/tools/analysis.py", - "relative_path": "codewiki/mcp/tools/analysis.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve" - ], - "source_code": "def _detect_via_git(\n repo_path: Path,\n metadata: Dict[str, Any],\n output_dir: Path | None = None,\n) -> Optional[Dict[str, Any]]:\n \"\"\"Detect changes via git. Returns None if not in a git repo or if no\n previous commit is recorded (so the caller can fall through to mtime).\n\n Checks committed changes (diff against stored commit_id), staged changes\n (``index.diff('HEAD')``), and unstaged/untracked changes.\n \"\"\"\n try:\n import git\n repo = git.Repo(repo_path, search_parent_directories=True)\n except Exception:\n return None\n\n prev_commit = metadata.get(\"generation_info\", {}).get(\"commit_id\")\n if not prev_commit:\n return None # No baseline to compare; let mtime fallback handle it\n\n try:\n current_commit = repo.head.commit.hexsha\n except Exception:\n return None\n\n # Compute subpath prefix for monorepo support.\n # Git diff returns paths relative to the git root, but component IDs\n # use paths relative to repo_path. Strip the prefix so they align.\n git_root = Path(repo.working_dir).resolve()\n repo_root = repo_path.resolve()\n try:\n subpath = repo_root.relative_to(git_root).as_posix()\n except ValueError:\n subpath = \"\"\n if subpath == \".\":\n subpath = \"\"\n\n # Output-dir prefix (relative to repo_path) so generated docs, metadata\n # and session workspace files never count as source changes.\n output_dir_rel = \"\"\n if output_dir is not None:\n try:\n output_dir_rel = Path(output_dir).resolve().relative_to(repo_root).as_posix()\n if output_dir_rel == \".\":\n output_dir_rel = \"\"\n except (ValueError, TypeError):\n pass\n\n def _normalize(p: str) -> Optional[str]:\n \"\"\"Strip the monorepo subpath and drop generated/non-source paths.\"\"\"\n if subpath:\n if not p.startswith(subpath + \"/\"):\n return None # outside target subdirectory\n p = p[len(subpath) + 1:]\n if p.startswith(\".codewiki/\"):\n return None\n if output_dir_rel and (p == output_dir_rel or p.startswith(output_dir_rel + \"/\")):\n return None\n return p\n\n changed: list[str] = []\n seen: set[str] = set()\n\n def _add(raw: Optional[str]) -> None:\n if raw:\n p = _normalize(raw)\n if p and p not in seen:\n changed.append(p)\n seen.add(p)\n\n # 1) Committed changes since last generation\n if prev_commit != current_commit:\n try:\n diff_index = repo.commit(prev_commit).diff(current_commit)\n except Exception:\n # Baseline commit unreachable (shallow clone, rebase, gc).\n # Committed changes can't be enumerated, and returning an empty\n # list here would falsely report \"up to date\" on a clean tree β€”\n # fall back to mtime detection instead.\n logger.warning(\n \"Stored commit %s is unreachable in %s; falling back to mtime detection\",\n prev_commit, repo_path,\n )\n return None\n for diff in diff_index:\n for p in (diff.a_path, diff.b_path):\n _add(p)\n\n # 2) Uncommitted changes: staged (index vs HEAD) + unstaged (working tree vs index) + untracked\n try:\n for d in list(repo.index.diff(\"HEAD\")) + list(repo.index.diff(None)):\n _add(d.a_path)\n _add(d.b_path)\n for item in repo.untracked_files:\n _add(item)\n except Exception:\n pass\n\n return {\"changed_files\": changed, \"method\": \"git\"}", - "start_line": 90, - "end_line": 189, - "has_docstring": true, - "docstring": "Detect changes via git. Returns None if not in a git repo or if no\nprevious commit is recorded (so the caller can fall through to mtime).\n\nChecks committed changes (diff against stored commit_id), staged changes\n(``index.diff('HEAD')``), and unstaged/untracked changes.", - "parameters": [ - "repo_path", - "metadata", - "output_dir" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _detect_via_git", - "component_id": "codewiki/mcp/tools/analysis.py::_detect_via_git", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/tools/analysis.py::_detect_via_mtime": { - "id": "codewiki/mcp/tools/analysis.py::_detect_via_mtime", - "name": "_detect_via_mtime", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/tools/analysis.py", - "relative_path": "codewiki/mcp/tools/analysis.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": "def _detect_via_mtime(\n repo_path: Path,\n metadata: Dict[str, Any],\n) -> Optional[Dict[str, Any]]:\n \"\"\"Fallback: detect changed files by comparing mtime with generation timestamp.\"\"\"\n timestamp_str = metadata.get(\"generation_info\", {}).get(\"timestamp\")\n if not timestamp_str:\n return None\n\n try:\n from datetime import datetime\n prev_time = datetime.fromisoformat(timestamp_str).timestamp()\n except (ValueError, TypeError):\n return None\n\n # Language extensions recognized by CodeWiki\n source_extensions = {\n \".py\", \".java\", \".js\", \".jsx\", \".ts\", \".tsx\",\n \".c\", \".h\", \".cpp\", \".hpp\", \".cc\", \".hh\",\n \".cs\", \".kt\", \".kts\",\n }\n\n changed: list[str] = []\n for dirpath, dirnames, filenames in os.walk(repo_path):\n # Skip hidden dirs and common non-source dirs\n dirnames[:] = [\n d for d in dirnames\n if not d.startswith(\".\") and d not in (\"node_modules\", \"__pycache__\", \"venv\", \".venv\")\n ]\n for filename in filenames:\n filepath = Path(dirpath) / filename\n if filepath.suffix.lower() not in source_extensions:\n continue\n try:\n if filepath.stat().st_mtime > prev_time:\n rel_path = filepath.relative_to(repo_path).as_posix()\n changed.append(rel_path)\n except OSError:\n continue\n\n return {\"changed_files\": changed, \"method\": \"mtime\"}", - "start_line": 192, - "end_line": 232, - "has_docstring": true, - "docstring": "Fallback: detect changed files by comparing mtime with generation timestamp.", - "parameters": [ - "repo_path", - "metadata" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _detect_via_mtime", - "component_id": "codewiki/mcp/tools/analysis.py::_detect_via_mtime", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/tools/analysis.py::_find_affected_modules": { - "id": "codewiki/mcp/tools/analysis.py::_find_affected_modules", - "name": "_find_affected_modules", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/tools/analysis.py", - "relative_path": "codewiki/mcp/tools/analysis.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/cli/utils/progress.py::ModuleProgressBar.update" - ], - "source_code": "def _find_affected_modules(\n module_tree: Dict[str, Any],\n changed_files: List[str],\n) -> Tuple[set, set]:\n \"\"\"Map changed files to affected modules using module_tree.json.\n\n Uses substring matching (same as the CLI ``_invalidate_affected_modules``).\n Returns (affected_modules, cascade_parent_modules).\n \"\"\"\n affected: set[str] = set()\n cascade: set[str] = set()\n\n def _walk(tree: Dict, parents: list[str] | None = None):\n if parents is None:\n parents = []\n for mod_name, mod_info in tree.items():\n components = mod_info.get(\"components\", [])\n hit = False\n for comp in components:\n comp_file = comp.split(\"::\")[0]\n for cf in changed_files:\n if comp_file == cf or comp_file.endswith(\"/\" + cf) or cf.endswith(\"/\" + comp_file):\n hit = True\n break\n # Changed dir contains the component file, or vice versa\n if cf.startswith(comp_file + \"/\") or comp_file.startswith(cf + \"/\"):\n hit = True\n break\n if hit:\n break\n if hit:\n affected.add(mod_name)\n cascade.update(parents)\n\n children = mod_info.get(\"children\", {})\n if isinstance(children, dict) and children:\n _walk(children, parents + [mod_name])\n\n _walk(module_tree)\n\n # overview.md depends on all child docs, always refresh if anything changed\n if affected:\n cascade.add(\"overview\")\n\n return affected, cascade", - "start_line": 235, - "end_line": 279, - "has_docstring": true, - "docstring": "Map changed files to affected modules using module_tree.json.\n\nUses substring matching (same as the CLI ``_invalidate_affected_modules``).\nReturns (affected_modules, cascade_parent_modules).", - "parameters": [ - "module_tree", - "changed_files" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _find_affected_modules", - "component_id": "codewiki/mcp/tools/analysis.py::_find_affected_modules", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/tools/analysis.py::handle_analyze_repo": { - "id": "codewiki/mcp/tools/analysis.py::handle_analyze_repo", - "name": "handle_analyze_repo", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/tools/analysis.py", - "relative_path": "codewiki/mcp/tools/analysis.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/cli/utils/repo_validator.py::get_git_commit_hash", - "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py::DependencyGraphBuilder.build_dependency_graph", - "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py::DependencyGraphBuilder", - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/mcp/session.py::SessionStore.create", - "codewiki/mcp/tools/analysis.py::_detect_changes", - "codewiki/mcp/workspace.py::SessionWorkspace", - "codewiki/mcp/workspace.py::SessionWorkspace.write_json", - "codewiki/src/config.py::Config" - ], - "source_code": "def handle_analyze_repo(\n arguments: Dict[str, Any],\n store: SessionStore,\n) -> str:\n \"\"\"Run the dependency analysis, write results to workspace files,\n and return a compact summary with file paths.\"\"\"\n repo_path = Path(arguments[\"repo_path\"]).expanduser().resolve()\n if not repo_path.exists():\n return json.dumps({\"error\": f\"Repository not found: {repo_path}\"})\n\n output_dir = Path(arguments.get(\"output_dir\", str(repo_path / \"docs\"))).expanduser().resolve()\n output_dir.mkdir(parents=True, exist_ok=True)\n\n # Build a minimal Config for the dependency analyzer (no LLM fields used)\n from codewiki.src.config import Config\n config = Config(\n repo_path=str(repo_path),\n output_dir=str(output_dir / \"temp\"),\n dependency_graph_dir=str(output_dir / \"temp\" / \"dependency_graphs\"),\n docs_dir=str(output_dir),\n max_depth=2,\n llm_base_url=\"not-needed\",\n llm_api_key=\"not-needed\",\n main_model=\"unused\",\n cluster_model=\"unused\",\n use_gitignore=arguments.get(\"use_gitignore\", True),\n )\n\n # Apply optional include/exclude patterns\n include = arguments.get(\"include_patterns\")\n exclude = arguments.get(\"exclude_patterns\")\n if include or exclude:\n agent_instructions: Dict[str, Any] = {}\n if include:\n agent_instructions[\"include_patterns\"] = [p.strip() for p in include.split(\",\")]\n if exclude:\n agent_instructions[\"exclude_patterns\"] = [p.strip() for p in exclude.split(\",\")]\n config.agent_instructions = agent_instructions\n\n from codewiki.src.be.dependency_analyzer import DependencyGraphBuilder\n builder = DependencyGraphBuilder(config)\n components, leaf_nodes = builder.build_dependency_graph()\n\n # Create the session (generates session_id)\n session = store.create(\n repo_path=str(repo_path),\n output_dir=str(output_dir),\n components=components,\n leaf_nodes=leaf_nodes,\n )\n\n # Record the analyzed commit now β€” close_session uses it as the\n # incremental-update baseline in metadata.json.\n from codewiki.cli.utils.repo_validator import get_git_commit_hash\n session.analyzed_commit = get_git_commit_hash(repo_path) or None\n\n # Create the workspace with the real session_id\n workspace = SessionWorkspace(repo_path, session.session_id)\n session.workspace = workspace\n\n # -- Write full data to workspace files --\n\n # 1. Full component index (no pagination)\n component_index: list[dict] = []\n for comp_id, node in components.items():\n component_index.append({\n \"id\": comp_id,\n \"type\": getattr(node, \"component_type\", \"unknown\"),\n \"file\": getattr(node, \"relative_path\", \"\"),\n })\n workspace.write_json(\"component_index.json\", component_index)\n\n # 2. Full leaf nodes list\n workspace.write_json(\"leaf_nodes.json\", leaf_nodes)\n\n # 3. Language stats\n languages: Dict[str, int] = {}\n for node in components.values():\n lang = getattr(node, \"language\", \"unknown\")\n languages[lang] = languages.get(lang, 0) + 1\n workspace.write_json(\"languages.json\", languages)\n\n # 4. Incremental update: detect changes since last generation\n changes = _detect_changes(repo_path, output_dir)\n if changes is not None:\n workspace.write_json(\"changes.json\", changes)\n\n # 5. Summary with preview for quick reference\n summary = {\n \"session_id\": session.session_id,\n \"repo_name\": repo_path.name,\n \"repo_path\": str(repo_path),\n \"output_dir\": str(output_dir),\n \"total_components\": len(components),\n \"total_leaf_nodes\": len(leaf_nodes),\n \"languages\": languages,\n \"leaf_nodes_preview\": leaf_nodes[:20],\n }\n workspace.write_json(\"summary.json\", summary)\n\n # -- Return compact MCP response --\n result = {\n \"session_id\": session.session_id,\n \"workspace_dir\": str(workspace.root),\n \"repo_name\": repo_path.name,\n \"output_dir\": str(output_dir),\n \"stats\": {\n \"total_components\": len(components),\n \"total_leaf_nodes\": len(leaf_nodes),\n \"languages\": languages,\n },\n \"files\": {\n \"component_index\": str(workspace.root / \"component_index.json\"),\n \"leaf_nodes\": str(workspace.root / \"leaf_nodes.json\"),\n \"languages\": str(workspace.root / \"languages.json\"),\n \"summary\": str(workspace.root / \"summary.json\"),\n },\n \"changes\": changes,\n \"hint\": (\n \"Read the files above for full data. \"\n \"Use read_code_components(session_id, component_ids) to read source code. \"\n \"Use save_module_tree(session_id, module_tree) after clustering. \"\n \"Call get_prompt('cluster') for clustering rules.\"\n ),\n }\n if changes and not changes.get(\"no_changes\"):\n result[\"hint\"] = (\n \"Incremental update detected. Only update affected modules listed in \"\n \"'changes.affected_modules'. Use edit_doc_file for targeted updates. \"\n \"Refresh cascade parent modules in 'changes.cascade_modules'.\"\n )\n return json.dumps(result, indent=2, ensure_ascii=False)", - "start_line": 282, - "end_line": 413, - "has_docstring": true, - "docstring": "Run the dependency analysis, write results to workspace files,\nand return a compact summary with file paths.", - "parameters": [ - "arguments", - "store" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function handle_analyze_repo", - "component_id": "codewiki/mcp/tools/analysis.py::handle_analyze_repo", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/tools/code_reader.py::handle_read_code_components": { - "id": "codewiki/mcp/tools/code_reader.py::handle_read_code_components", - "name": "handle_read_code_components", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/tools/code_reader.py", - "relative_path": "codewiki/mcp/tools/code_reader.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/mcp/workspace.py::SessionWorkspace.write_component_source" - ], - "source_code": "def handle_read_code_components(\n arguments: Dict[str, Any],\n store: SessionStore,\n) -> str:\n \"\"\"Write the source code for given component IDs to workspace files.\n\n Returns a compact JSON with file paths β€” no source code inline.\n \"\"\"\n session_id = arguments[\"session_id\"]\n session = store.get(session_id)\n if session is None:\n return json.dumps({\"error\": f\"Session {session_id} not found or expired.\"})\n\n if session.workspace is None:\n return json.dumps({\"error\": \"Session workspace not initialized.\"})\n\n component_ids: List[str] = arguments[\"component_ids\"]\n components = session.components\n workspace = session.workspace\n\n written_files: Dict[str, str] = {} # filename -> component_id\n not_found: List[str] = []\n\n for cid in component_ids:\n node = components.get(cid)\n if node is None:\n not_found.append(cid)\n continue\n lang = getattr(node, \"language\", \"\")\n source = (getattr(node, \"source_code\", None) or \"\").strip()\n file_path = workspace.write_component_source(cid, source, lang)\n written_files[file_path.name] = cid\n\n result = {\n \"written\": len(written_files),\n \"not_found_count\": len(not_found),\n \"not_found\": not_found,\n \"source_dir\": str(workspace.root / \"sources\"),\n \"files\": written_files,\n }\n return json.dumps(result, indent=2, ensure_ascii=False)", - "start_line": 21, - "end_line": 61, - "has_docstring": true, - "docstring": "Write the source code for given component IDs to workspace files.\n\nReturns a compact JSON with file paths β€” no source code inline.", - "parameters": [ - "arguments", - "store" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function handle_read_code_components", - "component_id": "codewiki/mcp/tools/code_reader.py::handle_read_code_components", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/tools/doc_writer.py::_is_within": { - "id": "codewiki/mcp/tools/doc_writer.py::_is_within", - "name": "_is_within", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/tools/doc_writer.py", - "relative_path": "codewiki/mcp/tools/doc_writer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve" - ], - "source_code": "def _is_within(path: Path, base: Path) -> bool:\n \"\"\"Return True if *path* resolves to somewhere inside *base*.\"\"\"\n try:\n path.resolve().relative_to(base.resolve())\n return True\n except ValueError:\n return False", - "start_line": 23, - "end_line": 29, - "has_docstring": true, - "docstring": "Return True if *path* resolves to somewhere inside *base*.", - "parameters": [ - "path", - "base" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _is_within", - "component_id": "codewiki/mcp/tools/doc_writer.py::_is_within", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/tools/doc_writer.py::_safe_doc_path": { - "id": "codewiki/mcp/tools/doc_writer.py::_safe_doc_path", - "name": "_safe_doc_path", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/tools/doc_writer.py", - "relative_path": "codewiki/mcp/tools/doc_writer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/mcp/tools/doc_writer.py::_is_within" - ], - "source_code": "def _safe_doc_path(session: SessionState, filename: str) -> Path | None:\n \"\"\"Resolve *filename* within session.output_dir, guarding against traversal.\"\"\"\n if not filename.endswith(\".md\"):\n filename += \".md\"\n output_base = Path(session.output_dir).resolve()\n doc_path = (output_base / filename).resolve()\n if not _is_within(doc_path, output_base):\n return None\n return doc_path", - "start_line": 32, - "end_line": 40, - "has_docstring": true, - "docstring": "Resolve *filename* within session.output_dir, guarding against traversal.", - "parameters": [ - "session", - "filename" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _safe_doc_path", - "component_id": "codewiki/mcp/tools/doc_writer.py::_safe_doc_path", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/tools/doc_writer.py::_ensure_parent_dirs": { - "id": "codewiki/mcp/tools/doc_writer.py::_ensure_parent_dirs", - "name": "_ensure_parent_dirs", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/tools/doc_writer.py", - "relative_path": "codewiki/mcp/tools/doc_writer.py", - "depends_on": [], - "source_code": "def _ensure_parent_dirs(path: Path) -> None:\n \"\"\"Create parent directories if they don't exist.\"\"\"\n path.parent.mkdir(parents=True, exist_ok=True)", - "start_line": 43, - "end_line": 45, - "has_docstring": true, - "docstring": "Create parent directories if they don't exist.", - "parameters": [ - "path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _ensure_parent_dirs", - "component_id": "codewiki/mcp/tools/doc_writer.py::_ensure_parent_dirs", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/tools/doc_writer.py::_validate_mermaid": { - "id": "codewiki/mcp/tools/doc_writer.py::_validate_mermaid", - "name": "_validate_mermaid", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/tools/doc_writer.py", - "relative_path": "codewiki/mcp/tools/doc_writer.py", - "depends_on": [ - "codewiki/src/be/utils.py::validate_mermaid_diagrams" - ], - "source_code": "async def _validate_mermaid(file_path: str, relative_path: str) -> str:\n \"\"\"Run Mermaid validation and return the result string.\"\"\"\n try:\n from codewiki.src.be.utils import validate_mermaid_diagrams\n return await validate_mermaid_diagrams(file_path, relative_path)\n except Exception as e:\n return f\"Mermaid validation skipped: {e}\"", - "start_line": 48, - "end_line": 54, - "has_docstring": true, - "docstring": "Run Mermaid validation and return the result string.", - "parameters": [ - "file_path", - "relative_path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _validate_mermaid", - "component_id": "codewiki/mcp/tools/doc_writer.py::_validate_mermaid", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/tools/doc_writer.py::_save_history": { - "id": "codewiki/mcp/tools/doc_writer.py::_save_history", - "name": "_save_history", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/tools/doc_writer.py", - "relative_path": "codewiki/mcp/tools/doc_writer.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": "def _save_history(session: SessionState, doc_path: Path, content: str) -> None:\n \"\"\"Append *content* to edit history for *doc_path*, capped at _MAX_HISTORY_PER_FILE.\"\"\"\n history = session.registry.get(\"file_history\")\n if history is None:\n history = {}\n elif isinstance(history, str):\n history = json.loads(history)\n key = str(doc_path)\n entry = history.setdefault(key, [])\n entry.append(content)\n # Trim to last N entries\n if len(entry) > _MAX_HISTORY_PER_FILE:\n del entry[: len(entry) - _MAX_HISTORY_PER_FILE]\n session.registry[\"file_history\"] = history # keep as native dict", - "start_line": 57, - "end_line": 70, - "has_docstring": true, - "docstring": "Append *content* to edit history for *doc_path*, capped at _MAX_HISTORY_PER_FILE.", - "parameters": [ - "session", - "doc_path", - "content" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _save_history", - "component_id": "codewiki/mcp/tools/doc_writer.py::_save_history", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/tools/doc_writer.py::handle_write_doc_file": { - "id": "codewiki/mcp/tools/doc_writer.py::handle_write_doc_file", - "name": "handle_write_doc_file", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/tools/doc_writer.py", - "relative_path": "codewiki/mcp/tools/doc_writer.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/mcp/tools/doc_writer.py::_safe_doc_path", - "codewiki/mcp/tools/doc_writer.py::_validate_mermaid" - ], - "source_code": "async def handle_write_doc_file(\n arguments: Dict[str, Any],\n store: SessionStore,\n) -> str:\n \"\"\"Create a new documentation file in the output directory.\"\"\"\n session_id = arguments[\"session_id\"]\n session = store.get(session_id)\n if session is None:\n return json.dumps({\"error\": f\"Session {session_id} not found or expired.\"})\n\n filename = arguments[\"filename\"]\n doc_path = _safe_doc_path(session, filename)\n if doc_path is None:\n return json.dumps({\"error\": \"Filename escapes output directory.\"})\n\n content = arguments[\"content\"]\n\n await asyncio.to_thread(_ensure_parent_dirs, doc_path)\n\n if await asyncio.to_thread(doc_path.exists):\n return json.dumps({\n \"error\": f\"File already exists: {filename}. Use edit_doc_file to modify it.\"\n })\n\n await asyncio.to_thread(doc_path.write_text, content, \"utf-8\")\n session.docs_written += 1\n\n # Mermaid validation\n mermaid_result = await _validate_mermaid(str(doc_path), filename)\n\n result = {\n \"status\": \"created\",\n \"path\": str(doc_path),\n \"filename\": filename,\n \"lines\": content.count(\"\\n\") + 1,\n \"mermaid_validation\": mermaid_result,\n }\n return json.dumps(result, indent=2, ensure_ascii=False)", - "start_line": 73, - "end_line": 110, - "has_docstring": true, - "docstring": "Create a new documentation file in the output directory.", - "parameters": [ - "arguments", - "store" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function handle_write_doc_file", - "component_id": "codewiki/mcp/tools/doc_writer.py::handle_write_doc_file", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/tools/doc_writer.py::handle_edit_doc_file": { - "id": "codewiki/mcp/tools/doc_writer.py::handle_edit_doc_file", - "name": "handle_edit_doc_file", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/tools/doc_writer.py", - "relative_path": "codewiki/mcp/tools/doc_writer.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/mcp/tools/doc_writer.py::_save_history", - "codewiki/mcp/tools/doc_writer.py::_safe_doc_path", - "codewiki/mcp/tools/doc_writer.py::_validate_mermaid" - ], - "source_code": "async def handle_edit_doc_file(\n arguments: Dict[str, Any],\n store: SessionStore,\n) -> str:\n \"\"\"Edit an existing documentation file (str_replace, insert, or undo).\"\"\"\n session_id = arguments[\"session_id\"]\n session = store.get(session_id)\n if session is None:\n return json.dumps({\"error\": f\"Session {session_id} not found or expired.\"})\n\n filename = arguments[\"filename\"]\n doc_path = _safe_doc_path(session, filename)\n if doc_path is None:\n return json.dumps({\"error\": \"Filename escapes output directory.\"})\n\n command = arguments[\"command\"]\n\n if command == \"undo\":\n # Undo via registry history\n history = session.registry.get(\"file_history\", {})\n if isinstance(history, str):\n history = json.loads(history)\n path_history = history.get(str(doc_path), [])\n if not path_history:\n return json.dumps({\"error\": f\"No edit history found for {filename}.\"})\n old_content = path_history.pop()\n history[str(doc_path)] = path_history\n session.registry[\"file_history\"] = history\n await asyncio.to_thread(doc_path.write_text, old_content, \"utf-8\")\n\n # Validate Mermaid after undo\n mermaid_result = await _validate_mermaid(str(doc_path), filename)\n return json.dumps({\n \"status\": \"undone\",\n \"filename\": filename,\n \"mermaid_validation\": mermaid_result,\n }, ensure_ascii=False)\n\n if not await asyncio.to_thread(doc_path.exists):\n return json.dumps({\"error\": f\"File not found: {filename}. Use write_doc_file to create it.\"})\n\n current_content = await asyncio.to_thread(doc_path.read_text, \"utf-8\")\n\n if command == \"str_replace\":\n old_str = arguments.get(\"old_str\")\n new_str = arguments.get(\"new_str\", \"\")\n if old_str is None:\n return json.dumps({\"error\": \"old_str is required for str_replace.\"})\n\n occurrences = current_content.count(old_str)\n if occurrences == 0:\n return json.dumps({\"error\": f\"old_str not found in {filename}.\"})\n if occurrences > 1:\n return json.dumps({\"error\": f\"old_str appears {occurrences} times in {filename}. Make it unique.\"})\n\n new_content = current_content.replace(old_str, new_str, 1)\n # Save history only for edits that actually happen, so undo never\n # pops a no-op entry left behind by a failed/rejected command.\n _save_history(session, doc_path, current_content)\n await asyncio.to_thread(doc_path.write_text, new_content, \"utf-8\")\n\n # Snippet around the edit\n replacement_line = current_content.split(old_str)[0].count(\"\\n\")\n lines = new_content.split(\"\\n\")\n start = max(0, replacement_line - 4)\n end = min(len(lines), start + new_str.count(\"\\n\") + 9)\n snippet = \"\\n\".join(f\"{i + 1:6}\\t{lines[i]}\" for i in range(start, end))\n\n elif command == \"insert\":\n insert_line = arguments.get(\"insert_line\", 0)\n new_str = arguments.get(\"new_str\", \"\")\n if not new_str:\n return json.dumps({\"error\": \"new_str is required for insert.\"})\n\n lines = current_content.split(\"\\n\")\n insert_line = max(0, min(insert_line, len(lines)))\n new_str_lines = new_str.split(\"\\n\")\n lines = lines[:insert_line] + new_str_lines + lines[insert_line:]\n new_content = \"\\n\".join(lines)\n _save_history(session, doc_path, current_content)\n await asyncio.to_thread(doc_path.write_text, new_content, \"utf-8\")\n\n start = max(0, insert_line - 4)\n end = min(len(lines), start + len(new_str_lines) + 8)\n snippet = \"\\n\".join(f\"{i + 1:6}\\t{lines[i]}\" for i in range(start, end))\n\n else:\n return json.dumps({\"error\": f\"Unknown command: {command}. Use str_replace, insert, or undo.\"})\n\n session.docs_written += 1\n\n # Mermaid validation\n mermaid_result = await _validate_mermaid(str(doc_path), filename)\n\n result = {\n \"status\": \"edited\",\n \"command\": command,\n \"filename\": filename,\n \"snippet\": snippet,\n \"mermaid_validation\": mermaid_result,\n }\n return json.dumps(result, indent=2, ensure_ascii=False)", - "start_line": 113, - "end_line": 214, - "has_docstring": true, - "docstring": "Edit an existing documentation file (str_replace, insert, or undo).", - "parameters": [ - "arguments", - "store" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function handle_edit_doc_file", - "component_id": "codewiki/mcp/tools/doc_writer.py::handle_edit_doc_file", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/tools/module_tree.py::_get_processing_order": { - "id": "codewiki/mcp/tools/module_tree.py::_get_processing_order", - "name": "_get_processing_order", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/tools/module_tree.py", - "relative_path": "codewiki/mcp/tools/module_tree.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": "def _get_processing_order(module_tree: Dict[str, Any], parent_path: List[str] | None = None) -> List[Dict[str, Any]]:\n \"\"\"Compute leaf-first processing order from a module tree.\n\n Returns a list of dicts with module path, name, leaf status, and\n component/children info.\n \"\"\"\n if parent_path is None:\n parent_path = []\n order: List[Dict[str, Any]] = []\n\n def _collect(tree: Dict[str, Any], path: List[str]) -> None:\n for module_name, module_info in tree.items():\n current_path = path + [module_name]\n children = module_info.get(\"children\", {})\n has_children = isinstance(children, dict) and len(children) > 0\n\n if has_children:\n _collect(children, current_path)\n order.append({\n \"module\": module_name,\n \"path\": current_path,\n \"is_leaf\": False,\n \"children\": list(children.keys()),\n \"components\": module_info.get(\"components\", []),\n })\n else:\n order.append({\n \"module\": module_name,\n \"path\": current_path,\n \"is_leaf\": True,\n \"components\": module_info.get(\"components\", []),\n })\n\n _collect(module_tree, parent_path)\n return order", - "start_line": 22, - "end_line": 56, - "has_docstring": true, - "docstring": "Compute leaf-first processing order from a module tree.\n\nReturns a list of dicts with module path, name, leaf status, and\ncomponent/children info.", - "parameters": [ - "module_tree", - "parent_path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _get_processing_order", - "component_id": "codewiki/mcp/tools/module_tree.py::_get_processing_order", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/tools/module_tree.py::handle_save_module_tree": { - "id": "codewiki/mcp/tools/module_tree.py::handle_save_module_tree", - "name": "handle_save_module_tree", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/tools/module_tree.py", - "relative_path": "codewiki/mcp/tools/module_tree.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/mcp/workspace.py::SessionWorkspace.write_json", - "codewiki/mcp/tools/module_tree.py::_get_processing_order" - ], - "source_code": "def handle_save_module_tree(\n arguments: Dict[str, Any],\n store: SessionStore,\n) -> str:\n \"\"\"Persist the IDE agent's clustering result as the module tree.\"\"\"\n session_id = arguments[\"session_id\"]\n session = store.get(session_id)\n if session is None:\n return json.dumps({\"error\": f\"Session {session_id} not found or expired.\"})\n\n module_tree = arguments[\"module_tree\"]\n output_dir = session.output_dir\n\n # Save both immutable snapshot and mutable working copy\n first_path = os.path.join(output_dir, FIRST_MODULE_TREE_FILENAME)\n working_path = os.path.join(output_dir, MODULE_TREE_FILENAME)\n\n os.makedirs(output_dir, exist_ok=True)\n\n with open(first_path, \"w\", encoding=\"utf-8\") as f:\n json.dump(module_tree, f, indent=2, ensure_ascii=False)\n with open(working_path, \"w\", encoding=\"utf-8\") as f:\n json.dump(module_tree, f, indent=2, ensure_ascii=False)\n\n # Cache in session\n session.module_tree = module_tree\n\n # Compute processing order and write to workspace file\n order = _get_processing_order(module_tree)\n order_file = None\n if session.workspace is not None:\n order_path = session.workspace.write_json(\"processing_order.json\", order)\n order_file = str(order_path)\n\n result = {\n \"status\": \"saved\",\n \"module_count\": len(module_tree),\n \"tree_path\": working_path,\n \"first_tree_path\": first_path,\n \"processing_order_file\": order_file,\n \"hint\": (\n \"Read the processing_order.json file for the leaf-first generation order. \"\n \"Process leaf modules first (is_leaf=true), then parent modules. \"\n \"For each leaf module: get_prompt('system_leaf') + read_code_components + write_doc_file. \"\n \"For each parent module: get_prompt('overview_module') + write_doc_file.\"\n ),\n }\n return json.dumps(result, indent=2, ensure_ascii=False)", - "start_line": 59, - "end_line": 106, - "has_docstring": true, - "docstring": "Persist the IDE agent's clustering result as the module tree.", - "parameters": [ - "arguments", - "store" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function handle_save_module_tree", - "component_id": "codewiki/mcp/tools/module_tree.py::handle_save_module_tree", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/tools/module_tree.py::handle_get_processing_order": { - "id": "codewiki/mcp/tools/module_tree.py::handle_get_processing_order", - "name": "handle_get_processing_order", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/tools/module_tree.py", - "relative_path": "codewiki/mcp/tools/module_tree.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/mcp/workspace.py::SessionWorkspace.write_json", - "codewiki/mcp/tools/module_tree.py::_get_processing_order", - "codewiki/cli/config_manager.py::ConfigManager.load" - ], - "source_code": "def handle_get_processing_order(\n arguments: Dict[str, Any],\n store: SessionStore,\n) -> str:\n \"\"\"Write the leaf-first processing order to a workspace file and return its path.\"\"\"\n session_id = arguments[\"session_id\"]\n session = store.get(session_id)\n if session is None:\n return json.dumps({\"error\": f\"Session {session_id} not found or expired.\"})\n\n # Try session cache first, then disk\n module_tree = session.module_tree\n if not module_tree:\n tree_path = os.path.join(session.output_dir, MODULE_TREE_FILENAME)\n if os.path.exists(tree_path):\n with open(tree_path, encoding=\"utf-8\") as f:\n module_tree = json.load(f)\n session.module_tree = module_tree\n else:\n return json.dumps({\n \"error\": \"Module tree not found. Call save_module_tree first.\"\n })\n\n order = _get_processing_order(module_tree)\n\n # Write to workspace file\n order_file = None\n if session.workspace is not None:\n order_path = session.workspace.write_json(\"processing_order.json\", order)\n order_file = str(order_path)\n\n result = {\n \"session_id\": session_id,\n \"module_count\": len(module_tree),\n \"processing_order_file\": order_file,\n \"hint\": \"Read the processing_order.json file for the full leaf-first order.\",\n }\n return json.dumps(result, indent=2, ensure_ascii=False)", - "start_line": 109, - "end_line": 146, - "has_docstring": true, - "docstring": "Write the leaf-first processing order to a workspace file and return its path.", - "parameters": [ - "arguments", - "store" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function handle_get_processing_order", - "component_id": "codewiki/mcp/tools/module_tree.py::handle_get_processing_order", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/tools/prompt_server.py::handle_get_prompt": { - "id": "codewiki/mcp/tools/prompt_server.py::handle_get_prompt", - "name": "handle_get_prompt", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/tools/prompt_server.py", - "relative_path": "codewiki/mcp/tools/prompt_server.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/mcp/tools/prompt_server.py::_resolve_prompt" - ], - "source_code": "def handle_get_prompt(\n arguments: Dict[str, Any],\n store: SessionStore,\n) -> str:\n \"\"\"Return a prompt template, optionally with variables filled in.\"\"\"\n prompt_type = arguments[\"prompt_type\"]\n variables = arguments.get(\"variables\", {})\n\n if prompt_type not in _PROMPT_CATALOG:\n available = list(_PROMPT_CATALOG.keys())\n return json.dumps({\n \"error\": f\"Unknown prompt_type: {prompt_type}\",\n \"available_types\": available,\n })\n\n catalog_entry = _PROMPT_CATALOG[prompt_type]\n\n # Resolve the prompt content\n content = _resolve_prompt(prompt_type, variables)\n\n result = {\n \"prompt_type\": prompt_type,\n \"description\": catalog_entry[\"description\"],\n \"usage_hint\": catalog_entry[\"usage_hint\"],\n \"content\": content,\n }\n return json.dumps(result, indent=2, ensure_ascii=False)", - "start_line": 77, - "end_line": 103, - "has_docstring": true, - "docstring": "Return a prompt template, optionally with variables filled in.", - "parameters": [ - "arguments", - "store" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function handle_get_prompt", - "component_id": "codewiki/mcp/tools/prompt_server.py::handle_get_prompt", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/tools/prompt_server.py::_resolve_prompt": { - "id": "codewiki/mcp/tools/prompt_server.py::_resolve_prompt", - "name": "_resolve_prompt", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/tools/prompt_server.py", - "relative_path": "codewiki/mcp/tools/prompt_server.py", - "depends_on": [ - "codewiki/src/be/prompt_template.py::format_leaf_system_prompt", - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter.format", - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/prompt_template.py::format_cluster_prompt", - "codewiki/src/be/prompt_template.py::format_system_prompt" - ], - "source_code": "def _resolve_prompt(prompt_type: str, variables: Dict[str, Any]) -> str:\n \"\"\"Resolve a prompt template with optional variable substitution.\"\"\"\n\n if prompt_type == \"cluster\":\n potential_core_components = variables.get(\"potential_core_components\", \"\")\n module_tree = variables.get(\"module_tree\", {})\n module_name = variables.get(\"module_name\", None)\n return format_cluster_prompt(\n potential_core_components=potential_core_components,\n module_tree=module_tree,\n module_name=module_name,\n )\n\n elif prompt_type == \"system_complex\":\n module_name = variables.get(\"module_name\", \"MODULE_NAME\")\n custom_instructions = variables.get(\"custom_instructions\", None)\n return format_system_prompt(module_name, custom_instructions)\n\n elif prompt_type == \"system_leaf\":\n module_name = variables.get(\"module_name\", \"MODULE_NAME\")\n custom_instructions = variables.get(\"custom_instructions\", None)\n return format_leaf_system_prompt(module_name, custom_instructions)\n\n elif prompt_type == \"user\":\n module_name = variables.get(\"module_name\", \"MODULE_NAME\")\n module_tree = variables.get(\"module_tree\", {})\n\n # Return the template with placeholders filled as possible\n return USER_PROMPT.format(\n module_name=module_name,\n module_tree=json.dumps(module_tree, indent=2) if module_tree else \"\",\n formatted_core_component_codes=variables.get(\n \"formatted_core_component_codes\",\n \"\"\n ),\n )\n\n elif prompt_type == \"overview_module\":\n module_name = variables.get(\"module_name\", \"MODULE_NAME\")\n repo_structure = variables.get(\"repo_structure\", \"\")\n return MODULE_OVERVIEW_PROMPT.format(\n module_name=module_name,\n repo_structure=repo_structure if isinstance(repo_structure, str) else json.dumps(repo_structure, indent=4),\n )\n\n elif prompt_type == \"overview_repo\":\n repo_name = variables.get(\"repo_name\", \"REPO_NAME\")\n repo_structure = variables.get(\"repo_structure\", \"\")\n return REPO_OVERVIEW_PROMPT.format(\n repo_name=repo_name,\n repo_structure=repo_structure if isinstance(repo_structure, str) else json.dumps(repo_structure, indent=4),\n )\n\n return f\"Unknown prompt type: {prompt_type}\"", - "start_line": 106, - "end_line": 159, - "has_docstring": true, - "docstring": "Resolve a prompt template with optional variable substitution.", - "parameters": [ - "prompt_type", - "variables" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _resolve_prompt", - "component_id": "codewiki/mcp/tools/prompt_server.py::_resolve_prompt", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/workspace.py::_safe_filename": { - "id": "codewiki/mcp/workspace.py::_safe_filename", - "name": "_safe_filename", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/workspace.py", - "relative_path": "codewiki/mcp/workspace.py", - "depends_on": [], - "source_code": "def _safe_filename(component_id: str) -> str:\n \"\"\"Sanitize a component ID for use as a filename.\n\n Component IDs look like ``src/main.py::MyClass``. We replace any\n character that is not a word char, hyphen, or dot with ``__``.\n A short hash suffix is appended to prevent collisions when different\n component IDs sanitize to the same string (e.g. ``src/a-b.py`` vs\n ``src/a_b.py``).\n\n The sanitized part is truncated so the filename stays under the\n common 255-byte NAME_MAX (separator chars expand to two chars each,\n so deep paths overflow it easily); the hash suffix keeps truncated\n names unique.\n \"\"\"\n sanitized = re.sub(r\"[^\\w\\-.]\", \"__\", component_id)[:180]\n hash_suffix = hashlib.sha1(component_id.encode()).hexdigest()[:8]\n return f\"{sanitized}_{hash_suffix}.src\"", - "start_line": 37, - "end_line": 53, - "has_docstring": true, - "docstring": "Sanitize a component ID for use as a filename.\n\nComponent IDs look like ``src/main.py::MyClass``. We replace any\ncharacter that is not a word char, hyphen, or dot with ``__``.\nA short hash suffix is appended to prevent collisions when different\ncomponent IDs sanitize to the same string (e.g. ``src/a-b.py`` vs\n``src/a_b.py``).\n\nThe sanitized part is truncated so the filename stays under the\ncommon 255-byte NAME_MAX (separator chars expand to two chars each,\nso deep paths overflow it easily); the hash suffix keeps truncated\nnames unique.", - "parameters": [ - "component_id" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _safe_filename", - "component_id": "codewiki/mcp/workspace.py::_safe_filename", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/workspace.py::SessionWorkspace": { - "id": "codewiki/mcp/workspace.py::SessionWorkspace", - "name": "SessionWorkspace", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/workspace.py", - "relative_path": "codewiki/mcp/workspace.py", - "depends_on": [], - "source_code": "class SessionWorkspace:\n \"\"\"Manages the on-disk workspace for a single MCP session.\"\"\"\n\n def __init__(self, repo_path: Path, session_id: str) -> None:\n self.root = repo_path / _WORKSPACE_REL / session_id\n self.root.mkdir(parents=True, exist_ok=True)\n (self.root / \"sources\").mkdir(exist_ok=True)\n logger.debug(\"Workspace created at %s\", self.root)\n\n # -- writers ----------------------------------------------------------\n\n def write_json(self, name: str, data: Any) -> Path:\n \"\"\"Write *data* as pretty-printed JSON and return the file path.\"\"\"\n p = self.root / name\n p.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding=\"utf-8\")\n return p\n\n def write_component_source(\n self,\n component_id: str,\n source: str,\n language: str = \"\",\n ) -> Path:\n \"\"\"Write a single component's source code to the ``sources/`` dir.\"\"\"\n p = self.root / \"sources\" / _safe_filename(component_id)\n header = f\"// Component: {component_id}\\n// Language: {language}\\n\"\n p.write_text(header + source, encoding=\"utf-8\")\n return p\n\n # -- readers ----------------------------------------------------------\n\n def read_json(self, name: str) -> Any:\n \"\"\"Read a JSON file from the workspace. Returns ``None`` if missing.\"\"\"\n p = self.root / name\n if not p.exists():\n return None\n return json.loads(p.read_text(encoding=\"utf-8\"))\n\n # -- cleanup ----------------------------------------------------------\n\n def cleanup(self) -> None:\n \"\"\"Remove the session directory and try to prune empty parents.\"\"\"\n if self.root.exists():\n shutil.rmtree(self.root, ignore_errors=True)\n # Walk up and remove empty parent directories\n try:\n sessions_dir = self.root.parent # .codewiki/sessions\n if sessions_dir.exists() and not any(sessions_dir.iterdir()):\n sessions_dir.rmdir()\n base_dir = sessions_dir.parent # .codewiki\n if base_dir.exists() and not any(base_dir.iterdir()):\n base_dir.rmdir()\n except OSError:\n pass\n logger.debug(\"Workspace cleaned up: %s\", self.root)", - "start_line": 56, - "end_line": 110, - "has_docstring": true, - "docstring": "Manages the on-disk workspace for a single MCP session.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class SessionWorkspace", - "component_id": "codewiki/mcp/workspace.py::SessionWorkspace", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/workspace.py::SessionWorkspace.__init__": { - "id": "codewiki/mcp/workspace.py::SessionWorkspace.__init__", - "name": "SessionWorkspace.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/workspace.py", - "relative_path": "codewiki/mcp/workspace.py", - "depends_on": [ - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": " def __init__(self, repo_path: Path, session_id: str) -> None:\n self.root = repo_path / _WORKSPACE_REL / session_id\n self.root.mkdir(parents=True, exist_ok=True)\n (self.root / \"sources\").mkdir(exist_ok=True)\n logger.debug(\"Workspace created at %s\", self.root)", - "start_line": 59, - "end_line": 63, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "repo_path", - "session_id" - ], - "node_type": "method", - "base_classes": null, - "class_name": "SessionWorkspace", - "display_name": "method SessionWorkspace.__init__", - "component_id": "codewiki/mcp/workspace.py::SessionWorkspace.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/workspace.py::SessionWorkspace.write_json": { - "id": "codewiki/mcp/workspace.py::SessionWorkspace.write_json", - "name": "SessionWorkspace.write_json", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/workspace.py", - "relative_path": "codewiki/mcp/workspace.py", - "depends_on": [], - "source_code": " def write_json(self, name: str, data: Any) -> Path:\n \"\"\"Write *data* as pretty-printed JSON and return the file path.\"\"\"\n p = self.root / name\n p.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding=\"utf-8\")\n return p", - "start_line": 67, - "end_line": 71, - "has_docstring": true, - "docstring": "Write *data* as pretty-printed JSON and return the file path.", - "parameters": [ - "self", - "name", - "data" - ], - "node_type": "method", - "base_classes": null, - "class_name": "SessionWorkspace", - "display_name": "method SessionWorkspace.write_json", - "component_id": "codewiki/mcp/workspace.py::SessionWorkspace.write_json", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/workspace.py::SessionWorkspace.write_component_source": { - "id": "codewiki/mcp/workspace.py::SessionWorkspace.write_component_source", - "name": "SessionWorkspace.write_component_source", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/workspace.py", - "relative_path": "codewiki/mcp/workspace.py", - "depends_on": [ - "codewiki/mcp/workspace.py::_safe_filename" - ], - "source_code": " def write_component_source(\n self,\n component_id: str,\n source: str,\n language: str = \"\",\n ) -> Path:\n \"\"\"Write a single component's source code to the ``sources/`` dir.\"\"\"\n p = self.root / \"sources\" / _safe_filename(component_id)\n header = f\"// Component: {component_id}\\n// Language: {language}\\n\"\n p.write_text(header + source, encoding=\"utf-8\")\n return p", - "start_line": 73, - "end_line": 83, - "has_docstring": true, - "docstring": "Write a single component's source code to the ``sources/`` dir.", - "parameters": [ - "self", - "component_id", - "source", - "language" - ], - "node_type": "method", - "base_classes": null, - "class_name": "SessionWorkspace", - "display_name": "method SessionWorkspace.write_component_source", - "component_id": "codewiki/mcp/workspace.py::SessionWorkspace.write_component_source", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/workspace.py::SessionWorkspace.read_json": { - "id": "codewiki/mcp/workspace.py::SessionWorkspace.read_json", - "name": "SessionWorkspace.read_json", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/workspace.py", - "relative_path": "codewiki/mcp/workspace.py", - "depends_on": [], - "source_code": " def read_json(self, name: str) -> Any:\n \"\"\"Read a JSON file from the workspace. Returns ``None`` if missing.\"\"\"\n p = self.root / name\n if not p.exists():\n return None\n return json.loads(p.read_text(encoding=\"utf-8\"))", - "start_line": 87, - "end_line": 92, - "has_docstring": true, - "docstring": "Read a JSON file from the workspace. Returns ``None`` if missing.", - "parameters": [ - "self", - "name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "SessionWorkspace", - "display_name": "method SessionWorkspace.read_json", - "component_id": "codewiki/mcp/workspace.py::SessionWorkspace.read_json", - "language": null, - "qualified_name": null - }, - "codewiki/mcp/workspace.py::SessionWorkspace.cleanup": { - "id": "codewiki/mcp/workspace.py::SessionWorkspace.cleanup", - "name": "SessionWorkspace.cleanup", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/mcp/workspace.py", - "relative_path": "codewiki/mcp/workspace.py", - "depends_on": [ - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": " def cleanup(self) -> None:\n \"\"\"Remove the session directory and try to prune empty parents.\"\"\"\n if self.root.exists():\n shutil.rmtree(self.root, ignore_errors=True)\n # Walk up and remove empty parent directories\n try:\n sessions_dir = self.root.parent # .codewiki/sessions\n if sessions_dir.exists() and not any(sessions_dir.iterdir()):\n sessions_dir.rmdir()\n base_dir = sessions_dir.parent # .codewiki\n if base_dir.exists() and not any(base_dir.iterdir()):\n base_dir.rmdir()\n except OSError:\n pass\n logger.debug(\"Workspace cleaned up: %s\", self.root)", - "start_line": 96, - "end_line": 110, - "has_docstring": true, - "docstring": "Remove the session directory and try to prune empty parents.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "SessionWorkspace", - "display_name": "method SessionWorkspace.cleanup", - "component_id": "codewiki/mcp/workspace.py::SessionWorkspace.cleanup", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/deps.py::CodeWikiDeps": { - "id": "codewiki/src/be/agent_tools/deps.py::CodeWikiDeps", - "name": "CodeWikiDeps", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/deps.py", - "relative_path": "codewiki/src/be/agent_tools/deps.py", - "depends_on": [], - "source_code": "class CodeWikiDeps:\n absolute_docs_path: str\n absolute_repo_path: str\n registry: dict\n components: dict[str, Node]\n path_to_current_module: list[str]\n current_module_name: str\n module_tree: dict[str, any]\n max_depth: int\n current_depth: int\n config: Config # LLM configuration\n custom_instructions: str = None", - "start_line": 6, - "end_line": 17, - "has_docstring": false, - "docstring": "", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class CodeWikiDeps", - "component_id": "codewiki/src/be/agent_tools/deps.py::CodeWikiDeps", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/generate_sub_module_documentations.py::generate_sub_module_documentation": { - "id": "codewiki/src/be/agent_tools/generate_sub_module_documentations.py::generate_sub_module_documentation", - "name": "generate_sub_module_documentation", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/generate_sub_module_documentations.py", - "relative_path": "codewiki/src/be/agent_tools/generate_sub_module_documentations.py", - "depends_on": [ - "codewiki/src/be/llm_services.py::create_fallback_models", - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter.format", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.run", - "codewiki/src/be/utils.py::is_complex_module", - "codewiki/src/be/utils.py::count_tokens", - "codewiki/src/be/prompt_template.py::format_user_prompt", - "codewiki/src/be/cluster_modules.py::format_potential_core_components", - "codewiki/src/be/module_naming.py::normalize_sub_module_specs" - ], - "source_code": "async def generate_sub_module_documentation(\n ctx: RunContext[CodeWikiDeps],\n sub_module_specs: dict[str, list[str]]\n) -> str:\n \"\"\"Delegate documentation generation of sub-modules to sub-agents. Each sub-module will be documented separately.\n\n Args:\n sub_module_specs: A dictionary mapping sub-module names to their core component IDs.\n Example: {\"authentication\": [\"auth_handler.py::AuthHandler\", \"auth_middleware.py::verify_token\"], \"database\": [\"db_client.py::DBClient\", \"models.py::UserModel\"]}\n Each key is a descriptive sub-module name, and the value is a list of component IDs from the current module's core components that belong to that sub-module.\n Sub-module names must be unique across the whole wiki; a name that is already used by another\n module is automatically prefixed with the current module name, and the tool result reports the\n final file names actually saved.\n \"\"\"\n\n deps = ctx.deps\n previous_module_name = deps.current_module_name\n\n # Create fallback models from config\n fallback_models = create_fallback_models(deps.config)\n\n # Resolve name collisions against the module tree and files already on disk\n # before touching the tree (issue #76): docs live in one flat directory.\n name_map = normalize_sub_module_specs(\n sub_module_specs,\n previous_module_name,\n deps.module_tree,\n deps.absolute_docs_path,\n )\n final_specs = {\n name_map[requested_name]: core_component_ids\n for requested_name, core_component_ids in sub_module_specs.items()\n }\n\n # add the sub-module to the module tree\n value = deps.module_tree\n for key in deps.path_to_current_module:\n value = value[key][\"children\"]\n for sub_module_name, core_component_ids in final_specs.items():\n value[sub_module_name] = {\"components\": core_component_ids, \"children\": {}}\n\n for sub_module_name, core_component_ids in final_specs.items():\n\n # Create visual indentation for nested modules\n indent = \" \" * deps.current_depth\n arrow = \"└─\" if deps.current_depth > 0 else \"β†’\"\n\n logger.info(f\"{indent}{arrow} Generating documentation for sub-module: {sub_module_name}\")\n\n num_tokens = count_tokens(format_potential_core_components(core_component_ids, ctx.deps.components)[-1])\n \n if is_complex_module(ctx.deps.components, core_component_ids) and ctx.deps.current_depth < ctx.deps.max_depth and num_tokens >= ctx.deps.config.max_token_per_leaf_module:\n sub_agent = Agent(\n model=fallback_models,\n name=sub_module_name,\n deps_type=CodeWikiDeps,\n system_prompt=SYSTEM_PROMPT.format(module_name=sub_module_name, custom_instructions=ctx.deps.custom_instructions),\n tools=[read_code_components_tool, str_replace_editor_tool, generate_sub_module_documentation_tool],\n )\n else:\n sub_agent = Agent(\n model=fallback_models,\n name=sub_module_name,\n deps_type=CodeWikiDeps,\n system_prompt=LEAF_SYSTEM_PROMPT.format(module_name=sub_module_name, custom_instructions=ctx.deps.custom_instructions),\n tools=[read_code_components_tool, str_replace_editor_tool],\n )\n\n deps.current_module_name = sub_module_name\n deps.path_to_current_module.append(sub_module_name)\n deps.current_depth += 1\n # log the current module tree\n # print(f\"Current module tree: {json.dumps(deps.module_tree, indent=4)}\")\n\n result = await sub_agent.run(\n format_user_prompt(\n module_name=deps.current_module_name,\n core_component_ids=core_component_ids,\n components=ctx.deps.components,\n module_tree=ctx.deps.module_tree,\n ),\n deps=ctx.deps\n )\n\n # remove the sub-module name from the path to current module and the module tree\n deps.path_to_current_module.pop()\n deps.current_depth -= 1\n\n # restore the previous module name\n deps.current_module_name = previous_module_name\n\n # Report what actually landed on disk so the parent agent links real filenames.\n saved = []\n missing = []\n for requested_name, final_name in name_map.items():\n entry = f\"{final_name}.md\"\n if final_name != requested_name:\n entry += f\" (requested '{requested_name}', renamed to avoid a collision)\"\n if os.path.exists(os.path.join(deps.absolute_docs_path, f\"{final_name}.md\")):\n saved.append(entry)\n else:\n missing.append(entry)\n\n report = f\"Saved documentations: {', '.join(saved) if saved else 'none'}.\"\n if missing:\n report += f\" MISSING (generation did not produce these files): {', '.join(missing)}.\"\n logger.warning(\"Sub-module documentation missing after generation: %s\", \", \".join(missing))\n return report", - "start_line": 19, - "end_line": 126, - "has_docstring": true, - "docstring": "Delegate documentation generation of sub-modules to sub-agents. Each sub-module will be documented separately.\n\nArgs:\n sub_module_specs: A dictionary mapping sub-module names to their core component IDs.\n Example: {\"authentication\": [\"auth_handler.py::AuthHandler\", \"auth_middleware.py::verify_token\"], \"database\": [\"db_client.py::DBClient\", \"models.py::UserModel\"]}\n Each key is a descriptive sub-module name, and the value is a list of component IDs from the current module's core components that belong to that sub-module.\n Sub-module names must be unique across the whole wiki; a name that is already used by another\n module is automatically prefixed with the current module name, and the tool result reports the\n final file names actually saved.", - "parameters": [ - "ctx", - "sub_module_specs" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function generate_sub_module_documentation", - "component_id": "codewiki/src/be/agent_tools/generate_sub_module_documentations.py::generate_sub_module_documentation", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/read_code_components.py::read_code_components": { - "id": "codewiki/src/be/agent_tools/read_code_components.py::read_code_components", - "name": "read_code_components", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/read_code_components.py", - "relative_path": "codewiki/src/be/agent_tools/read_code_components.py", - "depends_on": [], - "source_code": "async def read_code_components(ctx: RunContext[CodeWikiDeps], component_ids: list[str]) -> str:\n \"\"\"Read the code of a given component id\n\n Args:\n component_ids: The ids of the components to read, e.g. [\"sweagent/types.py::AgentRunResult\", \"auth/middleware.py::verify_token\"] where the part before :: is the file path and the part after :: is the component name\n \"\"\"\n\n results = []\n\n for component_id in component_ids:\n if component_id not in ctx.deps.components:\n results.append(f\"# Component {component_id} not found\")\n else:\n results.append(f\"# Component {component_id}:\\n{ctx.deps.components[component_id].source_code.strip()}\\n\\n\")\n\n return \"\\n\".join(results)", - "start_line": 5, - "end_line": 20, - "has_docstring": true, - "docstring": "Read the code of a given component id\n\nArgs:\n component_ids: The ids of the components to read, e.g. [\"sweagent/types.py::AgentRunResult\", \"auth/middleware.py::verify_token\"] where the part before :: is the file path and the part after :: is the component name", - "parameters": [ - "ctx", - "component_ids" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function read_code_components", - "component_id": "codewiki/src/be/agent_tools/read_code_components.py::read_code_components", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::_coerce_json_string": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::_coerce_json_string", - "name": "_coerce_json_string", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [], - "source_code": "def _coerce_json_string(value):\n \"\"\"Coerce a JSON encoded string to its parsed Python value before pydantic\n strict validation runs. No op on already typed values.\n\n Some local models routed through OpenAI compatible endpoints (LiteLLM,\n vLLM, Ollama, etc.) emit list and int tool args as JSON encoded strings\n (e.g. `\"[1, 50]\"` instead of `[1, 50]`) which strict pydantic validation\n rejects. This validator parses them so the tool accepts both shapes.\n Anthropic native API users are unaffected because they already emit\n structured values.\n \"\"\"\n if isinstance(value, str):\n try:\n return json.loads(value)\n except ValueError:\n pass\n return value", - "start_line": 29, - "end_line": 45, - "has_docstring": true, - "docstring": "Coerce a JSON encoded string to its parsed Python value before pydantic\nstrict validation runs. No op on already typed values.\n\nSome local models routed through OpenAI compatible endpoints (LiteLLM,\nvLLM, Ollama, etc.) emit list and int tool args as JSON encoded strings\n(e.g. `\"[1, 50]\"` instead of `[1, 50]`) which strict pydantic validation\nrejects. This validator parses them so the tool accepts both shapes.\nAnthropic native API users are unaffected because they already emit\nstructured values.", - "parameters": [ - "value" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _coerce_json_string", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::_coerce_json_string", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::maybe_truncate": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::maybe_truncate", - "name": "maybe_truncate", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [], - "source_code": "def maybe_truncate(content: str, truncate_after: Optional[int] = MAX_RESPONSE_LEN):\n \"\"\"Truncate content and append a notice if content exceeds the specified length.\"\"\"\n return (\n content\n if not truncate_after or len(content) <= truncate_after\n else content[:truncate_after] + TRUNCATED_MESSAGE\n )", - "start_line": 87, - "end_line": 93, - "has_docstring": true, - "docstring": "Truncate content and append a notice if content exceeds the specified length.", - "parameters": [ - "content", - "truncate_after" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function maybe_truncate", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::maybe_truncate", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::Flake8Error": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::Flake8Error", - "name": "Flake8Error", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [], - "source_code": "class Flake8Error:\n \"\"\"A class to represent a single flake8 error\"\"\"\n\n def __init__(self, filename: str, line_number: int, col_number: int, problem: str):\n self.filename = filename\n self.line_number = line_number\n self.col_number = col_number\n self.problem = problem\n\n @classmethod\n def from_line(cls, line: str):\n try:\n prefix, _sep, problem = line.partition(\": \")\n filename, line_number, col_number = prefix.split(\":\")\n except (ValueError, IndexError) as e:\n msg = f\"Invalid flake8 error line: {line}\"\n raise ValueError(msg) from e\n return cls(filename, int(line_number), int(col_number), problem)\n\n def __eq__(self, other):\n if not isinstance(other, Flake8Error):\n return NotImplemented\n return (\n self.filename == other.filename\n and self.line_number == other.line_number\n and self.col_number == other.col_number\n and self.problem == other.problem\n )\n\n def __repr__(self):\n return f\"Flake8Error(filename={self.filename}, line_number={self.line_number}, col_number={self.col_number}, problem={self.problem})\"", - "start_line": 96, - "end_line": 126, - "has_docstring": true, - "docstring": "A class to represent a single flake8 error", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class Flake8Error", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::Flake8Error", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::Flake8Error.__init__": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::Flake8Error.__init__", - "name": "Flake8Error.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [], - "source_code": " def __init__(self, filename: str, line_number: int, col_number: int, problem: str):\n self.filename = filename\n self.line_number = line_number\n self.col_number = col_number\n self.problem = problem", - "start_line": 99, - "end_line": 103, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "filename", - "line_number", - "col_number", - "problem" - ], - "node_type": "method", - "base_classes": null, - "class_name": "Flake8Error", - "display_name": "method Flake8Error.__init__", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::Flake8Error.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::Flake8Error.from_line": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::Flake8Error.from_line", - "name": "Flake8Error.from_line", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [], - "source_code": " def from_line(cls, line: str):\n try:\n prefix, _sep, problem = line.partition(\": \")\n filename, line_number, col_number = prefix.split(\":\")\n except (ValueError, IndexError) as e:\n msg = f\"Invalid flake8 error line: {line}\"\n raise ValueError(msg) from e\n return cls(filename, int(line_number), int(col_number), problem)", - "start_line": 106, - "end_line": 113, - "has_docstring": false, - "docstring": "", - "parameters": [ - "cls", - "line" - ], - "node_type": "method", - "base_classes": null, - "class_name": "Flake8Error", - "display_name": "method Flake8Error.from_line", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::Flake8Error.from_line", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::Flake8Error.__eq__": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::Flake8Error.__eq__", - "name": "Flake8Error.__eq__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [], - "source_code": " def __eq__(self, other):\n if not isinstance(other, Flake8Error):\n return NotImplemented\n return (\n self.filename == other.filename\n and self.line_number == other.line_number\n and self.col_number == other.col_number\n and self.problem == other.problem\n )", - "start_line": 115, - "end_line": 123, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "other" - ], - "node_type": "method", - "base_classes": null, - "class_name": "Flake8Error", - "display_name": "method Flake8Error.__eq__", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::Flake8Error.__eq__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::Flake8Error.__repr__": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::Flake8Error.__repr__", - "name": "Flake8Error.__repr__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [], - "source_code": " def __repr__(self):\n return f\"Flake8Error(filename={self.filename}, line_number={self.line_number}, col_number={self.col_number}, problem={self.problem})\"", - "start_line": 125, - "end_line": 126, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "Flake8Error", - "display_name": "method Flake8Error.__repr__", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::Flake8Error.__repr__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::_update_previous_errors": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::_update_previous_errors", - "name": "_update_previous_errors", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [ - "codewiki/src/be/agent_tools/str_replace_editor.py::Flake8Error" - ], - "source_code": "def _update_previous_errors(\n previous_errors: List[Flake8Error], replacement_window: Tuple[int, int], replacement_n_lines: int\n) -> List[Flake8Error]:\n \"\"\"Update the line numbers of the previous errors to what they would be after the edit window.\n This is a helper function for `_filter_previous_errors`.\n\n All previous errors that are inside of the edit window should not be ignored,\n so they are removed from the previous errors list.\n\n Args:\n previous_errors: list of errors with old line numbers\n replacement_window: the window of the edit/lines that will be replaced\n replacement_n_lines: the number of lines that will be used to replace the text\n\n Returns:\n list of errors with updated line numbers\n \"\"\"\n updated = []\n lines_added = replacement_n_lines - (replacement_window[1] - replacement_window[0] + 1)\n for error in previous_errors:\n if error.line_number < replacement_window[0]:\n # no need to adjust the line number\n updated.append(error)\n continue\n if replacement_window[0] <= error.line_number <= replacement_window[1]:\n # The error is within the edit window, so let's not ignore it\n # either way (we wouldn't know how to adjust the line number anyway)\n continue\n # We're out of the edit window, so we need to adjust the line number\n updated.append(Flake8Error(error.filename, error.line_number + lines_added, error.col_number, error.problem))\n return updated", - "start_line": 129, - "end_line": 159, - "has_docstring": true, - "docstring": "Update the line numbers of the previous errors to what they would be after the edit window.\nThis is a helper function for `_filter_previous_errors`.\n\nAll previous errors that are inside of the edit window should not be ignored,\nso they are removed from the previous errors list.\n\nArgs:\n previous_errors: list of errors with old line numbers\n replacement_window: the window of the edit/lines that will be replaced\n replacement_n_lines: the number of lines that will be used to replace the text\n\nReturns:\n list of errors with updated line numbers", - "parameters": [ - "previous_errors", - "replacement_window", - "replacement_n_lines" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _update_previous_errors", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::_update_previous_errors", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::format_flake8_output": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::format_flake8_output", - "name": "format_flake8_output", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [ - "codewiki/src/be/agent_tools/str_replace_editor.py::Flake8Error.from_line", - "codewiki/src/be/agent_tools/str_replace_editor.py::_update_previous_errors" - ], - "source_code": "def format_flake8_output(\n input_string: str,\n show_line_numbers: bool = False,\n *,\n previous_errors_string: str = \"\",\n replacement_window: Optional[Tuple[int, int]] = None,\n replacement_n_lines: Optional[int] = None,\n) -> str:\n \"\"\"Filter flake8 output for previous errors and print it for a given file.\n\n Args:\n input_string: The flake8 output as a string\n show_line_numbers: Whether to show line numbers in the output\n previous_errors_string: The previous errors as a string\n replacement_window: The window of the edit (lines that will be replaced)\n replacement_n_lines: The number of lines used to replace the text\n\n Returns:\n The filtered flake8 output as a string\n \"\"\"\n # print(f\"Replacement window: {replacement_window}\")\n # print(\"Replacement n lines:\", replacement_n_lines)\n # print(\"Previous errors string:\", previous_errors_string)\n # print(\"Input string:\", input_string)\n errors = [Flake8Error.from_line(line.strip()) for line in input_string.split(\"\\n\") if line.strip()]\n # print(f\"New errors before filtering: {errors=}\")\n lines = []\n if previous_errors_string:\n assert replacement_window is not None\n assert replacement_n_lines is not None\n previous_errors = [\n Flake8Error.from_line(line.strip()) for line in previous_errors_string.split(\"\\n\") if line.strip()\n ]\n # print(f\"Previous errors before updating: {previous_errors=}\")\n previous_errors = _update_previous_errors(previous_errors, replacement_window, replacement_n_lines)\n # print(f\"Previous errors after updating: {previous_errors=}\")\n errors = [error for error in errors if error not in previous_errors]\n # Sometimes new errors appear above the replacement window that were 'shadowed' by the previous errors\n # they still clearly aren't caused by the edit.\n errors = [error for error in errors if error.line_number >= replacement_window[0]]\n # print(f\"New errors after filtering: {errors=}\")\n for error in errors:\n if not show_line_numbers:\n lines.append(f\"- {error.problem}\")\n else:\n lines.append(f\"- line {error.line_number} col {error.col_number}: {error.problem}\")\n return \"\\n\".join(lines)", - "start_line": 162, - "end_line": 208, - "has_docstring": true, - "docstring": "Filter flake8 output for previous errors and print it for a given file.\n\nArgs:\n input_string: The flake8 output as a string\n show_line_numbers: Whether to show line numbers in the output\n previous_errors_string: The previous errors as a string\n replacement_window: The window of the edit (lines that will be replaced)\n replacement_n_lines: The number of lines used to replace the text\n\nReturns:\n The filtered flake8 output as a string", - "parameters": [ - "input_string", - "show_line_numbers" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function format_flake8_output", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::format_flake8_output", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::flake8": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::flake8", - "name": "flake8", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [ - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.run", - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter.format" - ], - "source_code": "def flake8(file_path: str) -> str:\n \"\"\"Run flake8 on a given file and return the output as a string\"\"\"\n if Path(file_path).suffix != \".py\":\n return \"\"\n cmd = \"flake8 --isolated --select=F821,F822,F831,E111,E112,E113,E999,E902 {file_path}\"\n # don't use capture_output because it's not compatible with python3.6\n out = subprocess.run(cmd.format(file_path=file_path), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n # Use errors=\"replace\" so non-UTF-8 bytes (e.g. GBK-encoded paths on Windows) don't crash decoding.\n return out.stdout.decode(\"utf-8\", errors=\"replace\")", - "start_line": 211, - "end_line": 219, - "has_docstring": true, - "docstring": "Run flake8 on a given file and return the output as a string", - "parameters": [ - "file_path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function flake8", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::flake8", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::Filemap": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::Filemap", - "name": "Filemap", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [], - "source_code": "class Filemap:\n def show_filemap(self, file_contents: str, encoding: str = \"utf8\"):\n import warnings\n from tree_sitter_languages import get_language, get_parser\n\n warnings.simplefilter(\"ignore\", category=FutureWarning)\n\n parser = get_parser(\"python\")\n language = get_language(\"python\")\n\n tree = parser.parse(bytes(file_contents.encode(encoding, errors=\"replace\")))\n\n # See https://tree-sitter.github.io/tree-sitter/using-parsers#pattern-matching-with-queries.\n query = language.query(\"\"\"\n (function_definition\n body: (_) @body)\n \"\"\")\n\n # TODO: consider special casing docstrings such that they are not elided. This\n # could be accomplished by checking whether `body.text.decode('utf8')` starts\n # with `\"\"\"` or `'''`.\n elide_line_ranges = [\n (node.start_point[0], node.end_point[0])\n for node, _ in query.captures(tree.root_node)\n # Only elide if it's sufficiently long\n if node.end_point[0] - node.start_point[0] >= 5\n ]\n # Note that tree-sitter line numbers are 0-indexed, but we display 1-indexed.\n elide_lines = {line for start, end in elide_line_ranges for line in range(start, end + 1)}\n elide_messages = [(start, f\"... eliding lines {start+1}-{end+1} ...\") for start, end in elide_line_ranges]\n out = []\n for i, line in sorted(\n elide_messages + [(i, line) for i, line in enumerate(file_contents.splitlines()) if i not in elide_lines]\n ):\n out.append(f\"{i+1:6d} {line}\")\n return \"\\n\".join(out)", - "start_line": 222, - "end_line": 257, - "has_docstring": false, - "docstring": "", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class Filemap", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::Filemap", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::Filemap.show_filemap": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::Filemap.show_filemap", - "name": "Filemap.show_filemap", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [], - "source_code": " def show_filemap(self, file_contents: str, encoding: str = \"utf8\"):\n import warnings\n from tree_sitter_languages import get_language, get_parser\n\n warnings.simplefilter(\"ignore\", category=FutureWarning)\n\n parser = get_parser(\"python\")\n language = get_language(\"python\")\n\n tree = parser.parse(bytes(file_contents.encode(encoding, errors=\"replace\")))\n\n # See https://tree-sitter.github.io/tree-sitter/using-parsers#pattern-matching-with-queries.\n query = language.query(\"\"\"\n (function_definition\n body: (_) @body)\n \"\"\")\n\n # TODO: consider special casing docstrings such that they are not elided. This\n # could be accomplished by checking whether `body.text.decode('utf8')` starts\n # with `\"\"\"` or `'''`.\n elide_line_ranges = [\n (node.start_point[0], node.end_point[0])\n for node, _ in query.captures(tree.root_node)\n # Only elide if it's sufficiently long\n if node.end_point[0] - node.start_point[0] >= 5\n ]\n # Note that tree-sitter line numbers are 0-indexed, but we display 1-indexed.\n elide_lines = {line for start, end in elide_line_ranges for line in range(start, end + 1)}\n elide_messages = [(start, f\"... eliding lines {start+1}-{end+1} ...\") for start, end in elide_line_ranges]\n out = []\n for i, line in sorted(\n elide_messages + [(i, line) for i, line in enumerate(file_contents.splitlines()) if i not in elide_lines]\n ):\n out.append(f\"{i+1:6d} {line}\")\n return \"\\n\".join(out)", - "start_line": 223, - "end_line": 257, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "file_contents", - "encoding" - ], - "node_type": "method", - "base_classes": null, - "class_name": "Filemap", - "display_name": "method Filemap.show_filemap", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::Filemap.show_filemap", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander", - "name": "WindowExpander", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [], - "source_code": "class WindowExpander:\n def __init__(self, suffix: str = \"\"):\n \"\"\"Try to expand viewports to include whole functions, classes, etc. rather than\n using fixed line windows.\n\n Args:\n suffix: Filename suffix\n \"\"\"\n self.suffix = suffix\n if self.suffix:\n assert self.suffix.startswith(\".\")\n\n def _find_breakpoints(self, lines: List[str], current_line: int, direction=1, max_added_lines: int = 30) -> int:\n \"\"\"Returns 1-based line number of breakpoint. This line is meant to still be included in the viewport.\n\n Args:\n lines: List of lines of the file\n current_line: 1-based line number of the current viewport\n direction: 1 for down, -1 for up\n max_added_lines: Maximum number of lines to extend\n\n Returns:\n 1-based line number of breakpoint. This line is meant to still be included in the viewport.\n \"\"\"\n assert 1 <= current_line <= len(lines)\n assert 0 <= max_added_lines\n\n # 1. Find line range that we want to search for breakpoints in\n\n if direction == 1:\n # down\n if current_line == len(lines):\n # already last line, can't extend down\n return current_line\n iter_lines = range(current_line, 1 + min(current_line + max_added_lines, len(lines)))\n elif direction == -1:\n # up\n if current_line == 1:\n # already first line, can't extend up\n return current_line\n iter_lines = range(current_line, -1 + max(current_line - max_added_lines, 1), -1)\n else:\n msg = f\"Invalid direction {direction}\"\n raise ValueError(msg)\n\n # 2. Find the best breakpoint in the line range\n\n # Every condition gives a score, the best score is the best breakpoint\n best_score = 0\n best_breakpoint = current_line\n for i_line in iter_lines:\n next_line = None\n line = lines[i_line - 1]\n if i_line + direction in iter_lines:\n next_line = lines[i_line + direction - 1]\n score = 0\n if line == \"\":\n score = 1\n if next_line == \"\":\n # Double new blank line:\n score = 2\n if self.suffix == \".py\" and any(\n re.match(regex, line) for regex in [r\"^\\s*def\\s+\", r\"^\\s*class\\s+\", r\"^\\s*@\"]\n ):\n # We include decorators here, because they are always on top of the function/class definition\n score = 3\n if score > best_score:\n best_score = score\n best_breakpoint = i_line\n if direction == 1 and i_line != current_line:\n best_breakpoint -= 1\n if i_line == 1 or i_line == len(lines):\n score = 3\n if score > best_score:\n best_score = score\n best_breakpoint = i_line\n # print(f\"Score {score} for line {i_line} ({line})\")\n\n # print(f\"Best score {best_score} for line {best_breakpoint} ({lines[best_breakpoint-1]})\")\n if direction == 1 and best_breakpoint < current_line or direction == -1 and best_breakpoint > current_line:\n # We don't want to shrink the view port, so we return the current line\n return current_line\n\n return best_breakpoint\n\n def expand_window(self, lines: List[str], start: int, stop: int, max_added_lines: int) -> Tuple[int, int]:\n \"\"\"\n\n Args:\n lines: All lines of the file\n start: 1-based line number of the start of the viewport\n stop: 1-based line number of the end of the viewport\n max_added_lines: Maximum number of lines to extend (separately for each side)\n\n Returns:\n Tuple of 1-based line numbers of the start and end of the viewport.\n Both inclusive.\n \"\"\"\n # print(\"Input:\", start, stop)\n assert 1 <= start <= stop <= len(lines), (start, stop, len(lines))\n if max_added_lines <= 0:\n # Already at max range, no expansion\n return start, stop\n new_start = self._find_breakpoints(lines, start, direction=-1, max_added_lines=max_added_lines)\n new_stop = self._find_breakpoints(lines, stop, direction=1, max_added_lines=max_added_lines)\n # print(f\"Expanded window is {new_start} to {new_stop}\")\n assert new_start <= new_stop, (new_start, new_stop)\n assert new_start <= start, (new_start, start)\n assert start - new_start <= max_added_lines, (start, new_start)\n assert new_stop >= stop, (new_stop, stop)\n assert new_stop - stop <= max_added_lines, (new_stop, stop)\n return new_start, new_stop", - "start_line": 260, - "end_line": 371, - "has_docstring": false, - "docstring": "", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class WindowExpander", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander.__init__": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander.__init__", - "name": "WindowExpander.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [], - "source_code": " def __init__(self, suffix: str = \"\"):\n \"\"\"Try to expand viewports to include whole functions, classes, etc. rather than\n using fixed line windows.\n\n Args:\n suffix: Filename suffix\n \"\"\"\n self.suffix = suffix\n if self.suffix:\n assert self.suffix.startswith(\".\")", - "start_line": 261, - "end_line": 270, - "has_docstring": true, - "docstring": "Try to expand viewports to include whole functions, classes, etc. rather than\nusing fixed line windows.\n\nArgs:\n suffix: Filename suffix", - "parameters": [ - "self", - "suffix" - ], - "node_type": "method", - "base_classes": null, - "class_name": "WindowExpander", - "display_name": "method WindowExpander.__init__", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander._find_breakpoints": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander._find_breakpoints", - "name": "WindowExpander._find_breakpoints", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [], - "source_code": " def _find_breakpoints(self, lines: List[str], current_line: int, direction=1, max_added_lines: int = 30) -> int:\n \"\"\"Returns 1-based line number of breakpoint. This line is meant to still be included in the viewport.\n\n Args:\n lines: List of lines of the file\n current_line: 1-based line number of the current viewport\n direction: 1 for down, -1 for up\n max_added_lines: Maximum number of lines to extend\n\n Returns:\n 1-based line number of breakpoint. This line is meant to still be included in the viewport.\n \"\"\"\n assert 1 <= current_line <= len(lines)\n assert 0 <= max_added_lines\n\n # 1. Find line range that we want to search for breakpoints in\n\n if direction == 1:\n # down\n if current_line == len(lines):\n # already last line, can't extend down\n return current_line\n iter_lines = range(current_line, 1 + min(current_line + max_added_lines, len(lines)))\n elif direction == -1:\n # up\n if current_line == 1:\n # already first line, can't extend up\n return current_line\n iter_lines = range(current_line, -1 + max(current_line - max_added_lines, 1), -1)\n else:\n msg = f\"Invalid direction {direction}\"\n raise ValueError(msg)\n\n # 2. Find the best breakpoint in the line range\n\n # Every condition gives a score, the best score is the best breakpoint\n best_score = 0\n best_breakpoint = current_line\n for i_line in iter_lines:\n next_line = None\n line = lines[i_line - 1]\n if i_line + direction in iter_lines:\n next_line = lines[i_line + direction - 1]\n score = 0\n if line == \"\":\n score = 1\n if next_line == \"\":\n # Double new blank line:\n score = 2\n if self.suffix == \".py\" and any(\n re.match(regex, line) for regex in [r\"^\\s*def\\s+\", r\"^\\s*class\\s+\", r\"^\\s*@\"]\n ):\n # We include decorators here, because they are always on top of the function/class definition\n score = 3\n if score > best_score:\n best_score = score\n best_breakpoint = i_line\n if direction == 1 and i_line != current_line:\n best_breakpoint -= 1\n if i_line == 1 or i_line == len(lines):\n score = 3\n if score > best_score:\n best_score = score\n best_breakpoint = i_line\n # print(f\"Score {score} for line {i_line} ({line})\")\n\n # print(f\"Best score {best_score} for line {best_breakpoint} ({lines[best_breakpoint-1]})\")\n if direction == 1 and best_breakpoint < current_line or direction == -1 and best_breakpoint > current_line:\n # We don't want to shrink the view port, so we return the current line\n return current_line\n\n return best_breakpoint", - "start_line": 272, - "end_line": 343, - "has_docstring": true, - "docstring": "Returns 1-based line number of breakpoint. This line is meant to still be included in the viewport.\n\nArgs:\n lines: List of lines of the file\n current_line: 1-based line number of the current viewport\n direction: 1 for down, -1 for up\n max_added_lines: Maximum number of lines to extend\n\nReturns:\n 1-based line number of breakpoint. This line is meant to still be included in the viewport.", - "parameters": [ - "self", - "lines", - "current_line", - "direction", - "max_added_lines" - ], - "node_type": "method", - "base_classes": null, - "class_name": "WindowExpander", - "display_name": "method WindowExpander._find_breakpoints", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander._find_breakpoints", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander.expand_window": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander.expand_window", - "name": "WindowExpander.expand_window", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [ - "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander._find_breakpoints" - ], - "source_code": " def expand_window(self, lines: List[str], start: int, stop: int, max_added_lines: int) -> Tuple[int, int]:\n \"\"\"\n\n Args:\n lines: All lines of the file\n start: 1-based line number of the start of the viewport\n stop: 1-based line number of the end of the viewport\n max_added_lines: Maximum number of lines to extend (separately for each side)\n\n Returns:\n Tuple of 1-based line numbers of the start and end of the viewport.\n Both inclusive.\n \"\"\"\n # print(\"Input:\", start, stop)\n assert 1 <= start <= stop <= len(lines), (start, stop, len(lines))\n if max_added_lines <= 0:\n # Already at max range, no expansion\n return start, stop\n new_start = self._find_breakpoints(lines, start, direction=-1, max_added_lines=max_added_lines)\n new_stop = self._find_breakpoints(lines, stop, direction=1, max_added_lines=max_added_lines)\n # print(f\"Expanded window is {new_start} to {new_stop}\")\n assert new_start <= new_stop, (new_start, new_stop)\n assert new_start <= start, (new_start, start)\n assert start - new_start <= max_added_lines, (start, new_start)\n assert new_stop >= stop, (new_stop, stop)\n assert new_stop - stop <= max_added_lines, (new_stop, stop)\n return new_start, new_stop", - "start_line": 345, - "end_line": 371, - "has_docstring": true, - "docstring": "Args:\n lines: All lines of the file\n start: 1-based line number of the start of the viewport\n stop: 1-based line number of the end of the viewport\n max_added_lines: Maximum number of lines to extend (separately for each side)\n\nReturns:\n Tuple of 1-based line numbers of the start and end of the viewport.\n Both inclusive.", - "parameters": [ - "self", - "lines", - "start", - "stop", - "max_added_lines" - ], - "node_type": "method", - "base_classes": null, - "class_name": "WindowExpander", - "display_name": "method WindowExpander.expand_window", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander.expand_window", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool", - "name": "EditTool", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [], - "source_code": "class EditTool:\n \"\"\"\n An filesystem editor tool that allows the agent to view, create, and edit files.\n The tool parameters are defined by Anthropic and are not editable.\n \"\"\"\n\n name = \"str_replace_editor\"\n\n def __init__(self, REGISTRY, absolute_docs_path=None):\n super().__init__()\n self._encoding = None\n self.REGISTRY = REGISTRY\n self.logs = []\n self.absolute_docs_path = Path(absolute_docs_path) if absolute_docs_path else None\n\n def _get_display_path(self, path: Path) -> str:\n \"\"\"Get path for display purposes - relative to absolute_docs_path if available\"\"\"\n if self.absolute_docs_path and path.is_absolute():\n try:\n return str(path.relative_to(self.absolute_docs_path))\n except ValueError:\n # Path is not under absolute_docs_path, return as-is\n return str(path)\n return str(path)\n\n @property\n def _file_history(self):\n return defaultdict(list, json.loads(self.REGISTRY.get(\"file_history\", \"{}\")))\n\n @_file_history.setter\n def _file_history(self, value: dict):\n self.REGISTRY[\"file_history\"] = json.dumps(value)\n\n def __call__(\n self,\n *,\n command: Command,\n path: str,\n file_text: Optional[str] = None,\n view_range: Optional[List[int]] = None,\n old_str: Optional[str] = None,\n new_str: Optional[str] = None,\n insert_line: Optional[int] = None,\n **kwargs,\n ):\n _path = Path(path)\n if not self.validate_path(command, _path):\n return\n if command == \"view\":\n return self.view(_path, view_range)\n elif command == \"create\":\n if file_text is None:\n self.logs.append(\"Parameter `file_text` is required for command: create\")\n return\n self.create_file(_path, file_text)\n return None\n elif command == \"str_replace\":\n if old_str is None:\n self.logs.append(\"Parameter `old_str` is required for command: str_replace\")\n return\n return self.str_replace(_path, old_str, new_str)\n elif command == \"insert\":\n if insert_line is None:\n self.logs.append(\"Parameter `insert_line` is required for command: insert\")\n return\n if new_str is None:\n self.logs.append(\"Parameter `new_str` is required for command: insert\")\n return\n return self.insert(_path, insert_line, new_str)\n elif command == \"undo_edit\":\n return self.undo_edit(_path)\n self.logs.append(\n f'Unrecognized command {command}. The allowed commands for the {self.name} tool are: \"view\", \"create\", \"str_replace\", \"insert\", \"undo_edit\"'\n )\n return\n\n def validate_path(self, command: str, path: Path):\n \"\"\"\n Check that the path/command combination is valid.\n \"\"\"\n # Check if its an absolute path\n if not path.is_absolute():\n suggested_path = Path.cwd() / path\n self.logs.append(\n f\"The path {self._get_display_path(path)} is not an absolute path, it should start with `/`. Maybe you meant {self._get_display_path(suggested_path)}?\"\n )\n return False\n # Check if path exists\n if not path.exists() and command != \"create\":\n self.logs.append(f\"The path {self._get_display_path(path)} does not exist. Please provide a valid path.\")\n return False\n if path.exists() and command == \"create\":\n self.logs.append(f\"File already exists at: {self._get_display_path(path)}. Cannot overwrite files using command `create`.\")\n return False\n # Check if the path points to a directory\n if path.is_dir():\n if command != \"view\":\n self.logs.append(f\"The path {self._get_display_path(path)} is a directory and only the `view` command can be used on directories\")\n return False\n return True\n\n def create_file(self, path: Path, file_text: str):\n if not path.parent.exists():\n self.logs.append(f\"The parent directory {self._get_display_path(path.parent)} does not exist. Please create it first.\")\n return\n self.write_file(path, file_text)\n self._file_history[path].append(file_text)\n self.logs.append(f\"File created successfully at: {self._get_display_path(path)}\")\n\n def view(self, path: Path, view_range: Optional[List[int]] = None):\n \"\"\"Implement the view command\"\"\"\n if path.is_dir():\n if view_range:\n self.logs.append(\"The `view_range` parameter is not allowed when `path` points to a directory.\")\n return\n\n out = subprocess.run(\n rf\"find {path} -maxdepth 2 -not -path '*/\\.*'\",\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n # Use errors=\"replace\" so non-UTF-8 bytes (e.g. GBK-encoded filenames on Windows) don't crash decoding.\n stdout = out.stdout.decode(\"utf-8\", errors=\"replace\")\n stderr = out.stderr.decode(\"utf-8\", errors=\"replace\")\n\n if not stderr:\n stdout = stdout.replace(str(path), self._get_display_path(path))\n stdout = f\"Here's the files and directories up to 2 levels deep in {self._get_display_path(path)}, excluding hidden items:\\n{stdout}\\n\"\n self.logs.append(stdout)\n return\n\n file_content = self.read_file(path)\n if view_range:\n if len(view_range) != 2 or not all(isinstance(i, int) for i in view_range):\n self.logs.append(\"Invalid `view_range`. It should be a list of two integers.\")\n return\n file_lines = file_content.split(\"\\n\")\n n_lines_file = len(file_lines)\n init_line, final_line = view_range\n if init_line < 1 or init_line > n_lines_file:\n self.logs.append(\n f\"Invalid `view_range`: {view_range}. Its first element `{init_line}` should be within the range of lines of the file: {[1, n_lines_file]}\"\n )\n return\n if final_line > n_lines_file:\n self.logs.append(\n f\"Invalid `view_range`: {view_range}. Its second element `{final_line}` should be smaller than the number of lines in the file: `{n_lines_file}`\"\n )\n return\n if final_line != -1 and final_line < init_line:\n self.logs.append(\n f\"Invalid `view_range`: {view_range}. Its second element `{final_line}` should be larger or equal than its first `{init_line}`\"\n )\n return\n\n if final_line == -1:\n final_line = n_lines_file\n\n # Expand the viewport to include the whole function or class\n init_line, final_line = WindowExpander(suffix=path.suffix).expand_window(\n file_lines, init_line, final_line, max_added_lines=MAX_WINDOW_EXPANSION_VIEW\n )\n\n file_content = \"\\n\".join(file_lines[init_line - 1 : final_line])\n else:\n if path.suffix == \".py\" and len(file_content) > MAX_RESPONSE_LEN and USE_FILEMAP:\n try:\n filemap = Filemap().show_filemap(file_content, encoding=self._encoding or \"utf-8\")\n except Exception:\n # If we fail to show the filemap, just show the truncated file content\n pass\n else:\n self.logs.append(\n \"This file is too large to display entirely. Showing abbreviated version. \"\n \"Please use `str_replace_editor view` with the `view_range` parameter to show selected lines next.\"\n )\n filemap = maybe_truncate(filemap.expandtabs())\n self.logs.append(filemap)\n self.logs.append(\n \"The above file has been abbreviated. Please use `str_replace editor view` with `view_range` to look at relevant files in detail.\"\n )\n return\n # Else just show\n init_line = 1\n\n # init_line is 1-based\n self.logs.append(self._make_output(file_content, self._get_display_path(path), init_line=init_line))\n\n def str_replace(self, path: Path, old_str: str, new_str: Optional[str]):\n \"\"\"Implement the str_replace command, which replaces old_str with new_str in the file content\"\"\"\n # Read the file content\n file_content = self.read_file(path).expandtabs()\n old_str = old_str.expandtabs()\n new_str = new_str.expandtabs() if new_str is not None else \"\"\n\n # Check if old_str is unique in the file\n occurrences = file_content.count(old_str)\n if occurrences == 0:\n self.logs.append(f\"No replacement was performed, old_str `{old_str}` did not appear verbatim in {self._get_display_path(path)}.\")\n return\n elif occurrences > 1:\n file_content_lines = file_content.split(\"\\n\")\n lines = [idx + 1 for idx, line in enumerate(file_content_lines) if old_str in line]\n self.logs.append(\n f\"No replacement was performed. Multiple occurrences of old_str `{old_str}` in lines {lines}. Please ensure it is unique\"\n )\n return\n\n if new_str == old_str:\n self.logs.append(f\"No replacement was performed, old_str `{old_str}` is the same as new_str `{new_str}`.\")\n return\n\n pre_edit_lint = \"\"\n if USE_LINTER:\n try:\n pre_edit_lint = flake8(str(path))\n except Exception as e:\n self.logs.append(f\"Warning: Failed to run pre-edit linter on {path}: {e}\")\n\n # Replace old_str with new_str\n new_file_content = file_content.replace(old_str, new_str)\n\n # Write the new content to the file\n self.write_file(path, new_file_content)\n\n post_edit_lint = \"\"\n if USE_LINTER:\n try:\n post_edit_lint = flake8(str(path))\n except Exception as e:\n self.logs.append(f\"Warning: Failed to run post-edit linter on {path}: {e}\")\n\n epilogue = \"\"\n if post_edit_lint:\n ...\n replacement_window_start_line = file_content.split(old_str)[0].count(\"\\n\") + 1\n replacement_lines = len(new_str.split(\"\\n\"))\n replacement_window_end_line = replacement_window_start_line + replacement_lines - 1\n replacement_window = (replacement_window_start_line, replacement_window_end_line)\n errors = format_flake8_output(\n post_edit_lint,\n previous_errors_string=pre_edit_lint,\n replacement_window=replacement_window,\n replacement_n_lines=replacement_lines,\n )\n if errors.strip():\n epilogue = LINT_WARNING_TEMPLATE.format(errors=errors)\n\n # Save the content to history\n self._file_history[path].append(file_content)\n\n # Create a snippet of the edited section\n replacement_line = file_content.split(old_str)[0].count(\"\\n\")\n start_line = max(1, replacement_line - SNIPPET_LINES)\n end_line = min(replacement_line + SNIPPET_LINES + new_str.count(\"\\n\"), len(new_file_content.splitlines()))\n start_line, end_line = WindowExpander(suffix=path.suffix).expand_window(\n new_file_content.split(\"\\n\"), start_line, end_line, max_added_lines=MAX_WINDOW_EXPANSION_EDIT_CONFIRM\n )\n snippet = \"\\n\".join(new_file_content.split(\"\\n\")[start_line - 1 : end_line])\n\n # Prepare the success message\n success_msg = f\"The file {self._get_display_path(path)} has been edited. \"\n success_msg += self._make_output(snippet, f\"a snippet of {self._get_display_path(path)}\", start_line)\n success_msg += \"Review the changes and make sure they are as expected. Edit the file again if necessary.\"\n success_msg += epilogue\n\n self.logs.append(success_msg)\n\n def insert(self, path: Path, insert_line: int, new_str: str):\n \"\"\"Implement the insert command, which inserts new_str at the specified line in the file content.\"\"\"\n file_text = self.read_file(path).expandtabs()\n new_str = new_str.expandtabs()\n file_text_lines = file_text.split(\"\\n\")\n n_lines_file = len(file_text_lines)\n\n if insert_line < 0 or insert_line > n_lines_file:\n self.logs.append(\n f\"Invalid `insert_line` parameter: {insert_line}. It should be within the range of lines of the file: {[0, n_lines_file]}\"\n )\n return\n\n new_str_lines = new_str.split(\"\\n\")\n new_file_text_lines = file_text_lines[:insert_line] + new_str_lines + file_text_lines[insert_line:]\n snippet_lines = (\n file_text_lines[max(0, insert_line - SNIPPET_LINES) : insert_line]\n + new_str_lines\n + file_text_lines[insert_line : insert_line + SNIPPET_LINES]\n )\n\n new_file_text = \"\\n\".join(new_file_text_lines)\n snippet = \"\\n\".join(snippet_lines)\n\n self.write_file(path, new_file_text)\n self._file_history[path].append(file_text)\n\n # todo: Also expand these windows\n\n success_msg = f\"The file {self._get_display_path(path)} has been edited. \"\n success_msg += self._make_output(\n snippet,\n \"a snippet of the edited file\",\n max(1, insert_line - SNIPPET_LINES + 1),\n )\n success_msg += \"Review the changes and make sure they are as expected (correct indentation, no duplicate lines, etc). Edit the file again if necessary.\"\n self.logs.append(success_msg)\n\n def undo_edit(self, path: Path):\n \"\"\"Implement the undo_edit command.\"\"\"\n if not self._file_history[path]:\n self.logs.append(f\"No edit history found for {self._get_display_path(path)}.\")\n return\n\n old_text = self._file_history[path].pop()\n self.write_file(path, old_text)\n\n self.logs.append(f\"Last edit to {self._get_display_path(path)} undone successfully. {self._make_output(old_text, self._get_display_path(path))}\")\n\n def read_file(self, path: Path):\n \"\"\"Read the content of a file from a given path; raise a ToolError if an error occurs.\"\"\"\n encodings = [\n (None, None),\n (\"utf-8\", None),\n (\"latin-1\", None),\n (\"utf-8\", \"replace\"),\n ]\n exception = None\n for self._encoding, errors in encodings:\n try:\n text = path.read_text(encoding=self._encoding, errors=errors)\n except UnicodeDecodeError as e:\n exception = e\n else:\n break\n else:\n self.logs.append(f\"Ran into UnicodeDecodeError {exception} while trying to read {self._get_display_path(path)}\")\n return\n return text\n\n def write_file(self, path: Path, file: str):\n \"\"\"Write the content of a file to a given path; raise a ToolError if an error occurs.\"\"\"\n try:\n path.write_text(file, encoding=self._encoding or \"utf-8\")\n except Exception as e:\n self.logs.append(f\"Ran into {e} while trying to write to {self._get_display_path(path)}\")\n return\n\n def _make_output(\n self,\n file_content: str,\n file_descriptor: str,\n init_line: int = 1,\n expand_tabs: bool = True,\n ):\n \"\"\"Generate output for the CLI based on the content of a file.\"\"\"\n file_content = maybe_truncate(file_content)\n if expand_tabs:\n file_content = file_content.expandtabs()\n file_content = \"\\n\".join([f\"{i + init_line:6}\\t{line}\" for i, line in enumerate(file_content.split(\"\\n\"))])\n return f\"Here's the result of running `cat -n` on {file_descriptor}:\\n\" + file_content + \"\\n\"", - "start_line": 374, - "end_line": 733, - "has_docstring": true, - "docstring": "An filesystem editor tool that allows the agent to view, create, and edit files.\nThe tool parameters are defined by Anthropic and are not editable.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class EditTool", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.__init__": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.__init__", - "name": "EditTool.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [], - "source_code": " def __init__(self, REGISTRY, absolute_docs_path=None):\n super().__init__()\n self._encoding = None\n self.REGISTRY = REGISTRY\n self.logs = []\n self.absolute_docs_path = Path(absolute_docs_path) if absolute_docs_path else None", - "start_line": 382, - "end_line": 387, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "REGISTRY", - "absolute_docs_path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "EditTool", - "display_name": "method EditTool.__init__", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._get_display_path": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._get_display_path", - "name": "EditTool._get_display_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [], - "source_code": " def _get_display_path(self, path: Path) -> str:\n \"\"\"Get path for display purposes - relative to absolute_docs_path if available\"\"\"\n if self.absolute_docs_path and path.is_absolute():\n try:\n return str(path.relative_to(self.absolute_docs_path))\n except ValueError:\n # Path is not under absolute_docs_path, return as-is\n return str(path)\n return str(path)", - "start_line": 389, - "end_line": 397, - "has_docstring": true, - "docstring": "Get path for display purposes - relative to absolute_docs_path if available", - "parameters": [ - "self", - "path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "EditTool", - "display_name": "method EditTool._get_display_path", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._get_display_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._file_history": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._file_history", - "name": "EditTool._file_history", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def _file_history(self, value: dict):\n self.REGISTRY[\"file_history\"] = json.dumps(value)", - "start_line": 404, - "end_line": 405, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "value" - ], - "node_type": "method", - "base_classes": null, - "class_name": "EditTool", - "display_name": "method EditTool._file_history", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._file_history", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.__call__": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.__call__", - "name": "EditTool.__call__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [ - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.validate_path", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.str_replace", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.view", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.create_file", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.insert", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.undo_edit" - ], - "source_code": " def __call__(\n self,\n *,\n command: Command,\n path: str,\n file_text: Optional[str] = None,\n view_range: Optional[List[int]] = None,\n old_str: Optional[str] = None,\n new_str: Optional[str] = None,\n insert_line: Optional[int] = None,\n **kwargs,\n ):\n _path = Path(path)\n if not self.validate_path(command, _path):\n return\n if command == \"view\":\n return self.view(_path, view_range)\n elif command == \"create\":\n if file_text is None:\n self.logs.append(\"Parameter `file_text` is required for command: create\")\n return\n self.create_file(_path, file_text)\n return None\n elif command == \"str_replace\":\n if old_str is None:\n self.logs.append(\"Parameter `old_str` is required for command: str_replace\")\n return\n return self.str_replace(_path, old_str, new_str)\n elif command == \"insert\":\n if insert_line is None:\n self.logs.append(\"Parameter `insert_line` is required for command: insert\")\n return\n if new_str is None:\n self.logs.append(\"Parameter `new_str` is required for command: insert\")\n return\n return self.insert(_path, insert_line, new_str)\n elif command == \"undo_edit\":\n return self.undo_edit(_path)\n self.logs.append(\n f'Unrecognized command {command}. The allowed commands for the {self.name} tool are: \"view\", \"create\", \"str_replace\", \"insert\", \"undo_edit\"'\n )\n return", - "start_line": 407, - "end_line": 448, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "EditTool", - "display_name": "method EditTool.__call__", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.__call__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.validate_path": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.validate_path", - "name": "EditTool.validate_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [ - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._get_display_path" - ], - "source_code": " def validate_path(self, command: str, path: Path):\n \"\"\"\n Check that the path/command combination is valid.\n \"\"\"\n # Check if its an absolute path\n if not path.is_absolute():\n suggested_path = Path.cwd() / path\n self.logs.append(\n f\"The path {self._get_display_path(path)} is not an absolute path, it should start with `/`. Maybe you meant {self._get_display_path(suggested_path)}?\"\n )\n return False\n # Check if path exists\n if not path.exists() and command != \"create\":\n self.logs.append(f\"The path {self._get_display_path(path)} does not exist. Please provide a valid path.\")\n return False\n if path.exists() and command == \"create\":\n self.logs.append(f\"File already exists at: {self._get_display_path(path)}. Cannot overwrite files using command `create`.\")\n return False\n # Check if the path points to a directory\n if path.is_dir():\n if command != \"view\":\n self.logs.append(f\"The path {self._get_display_path(path)} is a directory and only the `view` command can be used on directories\")\n return False\n return True", - "start_line": 450, - "end_line": 473, - "has_docstring": true, - "docstring": "Check that the path/command combination is valid.", - "parameters": [ - "self", - "command", - "path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "EditTool", - "display_name": "method EditTool.validate_path", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.validate_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.create_file": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.create_file", - "name": "EditTool.create_file", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [ - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.write_file", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._get_display_path" - ], - "source_code": " def create_file(self, path: Path, file_text: str):\n if not path.parent.exists():\n self.logs.append(f\"The parent directory {self._get_display_path(path.parent)} does not exist. Please create it first.\")\n return\n self.write_file(path, file_text)\n self._file_history[path].append(file_text)\n self.logs.append(f\"File created successfully at: {self._get_display_path(path)}\")", - "start_line": 475, - "end_line": 481, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "path", - "file_text" - ], - "node_type": "method", - "base_classes": null, - "class_name": "EditTool", - "display_name": "method EditTool.create_file", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.create_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.view": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.view", - "name": "EditTool.view", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [ - "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander.expand_window", - "codewiki/src/be/agent_tools/str_replace_editor.py::maybe_truncate", - "codewiki/src/be/agent_tools/str_replace_editor.py::Filemap.show_filemap", - "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.run", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.read_file", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._make_output", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._get_display_path", - "codewiki/src/be/agent_tools/str_replace_editor.py::Filemap" - ], - "source_code": " def view(self, path: Path, view_range: Optional[List[int]] = None):\n \"\"\"Implement the view command\"\"\"\n if path.is_dir():\n if view_range:\n self.logs.append(\"The `view_range` parameter is not allowed when `path` points to a directory.\")\n return\n\n out = subprocess.run(\n rf\"find {path} -maxdepth 2 -not -path '*/\\.*'\",\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n # Use errors=\"replace\" so non-UTF-8 bytes (e.g. GBK-encoded filenames on Windows) don't crash decoding.\n stdout = out.stdout.decode(\"utf-8\", errors=\"replace\")\n stderr = out.stderr.decode(\"utf-8\", errors=\"replace\")\n\n if not stderr:\n stdout = stdout.replace(str(path), self._get_display_path(path))\n stdout = f\"Here's the files and directories up to 2 levels deep in {self._get_display_path(path)}, excluding hidden items:\\n{stdout}\\n\"\n self.logs.append(stdout)\n return\n\n file_content = self.read_file(path)\n if view_range:\n if len(view_range) != 2 or not all(isinstance(i, int) for i in view_range):\n self.logs.append(\"Invalid `view_range`. It should be a list of two integers.\")\n return\n file_lines = file_content.split(\"\\n\")\n n_lines_file = len(file_lines)\n init_line, final_line = view_range\n if init_line < 1 or init_line > n_lines_file:\n self.logs.append(\n f\"Invalid `view_range`: {view_range}. Its first element `{init_line}` should be within the range of lines of the file: {[1, n_lines_file]}\"\n )\n return\n if final_line > n_lines_file:\n self.logs.append(\n f\"Invalid `view_range`: {view_range}. Its second element `{final_line}` should be smaller than the number of lines in the file: `{n_lines_file}`\"\n )\n return\n if final_line != -1 and final_line < init_line:\n self.logs.append(\n f\"Invalid `view_range`: {view_range}. Its second element `{final_line}` should be larger or equal than its first `{init_line}`\"\n )\n return\n\n if final_line == -1:\n final_line = n_lines_file\n\n # Expand the viewport to include the whole function or class\n init_line, final_line = WindowExpander(suffix=path.suffix).expand_window(\n file_lines, init_line, final_line, max_added_lines=MAX_WINDOW_EXPANSION_VIEW\n )\n\n file_content = \"\\n\".join(file_lines[init_line - 1 : final_line])\n else:\n if path.suffix == \".py\" and len(file_content) > MAX_RESPONSE_LEN and USE_FILEMAP:\n try:\n filemap = Filemap().show_filemap(file_content, encoding=self._encoding or \"utf-8\")\n except Exception:\n # If we fail to show the filemap, just show the truncated file content\n pass\n else:\n self.logs.append(\n \"This file is too large to display entirely. Showing abbreviated version. \"\n \"Please use `str_replace_editor view` with the `view_range` parameter to show selected lines next.\"\n )\n filemap = maybe_truncate(filemap.expandtabs())\n self.logs.append(filemap)\n self.logs.append(\n \"The above file has been abbreviated. Please use `str_replace editor view` with `view_range` to look at relevant files in detail.\"\n )\n return\n # Else just show\n init_line = 1\n\n # init_line is 1-based\n self.logs.append(self._make_output(file_content, self._get_display_path(path), init_line=init_line))", - "start_line": 483, - "end_line": 561, - "has_docstring": true, - "docstring": "Implement the view command", - "parameters": [ - "self", - "path", - "view_range" - ], - "node_type": "method", - "base_classes": null, - "class_name": "EditTool", - "display_name": "method EditTool.view", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.view", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.str_replace": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.str_replace", - "name": "EditTool.str_replace", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [ - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.write_file", - "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander.expand_window", - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter.format", - "codewiki/src/be/agent_tools/str_replace_editor.py::WindowExpander", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.read_file", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._make_output", - "codewiki/src/be/agent_tools/str_replace_editor.py::flake8", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._get_display_path", - "codewiki/src/be/agent_tools/str_replace_editor.py::format_flake8_output" - ], - "source_code": " def str_replace(self, path: Path, old_str: str, new_str: Optional[str]):\n \"\"\"Implement the str_replace command, which replaces old_str with new_str in the file content\"\"\"\n # Read the file content\n file_content = self.read_file(path).expandtabs()\n old_str = old_str.expandtabs()\n new_str = new_str.expandtabs() if new_str is not None else \"\"\n\n # Check if old_str is unique in the file\n occurrences = file_content.count(old_str)\n if occurrences == 0:\n self.logs.append(f\"No replacement was performed, old_str `{old_str}` did not appear verbatim in {self._get_display_path(path)}.\")\n return\n elif occurrences > 1:\n file_content_lines = file_content.split(\"\\n\")\n lines = [idx + 1 for idx, line in enumerate(file_content_lines) if old_str in line]\n self.logs.append(\n f\"No replacement was performed. Multiple occurrences of old_str `{old_str}` in lines {lines}. Please ensure it is unique\"\n )\n return\n\n if new_str == old_str:\n self.logs.append(f\"No replacement was performed, old_str `{old_str}` is the same as new_str `{new_str}`.\")\n return\n\n pre_edit_lint = \"\"\n if USE_LINTER:\n try:\n pre_edit_lint = flake8(str(path))\n except Exception as e:\n self.logs.append(f\"Warning: Failed to run pre-edit linter on {path}: {e}\")\n\n # Replace old_str with new_str\n new_file_content = file_content.replace(old_str, new_str)\n\n # Write the new content to the file\n self.write_file(path, new_file_content)\n\n post_edit_lint = \"\"\n if USE_LINTER:\n try:\n post_edit_lint = flake8(str(path))\n except Exception as e:\n self.logs.append(f\"Warning: Failed to run post-edit linter on {path}: {e}\")\n\n epilogue = \"\"\n if post_edit_lint:\n ...\n replacement_window_start_line = file_content.split(old_str)[0].count(\"\\n\") + 1\n replacement_lines = len(new_str.split(\"\\n\"))\n replacement_window_end_line = replacement_window_start_line + replacement_lines - 1\n replacement_window = (replacement_window_start_line, replacement_window_end_line)\n errors = format_flake8_output(\n post_edit_lint,\n previous_errors_string=pre_edit_lint,\n replacement_window=replacement_window,\n replacement_n_lines=replacement_lines,\n )\n if errors.strip():\n epilogue = LINT_WARNING_TEMPLATE.format(errors=errors)\n\n # Save the content to history\n self._file_history[path].append(file_content)\n\n # Create a snippet of the edited section\n replacement_line = file_content.split(old_str)[0].count(\"\\n\")\n start_line = max(1, replacement_line - SNIPPET_LINES)\n end_line = min(replacement_line + SNIPPET_LINES + new_str.count(\"\\n\"), len(new_file_content.splitlines()))\n start_line, end_line = WindowExpander(suffix=path.suffix).expand_window(\n new_file_content.split(\"\\n\"), start_line, end_line, max_added_lines=MAX_WINDOW_EXPANSION_EDIT_CONFIRM\n )\n snippet = \"\\n\".join(new_file_content.split(\"\\n\")[start_line - 1 : end_line])\n\n # Prepare the success message\n success_msg = f\"The file {self._get_display_path(path)} has been edited. \"\n success_msg += self._make_output(snippet, f\"a snippet of {self._get_display_path(path)}\", start_line)\n success_msg += \"Review the changes and make sure they are as expected. Edit the file again if necessary.\"\n success_msg += epilogue\n\n self.logs.append(success_msg)", - "start_line": 563, - "end_line": 641, - "has_docstring": true, - "docstring": "Implement the str_replace command, which replaces old_str with new_str in the file content", - "parameters": [ - "self", - "path", - "old_str", - "new_str" - ], - "node_type": "method", - "base_classes": null, - "class_name": "EditTool", - "display_name": "method EditTool.str_replace", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.str_replace", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.insert": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.insert", - "name": "EditTool.insert", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [ - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.read_file", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._make_output", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.write_file", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._get_display_path" - ], - "source_code": " def insert(self, path: Path, insert_line: int, new_str: str):\n \"\"\"Implement the insert command, which inserts new_str at the specified line in the file content.\"\"\"\n file_text = self.read_file(path).expandtabs()\n new_str = new_str.expandtabs()\n file_text_lines = file_text.split(\"\\n\")\n n_lines_file = len(file_text_lines)\n\n if insert_line < 0 or insert_line > n_lines_file:\n self.logs.append(\n f\"Invalid `insert_line` parameter: {insert_line}. It should be within the range of lines of the file: {[0, n_lines_file]}\"\n )\n return\n\n new_str_lines = new_str.split(\"\\n\")\n new_file_text_lines = file_text_lines[:insert_line] + new_str_lines + file_text_lines[insert_line:]\n snippet_lines = (\n file_text_lines[max(0, insert_line - SNIPPET_LINES) : insert_line]\n + new_str_lines\n + file_text_lines[insert_line : insert_line + SNIPPET_LINES]\n )\n\n new_file_text = \"\\n\".join(new_file_text_lines)\n snippet = \"\\n\".join(snippet_lines)\n\n self.write_file(path, new_file_text)\n self._file_history[path].append(file_text)\n\n # todo: Also expand these windows\n\n success_msg = f\"The file {self._get_display_path(path)} has been edited. \"\n success_msg += self._make_output(\n snippet,\n \"a snippet of the edited file\",\n max(1, insert_line - SNIPPET_LINES + 1),\n )\n success_msg += \"Review the changes and make sure they are as expected (correct indentation, no duplicate lines, etc). Edit the file again if necessary.\"\n self.logs.append(success_msg)", - "start_line": 643, - "end_line": 679, - "has_docstring": true, - "docstring": "Implement the insert command, which inserts new_str at the specified line in the file content.", - "parameters": [ - "self", - "path", - "insert_line", - "new_str" - ], - "node_type": "method", - "base_classes": null, - "class_name": "EditTool", - "display_name": "method EditTool.insert", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.insert", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.undo_edit": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.undo_edit", - "name": "EditTool.undo_edit", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [ - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.write_file", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._make_output", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._get_display_path" - ], - "source_code": " def undo_edit(self, path: Path):\n \"\"\"Implement the undo_edit command.\"\"\"\n if not self._file_history[path]:\n self.logs.append(f\"No edit history found for {self._get_display_path(path)}.\")\n return\n\n old_text = self._file_history[path].pop()\n self.write_file(path, old_text)\n\n self.logs.append(f\"Last edit to {self._get_display_path(path)} undone successfully. {self._make_output(old_text, self._get_display_path(path))}\")", - "start_line": 681, - "end_line": 690, - "has_docstring": true, - "docstring": "Implement the undo_edit command.", - "parameters": [ - "self", - "path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "EditTool", - "display_name": "method EditTool.undo_edit", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.undo_edit", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.read_file": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.read_file", - "name": "EditTool.read_file", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [ - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._get_display_path" - ], - "source_code": " def read_file(self, path: Path):\n \"\"\"Read the content of a file from a given path; raise a ToolError if an error occurs.\"\"\"\n encodings = [\n (None, None),\n (\"utf-8\", None),\n (\"latin-1\", None),\n (\"utf-8\", \"replace\"),\n ]\n exception = None\n for self._encoding, errors in encodings:\n try:\n text = path.read_text(encoding=self._encoding, errors=errors)\n except UnicodeDecodeError as e:\n exception = e\n else:\n break\n else:\n self.logs.append(f\"Ran into UnicodeDecodeError {exception} while trying to read {self._get_display_path(path)}\")\n return\n return text", - "start_line": 692, - "end_line": 711, - "has_docstring": true, - "docstring": "Read the content of a file from a given path; raise a ToolError if an error occurs.", - "parameters": [ - "self", - "path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "EditTool", - "display_name": "method EditTool.read_file", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.read_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.write_file": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.write_file", - "name": "EditTool.write_file", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [ - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._get_display_path" - ], - "source_code": " def write_file(self, path: Path, file: str):\n \"\"\"Write the content of a file to a given path; raise a ToolError if an error occurs.\"\"\"\n try:\n path.write_text(file, encoding=self._encoding or \"utf-8\")\n except Exception as e:\n self.logs.append(f\"Ran into {e} while trying to write to {self._get_display_path(path)}\")\n return", - "start_line": 713, - "end_line": 719, - "has_docstring": true, - "docstring": "Write the content of a file to a given path; raise a ToolError if an error occurs.", - "parameters": [ - "self", - "path", - "file" - ], - "node_type": "method", - "base_classes": null, - "class_name": "EditTool", - "display_name": "method EditTool.write_file", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.write_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._make_output": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._make_output", - "name": "EditTool._make_output", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [ - "codewiki/src/be/agent_tools/str_replace_editor.py::maybe_truncate" - ], - "source_code": " def _make_output(\n self,\n file_content: str,\n file_descriptor: str,\n init_line: int = 1,\n expand_tabs: bool = True,\n ):\n \"\"\"Generate output for the CLI based on the content of a file.\"\"\"\n file_content = maybe_truncate(file_content)\n if expand_tabs:\n file_content = file_content.expandtabs()\n file_content = \"\\n\".join([f\"{i + init_line:6}\\t{line}\" for i, line in enumerate(file_content.split(\"\\n\"))])\n return f\"Here's the result of running `cat -n` on {file_descriptor}:\\n\" + file_content + \"\\n\"", - "start_line": 721, - "end_line": 733, - "has_docstring": true, - "docstring": "Generate output for the CLI based on the content of a file.", - "parameters": [ - "self", - "file_content", - "file_descriptor", - "init_line", - "expand_tabs" - ], - "node_type": "method", - "base_classes": null, - "class_name": "EditTool", - "display_name": "method EditTool._make_output", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool._make_output", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/agent_tools/str_replace_editor.py::str_replace_editor": { - "id": "codewiki/src/be/agent_tools/str_replace_editor.py::str_replace_editor", - "name": "str_replace_editor", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/agent_tools/str_replace_editor.py", - "relative_path": "codewiki/src/be/agent_tools/str_replace_editor.py", - "depends_on": [ - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool", - "codewiki/src/be/utils.py::validate_mermaid_diagrams" - ], - "source_code": "async def str_replace_editor(\n ctx: RunContext[CodeWikiDeps],\n working_dir: Literal[\"repo\", \"docs\"],\n command: Literal[\"view\", \"create\", \"str_replace\", \"insert\", \"undo_edit\"],\n path: Optional[str] = None,\n file: Optional[str] = None,\n file_text: Optional[str] = None,\n view_range: ViewRange = None,\n old_str: Optional[str] = None,\n new_str: Optional[str] = None,\n insert_line: InsertLine = None,\n) -> str:\n \"\"\"\n Custom editing tool for viewing, creating and editing files\n * State is persistent across command calls and discussions with the user\n * If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep.\n * The `create` command cannot be used if the specified `path` already exists as a file\n * If a `command` generates a long output, it will be truncated and marked with ``\n * The `undo_edit` command will revert the last edit made to the file at `path`\n * Only `view` command is allowed when `working_dir` is `repo`.\n\n Args:\n working_dir: The working directory to use. Choose `repo` to work with the repository files, or `docs` to work with the generated documentation files.\n command: The command to run. Allowed options are: `view`, `create`, `str_replace`, `insert`, `undo_edit`.\n path: Path to file or directory, e.g. `./chat_core.md` or `./agents/`\n file: Alias for `path` parameter (for compatibility with some models)\n file_text: Required parameter of `create` command, with the content of the file to be created.\n view_range: Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.\n old_str: Required parameter of `str_replace` command containing the string in `path` to replace.\n new_str: Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert.\n \"\"\"\n\n # Handle both `path` and `file` parameters for model compatibility\n if path is None and file is None:\n return \"Error: Either `path` or `file` parameter must be provided.\"\n if path is None:\n path = file\n\n tool = EditTool(ctx.deps.registry, ctx.deps.absolute_docs_path)\n if working_dir == \"docs\":\n absolute_path = str(Path(ctx.deps.absolute_docs_path) / path)\n else:\n absolute_path = str(Path(ctx.deps.absolute_repo_path) / path)\n\n # validate command\n if command != \"view\" and working_dir == \"repo\":\n return \"The `view` command is the only allowed command when `working_dir` is `repo`.\"\n\n tool(\n command=command,\n path=absolute_path,\n file_text=file_text,\n view_range=view_range,\n old_str=old_str,\n new_str=new_str,\n insert_line=insert_line,\n )\n\n result = \"\\n\".join(tool.logs)\n\n if command != \"view\" and path.endswith(\".md\"):\n mermaid_validation = await validate_mermaid_diagrams(absolute_path, path)\n result = result + \"\\n---------- Mermaid validation ----------\\n\" + mermaid_validation\n\n return result", - "start_line": 735, - "end_line": 799, - "has_docstring": true, - "docstring": "Custom editing tool for viewing, creating and editing files\n * State is persistent across command calls and discussions with the user\n * If `path` is a file, `view` displays the result of applying `cat -n`. If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep.\n * The `create` command cannot be used if the specified `path` already exists as a file\n * If a `command` generates a long output, it will be truncated and marked with ``\n * The `undo_edit` command will revert the last edit made to the file at `path`\n * Only `view` command is allowed when `working_dir` is `repo`.\n\nArgs:\n working_dir: The working directory to use. Choose `repo` to work with the repository files, or `docs` to work with the generated documentation files.\n command: The command to run. Allowed options are: `view`, `create`, `str_replace`, `insert`, `undo_edit`.\n path: Path to file or directory, e.g. `./chat_core.md` or `./agents/`\n file: Alias for `path` parameter (for compatibility with some models)\n file_text: Required parameter of `create` command, with the content of the file to be created.\n view_range: Optional parameter of `view` command when `path` points to a file. If none is given, the full file is shown. If provided, the file will be shown in the indicated line number range, e.g. [11, 12] will show lines 11 and 12. Indexing at 1 to start. Setting `[start_line, -1]` shows all lines from `start_line` to the end of the file.\n old_str: Required parameter of `str_replace` command containing the string in `path` to replace.\n new_str: Optional parameter of `str_replace` command containing the new string (if not given, no string will be added). Required parameter of `insert` command containing the string to insert.", - "parameters": [ - "ctx", - "working_dir", - "command", - "path", - "file", - "file_text", - "view_range", - "old_str", - "new_str", - "insert_line" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function str_replace_editor", - "component_id": "codewiki/src/be/agent_tools/str_replace_editor.py::str_replace_editor", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/backend.py::is_caw_provider": { - "id": "codewiki/src/be/backend.py::is_caw_provider", - "name": "is_caw_provider", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/backend.py", - "relative_path": "codewiki/src/be/backend.py", - "depends_on": [], - "source_code": "def is_caw_provider(provider: str) -> bool:\n \"\"\"Return True if *provider* uses caw (CLI subscription mode).\"\"\"\n return provider in CAW_PROVIDERS", - "start_line": 30, - "end_line": 32, - "has_docstring": true, - "docstring": "Return True if *provider* uses caw (CLI subscription mode).", - "parameters": [ - "provider" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function is_caw_provider", - "component_id": "codewiki/src/be/backend.py::is_caw_provider", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/backend.py::LLMBackend": { - "id": "codewiki/src/be/backend.py::LLMBackend", - "name": "LLMBackend", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/backend.py", - "relative_path": "codewiki/src/be/backend.py", - "depends_on": [], - "source_code": "class LLMBackend(abc.ABC):\n \"\"\"Abstract LLM backend used by the documentation generator.\"\"\"\n\n @abc.abstractmethod\n def complete(\n self,\n prompt: str,\n *,\n model: str | None = None,\n ) -> str:\n \"\"\"Single-shot text completion.\"\"\"\n\n @abc.abstractmethod\n async def run_module_agent(\n self,\n module_name: str,\n components: Dict[str, \"Node\"],\n core_component_ids: List[str],\n module_path: List[str],\n working_dir: str,\n ) -> Dict[str, Any]:\n \"\"\"Run the per-module agent loop. Returns the updated module_tree dict.\"\"\"", - "start_line": 35, - "end_line": 56, - "has_docstring": true, - "docstring": "Abstract LLM backend used by the documentation generator.", - "parameters": null, - "node_type": "class", - "base_classes": [ - "abc.ABC" - ], - "class_name": null, - "display_name": "class LLMBackend", - "component_id": "codewiki/src/be/backend.py::LLMBackend", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/backend.py::LLMBackend.complete": { - "id": "codewiki/src/be/backend.py::LLMBackend.complete", - "name": "LLMBackend.complete", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/backend.py", - "relative_path": "codewiki/src/be/backend.py", - "depends_on": [], - "source_code": " def complete(\n self,\n prompt: str,\n *,\n model: str | None = None,\n ) -> str:\n \"\"\"Single-shot text completion.\"\"\"", - "start_line": 39, - "end_line": 45, - "has_docstring": true, - "docstring": "Single-shot text completion.", - "parameters": [ - "self", - "prompt" - ], - "node_type": "method", - "base_classes": null, - "class_name": "LLMBackend", - "display_name": "method LLMBackend.complete", - "component_id": "codewiki/src/be/backend.py::LLMBackend.complete", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/backend.py::LLMBackend.run_module_agent": { - "id": "codewiki/src/be/backend.py::LLMBackend.run_module_agent", - "name": "LLMBackend.run_module_agent", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/backend.py", - "relative_path": "codewiki/src/be/backend.py", - "depends_on": [], - "source_code": " async def run_module_agent(\n self,\n module_name: str,\n components: Dict[str, \"Node\"],\n core_component_ids: List[str],\n module_path: List[str],\n working_dir: str,\n ) -> Dict[str, Any]:\n \"\"\"Run the per-module agent loop. Returns the updated module_tree dict.\"\"\"", - "start_line": 48, - "end_line": 56, - "has_docstring": true, - "docstring": "Run the per-module agent loop. Returns the updated module_tree dict.", - "parameters": [ - "self", - "module_name", - "components", - "core_component_ids", - "module_path", - "working_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "LLMBackend", - "display_name": "method LLMBackend.run_module_agent", - "component_id": "codewiki/src/be/backend.py::LLMBackend.run_module_agent", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/backend.py::get_backend": { - "id": "codewiki/src/be/backend.py::get_backend", - "name": "get_backend", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/backend.py", - "relative_path": "codewiki/src/be/backend.py", - "depends_on": [ - "codewiki/src/be/caw_backend.py::CawBackend", - "codewiki/src/be/pydantic_ai_backend.py::PydanticAIBackend", - "codewiki/src/be/backend.py::is_caw_provider" - ], - "source_code": "def get_backend(config) -> \"LLMBackend\":\n \"\"\"Return the backend instance matching ``config.provider``.\"\"\"\n provider = getattr(config, \"provider\", \"openai-compatible\")\n if is_caw_provider(provider):\n from codewiki.src.be.caw_backend import CawBackend\n return CawBackend(config)\n from codewiki.src.be.pydantic_ai_backend import PydanticAIBackend\n return PydanticAIBackend(config)", - "start_line": 59, - "end_line": 66, - "has_docstring": true, - "docstring": "Return the backend instance matching ``config.provider``.", - "parameters": [ - "config" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function get_backend", - "component_id": "codewiki/src/be/backend.py::get_backend", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/caw_backend.py::_agent_tool_group_for_provider": { - "id": "codewiki/src/be/caw_backend.py::_agent_tool_group_for_provider", - "name": "_agent_tool_group_for_provider", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/caw_backend.py", - "relative_path": "codewiki/src/be/caw_backend.py", - "depends_on": [], - "source_code": "def _agent_tool_group_for_provider(provider: str) -> ToolGroup:\n \"\"\"Return the caw tool group needed for a module-agent session.\"\"\"\n if provider == \"codex\":\n # Codex CLI 0.118+ discovers streamable-HTTP MCP servers in read-only\n # or workspace-write sandbox mode, but cancels MCP tool calls in\n # non-interactive `codex exec` with \"user cancelled MCP tool call\".\n # In caw's Codex adapter, including EXEC maps the session to\n # `--dangerously-bypass-approvals-and-sandbox`, which is currently the\n # mode where CodeWiki's MCP tools run reliably. Codex cannot enforce\n # finer-grained built-in tool restrictions anyway, so prompts still\n # direct the agent to use CodeWiki's str_replace_editor for writes.\n return _AGENT_TOOL_GROUP | ToolGroup.EXEC\n return _AGENT_TOOL_GROUP", - "start_line": 65, - "end_line": 77, - "has_docstring": true, - "docstring": "Return the caw tool group needed for a module-agent session.", - "parameters": [ - "provider" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _agent_tool_group_for_provider", - "component_id": "codewiki/src/be/caw_backend.py::_agent_tool_group_for_provider", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/caw_backend.py::_resolve_caw_provider": { - "id": "codewiki/src/be/caw_backend.py::_resolve_caw_provider", - "name": "_resolve_caw_provider", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/caw_backend.py", - "relative_path": "codewiki/src/be/caw_backend.py", - "depends_on": [], - "source_code": "def _resolve_caw_provider(provider: str) -> str:\n try:\n return _CAW_PROVIDER_MAP[provider]\n except KeyError as e:\n raise ValueError(\n f\"Unsupported caw provider {provider!r}. Expected one of: \"\n f\"{sorted(_CAW_PROVIDER_MAP.keys())}\"\n ) from e", - "start_line": 80, - "end_line": 87, - "has_docstring": false, - "docstring": "", - "parameters": [ - "provider" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _resolve_caw_provider", - "component_id": "codewiki/src/be/caw_backend.py::_resolve_caw_provider", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/caw_backend.py::_patch_codex_tool_timeout": { - "id": "codewiki/src/be/caw_backend.py::_patch_codex_tool_timeout", - "name": "_patch_codex_tool_timeout", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/caw_backend.py", - "relative_path": "codewiki/src/be/caw_backend.py", - "depends_on": [], - "source_code": "def _patch_codex_tool_timeout() -> None:\n global _CODEX_PATCH_APPLIED\n if _CODEX_PATCH_APPLIED:\n return\n from caw.providers.codex import CodexSession\n\n _orig = CodexSession._mcp_config_args\n\n def _patched(self) -> list[str]:\n args = list(_orig(self))\n for srv in self._mcp_servers:\n args += [\n \"-c\",\n f\"mcp_servers.{srv.name}.tool_timeout_sec={_CODEX_TOOL_TIMEOUT_SEC}\",\n ]\n return args\n\n CodexSession._mcp_config_args = _patched\n _CODEX_PATCH_APPLIED = True", - "start_line": 98, - "end_line": 116, - "has_docstring": false, - "docstring": "", - "parameters": [], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _patch_codex_tool_timeout", - "component_id": "codewiki/src/be/caw_backend.py::_patch_codex_tool_timeout", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/caw_backend.py::_with_allowed_tools": { - "id": "codewiki/src/be/caw_backend.py::_with_allowed_tools", - "name": "_with_allowed_tools", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/caw_backend.py", - "relative_path": "codewiki/src/be/caw_backend.py", - "depends_on": [ - "codewiki/cli/config_manager.py::ConfigManager.load" - ], - "source_code": "def _with_allowed_tools(cmd):\n \"\"\"Append ``--allowedTools mcp__,...`` to a ``claude`` command.\n\n Pure ``list -> list`` transform. Applies only when *cmd* is a claude\n invocation carrying ``--mcp-config`` and no explicit allow-list already;\n otherwise (or on any error) *cmd* is returned unchanged.\n \"\"\"\n import json\n\n try:\n if not (\n isinstance(cmd, (list, tuple))\n and cmd\n and os.path.basename(str(cmd[0])) == \"claude\"\n and \"--mcp-config\" in cmd\n and \"--allowedTools\" not in cmd\n and \"--allowed-tools\" not in cmd\n ):\n return cmd\n # caw emits a single `--mcp-config `; only the first occurrence\n # is considered.\n cfg_path = cmd[list(cmd).index(\"--mcp-config\") + 1]\n with open(cfg_path) as f:\n servers = list(json.load(f).get(\"mcpServers\", {}).keys())\n if not servers:\n return cmd\n allowed = \",\".join(f\"mcp__{s}\" for s in servers)\n logger.info(\"Injected --allowedTools for MCP servers: %s\", servers)\n return list(cmd) + [\"--allowedTools\", allowed]\n except Exception as e: # never break the spawn on a patch hiccup\n logger.warning(\"claude allowedTools patch skipped: %s\", e)\n return cmd", - "start_line": 144, - "end_line": 175, - "has_docstring": true, - "docstring": "Append ``--allowedTools mcp__,...`` to a ``claude`` command.\n\nPure ``list -> list`` transform. Applies only when *cmd* is a claude\ninvocation carrying ``--mcp-config`` and no explicit allow-list already;\notherwise (or on any error) *cmd* is returned unchanged.", - "parameters": [ - "cmd" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _with_allowed_tools", - "component_id": "codewiki/src/be/caw_backend.py::_with_allowed_tools", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/caw_backend.py::_patch_claude_allowed_tools": { - "id": "codewiki/src/be/caw_backend.py::_patch_claude_allowed_tools", - "name": "_patch_claude_allowed_tools", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/caw_backend.py", - "relative_path": "codewiki/src/be/caw_backend.py", - "depends_on": [ - "codewiki/src/be/caw_backend.py::_with_allowed_tools" - ], - "source_code": "def _patch_claude_allowed_tools() -> None:\n global _CLAUDE_ALLOWED_PATCH_APPLIED\n if _CLAUDE_ALLOWED_PATCH_APPLIED:\n return\n import subprocess\n\n from caw.providers import claude_code as _caw_claude\n\n class _SubprocessProxy:\n \"\"\"``subprocess`` stand-in that rewrites Popen commands.\n\n Every other attribute (PIPE, run, ...) delegates to the real module.\n \"\"\"\n\n @staticmethod\n def Popen(cmd, *args, **kwargs):\n return subprocess.Popen(_with_allowed_tools(cmd), *args, **kwargs)\n\n def __getattr__(self, name):\n return getattr(subprocess, name)\n\n _caw_claude.subprocess = _SubprocessProxy()\n _CLAUDE_ALLOWED_PATCH_APPLIED = True", - "start_line": 178, - "end_line": 200, - "has_docstring": false, - "docstring": "", - "parameters": [], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _patch_claude_allowed_tools", - "component_id": "codewiki/src/be/caw_backend.py::_patch_claude_allowed_tools", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/caw_backend.py::CawBackend": { - "id": "codewiki/src/be/caw_backend.py::CawBackend", - "name": "CawBackend", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/caw_backend.py", - "relative_path": "codewiki/src/be/caw_backend.py", - "depends_on": [ - "codewiki/src/be/backend.py::LLMBackend" - ], - "source_code": "class CawBackend(LLMBackend):\n \"\"\"Routes LLM operations through the claude / codex CLI subscription.\"\"\"\n\n def __init__(self, config: Config) -> None:\n self._config = config\n self._caw_provider = _resolve_caw_provider(config.provider)\n # main_model is passed straight through; empty string β†’ caw default.\n self._model: str | None = config.main_model or None\n # Resolve once, before any agent-run chdir can move the cwd β€”\n # os.path.abspath is cwd-relative and _run_module_agent_sync recurses\n # (via generate_sub_module_documentation) while the cwd is pinned.\n self._repo_root = str(os.path.abspath(config.repo_path))\n\n # Fail loudly here rather than producing a confusing caw error mid-run.\n cli = _CLI_BINARY[config.provider]\n if shutil.which(cli) is None:\n raise RuntimeError(\n f\"Subscription mode requires the '{cli}' CLI on PATH. \"\n f\"Install it and run '{cli} login', then try again.\"\n )\n\n if self._caw_provider == \"claude_code\":\n # Prevent claude-code CLI from cancelling long sub-module recursion;\n # setdefault preserves a user-supplied value (e.g. shell override).\n os.environ.setdefault(\"MCP_TOOL_TIMEOUT\", \"86400000\")\n os.environ.setdefault(\"MCP_TIMEOUT\", \"60000\")\n logger.info(\n \"claude-code MCP timeouts: MCP_TOOL_TIMEOUT=%s MCP_TIMEOUT=%s\",\n os.environ[\"MCP_TOOL_TIMEOUT\"],\n os.environ[\"MCP_TIMEOUT\"],\n )\n\n # ------------------------------------------------------------------\n # Single-shot completion (clustering, parent / repo overviews)\n # ------------------------------------------------------------------\n\n def complete(\n self,\n prompt: str,\n *,\n model: str | None = None,\n ) -> str:\n # Blocks the calling thread for the lifetime of the claude/codex\n # subprocess. Callers running this from an async context (e.g. the\n # documentation_generator) accept this β€” there is no concurrent work\n # to do while clustering is in flight anyway.\n effective_model = model or self._model\n agent = CawAgent(\n provider=self._caw_provider,\n model=effective_model,\n tools=ToolGroup.READER,\n )\n traj = agent.completion(prompt)\n return traj.result\n\n # ------------------------------------------------------------------\n # Per-module agent loop\n # ------------------------------------------------------------------\n\n async def run_module_agent(\n self,\n module_name: str,\n components: Dict[str, Node],\n core_component_ids: List[str],\n module_path: List[str],\n working_dir: str,\n ) -> Dict[str, Any]:\n # caw.completion shells out to a subprocess and blocks the calling\n # thread. Push it off the event loop so the rest of the async\n # pipeline keeps moving.\n # Mermaid validation goes through PythonMonkey, which binds its JS\n # engine to the thread where it was first imported (the main\n # thread). caw routes MCP tool calls through a FastMCP daemon\n # thread, so the validator would otherwise lose its event loop.\n # Hand the main loop to utils so the worker-thread tool calls can\n # marshal parse_mermaid_py back here.\n set_main_loop(asyncio.get_running_loop())\n return await asyncio.to_thread(\n self._run_module_agent_sync,\n module_name,\n components,\n core_component_ids,\n module_path,\n working_dir,\n )\n\n def _run_module_agent_sync(\n self,\n module_name: str,\n components: Dict[str, Node],\n core_component_ids: List[str],\n module_path: List[str],\n working_dir: str,\n start_depth: int = 1,\n module_tree: Dict[str, Any] | None = None,\n ) -> Dict[str, Any]:\n # ``start_depth`` lets the recursion preserve max_depth across nested\n # _run_module_agent_sync calls β€” each fresh deps object would otherwise\n # reset current_depth to 1 and silently bypass max_depth guards.\n # ``module_tree`` carries the parent's in-memory tree across the\n # recursion. Reloading from disk only works at the top level β€” by the\n # time a sub-agent runs, the parent has staged new branches in memory\n # but has not yet saved (save happens after agent.completion returns).\n from codewiki.src.be.caw_toolkit import CawToolKit # local import to avoid cycles\n\n config = self._config\n module_tree_path = os.path.join(working_dir, MODULE_TREE_FILENAME)\n if module_tree is None:\n module_tree = file_manager.load_json(module_tree_path)\n\n overview_docs_path = os.path.join(working_dir, OVERVIEW_FILENAME)\n if os.path.exists(overview_docs_path):\n logger.info(\"βœ“ Overview docs already exists at %s\", overview_docs_path)\n return module_tree\n docs_path = os.path.join(working_dir, f\"{module_name}.md\")\n if os.path.exists(docs_path):\n logger.info(\"βœ“ Module docs already exists at %s\", docs_path)\n return module_tree\n\n custom_instructions = config.get_prompt_addition()\n\n # Mirror PydanticAIBackend's early-cut: a module is only worth\n # delegating to sub-agents when it spans multiple files AND has enough\n # content to justify the cost AND we still have recursion budget.\n # Without this gate the caw path would give every multi-file sub-module\n # the recursive SYSTEM_PROMPT + delegation tool and fan out one extra\n # agent call per sub-spec even when a single leaf write would suffice.\n # See generate_sub_module_documentation_tool for the pydantic-ai\n # equivalent.\n _, components_with_code = format_potential_core_components(\n core_component_ids, components\n )\n num_tokens = count_tokens(components_with_code)\n can_delegate = (\n is_complex_module(components, core_component_ids)\n and start_depth < config.max_depth\n and num_tokens >= config.max_token_per_leaf_module\n )\n logger.info(f\"Module {module_name} can delegate: {can_delegate} - is_complex_module: {is_complex_module(components, core_component_ids)} - start_depth: {start_depth} - num_tokens: {num_tokens} - max_depth: {config.max_depth} - max_token_per_leaf_module: {config.max_token_per_leaf_module}\")\n\n if can_delegate:\n system_prompt = format_system_prompt(module_name, custom_instructions)\n else:\n system_prompt = format_leaf_system_prompt(module_name, custom_instructions)\n\n deps = CodeWikiDeps(\n absolute_docs_path=working_dir,\n absolute_repo_path=self._repo_root,\n registry={},\n components=components,\n path_to_current_module=list(module_path),\n current_module_name=module_name,\n module_tree=module_tree,\n max_depth=config.max_depth,\n current_depth=start_depth,\n config=config,\n custom_instructions=custom_instructions,\n )\n\n toolkit = CawToolKit(deps=deps, backend=self, allow_subagent=can_delegate)\n\n agent = CawAgent(\n provider=self._caw_provider,\n model=self._model,\n system_prompt=system_prompt,\n tools=_agent_tool_group_for_provider(self._caw_provider),\n tool_servers=[toolkit],\n )\n\n user_prompt = format_user_prompt(\n module_name=module_name,\n core_component_ids=core_component_ids,\n components=components,\n module_tree=deps.module_tree,\n )\n\n # caw forks claude / codex via subprocess.Popen without a cwd, so the\n # child CLI inherits Python's cwd β€” typically the repo root where the\n # user invoked ``codewiki``. Codex's native ``file_change`` tool\n # (always present under the danger-full-access sandbox EXEC requires)\n # then resolves relative paths against that cwd, dropping the .md at\n # the repo root. Pin cwd to the docs output dir for the duration of\n # the agent run so file_change lands inside ``--output``. Reads still\n # go through MCP tools that use absolute paths from ``deps``, so\n # they're cwd-independent. Safe to mutate process-wide cwd because\n # documentation_generator processes modules sequentially and recursive\n # _run_module_agent_sync calls chdir to the same absolute_docs_path.\n # caw runs claude with `--dangerously-skip-permissions`, expecting\n # bypassPermissions (\"Everything\" runs without asking). But an org\n # managed policy can DISABLE bypass mode, in which case the flag is\n # downgraded to `acceptEdits` β€” observed here: both\n # `--dangerously-skip-permissions` and `--permission-mode\n # bypassPermissions` report permissionMode=acceptEdits.\n # permission modes: https://code.claude.com/docs/en/permission-modes\n # (see #skip-all-checks-with-bypasspermissions-mode and its\n # disableBypassPermissionsMode managed setting).\n # Under acceptEdits, auto-approval is limited to reads/edits INSIDE the\n # working directory or additionalDirectories; paths outside that scope\n # still prompt (== denied in non-interactive `-p`):\n # https://code.claude.com/docs/en/permission-modes#auto-approve-file-edits-with-acceptedits-mode\n # caw chdir's into the output subdir (for codex's native file_change),\n # so the source tree in the PARENT repo is out-of-scope and every\n # source Read is denied -> empty docs. claude writes via CodeWiki's\n # str_replace_editor (absolute deps path), so it does NOT need cwd\n # pinned to the output dir. Pin cwd to the repo root so BOTH the source\n # tree and the output dir fall inside the workspace (alt: --add-dir,\n # https://code.claude.com/docs/en/cli-reference). Codex keeps the\n # output-dir chdir because its file_change resolves relative paths.\n original_cwd = os.getcwd()\n if self._caw_provider == \"codex\":\n run_cwd = working_dir\n else:\n run_cwd = self._repo_root\n try:\n os.chdir(run_cwd)\n try:\n traj = agent.completion(user_prompt)\n finally:\n os.chdir(original_cwd)\n logger.info(\n \"Module %s completed via caw (turns=%d, tool_calls=%d)\",\n module_name,\n traj.num_turns,\n traj.total_tool_calls,\n )\n file_manager.save_json(deps.module_tree, module_tree_path)\n return deps.module_tree\n except Exception as e:\n logger.error(\"Error processing module %s via caw: %s\", module_name, e)\n raise", - "start_line": 207, - "end_line": 436, - "has_docstring": true, - "docstring": "Routes LLM operations through the claude / codex CLI subscription.", - "parameters": null, - "node_type": "class", - "base_classes": [ - "LLMBackend" - ], - "class_name": null, - "display_name": "class CawBackend", - "component_id": "codewiki/src/be/caw_backend.py::CawBackend", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/caw_backend.py::CawBackend.__init__": { - "id": "codewiki/src/be/caw_backend.py::CawBackend.__init__", - "name": "CawBackend.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/caw_backend.py", - "relative_path": "codewiki/src/be/caw_backend.py", - "depends_on": [ - "codewiki/src/be/caw_backend.py::_resolve_caw_provider" - ], - "source_code": " def __init__(self, config: Config) -> None:\n self._config = config\n self._caw_provider = _resolve_caw_provider(config.provider)\n # main_model is passed straight through; empty string β†’ caw default.\n self._model: str | None = config.main_model or None\n # Resolve once, before any agent-run chdir can move the cwd β€”\n # os.path.abspath is cwd-relative and _run_module_agent_sync recurses\n # (via generate_sub_module_documentation) while the cwd is pinned.\n self._repo_root = str(os.path.abspath(config.repo_path))\n\n # Fail loudly here rather than producing a confusing caw error mid-run.\n cli = _CLI_BINARY[config.provider]\n if shutil.which(cli) is None:\n raise RuntimeError(\n f\"Subscription mode requires the '{cli}' CLI on PATH. \"\n f\"Install it and run '{cli} login', then try again.\"\n )\n\n if self._caw_provider == \"claude_code\":\n # Prevent claude-code CLI from cancelling long sub-module recursion;\n # setdefault preserves a user-supplied value (e.g. shell override).\n os.environ.setdefault(\"MCP_TOOL_TIMEOUT\", \"86400000\")\n os.environ.setdefault(\"MCP_TIMEOUT\", \"60000\")\n logger.info(\n \"claude-code MCP timeouts: MCP_TOOL_TIMEOUT=%s MCP_TIMEOUT=%s\",\n os.environ[\"MCP_TOOL_TIMEOUT\"],\n os.environ[\"MCP_TIMEOUT\"],\n )", - "start_line": 210, - "end_line": 237, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "config" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CawBackend", - "display_name": "method CawBackend.__init__", - "component_id": "codewiki/src/be/caw_backend.py::CawBackend.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/caw_backend.py::CawBackend.complete": { - "id": "codewiki/src/be/caw_backend.py::CawBackend.complete", - "name": "CawBackend.complete", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/caw_backend.py", - "relative_path": "codewiki/src/be/caw_backend.py", - "depends_on": [], - "source_code": " def complete(\n self,\n prompt: str,\n *,\n model: str | None = None,\n ) -> str:\n # Blocks the calling thread for the lifetime of the claude/codex\n # subprocess. Callers running this from an async context (e.g. the\n # documentation_generator) accept this β€” there is no concurrent work\n # to do while clustering is in flight anyway.\n effective_model = model or self._model\n agent = CawAgent(\n provider=self._caw_provider,\n model=effective_model,\n tools=ToolGroup.READER,\n )\n traj = agent.completion(prompt)\n return traj.result", - "start_line": 243, - "end_line": 260, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "prompt" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CawBackend", - "display_name": "method CawBackend.complete", - "component_id": "codewiki/src/be/caw_backend.py::CawBackend.complete", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/caw_backend.py::CawBackend.run_module_agent": { - "id": "codewiki/src/be/caw_backend.py::CawBackend.run_module_agent", - "name": "CawBackend.run_module_agent", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/caw_backend.py", - "relative_path": "codewiki/src/be/caw_backend.py", - "depends_on": [ - "codewiki/src/be/utils.py::set_main_loop" - ], - "source_code": " async def run_module_agent(\n self,\n module_name: str,\n components: Dict[str, Node],\n core_component_ids: List[str],\n module_path: List[str],\n working_dir: str,\n ) -> Dict[str, Any]:\n # caw.completion shells out to a subprocess and blocks the calling\n # thread. Push it off the event loop so the rest of the async\n # pipeline keeps moving.\n # Mermaid validation goes through PythonMonkey, which binds its JS\n # engine to the thread where it was first imported (the main\n # thread). caw routes MCP tool calls through a FastMCP daemon\n # thread, so the validator would otherwise lose its event loop.\n # Hand the main loop to utils so the worker-thread tool calls can\n # marshal parse_mermaid_py back here.\n set_main_loop(asyncio.get_running_loop())\n return await asyncio.to_thread(\n self._run_module_agent_sync,\n module_name,\n components,\n core_component_ids,\n module_path,\n working_dir,\n )", - "start_line": 266, - "end_line": 291, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "module_name", - "components", - "core_component_ids", - "module_path", - "working_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CawBackend", - "display_name": "method CawBackend.run_module_agent", - "component_id": "codewiki/src/be/caw_backend.py::CawBackend.run_module_agent", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/caw_backend.py::CawBackend._run_module_agent_sync": { - "id": "codewiki/src/be/caw_backend.py::CawBackend._run_module_agent_sync", - "name": "CawBackend._run_module_agent_sync", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/caw_backend.py", - "relative_path": "codewiki/src/be/caw_backend.py", - "depends_on": [ - "codewiki/src/be/prompt_template.py::format_leaf_system_prompt", - "codewiki/src/be/agent_tools/deps.py::CodeWikiDeps", - "codewiki/src/be/caw_toolkit.py::CawToolKit", - "codewiki/src/utils.py::FileManager.load_json", - "codewiki/src/be/caw_backend.py::_agent_tool_group_for_provider", - "codewiki/src/be/prompt_template.py::format_system_prompt", - "codewiki/src/be/utils.py::is_complex_module", - "codewiki/src/be/utils.py::count_tokens", - "codewiki/src/utils.py::FileManager.save_json", - "codewiki/src/be/prompt_template.py::format_user_prompt", - "codewiki/src/be/cluster_modules.py::format_potential_core_components", - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": " def _run_module_agent_sync(\n self,\n module_name: str,\n components: Dict[str, Node],\n core_component_ids: List[str],\n module_path: List[str],\n working_dir: str,\n start_depth: int = 1,\n module_tree: Dict[str, Any] | None = None,\n ) -> Dict[str, Any]:\n # ``start_depth`` lets the recursion preserve max_depth across nested\n # _run_module_agent_sync calls β€” each fresh deps object would otherwise\n # reset current_depth to 1 and silently bypass max_depth guards.\n # ``module_tree`` carries the parent's in-memory tree across the\n # recursion. Reloading from disk only works at the top level β€” by the\n # time a sub-agent runs, the parent has staged new branches in memory\n # but has not yet saved (save happens after agent.completion returns).\n from codewiki.src.be.caw_toolkit import CawToolKit # local import to avoid cycles\n\n config = self._config\n module_tree_path = os.path.join(working_dir, MODULE_TREE_FILENAME)\n if module_tree is None:\n module_tree = file_manager.load_json(module_tree_path)\n\n overview_docs_path = os.path.join(working_dir, OVERVIEW_FILENAME)\n if os.path.exists(overview_docs_path):\n logger.info(\"βœ“ Overview docs already exists at %s\", overview_docs_path)\n return module_tree\n docs_path = os.path.join(working_dir, f\"{module_name}.md\")\n if os.path.exists(docs_path):\n logger.info(\"βœ“ Module docs already exists at %s\", docs_path)\n return module_tree\n\n custom_instructions = config.get_prompt_addition()\n\n # Mirror PydanticAIBackend's early-cut: a module is only worth\n # delegating to sub-agents when it spans multiple files AND has enough\n # content to justify the cost AND we still have recursion budget.\n # Without this gate the caw path would give every multi-file sub-module\n # the recursive SYSTEM_PROMPT + delegation tool and fan out one extra\n # agent call per sub-spec even when a single leaf write would suffice.\n # See generate_sub_module_documentation_tool for the pydantic-ai\n # equivalent.\n _, components_with_code = format_potential_core_components(\n core_component_ids, components\n )\n num_tokens = count_tokens(components_with_code)\n can_delegate = (\n is_complex_module(components, core_component_ids)\n and start_depth < config.max_depth\n and num_tokens >= config.max_token_per_leaf_module\n )\n logger.info(f\"Module {module_name} can delegate: {can_delegate} - is_complex_module: {is_complex_module(components, core_component_ids)} - start_depth: {start_depth} - num_tokens: {num_tokens} - max_depth: {config.max_depth} - max_token_per_leaf_module: {config.max_token_per_leaf_module}\")\n\n if can_delegate:\n system_prompt = format_system_prompt(module_name, custom_instructions)\n else:\n system_prompt = format_leaf_system_prompt(module_name, custom_instructions)\n\n deps = CodeWikiDeps(\n absolute_docs_path=working_dir,\n absolute_repo_path=self._repo_root,\n registry={},\n components=components,\n path_to_current_module=list(module_path),\n current_module_name=module_name,\n module_tree=module_tree,\n max_depth=config.max_depth,\n current_depth=start_depth,\n config=config,\n custom_instructions=custom_instructions,\n )\n\n toolkit = CawToolKit(deps=deps, backend=self, allow_subagent=can_delegate)\n\n agent = CawAgent(\n provider=self._caw_provider,\n model=self._model,\n system_prompt=system_prompt,\n tools=_agent_tool_group_for_provider(self._caw_provider),\n tool_servers=[toolkit],\n )\n\n user_prompt = format_user_prompt(\n module_name=module_name,\n core_component_ids=core_component_ids,\n components=components,\n module_tree=deps.module_tree,\n )\n\n # caw forks claude / codex via subprocess.Popen without a cwd, so the\n # child CLI inherits Python's cwd β€” typically the repo root where the\n # user invoked ``codewiki``. Codex's native ``file_change`` tool\n # (always present under the danger-full-access sandbox EXEC requires)\n # then resolves relative paths against that cwd, dropping the .md at\n # the repo root. Pin cwd to the docs output dir for the duration of\n # the agent run so file_change lands inside ``--output``. Reads still\n # go through MCP tools that use absolute paths from ``deps``, so\n # they're cwd-independent. Safe to mutate process-wide cwd because\n # documentation_generator processes modules sequentially and recursive\n # _run_module_agent_sync calls chdir to the same absolute_docs_path.\n # caw runs claude with `--dangerously-skip-permissions`, expecting\n # bypassPermissions (\"Everything\" runs without asking). But an org\n # managed policy can DISABLE bypass mode, in which case the flag is\n # downgraded to `acceptEdits` β€” observed here: both\n # `--dangerously-skip-permissions` and `--permission-mode\n # bypassPermissions` report permissionMode=acceptEdits.\n # permission modes: https://code.claude.com/docs/en/permission-modes\n # (see #skip-all-checks-with-bypasspermissions-mode and its\n # disableBypassPermissionsMode managed setting).\n # Under acceptEdits, auto-approval is limited to reads/edits INSIDE the\n # working directory or additionalDirectories; paths outside that scope\n # still prompt (== denied in non-interactive `-p`):\n # https://code.claude.com/docs/en/permission-modes#auto-approve-file-edits-with-acceptedits-mode\n # caw chdir's into the output subdir (for codex's native file_change),\n # so the source tree in the PARENT repo is out-of-scope and every\n # source Read is denied -> empty docs. claude writes via CodeWiki's\n # str_replace_editor (absolute deps path), so it does NOT need cwd\n # pinned to the output dir. Pin cwd to the repo root so BOTH the source\n # tree and the output dir fall inside the workspace (alt: --add-dir,\n # https://code.claude.com/docs/en/cli-reference). Codex keeps the\n # output-dir chdir because its file_change resolves relative paths.\n original_cwd = os.getcwd()\n if self._caw_provider == \"codex\":\n run_cwd = working_dir\n else:\n run_cwd = self._repo_root\n try:\n os.chdir(run_cwd)\n try:\n traj = agent.completion(user_prompt)\n finally:\n os.chdir(original_cwd)\n logger.info(\n \"Module %s completed via caw (turns=%d, tool_calls=%d)\",\n module_name,\n traj.num_turns,\n traj.total_tool_calls,\n )\n file_manager.save_json(deps.module_tree, module_tree_path)\n return deps.module_tree\n except Exception as e:\n logger.error(\"Error processing module %s via caw: %s\", module_name, e)\n raise", - "start_line": 293, - "end_line": 436, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "module_name", - "components", - "core_component_ids", - "module_path", - "working_dir", - "start_depth", - "module_tree" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CawBackend", - "display_name": "method CawBackend._run_module_agent_sync", - "component_id": "codewiki/src/be/caw_backend.py::CawBackend._run_module_agent_sync", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/caw_toolkit.py::_heartbeat": { - "id": "codewiki/src/be/caw_toolkit.py::_heartbeat", - "name": "_heartbeat", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/caw_toolkit.py", - "relative_path": "codewiki/src/be/caw_toolkit.py", - "depends_on": [], - "source_code": "async def _heartbeat(ctx: Context, work: asyncio.Task) -> None:\n # Keeps the codex / claude-code CLI from cancelling the parent tool call\n # during long sub-module recursion. Failures are swallowed β€” a broken\n # heartbeat must never abort real work.\n progress = 0\n while not work.done():\n await asyncio.sleep(_HEARTBEAT_INTERVAL_SEC)\n progress += 1\n try:\n await ctx.report_progress(\n progress=progress,\n total=None,\n message=\"sub-module generation in progress\",\n )\n except Exception:\n pass", - "start_line": 45, - "end_line": 60, - "has_docstring": false, - "docstring": "", - "parameters": [ - "ctx", - "work" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _heartbeat", - "component_id": "codewiki/src/be/caw_toolkit.py::_heartbeat", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/caw_toolkit.py::_coerce_json_arg": { - "id": "codewiki/src/be/caw_toolkit.py::_coerce_json_arg", - "name": "_coerce_json_arg", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/caw_toolkit.py", - "relative_path": "codewiki/src/be/caw_toolkit.py", - "depends_on": [], - "source_code": "def _coerce_json_arg(value):\n # Some MCP/CLI bridges emit list/int tool args as JSON-encoded strings\n # (e.g. ``\"[1, 50]\"`` instead of ``[1, 50]``). Parity with the\n # pydantic-ai tool path; see _coerce_json_string in str_replace_editor.py.\n if isinstance(value, str):\n try:\n return json.loads(value)\n except ValueError:\n pass\n return value", - "start_line": 63, - "end_line": 72, - "has_docstring": false, - "docstring": "", - "parameters": [ - "value" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _coerce_json_arg", - "component_id": "codewiki/src/be/caw_toolkit.py::_coerce_json_arg", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/caw_toolkit.py::CawToolKit": { - "id": "codewiki/src/be/caw_toolkit.py::CawToolKit", - "name": "CawToolKit", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/caw_toolkit.py", - "relative_path": "codewiki/src/be/caw_toolkit.py", - "depends_on": [], - "source_code": "class CawToolKit(\n ToolKit,\n server_name=\"codewiki_tools\",\n display_name=\"CodeWiki Tools\",\n):\n \"\"\"MCP tool server exposing CodeWiki tools to a caw Agent.\"\"\"\n\n def __init__(\n self,\n deps: CodeWikiDeps,\n backend: \"CawBackend\",\n allow_subagent: bool,\n ) -> None:\n self._deps = deps\n self._backend = backend\n self._allow_subagent = allow_subagent\n\n # ------------------------------------------------------------------\n # Tool: read_code_components\n # ------------------------------------------------------------------\n\n @tool(\n description=(\n \"Read the source code of the given component ids. \"\n \"component_ids is a list of strings like \"\n \"['sweagent/types.py::AgentRunResult', 'auth/middleware.py::verify_token'] \"\n \"where the part before '::' is the file path and the part after is the component name.\"\n )\n )\n async def read_code_components(self, component_ids: list[str]) -> str:\n results = []\n for cid in component_ids:\n if cid not in self._deps.components:\n results.append(f\"# Component {cid} not found\")\n else:\n results.append(\n f\"# Component {cid}:\\n\"\n f\"{self._deps.components[cid].source_code.strip()}\\n\\n\"\n )\n return \"\\n\".join(results)\n\n # ------------------------------------------------------------------\n # Tool: str_replace_editor\n # Reuses the EditTool implementation + Mermaid validator from the\n # existing module so behavior matches the pydantic-ai path exactly.\n # ------------------------------------------------------------------\n\n @tool(\n description=(\n \"Custom editing tool for viewing, creating and editing files.\\n\"\n \"* If `path` is a file, `view` displays the result of applying `cat -n`. \"\n \"If `path` is a directory, `view` lists non-hidden files and directories up to 2 levels deep.\\n\"\n \"* The `create` command cannot be used if the specified `path` already exists as a file.\\n\"\n \"* If a `command` generates a long output, it will be truncated and marked with ``.\\n\"\n \"* The `undo_edit` command will revert the last edit made to the file at `path`.\\n\"\n \"* Only `view` command is allowed when `working_dir` is `repo`.\"\n )\n )\n async def str_replace_editor(\n self,\n working_dir: str,\n command: str,\n path: str | None = None,\n file: str | None = None,\n file_text: str | None = None,\n view_range: list[int] | str | None = None,\n old_str: str | None = None,\n new_str: str | None = None,\n insert_line: int | str | None = None,\n ) -> str:\n from codewiki.src.be.agent_tools.str_replace_editor import EditTool\n from codewiki.src.be.utils import validate_mermaid_diagrams\n\n # ``Literal`` annotations would be the cleanest way to constrain these,\n # but ``from __future__ import annotations`` turns them into forward refs\n # that FastMCP's pydantic schema rebuild cannot resolve. Validate at\n # call time instead so a bogus working_dir (empty string, ``\".\"``, etc.)\n # cannot silently route writes to the repo root.\n if working_dir not in _VALID_WORKING_DIRS:\n return (\n f\"Error: invalid `working_dir`={working_dir!r}. \"\n f\"Allowed values: {list(_VALID_WORKING_DIRS)}.\"\n )\n if command not in _VALID_EDITOR_COMMANDS:\n return (\n f\"Error: invalid `command`={command!r}. \"\n f\"Allowed values: {list(_VALID_EDITOR_COMMANDS)}.\"\n )\n\n if path is None and file is None:\n return \"Error: Either `path` or `file` parameter must be provided.\"\n if path is None:\n path = file\n if command != \"view\" and working_dir == \"repo\":\n return \"The `view` command is the only allowed command when `working_dir` is `repo`.\"\n\n # Reject absolute paths: ``Path(\"/abs/base\") / \"/abs/other\"`` resolves to\n # ``/abs/other``, which would silently bypass ``working_dir`` and let the\n # agent write outside the docs path. Force the agent to pass a path\n # relative to the chosen working_dir.\n if os.path.isabs(path):\n return (\n f\"Error: `path` must be relative to `working_dir` ({working_dir!r}), \"\n f\"got absolute path {path!r}. Pass a relative path like \"\n f\"'module_name.md' (resolved under absolute_docs_path when \"\n f\"working_dir='docs').\"\n )\n\n view_range = _coerce_json_arg(view_range)\n insert_line = _coerce_json_arg(insert_line)\n\n edit_tool = EditTool(self._deps.registry, self._deps.absolute_docs_path)\n\n base_dir = (\n self._deps.absolute_docs_path\n if working_dir == \"docs\"\n else self._deps.absolute_repo_path\n )\n absolute_path = str(Path(base_dir) / path)\n\n # Defense in depth: even with a relative path, ``..`` segments could\n # escape ``base_dir``. Verify the resolved path stays inside.\n try:\n resolved = Path(absolute_path).resolve()\n base_resolved = Path(base_dir).resolve()\n resolved.relative_to(base_resolved)\n except ValueError:\n return (\n f\"Error: resolved path {absolute_path!r} escapes \"\n f\"working_dir={working_dir!r} root {base_dir!r}. \"\n f\"Pass a path that stays inside the working directory.\"\n )\n\n edit_tool(\n command=command,\n path=absolute_path,\n file_text=file_text,\n view_range=view_range,\n old_str=old_str,\n new_str=new_str,\n insert_line=insert_line,\n )\n\n result = \"\\n\".join(edit_tool.logs)\n\n if command != \"view\" and path.endswith(\".md\"):\n mermaid_validation = await validate_mermaid_diagrams(absolute_path, path)\n result = result + \"\\n---------- Mermaid validation ----------\\n\" + mermaid_validation\n\n return result\n\n # ------------------------------------------------------------------\n # Tool: generate_sub_module_documentation\n # ------------------------------------------------------------------\n\n @tool(\n description=(\n \"Delegate documentation generation of sub-modules to sub-agents. Each sub-module \"\n \"is documented separately.\\n\"\n \"sub_module_specs: a dictionary mapping sub-module names to their core component IDs. \"\n \"Example: {'authentication': ['auth_handler.py::AuthHandler'], \"\n \"'database': ['db_client.py::DBClient']}\\n\"\n \"Sub-module names must be unique across the whole wiki; a name already used by another \"\n \"module is automatically prefixed with the current module name, and the tool result \"\n \"reports the final file names actually saved.\"\n )\n )\n async def generate_sub_module_documentation(\n self, sub_module_specs: dict[str, list[str]], ctx: Context\n ) -> str:\n if not self._allow_subagent:\n return (\n \"generate_sub_module_documentation is NOT available for this module \"\n \"(leaf module: single-file or below the token threshold, or max recursion \"\n \"depth reached). DO NOT call this tool again for this module. \"\n \"Instead, write the documentation directly with `str_replace_editor` \"\n f\"(create command) as a single `{self._deps.current_module_name}.md` \"\n \"file covering the provided core components inline (architecture, \"\n \"components, diagrams, etc.) β€” no sub-module fan-out.\"\n )\n\n # Run the blocking recursion in a worker thread so the caw MCP server's\n # event loop stays responsive while sub-agents run. A heartbeat task\n # emits MCP progress notifications so the CLI does not treat the long\n # tool call as a stalled / cancelled invocation.\n work = asyncio.create_task(\n asyncio.to_thread(self._run_sub_modules, sub_module_specs)\n )\n heartbeat = asyncio.create_task(_heartbeat(ctx, work))\n try:\n return await work\n finally:\n heartbeat.cancel()\n with contextlib.suppress(asyncio.CancelledError):\n await heartbeat\n\n # ------------------------------------------------------------------\n # Internal: synchronous recursion driver\n # ------------------------------------------------------------------\n\n def _run_sub_modules(self, sub_module_specs: dict[str, list[str]]) -> str:\n deps = self._deps\n previous_module_name = deps.current_module_name\n\n # Resolve name collisions against the module tree and files already on\n # disk before touching the tree (issue #76): docs live in one flat directory.\n name_map = normalize_sub_module_specs(\n sub_module_specs,\n previous_module_name,\n deps.module_tree,\n deps.absolute_docs_path,\n )\n final_specs = {\n name_map[requested_name]: core_ids\n for requested_name, core_ids in sub_module_specs.items()\n }\n\n # Add sub-modules to the in-memory module tree.\n value = deps.module_tree\n for key in deps.path_to_current_module:\n value = value[key][\"children\"]\n for sub_name, core_ids in final_specs.items():\n value[sub_name] = {\"components\": core_ids, \"children\": {}}\n\n try:\n for sub_name, core_ids in final_specs.items():\n indent = \" \" * deps.current_depth\n arrow = \"└─\" if deps.current_depth > 0 else \"β†’\"\n logger.info(\"%s%s Generating documentation for sub-module: %s\", indent, arrow, sub_name)\n\n deps.current_module_name = sub_name\n deps.path_to_current_module.append(sub_name)\n deps.current_depth += 1\n try:\n # Spawn a fresh caw session for the sub-module. We already\n # run inside a worker thread (started by the parent tool\n # call), so call the sync entry point directly to avoid\n # double-wrapping. ``start_depth`` carries the parent's\n # depth so the sub-agent's max_depth guard stays accurate.\n self._backend._run_module_agent_sync(\n module_name=sub_name,\n components=deps.components,\n core_component_ids=core_ids,\n module_path=list(deps.path_to_current_module),\n working_dir=deps.absolute_docs_path,\n start_depth=deps.current_depth,\n module_tree=deps.module_tree,\n )\n finally:\n deps.path_to_current_module.pop()\n deps.current_depth -= 1\n finally:\n deps.current_module_name = previous_module_name\n\n # Report what actually landed on disk so the parent agent links real filenames.\n saved = []\n missing = []\n for requested_name, final_name in name_map.items():\n entry = f\"{final_name}.md\"\n if final_name != requested_name:\n entry += f\" (requested '{requested_name}', renamed to avoid a collision)\"\n if os.path.exists(os.path.join(deps.absolute_docs_path, f\"{final_name}.md\")):\n saved.append(entry)\n else:\n missing.append(entry)\n\n report = f\"Saved documentations: {', '.join(saved) if saved else 'none'}.\"\n if missing:\n report += f\" MISSING (generation did not produce these files): {', '.join(missing)}.\"\n logger.warning(\"Sub-module documentation missing after generation: %s\", \", \".join(missing))\n return report", - "start_line": 75, - "end_line": 345, - "has_docstring": true, - "docstring": "MCP tool server exposing CodeWiki tools to a caw Agent.", - "parameters": null, - "node_type": "class", - "base_classes": [ - "ToolKit" - ], - "class_name": null, - "display_name": "class CawToolKit", - "component_id": "codewiki/src/be/caw_toolkit.py::CawToolKit", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/caw_toolkit.py::CawToolKit.__init__": { - "id": "codewiki/src/be/caw_toolkit.py::CawToolKit.__init__", - "name": "CawToolKit.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/caw_toolkit.py", - "relative_path": "codewiki/src/be/caw_toolkit.py", - "depends_on": [], - "source_code": " def __init__(\n self,\n deps: CodeWikiDeps,\n backend: \"CawBackend\",\n allow_subagent: bool,\n ) -> None:\n self._deps = deps\n self._backend = backend\n self._allow_subagent = allow_subagent", - "start_line": 82, - "end_line": 90, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "deps", - "backend", - "allow_subagent" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CawToolKit", - "display_name": "method CawToolKit.__init__", - "component_id": "codewiki/src/be/caw_toolkit.py::CawToolKit.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/caw_toolkit.py::CawToolKit.read_code_components": { - "id": "codewiki/src/be/caw_toolkit.py::CawToolKit.read_code_components", - "name": "CawToolKit.read_code_components", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/caw_toolkit.py", - "relative_path": "codewiki/src/be/caw_toolkit.py", - "depends_on": [], - "source_code": " async def read_code_components(self, component_ids: list[str]) -> str:\n results = []\n for cid in component_ids:\n if cid not in self._deps.components:\n results.append(f\"# Component {cid} not found\")\n else:\n results.append(\n f\"# Component {cid}:\\n\"\n f\"{self._deps.components[cid].source_code.strip()}\\n\\n\"\n )\n return \"\\n\".join(results)", - "start_line": 104, - "end_line": 114, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "component_ids" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CawToolKit", - "display_name": "method CawToolKit.read_code_components", - "component_id": "codewiki/src/be/caw_toolkit.py::CawToolKit.read_code_components", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/caw_toolkit.py::CawToolKit.str_replace_editor": { - "id": "codewiki/src/be/caw_toolkit.py::CawToolKit.str_replace_editor", - "name": "CawToolKit.str_replace_editor", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/caw_toolkit.py", - "relative_path": "codewiki/src/be/caw_toolkit.py", - "depends_on": [ - "codewiki/src/be/caw_toolkit.py::_coerce_json_arg", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool", - "codewiki/src/be/utils.py::validate_mermaid_diagrams" - ], - "source_code": " async def str_replace_editor(\n self,\n working_dir: str,\n command: str,\n path: str | None = None,\n file: str | None = None,\n file_text: str | None = None,\n view_range: list[int] | str | None = None,\n old_str: str | None = None,\n new_str: str | None = None,\n insert_line: int | str | None = None,\n ) -> str:\n from codewiki.src.be.agent_tools.str_replace_editor import EditTool\n from codewiki.src.be.utils import validate_mermaid_diagrams\n\n # ``Literal`` annotations would be the cleanest way to constrain these,\n # but ``from __future__ import annotations`` turns them into forward refs\n # that FastMCP's pydantic schema rebuild cannot resolve. Validate at\n # call time instead so a bogus working_dir (empty string, ``\".\"``, etc.)\n # cannot silently route writes to the repo root.\n if working_dir not in _VALID_WORKING_DIRS:\n return (\n f\"Error: invalid `working_dir`={working_dir!r}. \"\n f\"Allowed values: {list(_VALID_WORKING_DIRS)}.\"\n )\n if command not in _VALID_EDITOR_COMMANDS:\n return (\n f\"Error: invalid `command`={command!r}. \"\n f\"Allowed values: {list(_VALID_EDITOR_COMMANDS)}.\"\n )\n\n if path is None and file is None:\n return \"Error: Either `path` or `file` parameter must be provided.\"\n if path is None:\n path = file\n if command != \"view\" and working_dir == \"repo\":\n return \"The `view` command is the only allowed command when `working_dir` is `repo`.\"\n\n # Reject absolute paths: ``Path(\"/abs/base\") / \"/abs/other\"`` resolves to\n # ``/abs/other``, which would silently bypass ``working_dir`` and let the\n # agent write outside the docs path. Force the agent to pass a path\n # relative to the chosen working_dir.\n if os.path.isabs(path):\n return (\n f\"Error: `path` must be relative to `working_dir` ({working_dir!r}), \"\n f\"got absolute path {path!r}. Pass a relative path like \"\n f\"'module_name.md' (resolved under absolute_docs_path when \"\n f\"working_dir='docs').\"\n )\n\n view_range = _coerce_json_arg(view_range)\n insert_line = _coerce_json_arg(insert_line)\n\n edit_tool = EditTool(self._deps.registry, self._deps.absolute_docs_path)\n\n base_dir = (\n self._deps.absolute_docs_path\n if working_dir == \"docs\"\n else self._deps.absolute_repo_path\n )\n absolute_path = str(Path(base_dir) / path)\n\n # Defense in depth: even with a relative path, ``..`` segments could\n # escape ``base_dir``. Verify the resolved path stays inside.\n try:\n resolved = Path(absolute_path).resolve()\n base_resolved = Path(base_dir).resolve()\n resolved.relative_to(base_resolved)\n except ValueError:\n return (\n f\"Error: resolved path {absolute_path!r} escapes \"\n f\"working_dir={working_dir!r} root {base_dir!r}. \"\n f\"Pass a path that stays inside the working directory.\"\n )\n\n edit_tool(\n command=command,\n path=absolute_path,\n file_text=file_text,\n view_range=view_range,\n old_str=old_str,\n new_str=new_str,\n insert_line=insert_line,\n )\n\n result = \"\\n\".join(edit_tool.logs)\n\n if command != \"view\" and path.endswith(\".md\"):\n mermaid_validation = await validate_mermaid_diagrams(absolute_path, path)\n result = result + \"\\n---------- Mermaid validation ----------\\n\" + mermaid_validation\n\n return result", - "start_line": 133, - "end_line": 224, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "working_dir", - "command", - "path", - "file", - "file_text", - "view_range", - "old_str", - "new_str", - "insert_line" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CawToolKit", - "display_name": "method CawToolKit.str_replace_editor", - "component_id": "codewiki/src/be/caw_toolkit.py::CawToolKit.str_replace_editor", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/caw_toolkit.py::CawToolKit.generate_sub_module_documentation": { - "id": "codewiki/src/be/caw_toolkit.py::CawToolKit.generate_sub_module_documentation", - "name": "CawToolKit.generate_sub_module_documentation", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/caw_toolkit.py", - "relative_path": "codewiki/src/be/caw_toolkit.py", - "depends_on": [ - "codewiki/src/be/caw_toolkit.py::_heartbeat" - ], - "source_code": " async def generate_sub_module_documentation(\n self, sub_module_specs: dict[str, list[str]], ctx: Context\n ) -> str:\n if not self._allow_subagent:\n return (\n \"generate_sub_module_documentation is NOT available for this module \"\n \"(leaf module: single-file or below the token threshold, or max recursion \"\n \"depth reached). DO NOT call this tool again for this module. \"\n \"Instead, write the documentation directly with `str_replace_editor` \"\n f\"(create command) as a single `{self._deps.current_module_name}.md` \"\n \"file covering the provided core components inline (architecture, \"\n \"components, diagrams, etc.) β€” no sub-module fan-out.\"\n )\n\n # Run the blocking recursion in a worker thread so the caw MCP server's\n # event loop stays responsive while sub-agents run. A heartbeat task\n # emits MCP progress notifications so the CLI does not treat the long\n # tool call as a stalled / cancelled invocation.\n work = asyncio.create_task(\n asyncio.to_thread(self._run_sub_modules, sub_module_specs)\n )\n heartbeat = asyncio.create_task(_heartbeat(ctx, work))\n try:\n return await work\n finally:\n heartbeat.cancel()\n with contextlib.suppress(asyncio.CancelledError):\n await heartbeat", - "start_line": 242, - "end_line": 269, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "sub_module_specs", - "ctx" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CawToolKit", - "display_name": "method CawToolKit.generate_sub_module_documentation", - "component_id": "codewiki/src/be/caw_toolkit.py::CawToolKit.generate_sub_module_documentation", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/caw_toolkit.py::CawToolKit._run_sub_modules": { - "id": "codewiki/src/be/caw_toolkit.py::CawToolKit._run_sub_modules", - "name": "CawToolKit._run_sub_modules", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/caw_toolkit.py", - "relative_path": "codewiki/src/be/caw_toolkit.py", - "depends_on": [ - "codewiki/src/be/caw_backend.py::CawBackend._run_module_agent_sync", - "codewiki/src/be/module_naming.py::normalize_sub_module_specs" - ], - "source_code": " def _run_sub_modules(self, sub_module_specs: dict[str, list[str]]) -> str:\n deps = self._deps\n previous_module_name = deps.current_module_name\n\n # Resolve name collisions against the module tree and files already on\n # disk before touching the tree (issue #76): docs live in one flat directory.\n name_map = normalize_sub_module_specs(\n sub_module_specs,\n previous_module_name,\n deps.module_tree,\n deps.absolute_docs_path,\n )\n final_specs = {\n name_map[requested_name]: core_ids\n for requested_name, core_ids in sub_module_specs.items()\n }\n\n # Add sub-modules to the in-memory module tree.\n value = deps.module_tree\n for key in deps.path_to_current_module:\n value = value[key][\"children\"]\n for sub_name, core_ids in final_specs.items():\n value[sub_name] = {\"components\": core_ids, \"children\": {}}\n\n try:\n for sub_name, core_ids in final_specs.items():\n indent = \" \" * deps.current_depth\n arrow = \"└─\" if deps.current_depth > 0 else \"β†’\"\n logger.info(\"%s%s Generating documentation for sub-module: %s\", indent, arrow, sub_name)\n\n deps.current_module_name = sub_name\n deps.path_to_current_module.append(sub_name)\n deps.current_depth += 1\n try:\n # Spawn a fresh caw session for the sub-module. We already\n # run inside a worker thread (started by the parent tool\n # call), so call the sync entry point directly to avoid\n # double-wrapping. ``start_depth`` carries the parent's\n # depth so the sub-agent's max_depth guard stays accurate.\n self._backend._run_module_agent_sync(\n module_name=sub_name,\n components=deps.components,\n core_component_ids=core_ids,\n module_path=list(deps.path_to_current_module),\n working_dir=deps.absolute_docs_path,\n start_depth=deps.current_depth,\n module_tree=deps.module_tree,\n )\n finally:\n deps.path_to_current_module.pop()\n deps.current_depth -= 1\n finally:\n deps.current_module_name = previous_module_name\n\n # Report what actually landed on disk so the parent agent links real filenames.\n saved = []\n missing = []\n for requested_name, final_name in name_map.items():\n entry = f\"{final_name}.md\"\n if final_name != requested_name:\n entry += f\" (requested '{requested_name}', renamed to avoid a collision)\"\n if os.path.exists(os.path.join(deps.absolute_docs_path, f\"{final_name}.md\")):\n saved.append(entry)\n else:\n missing.append(entry)\n\n report = f\"Saved documentations: {', '.join(saved) if saved else 'none'}.\"\n if missing:\n report += f\" MISSING (generation did not produce these files): {', '.join(missing)}.\"\n logger.warning(\"Sub-module documentation missing after generation: %s\", \", \".join(missing))\n return report", - "start_line": 275, - "end_line": 345, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "sub_module_specs" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CawToolKit", - "display_name": "method CawToolKit._run_sub_modules", - "component_id": "codewiki/src/be/caw_toolkit.py::CawToolKit._run_sub_modules", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/cluster_modules.py::format_potential_core_components": { - "id": "codewiki/src/be/cluster_modules.py::format_potential_core_components", - "name": "format_potential_core_components", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/cluster_modules.py", - "relative_path": "codewiki/src/be/cluster_modules.py", - "depends_on": [], - "source_code": "def format_potential_core_components(leaf_nodes: List[str], components: Dict[str, Node]) -> tuple[str, str]:\n \"\"\"\n Format the potential core components into a string that can be used in the prompt.\n \"\"\"\n # Filter out any invalid leaf nodes that don't exist in components\n valid_leaf_nodes = []\n for leaf_node in leaf_nodes:\n if leaf_node in components:\n valid_leaf_nodes.append(leaf_node)\n else:\n logger.warning(f\"Skipping invalid leaf node '{leaf_node}' - not found in components\")\n \n #group leaf nodes by file\n leaf_nodes_by_file = defaultdict(list)\n for leaf_node in valid_leaf_nodes:\n leaf_nodes_by_file[components[leaf_node].relative_path].append(leaf_node)\n\n potential_core_components = \"\"\n potential_core_components_with_code = \"\"\n for file, leaf_nodes in dict(sorted(leaf_nodes_by_file.items())).items():\n potential_core_components += f\"# {file}\\n\"\n potential_core_components_with_code += f\"# {file}\\n\"\n for leaf_node in leaf_nodes:\n potential_core_components += f\"\\t{leaf_node}\\n\"\n potential_core_components_with_code += f\"\\t{leaf_node}\\n\"\n potential_core_components_with_code += f\"{components[leaf_node].source_code}\\n\"\n\n return potential_core_components, potential_core_components_with_code", - "start_line": 20, - "end_line": 47, - "has_docstring": true, - "docstring": "Format the potential core components into a string that can be used in the prompt.", - "parameters": [ - "leaf_nodes", - "components" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function format_potential_core_components", - "component_id": "codewiki/src/be/cluster_modules.py::format_potential_core_components", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/cluster_modules.py::get_clustering_input_token_count": { - "id": "codewiki/src/be/cluster_modules.py::get_clustering_input_token_count", - "name": "get_clustering_input_token_count", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/cluster_modules.py", - "relative_path": "codewiki/src/be/cluster_modules.py", - "depends_on": [ - "codewiki/src/be/cluster_modules.py::format_potential_core_components", - "codewiki/src/be/utils.py::count_tokens" - ], - "source_code": "def get_clustering_input_token_count(\n leaf_nodes: List[str], components: Dict[str, Node]\n) -> int:\n \"\"\"Count the tokens used to decide whether a module needs clustering.\"\"\"\n _, potential_core_components_with_code = format_potential_core_components(\n leaf_nodes, components\n )\n return count_tokens(potential_core_components_with_code)", - "start_line": 50, - "end_line": 57, - "has_docstring": true, - "docstring": "Count the tokens used to decide whether a module needs clustering.", - "parameters": [ - "leaf_nodes", - "components" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function get_clustering_input_token_count", - "component_id": "codewiki/src/be/cluster_modules.py::get_clustering_input_token_count", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/cluster_modules.py::cluster_modules": { - "id": "codewiki/src/be/cluster_modules.py::cluster_modules", - "name": "cluster_modules", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/cluster_modules.py", - "relative_path": "codewiki/src/be/cluster_modules.py", - "depends_on": [ - "codewiki/src/be/llm_services.py::call_llm", - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/cluster_modules.py::cluster_modules", - "codewiki/src/be/prompt_template.py::format_cluster_prompt", - "codewiki/src/be/utils.py::count_tokens", - "codewiki/src/be/cluster_modules.py::format_potential_core_components", - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": "def cluster_modules(\n leaf_nodes: List[str],\n components: Dict[str, Node],\n config: Config,\n current_module_tree: dict[str, Any] = {},\n current_module_name: str = None,\n current_module_path: List[str] = [],\n completer: Optional[Completer] = None,\n) -> Dict[str, Any]:\n \"\"\"\n Cluster the potential core components into modules.\n\n Args:\n completer: optional ``(prompt: str) -> str`` callable. When provided,\n clustering calls go through this completer instead of the legacy\n ``call_llm``. This is how the LLMBackend abstraction injects\n subscription-mode (caw) routing. If ``None``, falls back to\n ``call_llm`` for backward compatibility with direct callers.\n \"\"\"\n potential_core_components, potential_core_components_with_code = (\n format_potential_core_components(leaf_nodes, components)\n )\n input_tokens = count_tokens(potential_core_components_with_code)\n threshold = config.max_token_per_module\n module_label = current_module_name or \"repository\"\n\n logger.info(\n \"Module clustering input for %s: %d leaf nodes, %d tokens, threshold %d\",\n module_label,\n len(leaf_nodes),\n input_tokens,\n threshold,\n )\n\n if input_tokens <= threshold:\n logger.info(\n \"Skipping LLM module clustering for %s because %d tokens fit within the \"\n \"%d-token threshold; using whole-module documentation mode.\",\n module_label,\n input_tokens,\n threshold,\n )\n if current_module_name is None:\n leaf_files = {\n components[leaf_node].relative_path\n for leaf_node in leaf_nodes\n if leaf_node in components\n }\n all_files = {c.relative_path for c in components.values()}\n if all_files and len(leaf_files) / len(all_files) < LOW_COVERAGE_RATIO:\n logger.warning(\n \"Leaf-node entry points cover only %d of %d parsed files (%.0f%%). \"\n \"Whole-repository documentation will start from these entry points and \"\n \"rely on agent exploration to reach the rest of the codebase.\",\n len(leaf_files),\n len(all_files),\n 100 * len(leaf_files) / len(all_files),\n )\n return {}\n\n prompt = format_cluster_prompt(potential_core_components, current_module_tree, current_module_name)\n logger.info(\n \"Requesting LLM module clustering for %s because %d tokens exceed the %d-token threshold.\",\n module_label,\n input_tokens,\n threshold,\n )\n if completer is not None:\n response = completer(prompt)\n else:\n response = call_llm(prompt, config, model=config.cluster_model)\n\n #parse the response\n try:\n if \"\" not in response or \"\" not in response:\n logger.warning(\n \"Invalid LLM clustering response for %s: missing \"\n \"tags; falling back to whole-module documentation. Response preview: %s...\",\n module_label,\n response[:200],\n )\n return {}\n \n response_content = response.split(\"\")[1].split(\"\")[0]\n module_tree = eval(response_content)\n \n if not isinstance(module_tree, dict):\n logger.error(f\"Invalid module tree format - expected dict, got {type(module_tree)}\")\n return {}\n \n except Exception as e:\n logger.warning(\n \"Failed to parse LLM clustering response for %s; falling back to \"\n \"whole-module documentation. Error: %s. Response preview: %s...\",\n module_label,\n e,\n response[:200],\n )\n logger.error(f\"Traceback: {traceback.format_exc()}\")\n return {}\n\n # check if the module tree is valid\n if len(module_tree) <= 1:\n logger.info(\n \"Skipping LLM clustering result for %s because it produced only \"\n \"%d module(s); using whole-module documentation mode.\",\n module_label,\n len(module_tree),\n )\n return {}\n\n logger.info(\n \"LLM module clustering for %s produced %d top-level modules.\",\n module_label,\n len(module_tree),\n )\n\n if current_module_tree == {}:\n current_module_tree = module_tree\n else:\n value = current_module_tree\n for key in current_module_path:\n value = value[key][\"children\"]\n for module_name, module_info in module_tree.items():\n del module_info[\"path\"]\n value[module_name] = module_info\n\n for module_name, module_info in module_tree.items():\n sub_leaf_nodes = module_info.get(\"components\", [])\n \n # Filter sub_leaf_nodes to ensure they exist in components\n valid_sub_leaf_nodes = []\n for node in sub_leaf_nodes:\n if node in components:\n valid_sub_leaf_nodes.append(node)\n else:\n logger.warning(f\"Skipping invalid sub leaf node '{node}' in module '{module_name}' - not found in components\")\n \n current_module_path.append(module_name)\n module_info[\"children\"] = {}\n module_info[\"children\"] = cluster_modules(\n valid_sub_leaf_nodes,\n components,\n config,\n current_module_tree,\n module_name,\n current_module_path,\n completer=completer,\n )\n current_module_path.pop()\n\n return module_tree", - "start_line": 60, - "end_line": 211, - "has_docstring": true, - "docstring": "Cluster the potential core components into modules.\n\nArgs:\n completer: optional ``(prompt: str) -> str`` callable. When provided,\n clustering calls go through this completer instead of the legacy\n ``call_llm``. This is how the LLMBackend abstraction injects\n subscription-mode (caw) routing. If ``None``, falls back to\n ``call_llm`` for backward compatibility with direct callers.", - "parameters": [ - "leaf_nodes", - "components", - "config", - "current_module_tree", - "current_module_name", - "current_module_path", - "completer" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function cluster_modules", - "component_id": "codewiki/src/be/cluster_modules.py::cluster_modules", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService": { - "id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService", - "name": "AnalysisService", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "depends_on": [], - "source_code": "class AnalysisService:\n \"\"\"\n Centralized analysis service supporting multiple programming languages.\n\n This service orchestrates the complete analysis workflow:\n 1. Repository cloning and validation\n 2. File structure analysis with filtering\n 3. Multi-language AST parsing and call graph generation\n 4. Result consolidation and cleanup\n\n \"\"\"\n\n def __init__(self):\n \"\"\"Initialize the analysis service with language-specific analyzers.\"\"\"\n self.call_graph_analyzer = CallGraphAnalyzer()\n self._temp_directories = []\n\n def analyze_local_repository(\n self,\n repo_path: str,\n max_files: int = 100,\n languages: Optional[List[str]] = None,\n use_gitignore: bool = True,\n ) -> Dict[str, Any]:\n \"\"\"\n Analyze a local repository folder.\n \n Args:\n repo_path: Path to local repository folder\n max_files: Maximum number of files to analyze\n languages: List of languages to include (e.g., ['python', 'javascript'])\n use_gitignore: Whether to apply Git ignore rules\n \n Returns:\n Dict with analysis results including nodes and relationships\n \"\"\"\n try:\n logger.debug(f\"Analyzing local repository at {repo_path}\")\n \n # Get repo analyzer to find files\n repo_analyzer = RepoAnalyzer(use_gitignore=use_gitignore)\n structure_result = repo_analyzer.analyze_repository_structure(repo_path)\n \n # Extract code files\n code_files = self.call_graph_analyzer.extract_code_files(structure_result[\"file_tree\"])\n \n # Filter by languages if specified\n if languages:\n code_files = [f for f in code_files if f.get(\"language\") in languages]\n \n # Limit number of files\n if len(code_files) > max_files:\n code_files = code_files[:max_files]\n logger.debug(f\"Limited analysis to {max_files} files\")\n \n logger.debug(f\"Analyzing {len(code_files)} files\")\n \n # Analyze files\n result = self.call_graph_analyzer.analyze_code_files(code_files, repo_path)\n \n return {\n \"nodes\": result.get(\"functions\", {}),\n \"relationships\": result.get(\"relationships\", []),\n \"summary\": {\n \"total_files\": len(code_files),\n \"total_nodes\": len(result.get(\"functions\", {})),\n \"total_relationships\": len(result.get(\"relationships\", []))\n }\n }\n \n except Exception as e:\n logger.error(f\"Local repository analysis failed: {str(e)}\", exc_info=True)\n raise RuntimeError(f\"Analysis failed: {str(e)}\")\n\n def analyze_repository_full(\n self,\n github_url: str,\n include_patterns: Optional[List[str]] = None,\n exclude_patterns: Optional[List[str]] = None,\n use_gitignore: bool = True,\n ) -> AnalysisResult:\n \"\"\"\n Perform complete repository analysis including call graph generation.\n\n Args:\n github_url: GitHub repository URL to analyze\n include_patterns: File patterns to include (e.g., ['*.py', '*.js'])\n exclude_patterns: Additional patterns to exclude\n use_gitignore: Whether to apply Git ignore rules\n\n Returns:\n AnalysisResult: Complete analysis with functions, relationships, and visualization\n\n Raises:\n ValueError: If GitHub URL is invalid\n RuntimeError: If analysis fails\n \"\"\"\n temp_dir = None\n try:\n logger.debug(f\"Starting full analysis of {github_url}\")\n\n temp_dir = self._clone_repository(github_url)\n repo_info = self._parse_repository_info(github_url)\n\n logger.debug(\"Analyzing repository file structure...\")\n structure_result = self._analyze_structure(\n temp_dir, include_patterns, exclude_patterns, use_gitignore\n )\n logger.debug(f\"Found {structure_result['summary']['total_files']} files to analyze.\")\n\n logger.debug(\"Starting call graph analysis...\")\n call_graph_result = self._analyze_call_graph(structure_result[\"file_tree\"], temp_dir)\n logger.debug(\n f\"Call graph analysis complete. Found {call_graph_result['call_graph']['total_functions']} functions.\"\n )\n\n readme_content = self._read_readme_file(temp_dir)\n\n analysis_result = AnalysisResult(\n repository=Repository(\n url=repo_info[\"url\"],\n name=repo_info[\"name\"],\n clone_path=temp_dir,\n analysis_id=f\"{repo_info['owner']}-{repo_info['name']}\",\n ),\n functions=call_graph_result[\"functions\"],\n relationships=call_graph_result[\"relationships\"],\n file_tree=structure_result[\"file_tree\"],\n summary={\n **structure_result[\"summary\"],\n **call_graph_result[\"call_graph\"],\n \"analysis_type\": \"full\",\n \"languages_analyzed\": call_graph_result[\"call_graph\"][\"languages_found\"],\n },\n visualization=call_graph_result[\"visualization\"],\n readme_content=readme_content,\n )\n\n logger.debug(f\"Cleaning up temporary repository directory: {temp_dir}\")\n self._cleanup_repository(temp_dir)\n\n logger.debug(\n f\"Analysis completed: {analysis_result.summary['total_functions']} functions found\"\n )\n return analysis_result\n\n except Exception as e:\n logger.error(f\"Analysis failed: {str(e)}\", exc_info=True)\n if \"temp_dir\" in locals() and Path(temp_dir).exists():\n self._cleanup_repository(temp_dir)\n raise RuntimeError(f\"Repository analysis failed: {str(e)}\")\n\n def analyze_repository_structure_only(\n self,\n github_url: str,\n include_patterns: Optional[List[str]] = None,\n exclude_patterns: Optional[List[str]] = None,\n use_gitignore: bool = True,\n ) -> Dict[str, Any]:\n \"\"\"\n Perform lightweight structure-only analysis without call graph generation.\n\n Args:\n github_url: GitHub repository URL to analyze\n include_patterns: File patterns to include\n exclude_patterns: Additional patterns to exclude\n use_gitignore: Whether to apply Git ignore rules\n\n Returns:\n Dict: Repository structure with file tree and summary statistics\n \"\"\"\n temp_dir = None\n try:\n logger.debug(f\"Starting structure analysis of {github_url}\")\n\n temp_dir = self._clone_repository(github_url)\n repo_info = self._parse_repository_info(github_url)\n\n structure_result = self._analyze_structure(\n temp_dir, include_patterns, exclude_patterns, use_gitignore\n )\n\n result = {\n \"repository\": repo_info,\n \"file_tree\": structure_result[\"file_tree\"],\n \"file_summary\": {\n **structure_result[\"summary\"],\n \"analysis_type\": \"structure_only\",\n },\n }\n\n self._cleanup_repository(temp_dir)\n\n logger.debug(\n f\"Structure analysis completed: {result['file_summary']['total_files']} files found\"\n )\n return result\n\n except Exception as e:\n if temp_dir:\n self._cleanup_repository(temp_dir)\n logger.error(f\"Structure analysis failed for {github_url}: {str(e)}\")\n logger.error(f\"Traceback: {traceback.format_exc()}\")\n raise RuntimeError(f\"Structure analysis failed: {str(e)}\") from e\n\n def _clone_repository(self, github_url: str) -> str:\n \"\"\"Clone repository and return temp dir path.\"\"\"\n logger.debug(f\"Cloning {github_url}...\")\n temp_dir = clone_repository(github_url)\n logger.debug(f\"Repository cloned to {temp_dir}\")\n self._temp_directories.append(temp_dir)\n return temp_dir\n\n def _parse_repository_info(self, github_url: str) -> Dict[str, str]:\n \"\"\"Parse GitHub URL and extract repository metadata.\"\"\"\n return parse_github_url(github_url)\n\n def _analyze_structure(\n self,\n repo_dir: str,\n include_patterns: Optional[List[str]],\n exclude_patterns: Optional[List[str]],\n use_gitignore: bool = True,\n ) -> Dict[str, Any]:\n \"\"\"Analyze repository file structure with filtering.\"\"\"\n logger.debug(\n \"Initializing RepoAnalyzer with include: %s, exclude: %s, use_gitignore: %s\",\n include_patterns,\n exclude_patterns,\n use_gitignore,\n )\n repo_analyzer = RepoAnalyzer(include_patterns, exclude_patterns, use_gitignore)\n return repo_analyzer.analyze_repository_structure(repo_dir)\n\n def _read_readme_file(self, repo_dir: str) -> Optional[str]:\n \"\"\"Find and read the README file from the repository root.\"\"\"\n # possible_readme_names = [\"README.md\", \"README\", \"readme.md\", \"README.txt\"]\n # for name in possible_readme_names:\n # readme_path = Path(repo_dir) / name\n # if readme_path.exists():\n # try:\n # logger.debug(f\"Found README file at {readme_path}\")\n # return readme_path.read_text(encoding=\"utf-8\")\n # except Exception as e:\n # logger.warning(f\"Could not read README file at {readme_path}: {e}\")\n # return None\n # logger.debug(\"No README file found in repository root.\")\n # return None\n base = Path(repo_dir)\n possible_readme_names = [\"README.md\", \"README\", \"readme.md\", \"README.txt\"]\n for name in possible_readme_names:\n p = base / name\n if p.exists():\n try:\n assert_safe_path(base, p)\n logger.debug(f\"Found README file at {p}\")\n return safe_open_text(base, p, encoding=\"utf-8\")\n except Exception as e:\n logger.warning(f\"Skipping unsafe/ unreadable README at {p}: {e}\")\n return None\n logger.debug(\"No README file found in repository root.\")\n return None\n\n def _analyze_call_graph(self, file_tree: Dict[str, Any], repo_dir: str) -> Dict[str, Any]:\n \"\"\"\n Perform multi-language call graph analysis.\n\n This method will be expanded to handle:\n - Python AST analysis (current)\n - JavaScript/TypeScript AST analysis (planned)\n - Additional language support (future)\n \"\"\"\n logger.debug(\"Extracting code files from file tree...\")\n code_files = self.call_graph_analyzer.extract_code_files(file_tree)\n\n logger.debug(f\"Found {len(code_files)} total code files. Filtering for supported languages.\")\n supported_files = self._filter_supported_languages(code_files)\n logger.debug(f\"Analyzing {len(supported_files)} supported files.\")\n\n result = self.call_graph_analyzer.analyze_code_files(supported_files, repo_dir)\n\n result[\"call_graph\"][\"supported_languages\"] = self._get_supported_languages()\n result[\"call_graph\"][\"unsupported_files\"] = len(code_files) - len(supported_files)\n\n return result\n\n def _filter_supported_languages(self, code_files: List[Dict]) -> List[Dict]:\n \"\"\"\n Filter code files to only include supported languages.\n\n Supports Python, JavaScript, TypeScript, Java, C#, C, C++, PHP, Go, and Rust.\n \"\"\"\n supported_languages = {\n \"python\",\n \"javascript\",\n \"typescript\",\n \"java\",\n \"csharp\",\n \"c\",\n \"cpp\",\n \"php\",\n \"go\",\n \"rust\",\n \"kotlin\",\n }\n\n return [\n file_info\n for file_info in code_files\n if file_info.get(\"language\") in supported_languages\n ]\n\n def _get_supported_languages(self) -> List[str]:\n \"\"\"Get list of currently supported languages for analysis.\"\"\"\n return [\"python\", \"javascript\", \"typescript\", \"java\", \"csharp\", \"c\", \"cpp\", \"php\", \"kotlin\"]\n\n def _cleanup_repository(self, temp_dir: str):\n \"\"\"Clean up cloned repository.\"\"\"\n logger.debug(f\"Attempting to clean up {temp_dir}\")\n cleanup_repository(temp_dir)\n if temp_dir in self._temp_directories:\n self._temp_directories.remove(temp_dir)\n\n def cleanup_all(self):\n \"\"\"Clean up all tracked temporary directories.\"\"\"\n for temp_dir in self._temp_directories[:]:\n self._cleanup_repository(temp_dir)\n\n def __del__(self):\n \"\"\"Ensure cleanup on service destruction.\"\"\"\n self.cleanup_all()", - "start_line": 24, - "end_line": 354, - "has_docstring": true, - "docstring": "Centralized analysis service supporting multiple programming languages.\n\nThis service orchestrates the complete analysis workflow:\n1. Repository cloning and validation\n2. File structure analysis with filtering\n3. Multi-language AST parsing and call graph generation\n4. Result consolidation and cleanup", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class AnalysisService", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.__init__": { - "id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.__init__", - "name": "AnalysisService.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer" - ], - "source_code": " def __init__(self):\n \"\"\"Initialize the analysis service with language-specific analyzers.\"\"\"\n self.call_graph_analyzer = CallGraphAnalyzer()\n self._temp_directories = []", - "start_line": 36, - "end_line": 39, - "has_docstring": true, - "docstring": "Initialize the analysis service with language-specific analyzers.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "AnalysisService", - "display_name": "method AnalysisService.__init__", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.analyze_local_repository": { - "id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.analyze_local_repository", - "name": "AnalysisService.analyze_local_repository", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer.analyze_code_files", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer.extract_code_files", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer.analyze_repository_structure", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer", - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": " def analyze_local_repository(\n self,\n repo_path: str,\n max_files: int = 100,\n languages: Optional[List[str]] = None,\n use_gitignore: bool = True,\n ) -> Dict[str, Any]:\n \"\"\"\n Analyze a local repository folder.\n \n Args:\n repo_path: Path to local repository folder\n max_files: Maximum number of files to analyze\n languages: List of languages to include (e.g., ['python', 'javascript'])\n use_gitignore: Whether to apply Git ignore rules\n \n Returns:\n Dict with analysis results including nodes and relationships\n \"\"\"\n try:\n logger.debug(f\"Analyzing local repository at {repo_path}\")\n \n # Get repo analyzer to find files\n repo_analyzer = RepoAnalyzer(use_gitignore=use_gitignore)\n structure_result = repo_analyzer.analyze_repository_structure(repo_path)\n \n # Extract code files\n code_files = self.call_graph_analyzer.extract_code_files(structure_result[\"file_tree\"])\n \n # Filter by languages if specified\n if languages:\n code_files = [f for f in code_files if f.get(\"language\") in languages]\n \n # Limit number of files\n if len(code_files) > max_files:\n code_files = code_files[:max_files]\n logger.debug(f\"Limited analysis to {max_files} files\")\n \n logger.debug(f\"Analyzing {len(code_files)} files\")\n \n # Analyze files\n result = self.call_graph_analyzer.analyze_code_files(code_files, repo_path)\n \n return {\n \"nodes\": result.get(\"functions\", {}),\n \"relationships\": result.get(\"relationships\", []),\n \"summary\": {\n \"total_files\": len(code_files),\n \"total_nodes\": len(result.get(\"functions\", {})),\n \"total_relationships\": len(result.get(\"relationships\", []))\n }\n }\n \n except Exception as e:\n logger.error(f\"Local repository analysis failed: {str(e)}\", exc_info=True)\n raise RuntimeError(f\"Analysis failed: {str(e)}\")", - "start_line": 41, - "end_line": 96, - "has_docstring": true, - "docstring": "Analyze a local repository folder.\n\nArgs:\n repo_path: Path to local repository folder\n max_files: Maximum number of files to analyze\n languages: List of languages to include (e.g., ['python', 'javascript'])\n use_gitignore: Whether to apply Git ignore rules\n \nReturns:\n Dict with analysis results including nodes and relationships", - "parameters": [ - "self", - "repo_path", - "max_files", - "languages", - "use_gitignore" - ], - "node_type": "method", - "base_classes": null, - "class_name": "AnalysisService", - "display_name": "method AnalysisService.analyze_local_repository", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.analyze_local_repository", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.analyze_repository_full": { - "id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.analyze_repository_full", - "name": "AnalysisService.analyze_repository_full", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._cleanup_repository", - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._analyze_call_graph", - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._clone_repository", - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._analyze_structure", - "codewiki/src/be/dependency_analyzer/models/analysis.py::AnalysisResult", - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._read_readme_file", - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._parse_repository_info", - "codewiki/src/be/dependency_analyzer/models/core.py::Repository", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": " def analyze_repository_full(\n self,\n github_url: str,\n include_patterns: Optional[List[str]] = None,\n exclude_patterns: Optional[List[str]] = None,\n use_gitignore: bool = True,\n ) -> AnalysisResult:\n \"\"\"\n Perform complete repository analysis including call graph generation.\n\n Args:\n github_url: GitHub repository URL to analyze\n include_patterns: File patterns to include (e.g., ['*.py', '*.js'])\n exclude_patterns: Additional patterns to exclude\n use_gitignore: Whether to apply Git ignore rules\n\n Returns:\n AnalysisResult: Complete analysis with functions, relationships, and visualization\n\n Raises:\n ValueError: If GitHub URL is invalid\n RuntimeError: If analysis fails\n \"\"\"\n temp_dir = None\n try:\n logger.debug(f\"Starting full analysis of {github_url}\")\n\n temp_dir = self._clone_repository(github_url)\n repo_info = self._parse_repository_info(github_url)\n\n logger.debug(\"Analyzing repository file structure...\")\n structure_result = self._analyze_structure(\n temp_dir, include_patterns, exclude_patterns, use_gitignore\n )\n logger.debug(f\"Found {structure_result['summary']['total_files']} files to analyze.\")\n\n logger.debug(\"Starting call graph analysis...\")\n call_graph_result = self._analyze_call_graph(structure_result[\"file_tree\"], temp_dir)\n logger.debug(\n f\"Call graph analysis complete. Found {call_graph_result['call_graph']['total_functions']} functions.\"\n )\n\n readme_content = self._read_readme_file(temp_dir)\n\n analysis_result = AnalysisResult(\n repository=Repository(\n url=repo_info[\"url\"],\n name=repo_info[\"name\"],\n clone_path=temp_dir,\n analysis_id=f\"{repo_info['owner']}-{repo_info['name']}\",\n ),\n functions=call_graph_result[\"functions\"],\n relationships=call_graph_result[\"relationships\"],\n file_tree=structure_result[\"file_tree\"],\n summary={\n **structure_result[\"summary\"],\n **call_graph_result[\"call_graph\"],\n \"analysis_type\": \"full\",\n \"languages_analyzed\": call_graph_result[\"call_graph\"][\"languages_found\"],\n },\n visualization=call_graph_result[\"visualization\"],\n readme_content=readme_content,\n )\n\n logger.debug(f\"Cleaning up temporary repository directory: {temp_dir}\")\n self._cleanup_repository(temp_dir)\n\n logger.debug(\n f\"Analysis completed: {analysis_result.summary['total_functions']} functions found\"\n )\n return analysis_result\n\n except Exception as e:\n logger.error(f\"Analysis failed: {str(e)}\", exc_info=True)\n if \"temp_dir\" in locals() and Path(temp_dir).exists():\n self._cleanup_repository(temp_dir)\n raise RuntimeError(f\"Repository analysis failed: {str(e)}\")", - "start_line": 98, - "end_line": 174, - "has_docstring": true, - "docstring": "Perform complete repository analysis including call graph generation.\n\nArgs:\n github_url: GitHub repository URL to analyze\n include_patterns: File patterns to include (e.g., ['*.py', '*.js'])\n exclude_patterns: Additional patterns to exclude\n use_gitignore: Whether to apply Git ignore rules\n\nReturns:\n AnalysisResult: Complete analysis with functions, relationships, and visualization\n\nRaises:\n ValueError: If GitHub URL is invalid\n RuntimeError: If analysis fails", - "parameters": [ - "self", - "github_url", - "include_patterns", - "exclude_patterns", - "use_gitignore" - ], - "node_type": "method", - "base_classes": null, - "class_name": "AnalysisService", - "display_name": "method AnalysisService.analyze_repository_full", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.analyze_repository_full", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.analyze_repository_structure_only": { - "id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.analyze_repository_structure_only", - "name": "AnalysisService.analyze_repository_structure_only", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._cleanup_repository", - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._clone_repository", - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._analyze_structure", - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._parse_repository_info", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": " def analyze_repository_structure_only(\n self,\n github_url: str,\n include_patterns: Optional[List[str]] = None,\n exclude_patterns: Optional[List[str]] = None,\n use_gitignore: bool = True,\n ) -> Dict[str, Any]:\n \"\"\"\n Perform lightweight structure-only analysis without call graph generation.\n\n Args:\n github_url: GitHub repository URL to analyze\n include_patterns: File patterns to include\n exclude_patterns: Additional patterns to exclude\n use_gitignore: Whether to apply Git ignore rules\n\n Returns:\n Dict: Repository structure with file tree and summary statistics\n \"\"\"\n temp_dir = None\n try:\n logger.debug(f\"Starting structure analysis of {github_url}\")\n\n temp_dir = self._clone_repository(github_url)\n repo_info = self._parse_repository_info(github_url)\n\n structure_result = self._analyze_structure(\n temp_dir, include_patterns, exclude_patterns, use_gitignore\n )\n\n result = {\n \"repository\": repo_info,\n \"file_tree\": structure_result[\"file_tree\"],\n \"file_summary\": {\n **structure_result[\"summary\"],\n \"analysis_type\": \"structure_only\",\n },\n }\n\n self._cleanup_repository(temp_dir)\n\n logger.debug(\n f\"Structure analysis completed: {result['file_summary']['total_files']} files found\"\n )\n return result\n\n except Exception as e:\n if temp_dir:\n self._cleanup_repository(temp_dir)\n logger.error(f\"Structure analysis failed for {github_url}: {str(e)}\")\n logger.error(f\"Traceback: {traceback.format_exc()}\")\n raise RuntimeError(f\"Structure analysis failed: {str(e)}\") from e", - "start_line": 176, - "end_line": 227, - "has_docstring": true, - "docstring": "Perform lightweight structure-only analysis without call graph generation.\n\nArgs:\n github_url: GitHub repository URL to analyze\n include_patterns: File patterns to include\n exclude_patterns: Additional patterns to exclude\n use_gitignore: Whether to apply Git ignore rules\n\nReturns:\n Dict: Repository structure with file tree and summary statistics", - "parameters": [ - "self", - "github_url", - "include_patterns", - "exclude_patterns", - "use_gitignore" - ], - "node_type": "method", - "base_classes": null, - "class_name": "AnalysisService", - "display_name": "method AnalysisService.analyze_repository_structure_only", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.analyze_repository_structure_only", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._clone_repository": { - "id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._clone_repository", - "name": "AnalysisService._clone_repository", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "depends_on": [ - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/src/be/dependency_analyzer/analysis/cloning.py::clone_repository" - ], - "source_code": " def _clone_repository(self, github_url: str) -> str:\n \"\"\"Clone repository and return temp dir path.\"\"\"\n logger.debug(f\"Cloning {github_url}...\")\n temp_dir = clone_repository(github_url)\n logger.debug(f\"Repository cloned to {temp_dir}\")\n self._temp_directories.append(temp_dir)\n return temp_dir", - "start_line": 229, - "end_line": 235, - "has_docstring": true, - "docstring": "Clone repository and return temp dir path.", - "parameters": [ - "self", - "github_url" - ], - "node_type": "method", - "base_classes": null, - "class_name": "AnalysisService", - "display_name": "method AnalysisService._clone_repository", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._clone_repository", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._parse_repository_info": { - "id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._parse_repository_info", - "name": "AnalysisService._parse_repository_info", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/cloning.py::parse_github_url" - ], - "source_code": " def _parse_repository_info(self, github_url: str) -> Dict[str, str]:\n \"\"\"Parse GitHub URL and extract repository metadata.\"\"\"\n return parse_github_url(github_url)", - "start_line": 237, - "end_line": 239, - "has_docstring": true, - "docstring": "Parse GitHub URL and extract repository metadata.", - "parameters": [ - "self", - "github_url" - ], - "node_type": "method", - "base_classes": null, - "class_name": "AnalysisService", - "display_name": "method AnalysisService._parse_repository_info", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._parse_repository_info", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._analyze_structure": { - "id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._analyze_structure", - "name": "AnalysisService._analyze_structure", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer.analyze_repository_structure", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer" - ], - "source_code": " def _analyze_structure(\n self,\n repo_dir: str,\n include_patterns: Optional[List[str]],\n exclude_patterns: Optional[List[str]],\n use_gitignore: bool = True,\n ) -> Dict[str, Any]:\n \"\"\"Analyze repository file structure with filtering.\"\"\"\n logger.debug(\n \"Initializing RepoAnalyzer with include: %s, exclude: %s, use_gitignore: %s\",\n include_patterns,\n exclude_patterns,\n use_gitignore,\n )\n repo_analyzer = RepoAnalyzer(include_patterns, exclude_patterns, use_gitignore)\n return repo_analyzer.analyze_repository_structure(repo_dir)", - "start_line": 241, - "end_line": 256, - "has_docstring": true, - "docstring": "Analyze repository file structure with filtering.", - "parameters": [ - "self", - "repo_dir", - "include_patterns", - "exclude_patterns", - "use_gitignore" - ], - "node_type": "method", - "base_classes": null, - "class_name": "AnalysisService", - "display_name": "method AnalysisService._analyze_structure", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._analyze_structure", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._read_readme_file": { - "id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._read_readme_file", - "name": "AnalysisService._read_readme_file", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/utils/security.py::assert_safe_path", - "codewiki/src/be/dependency_analyzer/utils/security.py::safe_open_text", - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": " def _read_readme_file(self, repo_dir: str) -> Optional[str]:\n \"\"\"Find and read the README file from the repository root.\"\"\"\n # possible_readme_names = [\"README.md\", \"README\", \"readme.md\", \"README.txt\"]\n # for name in possible_readme_names:\n # readme_path = Path(repo_dir) / name\n # if readme_path.exists():\n # try:\n # logger.debug(f\"Found README file at {readme_path}\")\n # return readme_path.read_text(encoding=\"utf-8\")\n # except Exception as e:\n # logger.warning(f\"Could not read README file at {readme_path}: {e}\")\n # return None\n # logger.debug(\"No README file found in repository root.\")\n # return None\n base = Path(repo_dir)\n possible_readme_names = [\"README.md\", \"README\", \"readme.md\", \"README.txt\"]\n for name in possible_readme_names:\n p = base / name\n if p.exists():\n try:\n assert_safe_path(base, p)\n logger.debug(f\"Found README file at {p}\")\n return safe_open_text(base, p, encoding=\"utf-8\")\n except Exception as e:\n logger.warning(f\"Skipping unsafe/ unreadable README at {p}: {e}\")\n return None\n logger.debug(\"No README file found in repository root.\")\n return None", - "start_line": 258, - "end_line": 285, - "has_docstring": true, - "docstring": "Find and read the README file from the repository root.", - "parameters": [ - "self", - "repo_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "AnalysisService", - "display_name": "method AnalysisService._read_readme_file", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._read_readme_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._analyze_call_graph": { - "id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._analyze_call_graph", - "name": "AnalysisService._analyze_call_graph", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._filter_supported_languages", - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._get_supported_languages", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer.analyze_code_files", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer.extract_code_files", - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": " def _analyze_call_graph(self, file_tree: Dict[str, Any], repo_dir: str) -> Dict[str, Any]:\n \"\"\"\n Perform multi-language call graph analysis.\n\n This method will be expanded to handle:\n - Python AST analysis (current)\n - JavaScript/TypeScript AST analysis (planned)\n - Additional language support (future)\n \"\"\"\n logger.debug(\"Extracting code files from file tree...\")\n code_files = self.call_graph_analyzer.extract_code_files(file_tree)\n\n logger.debug(f\"Found {len(code_files)} total code files. Filtering for supported languages.\")\n supported_files = self._filter_supported_languages(code_files)\n logger.debug(f\"Analyzing {len(supported_files)} supported files.\")\n\n result = self.call_graph_analyzer.analyze_code_files(supported_files, repo_dir)\n\n result[\"call_graph\"][\"supported_languages\"] = self._get_supported_languages()\n result[\"call_graph\"][\"unsupported_files\"] = len(code_files) - len(supported_files)\n\n return result", - "start_line": 287, - "end_line": 308, - "has_docstring": true, - "docstring": "Perform multi-language call graph analysis.\n\nThis method will be expanded to handle:\n- Python AST analysis (current)\n- JavaScript/TypeScript AST analysis (planned)\n- Additional language support (future)", - "parameters": [ - "self", - "file_tree", - "repo_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "AnalysisService", - "display_name": "method AnalysisService._analyze_call_graph", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._analyze_call_graph", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._filter_supported_languages": { - "id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._filter_supported_languages", - "name": "AnalysisService._filter_supported_languages", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def _filter_supported_languages(self, code_files: List[Dict]) -> List[Dict]:\n \"\"\"\n Filter code files to only include supported languages.\n\n Supports Python, JavaScript, TypeScript, Java, C#, C, C++, PHP, Go, and Rust.\n \"\"\"\n supported_languages = {\n \"python\",\n \"javascript\",\n \"typescript\",\n \"java\",\n \"csharp\",\n \"c\",\n \"cpp\",\n \"php\",\n \"go\",\n \"rust\",\n \"kotlin\",\n }\n\n return [\n file_info\n for file_info in code_files\n if file_info.get(\"language\") in supported_languages\n ]", - "start_line": 310, - "end_line": 334, - "has_docstring": true, - "docstring": "Filter code files to only include supported languages.\n\nSupports Python, JavaScript, TypeScript, Java, C#, C, C++, PHP, Go, and Rust.", - "parameters": [ - "self", - "code_files" - ], - "node_type": "method", - "base_classes": null, - "class_name": "AnalysisService", - "display_name": "method AnalysisService._filter_supported_languages", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._filter_supported_languages", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._get_supported_languages": { - "id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._get_supported_languages", - "name": "AnalysisService._get_supported_languages", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "depends_on": [], - "source_code": " def _get_supported_languages(self) -> List[str]:\n \"\"\"Get list of currently supported languages for analysis.\"\"\"\n return [\"python\", \"javascript\", \"typescript\", \"java\", \"csharp\", \"c\", \"cpp\", \"php\", \"kotlin\"]", - "start_line": 336, - "end_line": 338, - "has_docstring": true, - "docstring": "Get list of currently supported languages for analysis.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "AnalysisService", - "display_name": "method AnalysisService._get_supported_languages", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._get_supported_languages", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._cleanup_repository": { - "id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._cleanup_repository", - "name": "AnalysisService._cleanup_repository", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/cloning.py::cleanup_repository", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/mcp/session.py::SessionStore.remove" - ], - "source_code": " def _cleanup_repository(self, temp_dir: str):\n \"\"\"Clean up cloned repository.\"\"\"\n logger.debug(f\"Attempting to clean up {temp_dir}\")\n cleanup_repository(temp_dir)\n if temp_dir in self._temp_directories:\n self._temp_directories.remove(temp_dir)", - "start_line": 340, - "end_line": 345, - "has_docstring": true, - "docstring": "Clean up cloned repository.", - "parameters": [ - "self", - "temp_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "AnalysisService", - "display_name": "method AnalysisService._cleanup_repository", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._cleanup_repository", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.cleanup_all": { - "id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.cleanup_all", - "name": "AnalysisService.cleanup_all", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._cleanup_repository" - ], - "source_code": " def cleanup_all(self):\n \"\"\"Clean up all tracked temporary directories.\"\"\"\n for temp_dir in self._temp_directories[:]:\n self._cleanup_repository(temp_dir)", - "start_line": 347, - "end_line": 350, - "has_docstring": true, - "docstring": "Clean up all tracked temporary directories.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "AnalysisService", - "display_name": "method AnalysisService.cleanup_all", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.cleanup_all", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.__del__": { - "id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.__del__", - "name": "AnalysisService.__del__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.cleanup_all" - ], - "source_code": " def __del__(self):\n \"\"\"Ensure cleanup on service destruction.\"\"\"\n self.cleanup_all()", - "start_line": 352, - "end_line": 354, - "has_docstring": true, - "docstring": "Ensure cleanup on service destruction.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "AnalysisService", - "display_name": "method AnalysisService.__del__", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.__del__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::analyze_repository": { - "id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::analyze_repository", - "name": "analyze_repository", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.analyze_repository_full", - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService" - ], - "source_code": "def analyze_repository(\n github_url: str, include_patterns=None, exclude_patterns=None, use_gitignore=True\n) -> tuple[AnalysisResult, None]:\n \"\"\"\n Backward compatibility function.\n\n Returns:\n tuple: (AnalysisResult, None) - None instead of temp_dir since cleanup is handled internally\n \"\"\"\n service = AnalysisService()\n result = service.analyze_repository_full(\n github_url, include_patterns, exclude_patterns, use_gitignore\n )\n return result, None", - "start_line": 357, - "end_line": 370, - "has_docstring": true, - "docstring": "Backward compatibility function.\n\nReturns:\n tuple: (AnalysisResult, None) - None instead of temp_dir since cleanup is handled internally", - "parameters": [ - "github_url", - "include_patterns", - "exclude_patterns", - "use_gitignore" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function analyze_repository", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::analyze_repository", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::analyze_repository_structure_only": { - "id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::analyze_repository_structure_only", - "name": "analyze_repository_structure_only", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService.analyze_repository_structure_only", - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService" - ], - "source_code": "def analyze_repository_structure_only(\n github_url: str, include_patterns=None, exclude_patterns=None, use_gitignore=True\n) -> tuple[Dict, None]:\n \"\"\"\n Backward compatibility function.\n\n Returns:\n tuple: (structure_result, None) - None instead of temp_dir since cleanup is handled internally\n \"\"\"\n service = AnalysisService()\n result = service.analyze_repository_structure_only(\n github_url, include_patterns, exclude_patterns, use_gitignore\n )\n return result, None", - "start_line": 373, - "end_line": 386, - "has_docstring": true, - "docstring": "Backward compatibility function.\n\nReturns:\n tuple: (structure_result, None) - None instead of temp_dir since cleanup is handled internally", - "parameters": [ - "github_url", - "include_patterns", - "exclude_patterns", - "use_gitignore" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function analyze_repository_structure_only", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::analyze_repository_structure_only", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::TimeoutError": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::TimeoutError", - "name": "TimeoutError", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [], - "source_code": "class TimeoutError(Exception):\n \"\"\"Raised when file parsing exceeds timeout.\"\"\"\n pass", - "start_line": 30, - "end_line": 32, - "has_docstring": true, - "docstring": "Raised when file parsing exceeds timeout.", - "parameters": null, - "node_type": "class", - "base_classes": [ - "Exception" - ], - "class_name": null, - "display_name": "class TimeoutError", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::TimeoutError", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::timeout": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::timeout", - "name": "timeout", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::TimeoutError" - ], - "source_code": "def timeout(seconds):\n \"\"\"Context manager for timeout on file parsing.\"\"\"\n def signal_handler(signum, frame):\n raise TimeoutError(f\"File parsing exceeded {seconds}s timeout\")\n \n # Only use signal on Unix systems (not Windows)\n try:\n old_handler = signal.signal(signal.SIGALRM, signal_handler)\n signal.alarm(seconds)\n yield\n except AttributeError:\n # Windows doesn't support SIGALRM, skip timeout\n yield\n finally:\n try:\n signal.alarm(0)\n signal.signal(signal.SIGALRM, old_handler)\n except (AttributeError, ValueError):\n pass", - "start_line": 36, - "end_line": 54, - "has_docstring": true, - "docstring": "Context manager for timeout on file parsing.", - "parameters": [ - "seconds" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function timeout", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::timeout", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer", - "name": "CallGraphAnalyzer", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [], - "source_code": "class CallGraphAnalyzer:\n def __init__(self):\n \"\"\"Initialize the call graph analyzer.\"\"\"\n self.functions: Dict[str, Node] = {}\n self.call_relationships: List[CallRelationship] = []\n self._python_project_modules: set = set()\n self._python_external_import_roots: set = set()\n logger.debug(\"CallGraphAnalyzer initialized.\")\n\n def analyze_code_files(self, code_files: List[Dict], base_dir: str) -> Dict:\n \"\"\"\n Complete analysis: Analyze all files to build complete call graph with all nodes.\n\n This approach:\n 1. Analyzes all code files \n 2. Extracts all functions and relationships\n 3. Builds complete call graph\n 4. Returns all nodes and relationships \n \"\"\"\n logger.debug(f\"Starting analysis of {len(code_files)} files\")\n logger.info(f\"πŸ“Š Parsing {len(code_files)} source files (this may take a few minutes)...\")\n\n self.functions = {}\n self.call_relationships = []\n code_files = self._route_contextual_headers(code_files, base_dir)\n self._python_project_modules = self._collect_python_modules(code_files)\n self._python_external_import_roots = set()\n\n files_analyzed = 0\n files_failed = 0\n start_time = time.time()\n \n for idx, file_info in enumerate(code_files, 1):\n file_path = file_info['path']\n try:\n # Log progress every file with elapsed time\n if idx % max(1, len(code_files) // 10) == 0 or idx <= 5:\n elapsed = time.time() - start_time\n rate = idx / elapsed if elapsed > 0 else 0\n remaining = (len(code_files) - idx) / rate if rate > 0 else 0\n logger.info(f\" [{idx}/{len(code_files)}] {file_path} ({elapsed:.1f}s elapsed, ~{remaining:.1f}s remaining)\")\n \n self._analyze_code_file(base_dir, file_info)\n files_analyzed += 1\n except Exception as e:\n files_failed += 1\n logger.warning(f\" ⚠️ [{idx}/{len(code_files)}] Failed to analyze {file_path}: {str(e)[:100]}\")\n \n elapsed_time = time.time() - start_time\n logger.info(\n f\"βœ“ Analysis complete: {files_analyzed}/{len(code_files)} files analyzed, \"\n f\"{files_failed} failed, {len(self.functions)} functions, {len(self.call_relationships)} relationships ({elapsed_time:.1f}s)\"\n )\n\n logger.debug(\"Resolving call relationships\")\n self._resolve_call_relationships()\n self._deduplicate_relationships()\n viz_data = self._generate_visualization_data()\n\n return {\n \"call_graph\": {\n \"total_functions\": len(self.functions),\n \"total_calls\": len(self.call_relationships),\n \"languages_found\": list(set(f.get(\"language\") for f in code_files)),\n \"files_analyzed\": files_analyzed,\n \"analysis_approach\": \"complete_unlimited\",\n },\n \"functions\": [func.model_dump() for func in self.functions.values()],\n \"relationships\": [rel.model_dump() for rel in self.call_relationships],\n \"visualization\": viz_data,\n }\n\n def extract_code_files(self, file_tree: Dict) -> List[Dict]:\n \"\"\"\n Extract code files from file tree structure.\n\n Filters files based on supported extensions and excludes test/config files.\n\n Args:\n file_tree: Nested dictionary representing file structure\n\n Returns:\n List of code file information dictionaries\n \"\"\"\n code_files = []\n\n def traverse(tree):\n if tree[\"type\"] == \"file\":\n ext = tree.get(\"extension\", \"\").lower()\n if ext in CODE_EXTENSIONS:\n name = tree[\"name\"].lower()\n if not any(skip in name for skip in []):\n code_files.append(\n {\n \"path\": tree[\"path\"],\n \"name\": tree[\"name\"],\n \"extension\": ext,\n \"language\": CODE_EXTENSIONS[ext],\n }\n )\n elif tree[\"type\"] == \"directory\" and tree.get(\"children\"):\n for child in tree[\"children\"]:\n traverse(child)\n\n traverse(file_tree)\n return code_files\n\n def _route_contextual_headers(self, code_files: List[Dict], base_dir: str) -> List[Dict]:\n \"\"\"Route ambiguous .h headers per file.\n\n A header is parsed as C++ when its own content shows C++ signals, or\n when the repository is C++-only (so even a signal-free header cannot be\n C). In a mixed C/C++ repository, a plain C header stays routed as C.\n \"\"\"\n cpp_extensions = {\".cpp\", \".cc\", \".cxx\", \".c++\", \".hpp\", \".hxx\", \".h++\"}\n has_cpp_files = any(\n file_info.get(\"extension\", \"\").lower() in cpp_extensions\n or file_info.get(\"language\") == \"cpp\"\n for file_info in code_files\n )\n has_c_files = any(\n file_info.get(\"extension\", \"\").lower() == \".c\" for file_info in code_files\n )\n\n routed_files = []\n for file_info in code_files:\n routed = dict(file_info)\n if routed.get(\"extension\", \"\").lower() == \".h\":\n if self._header_has_cpp_signal(base_dir, routed[\"path\"]):\n routed[\"language\"] = \"cpp\"\n elif has_cpp_files and not has_c_files:\n routed[\"language\"] = \"cpp\"\n routed_files.append(routed)\n return routed_files\n\n def _header_has_cpp_signal(self, base_dir: str, relative_path: str) -> bool:\n base = Path(base_dir)\n try:\n content = safe_open_text(base, base / relative_path)\n except Exception:\n return False\n\n if re.search(\n r\"\\b(?:namespace\\s+[A-Za-z_{:]|class\\s+[A-Za-z_]|template\\s*<\"\n r\"|typename\\b|(?:public|private|protected)\\s*:)\",\n content,\n ):\n return True\n if \"::\" in content:\n return True\n for header in CPP_STANDARD_HEADERS:\n if f\"#include <{header}>\" in content:\n return True\n return False\n\n def _analyze_code_file(self, repo_dir: str, file_info: Dict):\n \"\"\"\n Analyze a single code file based on its language.\n\n Routes to appropriate language-specific analyzer.\n\n Args:\n repo_dir: Repository directory path\n file_info: File information dictionary\n \"\"\"\n\n base = Path(repo_dir)\n file_path = base / file_info[\"path\"]\n\n try:\n # Add timeout protection (30 seconds per file max)\n with timeout(30):\n content = safe_open_text(base, file_path)\n language = file_info[\"language\"]\n if language == \"python\":\n self._analyze_python_file(file_path, content, repo_dir)\n elif language == \"javascript\":\n self._analyze_javascript_file(file_path, content, repo_dir)\n elif language == \"typescript\":\n self._analyze_typescript_file(file_path, content, repo_dir)\n elif language == \"java\":\n self._analyze_java_file(file_path, content, repo_dir)\n elif language == \"kotlin\":\n self._analyze_kotlin_file(file_path, content, repo_dir)\n elif language == \"csharp\":\n self._analyze_csharp_file(file_path, content, repo_dir)\n elif language == \"c\":\n self._analyze_c_file(file_path, content, repo_dir)\n elif language == \"cpp\":\n self._analyze_cpp_file(file_path, content, repo_dir)\n elif language == \"php\":\n self._analyze_php_file(file_path, content, repo_dir)\n # else:\n # logger.warning(\n # f\"Unsupported language for call graph analysis: {language} for file {file_path}\"\n # )\n\n except TimeoutError as e:\n logger.warning(f\"⏱️ Timeout analyzing {file_path}: {str(e)}\")\n except Exception as e:\n logger.debug(f\"Error analyzing {file_path}: {str(e)}\")\n logger.debug(f\"Traceback: {traceback.format_exc()}\")\n\n def _analyze_python_file(self, file_path: str, content: str, base_dir: str):\n \"\"\"\n Analyze Python file using Python AST analyzer.\n\n Args:\n file_path: Relative path to the Python file\n content: File content string\n base_dir: Repository base directory path\n \"\"\"\n from codewiki.src.be.dependency_analyzer.analyzers.python import analyze_python_file\n\n try:\n functions, relationships, external_import_roots = analyze_python_file(\n file_path,\n content,\n repo_path=base_dir,\n project_modules=self._python_project_modules,\n )\n\n for func in functions:\n func_id = func.id if func.id else f\"{file_path}:{func.name}\"\n self.functions[func_id] = func\n\n self.call_relationships.extend(relationships)\n self._python_external_import_roots.update(external_import_roots)\n except Exception as e:\n logger.error(f\"Failed to analyze Python file {file_path}: {e}\", exc_info=True)\n\n @staticmethod\n def _collect_python_modules(code_files: List[Dict]) -> set:\n \"\"\"Dotted module paths for every Python file in the repository.\"\"\"\n modules = set()\n for file_info in code_files:\n if file_info.get(\"language\") != \"python\":\n continue\n path = file_info[\"path\"]\n for ext in (\".py\", \".pyx\"):\n if path.endswith(ext):\n path = path[: -len(ext)]\n break\n module = path.replace(\"/\", \".\").replace(\"\\\\\", \".\")\n if module.endswith(\".__init__\"):\n module = module[: -len(\".__init__\")]\n if module:\n modules.add(module)\n return modules\n\n def _analyze_javascript_file(self, file_path: str, content: str, repo_dir: str):\n \"\"\"\n Analyze JavaScript file using tree-sitter based AST analyzer\n\n Args:\n file_path: Relative path to the JavaScript file\n content: File content string\n repo_dir: Repository base directory\n \"\"\"\n try:\n\n from codewiki.src.be.dependency_analyzer.analyzers.javascript import analyze_javascript_file_treesitter\n\n functions, relationships = analyze_javascript_file_treesitter(\n file_path, content, repo_path=repo_dir\n )\n\n for func in functions:\n func_id = func.id if func.id else f\"{file_path}:{func.name}\"\n self.functions[func_id] = func\n\n self.call_relationships.extend(relationships)\n\n except Exception as e:\n logger.error(f\"Failed to analyze JavaScript file {file_path}: {e}\", exc_info=True)\n\n def _analyze_typescript_file(self, file_path: str, content: str, repo_dir: str):\n \"\"\"\n Analyze TypeScript file using tree-sitter based AST analyzer \n\n Args:\n file_path: Relative path to the TypeScript file\n content: File content string\n \"\"\"\n try:\n\n from codewiki.src.be.dependency_analyzer.analyzers.typescript import analyze_typescript_file_treesitter\n\n functions, relationships = analyze_typescript_file_treesitter(\n file_path, content, repo_path=repo_dir\n )\n\n for func in functions:\n func_id = func.id if func.id else f\"{file_path}:{func.name}\"\n self.functions[func_id] = func\n\n self.call_relationships.extend(relationships)\n\n except Exception as e:\n logger.error(f\"Failed to analyze TypeScript file {file_path}: {e}\", exc_info=True)\n\n\n\n def _analyze_c_file(self, file_path: str, content: str, repo_dir: str):\n \"\"\"\n Analyze C file using tree-sitter based analyzer.\n\n Args:\n file_path: Relative path to the C file\n content: File content string\n repo_dir: Repository base directory\n \"\"\"\n from codewiki.src.be.dependency_analyzer.analyzers.c import analyze_c_file\n\n functions, relationships = analyze_c_file(file_path, content, repo_path=repo_dir)\n\n for func in functions:\n func_id = func.id if func.id else f\"{file_path}:{func.name}\"\n self.functions[func_id] = func\n\n self.call_relationships.extend(relationships)\n\n def _analyze_cpp_file(self, file_path: str, content: str, repo_dir: str):\n \"\"\"\n Analyze C++ file using tree-sitter based analyzer.\n\n Args:\n file_path: Relative path to the C++ file\n content: File content string\n \"\"\"\n from codewiki.src.be.dependency_analyzer.analyzers.cpp import analyze_cpp_file\n\n functions, relationships = analyze_cpp_file(\n file_path, content, repo_path=repo_dir\n )\n\n for func in functions:\n func_id = func.id if func.id else f\"{file_path}:{func.name}\"\n self.functions[func_id] = func\n\n self.call_relationships.extend(relationships)\n\n def _analyze_java_file(self, file_path: str, content: str, repo_dir: str):\n \"\"\"\n Analyze Java file using tree-sitter based analyzer.\n\n Args:\n file_path: Relative path to the Java file\n content: File content string\n repo_dir: Repository base directory\n \"\"\"\n from codewiki.src.be.dependency_analyzer.analyzers.java import analyze_java_file\n\n try:\n functions, relationships = analyze_java_file(file_path, content, repo_path=repo_dir)\n for func in functions:\n func_id = func.id if func.id else f\"{file_path}:{func.name}\"\n self.functions[func_id] = func\n\n self.call_relationships.extend(relationships)\n except Exception as e:\n logger.error(f\"Failed to analyze Java file {file_path}: {e}\", exc_info=True)\n\n def _analyze_kotlin_file(self, file_path: str, content: str, repo_dir: str):\n \"\"\"\n Analyze Kotlin file using tree-sitter based analyzer.\n\n Args:\n file_path: Relative path to the Kotlin file\n content: File content string\n repo_dir: Repository base directory\n \"\"\"\n from codewiki.src.be.dependency_analyzer.analyzers.kotlin import analyze_kotlin_file\n\n try:\n functions, relationships = analyze_kotlin_file(file_path, content, repo_path=repo_dir)\n for func in functions:\n func_id = func.id if func.id else f\"{file_path}:{func.name}\"\n self.functions[func_id] = func\n\n self.call_relationships.extend(relationships)\n except Exception as e:\n logger.error(f\"Failed to analyze Kotlin file {file_path}: {e}\", exc_info=True)\n\n def _analyze_csharp_file(self, file_path: str, content: str, repo_dir: str):\n \"\"\"\n Analyze C# file using tree-sitter based analyzer.\n\n Args:\n file_path: Relative path to the C# file\n content: File content string\n repo_dir: Repository base directory\n \"\"\"\n from codewiki.src.be.dependency_analyzer.analyzers.csharp import analyze_csharp_file\n\n try:\n functions, relationships = analyze_csharp_file(file_path, content, repo_path=repo_dir)\n\n for func in functions:\n func_id = func.id if func.id else f\"{file_path}:{func.name}\"\n self.functions[func_id] = func\n\n self.call_relationships.extend(relationships)\n except Exception as e:\n logger.error(f\"Failed to analyze C# file {file_path}: {e}\", exc_info=True)\n\n def _analyze_php_file(self, file_path: str, content: str, repo_dir: str):\n \"\"\"\n Analyze PHP file using tree-sitter based analyzer.\n\n Args:\n file_path: Relative path to the PHP file\n content: File content string\n repo_dir: Repository base directory\n \"\"\"\n from codewiki.src.be.dependency_analyzer.analyzers.php import analyze_php_file\n\n try:\n functions, relationships = analyze_php_file(file_path, content, repo_path=repo_dir)\n\n for func in functions:\n func_id = func.id if func.id else f\"{file_path}:{func.name}\"\n self.functions[func_id] = func\n\n self.call_relationships.extend(relationships)\n except Exception as e:\n logger.error(f\"Failed to analyze PHP file {file_path}: {e}\", exc_info=True)\n\n def _resolve_call_relationships(self):\n \"\"\"\n Resolve function call relationships across all languages.\n\n Attempts to match function calls to actual function definitions,\n handling cross-language calls where possible.\n \"\"\"\n for func_id, func_info in self.functions.items():\n if not func_info.language:\n file_ext = Path(func_info.file_path).suffix.lower()\n func_info.language = CODE_EXTENSIONS.get(file_ext)\n\n indexes = self._build_resolution_indexes()\n\n resolved_count = 0\n for relationship in self.call_relationships:\n if relationship.is_resolved and relationship.callee in self.functions:\n continue\n\n resolved_id = self._resolve_callee(relationship, indexes)\n if resolved_id:\n relationship.callee = resolved_id\n relationship.is_resolved = True\n resolved_count += 1\n\n dotted_packages = self._dotted_project_packages()\n self.call_relationships = [\n relationship\n for relationship in self.call_relationships\n if relationship.is_resolved\n or not self._is_external_callee(\n self._caller_language(relationship.caller),\n relationship.callee,\n dotted_packages,\n )\n ]\n\n def _dotted_project_packages(self) -> Dict[str, set]:\n \"\"\"Project packages/namespaces, partitioned by language. Java and C#\n share the namespace-origin rule: a dotted callee qualified to a package\n with no prefix relation to any project package came from a third-party\n import.\"\"\"\n packages: Dict[str, set] = defaultdict(set)\n for func_info in self.functions.values():\n if func_info.language in (\"java\", \"csharp\"):\n package = self._dotted_package_for_node(func_info)\n if package:\n packages[func_info.language].add(package)\n return packages\n\n def _is_external_callee(self, language: Optional[str], callee: str, dotted_packages: Dict[str, set]) -> bool:\n \"\"\"Classify a still-unresolved callee as external, after project\n resolution has had its chance.\n\n Rules are generic, not name lists: prefix/standard-library knowledge in\n is_external_symbol, the C/C++ ALL_CAPS macro convention (macros are\n never components, so such calls can never resolve), and Java package\n origin β€” a dotted name qualified to a package with no prefix relation\n to any project package came from a third-party import.\n \"\"\"\n if is_external_symbol(language, callee):\n return True\n if language in (\"c\", \"cpp\") and is_macro_name(callee):\n return True\n if language in (\"java\", \"csharp\") and \".\" in callee and dotted_packages.get(language):\n package = callee.rsplit(\".\", 1)[0]\n if not any(\n package == project\n or package.startswith(project + \".\")\n or project.startswith(package + \".\")\n for project in dotted_packages[language]\n ):\n return True\n if language == \"python\" and \".\" in callee:\n return self._is_external_python_callee(callee)\n return False\n\n def _is_external_python_callee(self, callee: str) -> bool:\n \"\"\"Classify a still-unresolved dotted Python callee.\n\n A callee whose dotted prefix aligns with a project module is an\n honest project gap, never external. Otherwise the import-origin rule\n (head was imported from outside the project) and the core-object\n method rule (a tail like ``append``/``endswith`` on an unknowable\n receiver can never be a project component) apply.\n \"\"\"\n from codewiki.src.be.dependency_analyzer.analyzers.python import is_project_import\n from codewiki.src.be.dependency_analyzer.utils.external_symbols import (\n PYTHON_OBJECT_METHODS,\n )\n\n parts = callee.split(\".\")\n if self._python_project_modules:\n for end in range(len(parts) - 1, 0, -1):\n if is_project_import(\".\".join(parts[:end]), self._python_project_modules):\n return False\n if parts[0] in self._python_external_import_roots:\n return True\n return parts[-1] in PYTHON_OBJECT_METHODS\n\n def _build_resolution_indexes(self) -> Dict[str, Dict]:\n \"\"\"Build exact/simple-name lookup indexes, both globally and per\n language. Resolution prefers the caller's own language partition: a\n name that is unique within the caller's language resolves even when\n another language defines the same name, and names made ambiguous only\n by foreign-language components keep resolving as before.\"\"\"\n def make() -> Dict[str, Dict[str, List[str]]]:\n return {\"exact\": defaultdict(list), \"simple\": defaultdict(list)}\n\n global_indexes = make()\n by_lang: Dict[str, Dict[str, Dict[str, List[str]]]] = defaultdict(make)\n\n def add(index: Dict[str, List[str]], key: Optional[str], func_id: str) -> None:\n if key and func_id not in index[key]:\n index[key].append(func_id)\n\n for func_id, func_info in self.functions.items():\n targets = [global_indexes]\n if func_info.language:\n targets.append(by_lang[func_info.language])\n\n exact_keys = [\n func_id,\n func_info.component_id,\n func_info.qualified_name,\n func_info.name,\n ]\n\n names = {func_info.name}\n if func_info.component_id:\n names.add(func_info.component_id.split(\"::\")[-1])\n if func_info.qualified_name:\n names.add(func_info.qualified_name.split(\".\")[-1])\n parts = func_info.qualified_name.split(\".\")\n if len(parts) >= 2:\n names.add(\".\".join(parts[-2:]))\n\n for target in targets:\n for key in exact_keys:\n add(target[\"exact\"], key, func_id)\n for name in names:\n add(target[\"simple\"], name, func_id)\n if name and \".\" in name:\n add(target[\"simple\"], name.split(\".\")[-1], func_id)\n\n return {\n \"exact\": global_indexes[\"exact\"],\n \"simple\": global_indexes[\"simple\"],\n \"by_lang\": dict(by_lang),\n }\n\n def _resolve_callee(self, relationship: CallRelationship, indexes: Dict[str, Dict]) -> Optional[str]:\n caller = self.functions.get(relationship.caller)\n caller_language = caller.language if caller else None\n\n lang_indexes = indexes[\"by_lang\"].get(caller_language) if caller_language else None\n if lang_indexes:\n match = self._resolve_callee_in(relationship, lang_indexes[\"exact\"], lang_indexes[\"simple\"])\n if match:\n return match\n\n return self._resolve_callee_in(relationship, indexes[\"exact\"], indexes[\"simple\"])\n\n def _resolve_callee_in(\n self,\n relationship: CallRelationship,\n exact: Dict[str, List[str]],\n simple: Dict[str, List[str]],\n ) -> Optional[str]:\n callee_name = relationship.callee\n\n exact_match = self._unique_match(exact, callee_name)\n if exact_match:\n return exact_match\n\n if \"::\" in callee_name:\n suffix = callee_name.split(\"::\")[-1]\n exact_match = self._unique_match(exact, suffix)\n if exact_match:\n return exact_match\n simple_match = self._unique_match(simple, suffix)\n if simple_match:\n return simple_match\n\n if \".\" in callee_name:\n simple_match = self._unique_match(simple, callee_name)\n if simple_match:\n return simple_match\n tail_match = self._unique_match(simple, callee_name.split(\".\")[-1])\n if tail_match:\n return tail_match\n\n caller = self.functions.get(relationship.caller)\n if caller and caller.language in (\"java\", \"csharp\") and \".\" not in callee_name:\n package = self._dotted_package_for_node(caller)\n if package:\n same_package_match = self._unique_match(exact, f\"{package}.{callee_name}\")\n if same_package_match:\n return same_package_match\n\n return self._unique_match(simple, callee_name)\n\n def _unique_match(self, index: Dict[str, List[str]], key: str) -> Optional[str]:\n matches = index.get(key, [])\n return matches[0] if len(matches) == 1 else None\n\n def _dotted_package_for_node(self, node: Node) -> str:\n \"\"\"The package (Java) / namespace (C#) a node lives in, derived from its\n dotted qualified name. Both languages share the same shape: a type's\n package is its qualified name minus the type, a method's is minus\n ``Type.method``.\"\"\"\n qualified_name = node.qualified_name or \"\"\n parts = qualified_name.split(\".\")\n if len(parts) < 2:\n return \"\"\n if node.component_type == \"method\" and len(parts) >= 3:\n return \".\".join(parts[:-2])\n return \".\".join(parts[:-1])\n\n def _caller_language(self, caller_id: str) -> Optional[str]:\n caller = self.functions.get(caller_id)\n if caller and caller.language:\n return caller.language\n if caller:\n return CODE_EXTENSIONS.get(Path(caller.file_path).suffix.lower())\n return None\n\n def _deduplicate_relationships(self):\n \"\"\"\n Deduplicate call relationships based on caller-callee pairs.\n\n Removes duplicate relationships while preserving the first occurrence.\n This helps eliminate noise from multiple calls to the same function.\n \"\"\"\n seen = set()\n unique_relationships = []\n\n for rel in self.call_relationships:\n key = (rel.caller, rel.callee)\n if key not in seen:\n seen.add(key)\n unique_relationships.append(rel)\n\n self.call_relationships = unique_relationships\n\n def _generate_visualization_data(self) -> Dict:\n \"\"\"\n Generate visualization data for graph rendering.\n\n Creates Cytoscape.js compatible graph data with nodes and edges.\n\n Returns:\n Dict: Visualization data with cytoscape elements and summary\n \"\"\"\n cytoscape_elements = []\n\n for func_id, func_info in self.functions.items():\n node_classes = []\n if func_info.node_type == \"method\":\n node_classes.append(\"node-method\")\n else:\n node_classes.append(\"node-function\")\n\n file_ext = Path(func_info.file_path).suffix.lower()\n language = func_info.language or CODE_EXTENSIONS.get(file_ext, \"unknown\")\n if file_ext == \".py\":\n node_classes.append(\"lang-python\")\n elif file_ext == \".js\":\n node_classes.append(\"lang-javascript\")\n elif file_ext == \".ts\":\n node_classes.append(\"lang-typescript\")\n elif language == \"c\":\n node_classes.append(\"lang-c\")\n elif language == \"cpp\" or file_ext in [\".cpp\", \".cc\", \".cxx\", \".c++\", \".hpp\", \".hxx\", \".h++\"]:\n node_classes.append(\"lang-cpp\")\n elif file_ext in [\".kt\", \".kts\"]:\n node_classes.append(\"lang-kotlin\")\n elif file_ext in [\".php\", \".phtml\", \".inc\"]:\n node_classes.append(\"lang-php\")\n\n cytoscape_elements.append(\n {\n \"data\": {\n \"id\": func_id,\n \"label\": func_info.name,\n \"file\": func_info.file_path,\n \"type\": func_info.node_type or \"function\",\n \"language\": language,\n },\n \"classes\": \" \".join(node_classes),\n }\n )\n\n resolved_rels = [r for r in self.call_relationships if r.is_resolved]\n for rel in resolved_rels:\n cytoscape_elements.append(\n {\n \"data\": {\n \"id\": f\"{rel.caller}->{rel.callee}\",\n \"source\": rel.caller,\n \"target\": rel.callee,\n \"line\": rel.call_line,\n },\n \"classes\": \"edge-call\",\n }\n )\n\n summary = {\n \"total_nodes\": len(self.functions),\n \"total_edges\": len(resolved_rels),\n \"unresolved_calls\": len(self.call_relationships) - len(resolved_rels),\n }\n\n return {\n \"cytoscape\": {\"elements\": cytoscape_elements},\n \"summary\": summary,\n }\n\n def generate_llm_format(self) -> Dict:\n \"\"\"Generate clean format optimized for LLM consumption.\"\"\"\n return {\n \"functions\": [\n {\n \"name\": func.name,\n \"file\": Path(func.file_path).name,\n \"purpose\": (func.docstring.split(\"\\n\")[0] if func.docstring else None),\n \"parameters\": func.parameters,\n \"is_recursive\": func.name\n in [\n rel.callee\n for rel in self.call_relationships\n if rel.caller.endswith(func.name)\n ],\n }\n for func in self.functions.values()\n ],\n \"relationships\": {\n func.name: {\n \"calls\": [\n rel.callee.split(\":\")[-1]\n for rel in self.call_relationships\n if rel.caller.endswith(func.name) and rel.is_resolved\n ],\n \"called_by\": [\n rel.caller.split(\":\")[-1]\n for rel in self.call_relationships\n if rel.callee.endswith(func.name) and rel.is_resolved\n ],\n }\n for func in self.functions.values()\n },\n }\n\n def _select_most_connected_nodes(self, target_count: int):\n \"\"\"\n Select the most connected nodes from the call graph.\n\n Args:\n target_count: The number of nodes to select\n \"\"\"\n if len(self.functions) <= target_count:\n return\n\n if not self.call_relationships:\n logger.warning(\"No call relationships found - keeping all functions by name\")\n func_ids = list(self.functions.keys())[:target_count]\n self.functions = {fid: func for fid, func in self.functions.items() if fid in func_ids}\n return\n\n graph = {}\n for rel in self.call_relationships:\n if rel.caller in self.functions:\n if rel.caller not in graph:\n graph[rel.caller] = set()\n if rel.callee in self.functions:\n if rel.callee not in graph:\n graph[rel.callee] = set()\n\n if rel.caller in graph and rel.callee in graph:\n graph[rel.caller].add(rel.callee)\n graph[rel.callee].add(rel.caller)\n\n degree_centrality = {}\n for func_id in self.functions.keys():\n degree_centrality[func_id] = len(graph.get(func_id, set()))\n\n sorted_func_ids = sorted(degree_centrality, key=degree_centrality.get, reverse=True)\n\n selected_func_ids = sorted_func_ids[:target_count]\n\n original_func_count = len(self.functions)\n self.functions = {\n fid: func for fid, func in self.functions.items() if fid in selected_func_ids\n }\n\n original_rel_count = len(self.call_relationships)\n self.call_relationships = [\n rel\n for rel in self.call_relationships\n if rel.caller in selected_func_ids and rel.callee in selected_func_ids\n ]", - "start_line": 57, - "end_line": 885, - "has_docstring": false, - "docstring": "", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class CallGraphAnalyzer", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer.__init__": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer.__init__", - "name": "CallGraphAnalyzer.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": " def __init__(self):\n \"\"\"Initialize the call graph analyzer.\"\"\"\n self.functions: Dict[str, Node] = {}\n self.call_relationships: List[CallRelationship] = []\n self._python_project_modules: set = set()\n self._python_external_import_roots: set = set()\n logger.debug(\"CallGraphAnalyzer initialized.\")", - "start_line": 58, - "end_line": 64, - "has_docstring": true, - "docstring": "Initialize the call graph analyzer.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer.__init__", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer.analyze_code_files": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer.analyze_code_files", - "name": "CallGraphAnalyzer.analyze_code_files", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._route_contextual_headers", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_code_file", - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._collect_python_modules", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._generate_visualization_data", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._resolve_call_relationships", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._deduplicate_relationships" - ], - "source_code": " def analyze_code_files(self, code_files: List[Dict], base_dir: str) -> Dict:\n \"\"\"\n Complete analysis: Analyze all files to build complete call graph with all nodes.\n\n This approach:\n 1. Analyzes all code files \n 2. Extracts all functions and relationships\n 3. Builds complete call graph\n 4. Returns all nodes and relationships \n \"\"\"\n logger.debug(f\"Starting analysis of {len(code_files)} files\")\n logger.info(f\"πŸ“Š Parsing {len(code_files)} source files (this may take a few minutes)...\")\n\n self.functions = {}\n self.call_relationships = []\n code_files = self._route_contextual_headers(code_files, base_dir)\n self._python_project_modules = self._collect_python_modules(code_files)\n self._python_external_import_roots = set()\n\n files_analyzed = 0\n files_failed = 0\n start_time = time.time()\n \n for idx, file_info in enumerate(code_files, 1):\n file_path = file_info['path']\n try:\n # Log progress every file with elapsed time\n if idx % max(1, len(code_files) // 10) == 0 or idx <= 5:\n elapsed = time.time() - start_time\n rate = idx / elapsed if elapsed > 0 else 0\n remaining = (len(code_files) - idx) / rate if rate > 0 else 0\n logger.info(f\" [{idx}/{len(code_files)}] {file_path} ({elapsed:.1f}s elapsed, ~{remaining:.1f}s remaining)\")\n \n self._analyze_code_file(base_dir, file_info)\n files_analyzed += 1\n except Exception as e:\n files_failed += 1\n logger.warning(f\" ⚠️ [{idx}/{len(code_files)}] Failed to analyze {file_path}: {str(e)[:100]}\")\n \n elapsed_time = time.time() - start_time\n logger.info(\n f\"βœ“ Analysis complete: {files_analyzed}/{len(code_files)} files analyzed, \"\n f\"{files_failed} failed, {len(self.functions)} functions, {len(self.call_relationships)} relationships ({elapsed_time:.1f}s)\"\n )\n\n logger.debug(\"Resolving call relationships\")\n self._resolve_call_relationships()\n self._deduplicate_relationships()\n viz_data = self._generate_visualization_data()\n\n return {\n \"call_graph\": {\n \"total_functions\": len(self.functions),\n \"total_calls\": len(self.call_relationships),\n \"languages_found\": list(set(f.get(\"language\") for f in code_files)),\n \"files_analyzed\": files_analyzed,\n \"analysis_approach\": \"complete_unlimited\",\n },\n \"functions\": [func.model_dump() for func in self.functions.values()],\n \"relationships\": [rel.model_dump() for rel in self.call_relationships],\n \"visualization\": viz_data,\n }", - "start_line": 66, - "end_line": 127, - "has_docstring": true, - "docstring": "Complete analysis: Analyze all files to build complete call graph with all nodes.\n\nThis approach:\n1. Analyzes all code files \n2. Extracts all functions and relationships\n3. Builds complete call graph\n4. Returns all nodes and relationships ", - "parameters": [ - "self", - "code_files", - "base_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer.analyze_code_files", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer.analyze_code_files", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer.extract_code_files": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer.extract_code_files", - "name": "CallGraphAnalyzer.extract_code_files", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def extract_code_files(self, file_tree: Dict) -> List[Dict]:\n \"\"\"\n Extract code files from file tree structure.\n\n Filters files based on supported extensions and excludes test/config files.\n\n Args:\n file_tree: Nested dictionary representing file structure\n\n Returns:\n List of code file information dictionaries\n \"\"\"\n code_files = []\n\n def traverse(tree):\n if tree[\"type\"] == \"file\":\n ext = tree.get(\"extension\", \"\").lower()\n if ext in CODE_EXTENSIONS:\n name = tree[\"name\"].lower()\n if not any(skip in name for skip in []):\n code_files.append(\n {\n \"path\": tree[\"path\"],\n \"name\": tree[\"name\"],\n \"extension\": ext,\n \"language\": CODE_EXTENSIONS[ext],\n }\n )\n elif tree[\"type\"] == \"directory\" and tree.get(\"children\"):\n for child in tree[\"children\"]:\n traverse(child)\n\n traverse(file_tree)\n return code_files", - "start_line": 129, - "end_line": 162, - "has_docstring": true, - "docstring": "Extract code files from file tree structure.\n\nFilters files based on supported extensions and excludes test/config files.\n\nArgs:\n file_tree: Nested dictionary representing file structure\n\nReturns:\n List of code file information dictionaries", - "parameters": [ - "self", - "file_tree" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer.extract_code_files", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer.extract_code_files", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._route_contextual_headers": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._route_contextual_headers", - "name": "CallGraphAnalyzer._route_contextual_headers", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._header_has_cpp_signal" - ], - "source_code": " def _route_contextual_headers(self, code_files: List[Dict], base_dir: str) -> List[Dict]:\n \"\"\"Route ambiguous .h headers per file.\n\n A header is parsed as C++ when its own content shows C++ signals, or\n when the repository is C++-only (so even a signal-free header cannot be\n C). In a mixed C/C++ repository, a plain C header stays routed as C.\n \"\"\"\n cpp_extensions = {\".cpp\", \".cc\", \".cxx\", \".c++\", \".hpp\", \".hxx\", \".h++\"}\n has_cpp_files = any(\n file_info.get(\"extension\", \"\").lower() in cpp_extensions\n or file_info.get(\"language\") == \"cpp\"\n for file_info in code_files\n )\n has_c_files = any(\n file_info.get(\"extension\", \"\").lower() == \".c\" for file_info in code_files\n )\n\n routed_files = []\n for file_info in code_files:\n routed = dict(file_info)\n if routed.get(\"extension\", \"\").lower() == \".h\":\n if self._header_has_cpp_signal(base_dir, routed[\"path\"]):\n routed[\"language\"] = \"cpp\"\n elif has_cpp_files and not has_c_files:\n routed[\"language\"] = \"cpp\"\n routed_files.append(routed)\n return routed_files", - "start_line": 164, - "end_line": 190, - "has_docstring": true, - "docstring": "Route ambiguous .h headers per file.\n\nA header is parsed as C++ when its own content shows C++ signals, or\nwhen the repository is C++-only (so even a signal-free header cannot be\nC). In a mixed C/C++ repository, a plain C header stays routed as C.", - "parameters": [ - "self", - "code_files", - "base_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._route_contextual_headers", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._route_contextual_headers", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._header_has_cpp_signal": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._header_has_cpp_signal", - "name": "CallGraphAnalyzer._header_has_cpp_signal", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/utils/security.py::safe_open_text" - ], - "source_code": " def _header_has_cpp_signal(self, base_dir: str, relative_path: str) -> bool:\n base = Path(base_dir)\n try:\n content = safe_open_text(base, base / relative_path)\n except Exception:\n return False\n\n if re.search(\n r\"\\b(?:namespace\\s+[A-Za-z_{:]|class\\s+[A-Za-z_]|template\\s*<\"\n r\"|typename\\b|(?:public|private|protected)\\s*:)\",\n content,\n ):\n return True\n if \"::\" in content:\n return True\n for header in CPP_STANDARD_HEADERS:\n if f\"#include <{header}>\" in content:\n return True\n return False", - "start_line": 192, - "end_line": 210, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "base_dir", - "relative_path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._header_has_cpp_signal", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._header_has_cpp_signal", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_code_file": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_code_file", - "name": "CallGraphAnalyzer._analyze_code_file", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::timeout", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_typescript_file", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_java_file", - "codewiki/src/be/dependency_analyzer/utils/security.py::safe_open_text", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_kotlin_file", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_python_file", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_c_file", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_cpp_file", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_javascript_file", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_csharp_file", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_php_file", - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": " def _analyze_code_file(self, repo_dir: str, file_info: Dict):\n \"\"\"\n Analyze a single code file based on its language.\n\n Routes to appropriate language-specific analyzer.\n\n Args:\n repo_dir: Repository directory path\n file_info: File information dictionary\n \"\"\"\n\n base = Path(repo_dir)\n file_path = base / file_info[\"path\"]\n\n try:\n # Add timeout protection (30 seconds per file max)\n with timeout(30):\n content = safe_open_text(base, file_path)\n language = file_info[\"language\"]\n if language == \"python\":\n self._analyze_python_file(file_path, content, repo_dir)\n elif language == \"javascript\":\n self._analyze_javascript_file(file_path, content, repo_dir)\n elif language == \"typescript\":\n self._analyze_typescript_file(file_path, content, repo_dir)\n elif language == \"java\":\n self._analyze_java_file(file_path, content, repo_dir)\n elif language == \"kotlin\":\n self._analyze_kotlin_file(file_path, content, repo_dir)\n elif language == \"csharp\":\n self._analyze_csharp_file(file_path, content, repo_dir)\n elif language == \"c\":\n self._analyze_c_file(file_path, content, repo_dir)\n elif language == \"cpp\":\n self._analyze_cpp_file(file_path, content, repo_dir)\n elif language == \"php\":\n self._analyze_php_file(file_path, content, repo_dir)\n # else:\n # logger.warning(\n # f\"Unsupported language for call graph analysis: {language} for file {file_path}\"\n # )\n\n except TimeoutError as e:\n logger.warning(f\"⏱️ Timeout analyzing {file_path}: {str(e)}\")\n except Exception as e:\n logger.debug(f\"Error analyzing {file_path}: {str(e)}\")\n logger.debug(f\"Traceback: {traceback.format_exc()}\")", - "start_line": 212, - "end_line": 258, - "has_docstring": true, - "docstring": "Analyze a single code file based on its language.\n\nRoutes to appropriate language-specific analyzer.\n\nArgs:\n repo_dir: Repository directory path\n file_info: File information dictionary", - "parameters": [ - "self", - "repo_dir", - "file_info" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._analyze_code_file", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_code_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_python_file": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_python_file", - "name": "CallGraphAnalyzer._analyze_python_file", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/python.py::analyze_python_file", - "codewiki/cli/utils/progress.py::ModuleProgressBar.update", - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": " def _analyze_python_file(self, file_path: str, content: str, base_dir: str):\n \"\"\"\n Analyze Python file using Python AST analyzer.\n\n Args:\n file_path: Relative path to the Python file\n content: File content string\n base_dir: Repository base directory path\n \"\"\"\n from codewiki.src.be.dependency_analyzer.analyzers.python import analyze_python_file\n\n try:\n functions, relationships, external_import_roots = analyze_python_file(\n file_path,\n content,\n repo_path=base_dir,\n project_modules=self._python_project_modules,\n )\n\n for func in functions:\n func_id = func.id if func.id else f\"{file_path}:{func.name}\"\n self.functions[func_id] = func\n\n self.call_relationships.extend(relationships)\n self._python_external_import_roots.update(external_import_roots)\n except Exception as e:\n logger.error(f\"Failed to analyze Python file {file_path}: {e}\", exc_info=True)", - "start_line": 260, - "end_line": 286, - "has_docstring": true, - "docstring": "Analyze Python file using Python AST analyzer.\n\nArgs:\n file_path: Relative path to the Python file\n content: File content string\n base_dir: Repository base directory path", - "parameters": [ - "self", - "file_path", - "content", - "base_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._analyze_python_file", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_python_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._collect_python_modules": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._collect_python_modules", - "name": "CallGraphAnalyzer._collect_python_modules", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def _collect_python_modules(code_files: List[Dict]) -> set:\n \"\"\"Dotted module paths for every Python file in the repository.\"\"\"\n modules = set()\n for file_info in code_files:\n if file_info.get(\"language\") != \"python\":\n continue\n path = file_info[\"path\"]\n for ext in (\".py\", \".pyx\"):\n if path.endswith(ext):\n path = path[: -len(ext)]\n break\n module = path.replace(\"/\", \".\").replace(\"\\\\\", \".\")\n if module.endswith(\".__init__\"):\n module = module[: -len(\".__init__\")]\n if module:\n modules.add(module)\n return modules", - "start_line": 289, - "end_line": 305, - "has_docstring": true, - "docstring": "Dotted module paths for every Python file in the repository.", - "parameters": [ - "code_files" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._collect_python_modules", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._collect_python_modules", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_javascript_file": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_javascript_file", - "name": "CallGraphAnalyzer._analyze_javascript_file", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/cli/utils/logging.py::CLILogger.error", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::analyze_javascript_file_treesitter" - ], - "source_code": " def _analyze_javascript_file(self, file_path: str, content: str, repo_dir: str):\n \"\"\"\n Analyze JavaScript file using tree-sitter based AST analyzer\n\n Args:\n file_path: Relative path to the JavaScript file\n content: File content string\n repo_dir: Repository base directory\n \"\"\"\n try:\n\n from codewiki.src.be.dependency_analyzer.analyzers.javascript import analyze_javascript_file_treesitter\n\n functions, relationships = analyze_javascript_file_treesitter(\n file_path, content, repo_path=repo_dir\n )\n\n for func in functions:\n func_id = func.id if func.id else f\"{file_path}:{func.name}\"\n self.functions[func_id] = func\n\n self.call_relationships.extend(relationships)\n\n except Exception as e:\n logger.error(f\"Failed to analyze JavaScript file {file_path}: {e}\", exc_info=True)", - "start_line": 307, - "end_line": 331, - "has_docstring": true, - "docstring": "Analyze JavaScript file using tree-sitter based AST analyzer\n\nArgs:\n file_path: Relative path to the JavaScript file\n content: File content string\n repo_dir: Repository base directory", - "parameters": [ - "self", - "file_path", - "content", - "repo_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._analyze_javascript_file", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_javascript_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_typescript_file": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_typescript_file", - "name": "CallGraphAnalyzer._analyze_typescript_file", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::analyze_typescript_file_treesitter", - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": " def _analyze_typescript_file(self, file_path: str, content: str, repo_dir: str):\n \"\"\"\n Analyze TypeScript file using tree-sitter based AST analyzer \n\n Args:\n file_path: Relative path to the TypeScript file\n content: File content string\n \"\"\"\n try:\n\n from codewiki.src.be.dependency_analyzer.analyzers.typescript import analyze_typescript_file_treesitter\n\n functions, relationships = analyze_typescript_file_treesitter(\n file_path, content, repo_path=repo_dir\n )\n\n for func in functions:\n func_id = func.id if func.id else f\"{file_path}:{func.name}\"\n self.functions[func_id] = func\n\n self.call_relationships.extend(relationships)\n\n except Exception as e:\n logger.error(f\"Failed to analyze TypeScript file {file_path}: {e}\", exc_info=True)", - "start_line": 333, - "end_line": 356, - "has_docstring": true, - "docstring": "Analyze TypeScript file using tree-sitter based AST analyzer \n\nArgs:\n file_path: Relative path to the TypeScript file\n content: File content string", - "parameters": [ - "self", - "file_path", - "content", - "repo_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._analyze_typescript_file", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_typescript_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_c_file": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_c_file", - "name": "CallGraphAnalyzer._analyze_c_file", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/c.py::analyze_c_file" - ], - "source_code": " def _analyze_c_file(self, file_path: str, content: str, repo_dir: str):\n \"\"\"\n Analyze C file using tree-sitter based analyzer.\n\n Args:\n file_path: Relative path to the C file\n content: File content string\n repo_dir: Repository base directory\n \"\"\"\n from codewiki.src.be.dependency_analyzer.analyzers.c import analyze_c_file\n\n functions, relationships = analyze_c_file(file_path, content, repo_path=repo_dir)\n\n for func in functions:\n func_id = func.id if func.id else f\"{file_path}:{func.name}\"\n self.functions[func_id] = func\n\n self.call_relationships.extend(relationships)", - "start_line": 360, - "end_line": 377, - "has_docstring": true, - "docstring": "Analyze C file using tree-sitter based analyzer.\n\nArgs:\n file_path: Relative path to the C file\n content: File content string\n repo_dir: Repository base directory", - "parameters": [ - "self", - "file_path", - "content", - "repo_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._analyze_c_file", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_c_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_cpp_file": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_cpp_file", - "name": "CallGraphAnalyzer._analyze_cpp_file", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::analyze_cpp_file" - ], - "source_code": " def _analyze_cpp_file(self, file_path: str, content: str, repo_dir: str):\n \"\"\"\n Analyze C++ file using tree-sitter based analyzer.\n\n Args:\n file_path: Relative path to the C++ file\n content: File content string\n \"\"\"\n from codewiki.src.be.dependency_analyzer.analyzers.cpp import analyze_cpp_file\n\n functions, relationships = analyze_cpp_file(\n file_path, content, repo_path=repo_dir\n )\n\n for func in functions:\n func_id = func.id if func.id else f\"{file_path}:{func.name}\"\n self.functions[func_id] = func\n\n self.call_relationships.extend(relationships)", - "start_line": 379, - "end_line": 397, - "has_docstring": true, - "docstring": "Analyze C++ file using tree-sitter based analyzer.\n\nArgs:\n file_path: Relative path to the C++ file\n content: File content string", - "parameters": [ - "self", - "file_path", - "content", - "repo_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._analyze_cpp_file", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_cpp_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_java_file": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_java_file", - "name": "CallGraphAnalyzer._analyze_java_file", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/java.py::analyze_java_file", - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": " def _analyze_java_file(self, file_path: str, content: str, repo_dir: str):\n \"\"\"\n Analyze Java file using tree-sitter based analyzer.\n\n Args:\n file_path: Relative path to the Java file\n content: File content string\n repo_dir: Repository base directory\n \"\"\"\n from codewiki.src.be.dependency_analyzer.analyzers.java import analyze_java_file\n\n try:\n functions, relationships = analyze_java_file(file_path, content, repo_path=repo_dir)\n for func in functions:\n func_id = func.id if func.id else f\"{file_path}:{func.name}\"\n self.functions[func_id] = func\n\n self.call_relationships.extend(relationships)\n except Exception as e:\n logger.error(f\"Failed to analyze Java file {file_path}: {e}\", exc_info=True)", - "start_line": 399, - "end_line": 418, - "has_docstring": true, - "docstring": "Analyze Java file using tree-sitter based analyzer.\n\nArgs:\n file_path: Relative path to the Java file\n content: File content string\n repo_dir: Repository base directory", - "parameters": [ - "self", - "file_path", - "content", - "repo_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._analyze_java_file", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_java_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_kotlin_file": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_kotlin_file", - "name": "CallGraphAnalyzer._analyze_kotlin_file", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::analyze_kotlin_file", - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": " def _analyze_kotlin_file(self, file_path: str, content: str, repo_dir: str):\n \"\"\"\n Analyze Kotlin file using tree-sitter based analyzer.\n\n Args:\n file_path: Relative path to the Kotlin file\n content: File content string\n repo_dir: Repository base directory\n \"\"\"\n from codewiki.src.be.dependency_analyzer.analyzers.kotlin import analyze_kotlin_file\n\n try:\n functions, relationships = analyze_kotlin_file(file_path, content, repo_path=repo_dir)\n for func in functions:\n func_id = func.id if func.id else f\"{file_path}:{func.name}\"\n self.functions[func_id] = func\n\n self.call_relationships.extend(relationships)\n except Exception as e:\n logger.error(f\"Failed to analyze Kotlin file {file_path}: {e}\", exc_info=True)", - "start_line": 420, - "end_line": 439, - "has_docstring": true, - "docstring": "Analyze Kotlin file using tree-sitter based analyzer.\n\nArgs:\n file_path: Relative path to the Kotlin file\n content: File content string\n repo_dir: Repository base directory", - "parameters": [ - "self", - "file_path", - "content", - "repo_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._analyze_kotlin_file", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_kotlin_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_csharp_file": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_csharp_file", - "name": "CallGraphAnalyzer._analyze_csharp_file", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::analyze_csharp_file", - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": " def _analyze_csharp_file(self, file_path: str, content: str, repo_dir: str):\n \"\"\"\n Analyze C# file using tree-sitter based analyzer.\n\n Args:\n file_path: Relative path to the C# file\n content: File content string\n repo_dir: Repository base directory\n \"\"\"\n from codewiki.src.be.dependency_analyzer.analyzers.csharp import analyze_csharp_file\n\n try:\n functions, relationships = analyze_csharp_file(file_path, content, repo_path=repo_dir)\n\n for func in functions:\n func_id = func.id if func.id else f\"{file_path}:{func.name}\"\n self.functions[func_id] = func\n\n self.call_relationships.extend(relationships)\n except Exception as e:\n logger.error(f\"Failed to analyze C# file {file_path}: {e}\", exc_info=True)", - "start_line": 441, - "end_line": 461, - "has_docstring": true, - "docstring": "Analyze C# file using tree-sitter based analyzer.\n\nArgs:\n file_path: Relative path to the C# file\n content: File content string\n repo_dir: Repository base directory", - "parameters": [ - "self", - "file_path", - "content", - "repo_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._analyze_csharp_file", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_csharp_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_php_file": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_php_file", - "name": "CallGraphAnalyzer._analyze_php_file", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/cli/utils/logging.py::CLILogger.error", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::analyze_php_file" - ], - "source_code": " def _analyze_php_file(self, file_path: str, content: str, repo_dir: str):\n \"\"\"\n Analyze PHP file using tree-sitter based analyzer.\n\n Args:\n file_path: Relative path to the PHP file\n content: File content string\n repo_dir: Repository base directory\n \"\"\"\n from codewiki.src.be.dependency_analyzer.analyzers.php import analyze_php_file\n\n try:\n functions, relationships = analyze_php_file(file_path, content, repo_path=repo_dir)\n\n for func in functions:\n func_id = func.id if func.id else f\"{file_path}:{func.name}\"\n self.functions[func_id] = func\n\n self.call_relationships.extend(relationships)\n except Exception as e:\n logger.error(f\"Failed to analyze PHP file {file_path}: {e}\", exc_info=True)", - "start_line": 463, - "end_line": 483, - "has_docstring": true, - "docstring": "Analyze PHP file using tree-sitter based analyzer.\n\nArgs:\n file_path: Relative path to the PHP file\n content: File content string\n repo_dir: Repository base directory", - "parameters": [ - "self", - "file_path", - "content", - "repo_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._analyze_php_file", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._analyze_php_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._resolve_call_relationships": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._resolve_call_relationships", - "name": "CallGraphAnalyzer._resolve_call_relationships", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._caller_language", - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._dotted_project_packages", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._resolve_callee", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._is_external_callee", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._build_resolution_indexes" - ], - "source_code": " def _resolve_call_relationships(self):\n \"\"\"\n Resolve function call relationships across all languages.\n\n Attempts to match function calls to actual function definitions,\n handling cross-language calls where possible.\n \"\"\"\n for func_id, func_info in self.functions.items():\n if not func_info.language:\n file_ext = Path(func_info.file_path).suffix.lower()\n func_info.language = CODE_EXTENSIONS.get(file_ext)\n\n indexes = self._build_resolution_indexes()\n\n resolved_count = 0\n for relationship in self.call_relationships:\n if relationship.is_resolved and relationship.callee in self.functions:\n continue\n\n resolved_id = self._resolve_callee(relationship, indexes)\n if resolved_id:\n relationship.callee = resolved_id\n relationship.is_resolved = True\n resolved_count += 1\n\n dotted_packages = self._dotted_project_packages()\n self.call_relationships = [\n relationship\n for relationship in self.call_relationships\n if relationship.is_resolved\n or not self._is_external_callee(\n self._caller_language(relationship.caller),\n relationship.callee,\n dotted_packages,\n )\n ]", - "start_line": 485, - "end_line": 520, - "has_docstring": true, - "docstring": "Resolve function call relationships across all languages.\n\nAttempts to match function calls to actual function definitions,\nhandling cross-language calls where possible.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._resolve_call_relationships", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._resolve_call_relationships", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._dotted_project_packages": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._dotted_project_packages", - "name": "CallGraphAnalyzer._dotted_project_packages", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._dotted_package_for_node" - ], - "source_code": " def _dotted_project_packages(self) -> Dict[str, set]:\n \"\"\"Project packages/namespaces, partitioned by language. Java and C#\n share the namespace-origin rule: a dotted callee qualified to a package\n with no prefix relation to any project package came from a third-party\n import.\"\"\"\n packages: Dict[str, set] = defaultdict(set)\n for func_info in self.functions.values():\n if func_info.language in (\"java\", \"csharp\"):\n package = self._dotted_package_for_node(func_info)\n if package:\n packages[func_info.language].add(package)\n return packages", - "start_line": 522, - "end_line": 533, - "has_docstring": true, - "docstring": "Project packages/namespaces, partitioned by language. Java and C#\nshare the namespace-origin rule: a dotted callee qualified to a package\nwith no prefix relation to any project package came from a third-party\nimport.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._dotted_project_packages", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._dotted_project_packages", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._is_external_callee": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._is_external_callee", - "name": "CallGraphAnalyzer._is_external_callee", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/utils/external_symbols.py::is_external_symbol", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._is_external_python_callee", - "codewiki/src/be/dependency_analyzer/utils/external_symbols.py::is_macro_name" - ], - "source_code": " def _is_external_callee(self, language: Optional[str], callee: str, dotted_packages: Dict[str, set]) -> bool:\n \"\"\"Classify a still-unresolved callee as external, after project\n resolution has had its chance.\n\n Rules are generic, not name lists: prefix/standard-library knowledge in\n is_external_symbol, the C/C++ ALL_CAPS macro convention (macros are\n never components, so such calls can never resolve), and Java package\n origin β€” a dotted name qualified to a package with no prefix relation\n to any project package came from a third-party import.\n \"\"\"\n if is_external_symbol(language, callee):\n return True\n if language in (\"c\", \"cpp\") and is_macro_name(callee):\n return True\n if language in (\"java\", \"csharp\") and \".\" in callee and dotted_packages.get(language):\n package = callee.rsplit(\".\", 1)[0]\n if not any(\n package == project\n or package.startswith(project + \".\")\n or project.startswith(package + \".\")\n for project in dotted_packages[language]\n ):\n return True\n if language == \"python\" and \".\" in callee:\n return self._is_external_python_callee(callee)\n return False", - "start_line": 535, - "end_line": 560, - "has_docstring": true, - "docstring": "Classify a still-unresolved callee as external, after project\nresolution has had its chance.\n\nRules are generic, not name lists: prefix/standard-library knowledge in\nis_external_symbol, the C/C++ ALL_CAPS macro convention (macros are\nnever components, so such calls can never resolve), and Java package\norigin β€” a dotted name qualified to a package with no prefix relation\nto any project package came from a third-party import.", - "parameters": [ - "self", - "language", - "callee", - "dotted_packages" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._is_external_callee", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._is_external_callee", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._is_external_python_callee": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._is_external_python_callee", - "name": "CallGraphAnalyzer._is_external_python_callee", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/python.py::is_project_import" - ], - "source_code": " def _is_external_python_callee(self, callee: str) -> bool:\n \"\"\"Classify a still-unresolved dotted Python callee.\n\n A callee whose dotted prefix aligns with a project module is an\n honest project gap, never external. Otherwise the import-origin rule\n (head was imported from outside the project) and the core-object\n method rule (a tail like ``append``/``endswith`` on an unknowable\n receiver can never be a project component) apply.\n \"\"\"\n from codewiki.src.be.dependency_analyzer.analyzers.python import is_project_import\n from codewiki.src.be.dependency_analyzer.utils.external_symbols import (\n PYTHON_OBJECT_METHODS,\n )\n\n parts = callee.split(\".\")\n if self._python_project_modules:\n for end in range(len(parts) - 1, 0, -1):\n if is_project_import(\".\".join(parts[:end]), self._python_project_modules):\n return False\n if parts[0] in self._python_external_import_roots:\n return True\n return parts[-1] in PYTHON_OBJECT_METHODS", - "start_line": 562, - "end_line": 583, - "has_docstring": true, - "docstring": "Classify a still-unresolved dotted Python callee.\n\nA callee whose dotted prefix aligns with a project module is an\nhonest project gap, never external. Otherwise the import-origin rule\n(head was imported from outside the project) and the core-object\nmethod rule (a tail like ``append``/``endswith`` on an unknowable\nreceiver can never be a project component) apply.", - "parameters": [ - "self", - "callee" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._is_external_python_callee", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._is_external_python_callee", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._build_resolution_indexes": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._build_resolution_indexes", - "name": "CallGraphAnalyzer._build_resolution_indexes", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [], - "source_code": " def _build_resolution_indexes(self) -> Dict[str, Dict]:\n \"\"\"Build exact/simple-name lookup indexes, both globally and per\n language. Resolution prefers the caller's own language partition: a\n name that is unique within the caller's language resolves even when\n another language defines the same name, and names made ambiguous only\n by foreign-language components keep resolving as before.\"\"\"\n def make() -> Dict[str, Dict[str, List[str]]]:\n return {\"exact\": defaultdict(list), \"simple\": defaultdict(list)}\n\n global_indexes = make()\n by_lang: Dict[str, Dict[str, Dict[str, List[str]]]] = defaultdict(make)\n\n def add(index: Dict[str, List[str]], key: Optional[str], func_id: str) -> None:\n if key and func_id not in index[key]:\n index[key].append(func_id)\n\n for func_id, func_info in self.functions.items():\n targets = [global_indexes]\n if func_info.language:\n targets.append(by_lang[func_info.language])\n\n exact_keys = [\n func_id,\n func_info.component_id,\n func_info.qualified_name,\n func_info.name,\n ]\n\n names = {func_info.name}\n if func_info.component_id:\n names.add(func_info.component_id.split(\"::\")[-1])\n if func_info.qualified_name:\n names.add(func_info.qualified_name.split(\".\")[-1])\n parts = func_info.qualified_name.split(\".\")\n if len(parts) >= 2:\n names.add(\".\".join(parts[-2:]))\n\n for target in targets:\n for key in exact_keys:\n add(target[\"exact\"], key, func_id)\n for name in names:\n add(target[\"simple\"], name, func_id)\n if name and \".\" in name:\n add(target[\"simple\"], name.split(\".\")[-1], func_id)\n\n return {\n \"exact\": global_indexes[\"exact\"],\n \"simple\": global_indexes[\"simple\"],\n \"by_lang\": dict(by_lang),\n }", - "start_line": 585, - "end_line": 634, - "has_docstring": true, - "docstring": "Build exact/simple-name lookup indexes, both globally and per\nlanguage. Resolution prefers the caller's own language partition: a\nname that is unique within the caller's language resolves even when\nanother language defines the same name, and names made ambiguous only\nby foreign-language components keep resolving as before.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._build_resolution_indexes", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._build_resolution_indexes", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._resolve_callee": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._resolve_callee", - "name": "CallGraphAnalyzer._resolve_callee", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._resolve_callee_in" - ], - "source_code": " def _resolve_callee(self, relationship: CallRelationship, indexes: Dict[str, Dict]) -> Optional[str]:\n caller = self.functions.get(relationship.caller)\n caller_language = caller.language if caller else None\n\n lang_indexes = indexes[\"by_lang\"].get(caller_language) if caller_language else None\n if lang_indexes:\n match = self._resolve_callee_in(relationship, lang_indexes[\"exact\"], lang_indexes[\"simple\"])\n if match:\n return match\n\n return self._resolve_callee_in(relationship, indexes[\"exact\"], indexes[\"simple\"])", - "start_line": 636, - "end_line": 646, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "relationship", - "indexes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._resolve_callee", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._resolve_callee", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._resolve_callee_in": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._resolve_callee_in", - "name": "CallGraphAnalyzer._resolve_callee_in", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._dotted_package_for_node", - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._unique_match" - ], - "source_code": " def _resolve_callee_in(\n self,\n relationship: CallRelationship,\n exact: Dict[str, List[str]],\n simple: Dict[str, List[str]],\n ) -> Optional[str]:\n callee_name = relationship.callee\n\n exact_match = self._unique_match(exact, callee_name)\n if exact_match:\n return exact_match\n\n if \"::\" in callee_name:\n suffix = callee_name.split(\"::\")[-1]\n exact_match = self._unique_match(exact, suffix)\n if exact_match:\n return exact_match\n simple_match = self._unique_match(simple, suffix)\n if simple_match:\n return simple_match\n\n if \".\" in callee_name:\n simple_match = self._unique_match(simple, callee_name)\n if simple_match:\n return simple_match\n tail_match = self._unique_match(simple, callee_name.split(\".\")[-1])\n if tail_match:\n return tail_match\n\n caller = self.functions.get(relationship.caller)\n if caller and caller.language in (\"java\", \"csharp\") and \".\" not in callee_name:\n package = self._dotted_package_for_node(caller)\n if package:\n same_package_match = self._unique_match(exact, f\"{package}.{callee_name}\")\n if same_package_match:\n return same_package_match\n\n return self._unique_match(simple, callee_name)", - "start_line": 648, - "end_line": 685, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "relationship", - "exact", - "simple" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._resolve_callee_in", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._resolve_callee_in", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._unique_match": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._unique_match", - "name": "CallGraphAnalyzer._unique_match", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def _unique_match(self, index: Dict[str, List[str]], key: str) -> Optional[str]:\n matches = index.get(key, [])\n return matches[0] if len(matches) == 1 else None", - "start_line": 687, - "end_line": 689, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "index", - "key" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._unique_match", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._unique_match", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._dotted_package_for_node": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._dotted_package_for_node", - "name": "CallGraphAnalyzer._dotted_package_for_node", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [], - "source_code": " def _dotted_package_for_node(self, node: Node) -> str:\n \"\"\"The package (Java) / namespace (C#) a node lives in, derived from its\n dotted qualified name. Both languages share the same shape: a type's\n package is its qualified name minus the type, a method's is minus\n ``Type.method``.\"\"\"\n qualified_name = node.qualified_name or \"\"\n parts = qualified_name.split(\".\")\n if len(parts) < 2:\n return \"\"\n if node.component_type == \"method\" and len(parts) >= 3:\n return \".\".join(parts[:-2])\n return \".\".join(parts[:-1])", - "start_line": 691, - "end_line": 702, - "has_docstring": true, - "docstring": "The package (Java) / namespace (C#) a node lives in, derived from its\ndotted qualified name. Both languages share the same shape: a type's\npackage is its qualified name minus the type, a method's is minus\n``Type.method``.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._dotted_package_for_node", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._dotted_package_for_node", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._caller_language": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._caller_language", - "name": "CallGraphAnalyzer._caller_language", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def _caller_language(self, caller_id: str) -> Optional[str]:\n caller = self.functions.get(caller_id)\n if caller and caller.language:\n return caller.language\n if caller:\n return CODE_EXTENSIONS.get(Path(caller.file_path).suffix.lower())\n return None", - "start_line": 704, - "end_line": 710, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "caller_id" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._caller_language", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._caller_language", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._deduplicate_relationships": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._deduplicate_relationships", - "name": "CallGraphAnalyzer._deduplicate_relationships", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [], - "source_code": " def _deduplicate_relationships(self):\n \"\"\"\n Deduplicate call relationships based on caller-callee pairs.\n\n Removes duplicate relationships while preserving the first occurrence.\n This helps eliminate noise from multiple calls to the same function.\n \"\"\"\n seen = set()\n unique_relationships = []\n\n for rel in self.call_relationships:\n key = (rel.caller, rel.callee)\n if key not in seen:\n seen.add(key)\n unique_relationships.append(rel)\n\n self.call_relationships = unique_relationships", - "start_line": 712, - "end_line": 728, - "has_docstring": true, - "docstring": "Deduplicate call relationships based on caller-callee pairs.\n\nRemoves duplicate relationships while preserving the first occurrence.\nThis helps eliminate noise from multiple calls to the same function.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._deduplicate_relationships", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._deduplicate_relationships", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._generate_visualization_data": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._generate_visualization_data", - "name": "CallGraphAnalyzer._generate_visualization_data", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def _generate_visualization_data(self) -> Dict:\n \"\"\"\n Generate visualization data for graph rendering.\n\n Creates Cytoscape.js compatible graph data with nodes and edges.\n\n Returns:\n Dict: Visualization data with cytoscape elements and summary\n \"\"\"\n cytoscape_elements = []\n\n for func_id, func_info in self.functions.items():\n node_classes = []\n if func_info.node_type == \"method\":\n node_classes.append(\"node-method\")\n else:\n node_classes.append(\"node-function\")\n\n file_ext = Path(func_info.file_path).suffix.lower()\n language = func_info.language or CODE_EXTENSIONS.get(file_ext, \"unknown\")\n if file_ext == \".py\":\n node_classes.append(\"lang-python\")\n elif file_ext == \".js\":\n node_classes.append(\"lang-javascript\")\n elif file_ext == \".ts\":\n node_classes.append(\"lang-typescript\")\n elif language == \"c\":\n node_classes.append(\"lang-c\")\n elif language == \"cpp\" or file_ext in [\".cpp\", \".cc\", \".cxx\", \".c++\", \".hpp\", \".hxx\", \".h++\"]:\n node_classes.append(\"lang-cpp\")\n elif file_ext in [\".kt\", \".kts\"]:\n node_classes.append(\"lang-kotlin\")\n elif file_ext in [\".php\", \".phtml\", \".inc\"]:\n node_classes.append(\"lang-php\")\n\n cytoscape_elements.append(\n {\n \"data\": {\n \"id\": func_id,\n \"label\": func_info.name,\n \"file\": func_info.file_path,\n \"type\": func_info.node_type or \"function\",\n \"language\": language,\n },\n \"classes\": \" \".join(node_classes),\n }\n )\n\n resolved_rels = [r for r in self.call_relationships if r.is_resolved]\n for rel in resolved_rels:\n cytoscape_elements.append(\n {\n \"data\": {\n \"id\": f\"{rel.caller}->{rel.callee}\",\n \"source\": rel.caller,\n \"target\": rel.callee,\n \"line\": rel.call_line,\n },\n \"classes\": \"edge-call\",\n }\n )\n\n summary = {\n \"total_nodes\": len(self.functions),\n \"total_edges\": len(resolved_rels),\n \"unresolved_calls\": len(self.call_relationships) - len(resolved_rels),\n }\n\n return {\n \"cytoscape\": {\"elements\": cytoscape_elements},\n \"summary\": summary,\n }", - "start_line": 730, - "end_line": 801, - "has_docstring": true, - "docstring": "Generate visualization data for graph rendering.\n\nCreates Cytoscape.js compatible graph data with nodes and edges.\n\nReturns:\n Dict: Visualization data with cytoscape elements and summary", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._generate_visualization_data", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._generate_visualization_data", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer.generate_llm_format": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer.generate_llm_format", - "name": "CallGraphAnalyzer.generate_llm_format", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [], - "source_code": " def generate_llm_format(self) -> Dict:\n \"\"\"Generate clean format optimized for LLM consumption.\"\"\"\n return {\n \"functions\": [\n {\n \"name\": func.name,\n \"file\": Path(func.file_path).name,\n \"purpose\": (func.docstring.split(\"\\n\")[0] if func.docstring else None),\n \"parameters\": func.parameters,\n \"is_recursive\": func.name\n in [\n rel.callee\n for rel in self.call_relationships\n if rel.caller.endswith(func.name)\n ],\n }\n for func in self.functions.values()\n ],\n \"relationships\": {\n func.name: {\n \"calls\": [\n rel.callee.split(\":\")[-1]\n for rel in self.call_relationships\n if rel.caller.endswith(func.name) and rel.is_resolved\n ],\n \"called_by\": [\n rel.caller.split(\":\")[-1]\n for rel in self.call_relationships\n if rel.callee.endswith(func.name) and rel.is_resolved\n ],\n }\n for func in self.functions.values()\n },\n }", - "start_line": 803, - "end_line": 836, - "has_docstring": true, - "docstring": "Generate clean format optimized for LLM consumption.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer.generate_llm_format", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer.generate_llm_format", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._select_most_connected_nodes": { - "id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._select_most_connected_nodes", - "name": "CallGraphAnalyzer._select_most_connected_nodes", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def _select_most_connected_nodes(self, target_count: int):\n \"\"\"\n Select the most connected nodes from the call graph.\n\n Args:\n target_count: The number of nodes to select\n \"\"\"\n if len(self.functions) <= target_count:\n return\n\n if not self.call_relationships:\n logger.warning(\"No call relationships found - keeping all functions by name\")\n func_ids = list(self.functions.keys())[:target_count]\n self.functions = {fid: func for fid, func in self.functions.items() if fid in func_ids}\n return\n\n graph = {}\n for rel in self.call_relationships:\n if rel.caller in self.functions:\n if rel.caller not in graph:\n graph[rel.caller] = set()\n if rel.callee in self.functions:\n if rel.callee not in graph:\n graph[rel.callee] = set()\n\n if rel.caller in graph and rel.callee in graph:\n graph[rel.caller].add(rel.callee)\n graph[rel.callee].add(rel.caller)\n\n degree_centrality = {}\n for func_id in self.functions.keys():\n degree_centrality[func_id] = len(graph.get(func_id, set()))\n\n sorted_func_ids = sorted(degree_centrality, key=degree_centrality.get, reverse=True)\n\n selected_func_ids = sorted_func_ids[:target_count]\n\n original_func_count = len(self.functions)\n self.functions = {\n fid: func for fid, func in self.functions.items() if fid in selected_func_ids\n }\n\n original_rel_count = len(self.call_relationships)\n self.call_relationships = [\n rel\n for rel in self.call_relationships\n if rel.caller in selected_func_ids and rel.callee in selected_func_ids\n ]", - "start_line": 838, - "end_line": 885, - "has_docstring": true, - "docstring": "Select the most connected nodes from the call graph.\n\nArgs:\n target_count: The number of nodes to select", - "parameters": [ - "self", - "target_count" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CallGraphAnalyzer", - "display_name": "method CallGraphAnalyzer._select_most_connected_nodes", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/call_graph_analyzer.py::CallGraphAnalyzer._select_most_connected_nodes", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/cloning.py::sanitize_github_url": { - "id": "codewiki/src/be/dependency_analyzer/analysis/cloning.py::sanitize_github_url", - "name": "sanitize_github_url", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/cloning.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/cloning.py", - "depends_on": [], - "source_code": "def sanitize_github_url(github_url: str) -> str:\n \"\"\"\n Sanitize GitHub URL to ensure proper format and remove extra path components.\n\n Args:\n github_url: Raw GitHub URL or repository path\n\n Returns:\n str: Sanitized GitHub URL suitable for cloning\n \"\"\"\n\n url = github_url.strip()\n\n protocol = \"https://\"\n if url.startswith(\"https://\"):\n url = url[8:]\n elif url.startswith(\"http://\"):\n url = url[7:]\n protocol = \"http://\"\n\n if url.startswith(\"www.\"):\n url = url[4:]\n\n parts = url.split(\"/\")\n\n if url.startswith(\"github.com/\"):\n url_parts = url.split(\"/\")\n if len(url_parts) >= 3:\n owner = url_parts[1]\n repo = url_parts[2]\n else:\n return github_url\n elif \"/\" in url and not url.startswith(\"github.com\"):\n url_parts = url.split(\"/\")\n if len(url_parts) >= 2:\n owner = url_parts[0]\n repo = url_parts[1]\n else:\n return github_url\n else:\n return github_url\n\n if repo.endswith(\".git\"):\n repo = repo[:-4]\n\n return f\"{protocol}github.com/{owner}/{repo}\"", - "start_line": 12, - "end_line": 57, - "has_docstring": true, - "docstring": "Sanitize GitHub URL to ensure proper format and remove extra path components.\n\nArgs:\n github_url: Raw GitHub URL or repository path\n\nReturns:\n str: Sanitized GitHub URL suitable for cloning", - "parameters": [ - "github_url" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function sanitize_github_url", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/cloning.py::sanitize_github_url", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/cloning.py::clone_repository": { - "id": "codewiki/src/be/dependency_analyzer/analysis/cloning.py::clone_repository", - "name": "clone_repository", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/cloning.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/cloning.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/cloning.py::sanitize_github_url", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.run", - "codewiki/src/be/dependency_analyzer/analysis/cloning.py::cleanup_repository_safe" - ], - "source_code": "def clone_repository(github_url: str) -> str:\n \"\"\"\n Clone a GitHub repository to a temporary directory.\n\n Args:\n github_url: GitHub repository URL (will be sanitized automatically)\n\n Returns:\n str: Path to the cloned repository directory\n\n Raises:\n RuntimeError: If cloning fails or git executable is not found.\n \"\"\"\n if not GIT_EXECUTABLE_PATH:\n raise RuntimeError(\n \"Git executable not found. Please install Git and ensure it is in the system's PATH.\"\n )\n\n sanitized_url = sanitize_github_url(github_url)\n\n temp_dir = tempfile.mkdtemp(prefix=\"gitprobe_\")\n\n try:\n if os.name == \"nt\":\n try:\n subprocess.run(\n [\n GIT_EXECUTABLE_PATH,\n \"config\",\n \"--global\",\n \"core.longpaths\",\n \"true\",\n ],\n capture_output=True,\n text=True,\n )\n except:\n pass\n\n subprocess.run(\n [\n GIT_EXECUTABLE_PATH,\n \"clone\",\n \"--depth\",\n \"1\",\n \"--filter=blob:none\",\n sanitized_url,\n temp_dir,\n ],\n check=True,\n capture_output=True,\n text=True,\n timeout=300,\n )\n\n if os.name == \"nt\":\n try:\n subprocess.run(\n [\n GIT_EXECUTABLE_PATH,\n \"-C\",\n temp_dir,\n \"config\",\n \"core.sparseCheckout\",\n \"true\",\n ],\n capture_output=True,\n text=True,\n )\n\n sparse_checkout_path = os.path.join(temp_dir, \".git\", \"info\", \"sparse-checkout\")\n os.makedirs(os.path.dirname(sparse_checkout_path), exist_ok=True)\n with open(sparse_checkout_path, \"w\") as f:\n f.write(\"*\\n\")\n f.write(\"!**/tests/**/CvnF9nAXfESwhrtdkjGhX2wAkKHzwr8N2rjExPK8eZYS/**\\n\")\n f.write(\n \"!**/0x0000000000000000000000000000000000000000000000000000000000000002/**\\n\"\n )\n\n subprocess.run(\n [\n GIT_EXECUTABLE_PATH,\n \"-C\",\n temp_dir,\n \"read-tree\",\n \"-m\",\n \"-u\",\n \"HEAD\",\n ],\n capture_output=True,\n text=True,\n )\n except:\n pass\n return temp_dir\n except subprocess.TimeoutExpired:\n if os.path.exists(temp_dir):\n cleanup_repository_safe(temp_dir)\n raise RuntimeError(\n f\"Repository cloning timed out after 5 minutes. The repository may be too large or network is slow.\"\n )\n except subprocess.CalledProcessError as e:\n if os.path.exists(temp_dir):\n cleanup_repository_safe(temp_dir)\n raise RuntimeError(f\"Failed to clone repository: {e.stderr}\")\n except FileNotFoundError:\n if os.path.exists(temp_dir):\n cleanup_repository_safe(temp_dir)\n raise RuntimeError(\n f\"Git executable not found at '{GIT_EXECUTABLE_PATH}'. \"\n \"Please ensure Git is installed and the path is correct.\"\n )", - "start_line": 60, - "end_line": 171, - "has_docstring": true, - "docstring": "Clone a GitHub repository to a temporary directory.\n\nArgs:\n github_url: GitHub repository URL (will be sanitized automatically)\n\nReturns:\n str: Path to the cloned repository directory\n\nRaises:\n RuntimeError: If cloning fails or git executable is not found.", - "parameters": [ - "github_url" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function clone_repository", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/cloning.py::clone_repository", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/cloning.py::cleanup_repository_safe": { - "id": "codewiki/src/be/dependency_analyzer/analysis/cloning.py::cleanup_repository_safe", - "name": "cleanup_repository_safe", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/cloning.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/cloning.py", - "depends_on": [], - "source_code": "def cleanup_repository_safe(repo_dir: str) -> bool:\n \"\"\"\n Windows-safe removal of the cloned repository directory.\n Handles read-only files and permission issues common on Windows.\n\n Args:\n repo_dir: Path to the repository directory to remove\n\n Returns:\n bool: True if cleanup successful, False otherwise\n \"\"\"\n\n def handle_remove_readonly(func, path, exc):\n \"\"\"Error handler for Windows read-only files.\"\"\"\n if os.path.exists(path):\n os.chmod(path, stat.S_IWRITE)\n func(path)\n\n try:\n if os.path.exists(repo_dir):\n if os.name == \"nt\":\n shutil.rmtree(repo_dir, onerror=handle_remove_readonly)\n else:\n shutil.rmtree(repo_dir)\n return True\n return False\n except PermissionError as e:\n try:\n time.sleep(1)\n if os.path.exists(repo_dir):\n for root, dirs, files in os.walk(repo_dir):\n for dir in dirs:\n os.chmod(os.path.join(root, dir), stat.S_IWRITE)\n for file in files:\n file_path = os.path.join(root, file)\n if os.path.exists(file_path):\n os.chmod(file_path, stat.S_IWRITE)\n shutil.rmtree(repo_dir)\n return True\n except Exception as retry_e:\n print(f\"⚠️ Warning: Failed to cleanup {repo_dir} after retry: {str(retry_e)}\")\n return False\n except Exception as e:\n print(f\"⚠️ Warning: Failed to cleanup {repo_dir}: {str(e)}\")\n return False", - "start_line": 174, - "end_line": 218, - "has_docstring": true, - "docstring": "Windows-safe removal of the cloned repository directory.\nHandles read-only files and permission issues common on Windows.\n\nArgs:\n repo_dir: Path to the repository directory to remove\n\nReturns:\n bool: True if cleanup successful, False otherwise", - "parameters": [ - "repo_dir" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function cleanup_repository_safe", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/cloning.py::cleanup_repository_safe", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/cloning.py::cleanup_repository": { - "id": "codewiki/src/be/dependency_analyzer/analysis/cloning.py::cleanup_repository", - "name": "cleanup_repository", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/cloning.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/cloning.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/cloning.py::cleanup_repository_safe" - ], - "source_code": "def cleanup_repository(repo_dir: str) -> bool:\n \"\"\"\n Remove the cloned repository directory (wrapper for backward compatibility).\n\n Args:\n repo_dir: Path to the repository directory to remove\n\n Returns:\n bool: True if cleanup successful, False otherwise\n \"\"\"\n return cleanup_repository_safe(repo_dir)", - "start_line": 221, - "end_line": 231, - "has_docstring": true, - "docstring": "Remove the cloned repository directory (wrapper for backward compatibility).\n\nArgs:\n repo_dir: Path to the repository directory to remove\n\nReturns:\n bool: True if cleanup successful, False otherwise", - "parameters": [ - "repo_dir" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function cleanup_repository", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/cloning.py::cleanup_repository", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/cloning.py::parse_github_url": { - "id": "codewiki/src/be/dependency_analyzer/analysis/cloning.py::parse_github_url", - "name": "parse_github_url", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/cloning.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/cloning.py", - "depends_on": [], - "source_code": "def parse_github_url(github_url: str) -> dict:\n \"\"\"\n Parse GitHub URL to extract owner and repository name.\n\n Args:\n github_url: GitHub repository URL\n\n Returns:\n dict: Repository information\n \"\"\"\n parts = github_url.rstrip(\"/\").split(\"/\")\n if len(parts) >= 2:\n owner = parts[-2]\n name = parts[-1].replace(\".git\", \"\")\n return {\n \"owner\": owner,\n \"name\": name,\n \"full_name\": f\"{owner}/{name}\",\n \"url\": github_url,\n }\n return {\n \"owner\": \"unknown\",\n \"name\": \"unknown\",\n \"full_name\": \"unknown\",\n \"url\": github_url,\n }", - "start_line": 234, - "end_line": 259, - "has_docstring": true, - "docstring": "Parse GitHub URL to extract owner and repository name.\n\nArgs:\n github_url: GitHub repository URL\n\nReturns:\n dict: Repository information", - "parameters": [ - "github_url" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function parse_github_url", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/cloning.py::parse_github_url", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter": { - "id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter", - "name": "GitIgnoreFilter", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "depends_on": [], - "source_code": "class GitIgnoreFilter:\n \"\"\"Evaluate Git ignore rules once per repository analysis.\n\n Git repositories use ``git ls-files`` so nested ignore files, repository\n excludes, global excludes, and tracked-file semantics exactly match Git.\n Plain directories fall back to pathspec-backed ``.gitignore`` evaluation.\n \"\"\"\n\n def __init__(self, repo_dir: Path) -> None:\n self.repo_dir = repo_dir.resolve()\n self._ignored_files: set[str] = set()\n self._ignored_dirs: set[str] = set()\n self._ignore_all_untracked = False\n self._fallback_specs: list[tuple[str, GitIgnoreSpec]] = []\n self._using_git = self._load_git_ignored_paths()\n if not self._using_git:\n self._load_fallback_specs()\n\n def _load_git_ignored_paths(self) -> bool:\n git_path = shutil.which(\"git\")\n if not git_path:\n logger.debug(\"Git is unavailable; falling back to direct .gitignore parsing\")\n return False\n\n try:\n root_result = subprocess.run(\n [git_path, \"-C\", str(self.repo_dir), \"rev-parse\", \"--show-toplevel\"],\n capture_output=True,\n text=True,\n timeout=10,\n )\n if root_result.returncode != 0:\n logger.debug(\n \"%s is not in a Git worktree; using direct .gitignore parsing\",\n self.repo_dir,\n )\n return False\n worktree_root = Path(root_result.stdout.strip()).resolve()\n scope = self.repo_dir.relative_to(worktree_root).as_posix()\n scope = scope if scope != \".\" else \".\"\n\n ignored_result = subprocess.run(\n [\n git_path,\n \"-C\",\n str(worktree_root),\n \"ls-files\",\n \"--others\",\n \"--ignored\",\n \"--exclude-standard\",\n \"--directory\",\n \"-z\",\n \"--\",\n scope,\n ],\n check=True,\n capture_output=True,\n timeout=30,\n )\n except (OSError, ValueError, subprocess.SubprocessError) as exc:\n logger.warning(\n \"Could not query Git ignore rules for %s; falling back to direct parsing: %s\",\n self.repo_dir,\n exc,\n )\n return False\n\n scope_prefix = \"\" if scope == \".\" else f\"{scope.rstrip('/')}/\"\n for raw_path in ignored_result.stdout.split(b\"\\0\"):\n if not raw_path:\n continue\n repo_relative = raw_path.decode(\"utf-8\", errors=\"surrogateescape\").replace(\"\\\\\", \"/\")\n if scope_prefix:\n if not repo_relative.startswith(scope_prefix):\n continue\n relative = repo_relative[len(scope_prefix) :]\n else:\n relative = repo_relative\n\n if not relative and repo_relative.endswith(\"/\"):\n self._ignore_all_untracked = True\n elif relative.endswith(\"/\"):\n self._ignored_dirs.add(relative.rstrip(\"/\"))\n else:\n self._ignored_files.add(relative)\n\n return True\n\n def _load_fallback_specs(self) -> None:\n try:\n candidates = sorted(\n (\n path\n for path in self.repo_dir.rglob(\".gitignore\")\n if path.is_file() and not path.is_symlink()\n ),\n key=lambda path: (len(path.relative_to(self.repo_dir).parts), path.as_posix()),\n )\n except OSError as exc:\n logger.warning(\"Could not discover .gitignore files under %s: %s\", self.repo_dir, exc)\n return\n\n for gitignore_path in candidates:\n try:\n lines = gitignore_path.read_text(encoding=\"utf-8\").splitlines()\n spec = GitIgnoreSpec.from_lines(lines)\n base = gitignore_path.parent.relative_to(self.repo_dir).as_posix()\n self._fallback_specs.append((\"\" if base == \".\" else base, spec))\n except (OSError, UnicodeError, ValueError) as exc:\n logger.warning(\"Skipping unreadable .gitignore at %s: %s\", gitignore_path, exc)\n\n def is_ignored(self, relative_path: str, is_dir: bool) -> bool:\n \"\"\"Return whether a repository-relative path should be ignored.\"\"\"\n normalized = relative_path.replace(\"\\\\\", \"/\")\n if normalized.startswith(\"./\"):\n normalized = normalized[2:]\n if normalized in (\"\", \".\"):\n return False\n\n if self._using_git:\n if self._ignore_all_untracked:\n return True\n if normalized in self._ignored_files or normalized in self._ignored_dirs:\n return True\n return any(\n normalized.startswith(f\"{ignored_dir}/\") for ignored_dir in self._ignored_dirs\n )\n\n ignored = False\n for base, spec in self._fallback_specs:\n if base:\n if normalized == base:\n local_path = \"\"\n elif normalized.startswith(f\"{base}/\"):\n local_path = normalized[len(base) + 1 :]\n else:\n continue\n else:\n local_path = normalized\n\n if not local_path:\n continue\n candidate = f\"{local_path}/\" if is_dir else local_path\n result = spec.check_file(candidate)\n if result.include is not None:\n ignored = bool(result.include)\n\n return ignored", - "start_line": 26, - "end_line": 173, - "has_docstring": true, - "docstring": "Evaluate Git ignore rules once per repository analysis.\n\nGit repositories use ``git ls-files`` so nested ignore files, repository\nexcludes, global excludes, and tracked-file semantics exactly match Git.\nPlain directories fall back to pathspec-backed ``.gitignore`` evaluation.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class GitIgnoreFilter", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter.__init__": { - "id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter.__init__", - "name": "GitIgnoreFilter.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter._load_git_ignored_paths", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter._load_fallback_specs" - ], - "source_code": " def __init__(self, repo_dir: Path) -> None:\n self.repo_dir = repo_dir.resolve()\n self._ignored_files: set[str] = set()\n self._ignored_dirs: set[str] = set()\n self._ignore_all_untracked = False\n self._fallback_specs: list[tuple[str, GitIgnoreSpec]] = []\n self._using_git = self._load_git_ignored_paths()\n if not self._using_git:\n self._load_fallback_specs()", - "start_line": 34, - "end_line": 42, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "repo_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "GitIgnoreFilter", - "display_name": "method GitIgnoreFilter.__init__", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter._load_git_ignored_paths": { - "id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter._load_git_ignored_paths", - "name": "GitIgnoreFilter._load_git_ignored_paths", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.run" - ], - "source_code": " def _load_git_ignored_paths(self) -> bool:\n git_path = shutil.which(\"git\")\n if not git_path:\n logger.debug(\"Git is unavailable; falling back to direct .gitignore parsing\")\n return False\n\n try:\n root_result = subprocess.run(\n [git_path, \"-C\", str(self.repo_dir), \"rev-parse\", \"--show-toplevel\"],\n capture_output=True,\n text=True,\n timeout=10,\n )\n if root_result.returncode != 0:\n logger.debug(\n \"%s is not in a Git worktree; using direct .gitignore parsing\",\n self.repo_dir,\n )\n return False\n worktree_root = Path(root_result.stdout.strip()).resolve()\n scope = self.repo_dir.relative_to(worktree_root).as_posix()\n scope = scope if scope != \".\" else \".\"\n\n ignored_result = subprocess.run(\n [\n git_path,\n \"-C\",\n str(worktree_root),\n \"ls-files\",\n \"--others\",\n \"--ignored\",\n \"--exclude-standard\",\n \"--directory\",\n \"-z\",\n \"--\",\n scope,\n ],\n check=True,\n capture_output=True,\n timeout=30,\n )\n except (OSError, ValueError, subprocess.SubprocessError) as exc:\n logger.warning(\n \"Could not query Git ignore rules for %s; falling back to direct parsing: %s\",\n self.repo_dir,\n exc,\n )\n return False\n\n scope_prefix = \"\" if scope == \".\" else f\"{scope.rstrip('/')}/\"\n for raw_path in ignored_result.stdout.split(b\"\\0\"):\n if not raw_path:\n continue\n repo_relative = raw_path.decode(\"utf-8\", errors=\"surrogateescape\").replace(\"\\\\\", \"/\")\n if scope_prefix:\n if not repo_relative.startswith(scope_prefix):\n continue\n relative = repo_relative[len(scope_prefix) :]\n else:\n relative = repo_relative\n\n if not relative and repo_relative.endswith(\"/\"):\n self._ignore_all_untracked = True\n elif relative.endswith(\"/\"):\n self._ignored_dirs.add(relative.rstrip(\"/\"))\n else:\n self._ignored_files.add(relative)\n\n return True", - "start_line": 44, - "end_line": 112, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "GitIgnoreFilter", - "display_name": "method GitIgnoreFilter._load_git_ignored_paths", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter._load_git_ignored_paths", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter._load_fallback_specs": { - "id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter._load_fallback_specs", - "name": "GitIgnoreFilter._load_fallback_specs", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "depends_on": [], - "source_code": " def _load_fallback_specs(self) -> None:\n try:\n candidates = sorted(\n (\n path\n for path in self.repo_dir.rglob(\".gitignore\")\n if path.is_file() and not path.is_symlink()\n ),\n key=lambda path: (len(path.relative_to(self.repo_dir).parts), path.as_posix()),\n )\n except OSError as exc:\n logger.warning(\"Could not discover .gitignore files under %s: %s\", self.repo_dir, exc)\n return\n\n for gitignore_path in candidates:\n try:\n lines = gitignore_path.read_text(encoding=\"utf-8\").splitlines()\n spec = GitIgnoreSpec.from_lines(lines)\n base = gitignore_path.parent.relative_to(self.repo_dir).as_posix()\n self._fallback_specs.append((\"\" if base == \".\" else base, spec))\n except (OSError, UnicodeError, ValueError) as exc:\n logger.warning(\"Skipping unreadable .gitignore at %s: %s\", gitignore_path, exc)", - "start_line": 114, - "end_line": 135, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "GitIgnoreFilter", - "display_name": "method GitIgnoreFilter._load_fallback_specs", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter._load_fallback_specs", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter.is_ignored": { - "id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter.is_ignored", - "name": "GitIgnoreFilter.is_ignored", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "depends_on": [], - "source_code": " def is_ignored(self, relative_path: str, is_dir: bool) -> bool:\n \"\"\"Return whether a repository-relative path should be ignored.\"\"\"\n normalized = relative_path.replace(\"\\\\\", \"/\")\n if normalized.startswith(\"./\"):\n normalized = normalized[2:]\n if normalized in (\"\", \".\"):\n return False\n\n if self._using_git:\n if self._ignore_all_untracked:\n return True\n if normalized in self._ignored_files or normalized in self._ignored_dirs:\n return True\n return any(\n normalized.startswith(f\"{ignored_dir}/\") for ignored_dir in self._ignored_dirs\n )\n\n ignored = False\n for base, spec in self._fallback_specs:\n if base:\n if normalized == base:\n local_path = \"\"\n elif normalized.startswith(f\"{base}/\"):\n local_path = normalized[len(base) + 1 :]\n else:\n continue\n else:\n local_path = normalized\n\n if not local_path:\n continue\n candidate = f\"{local_path}/\" if is_dir else local_path\n result = spec.check_file(candidate)\n if result.include is not None:\n ignored = bool(result.include)\n\n return ignored", - "start_line": 137, - "end_line": 173, - "has_docstring": true, - "docstring": "Return whether a repository-relative path should be ignored.", - "parameters": [ - "self", - "relative_path", - "is_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "GitIgnoreFilter", - "display_name": "method GitIgnoreFilter.is_ignored", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter.is_ignored", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer": { - "id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer", - "name": "RepoAnalyzer", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "depends_on": [], - "source_code": "class RepoAnalyzer:\n def __init__(\n self,\n include_patterns: Optional[List[str]] = None,\n exclude_patterns: Optional[List[str]] = None,\n use_gitignore: bool = True,\n ) -> None:\n # Include patterns: if specified, use ONLY those patterns (replaces defaults)\n self.include_patterns = (\n include_patterns if include_patterns is not None else DEFAULT_INCLUDE_PATTERNS\n )\n # Exclude patterns: if specified, MERGE with default ignore patterns\n self.exclude_patterns = (\n list(DEFAULT_IGNORE_PATTERNS) + exclude_patterns\n if exclude_patterns is not None\n else list(DEFAULT_IGNORE_PATTERNS)\n )\n self.use_gitignore = use_gitignore\n self._gitignore_filter: Optional[GitIgnoreFilter] = None\n\n def analyze_repository_structure(self, repo_dir: str) -> Dict:\n self._gitignore_filter = GitIgnoreFilter(Path(repo_dir)) if self.use_gitignore else None\n file_tree = self._build_file_tree(repo_dir)\n return {\n \"file_tree\": file_tree,\n \"summary\": {\n \"total_files\": self._count_files(file_tree),\n \"total_size_kb\": self._calculate_size(file_tree),\n },\n }\n\n def _build_file_tree(self, repo_dir: str) -> Dict:\n def build_tree(path: Path, base_path: Path) -> Optional[Dict]:\n relative_path = path.relative_to(base_path)\n relative_path_str = str(relative_path)\n\n # 🚫 Reject symlinks\n if path.is_symlink():\n return None\n\n # 🚫 Reject escaped paths (e.g., symlinks pointing outside)\n try:\n if not path.resolve().is_relative_to(base_path.resolve()):\n return None\n except AttributeError:\n if not str(path.resolve()).startswith(str(base_path.resolve())):\n return None\n\n if self._should_exclude_path(relative_path_str, path.name, path.is_dir()):\n return None\n\n if path.is_file():\n if not self._should_include_file(relative_path_str, path.name):\n return None\n\n size = path.stat().st_size\n return {\n \"type\": \"file\",\n \"name\": path.name,\n \"path\": relative_path_str,\n \"extension\": path.suffix,\n \"_size_bytes\": size,\n }\n\n elif path.is_dir():\n children = []\n try:\n for child in sorted(path.iterdir()):\n child_tree = build_tree(child, base_path)\n if child_tree is not None:\n children.append(child_tree)\n except PermissionError:\n pass\n\n if children or str(relative_path) == \".\":\n return {\n \"type\": \"directory\",\n \"name\": path.name,\n \"path\": relative_path_str,\n \"children\": children,\n }\n return None\n\n # Other types (sockets, devices, etc.)\n return None\n\n return build_tree(Path(repo_dir), Path(repo_dir))\n\n def _should_exclude_path(self, path: str, filename: str, is_dir: bool = False) -> bool:\n for pattern in self.exclude_patterns:\n if fnmatch.fnmatch(path, pattern) or fnmatch.fnmatch(filename, pattern):\n return True\n if pattern.endswith(\"/\") and path.startswith(pattern.rstrip(\"/\")):\n return True\n if path.startswith(pattern + \"/\") or path == pattern:\n return True\n if pattern in path.split(\"/\"):\n return True\n if self._gitignore_filter and self._gitignore_filter.is_ignored(path, is_dir):\n return True\n return False\n\n def _should_include_file(self, path: str, filename: str) -> bool:\n if not self.include_patterns:\n return True\n for pattern in self.include_patterns:\n if fnmatch.fnmatch(path, pattern) or fnmatch.fnmatch(filename, pattern):\n return True\n return False\n\n def _count_files(self, tree: Dict) -> int:\n if tree[\"type\"] == \"file\":\n return 1\n return sum(self._count_files(child) for child in tree.get(\"children\", []))\n\n def _calculate_size(self, tree: Dict) -> float:\n if tree[\"type\"] == \"file\":\n return tree.get(\"_size_bytes\", 0) / 1024\n return sum(self._calculate_size(child) for child in tree.get(\"children\", []))", - "start_line": 176, - "end_line": 294, - "has_docstring": false, - "docstring": "", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class RepoAnalyzer", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer.__init__": { - "id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer.__init__", - "name": "RepoAnalyzer.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "depends_on": [], - "source_code": " def __init__(\n self,\n include_patterns: Optional[List[str]] = None,\n exclude_patterns: Optional[List[str]] = None,\n use_gitignore: bool = True,\n ) -> None:\n # Include patterns: if specified, use ONLY those patterns (replaces defaults)\n self.include_patterns = (\n include_patterns if include_patterns is not None else DEFAULT_INCLUDE_PATTERNS\n )\n # Exclude patterns: if specified, MERGE with default ignore patterns\n self.exclude_patterns = (\n list(DEFAULT_IGNORE_PATTERNS) + exclude_patterns\n if exclude_patterns is not None\n else list(DEFAULT_IGNORE_PATTERNS)\n )\n self.use_gitignore = use_gitignore\n self._gitignore_filter: Optional[GitIgnoreFilter] = None", - "start_line": 177, - "end_line": 194, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "include_patterns", - "exclude_patterns", - "use_gitignore" - ], - "node_type": "method", - "base_classes": null, - "class_name": "RepoAnalyzer", - "display_name": "method RepoAnalyzer.__init__", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer.analyze_repository_structure": { - "id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer.analyze_repository_structure", - "name": "RepoAnalyzer.analyze_repository_structure", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._build_file_tree", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._count_files", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._calculate_size" - ], - "source_code": " def analyze_repository_structure(self, repo_dir: str) -> Dict:\n self._gitignore_filter = GitIgnoreFilter(Path(repo_dir)) if self.use_gitignore else None\n file_tree = self._build_file_tree(repo_dir)\n return {\n \"file_tree\": file_tree,\n \"summary\": {\n \"total_files\": self._count_files(file_tree),\n \"total_size_kb\": self._calculate_size(file_tree),\n },\n }", - "start_line": 196, - "end_line": 205, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "repo_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "RepoAnalyzer", - "display_name": "method RepoAnalyzer.analyze_repository_structure", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer.analyze_repository_structure", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._build_file_tree": { - "id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._build_file_tree", - "name": "RepoAnalyzer._build_file_tree", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._should_exclude_path", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._should_include_file" - ], - "source_code": " def _build_file_tree(self, repo_dir: str) -> Dict:\n def build_tree(path: Path, base_path: Path) -> Optional[Dict]:\n relative_path = path.relative_to(base_path)\n relative_path_str = str(relative_path)\n\n # 🚫 Reject symlinks\n if path.is_symlink():\n return None\n\n # 🚫 Reject escaped paths (e.g., symlinks pointing outside)\n try:\n if not path.resolve().is_relative_to(base_path.resolve()):\n return None\n except AttributeError:\n if not str(path.resolve()).startswith(str(base_path.resolve())):\n return None\n\n if self._should_exclude_path(relative_path_str, path.name, path.is_dir()):\n return None\n\n if path.is_file():\n if not self._should_include_file(relative_path_str, path.name):\n return None\n\n size = path.stat().st_size\n return {\n \"type\": \"file\",\n \"name\": path.name,\n \"path\": relative_path_str,\n \"extension\": path.suffix,\n \"_size_bytes\": size,\n }\n\n elif path.is_dir():\n children = []\n try:\n for child in sorted(path.iterdir()):\n child_tree = build_tree(child, base_path)\n if child_tree is not None:\n children.append(child_tree)\n except PermissionError:\n pass\n\n if children or str(relative_path) == \".\":\n return {\n \"type\": \"directory\",\n \"name\": path.name,\n \"path\": relative_path_str,\n \"children\": children,\n }\n return None\n\n # Other types (sockets, devices, etc.)\n return None\n\n return build_tree(Path(repo_dir), Path(repo_dir))", - "start_line": 207, - "end_line": 262, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "repo_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "RepoAnalyzer", - "display_name": "method RepoAnalyzer._build_file_tree", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._build_file_tree", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._should_exclude_path": { - "id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._should_exclude_path", - "name": "RepoAnalyzer._should_exclude_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::GitIgnoreFilter.is_ignored" - ], - "source_code": " def _should_exclude_path(self, path: str, filename: str, is_dir: bool = False) -> bool:\n for pattern in self.exclude_patterns:\n if fnmatch.fnmatch(path, pattern) or fnmatch.fnmatch(filename, pattern):\n return True\n if pattern.endswith(\"/\") and path.startswith(pattern.rstrip(\"/\")):\n return True\n if path.startswith(pattern + \"/\") or path == pattern:\n return True\n if pattern in path.split(\"/\"):\n return True\n if self._gitignore_filter and self._gitignore_filter.is_ignored(path, is_dir):\n return True\n return False", - "start_line": 264, - "end_line": 276, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "path", - "filename", - "is_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "RepoAnalyzer", - "display_name": "method RepoAnalyzer._should_exclude_path", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._should_exclude_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._should_include_file": { - "id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._should_include_file", - "name": "RepoAnalyzer._should_include_file", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "depends_on": [], - "source_code": " def _should_include_file(self, path: str, filename: str) -> bool:\n if not self.include_patterns:\n return True\n for pattern in self.include_patterns:\n if fnmatch.fnmatch(path, pattern) or fnmatch.fnmatch(filename, pattern):\n return True\n return False", - "start_line": 278, - "end_line": 284, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "path", - "filename" - ], - "node_type": "method", - "base_classes": null, - "class_name": "RepoAnalyzer", - "display_name": "method RepoAnalyzer._should_include_file", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._should_include_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._count_files": { - "id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._count_files", - "name": "RepoAnalyzer._count_files", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._count_files" - ], - "source_code": " def _count_files(self, tree: Dict) -> int:\n if tree[\"type\"] == \"file\":\n return 1\n return sum(self._count_files(child) for child in tree.get(\"children\", []))", - "start_line": 286, - "end_line": 289, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "tree" - ], - "node_type": "method", - "base_classes": null, - "class_name": "RepoAnalyzer", - "display_name": "method RepoAnalyzer._count_files", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._count_files", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._calculate_size": { - "id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._calculate_size", - "name": "RepoAnalyzer._calculate_size", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._calculate_size" - ], - "source_code": " def _calculate_size(self, tree: Dict) -> float:\n if tree[\"type\"] == \"file\":\n return tree.get(\"_size_bytes\", 0) / 1024\n return sum(self._calculate_size(child) for child in tree.get(\"children\", []))", - "start_line": 291, - "end_line": 294, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "tree" - ], - "node_type": "method", - "base_classes": null, - "class_name": "RepoAnalyzer", - "display_name": "method RepoAnalyzer._calculate_size", - "component_id": "codewiki/src/be/dependency_analyzer/analysis/repo_analyzer.py::RepoAnalyzer._calculate_size", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer", - "name": "TreeSitterCAnalyzer", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/c.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/c.py", - "depends_on": [], - "source_code": "class TreeSitterCAnalyzer:\n\tdef __init__(self, file_path: str, content: str, repo_path: str = None):\n\t\tself.file_path = Path(file_path)\n\t\tself.content = content\n\t\tself.repo_path = repo_path or \"\"\n\t\tself.nodes: List[Node] = []\n\t\tself.call_relationships: List[CallRelationship] = []\n\t\tself._analyze()\n\t\n\tdef _get_module_path(self) -> str:\n\t\tif self.repo_path:\n\t\t\ttry:\n\t\t\t\trel_path = os.path.relpath(str(self.file_path), self.repo_path)\n\t\t\texcept ValueError:\n\t\t\t\trel_path = str(self.file_path)\n\t\telse:\n\t\t\trel_path = str(self.file_path)\n\t\t\n\t\tfor ext in ['.c', '.h']:\n\t\t\tif rel_path.endswith(ext):\n\t\t\t\trel_path = rel_path[:-len(ext)]\n\t\t\t\tbreak\n\t\treturn rel_path.replace('/', '.').replace('\\\\', '.')\n\t\n\tdef _get_relative_path(self) -> str:\n\t\tif self.repo_path:\n\t\t\ttry:\n\t\t\t\treturn os.path.relpath(str(self.file_path), self.repo_path)\n\t\t\texcept ValueError:\n\t\t\t\treturn str(self.file_path)\n\t\telse:\n\t\t\treturn str(self.file_path)\n\t\n\tdef _get_component_id(self, name: str) -> str:\n\t\trel_path = self._get_relative_path()\n\t\treturn f\"{rel_path}::{name}\"\n\n\tdef _analyze(self):\n\t\tlanguage_capsule = tree_sitter_c.language()\n\t\tc_language = Language(language_capsule)\n\t\tparser = Parser(c_language)\n\t\ttree = parser.parse(bytes(self.content, \"utf8\"))\n\t\troot = tree.root_node\n\t\tlines = self.content.splitlines()\n\t\t\n\t\ttop_level_nodes = {}\n\t\t\n\t\t# collect all top-level nodes using recursive traversal\n\t\tself._extract_nodes(root, top_level_nodes, lines)\n\t\t\n\t\t# extract relationships between top-level nodes\n\t\tself._extract_relationships(root, top_level_nodes)\n\t\n\tdef _extract_nodes(self, node, top_level_nodes, lines):\n\t\t\"\"\"Recursively extract top-level nodes (functions, structs, and global variables).\"\"\"\n\t\tnode_type = None\n\t\tnode_name = None\n\t\t\n\t\tif node.type == \"function_definition\":\n\t\t\tnode_type = \"function\"\n\t\t\t# look for function_declarator\n\t\t\tdeclarator = next((c for c in node.children if c.type == \"function_declarator\"), None)\n\t\t\tif declarator:\n\t\t\t\tidentifier = next((c for c in declarator.children if c.type == \"identifier\"), None)\n\t\t\t\tif identifier:\n\t\t\t\t\tnode_name = identifier.text.decode()\n\t\telif node.type == \"struct_specifier\":\n\t\t\t# Extract struct definitions: struct Name { ... }\n\t\t\tnode_type = \"struct\"\n\t\t\t# Find type_identifier that represents the struct name\n\t\t\tfor child in node.children:\n\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\tnode_name = child.text.decode()\n\t\t\t\t\tbreak\n\t\telif node.type == \"type_definition\":\n\t\t\t# Handle typedef struct definitions: typedef struct { ... } Name;\n\t\t\t# Check if this typedef contains a struct\n\t\t\tstruct_spec = next((c for c in node.children if c.type == \"struct_specifier\"), None)\n\t\t\tif struct_spec:\n\t\t\t\tnode_type = \"struct\"\n\t\t\t\t# The typedef name is the type_identifier at the end\n\t\t\t\ttype_declarator = next((c for c in node.children if c.type == \"type_identifier\"), None)\n\t\t\t\tif type_declarator:\n\t\t\t\t\tnode_name = type_declarator.text.decode()\n\t\telif node.type == \"declaration\":\n\t\t\tif self._is_global_variable(node):\n\t\t\t\tnode_type = \"variable\"\n\t\t\t\tfor child in node.children:\n\t\t\t\t\tif child.type == \"init_declarator\":\n\t\t\t\t\t\tidentifier = next((c for c in child.children if c.type == \"identifier\"), None)\n\t\t\t\t\t\tif identifier:\n\t\t\t\t\t\t\tnode_name = identifier.text.decode()\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tpointer_declarator = next((c for c in child.children if c.type == \"pointer_declarator\"), None)\n\t\t\t\t\t\tif pointer_declarator:\n\t\t\t\t\t\t\tidentifier = next((c for c in pointer_declarator.children if c.type == \"identifier\"), None)\n\t\t\t\t\t\t\tif identifier:\n\t\t\t\t\t\t\t\tnode_name = identifier.text.decode()\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\telif child.type == \"identifier\":\n\t\t\t\t\t\tnode_name = child.text.decode()\n\t\t\t\t\t\tbreak\n\t\t\n\t\tif node_type and node_name:\n\t\t\tcomponent_id = self._get_component_id(node_name)\n\t\t\trelative_path = self._get_relative_path()\n\t\t\tnode_obj = Node(\n\t\t\t\tid=component_id,\n\t\t\t\tname=node_name,\n\t\t\t\tcomponent_type=node_type,\n\t\t\t\tfile_path=str(self.file_path),\n\t\t\t\trelative_path=relative_path,\n\t\t\t\tsource_code=\"\\n\".join(lines[node.start_point[0]:node.end_point[0]+1]),\n\t\t\t\tstart_line=node.start_point[0]+1,\n\t\t\t\tend_line=node.end_point[0]+1,\n\t\t\t\thas_docstring=False,\n\t\t\t\tdocstring=\"\",\n\t\t\t\tparameters=None,\n\t\t\t\tnode_type=node_type,\n\t\t\t\tbase_classes=None,\n\t\t\t\tclass_name=None,\n\t\t\t\tdisplay_name=f\"{node_type} {node_name}\",\n\t\t\t\tcomponent_id=component_id,\n\t\t\t\tlanguage=\"c\",\n\t\t\t\tqualified_name=node_name\n\t\t\t)\n\n\t\t\tif node_type in [\"function\", \"struct\"]:\n\t\t\t\tself.nodes.append(node_obj)\n\t\t\ttop_level_nodes[node_name] = node_obj\n\t\t\n\t\tfor child in node.children:\n\t\t\tself._extract_nodes(child, top_level_nodes, lines)\n\t\n\tdef _is_global_variable(self, node) -> bool:\n\t\tparent = node.parent\n\t\twhile parent:\n\t\t\tif parent.type == \"function_definition\":\n\t\t\t\treturn False\n\t\t\tparent = parent.parent\n\t\treturn True\n\t\n\tdef _extract_relationships(self, node, top_level_nodes):\n\t\t\"\"\"Extract various types of relationships between top-level nodes.\"\"\"\n\t\t\n\t\t# 1. function calls other functions\n\t\tif node.type == \"call_expression\":\n\t\t\tcontaining_function = self._find_containing_function(node, top_level_nodes)\n\t\t\tif containing_function:\n\t\t\t\tcontaining_function_id = self._get_component_id(containing_function)\n\t\t\t\t\n\t\t\t\t# Get called function name. External/libc filtering happens in\n\t\t\t\t# CallGraphAnalyzer after cross-file resolution, so a project\n\t\t\t\t# function that shadows a libc name still gets its edges.\n\t\t\t\tfunction_node = next((c for c in node.children if c.type == \"identifier\"), None)\n\t\t\t\tif function_node:\n\t\t\t\t\tcalled_function = function_node.text.decode()\n\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\tcaller=containing_function_id,\n\t\t\t\t\t\tcallee=called_function, # Use simple name for cross-file resolution\n\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\tis_resolved=False # Let CallGraphAnalyzer resolve\n\t\t\t\t\t))\n\t\t\n\t\t# 2. function uses global variables\n\t\tif node.type == \"identifier\":\n\t\t\tcontaining_function = self._find_containing_function(node, top_level_nodes)\n\t\t\tif containing_function:\n\t\t\t\tvar_name = node.text.decode()\n\t\t\t\t# Check if this identifier refers to a global variable\n\t\t\t\tif var_name in top_level_nodes and top_level_nodes[var_name].component_type == \"variable\":\n\t\t\t\t\tcontaining_function_id = self._get_component_id(containing_function)\n\t\t\t\t\tvar_component_id = self._get_component_id(var_name)\n\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\tcaller=containing_function_id,\n\t\t\t\t\t\tcallee=var_component_id,\n\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\tis_resolved=True # Local file relationship\n\t\t\t\t\t))\n\t\t\n\t\t# Recursively process children\n\t\tfor child in node.children:\n\t\t\tself._extract_relationships(child, top_level_nodes)\n\t\n\tdef _find_containing_function(self, node, top_level_nodes):\n\t\t\"\"\"Find the function that contains this node.\"\"\"\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type == \"function_definition\":\n\t\t\t\t# Get function name\n\t\t\t\tdeclarator = next((c for c in current.children if c.type == \"function_declarator\"), None)\n\t\t\t\tif declarator:\n\t\t\t\t\tidentifier = next((c for c in declarator.children if c.type == \"identifier\"), None)\n\t\t\t\t\tif identifier:\n\t\t\t\t\t\tfunc_name = identifier.text.decode()\n\t\t\t\t\t\tif func_name in top_level_nodes:\n\t\t\t\t\t\t\treturn func_name\n\t\t\tcurrent = current.parent\n\t\treturn None", - "start_line": 13, - "end_line": 211, - "has_docstring": false, - "docstring": "", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class TreeSitterCAnalyzer", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer.__init__": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer.__init__", - "name": "TreeSitterCAnalyzer.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/c.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/c.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._analyze" - ], - "source_code": "\tdef __init__(self, file_path: str, content: str, repo_path: str = None):\n\t\tself.file_path = Path(file_path)\n\t\tself.content = content\n\t\tself.repo_path = repo_path or \"\"\n\t\tself.nodes: List[Node] = []\n\t\tself.call_relationships: List[CallRelationship] = []\n\t\tself._analyze()", - "start_line": 14, - "end_line": 20, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "file_path", - "content", - "repo_path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCAnalyzer", - "display_name": "method TreeSitterCAnalyzer.__init__", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._get_module_path": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._get_module_path", - "name": "TreeSitterCAnalyzer._get_module_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/c.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/c.py", - "depends_on": [], - "source_code": "\tdef _get_module_path(self) -> str:\n\t\tif self.repo_path:\n\t\t\ttry:\n\t\t\t\trel_path = os.path.relpath(str(self.file_path), self.repo_path)\n\t\t\texcept ValueError:\n\t\t\t\trel_path = str(self.file_path)\n\t\telse:\n\t\t\trel_path = str(self.file_path)\n\t\t\n\t\tfor ext in ['.c', '.h']:\n\t\t\tif rel_path.endswith(ext):\n\t\t\t\trel_path = rel_path[:-len(ext)]\n\t\t\t\tbreak\n\t\treturn rel_path.replace('/', '.').replace('\\\\', '.')", - "start_line": 22, - "end_line": 35, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCAnalyzer", - "display_name": "method TreeSitterCAnalyzer._get_module_path", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._get_module_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._get_relative_path": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._get_relative_path", - "name": "TreeSitterCAnalyzer._get_relative_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/c.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/c.py", - "depends_on": [], - "source_code": "\tdef _get_relative_path(self) -> str:\n\t\tif self.repo_path:\n\t\t\ttry:\n\t\t\t\treturn os.path.relpath(str(self.file_path), self.repo_path)\n\t\t\texcept ValueError:\n\t\t\t\treturn str(self.file_path)\n\t\telse:\n\t\t\treturn str(self.file_path)", - "start_line": 37, - "end_line": 44, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCAnalyzer", - "display_name": "method TreeSitterCAnalyzer._get_relative_path", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._get_relative_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._get_component_id": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._get_component_id", - "name": "TreeSitterCAnalyzer._get_component_id", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/c.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/c.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._get_relative_path" - ], - "source_code": "\tdef _get_component_id(self, name: str) -> str:\n\t\trel_path = self._get_relative_path()\n\t\treturn f\"{rel_path}::{name}\"", - "start_line": 46, - "end_line": 48, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCAnalyzer", - "display_name": "method TreeSitterCAnalyzer._get_component_id", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._get_component_id", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._analyze": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._analyze", - "name": "TreeSitterCAnalyzer._analyze", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/c.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/c.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._extract_nodes", - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._extract_relationships" - ], - "source_code": "\tdef _analyze(self):\n\t\tlanguage_capsule = tree_sitter_c.language()\n\t\tc_language = Language(language_capsule)\n\t\tparser = Parser(c_language)\n\t\ttree = parser.parse(bytes(self.content, \"utf8\"))\n\t\troot = tree.root_node\n\t\tlines = self.content.splitlines()\n\t\t\n\t\ttop_level_nodes = {}\n\t\t\n\t\t# collect all top-level nodes using recursive traversal\n\t\tself._extract_nodes(root, top_level_nodes, lines)\n\t\t\n\t\t# extract relationships between top-level nodes\n\t\tself._extract_relationships(root, top_level_nodes)", - "start_line": 50, - "end_line": 64, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCAnalyzer", - "display_name": "method TreeSitterCAnalyzer._analyze", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._analyze", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._extract_nodes": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._extract_nodes", - "name": "TreeSitterCAnalyzer._extract_nodes", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/c.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/c.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._is_global_variable", - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._extract_nodes", - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._get_relative_path", - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._get_component_id" - ], - "source_code": "\tdef _extract_nodes(self, node, top_level_nodes, lines):\n\t\t\"\"\"Recursively extract top-level nodes (functions, structs, and global variables).\"\"\"\n\t\tnode_type = None\n\t\tnode_name = None\n\t\t\n\t\tif node.type == \"function_definition\":\n\t\t\tnode_type = \"function\"\n\t\t\t# look for function_declarator\n\t\t\tdeclarator = next((c for c in node.children if c.type == \"function_declarator\"), None)\n\t\t\tif declarator:\n\t\t\t\tidentifier = next((c for c in declarator.children if c.type == \"identifier\"), None)\n\t\t\t\tif identifier:\n\t\t\t\t\tnode_name = identifier.text.decode()\n\t\telif node.type == \"struct_specifier\":\n\t\t\t# Extract struct definitions: struct Name { ... }\n\t\t\tnode_type = \"struct\"\n\t\t\t# Find type_identifier that represents the struct name\n\t\t\tfor child in node.children:\n\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\tnode_name = child.text.decode()\n\t\t\t\t\tbreak\n\t\telif node.type == \"type_definition\":\n\t\t\t# Handle typedef struct definitions: typedef struct { ... } Name;\n\t\t\t# Check if this typedef contains a struct\n\t\t\tstruct_spec = next((c for c in node.children if c.type == \"struct_specifier\"), None)\n\t\t\tif struct_spec:\n\t\t\t\tnode_type = \"struct\"\n\t\t\t\t# The typedef name is the type_identifier at the end\n\t\t\t\ttype_declarator = next((c for c in node.children if c.type == \"type_identifier\"), None)\n\t\t\t\tif type_declarator:\n\t\t\t\t\tnode_name = type_declarator.text.decode()\n\t\telif node.type == \"declaration\":\n\t\t\tif self._is_global_variable(node):\n\t\t\t\tnode_type = \"variable\"\n\t\t\t\tfor child in node.children:\n\t\t\t\t\tif child.type == \"init_declarator\":\n\t\t\t\t\t\tidentifier = next((c for c in child.children if c.type == \"identifier\"), None)\n\t\t\t\t\t\tif identifier:\n\t\t\t\t\t\t\tnode_name = identifier.text.decode()\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tpointer_declarator = next((c for c in child.children if c.type == \"pointer_declarator\"), None)\n\t\t\t\t\t\tif pointer_declarator:\n\t\t\t\t\t\t\tidentifier = next((c for c in pointer_declarator.children if c.type == \"identifier\"), None)\n\t\t\t\t\t\t\tif identifier:\n\t\t\t\t\t\t\t\tnode_name = identifier.text.decode()\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\telif child.type == \"identifier\":\n\t\t\t\t\t\tnode_name = child.text.decode()\n\t\t\t\t\t\tbreak\n\t\t\n\t\tif node_type and node_name:\n\t\t\tcomponent_id = self._get_component_id(node_name)\n\t\t\trelative_path = self._get_relative_path()\n\t\t\tnode_obj = Node(\n\t\t\t\tid=component_id,\n\t\t\t\tname=node_name,\n\t\t\t\tcomponent_type=node_type,\n\t\t\t\tfile_path=str(self.file_path),\n\t\t\t\trelative_path=relative_path,\n\t\t\t\tsource_code=\"\\n\".join(lines[node.start_point[0]:node.end_point[0]+1]),\n\t\t\t\tstart_line=node.start_point[0]+1,\n\t\t\t\tend_line=node.end_point[0]+1,\n\t\t\t\thas_docstring=False,\n\t\t\t\tdocstring=\"\",\n\t\t\t\tparameters=None,\n\t\t\t\tnode_type=node_type,\n\t\t\t\tbase_classes=None,\n\t\t\t\tclass_name=None,\n\t\t\t\tdisplay_name=f\"{node_type} {node_name}\",\n\t\t\t\tcomponent_id=component_id,\n\t\t\t\tlanguage=\"c\",\n\t\t\t\tqualified_name=node_name\n\t\t\t)\n\n\t\t\tif node_type in [\"function\", \"struct\"]:\n\t\t\t\tself.nodes.append(node_obj)\n\t\t\ttop_level_nodes[node_name] = node_obj\n\t\t\n\t\tfor child in node.children:\n\t\t\tself._extract_nodes(child, top_level_nodes, lines)", - "start_line": 66, - "end_line": 145, - "has_docstring": true, - "docstring": "Recursively extract top-level nodes (functions, structs, and global variables).", - "parameters": [ - "self", - "node", - "top_level_nodes", - "lines" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCAnalyzer", - "display_name": "method TreeSitterCAnalyzer._extract_nodes", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._extract_nodes", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._is_global_variable": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._is_global_variable", - "name": "TreeSitterCAnalyzer._is_global_variable", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/c.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/c.py", - "depends_on": [], - "source_code": "\tdef _is_global_variable(self, node) -> bool:\n\t\tparent = node.parent\n\t\twhile parent:\n\t\t\tif parent.type == \"function_definition\":\n\t\t\t\treturn False\n\t\t\tparent = parent.parent\n\t\treturn True", - "start_line": 147, - "end_line": 153, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCAnalyzer", - "display_name": "method TreeSitterCAnalyzer._is_global_variable", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._is_global_variable", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._extract_relationships": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._extract_relationships", - "name": "TreeSitterCAnalyzer._extract_relationships", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/c.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/c.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._find_containing_function", - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._get_component_id", - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._extract_relationships" - ], - "source_code": "\tdef _extract_relationships(self, node, top_level_nodes):\n\t\t\"\"\"Extract various types of relationships between top-level nodes.\"\"\"\n\t\t\n\t\t# 1. function calls other functions\n\t\tif node.type == \"call_expression\":\n\t\t\tcontaining_function = self._find_containing_function(node, top_level_nodes)\n\t\t\tif containing_function:\n\t\t\t\tcontaining_function_id = self._get_component_id(containing_function)\n\t\t\t\t\n\t\t\t\t# Get called function name. External/libc filtering happens in\n\t\t\t\t# CallGraphAnalyzer after cross-file resolution, so a project\n\t\t\t\t# function that shadows a libc name still gets its edges.\n\t\t\t\tfunction_node = next((c for c in node.children if c.type == \"identifier\"), None)\n\t\t\t\tif function_node:\n\t\t\t\t\tcalled_function = function_node.text.decode()\n\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\tcaller=containing_function_id,\n\t\t\t\t\t\tcallee=called_function, # Use simple name for cross-file resolution\n\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\tis_resolved=False # Let CallGraphAnalyzer resolve\n\t\t\t\t\t))\n\t\t\n\t\t# 2. function uses global variables\n\t\tif node.type == \"identifier\":\n\t\t\tcontaining_function = self._find_containing_function(node, top_level_nodes)\n\t\t\tif containing_function:\n\t\t\t\tvar_name = node.text.decode()\n\t\t\t\t# Check if this identifier refers to a global variable\n\t\t\t\tif var_name in top_level_nodes and top_level_nodes[var_name].component_type == \"variable\":\n\t\t\t\t\tcontaining_function_id = self._get_component_id(containing_function)\n\t\t\t\t\tvar_component_id = self._get_component_id(var_name)\n\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\tcaller=containing_function_id,\n\t\t\t\t\t\tcallee=var_component_id,\n\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\tis_resolved=True # Local file relationship\n\t\t\t\t\t))\n\t\t\n\t\t# Recursively process children\n\t\tfor child in node.children:\n\t\t\tself._extract_relationships(child, top_level_nodes)", - "start_line": 155, - "end_line": 195, - "has_docstring": true, - "docstring": "Extract various types of relationships between top-level nodes.", - "parameters": [ - "self", - "node", - "top_level_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCAnalyzer", - "display_name": "method TreeSitterCAnalyzer._extract_relationships", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._extract_relationships", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._find_containing_function": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._find_containing_function", - "name": "TreeSitterCAnalyzer._find_containing_function", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/c.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/c.py", - "depends_on": [], - "source_code": "\tdef _find_containing_function(self, node, top_level_nodes):\n\t\t\"\"\"Find the function that contains this node.\"\"\"\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type == \"function_definition\":\n\t\t\t\t# Get function name\n\t\t\t\tdeclarator = next((c for c in current.children if c.type == \"function_declarator\"), None)\n\t\t\t\tif declarator:\n\t\t\t\t\tidentifier = next((c for c in declarator.children if c.type == \"identifier\"), None)\n\t\t\t\t\tif identifier:\n\t\t\t\t\t\tfunc_name = identifier.text.decode()\n\t\t\t\t\t\tif func_name in top_level_nodes:\n\t\t\t\t\t\t\treturn func_name\n\t\t\tcurrent = current.parent\n\t\treturn None", - "start_line": 197, - "end_line": 211, - "has_docstring": true, - "docstring": "Find the function that contains this node.", - "parameters": [ - "self", - "node", - "top_level_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCAnalyzer", - "display_name": "method TreeSitterCAnalyzer._find_containing_function", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer._find_containing_function", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/c.py::analyze_c_file": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::analyze_c_file", - "name": "analyze_c_file", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/c.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/c.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/c.py::TreeSitterCAnalyzer" - ], - "source_code": "def analyze_c_file(file_path: str, content: str, repo_path: str = None) -> Tuple[List[Node], List[CallRelationship]]:\n\tanalyzer = TreeSitterCAnalyzer(file_path, content, repo_path)\n\treturn analyzer.nodes, analyzer.call_relationships", - "start_line": 213, - "end_line": 215, - "has_docstring": false, - "docstring": "", - "parameters": [ - "file_path", - "content", - "repo_path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function analyze_c_file", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/c.py::analyze_c_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer", - "name": "TreeSitterCppAnalyzer", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [], - "source_code": "class TreeSitterCppAnalyzer:\n\tdef __init__(self, file_path: str, content: str, repo_path: str = None):\n\t\tself.file_path = Path(file_path)\n\t\tself.content = content\n\t\tself.repo_path = repo_path or \"\"\n\t\tself.nodes: List[Node] = []\n\t\tself.call_relationships: List[CallRelationship] = []\n\t\tself._analyze()\n\t\n\tdef _get_module_path(self) -> str:\n\t\tif self.repo_path:\n\t\t\ttry:\n\t\t\t\trel_path = os.path.relpath(str(self.file_path), self.repo_path)\n\t\t\texcept ValueError:\n\t\t\t\trel_path = str(self.file_path)\n\t\telse:\n\t\t\trel_path = str(self.file_path)\n\n\t\tfor ext in ['.cpp', '.cc', '.cxx', '.c++', '.hpp', '.hxx', '.h++', '.h']:\n\t\t\tif rel_path.endswith(ext):\n\t\t\t\trel_path = rel_path[:-len(ext)]\n\t\t\t\tbreak\n\t\treturn rel_path.replace('/', '.').replace('\\\\', '.')\n\t\n\tdef _get_relative_path(self) -> str:\n\t\tif self.repo_path:\n\t\t\ttry:\n\t\t\t\treturn os.path.relpath(str(self.file_path), self.repo_path)\n\t\t\texcept ValueError:\n\t\t\t\treturn str(self.file_path)\n\t\telse:\n\t\t\treturn str(self.file_path)\n\t\n\tdef _get_component_id(self, name: str, parent_class: str = None) -> str:\n\t\trel_path = self._get_relative_path()\n\t\tif parent_class:\n\t\t\treturn f\"{rel_path}::{parent_class}.{name}\"\n\t\treturn f\"{rel_path}::{name}\"\n\n\tdef _analyze(self):\n\t\tlanguage_capsule = tree_sitter_cpp.language()\n\t\tcpp_language = Language(language_capsule)\n\t\tparser = Parser(cpp_language)\n\t\troot = self._parse_with_macro_recovery(parser)\n\t\tlines = self.content.splitlines()\n\t\t\n\t\ttop_level_nodes = {}\n\t\t\n\t\t# collect all top-level nodes using recursive traversal\n\t\tself._extract_nodes(root, top_level_nodes, lines)\n\t\t\n\t\t# extract relationships between top-level nodes\n\t\tself._extract_relationships(root, top_level_nodes)\n\n\tdef _parse_with_macro_recovery(self, parser):\n\t\t\"\"\"Parse the original source; if it has syntax errors, retry with macro\n\t\tnormalization and keep whichever parse has fewer errors.\n\n\t\tNormalization strips ALL_CAPS tokens by naming convention, which is\n\t\twrong for code whose *types* are ALL_CAPS (e.g. Win32 `HANDLE`/`DWORD`).\n\t\tComparing error counts makes the heuristic self-correcting: clean files\n\t\tare never touched, and normalization is only kept when it demonstrably\n\t\trecovers structure.\n\t\t\"\"\"\n\t\ttree = parser.parse(bytes(self.content, \"utf8\"))\n\t\tif not tree.root_node.has_error:\n\t\t\treturn tree.root_node\n\n\t\tnormalized = self._normalize_for_parser(self.content)\n\t\tif normalized == self.content:\n\t\t\treturn tree.root_node\n\n\t\tnormalized_tree = parser.parse(bytes(normalized, \"utf8\"))\n\t\tif self._count_parse_errors(normalized_tree.root_node) < self._count_parse_errors(tree.root_node):\n\t\t\treturn normalized_tree.root_node\n\t\treturn tree.root_node\n\n\tdef _count_parse_errors(self, root) -> int:\n\t\terrors = 0\n\t\tstack = [root]\n\t\twhile stack:\n\t\t\tnode = stack.pop()\n\t\t\tif node.is_error or node.is_missing:\n\t\t\t\terrors += 1\n\t\t\tstack.extend(node.children)\n\t\treturn errors\n\n\tdef _normalize_for_parser(self, content: str) -> str:\n\t\t\"\"\"Strip ALL_CAPS attribute/specifier macros that sit in front of a\n\t\tdeclaration so tree-sitter can recover the underlying signature. This is\n\t\tname-agnostic: it keys off the conventional ALL_CAPS macro spelling, not\n\t\tany specific library's prefix, and only fires in specifier position so\n\t\tidentifiers used in expressions are preserved. Line count is unchanged so\n\t\treported line numbers stay accurate.\n\t\t\"\"\"\n\t\tnormalized_lines = []\n\t\tfor line in content.splitlines():\n\t\t\tupdated = line\n\t\t\tstandalone = _STANDALONE_MACRO_RE.match(updated)\n\t\t\tif standalone and is_macro_name(standalone.group(1)):\n\t\t\t\tnormalized_lines.append(\"\")\n\t\t\t\tcontinue\n\t\t\tfor pattern in (_SPECIFIER_MACRO_CALL_RE, _SPECIFIER_MACRO_RE):\n\t\t\t\tprevious = None\n\t\t\t\twhile previous != updated:\n\t\t\t\t\tprevious = updated\n\t\t\t\t\tupdated = pattern.sub(\n\t\t\t\t\t\tlambda m: (m.group(1) + m.group(3)) if is_macro_name(m.group(2)) else m.group(0),\n\t\t\t\t\t\tupdated,\n\t\t\t\t\t)\n\t\t\tupdated = _KEYWORD_MACRO_RE.sub(\n\t\t\t\tlambda m: (m.group(1) + m.group(2)) if is_macro_name(m.group(3)) else m.group(0),\n\t\t\t\tupdated,\n\t\t\t)\n\t\t\tnormalized_lines.append(updated)\n\t\treturn \"\\n\".join(normalized_lines)\n\t\n\tdef _extract_nodes(self, node, top_level_nodes, lines):\n\t\t\"\"\"Recursively extract top-level nodes (classes, functions, global variables).\"\"\"\n\t\tnode_type = None\n\t\tnode_name = None\n\t\tcontaining_class = None\n\t\t\n\t\tif node.type == \"class_specifier\":\n\t\t\t# \"class\" + type_identifier + { ... }\n\t\t\tnode_type = \"class\"\n\t\t\t# Find type_identifier that represents the class name\n\t\t\tfor child in node.children:\n\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\tnode_name = child.text.decode()\n\t\t\t\t\tbreak\n\t\telif node.type == \"struct_specifier\":\n\t\t\t# \"struct\" + type_identifier + { ... }\n\t\t\tnode_type = \"struct\"\n\t\t\t# Find type_identifier that represents the struct name\n\t\t\tfor child in node.children:\n\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\tnode_name = child.text.decode()\n\t\t\t\t\tbreak\n\t\telif node.type == \"function_definition\":\n\t\t\t# Check if this is inside a class or function\n\t\t\tcontaining_class = self._find_containing_class_for_method(node)\n\t\t\tdeclarator = next((c for c in node.children if c.type == \"function_declarator\"), None)\n\t\t\tqualified_parts = self._get_qualified_declarator_parts(declarator) if declarator else []\n\t\t\tif not containing_class and len(qualified_parts) > 1:\n\t\t\t\tcontaining_class = qualified_parts[-2]\n\t\t\tif containing_class:\n\t\t\t\tnode_type = \"method\"\n\t\t\telse:\n\t\t\t\tnode_type = \"function\"\n\t\t\t\n\t\t\tif declarator:\n\t\t\t\tfor child in declarator.children:\n\t\t\t\t\tif child.type == \"identifier\":\n\t\t\t\t\t\tnode_name = child.text.decode()\n\t\t\t\t\t\tbreak\n\t\t\t\t\telif child.type == \"field_identifier\":\n\t\t\t\t\t\tnode_name = child.text.decode()\n\t\t\t\t\t\tbreak\n\t\t\t\t\telif child.type == \"qualified_identifier\":\n\t\t\t\t\t\tidentifiers = [c for c in child.children if c.type == \"identifier\"]\n\t\t\t\t\t\tif identifiers:\n\t\t\t\t\t\t\tnode_name = identifiers[-1].text.decode()\n\t\t\t\t\t\t\tbreak\n\t\telif node.type == \"declaration\":\n\t\t\tcontaining_class = self._find_containing_class_for_method(node)\n\t\t\tdeclarator = next((c for c in node.children if c.type == \"function_declarator\"), None)\n\t\t\tif containing_class and declarator:\n\t\t\t\tnode_type = \"method\"\n\t\t\t\tnode_name = self._get_declarator_name(declarator)\n\t\t\telif self._is_global_variable(node):\n\t\t\t\tnode_type = \"variable\"\n\t\t\t\tfor child in node.children:\n\t\t\t\t\tif child.type == \"init_declarator\":\n\t\t\t\t\t\tidentifier = next((c for c in child.children if c.type == \"identifier\"), None)\n\t\t\t\t\t\tif identifier:\n\t\t\t\t\t\t\tnode_name = identifier.text.decode()\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\telif child.type == \"identifier\":\n\t\t\t\t\t\tnode_name = child.text.decode()\n\t\t\t\t\t\tbreak\n\t\telif node.type == \"alias_declaration\":\n\t\t\t# using name = type; β€” aliases are real API surface (e.g. a\n\t\t\t# library's public alias for an internal template), so they are\n\t\t\t# extracted as components and can resolve call/type references.\n\t\t\tnode_type = \"type_alias\"\n\t\t\tfor child in node.children:\n\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\tnode_name = child.text.decode()\n\t\t\t\t\tbreak\n\t\telif node.type == \"type_definition\":\n\t\t\t# typedef ... name; β€” the alias name is the trailing type_identifier\n\t\t\tnode_type = \"type_alias\"\n\t\t\tidentifiers = [c for c in node.children if c.type == \"type_identifier\"]\n\t\t\tif identifiers:\n\t\t\t\tnode_name = identifiers[-1].text.decode()\n\t\telif node.type == \"namespace_definition\":\n\t\t\tnode_type = \"namespace\"\n\t\t\tfound_namespace_keyword = False\n\t\t\tfor child in node.children:\n\t\t\t\tif child.type == \"namespace\":\n\t\t\t\t\tfound_namespace_keyword = True\n\t\t\t\telif found_namespace_keyword and child.type == \"identifier\":\n\t\t\t\t\tnode_name = child.text.decode()\n\t\t\t\t\tbreak\n\t\t\n\t\tif node_type and node_name:\n\t\t\tif node_type == \"method\":\n\t\t\t\tcomponent_id = self._get_component_id(node_name, containing_class)\n\t\t\t\ttop_level_key = component_id\n\t\t\telse:\n\t\t\t\tcomponent_id = self._get_component_id(node_name)\n\t\t\t\ttop_level_key = node_name\n\t\t\t\t\n\t\t\trelative_path = self._get_relative_path()\n\t\t\t\n\t\t\tnode_obj = Node(\n\t\t\t\tid=component_id,\n\t\t\t\tname=node_name,\n\t\t\t\tcomponent_type=node_type,\n\t\t\t\tfile_path=str(self.file_path),\n\t\t\t\trelative_path=relative_path,\n\t\t\t\tsource_code=\"\\n\".join(lines[node.start_point[0]:node.end_point[0]+1]),\n\t\t\t\tstart_line=node.start_point[0]+1,\n\t\t\t\tend_line=node.end_point[0]+1,\n\t\t\t\thas_docstring=False,\n\t\t\t\tdocstring=\"\",\n\t\t\t\tparameters=None,\n\t\t\t\tnode_type=node_type,\n\t\t\t\tbase_classes=None,\n\t\t\t\tclass_name=containing_class if node_type == \"method\" else None,\n\t\t\t\tdisplay_name=f\"{node_type} {node_name}\",\n\t\t\t\tcomponent_id=component_id,\n\t\t\t\tlanguage=\"cpp\",\n\t\t\t\tqualified_name=f\"{containing_class}.{node_name}\" if containing_class else node_name\n\t\t\t)\n\t\t\t\n\t\t\ttop_level_nodes[top_level_key] = node_obj\n\t\t\ttop_level_nodes[component_id] = node_obj\n\t\t\tif node_type == \"method\" and containing_class:\n\t\t\t\ttop_level_nodes[f\"{containing_class}.{node_name}\"] = node_obj\n\t\t\t\ttop_level_nodes.setdefault(node_name, node_obj)\n\t\t\t\n\t\t\tif node_type in [\"class\", \"struct\", \"function\", \"method\", \"type_alias\"]:\n\t\t\t\tself.nodes.append(node_obj)\n\t\t\n\t\t# Recursively process children\n\t\tfor child in node.children:\n\t\t\tself._extract_nodes(child, top_level_nodes, lines)\n\n\tdef _is_global_variable(self, node) -> bool:\n\t\t\"\"\"Check if a declaration node is a global variable.\"\"\"\n\t\tparent = node.parent\n\t\twhile parent:\n\t\t\tif parent.type in [\"function_definition\", \"class_specifier\", \"struct_specifier\"]:\n\t\t\t\treturn False\n\t\t\tparent = parent.parent\n\t\treturn True\n\n\tdef _get_declarator_name(self, declarator) -> Optional[str]:\n\t\t\"\"\"Extract the declared function or method name from nested declarators.\"\"\"\n\t\tfor child in declarator.children:\n\t\t\tif child.type in [\"identifier\", \"field_identifier\"]:\n\t\t\t\treturn child.text.decode()\n\t\t\tif child.type == \"qualified_identifier\":\n\t\t\t\tidentifiers = [c for c in child.children if c.type in [\"identifier\", \"field_identifier\"]]\n\t\t\t\tif identifiers:\n\t\t\t\t\treturn identifiers[-1].text.decode()\n\t\t\tif child.children:\n\t\t\t\tname = self._get_declarator_name(child)\n\t\t\t\tif name:\n\t\t\t\t\treturn name\n\t\treturn None\n\n\tdef _get_qualified_declarator_parts(self, declarator) -> list[str]:\n\t\tif declarator is None:\n\t\t\treturn []\n\t\tfor child in declarator.children:\n\t\t\tif child.type == \"qualified_identifier\":\n\t\t\t\treturn [\n\t\t\t\t\tc.text.decode()\n\t\t\t\t\tfor c in child.children\n\t\t\t\t\tif c.type in [\"identifier\", \"field_identifier\", \"type_identifier\", \"namespace_identifier\"]\n\t\t\t\t]\n\t\t\tif child.children:\n\t\t\t\tparts = self._get_qualified_declarator_parts(child)\n\t\t\t\tif parts:\n\t\t\t\t\treturn parts\n\t\treturn []\n\n\tdef _find_containing_class_for_method(self, node):\n\t\t\"\"\"Find the class that contains this method definition.\"\"\"\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type == \"class_specifier\":\n\t\t\t\t# Get class name\n\t\t\t\tfor child in current.children:\n\t\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\t\treturn child.text.decode()\n\t\t\telif current.type == \"struct_specifier\":\n\t\t\t\t# Get struct name \n\t\t\t\tfor child in current.children:\n\t\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\t\treturn child.text.decode()\n\t\t\tcurrent = current.parent\n\t\treturn None\n\n\tdef _extract_relationships(self, node, top_level_nodes):\n\t\tif node.type == \"call_expression\":\n\t\t\tcontaining_function_id = self._find_containing_function_or_method(node, top_level_nodes)\n\t\t\tif containing_function_id:\n\t\t\t\t\n\t\t\t\t# Get called function name \n\t\t\t\tcalled_function = None\n\t\t\t\treceiver_name = None\n\t\t\t\tfor child in node.children:\n\t\t\t\t\tif child.type == \"identifier\":\n\t\t\t\t\t\tcalled_function = child.text.decode()\n\t\t\t\t\t\tbreak\n\t\t\t\t\telif child.type == \"field_expression\":\n\t\t\t\t\t\treceiver_name, method_name = self._get_field_call_parts(child)\n\t\t\t\t\t\tif method_name:\n\t\t\t\t\t\t\tcalled_function = method_name\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\n\t\t\t\tif called_function:\n\t\t\t\t\ttarget_method = None\n\t\t\t\t\tif receiver_name:\n\t\t\t\t\t\treceiver_type = self._find_variable_type(node, receiver_name)\n\t\t\t\t\t\tif receiver_type:\n\t\t\t\t\t\t\ttarget_method = self._find_method_component(called_function, top_level_nodes, receiver_type)\n\t\t\t\t\tif not target_method:\n\t\t\t\t\t\ttarget_method = self._find_method_component(called_function, top_level_nodes)\n\t\t\t\t\ttarget_class = self._find_class_containing_method(called_function, top_level_nodes)\n\n\t\t\t\t\tif target_method:\n\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\tcaller=containing_function_id,\n\t\t\t\t\t\t\tcallee=target_method,\n\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\tis_resolved=True\n\t\t\t\t\t\t))\n\t\t\t\t\telif target_class:\n\t\t\t\t\t\ttarget_class_id = self._get_component_id(target_class)\n\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\tcaller=containing_function_id,\n\t\t\t\t\t\t\tcallee=target_class_id,\n\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\tis_resolved=True\n\t\t\t\t\t\t))\n\t\t\t\t\telif called_function in top_level_nodes:\n\t\t\t\t\t\tcalled_function_id = top_level_nodes[called_function].id\n\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\tcaller=containing_function_id,\n\t\t\t\t\t\t\tcallee=called_function_id,\n\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\tis_resolved=True\n\t\t\t\t\t\t))\n\t\t\t\t\telif receiver_name is not None:\n\t\t\t\t\t\t# A member call whose receiver type could not be\n\t\t\t\t\t\t# resolved: a name matching an STL member here is\n\t\t\t\t\t\t# overwhelmingly likely external, so suppress it.\n\t\t\t\t\t\tif not self._is_system_function(called_function):\n\t\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\t\tcaller=containing_function_id,\n\t\t\t\t\t\t\t\tcallee=called_function,\n\t\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\t\tis_resolved=False\n\t\t\t\t\t\t\t))\n\t\t\t\t\telif (\n\t\t\t\t\t\tnot is_macro_name(called_function)\n\t\t\t\t\t\tand called_function not in self._find_template_parameters(node)\n\t\t\t\t\t):\n\t\t\t\t\t\t# Plain calls are emitted for cross-file resolution;\n\t\t\t\t\t\t# external filtering happens centrally after the\n\t\t\t\t\t\t# project resolver has had its chance.\n\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\tcaller=containing_function_id,\n\t\t\t\t\t\t\tcallee=called_function,\n\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\tis_resolved=False\n\t\t\t\t\t\t))\n\t\t\n\t\telif node.type == \"base_class_clause\":\n\t\t\t# Find the containing class\n\t\t\tcontaining_class = self._find_containing_class(node)\n\t\t\tif containing_class:\n\t\t\t\ttemplate_params = self._find_template_parameters(node)\n\t\t\t\t# Extract base class names\n\t\t\t\tfor child in node.children:\n\t\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\t\tbase_class = child.text.decode()\n\t\t\t\t\t\tif base_class in template_params or is_macro_name(base_class):\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tcontaining_class_id = self._get_component_id(containing_class)\n\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\tcaller=containing_class_id,\n\t\t\t\t\t\t\tcallee=base_class,\n\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\tis_resolved=False\n\t\t\t\t\t\t))\n\t\t\n\t\telif node.type == \"new_expression\":\n\t\t\tcontaining_function_id = self._find_containing_function_or_method(node, top_level_nodes)\n\t\t\tif containing_function_id:\n\t\t\t\t\n\t\t\t\t# Get the class being instantiated\n\t\t\t\tfor child in node.children:\n\t\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\t\tclass_name = child.text.decode()\n\t\t\t\t\t\tif class_name in top_level_nodes:\n\t\t\t\t\t\t\tclass_id = self._get_component_id(class_name)\n\t\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\t\tcaller=containing_function_id,\n\t\t\t\t\t\t\t\tcallee=class_id,\n\t\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\t\tis_resolved=True\n\t\t\t\t\t\t\t))\n\t\t\t\t\t\tbreak\n\t\t\n\t\telif node.type == \"identifier\":\n\t\t\tparent = node.parent\n\t\t\tif parent and parent.type not in [\"function_definition\", \"class_specifier\", \"declaration\", \"function_declarator\"]:\n\t\t\t\tvar_name = node.text.decode()\n\t\t\t\tif var_name in top_level_nodes and top_level_nodes[var_name].component_type == \"variable\":\n\t\t\t\t\tcontaining_function_id = self._find_containing_function_or_method(node, top_level_nodes)\n\t\t\t\t\tif containing_function_id:\n\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\tcaller=containing_function_id,\n\t\t\t\t\t\t\tcallee=var_name,\n\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\tis_resolved=False\n\t\t\t\t\t\t))\n\t\t\n\t\t# Recursively process children\n\t\tfor child in node.children:\n\t\t\tself._extract_relationships(child, top_level_nodes)\n\n\tdef _get_field_call_parts(self, field_expression) -> tuple[Optional[str], Optional[str]]:\n\t\treceiver_name = None\n\t\tmethod_name = None\n\t\tfor child in field_expression.children:\n\t\t\tif child.type == \"field_identifier\":\n\t\t\t\tmethod_name = child.text.decode()\n\t\t\telif child.type == \"identifier\" and receiver_name is None:\n\t\t\t\treceiver_name = child.text.decode()\n\t\t\telif child.type == \"field_expression\" and receiver_name is None:\n\t\t\t\treceiver_name = child.text.decode().split(\".\")[-1].split(\"->\")[-1]\n\t\treturn receiver_name, method_name\n\n\tdef _find_variable_type(self, node, variable_name: str) -> Optional[str]:\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type in [\"compound_statement\", \"field_declaration_list\", \"translation_unit\"]:\n\t\t\t\tfound = self._search_variable_declaration(current, variable_name)\n\t\t\t\tif found:\n\t\t\t\t\treturn found\n\t\t\tif current.type == \"function_definition\":\n\t\t\t\tdeclarator = next((c for c in current.children if c.type == \"function_declarator\"), None)\n\t\t\t\tfound = self._search_parameter_declaration(declarator, variable_name)\n\t\t\t\tif found:\n\t\t\t\t\treturn found\n\t\t\tcurrent = current.parent\n\t\treturn None\n\n\tdef _search_variable_declaration(self, node, variable_name: str) -> Optional[str]:\n\t\tfor child in node.children:\n\t\t\tif child.type == \"declaration\":\n\t\t\t\ttype_name = self._get_declaration_type_name(child)\n\t\t\t\tdeclared_name = self._get_declared_variable_name(child)\n\t\t\t\tif declared_name == variable_name:\n\t\t\t\t\treturn type_name or self._get_constructor_type_name(child)\n\t\t\tif child.children and child.type not in [\"class_specifier\", \"struct_specifier\", \"function_definition\"]:\n\t\t\t\tfound = self._search_variable_declaration(child, variable_name)\n\t\t\t\tif found:\n\t\t\t\t\treturn found\n\t\treturn None\n\n\tdef _search_parameter_declaration(self, node, variable_name: str) -> Optional[str]:\n\t\tif node is None:\n\t\t\treturn None\n\t\tif node.type == \"parameter_declaration\":\n\t\t\ttype_name = self._get_declaration_type_name(node)\n\t\t\tdeclared_name = self._get_declared_variable_name(node)\n\t\t\tif declared_name == variable_name:\n\t\t\t\treturn type_name\n\t\tfor child in node.children:\n\t\t\tfound = self._search_parameter_declaration(child, variable_name)\n\t\t\tif found:\n\t\t\t\treturn found\n\t\treturn None\n\n\tdef _get_declaration_type_name(self, node) -> Optional[str]:\n\t\tfor child in node.children:\n\t\t\tif child.type in [\"type_identifier\", \"primitive_type\", \"qualified_identifier\"]:\n\t\t\t\treturn self._last_type_part(child.text.decode())\n\t\t\tif child.type in [\"template_type\", \"generic_type\"]:\n\t\t\t\treturn self._last_type_part(child.text.decode().split(\"<\", 1)[0])\n\t\treturn None\n\n\tdef _get_declared_variable_name(self, node) -> Optional[str]:\n\t\tfor child in reversed(node.children):\n\t\t\tif child.type in [\"identifier\", \"field_identifier\"]:\n\t\t\t\treturn child.text.decode()\n\t\t\tif child.type in [\"init_declarator\", \"pointer_declarator\", \"reference_declarator\", \"array_declarator\"]:\n\t\t\t\tname = self._get_declared_variable_name(child)\n\t\t\t\tif name:\n\t\t\t\t\treturn name\n\t\treturn None\n\n\tdef _get_constructor_type_name(self, node) -> Optional[str]:\n\t\tfor child in node.children:\n\t\t\tif child.type == \"call_expression\":\n\t\t\t\tfor call_child in child.children:\n\t\t\t\t\tif call_child.type in [\"identifier\", \"type_identifier\"]:\n\t\t\t\t\t\treturn call_child.text.decode()\n\t\t\tif child.children:\n\t\t\t\tfound = self._get_constructor_type_name(child)\n\t\t\t\tif found:\n\t\t\t\t\treturn found\n\t\treturn None\n\n\tdef _last_type_part(self, type_name: str) -> str:\n\t\treturn type_name.strip(\"&* \").split(\"::\")[-1]\n\n\tdef _find_containing_function(self, node, top_level_nodes):\n\t\t\"\"\"Find the function that contains this node.\"\"\"\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type == \"function_definition\":\n\t\t\t\t# Get function name\n\t\t\t\tdeclarator = next((c for c in current.children if c.type == \"function_declarator\"), None)\n\t\t\t\tif declarator:\n\t\t\t\t\tidentifier = next((c for c in declarator.children if c.type == \"identifier\"), None)\n\t\t\t\t\tif identifier:\n\t\t\t\t\t\tfunc_name = identifier.text.decode()\n\t\t\t\t\t\tif func_name in top_level_nodes:\n\t\t\t\t\t\t\treturn func_name\n\t\t\tcurrent = current.parent\n\t\treturn None\n\n\tdef _find_containing_function_or_method(self, node, top_level_nodes):\n\t\t\"\"\"Find the function or method that contains this node.\"\"\"\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type == \"function_definition\":\n\t\t\t\tdeclarator = next((c for c in current.children if c.type == \"function_declarator\"), None)\n\t\t\t\tif declarator:\n\t\t\t\t\tfunc_name = self._get_declarator_name(declarator)\n\t\t\t\t\tif func_name:\n\t\t\t\t\t\tcontaining_class = self._find_containing_class_for_method(current)\n\t\t\t\t\t\tqualified_parts = self._get_qualified_declarator_parts(declarator)\n\t\t\t\t\t\tif not containing_class and len(qualified_parts) > 1:\n\t\t\t\t\t\t\tcontaining_class = qualified_parts[-2]\n\t\t\t\t\t\tif containing_class:\n\t\t\t\t\t\t\treturn self._get_component_id(func_name, containing_class)\n\t\t\t\t\t\treturn self._get_component_id(func_name)\n\t\t\tcurrent = current.parent\n\t\treturn None\n\n\tdef _get_component_id_for_function(self, func_name, top_level_nodes):\n\t\tif func_name in top_level_nodes:\n\t\t\tnode_obj = top_level_nodes[func_name]\n\t\t\tif hasattr(node_obj, 'class_name') and node_obj.class_name:\n\t\t\t\treturn self._get_component_id(func_name, node_obj.class_name)\n\t\t\telse:\n\t\t\t\treturn self._get_component_id(func_name)\n\t\treturn self._get_component_id(func_name)\n\n\tdef _find_containing_class(self, node):\n\t\t\"\"\"Find the class that contains this node.\"\"\"\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type == \"class_specifier\":\n\t\t\t\t# Get class name\n\t\t\t\tfor child in current.children:\n\t\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\t\treturn child.text.decode()\n\t\t\tcurrent = current.parent\n\t\treturn None\n\n\tdef _find_template_parameters(self, node) -> set:\n\t\t\"\"\"Collect template type-parameter names in scope at this node, so a\n\t\treference to `T`/`Char`/... is not reported as an unresolved project\n\t\tsymbol.\"\"\"\n\t\tparams = set()\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type == \"template_declaration\":\n\t\t\t\tparam_list = next(\n\t\t\t\t\t(c for c in current.children if c.type == \"template_parameter_list\"), None\n\t\t\t\t)\n\t\t\t\tif param_list:\n\t\t\t\t\tfor param in param_list.children:\n\t\t\t\t\t\tfor child in getattr(param, \"children\", []):\n\t\t\t\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\t\t\t\tparams.add(child.text.decode())\n\t\t\tcurrent = current.parent\n\t\treturn params\n\n\tdef _is_system_function(self, func_name: str) -> bool:\n\t\t\"\"\"Check if a call target is external rather than a project function.\n\n\t\tBesides the curated standard-library set, an ALL_CAPS callee is treated as\n\t\ta macro invocation: macros are not extracted as components, so a call to\n\t\tone can never resolve to a project function and would otherwise pollute the\n\t\tgraph as unresolved noise. This only affects the unresolved fallback β€”\n\t\treal components in ALL_CAPS (rare in C++) are matched by the earlier\n\t\tresolution branches before this check runs.\n\t\t\"\"\"\n\t\tif is_external_symbol(\"cpp\", func_name):\n\t\t\treturn True\n\t\treturn is_macro_name(func_name)\n\n\tdef _find_method_component(self, method_name, top_level_nodes, class_name: str = None):\n\t\tif class_name:\n\t\t\tqualified_key = f\"{class_name}.{method_name}\"\n\t\t\tif qualified_key in top_level_nodes:\n\t\t\t\treturn top_level_nodes[qualified_key].id\n\t\tfor node_obj in top_level_nodes.values():\n\t\t\tif node_obj.component_type == \"method\" and node_obj.name == method_name:\n\t\t\t\treturn node_obj.id\n\t\treturn None\n\n\tdef _find_class_containing_method(self, method_name, top_level_nodes):\n\t\tfor node_name, node_obj in top_level_nodes.items():\n\t\t\tif node_obj.component_type in [\"class\", \"struct\"]:\n\t\t\t\tif self._class_has_method(node_obj, method_name):\n\t\t\t\t\treturn node_name\n\t\treturn None\n\n\tdef _class_has_method(self, class_node, method_name):\n\t\tlines = class_node.source_code.split('\\n')\n\t\tfor line in lines:\n\t\t\tif f'{method_name}(' in line and ('void' in line or 'int' in line or 'bool' in line or class_node.name in line):\n\t\t\t\treturn True\n\t\treturn False", - "start_line": 36, - "end_line": 672, - "has_docstring": false, - "docstring": "", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class TreeSitterCppAnalyzer", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer.__init__": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer.__init__", - "name": "TreeSitterCppAnalyzer.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._analyze" - ], - "source_code": "\tdef __init__(self, file_path: str, content: str, repo_path: str = None):\n\t\tself.file_path = Path(file_path)\n\t\tself.content = content\n\t\tself.repo_path = repo_path or \"\"\n\t\tself.nodes: List[Node] = []\n\t\tself.call_relationships: List[CallRelationship] = []\n\t\tself._analyze()", - "start_line": 37, - "end_line": 43, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "file_path", - "content", - "repo_path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer.__init__", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_module_path": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_module_path", - "name": "TreeSitterCppAnalyzer._get_module_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [], - "source_code": "\tdef _get_module_path(self) -> str:\n\t\tif self.repo_path:\n\t\t\ttry:\n\t\t\t\trel_path = os.path.relpath(str(self.file_path), self.repo_path)\n\t\t\texcept ValueError:\n\t\t\t\trel_path = str(self.file_path)\n\t\telse:\n\t\t\trel_path = str(self.file_path)\n\n\t\tfor ext in ['.cpp', '.cc', '.cxx', '.c++', '.hpp', '.hxx', '.h++', '.h']:\n\t\t\tif rel_path.endswith(ext):\n\t\t\t\trel_path = rel_path[:-len(ext)]\n\t\t\t\tbreak\n\t\treturn rel_path.replace('/', '.').replace('\\\\', '.')", - "start_line": 45, - "end_line": 58, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._get_module_path", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_module_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_relative_path": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_relative_path", - "name": "TreeSitterCppAnalyzer._get_relative_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [], - "source_code": "\tdef _get_relative_path(self) -> str:\n\t\tif self.repo_path:\n\t\t\ttry:\n\t\t\t\treturn os.path.relpath(str(self.file_path), self.repo_path)\n\t\t\texcept ValueError:\n\t\t\t\treturn str(self.file_path)\n\t\telse:\n\t\t\treturn str(self.file_path)", - "start_line": 60, - "end_line": 67, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._get_relative_path", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_relative_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_component_id": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_component_id", - "name": "TreeSitterCppAnalyzer._get_component_id", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_relative_path" - ], - "source_code": "\tdef _get_component_id(self, name: str, parent_class: str = None) -> str:\n\t\trel_path = self._get_relative_path()\n\t\tif parent_class:\n\t\t\treturn f\"{rel_path}::{parent_class}.{name}\"\n\t\treturn f\"{rel_path}::{name}\"", - "start_line": 69, - "end_line": 73, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "name", - "parent_class" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._get_component_id", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_component_id", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._analyze": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._analyze", - "name": "TreeSitterCppAnalyzer._analyze", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._parse_with_macro_recovery", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._extract_nodes", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._extract_relationships" - ], - "source_code": "\tdef _analyze(self):\n\t\tlanguage_capsule = tree_sitter_cpp.language()\n\t\tcpp_language = Language(language_capsule)\n\t\tparser = Parser(cpp_language)\n\t\troot = self._parse_with_macro_recovery(parser)\n\t\tlines = self.content.splitlines()\n\t\t\n\t\ttop_level_nodes = {}\n\t\t\n\t\t# collect all top-level nodes using recursive traversal\n\t\tself._extract_nodes(root, top_level_nodes, lines)\n\t\t\n\t\t# extract relationships between top-level nodes\n\t\tself._extract_relationships(root, top_level_nodes)", - "start_line": 75, - "end_line": 88, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._analyze", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._analyze", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._parse_with_macro_recovery": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._parse_with_macro_recovery", - "name": "TreeSitterCppAnalyzer._parse_with_macro_recovery", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._normalize_for_parser", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._count_parse_errors" - ], - "source_code": "\tdef _parse_with_macro_recovery(self, parser):\n\t\t\"\"\"Parse the original source; if it has syntax errors, retry with macro\n\t\tnormalization and keep whichever parse has fewer errors.\n\n\t\tNormalization strips ALL_CAPS tokens by naming convention, which is\n\t\twrong for code whose *types* are ALL_CAPS (e.g. Win32 `HANDLE`/`DWORD`).\n\t\tComparing error counts makes the heuristic self-correcting: clean files\n\t\tare never touched, and normalization is only kept when it demonstrably\n\t\trecovers structure.\n\t\t\"\"\"\n\t\ttree = parser.parse(bytes(self.content, \"utf8\"))\n\t\tif not tree.root_node.has_error:\n\t\t\treturn tree.root_node\n\n\t\tnormalized = self._normalize_for_parser(self.content)\n\t\tif normalized == self.content:\n\t\t\treturn tree.root_node\n\n\t\tnormalized_tree = parser.parse(bytes(normalized, \"utf8\"))\n\t\tif self._count_parse_errors(normalized_tree.root_node) < self._count_parse_errors(tree.root_node):\n\t\t\treturn normalized_tree.root_node\n\t\treturn tree.root_node", - "start_line": 90, - "end_line": 111, - "has_docstring": true, - "docstring": "Parse the original source; if it has syntax errors, retry with macro\nnormalization and keep whichever parse has fewer errors.\n\nNormalization strips ALL_CAPS tokens by naming convention, which is\nwrong for code whose *types* are ALL_CAPS (e.g. Win32 `HANDLE`/`DWORD`).\nComparing error counts makes the heuristic self-correcting: clean files\nare never touched, and normalization is only kept when it demonstrably\nrecovers structure.", - "parameters": [ - "self", - "parser" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._parse_with_macro_recovery", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._parse_with_macro_recovery", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._count_parse_errors": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._count_parse_errors", - "name": "TreeSitterCppAnalyzer._count_parse_errors", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [], - "source_code": "\tdef _count_parse_errors(self, root) -> int:\n\t\terrors = 0\n\t\tstack = [root]\n\t\twhile stack:\n\t\t\tnode = stack.pop()\n\t\t\tif node.is_error or node.is_missing:\n\t\t\t\terrors += 1\n\t\t\tstack.extend(node.children)\n\t\treturn errors", - "start_line": 113, - "end_line": 121, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "root" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._count_parse_errors", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._count_parse_errors", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._normalize_for_parser": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._normalize_for_parser", - "name": "TreeSitterCppAnalyzer._normalize_for_parser", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/utils/external_symbols.py::is_macro_name" - ], - "source_code": "\tdef _normalize_for_parser(self, content: str) -> str:\n\t\t\"\"\"Strip ALL_CAPS attribute/specifier macros that sit in front of a\n\t\tdeclaration so tree-sitter can recover the underlying signature. This is\n\t\tname-agnostic: it keys off the conventional ALL_CAPS macro spelling, not\n\t\tany specific library's prefix, and only fires in specifier position so\n\t\tidentifiers used in expressions are preserved. Line count is unchanged so\n\t\treported line numbers stay accurate.\n\t\t\"\"\"\n\t\tnormalized_lines = []\n\t\tfor line in content.splitlines():\n\t\t\tupdated = line\n\t\t\tstandalone = _STANDALONE_MACRO_RE.match(updated)\n\t\t\tif standalone and is_macro_name(standalone.group(1)):\n\t\t\t\tnormalized_lines.append(\"\")\n\t\t\t\tcontinue\n\t\t\tfor pattern in (_SPECIFIER_MACRO_CALL_RE, _SPECIFIER_MACRO_RE):\n\t\t\t\tprevious = None\n\t\t\t\twhile previous != updated:\n\t\t\t\t\tprevious = updated\n\t\t\t\t\tupdated = pattern.sub(\n\t\t\t\t\t\tlambda m: (m.group(1) + m.group(3)) if is_macro_name(m.group(2)) else m.group(0),\n\t\t\t\t\t\tupdated,\n\t\t\t\t\t)\n\t\t\tupdated = _KEYWORD_MACRO_RE.sub(\n\t\t\t\tlambda m: (m.group(1) + m.group(2)) if is_macro_name(m.group(3)) else m.group(0),\n\t\t\t\tupdated,\n\t\t\t)\n\t\t\tnormalized_lines.append(updated)\n\t\treturn \"\\n\".join(normalized_lines)", - "start_line": 123, - "end_line": 151, - "has_docstring": true, - "docstring": "Strip ALL_CAPS attribute/specifier macros that sit in front of a\ndeclaration so tree-sitter can recover the underlying signature. This is\nname-agnostic: it keys off the conventional ALL_CAPS macro spelling, not\nany specific library's prefix, and only fires in specifier position so\nidentifiers used in expressions are preserved. Line count is unchanged so\nreported line numbers stay accurate.", - "parameters": [ - "self", - "content" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._normalize_for_parser", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._normalize_for_parser", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._extract_nodes": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._extract_nodes", - "name": "TreeSitterCppAnalyzer._extract_nodes", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_component_id", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_declarator_name", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._is_global_variable", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_qualified_declarator_parts", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_relative_path", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_containing_class_for_method", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._extract_nodes" - ], - "source_code": "\tdef _extract_nodes(self, node, top_level_nodes, lines):\n\t\t\"\"\"Recursively extract top-level nodes (classes, functions, global variables).\"\"\"\n\t\tnode_type = None\n\t\tnode_name = None\n\t\tcontaining_class = None\n\t\t\n\t\tif node.type == \"class_specifier\":\n\t\t\t# \"class\" + type_identifier + { ... }\n\t\t\tnode_type = \"class\"\n\t\t\t# Find type_identifier that represents the class name\n\t\t\tfor child in node.children:\n\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\tnode_name = child.text.decode()\n\t\t\t\t\tbreak\n\t\telif node.type == \"struct_specifier\":\n\t\t\t# \"struct\" + type_identifier + { ... }\n\t\t\tnode_type = \"struct\"\n\t\t\t# Find type_identifier that represents the struct name\n\t\t\tfor child in node.children:\n\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\tnode_name = child.text.decode()\n\t\t\t\t\tbreak\n\t\telif node.type == \"function_definition\":\n\t\t\t# Check if this is inside a class or function\n\t\t\tcontaining_class = self._find_containing_class_for_method(node)\n\t\t\tdeclarator = next((c for c in node.children if c.type == \"function_declarator\"), None)\n\t\t\tqualified_parts = self._get_qualified_declarator_parts(declarator) if declarator else []\n\t\t\tif not containing_class and len(qualified_parts) > 1:\n\t\t\t\tcontaining_class = qualified_parts[-2]\n\t\t\tif containing_class:\n\t\t\t\tnode_type = \"method\"\n\t\t\telse:\n\t\t\t\tnode_type = \"function\"\n\t\t\t\n\t\t\tif declarator:\n\t\t\t\tfor child in declarator.children:\n\t\t\t\t\tif child.type == \"identifier\":\n\t\t\t\t\t\tnode_name = child.text.decode()\n\t\t\t\t\t\tbreak\n\t\t\t\t\telif child.type == \"field_identifier\":\n\t\t\t\t\t\tnode_name = child.text.decode()\n\t\t\t\t\t\tbreak\n\t\t\t\t\telif child.type == \"qualified_identifier\":\n\t\t\t\t\t\tidentifiers = [c for c in child.children if c.type == \"identifier\"]\n\t\t\t\t\t\tif identifiers:\n\t\t\t\t\t\t\tnode_name = identifiers[-1].text.decode()\n\t\t\t\t\t\t\tbreak\n\t\telif node.type == \"declaration\":\n\t\t\tcontaining_class = self._find_containing_class_for_method(node)\n\t\t\tdeclarator = next((c for c in node.children if c.type == \"function_declarator\"), None)\n\t\t\tif containing_class and declarator:\n\t\t\t\tnode_type = \"method\"\n\t\t\t\tnode_name = self._get_declarator_name(declarator)\n\t\t\telif self._is_global_variable(node):\n\t\t\t\tnode_type = \"variable\"\n\t\t\t\tfor child in node.children:\n\t\t\t\t\tif child.type == \"init_declarator\":\n\t\t\t\t\t\tidentifier = next((c for c in child.children if c.type == \"identifier\"), None)\n\t\t\t\t\t\tif identifier:\n\t\t\t\t\t\t\tnode_name = identifier.text.decode()\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\telif child.type == \"identifier\":\n\t\t\t\t\t\tnode_name = child.text.decode()\n\t\t\t\t\t\tbreak\n\t\telif node.type == \"alias_declaration\":\n\t\t\t# using name = type; β€” aliases are real API surface (e.g. a\n\t\t\t# library's public alias for an internal template), so they are\n\t\t\t# extracted as components and can resolve call/type references.\n\t\t\tnode_type = \"type_alias\"\n\t\t\tfor child in node.children:\n\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\tnode_name = child.text.decode()\n\t\t\t\t\tbreak\n\t\telif node.type == \"type_definition\":\n\t\t\t# typedef ... name; β€” the alias name is the trailing type_identifier\n\t\t\tnode_type = \"type_alias\"\n\t\t\tidentifiers = [c for c in node.children if c.type == \"type_identifier\"]\n\t\t\tif identifiers:\n\t\t\t\tnode_name = identifiers[-1].text.decode()\n\t\telif node.type == \"namespace_definition\":\n\t\t\tnode_type = \"namespace\"\n\t\t\tfound_namespace_keyword = False\n\t\t\tfor child in node.children:\n\t\t\t\tif child.type == \"namespace\":\n\t\t\t\t\tfound_namespace_keyword = True\n\t\t\t\telif found_namespace_keyword and child.type == \"identifier\":\n\t\t\t\t\tnode_name = child.text.decode()\n\t\t\t\t\tbreak\n\t\t\n\t\tif node_type and node_name:\n\t\t\tif node_type == \"method\":\n\t\t\t\tcomponent_id = self._get_component_id(node_name, containing_class)\n\t\t\t\ttop_level_key = component_id\n\t\t\telse:\n\t\t\t\tcomponent_id = self._get_component_id(node_name)\n\t\t\t\ttop_level_key = node_name\n\t\t\t\t\n\t\t\trelative_path = self._get_relative_path()\n\t\t\t\n\t\t\tnode_obj = Node(\n\t\t\t\tid=component_id,\n\t\t\t\tname=node_name,\n\t\t\t\tcomponent_type=node_type,\n\t\t\t\tfile_path=str(self.file_path),\n\t\t\t\trelative_path=relative_path,\n\t\t\t\tsource_code=\"\\n\".join(lines[node.start_point[0]:node.end_point[0]+1]),\n\t\t\t\tstart_line=node.start_point[0]+1,\n\t\t\t\tend_line=node.end_point[0]+1,\n\t\t\t\thas_docstring=False,\n\t\t\t\tdocstring=\"\",\n\t\t\t\tparameters=None,\n\t\t\t\tnode_type=node_type,\n\t\t\t\tbase_classes=None,\n\t\t\t\tclass_name=containing_class if node_type == \"method\" else None,\n\t\t\t\tdisplay_name=f\"{node_type} {node_name}\",\n\t\t\t\tcomponent_id=component_id,\n\t\t\t\tlanguage=\"cpp\",\n\t\t\t\tqualified_name=f\"{containing_class}.{node_name}\" if containing_class else node_name\n\t\t\t)\n\t\t\t\n\t\t\ttop_level_nodes[top_level_key] = node_obj\n\t\t\ttop_level_nodes[component_id] = node_obj\n\t\t\tif node_type == \"method\" and containing_class:\n\t\t\t\ttop_level_nodes[f\"{containing_class}.{node_name}\"] = node_obj\n\t\t\t\ttop_level_nodes.setdefault(node_name, node_obj)\n\t\t\t\n\t\t\tif node_type in [\"class\", \"struct\", \"function\", \"method\", \"type_alias\"]:\n\t\t\t\tself.nodes.append(node_obj)\n\t\t\n\t\t# Recursively process children\n\t\tfor child in node.children:\n\t\t\tself._extract_nodes(child, top_level_nodes, lines)", - "start_line": 153, - "end_line": 284, - "has_docstring": true, - "docstring": "Recursively extract top-level nodes (classes, functions, global variables).", - "parameters": [ - "self", - "node", - "top_level_nodes", - "lines" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._extract_nodes", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._extract_nodes", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._is_global_variable": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._is_global_variable", - "name": "TreeSitterCppAnalyzer._is_global_variable", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [], - "source_code": "\tdef _is_global_variable(self, node) -> bool:\n\t\t\"\"\"Check if a declaration node is a global variable.\"\"\"\n\t\tparent = node.parent\n\t\twhile parent:\n\t\t\tif parent.type in [\"function_definition\", \"class_specifier\", \"struct_specifier\"]:\n\t\t\t\treturn False\n\t\t\tparent = parent.parent\n\t\treturn True", - "start_line": 286, - "end_line": 293, - "has_docstring": true, - "docstring": "Check if a declaration node is a global variable.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._is_global_variable", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._is_global_variable", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_declarator_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_declarator_name", - "name": "TreeSitterCppAnalyzer._get_declarator_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_declarator_name" - ], - "source_code": "\tdef _get_declarator_name(self, declarator) -> Optional[str]:\n\t\t\"\"\"Extract the declared function or method name from nested declarators.\"\"\"\n\t\tfor child in declarator.children:\n\t\t\tif child.type in [\"identifier\", \"field_identifier\"]:\n\t\t\t\treturn child.text.decode()\n\t\t\tif child.type == \"qualified_identifier\":\n\t\t\t\tidentifiers = [c for c in child.children if c.type in [\"identifier\", \"field_identifier\"]]\n\t\t\t\tif identifiers:\n\t\t\t\t\treturn identifiers[-1].text.decode()\n\t\t\tif child.children:\n\t\t\t\tname = self._get_declarator_name(child)\n\t\t\t\tif name:\n\t\t\t\t\treturn name\n\t\treturn None", - "start_line": 295, - "end_line": 308, - "has_docstring": true, - "docstring": "Extract the declared function or method name from nested declarators.", - "parameters": [ - "self", - "declarator" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._get_declarator_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_declarator_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_qualified_declarator_parts": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_qualified_declarator_parts", - "name": "TreeSitterCppAnalyzer._get_qualified_declarator_parts", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_qualified_declarator_parts" - ], - "source_code": "\tdef _get_qualified_declarator_parts(self, declarator) -> list[str]:\n\t\tif declarator is None:\n\t\t\treturn []\n\t\tfor child in declarator.children:\n\t\t\tif child.type == \"qualified_identifier\":\n\t\t\t\treturn [\n\t\t\t\t\tc.text.decode()\n\t\t\t\t\tfor c in child.children\n\t\t\t\t\tif c.type in [\"identifier\", \"field_identifier\", \"type_identifier\", \"namespace_identifier\"]\n\t\t\t\t]\n\t\t\tif child.children:\n\t\t\t\tparts = self._get_qualified_declarator_parts(child)\n\t\t\t\tif parts:\n\t\t\t\t\treturn parts\n\t\treturn []", - "start_line": 310, - "end_line": 324, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "declarator" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._get_qualified_declarator_parts", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_qualified_declarator_parts", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_containing_class_for_method": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_containing_class_for_method", - "name": "TreeSitterCppAnalyzer._find_containing_class_for_method", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [], - "source_code": "\tdef _find_containing_class_for_method(self, node):\n\t\t\"\"\"Find the class that contains this method definition.\"\"\"\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type == \"class_specifier\":\n\t\t\t\t# Get class name\n\t\t\t\tfor child in current.children:\n\t\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\t\treturn child.text.decode()\n\t\t\telif current.type == \"struct_specifier\":\n\t\t\t\t# Get struct name \n\t\t\t\tfor child in current.children:\n\t\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\t\treturn child.text.decode()\n\t\t\tcurrent = current.parent\n\t\treturn None", - "start_line": 326, - "end_line": 341, - "has_docstring": true, - "docstring": "Find the class that contains this method definition.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._find_containing_class_for_method", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_containing_class_for_method", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._extract_relationships": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._extract_relationships", - "name": "TreeSitterCppAnalyzer._extract_relationships", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/utils/external_symbols.py::is_macro_name", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_component_id", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_field_call_parts", - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_class_containing_method", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_containing_function_or_method", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_template_parameters", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._extract_relationships", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_variable_type", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_method_component", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_containing_class", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._is_system_function" - ], - "source_code": "\tdef _extract_relationships(self, node, top_level_nodes):\n\t\tif node.type == \"call_expression\":\n\t\t\tcontaining_function_id = self._find_containing_function_or_method(node, top_level_nodes)\n\t\t\tif containing_function_id:\n\t\t\t\t\n\t\t\t\t# Get called function name \n\t\t\t\tcalled_function = None\n\t\t\t\treceiver_name = None\n\t\t\t\tfor child in node.children:\n\t\t\t\t\tif child.type == \"identifier\":\n\t\t\t\t\t\tcalled_function = child.text.decode()\n\t\t\t\t\t\tbreak\n\t\t\t\t\telif child.type == \"field_expression\":\n\t\t\t\t\t\treceiver_name, method_name = self._get_field_call_parts(child)\n\t\t\t\t\t\tif method_name:\n\t\t\t\t\t\t\tcalled_function = method_name\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\n\t\t\t\tif called_function:\n\t\t\t\t\ttarget_method = None\n\t\t\t\t\tif receiver_name:\n\t\t\t\t\t\treceiver_type = self._find_variable_type(node, receiver_name)\n\t\t\t\t\t\tif receiver_type:\n\t\t\t\t\t\t\ttarget_method = self._find_method_component(called_function, top_level_nodes, receiver_type)\n\t\t\t\t\tif not target_method:\n\t\t\t\t\t\ttarget_method = self._find_method_component(called_function, top_level_nodes)\n\t\t\t\t\ttarget_class = self._find_class_containing_method(called_function, top_level_nodes)\n\n\t\t\t\t\tif target_method:\n\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\tcaller=containing_function_id,\n\t\t\t\t\t\t\tcallee=target_method,\n\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\tis_resolved=True\n\t\t\t\t\t\t))\n\t\t\t\t\telif target_class:\n\t\t\t\t\t\ttarget_class_id = self._get_component_id(target_class)\n\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\tcaller=containing_function_id,\n\t\t\t\t\t\t\tcallee=target_class_id,\n\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\tis_resolved=True\n\t\t\t\t\t\t))\n\t\t\t\t\telif called_function in top_level_nodes:\n\t\t\t\t\t\tcalled_function_id = top_level_nodes[called_function].id\n\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\tcaller=containing_function_id,\n\t\t\t\t\t\t\tcallee=called_function_id,\n\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\tis_resolved=True\n\t\t\t\t\t\t))\n\t\t\t\t\telif receiver_name is not None:\n\t\t\t\t\t\t# A member call whose receiver type could not be\n\t\t\t\t\t\t# resolved: a name matching an STL member here is\n\t\t\t\t\t\t# overwhelmingly likely external, so suppress it.\n\t\t\t\t\t\tif not self._is_system_function(called_function):\n\t\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\t\tcaller=containing_function_id,\n\t\t\t\t\t\t\t\tcallee=called_function,\n\t\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\t\tis_resolved=False\n\t\t\t\t\t\t\t))\n\t\t\t\t\telif (\n\t\t\t\t\t\tnot is_macro_name(called_function)\n\t\t\t\t\t\tand called_function not in self._find_template_parameters(node)\n\t\t\t\t\t):\n\t\t\t\t\t\t# Plain calls are emitted for cross-file resolution;\n\t\t\t\t\t\t# external filtering happens centrally after the\n\t\t\t\t\t\t# project resolver has had its chance.\n\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\tcaller=containing_function_id,\n\t\t\t\t\t\t\tcallee=called_function,\n\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\tis_resolved=False\n\t\t\t\t\t\t))\n\t\t\n\t\telif node.type == \"base_class_clause\":\n\t\t\t# Find the containing class\n\t\t\tcontaining_class = self._find_containing_class(node)\n\t\t\tif containing_class:\n\t\t\t\ttemplate_params = self._find_template_parameters(node)\n\t\t\t\t# Extract base class names\n\t\t\t\tfor child in node.children:\n\t\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\t\tbase_class = child.text.decode()\n\t\t\t\t\t\tif base_class in template_params or is_macro_name(base_class):\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\tcontaining_class_id = self._get_component_id(containing_class)\n\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\tcaller=containing_class_id,\n\t\t\t\t\t\t\tcallee=base_class,\n\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\tis_resolved=False\n\t\t\t\t\t\t))\n\t\t\n\t\telif node.type == \"new_expression\":\n\t\t\tcontaining_function_id = self._find_containing_function_or_method(node, top_level_nodes)\n\t\t\tif containing_function_id:\n\t\t\t\t\n\t\t\t\t# Get the class being instantiated\n\t\t\t\tfor child in node.children:\n\t\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\t\tclass_name = child.text.decode()\n\t\t\t\t\t\tif class_name in top_level_nodes:\n\t\t\t\t\t\t\tclass_id = self._get_component_id(class_name)\n\t\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\t\tcaller=containing_function_id,\n\t\t\t\t\t\t\t\tcallee=class_id,\n\t\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\t\tis_resolved=True\n\t\t\t\t\t\t\t))\n\t\t\t\t\t\tbreak\n\t\t\n\t\telif node.type == \"identifier\":\n\t\t\tparent = node.parent\n\t\t\tif parent and parent.type not in [\"function_definition\", \"class_specifier\", \"declaration\", \"function_declarator\"]:\n\t\t\t\tvar_name = node.text.decode()\n\t\t\t\tif var_name in top_level_nodes and top_level_nodes[var_name].component_type == \"variable\":\n\t\t\t\t\tcontaining_function_id = self._find_containing_function_or_method(node, top_level_nodes)\n\t\t\t\t\tif containing_function_id:\n\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\tcaller=containing_function_id,\n\t\t\t\t\t\t\tcallee=var_name,\n\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\tis_resolved=False\n\t\t\t\t\t\t))\n\t\t\n\t\t# Recursively process children\n\t\tfor child in node.children:\n\t\t\tself._extract_relationships(child, top_level_nodes)", - "start_line": 343, - "end_line": 472, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "top_level_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._extract_relationships", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._extract_relationships", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_field_call_parts": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_field_call_parts", - "name": "TreeSitterCppAnalyzer._get_field_call_parts", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [], - "source_code": "\tdef _get_field_call_parts(self, field_expression) -> tuple[Optional[str], Optional[str]]:\n\t\treceiver_name = None\n\t\tmethod_name = None\n\t\tfor child in field_expression.children:\n\t\t\tif child.type == \"field_identifier\":\n\t\t\t\tmethod_name = child.text.decode()\n\t\t\telif child.type == \"identifier\" and receiver_name is None:\n\t\t\t\treceiver_name = child.text.decode()\n\t\t\telif child.type == \"field_expression\" and receiver_name is None:\n\t\t\t\treceiver_name = child.text.decode().split(\".\")[-1].split(\"->\")[-1]\n\t\treturn receiver_name, method_name", - "start_line": 474, - "end_line": 484, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "field_expression" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._get_field_call_parts", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_field_call_parts", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_variable_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_variable_type", - "name": "TreeSitterCppAnalyzer._find_variable_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._search_variable_declaration", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._search_parameter_declaration" - ], - "source_code": "\tdef _find_variable_type(self, node, variable_name: str) -> Optional[str]:\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type in [\"compound_statement\", \"field_declaration_list\", \"translation_unit\"]:\n\t\t\t\tfound = self._search_variable_declaration(current, variable_name)\n\t\t\t\tif found:\n\t\t\t\t\treturn found\n\t\t\tif current.type == \"function_definition\":\n\t\t\t\tdeclarator = next((c for c in current.children if c.type == \"function_declarator\"), None)\n\t\t\t\tfound = self._search_parameter_declaration(declarator, variable_name)\n\t\t\t\tif found:\n\t\t\t\t\treturn found\n\t\t\tcurrent = current.parent\n\t\treturn None", - "start_line": 486, - "end_line": 499, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "variable_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._find_variable_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_variable_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._search_variable_declaration": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._search_variable_declaration", - "name": "TreeSitterCppAnalyzer._search_variable_declaration", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_declared_variable_name", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._search_variable_declaration", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_declaration_type_name", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_constructor_type_name" - ], - "source_code": "\tdef _search_variable_declaration(self, node, variable_name: str) -> Optional[str]:\n\t\tfor child in node.children:\n\t\t\tif child.type == \"declaration\":\n\t\t\t\ttype_name = self._get_declaration_type_name(child)\n\t\t\t\tdeclared_name = self._get_declared_variable_name(child)\n\t\t\t\tif declared_name == variable_name:\n\t\t\t\t\treturn type_name or self._get_constructor_type_name(child)\n\t\t\tif child.children and child.type not in [\"class_specifier\", \"struct_specifier\", \"function_definition\"]:\n\t\t\t\tfound = self._search_variable_declaration(child, variable_name)\n\t\t\t\tif found:\n\t\t\t\t\treturn found\n\t\treturn None", - "start_line": 501, - "end_line": 512, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "variable_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._search_variable_declaration", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._search_variable_declaration", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._search_parameter_declaration": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._search_parameter_declaration", - "name": "TreeSitterCppAnalyzer._search_parameter_declaration", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_declared_variable_name", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_declaration_type_name", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._search_parameter_declaration" - ], - "source_code": "\tdef _search_parameter_declaration(self, node, variable_name: str) -> Optional[str]:\n\t\tif node is None:\n\t\t\treturn None\n\t\tif node.type == \"parameter_declaration\":\n\t\t\ttype_name = self._get_declaration_type_name(node)\n\t\t\tdeclared_name = self._get_declared_variable_name(node)\n\t\t\tif declared_name == variable_name:\n\t\t\t\treturn type_name\n\t\tfor child in node.children:\n\t\t\tfound = self._search_parameter_declaration(child, variable_name)\n\t\t\tif found:\n\t\t\t\treturn found\n\t\treturn None", - "start_line": 514, - "end_line": 526, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "variable_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._search_parameter_declaration", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._search_parameter_declaration", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_declaration_type_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_declaration_type_name", - "name": "TreeSitterCppAnalyzer._get_declaration_type_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._last_type_part" - ], - "source_code": "\tdef _get_declaration_type_name(self, node) -> Optional[str]:\n\t\tfor child in node.children:\n\t\t\tif child.type in [\"type_identifier\", \"primitive_type\", \"qualified_identifier\"]:\n\t\t\t\treturn self._last_type_part(child.text.decode())\n\t\t\tif child.type in [\"template_type\", \"generic_type\"]:\n\t\t\t\treturn self._last_type_part(child.text.decode().split(\"<\", 1)[0])\n\t\treturn None", - "start_line": 528, - "end_line": 534, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._get_declaration_type_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_declaration_type_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_declared_variable_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_declared_variable_name", - "name": "TreeSitterCppAnalyzer._get_declared_variable_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_declared_variable_name" - ], - "source_code": "\tdef _get_declared_variable_name(self, node) -> Optional[str]:\n\t\tfor child in reversed(node.children):\n\t\t\tif child.type in [\"identifier\", \"field_identifier\"]:\n\t\t\t\treturn child.text.decode()\n\t\t\tif child.type in [\"init_declarator\", \"pointer_declarator\", \"reference_declarator\", \"array_declarator\"]:\n\t\t\t\tname = self._get_declared_variable_name(child)\n\t\t\t\tif name:\n\t\t\t\t\treturn name\n\t\treturn None", - "start_line": 536, - "end_line": 544, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._get_declared_variable_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_declared_variable_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_constructor_type_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_constructor_type_name", - "name": "TreeSitterCppAnalyzer._get_constructor_type_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_constructor_type_name" - ], - "source_code": "\tdef _get_constructor_type_name(self, node) -> Optional[str]:\n\t\tfor child in node.children:\n\t\t\tif child.type == \"call_expression\":\n\t\t\t\tfor call_child in child.children:\n\t\t\t\t\tif call_child.type in [\"identifier\", \"type_identifier\"]:\n\t\t\t\t\t\treturn call_child.text.decode()\n\t\t\tif child.children:\n\t\t\t\tfound = self._get_constructor_type_name(child)\n\t\t\t\tif found:\n\t\t\t\t\treturn found\n\t\treturn None", - "start_line": 546, - "end_line": 556, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._get_constructor_type_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_constructor_type_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._last_type_part": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._last_type_part", - "name": "TreeSitterCppAnalyzer._last_type_part", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [], - "source_code": "\tdef _last_type_part(self, type_name: str) -> str:\n\t\treturn type_name.strip(\"&* \").split(\"::\")[-1]", - "start_line": 558, - "end_line": 559, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "type_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._last_type_part", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._last_type_part", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_containing_function": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_containing_function", - "name": "TreeSitterCppAnalyzer._find_containing_function", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [], - "source_code": "\tdef _find_containing_function(self, node, top_level_nodes):\n\t\t\"\"\"Find the function that contains this node.\"\"\"\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type == \"function_definition\":\n\t\t\t\t# Get function name\n\t\t\t\tdeclarator = next((c for c in current.children if c.type == \"function_declarator\"), None)\n\t\t\t\tif declarator:\n\t\t\t\t\tidentifier = next((c for c in declarator.children if c.type == \"identifier\"), None)\n\t\t\t\t\tif identifier:\n\t\t\t\t\t\tfunc_name = identifier.text.decode()\n\t\t\t\t\t\tif func_name in top_level_nodes:\n\t\t\t\t\t\t\treturn func_name\n\t\t\tcurrent = current.parent\n\t\treturn None", - "start_line": 561, - "end_line": 575, - "has_docstring": true, - "docstring": "Find the function that contains this node.", - "parameters": [ - "self", - "node", - "top_level_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._find_containing_function", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_containing_function", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_containing_function_or_method": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_containing_function_or_method", - "name": "TreeSitterCppAnalyzer._find_containing_function_or_method", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_qualified_declarator_parts", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_declarator_name", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_component_id", - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_containing_class_for_method" - ], - "source_code": "\tdef _find_containing_function_or_method(self, node, top_level_nodes):\n\t\t\"\"\"Find the function or method that contains this node.\"\"\"\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type == \"function_definition\":\n\t\t\t\tdeclarator = next((c for c in current.children if c.type == \"function_declarator\"), None)\n\t\t\t\tif declarator:\n\t\t\t\t\tfunc_name = self._get_declarator_name(declarator)\n\t\t\t\t\tif func_name:\n\t\t\t\t\t\tcontaining_class = self._find_containing_class_for_method(current)\n\t\t\t\t\t\tqualified_parts = self._get_qualified_declarator_parts(declarator)\n\t\t\t\t\t\tif not containing_class and len(qualified_parts) > 1:\n\t\t\t\t\t\t\tcontaining_class = qualified_parts[-2]\n\t\t\t\t\t\tif containing_class:\n\t\t\t\t\t\t\treturn self._get_component_id(func_name, containing_class)\n\t\t\t\t\t\treturn self._get_component_id(func_name)\n\t\t\tcurrent = current.parent\n\t\treturn None", - "start_line": 577, - "end_line": 594, - "has_docstring": true, - "docstring": "Find the function or method that contains this node.", - "parameters": [ - "self", - "node", - "top_level_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._find_containing_function_or_method", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_containing_function_or_method", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_component_id_for_function": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_component_id_for_function", - "name": "TreeSitterCppAnalyzer._get_component_id_for_function", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_component_id" - ], - "source_code": "\tdef _get_component_id_for_function(self, func_name, top_level_nodes):\n\t\tif func_name in top_level_nodes:\n\t\t\tnode_obj = top_level_nodes[func_name]\n\t\t\tif hasattr(node_obj, 'class_name') and node_obj.class_name:\n\t\t\t\treturn self._get_component_id(func_name, node_obj.class_name)\n\t\t\telse:\n\t\t\t\treturn self._get_component_id(func_name)\n\t\treturn self._get_component_id(func_name)", - "start_line": 596, - "end_line": 603, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "func_name", - "top_level_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._get_component_id_for_function", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._get_component_id_for_function", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_containing_class": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_containing_class", - "name": "TreeSitterCppAnalyzer._find_containing_class", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [], - "source_code": "\tdef _find_containing_class(self, node):\n\t\t\"\"\"Find the class that contains this node.\"\"\"\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type == \"class_specifier\":\n\t\t\t\t# Get class name\n\t\t\t\tfor child in current.children:\n\t\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\t\treturn child.text.decode()\n\t\t\tcurrent = current.parent\n\t\treturn None", - "start_line": 605, - "end_line": 615, - "has_docstring": true, - "docstring": "Find the class that contains this node.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._find_containing_class", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_containing_class", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_template_parameters": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_template_parameters", - "name": "TreeSitterCppAnalyzer._find_template_parameters", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [], - "source_code": "\tdef _find_template_parameters(self, node) -> set:\n\t\t\"\"\"Collect template type-parameter names in scope at this node, so a\n\t\treference to `T`/`Char`/... is not reported as an unresolved project\n\t\tsymbol.\"\"\"\n\t\tparams = set()\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type == \"template_declaration\":\n\t\t\t\tparam_list = next(\n\t\t\t\t\t(c for c in current.children if c.type == \"template_parameter_list\"), None\n\t\t\t\t)\n\t\t\t\tif param_list:\n\t\t\t\t\tfor param in param_list.children:\n\t\t\t\t\t\tfor child in getattr(param, \"children\", []):\n\t\t\t\t\t\t\tif child.type == \"type_identifier\":\n\t\t\t\t\t\t\t\tparams.add(child.text.decode())\n\t\t\tcurrent = current.parent\n\t\treturn params", - "start_line": 617, - "end_line": 634, - "has_docstring": true, - "docstring": "Collect template type-parameter names in scope at this node, so a\nreference to `T`/`Char`/... is not reported as an unresolved project\nsymbol.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._find_template_parameters", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_template_parameters", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._is_system_function": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._is_system_function", - "name": "TreeSitterCppAnalyzer._is_system_function", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/utils/external_symbols.py::is_macro_name", - "codewiki/src/be/dependency_analyzer/utils/external_symbols.py::is_external_symbol" - ], - "source_code": "\tdef _is_system_function(self, func_name: str) -> bool:\n\t\t\"\"\"Check if a call target is external rather than a project function.\n\n\t\tBesides the curated standard-library set, an ALL_CAPS callee is treated as\n\t\ta macro invocation: macros are not extracted as components, so a call to\n\t\tone can never resolve to a project function and would otherwise pollute the\n\t\tgraph as unresolved noise. This only affects the unresolved fallback β€”\n\t\treal components in ALL_CAPS (rare in C++) are matched by the earlier\n\t\tresolution branches before this check runs.\n\t\t\"\"\"\n\t\tif is_external_symbol(\"cpp\", func_name):\n\t\t\treturn True\n\t\treturn is_macro_name(func_name)", - "start_line": 636, - "end_line": 648, - "has_docstring": true, - "docstring": "Check if a call target is external rather than a project function.\n\nBesides the curated standard-library set, an ALL_CAPS callee is treated as\na macro invocation: macros are not extracted as components, so a call to\none can never resolve to a project function and would otherwise pollute the\ngraph as unresolved noise. This only affects the unresolved fallback β€”\nreal components in ALL_CAPS (rare in C++) are matched by the earlier\nresolution branches before this check runs.", - "parameters": [ - "self", - "func_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._is_system_function", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._is_system_function", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_method_component": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_method_component", - "name": "TreeSitterCppAnalyzer._find_method_component", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [], - "source_code": "\tdef _find_method_component(self, method_name, top_level_nodes, class_name: str = None):\n\t\tif class_name:\n\t\t\tqualified_key = f\"{class_name}.{method_name}\"\n\t\t\tif qualified_key in top_level_nodes:\n\t\t\t\treturn top_level_nodes[qualified_key].id\n\t\tfor node_obj in top_level_nodes.values():\n\t\t\tif node_obj.component_type == \"method\" and node_obj.name == method_name:\n\t\t\t\treturn node_obj.id\n\t\treturn None", - "start_line": 650, - "end_line": 658, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "method_name", - "top_level_nodes", - "class_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._find_method_component", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_method_component", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_class_containing_method": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_class_containing_method", - "name": "TreeSitterCppAnalyzer._find_class_containing_method", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._class_has_method" - ], - "source_code": "\tdef _find_class_containing_method(self, method_name, top_level_nodes):\n\t\tfor node_name, node_obj in top_level_nodes.items():\n\t\t\tif node_obj.component_type in [\"class\", \"struct\"]:\n\t\t\t\tif self._class_has_method(node_obj, method_name):\n\t\t\t\t\treturn node_name\n\t\treturn None", - "start_line": 660, - "end_line": 665, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "method_name", - "top_level_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._find_class_containing_method", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._find_class_containing_method", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._class_has_method": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._class_has_method", - "name": "TreeSitterCppAnalyzer._class_has_method", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [], - "source_code": "\tdef _class_has_method(self, class_node, method_name):\n\t\tlines = class_node.source_code.split('\\n')\n\t\tfor line in lines:\n\t\t\tif f'{method_name}(' in line and ('void' in line or 'int' in line or 'bool' in line or class_node.name in line):\n\t\t\t\treturn True\n\t\treturn False", - "start_line": 667, - "end_line": 672, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "class_node", - "method_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCppAnalyzer", - "display_name": "method TreeSitterCppAnalyzer._class_has_method", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer._class_has_method", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::analyze_cpp_file": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::analyze_cpp_file", - "name": "analyze_cpp_file", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::TreeSitterCppAnalyzer" - ], - "source_code": "def analyze_cpp_file(file_path: str, content: str, repo_path: str = None) -> Tuple[List[Node], List[CallRelationship]]:\n\tanalyzer = TreeSitterCppAnalyzer(file_path, content, repo_path)\n\treturn analyzer.nodes, analyzer.call_relationships", - "start_line": 674, - "end_line": 676, - "has_docstring": false, - "docstring": "", - "parameters": [ - "file_path", - "content", - "repo_path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function analyze_cpp_file", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/cpp.py::analyze_cpp_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer", - "name": "TreeSitterCSharpAnalyzer", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [], - "source_code": "class TreeSitterCSharpAnalyzer:\n def __init__(self, file_path: str, content: str, repo_path: str = None):\n self.file_path = Path(file_path)\n self.content = content\n self.repo_path = repo_path or \"\"\n self.nodes: List[Node] = []\n self.call_relationships: List[CallRelationship] = []\n self.alias_map: dict[str, str] = {}\n self.using_namespaces: list[str] = []\n self.static_usings: list[str] = []\n self.file_scoped_namespace: str = \"\"\n self._analyze()\n\n def _get_relative_path(self) -> str:\n if self.repo_path:\n try:\n return os.path.relpath(str(self.file_path), self.repo_path)\n except ValueError:\n return str(self.file_path)\n return str(self.file_path)\n\n def _get_component_id(self, name: str) -> str:\n return f\"{self._get_relative_path()}::{name}\"\n\n def _analyze(self):\n language_capsule = tree_sitter_c_sharp.language()\n cs_language = Language(language_capsule)\n parser = Parser(cs_language)\n tree = parser.parse(bytes(self.content, \"utf8\"))\n root = tree.root_node\n lines = self.content.splitlines()\n\n self._extract_usings(root)\n\n top_level_nodes = {}\n self._extract_nodes(root, top_level_nodes, lines)\n self._extract_relationships(root, top_level_nodes)\n\n # ------------------------------------------------------------------ usings\n\n def _extract_usings(self, node):\n \"\"\"Collect ``using`` directives (plain / alias / static) and the\n file-scoped namespace via an AST walk β€” directives can sit inside block\n namespaces and come in several forms that a regex would miss.\"\"\"\n if node.type == \"file_scoped_namespace_declaration\":\n name_node = node.child_by_field_name(\"name\")\n if name_node:\n self.file_scoped_namespace = name_node.text.decode()\n elif node.type == \"using_directive\":\n children = [c for c in node.children if c.type not in (\"using\", \";\", \"global\")]\n has_static = any(c.type == \"static\" for c in node.children)\n has_alias = any(c.type == \"=\" for c in node.children)\n name_children = [c for c in children if c.type in (\"identifier\", \"qualified_name\")]\n if has_alias and len(name_children) >= 2:\n self.alias_map[name_children[0].text.decode()] = name_children[1].text.decode()\n elif has_static and name_children:\n self.static_usings.append(name_children[-1].text.decode())\n elif name_children:\n self.using_namespaces.append(name_children[-1].text.decode())\n\n for child in node.children:\n self._extract_usings(child)\n\n # ------------------------------------------------------------- namespaces\n\n def _namespace_for(self, node) -> str:\n \"\"\"The namespace in scope at ``node``: the file-scoped namespace (if\n any) followed by every enclosing block ``namespace_declaration``.\"\"\"\n parts = []\n current = node\n while current:\n if current.type == \"namespace_declaration\":\n name_node = current.child_by_field_name(\"name\")\n if name_node:\n parts.append(name_node.text.decode())\n current = current.parent\n parts.reverse()\n if self.file_scoped_namespace:\n parts.insert(0, self.file_scoped_namespace)\n return \".\".join(p for p in parts if p)\n\n def _qualify(self, node, *names) -> str:\n ns = self._namespace_for(node)\n parts = [ns] if ns else []\n parts.extend(n for n in names if n)\n return \".\".join(parts)\n\n # ------------------------------------------------------------------ nodes\n\n def _extract_nodes(self, node, top_level_nodes, lines):\n node_type = None\n node_name = None\n qualified_name = None\n class_name = None\n\n if node.type == \"class_declaration\":\n is_abstract = any(c.type == \"modifier\" and c.text.decode() == \"abstract\" for c in node.children)\n is_static = any(c.type == \"modifier\" and c.text.decode() == \"static\" for c in node.children)\n node_type = \"static class\" if is_static else (\"abstract class\" if is_abstract else \"class\")\n node_name = self._decl_name(node)\n qualified_name = self._qualify(node, *self._find_containing_type_names(node), node_name)\n elif node.type == \"interface_declaration\":\n node_type = \"interface\"\n node_name = self._decl_name(node)\n qualified_name = self._qualify(node, *self._find_containing_type_names(node), node_name)\n elif node.type == \"struct_declaration\":\n node_type = \"struct\"\n node_name = self._decl_name(node)\n qualified_name = self._qualify(node, *self._find_containing_type_names(node), node_name)\n elif node.type == \"enum_declaration\":\n node_type = \"enum\"\n node_name = self._decl_name(node)\n qualified_name = self._qualify(node, *self._find_containing_type_names(node), node_name)\n elif node.type == \"record_declaration\":\n is_struct = any(c.type == \"struct\" for c in node.children)\n node_type = \"record struct\" if is_struct else \"record\"\n node_name = self._decl_name(node)\n qualified_name = self._qualify(node, *self._find_containing_type_names(node), node_name)\n elif node.type == \"delegate_declaration\":\n node_type = \"delegate\"\n node_name = self._decl_name(node)\n qualified_name = self._qualify(node, *self._find_containing_type_names(node), node_name)\n elif node.type == \"method_declaration\":\n method_name = self._decl_name(node)\n if method_name:\n node_type = \"method\"\n containing_types = self._find_containing_type_names(node)\n if containing_types:\n class_name = containing_types[-1]\n node_name = f\"{class_name}.{method_name}\"\n qualified_name = self._qualify(node, *containing_types, method_name)\n else:\n node_name = method_name\n qualified_name = self._qualify(node, method_name)\n\n if node_type and node_name:\n component_id = self._get_component_id(node_name)\n has_docstring, docstring = self._extract_doc_comment(node)\n node_obj = Node(\n id=component_id,\n name=node_name,\n component_type=node_type,\n file_path=str(self.file_path),\n relative_path=self._get_relative_path(),\n source_code=\"\\n\".join(lines[node.start_point[0]:node.end_point[0]+1]),\n start_line=node.start_point[0]+1,\n end_line=node.end_point[0]+1,\n has_docstring=has_docstring,\n docstring=docstring,\n parameters=None,\n node_type=node_type,\n base_classes=None,\n class_name=class_name,\n display_name=f\"{node_type} {node_name}\",\n component_id=component_id,\n language=\"csharp\",\n qualified_name=qualified_name,\n )\n self.nodes.append(node_obj)\n top_level_nodes[node_name] = node_obj\n top_level_nodes[component_id] = node_obj\n if qualified_name:\n top_level_nodes[qualified_name] = node_obj\n top_level_nodes.setdefault(qualified_name.split(\".\")[-1], node_obj)\n\n for child in node.children:\n self._extract_nodes(child, top_level_nodes, lines)\n\n def _extract_doc_comment(self, node) -> Tuple[bool, str]:\n \"\"\"Collect a ``///`` XML doc-comment block immediately preceding the\n declaration (skipping any attribute lists between comment and decl).\"\"\"\n comments = []\n sib = node.prev_sibling\n while sib is not None:\n if sib.type == \"attribute_list\":\n sib = sib.prev_sibling\n continue\n if sib.type == \"comment\" and sib.text.decode().lstrip().startswith(\"///\"):\n comments.append(sib.text.decode())\n sib = sib.prev_sibling\n continue\n break\n if not comments:\n return False, \"\"\n comments.reverse()\n cleaned = []\n for c in comments:\n stripped = c.strip()\n if stripped.startswith(\"///\"):\n stripped = stripped[3:].strip()\n cleaned.append(stripped)\n return True, \"\\n\".join(cleaned)\n\n # ---------------------------------------------------------- relationships\n\n def _extract_relationships(self, node, top_level_nodes):\n # 1. Base list β€” extends and/or implements (C# does not distinguish).\n if node.type in _TYPE_DECLS:\n decl_name = self._decl_name(node)\n base_list = next((c for c in node.children if c.type == \"base_list\"), None)\n if decl_name and base_list:\n caller_id = self._get_component_id(decl_name)\n for base_type in self._base_list_types(base_list):\n if not self._skip_type(base_type, node):\n self.call_relationships.append(CallRelationship(\n caller=caller_id,\n callee=self._resolve_cs_type(base_type, node, top_level_nodes),\n call_line=node.start_point[0]+1,\n is_resolved=False,\n ))\n\n # 2. Field / property / event type use + primary-constructor params.\n if node.type == \"field_declaration\":\n self._emit_type_use(self._variable_declaration_type(node), node, top_level_nodes)\n elif node.type == \"event_field_declaration\":\n self._emit_type_use(self._variable_declaration_type(node), node, top_level_nodes)\n elif node.type == \"property_declaration\":\n self._emit_type_use(node.child_by_field_name(\"type\"), node, top_level_nodes)\n elif node.type in (\"class_declaration\", \"struct_declaration\", \"record_declaration\"):\n # Primary constructor parameters (C# 12 / records).\n param_list = next((c for c in node.children if c.type == \"parameter_list\"), None)\n if param_list:\n for param in param_list.children:\n if param.type == \"parameter\":\n self._emit_type_use(param.child_by_field_name(\"type\"), node, top_level_nodes)\n\n # 3. Method / function invocations.\n if node.type == \"invocation_expression\":\n self._handle_invocation(node, top_level_nodes)\n\n # 4. Object creation.\n if node.type == \"object_creation_expression\":\n containing_class = self._find_containing_class(node, top_level_nodes)\n type_node = node.child_by_field_name(\"type\")\n if containing_class and type_node:\n created_type = self._unwrap_type(type_node)\n if created_type and not self._skip_type(created_type, node):\n self.call_relationships.append(CallRelationship(\n caller=containing_class,\n callee=self._resolve_cs_type(created_type, node, top_level_nodes),\n call_line=node.start_point[0]+1,\n is_resolved=False,\n ))\n\n for child in node.children:\n self._extract_relationships(child, top_level_nodes)\n\n def _emit_type_use(self, type_node, context_node, top_level_nodes):\n if type_node is None:\n return\n containing_class = self._find_containing_class(context_node, top_level_nodes)\n if not containing_class:\n return\n type_name = self._unwrap_type(type_node)\n if type_name and not self._skip_type(type_name, context_node):\n self.call_relationships.append(CallRelationship(\n caller=containing_class,\n callee=self._resolve_cs_type(type_name, context_node, top_level_nodes),\n call_line=context_node.start_point[0]+1,\n is_resolved=False,\n ))\n\n def _handle_invocation(self, node, top_level_nodes):\n containing_class = self._find_containing_class(node, top_level_nodes)\n if not containing_class:\n return\n caller_id = self._find_containing_method(node) or containing_class\n\n func = node.child_by_field_name(\"function\")\n if func is None:\n return\n\n method_name = None\n target_type = None\n bare = False\n\n if func.type == \"identifier\":\n method_name = func.text.decode()\n bare = True\n elif func.type == \"member_access_expression\":\n name_node = func.child_by_field_name(\"name\")\n if name_node is None or name_node.type != \"identifier\":\n return\n method_name = name_node.text.decode()\n expr = func.child_by_field_name(\"expression\")\n if expr is None:\n return\n if expr.type == \"this_expression\":\n bare = True\n elif expr.type == \"base_expression\":\n target_type = self._first_base_type(node)\n if target_type is None:\n bare = True\n elif expr.type == \"identifier\":\n receiver = expr.text.decode()\n target_type = self._find_variable_type(node, receiver)\n if not target_type and receiver in top_level_nodes:\n target_type = receiver\n if not target_type and receiver[:1].isupper() and not receiver.isupper():\n # PascalCase receiver with no matching variable reads as a\n # static call on a type from another file or a using; an\n # ALL_CAPS receiver is a constant, not a type.\n target_type = receiver\n else:\n # Chained / qualified receiver (a.B().C(), Outer.Inner.M()).\n return\n else:\n return\n\n if method_name in (None, \"nameof\"):\n return\n\n if bare:\n # A local / inherited member of an enclosing type (same-file nodes\n # match here; cross-file ones resolve later by simple/tail name).\n for candidate in self._enclosing_member_candidates(node, method_name):\n if candidate in top_level_nodes:\n self._add_edge(caller_id, candidate, node)\n return\n # Otherwise it may be a statically-imported member. We cannot know\n # which `using static` it came from, so emit one candidate per static\n # class: the right one resolves cross-file, framework guesses\n # (System.*) are filtered downstream, and a member that exists in no\n # static class simply stays an honest unresolved gap.\n for static_using in self.static_usings:\n self._add_edge(caller_id, f\"{static_using}.{method_name}\", node)\n return\n\n if target_type and not self._skip_type(target_type, node):\n callee = self._resolve_cs_member(method_name, node, top_level_nodes, target_type)\n if callee not in top_level_nodes and method_name in CSHARP_OBJECT_METHODS:\n # Inherited System.Object method the project type does not\n # override locally β€” never a project edge.\n return\n self._add_edge(caller_id, callee, node)\n\n def _add_edge(self, caller, callee, node):\n self.call_relationships.append(CallRelationship(\n caller=caller,\n callee=callee,\n call_line=node.start_point[0]+1,\n is_resolved=False,\n ))\n\n def _enclosing_member_candidates(self, node, member_name):\n containing_types = self._find_containing_type_names(node)\n return [\n self._qualify(node, *containing_types[:idx], member_name)\n for idx in range(len(containing_types), 0, -1)\n ]\n\n # ------------------------------------------------------------ type helpers\n\n def _base_list_types(self, base_list):\n types = []\n for child in base_list.children:\n if child.type in (\"identifier\", \"qualified_name\", \"generic_name\"):\n name = self._unwrap_type(child)\n if name:\n types.append(name)\n elif child.type == \"primary_constructor_base_type\":\n inner = next(\n (c for c in child.children if c.type in (\"identifier\", \"qualified_name\", \"generic_name\")),\n None,\n )\n name = self._unwrap_type(inner) if inner else None\n if name:\n types.append(name)\n return types\n\n def _first_base_type(self, node):\n \"\"\"First base type of the type enclosing ``node`` (for ``base.X()``).\"\"\"\n current = node.parent\n while current:\n if current.type in _TYPE_DECLS:\n base_list = next((c for c in current.children if c.type == \"base_list\"), None)\n if base_list:\n bases = self._base_list_types(base_list)\n return bases[0] if bases else None\n return None\n current = current.parent\n return None\n\n def _variable_declaration_type(self, node):\n vd = next((c for c in node.children if c.type == \"variable_declaration\"), None)\n if vd is None:\n return None\n return self._first_type_child(vd)\n\n def _first_type_child(self, node):\n return next(\n (c for c in node.children if c.type in _TYPE_NODES or c.type == \"implicit_type\"),\n None,\n )\n\n def _unwrap_type(self, node) -> Optional[str]:\n if node is None:\n return None\n if node.type in (\"identifier\", \"qualified_name\", \"predefined_type\"):\n return node.text.decode()\n if node.type == \"generic_name\":\n ident = next((c for c in node.children if c.type == \"identifier\"), None)\n return ident.text.decode() if ident else None\n if node.type in (\"nullable_type\", \"array_type\", \"pointer_type\"):\n inner = node.child_by_field_name(\"type\")\n if inner is None:\n inner = next((c for c in node.children if c.type in _TYPE_NODES), None)\n return self._unwrap_type(inner)\n return None\n\n def _simple_type_name(self, type_name: str) -> str:\n return type_name.strip().split(\"<\", 1)[0].strip()\n\n def _skip_type(self, type_name: str, context_node) -> bool:\n \"\"\"Types that can *never* be a project component: language primitives and\n generic type parameters in scope.\n\n Framework types (``List``, ``Console``, ``Task``...) are deliberately NOT\n filtered here. Doing so at extraction time would drop a real edge whenever\n a project type shadows a framework name (`resolve first, filter second`,\n per the parser audit). Their references are emitted unresolved and the\n cross-file resolver gets first chance; only the still-unresolved ones are\n classified external downstream in ``_is_external_callee``. Alias targets\n are likewise left to ``_resolve_cs_type``, which expands the alias to its\n fully-qualified form so a `using S = System.X;` reference filters\n downstream by its real namespace.\"\"\"\n if not type_name:\n return True\n simple = self._simple_type_name(type_name)\n if simple in _CSHARP_PRIMITIVES:\n return True\n return simple in self._find_type_parameters(context_node)\n\n def _find_type_parameters(self, node) -> set:\n params = set()\n current = node\n while current:\n if current.type in (*_TYPE_DECLS, \"delegate_declaration\", \"method_declaration\", \"local_function_statement\"):\n type_params = next((c for c in current.children if c.type == \"type_parameter_list\"), None)\n if type_params:\n for param in type_params.children:\n if param.type == \"type_parameter\":\n ident = next((c for c in param.children if c.type == \"identifier\"), None)\n if ident:\n params.add(ident.text.decode())\n current = current.parent\n return params\n\n def _resolve_cs_type(self, type_name: str, context_node, top_level_nodes) -> str:\n if not type_name:\n return type_name\n simple = self._simple_type_name(type_name)\n if \".\" in simple:\n return simple\n if simple in self.alias_map:\n return self.alias_map[simple]\n containing_types = self._find_containing_type_names(context_node)\n for idx in range(len(containing_types), 0, -1):\n candidate = self._qualify(context_node, *containing_types[:idx], simple)\n if candidate in top_level_nodes:\n return candidate\n # A `using MyApp.Models;` makes a type in that namespace reachable by its\n # simple name; prefer a known project node there over a bare guess.\n for namespace in self.using_namespaces:\n candidate = f\"{namespace}.{simple}\"\n if candidate in top_level_nodes:\n return candidate\n # Unlike Java, C# has no per-type imports, so the real namespace of an\n # unresolved simple type is unknown. Returning the bare name (rather than\n # fabricating the file's own namespace) lets a genuine project type still\n # match cross-file by its simple/tail name, while a third-party type used\n # via `using SomeLib;` stays unqualified β€” so the resolver's\n # namespace-origin rule can classify `SomeLib.Type.method`-style edges as\n # external instead of mistaking the fabricated namespace for the project.\n return simple\n\n def _resolve_cs_member(self, member_name, context_node, top_level_nodes, target_type) -> str:\n \"\"\"Resolve a member call on a known receiver type to a `Type.member`\n candidate the cross-file resolver can match.\"\"\"\n qualified_type = self._resolve_cs_type(target_type, context_node, top_level_nodes)\n candidate = f\"{qualified_type}.{member_name}\"\n if candidate in top_level_nodes:\n return candidate\n simple_candidate = f\"{qualified_type.split('.')[-1]}.{member_name}\"\n if simple_candidate in top_level_nodes:\n return simple_candidate\n return candidate\n\n # ----------------------------------------------------------- scope lookup\n\n def _decl_name(self, node) -> Optional[str]:\n name_node = node.child_by_field_name(\"name\")\n return name_node.text.decode() if name_node else None\n\n def _find_containing_class(self, node, top_level_nodes):\n current = node.parent\n while current:\n if current.type in _TYPE_DECLS:\n class_name = self._decl_name(current)\n if class_name and class_name in top_level_nodes:\n return self._get_component_id(class_name)\n current = current.parent\n return None\n\n def _find_containing_class_name(self, node):\n names = self._find_containing_type_names(node)\n return names[-1] if names else None\n\n def _find_containing_type_names(self, node) -> list:\n names = []\n current = node.parent\n while current:\n if current.type in _TYPE_DECLS:\n name = self._decl_name(current)\n if name:\n names.append(name)\n current = current.parent\n return list(reversed(names))\n\n def _find_containing_method(self, node):\n current = node.parent\n while current:\n if current.type == \"method_declaration\":\n method_name = self._decl_name(current)\n class_name = self._find_containing_class_name(current)\n if method_name and class_name:\n return self._get_component_id(f\"{class_name}.{method_name}\")\n current = current.parent\n return None\n\n def _find_variable_type(self, node, variable_name):\n # Method / constructor / local-function scope: parameters and locals.\n method_node = node.parent\n while method_node and method_node.type not in (\n \"method_declaration\", \"constructor_declaration\", \"local_function_statement\"\n ):\n method_node = method_node.parent\n\n if method_node:\n param_list = next((c for c in method_node.children if c.type == \"parameter_list\"), None)\n param_type = self._param_type(param_list, variable_name)\n if param_type:\n return param_type\n body = next((c for c in method_node.children if c.type == \"block\"), None)\n if body:\n local_type = self._search_variable_declaration(body, variable_name)\n if local_type:\n return local_type\n\n # Class scope: primary-constructor params, fields, and properties.\n class_node = node.parent\n while class_node and class_node.type not in _TYPE_DECLS:\n class_node = class_node.parent\n\n if class_node:\n param_list = next((c for c in class_node.children if c.type == \"parameter_list\"), None)\n param_type = self._param_type(param_list, variable_name)\n if param_type:\n return param_type\n body = next((c for c in class_node.children if c.type == \"declaration_list\"), None)\n if body:\n for member in body.children:\n if member.type in (\"field_declaration\", \"event_field_declaration\"):\n vd = next((c for c in member.children if c.type == \"variable_declaration\"), None)\n if vd and self._declares_variable(vd, variable_name):\n return self._unwrap_type(self._first_type_child(vd))\n elif member.type == \"property_declaration\":\n name_node = member.child_by_field_name(\"name\")\n if name_node and name_node.text.decode() == variable_name:\n return self._unwrap_type(member.child_by_field_name(\"type\"))\n return None\n\n def _param_type(self, param_list, variable_name):\n if param_list is None:\n return None\n for param in param_list.children:\n if param.type == \"parameter\":\n name_node = param.child_by_field_name(\"name\")\n type_node = param.child_by_field_name(\"type\")\n if name_node and type_node and name_node.text.decode() == variable_name:\n return self._unwrap_type(type_node)\n return None\n\n def _declares_variable(self, variable_declaration, variable_name) -> bool:\n for child in variable_declaration.children:\n if child.type == \"variable_declarator\":\n ident = next((c for c in child.children if c.type == \"identifier\"), None)\n if ident and ident.text.decode() == variable_name:\n return True\n return False\n\n def _search_variable_declaration(self, block_node, variable_name):\n for child in block_node.children:\n if child.type == \"local_declaration_statement\":\n vd = next((c for c in child.children if c.type == \"variable_declaration\"), None)\n if vd is None:\n continue\n type_node = self._first_type_child(vd)\n for decl in vd.children:\n if decl.type != \"variable_declarator\":\n continue\n ident = next((c for c in decl.children if c.type == \"identifier\"), None)\n if not (ident and ident.text.decode() == variable_name):\n continue\n if type_node is not None and type_node.type != \"implicit_type\":\n return self._unwrap_type(type_node)\n # `var` β€” recover the type only from a `new T()` initializer.\n init = next((c for c in decl.children if c.type == \"object_creation_expression\"), None)\n if init is not None:\n return self._unwrap_type(init.child_by_field_name(\"type\"))\n return None\n elif child.type in (\n \"block\", \"if_statement\", \"else_clause\", \"for_statement\",\n \"foreach_statement\", \"while_statement\", \"do_statement\",\n \"using_statement\", \"try_statement\", \"catch_clause\",\n \"finally_clause\", \"switch_statement\", \"lock_statement\",\n \"switch_section\",\n ):\n result = self._search_variable_declaration(child, variable_name)\n if result:\n return result\n return None", - "start_line": 61, - "end_line": 682, - "has_docstring": false, - "docstring": "", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class TreeSitterCSharpAnalyzer", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer.__init__": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer.__init__", - "name": "TreeSitterCSharpAnalyzer.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._analyze" - ], - "source_code": " def __init__(self, file_path: str, content: str, repo_path: str = None):\n self.file_path = Path(file_path)\n self.content = content\n self.repo_path = repo_path or \"\"\n self.nodes: List[Node] = []\n self.call_relationships: List[CallRelationship] = []\n self.alias_map: dict[str, str] = {}\n self.using_namespaces: list[str] = []\n self.static_usings: list[str] = []\n self.file_scoped_namespace: str = \"\"\n self._analyze()", - "start_line": 62, - "end_line": 72, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "file_path", - "content", - "repo_path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer.__init__", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._get_relative_path": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._get_relative_path", - "name": "TreeSitterCSharpAnalyzer._get_relative_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [], - "source_code": " def _get_relative_path(self) -> str:\n if self.repo_path:\n try:\n return os.path.relpath(str(self.file_path), self.repo_path)\n except ValueError:\n return str(self.file_path)\n return str(self.file_path)", - "start_line": 74, - "end_line": 80, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._get_relative_path", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._get_relative_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._get_component_id": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._get_component_id", - "name": "TreeSitterCSharpAnalyzer._get_component_id", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._get_relative_path" - ], - "source_code": " def _get_component_id(self, name: str) -> str:\n return f\"{self._get_relative_path()}::{name}\"", - "start_line": 82, - "end_line": 83, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._get_component_id", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._get_component_id", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._analyze": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._analyze", - "name": "TreeSitterCSharpAnalyzer._analyze", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._extract_relationships", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._extract_usings", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._extract_nodes" - ], - "source_code": " def _analyze(self):\n language_capsule = tree_sitter_c_sharp.language()\n cs_language = Language(language_capsule)\n parser = Parser(cs_language)\n tree = parser.parse(bytes(self.content, \"utf8\"))\n root = tree.root_node\n lines = self.content.splitlines()\n\n self._extract_usings(root)\n\n top_level_nodes = {}\n self._extract_nodes(root, top_level_nodes, lines)\n self._extract_relationships(root, top_level_nodes)", - "start_line": 85, - "end_line": 97, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._analyze", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._analyze", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._extract_usings": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._extract_usings", - "name": "TreeSitterCSharpAnalyzer._extract_usings", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._extract_usings" - ], - "source_code": " def _extract_usings(self, node):\n \"\"\"Collect ``using`` directives (plain / alias / static) and the\n file-scoped namespace via an AST walk β€” directives can sit inside block\n namespaces and come in several forms that a regex would miss.\"\"\"\n if node.type == \"file_scoped_namespace_declaration\":\n name_node = node.child_by_field_name(\"name\")\n if name_node:\n self.file_scoped_namespace = name_node.text.decode()\n elif node.type == \"using_directive\":\n children = [c for c in node.children if c.type not in (\"using\", \";\", \"global\")]\n has_static = any(c.type == \"static\" for c in node.children)\n has_alias = any(c.type == \"=\" for c in node.children)\n name_children = [c for c in children if c.type in (\"identifier\", \"qualified_name\")]\n if has_alias and len(name_children) >= 2:\n self.alias_map[name_children[0].text.decode()] = name_children[1].text.decode()\n elif has_static and name_children:\n self.static_usings.append(name_children[-1].text.decode())\n elif name_children:\n self.using_namespaces.append(name_children[-1].text.decode())\n\n for child in node.children:\n self._extract_usings(child)", - "start_line": 101, - "end_line": 122, - "has_docstring": true, - "docstring": "Collect ``using`` directives (plain / alias / static) and the\nfile-scoped namespace via an AST walk β€” directives can sit inside block\nnamespaces and come in several forms that a regex would miss.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._extract_usings", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._extract_usings", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._namespace_for": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._namespace_for", - "name": "TreeSitterCSharpAnalyzer._namespace_for", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.insert" - ], - "source_code": " def _namespace_for(self, node) -> str:\n \"\"\"The namespace in scope at ``node``: the file-scoped namespace (if\n any) followed by every enclosing block ``namespace_declaration``.\"\"\"\n parts = []\n current = node\n while current:\n if current.type == \"namespace_declaration\":\n name_node = current.child_by_field_name(\"name\")\n if name_node:\n parts.append(name_node.text.decode())\n current = current.parent\n parts.reverse()\n if self.file_scoped_namespace:\n parts.insert(0, self.file_scoped_namespace)\n return \".\".join(p for p in parts if p)", - "start_line": 126, - "end_line": 140, - "has_docstring": true, - "docstring": "The namespace in scope at ``node``: the file-scoped namespace (if\nany) followed by every enclosing block ``namespace_declaration``.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._namespace_for", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._namespace_for", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._qualify": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._qualify", - "name": "TreeSitterCSharpAnalyzer._qualify", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._namespace_for" - ], - "source_code": " def _qualify(self, node, *names) -> str:\n ns = self._namespace_for(node)\n parts = [ns] if ns else []\n parts.extend(n for n in names if n)\n return \".\".join(parts)", - "start_line": 142, - "end_line": 146, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._qualify", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._qualify", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._extract_nodes": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._extract_nodes", - "name": "TreeSitterCSharpAnalyzer._extract_nodes", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._get_component_id", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._qualify", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._decl_name", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._extract_doc_comment", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_type_names", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._get_relative_path", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._extract_nodes" - ], - "source_code": " def _extract_nodes(self, node, top_level_nodes, lines):\n node_type = None\n node_name = None\n qualified_name = None\n class_name = None\n\n if node.type == \"class_declaration\":\n is_abstract = any(c.type == \"modifier\" and c.text.decode() == \"abstract\" for c in node.children)\n is_static = any(c.type == \"modifier\" and c.text.decode() == \"static\" for c in node.children)\n node_type = \"static class\" if is_static else (\"abstract class\" if is_abstract else \"class\")\n node_name = self._decl_name(node)\n qualified_name = self._qualify(node, *self._find_containing_type_names(node), node_name)\n elif node.type == \"interface_declaration\":\n node_type = \"interface\"\n node_name = self._decl_name(node)\n qualified_name = self._qualify(node, *self._find_containing_type_names(node), node_name)\n elif node.type == \"struct_declaration\":\n node_type = \"struct\"\n node_name = self._decl_name(node)\n qualified_name = self._qualify(node, *self._find_containing_type_names(node), node_name)\n elif node.type == \"enum_declaration\":\n node_type = \"enum\"\n node_name = self._decl_name(node)\n qualified_name = self._qualify(node, *self._find_containing_type_names(node), node_name)\n elif node.type == \"record_declaration\":\n is_struct = any(c.type == \"struct\" for c in node.children)\n node_type = \"record struct\" if is_struct else \"record\"\n node_name = self._decl_name(node)\n qualified_name = self._qualify(node, *self._find_containing_type_names(node), node_name)\n elif node.type == \"delegate_declaration\":\n node_type = \"delegate\"\n node_name = self._decl_name(node)\n qualified_name = self._qualify(node, *self._find_containing_type_names(node), node_name)\n elif node.type == \"method_declaration\":\n method_name = self._decl_name(node)\n if method_name:\n node_type = \"method\"\n containing_types = self._find_containing_type_names(node)\n if containing_types:\n class_name = containing_types[-1]\n node_name = f\"{class_name}.{method_name}\"\n qualified_name = self._qualify(node, *containing_types, method_name)\n else:\n node_name = method_name\n qualified_name = self._qualify(node, method_name)\n\n if node_type and node_name:\n component_id = self._get_component_id(node_name)\n has_docstring, docstring = self._extract_doc_comment(node)\n node_obj = Node(\n id=component_id,\n name=node_name,\n component_type=node_type,\n file_path=str(self.file_path),\n relative_path=self._get_relative_path(),\n source_code=\"\\n\".join(lines[node.start_point[0]:node.end_point[0]+1]),\n start_line=node.start_point[0]+1,\n end_line=node.end_point[0]+1,\n has_docstring=has_docstring,\n docstring=docstring,\n parameters=None,\n node_type=node_type,\n base_classes=None,\n class_name=class_name,\n display_name=f\"{node_type} {node_name}\",\n component_id=component_id,\n language=\"csharp\",\n qualified_name=qualified_name,\n )\n self.nodes.append(node_obj)\n top_level_nodes[node_name] = node_obj\n top_level_nodes[component_id] = node_obj\n if qualified_name:\n top_level_nodes[qualified_name] = node_obj\n top_level_nodes.setdefault(qualified_name.split(\".\")[-1], node_obj)\n\n for child in node.children:\n self._extract_nodes(child, top_level_nodes, lines)", - "start_line": 150, - "end_line": 227, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "top_level_nodes", - "lines" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._extract_nodes", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._extract_nodes", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._extract_doc_comment": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._extract_doc_comment", - "name": "TreeSitterCSharpAnalyzer._extract_doc_comment", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [], - "source_code": " def _extract_doc_comment(self, node) -> Tuple[bool, str]:\n \"\"\"Collect a ``///`` XML doc-comment block immediately preceding the\n declaration (skipping any attribute lists between comment and decl).\"\"\"\n comments = []\n sib = node.prev_sibling\n while sib is not None:\n if sib.type == \"attribute_list\":\n sib = sib.prev_sibling\n continue\n if sib.type == \"comment\" and sib.text.decode().lstrip().startswith(\"///\"):\n comments.append(sib.text.decode())\n sib = sib.prev_sibling\n continue\n break\n if not comments:\n return False, \"\"\n comments.reverse()\n cleaned = []\n for c in comments:\n stripped = c.strip()\n if stripped.startswith(\"///\"):\n stripped = stripped[3:].strip()\n cleaned.append(stripped)\n return True, \"\\n\".join(cleaned)", - "start_line": 229, - "end_line": 252, - "has_docstring": true, - "docstring": "Collect a ``///`` XML doc-comment block immediately preceding the\ndeclaration (skipping any attribute lists between comment and decl).", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._extract_doc_comment", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._extract_doc_comment", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._extract_relationships": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._extract_relationships", - "name": "TreeSitterCSharpAnalyzer._extract_relationships", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._handle_invocation", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._get_component_id", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._base_list_types", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._extract_relationships", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._emit_type_use", - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._unwrap_type", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._skip_type", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._decl_name", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_class", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._variable_declaration_type", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._resolve_cs_type" - ], - "source_code": " def _extract_relationships(self, node, top_level_nodes):\n # 1. Base list β€” extends and/or implements (C# does not distinguish).\n if node.type in _TYPE_DECLS:\n decl_name = self._decl_name(node)\n base_list = next((c for c in node.children if c.type == \"base_list\"), None)\n if decl_name and base_list:\n caller_id = self._get_component_id(decl_name)\n for base_type in self._base_list_types(base_list):\n if not self._skip_type(base_type, node):\n self.call_relationships.append(CallRelationship(\n caller=caller_id,\n callee=self._resolve_cs_type(base_type, node, top_level_nodes),\n call_line=node.start_point[0]+1,\n is_resolved=False,\n ))\n\n # 2. Field / property / event type use + primary-constructor params.\n if node.type == \"field_declaration\":\n self._emit_type_use(self._variable_declaration_type(node), node, top_level_nodes)\n elif node.type == \"event_field_declaration\":\n self._emit_type_use(self._variable_declaration_type(node), node, top_level_nodes)\n elif node.type == \"property_declaration\":\n self._emit_type_use(node.child_by_field_name(\"type\"), node, top_level_nodes)\n elif node.type in (\"class_declaration\", \"struct_declaration\", \"record_declaration\"):\n # Primary constructor parameters (C# 12 / records).\n param_list = next((c for c in node.children if c.type == \"parameter_list\"), None)\n if param_list:\n for param in param_list.children:\n if param.type == \"parameter\":\n self._emit_type_use(param.child_by_field_name(\"type\"), node, top_level_nodes)\n\n # 3. Method / function invocations.\n if node.type == \"invocation_expression\":\n self._handle_invocation(node, top_level_nodes)\n\n # 4. Object creation.\n if node.type == \"object_creation_expression\":\n containing_class = self._find_containing_class(node, top_level_nodes)\n type_node = node.child_by_field_name(\"type\")\n if containing_class and type_node:\n created_type = self._unwrap_type(type_node)\n if created_type and not self._skip_type(created_type, node):\n self.call_relationships.append(CallRelationship(\n caller=containing_class,\n callee=self._resolve_cs_type(created_type, node, top_level_nodes),\n call_line=node.start_point[0]+1,\n is_resolved=False,\n ))\n\n for child in node.children:\n self._extract_relationships(child, top_level_nodes)", - "start_line": 256, - "end_line": 306, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "top_level_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._extract_relationships", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._extract_relationships", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._emit_type_use": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._emit_type_use", - "name": "TreeSitterCSharpAnalyzer._emit_type_use", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._unwrap_type", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_class", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._skip_type", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._resolve_cs_type" - ], - "source_code": " def _emit_type_use(self, type_node, context_node, top_level_nodes):\n if type_node is None:\n return\n containing_class = self._find_containing_class(context_node, top_level_nodes)\n if not containing_class:\n return\n type_name = self._unwrap_type(type_node)\n if type_name and not self._skip_type(type_name, context_node):\n self.call_relationships.append(CallRelationship(\n caller=containing_class,\n callee=self._resolve_cs_type(type_name, context_node, top_level_nodes),\n call_line=context_node.start_point[0]+1,\n is_resolved=False,\n ))", - "start_line": 308, - "end_line": 321, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "type_node", - "context_node", - "top_level_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._emit_type_use", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._emit_type_use", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._handle_invocation": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._handle_invocation", - "name": "TreeSitterCSharpAnalyzer._handle_invocation", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._add_edge", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._first_base_type", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._resolve_cs_member", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_variable_type", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_class", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._skip_type", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_method", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._enclosing_member_candidates" - ], - "source_code": " def _handle_invocation(self, node, top_level_nodes):\n containing_class = self._find_containing_class(node, top_level_nodes)\n if not containing_class:\n return\n caller_id = self._find_containing_method(node) or containing_class\n\n func = node.child_by_field_name(\"function\")\n if func is None:\n return\n\n method_name = None\n target_type = None\n bare = False\n\n if func.type == \"identifier\":\n method_name = func.text.decode()\n bare = True\n elif func.type == \"member_access_expression\":\n name_node = func.child_by_field_name(\"name\")\n if name_node is None or name_node.type != \"identifier\":\n return\n method_name = name_node.text.decode()\n expr = func.child_by_field_name(\"expression\")\n if expr is None:\n return\n if expr.type == \"this_expression\":\n bare = True\n elif expr.type == \"base_expression\":\n target_type = self._first_base_type(node)\n if target_type is None:\n bare = True\n elif expr.type == \"identifier\":\n receiver = expr.text.decode()\n target_type = self._find_variable_type(node, receiver)\n if not target_type and receiver in top_level_nodes:\n target_type = receiver\n if not target_type and receiver[:1].isupper() and not receiver.isupper():\n # PascalCase receiver with no matching variable reads as a\n # static call on a type from another file or a using; an\n # ALL_CAPS receiver is a constant, not a type.\n target_type = receiver\n else:\n # Chained / qualified receiver (a.B().C(), Outer.Inner.M()).\n return\n else:\n return\n\n if method_name in (None, \"nameof\"):\n return\n\n if bare:\n # A local / inherited member of an enclosing type (same-file nodes\n # match here; cross-file ones resolve later by simple/tail name).\n for candidate in self._enclosing_member_candidates(node, method_name):\n if candidate in top_level_nodes:\n self._add_edge(caller_id, candidate, node)\n return\n # Otherwise it may be a statically-imported member. We cannot know\n # which `using static` it came from, so emit one candidate per static\n # class: the right one resolves cross-file, framework guesses\n # (System.*) are filtered downstream, and a member that exists in no\n # static class simply stays an honest unresolved gap.\n for static_using in self.static_usings:\n self._add_edge(caller_id, f\"{static_using}.{method_name}\", node)\n return\n\n if target_type and not self._skip_type(target_type, node):\n callee = self._resolve_cs_member(method_name, node, top_level_nodes, target_type)\n if callee not in top_level_nodes and method_name in CSHARP_OBJECT_METHODS:\n # Inherited System.Object method the project type does not\n # override locally β€” never a project edge.\n return\n self._add_edge(caller_id, callee, node)", - "start_line": 323, - "end_line": 395, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "top_level_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._handle_invocation", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._handle_invocation", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._add_edge": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._add_edge", - "name": "TreeSitterCSharpAnalyzer._add_edge", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship" - ], - "source_code": " def _add_edge(self, caller, callee, node):\n self.call_relationships.append(CallRelationship(\n caller=caller,\n callee=callee,\n call_line=node.start_point[0]+1,\n is_resolved=False,\n ))", - "start_line": 397, - "end_line": 403, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "caller", - "callee", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._add_edge", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._add_edge", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._enclosing_member_candidates": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._enclosing_member_candidates", - "name": "TreeSitterCSharpAnalyzer._enclosing_member_candidates", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_type_names", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._qualify" - ], - "source_code": " def _enclosing_member_candidates(self, node, member_name):\n containing_types = self._find_containing_type_names(node)\n return [\n self._qualify(node, *containing_types[:idx], member_name)\n for idx in range(len(containing_types), 0, -1)\n ]", - "start_line": 405, - "end_line": 410, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "member_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._enclosing_member_candidates", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._enclosing_member_candidates", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._base_list_types": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._base_list_types", - "name": "TreeSitterCSharpAnalyzer._base_list_types", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._unwrap_type" - ], - "source_code": " def _base_list_types(self, base_list):\n types = []\n for child in base_list.children:\n if child.type in (\"identifier\", \"qualified_name\", \"generic_name\"):\n name = self._unwrap_type(child)\n if name:\n types.append(name)\n elif child.type == \"primary_constructor_base_type\":\n inner = next(\n (c for c in child.children if c.type in (\"identifier\", \"qualified_name\", \"generic_name\")),\n None,\n )\n name = self._unwrap_type(inner) if inner else None\n if name:\n types.append(name)\n return types", - "start_line": 414, - "end_line": 429, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "base_list" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._base_list_types", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._base_list_types", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._first_base_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._first_base_type", - "name": "TreeSitterCSharpAnalyzer._first_base_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._base_list_types" - ], - "source_code": " def _first_base_type(self, node):\n \"\"\"First base type of the type enclosing ``node`` (for ``base.X()``).\"\"\"\n current = node.parent\n while current:\n if current.type in _TYPE_DECLS:\n base_list = next((c for c in current.children if c.type == \"base_list\"), None)\n if base_list:\n bases = self._base_list_types(base_list)\n return bases[0] if bases else None\n return None\n current = current.parent\n return None", - "start_line": 431, - "end_line": 442, - "has_docstring": true, - "docstring": "First base type of the type enclosing ``node`` (for ``base.X()``).", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._first_base_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._first_base_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._variable_declaration_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._variable_declaration_type", - "name": "TreeSitterCSharpAnalyzer._variable_declaration_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._first_type_child" - ], - "source_code": " def _variable_declaration_type(self, node):\n vd = next((c for c in node.children if c.type == \"variable_declaration\"), None)\n if vd is None:\n return None\n return self._first_type_child(vd)", - "start_line": 444, - "end_line": 448, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._variable_declaration_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._variable_declaration_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._first_type_child": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._first_type_child", - "name": "TreeSitterCSharpAnalyzer._first_type_child", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [], - "source_code": " def _first_type_child(self, node):\n return next(\n (c for c in node.children if c.type in _TYPE_NODES or c.type == \"implicit_type\"),\n None,\n )", - "start_line": 450, - "end_line": 454, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._first_type_child", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._first_type_child", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._unwrap_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._unwrap_type", - "name": "TreeSitterCSharpAnalyzer._unwrap_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._unwrap_type" - ], - "source_code": " def _unwrap_type(self, node) -> Optional[str]:\n if node is None:\n return None\n if node.type in (\"identifier\", \"qualified_name\", \"predefined_type\"):\n return node.text.decode()\n if node.type == \"generic_name\":\n ident = next((c for c in node.children if c.type == \"identifier\"), None)\n return ident.text.decode() if ident else None\n if node.type in (\"nullable_type\", \"array_type\", \"pointer_type\"):\n inner = node.child_by_field_name(\"type\")\n if inner is None:\n inner = next((c for c in node.children if c.type in _TYPE_NODES), None)\n return self._unwrap_type(inner)\n return None", - "start_line": 456, - "end_line": 469, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._unwrap_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._unwrap_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._simple_type_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._simple_type_name", - "name": "TreeSitterCSharpAnalyzer._simple_type_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [], - "source_code": " def _simple_type_name(self, type_name: str) -> str:\n return type_name.strip().split(\"<\", 1)[0].strip()", - "start_line": 471, - "end_line": 472, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "type_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._simple_type_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._simple_type_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._skip_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._skip_type", - "name": "TreeSitterCSharpAnalyzer._skip_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_type_parameters", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._simple_type_name" - ], - "source_code": " def _skip_type(self, type_name: str, context_node) -> bool:\n \"\"\"Types that can *never* be a project component: language primitives and\n generic type parameters in scope.\n\n Framework types (``List``, ``Console``, ``Task``...) are deliberately NOT\n filtered here. Doing so at extraction time would drop a real edge whenever\n a project type shadows a framework name (`resolve first, filter second`,\n per the parser audit). Their references are emitted unresolved and the\n cross-file resolver gets first chance; only the still-unresolved ones are\n classified external downstream in ``_is_external_callee``. Alias targets\n are likewise left to ``_resolve_cs_type``, which expands the alias to its\n fully-qualified form so a `using S = System.X;` reference filters\n downstream by its real namespace.\"\"\"\n if not type_name:\n return True\n simple = self._simple_type_name(type_name)\n if simple in _CSHARP_PRIMITIVES:\n return True\n return simple in self._find_type_parameters(context_node)", - "start_line": 474, - "end_line": 492, - "has_docstring": true, - "docstring": "Types that can *never* be a project component: language primitives and\ngeneric type parameters in scope.\n\nFramework types (``List``, ``Console``, ``Task``...) are deliberately NOT\nfiltered here. Doing so at extraction time would drop a real edge whenever\na project type shadows a framework name (`resolve first, filter second`,\nper the parser audit). Their references are emitted unresolved and the\ncross-file resolver gets first chance; only the still-unresolved ones are\nclassified external downstream in ``_is_external_callee``. Alias targets\nare likewise left to ``_resolve_cs_type``, which expands the alias to its\nfully-qualified form so a `using S = System.X;` reference filters\ndownstream by its real namespace.", - "parameters": [ - "self", - "type_name", - "context_node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._skip_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._skip_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_type_parameters": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_type_parameters", - "name": "TreeSitterCSharpAnalyzer._find_type_parameters", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [], - "source_code": " def _find_type_parameters(self, node) -> set:\n params = set()\n current = node\n while current:\n if current.type in (*_TYPE_DECLS, \"delegate_declaration\", \"method_declaration\", \"local_function_statement\"):\n type_params = next((c for c in current.children if c.type == \"type_parameter_list\"), None)\n if type_params:\n for param in type_params.children:\n if param.type == \"type_parameter\":\n ident = next((c for c in param.children if c.type == \"identifier\"), None)\n if ident:\n params.add(ident.text.decode())\n current = current.parent\n return params", - "start_line": 494, - "end_line": 507, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._find_type_parameters", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_type_parameters", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._resolve_cs_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._resolve_cs_type", - "name": "TreeSitterCSharpAnalyzer._resolve_cs_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_type_names", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._qualify", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._simple_type_name" - ], - "source_code": " def _resolve_cs_type(self, type_name: str, context_node, top_level_nodes) -> str:\n if not type_name:\n return type_name\n simple = self._simple_type_name(type_name)\n if \".\" in simple:\n return simple\n if simple in self.alias_map:\n return self.alias_map[simple]\n containing_types = self._find_containing_type_names(context_node)\n for idx in range(len(containing_types), 0, -1):\n candidate = self._qualify(context_node, *containing_types[:idx], simple)\n if candidate in top_level_nodes:\n return candidate\n # A `using MyApp.Models;` makes a type in that namespace reachable by its\n # simple name; prefer a known project node there over a bare guess.\n for namespace in self.using_namespaces:\n candidate = f\"{namespace}.{simple}\"\n if candidate in top_level_nodes:\n return candidate\n # Unlike Java, C# has no per-type imports, so the real namespace of an\n # unresolved simple type is unknown. Returning the bare name (rather than\n # fabricating the file's own namespace) lets a genuine project type still\n # match cross-file by its simple/tail name, while a third-party type used\n # via `using SomeLib;` stays unqualified β€” so the resolver's\n # namespace-origin rule can classify `SomeLib.Type.method`-style edges as\n # external instead of mistaking the fabricated namespace for the project.\n return simple", - "start_line": 509, - "end_line": 535, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "type_name", - "context_node", - "top_level_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._resolve_cs_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._resolve_cs_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._resolve_cs_member": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._resolve_cs_member", - "name": "TreeSitterCSharpAnalyzer._resolve_cs_member", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._resolve_cs_type" - ], - "source_code": " def _resolve_cs_member(self, member_name, context_node, top_level_nodes, target_type) -> str:\n \"\"\"Resolve a member call on a known receiver type to a `Type.member`\n candidate the cross-file resolver can match.\"\"\"\n qualified_type = self._resolve_cs_type(target_type, context_node, top_level_nodes)\n candidate = f\"{qualified_type}.{member_name}\"\n if candidate in top_level_nodes:\n return candidate\n simple_candidate = f\"{qualified_type.split('.')[-1]}.{member_name}\"\n if simple_candidate in top_level_nodes:\n return simple_candidate\n return candidate", - "start_line": 537, - "end_line": 547, - "has_docstring": true, - "docstring": "Resolve a member call on a known receiver type to a `Type.member`\ncandidate the cross-file resolver can match.", - "parameters": [ - "self", - "member_name", - "context_node", - "top_level_nodes", - "target_type" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._resolve_cs_member", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._resolve_cs_member", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._decl_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._decl_name", - "name": "TreeSitterCSharpAnalyzer._decl_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [], - "source_code": " def _decl_name(self, node) -> Optional[str]:\n name_node = node.child_by_field_name(\"name\")\n return name_node.text.decode() if name_node else None", - "start_line": 551, - "end_line": 553, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._decl_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._decl_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_class": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_class", - "name": "TreeSitterCSharpAnalyzer._find_containing_class", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._get_component_id", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._decl_name" - ], - "source_code": " def _find_containing_class(self, node, top_level_nodes):\n current = node.parent\n while current:\n if current.type in _TYPE_DECLS:\n class_name = self._decl_name(current)\n if class_name and class_name in top_level_nodes:\n return self._get_component_id(class_name)\n current = current.parent\n return None", - "start_line": 555, - "end_line": 563, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "top_level_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._find_containing_class", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_class", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_class_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_class_name", - "name": "TreeSitterCSharpAnalyzer._find_containing_class_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_type_names" - ], - "source_code": " def _find_containing_class_name(self, node):\n names = self._find_containing_type_names(node)\n return names[-1] if names else None", - "start_line": 565, - "end_line": 567, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._find_containing_class_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_class_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_type_names": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_type_names", - "name": "TreeSitterCSharpAnalyzer._find_containing_type_names", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._decl_name" - ], - "source_code": " def _find_containing_type_names(self, node) -> list:\n names = []\n current = node.parent\n while current:\n if current.type in _TYPE_DECLS:\n name = self._decl_name(current)\n if name:\n names.append(name)\n current = current.parent\n return list(reversed(names))", - "start_line": 569, - "end_line": 578, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._find_containing_type_names", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_type_names", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_method": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_method", - "name": "TreeSitterCSharpAnalyzer._find_containing_method", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._get_component_id", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_class_name", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._decl_name" - ], - "source_code": " def _find_containing_method(self, node):\n current = node.parent\n while current:\n if current.type == \"method_declaration\":\n method_name = self._decl_name(current)\n class_name = self._find_containing_class_name(current)\n if method_name and class_name:\n return self._get_component_id(f\"{class_name}.{method_name}\")\n current = current.parent\n return None", - "start_line": 580, - "end_line": 589, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._find_containing_method", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_containing_method", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_variable_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_variable_type", - "name": "TreeSitterCSharpAnalyzer._find_variable_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._first_type_child", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._unwrap_type", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._declares_variable", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._param_type", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._search_variable_declaration" - ], - "source_code": " def _find_variable_type(self, node, variable_name):\n # Method / constructor / local-function scope: parameters and locals.\n method_node = node.parent\n while method_node and method_node.type not in (\n \"method_declaration\", \"constructor_declaration\", \"local_function_statement\"\n ):\n method_node = method_node.parent\n\n if method_node:\n param_list = next((c for c in method_node.children if c.type == \"parameter_list\"), None)\n param_type = self._param_type(param_list, variable_name)\n if param_type:\n return param_type\n body = next((c for c in method_node.children if c.type == \"block\"), None)\n if body:\n local_type = self._search_variable_declaration(body, variable_name)\n if local_type:\n return local_type\n\n # Class scope: primary-constructor params, fields, and properties.\n class_node = node.parent\n while class_node and class_node.type not in _TYPE_DECLS:\n class_node = class_node.parent\n\n if class_node:\n param_list = next((c for c in class_node.children if c.type == \"parameter_list\"), None)\n param_type = self._param_type(param_list, variable_name)\n if param_type:\n return param_type\n body = next((c for c in class_node.children if c.type == \"declaration_list\"), None)\n if body:\n for member in body.children:\n if member.type in (\"field_declaration\", \"event_field_declaration\"):\n vd = next((c for c in member.children if c.type == \"variable_declaration\"), None)\n if vd and self._declares_variable(vd, variable_name):\n return self._unwrap_type(self._first_type_child(vd))\n elif member.type == \"property_declaration\":\n name_node = member.child_by_field_name(\"name\")\n if name_node and name_node.text.decode() == variable_name:\n return self._unwrap_type(member.child_by_field_name(\"type\"))\n return None", - "start_line": 591, - "end_line": 631, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "variable_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._find_variable_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._find_variable_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._param_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._param_type", - "name": "TreeSitterCSharpAnalyzer._param_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._unwrap_type" - ], - "source_code": " def _param_type(self, param_list, variable_name):\n if param_list is None:\n return None\n for param in param_list.children:\n if param.type == \"parameter\":\n name_node = param.child_by_field_name(\"name\")\n type_node = param.child_by_field_name(\"type\")\n if name_node and type_node and name_node.text.decode() == variable_name:\n return self._unwrap_type(type_node)\n return None", - "start_line": 633, - "end_line": 642, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "param_list", - "variable_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._param_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._param_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._declares_variable": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._declares_variable", - "name": "TreeSitterCSharpAnalyzer._declares_variable", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [], - "source_code": " def _declares_variable(self, variable_declaration, variable_name) -> bool:\n for child in variable_declaration.children:\n if child.type == \"variable_declarator\":\n ident = next((c for c in child.children if c.type == \"identifier\"), None)\n if ident and ident.text.decode() == variable_name:\n return True\n return False", - "start_line": 644, - "end_line": 650, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "variable_declaration", - "variable_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._declares_variable", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._declares_variable", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._search_variable_declaration": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._search_variable_declaration", - "name": "TreeSitterCSharpAnalyzer._search_variable_declaration", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._first_type_child", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._search_variable_declaration", - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._unwrap_type" - ], - "source_code": " def _search_variable_declaration(self, block_node, variable_name):\n for child in block_node.children:\n if child.type == \"local_declaration_statement\":\n vd = next((c for c in child.children if c.type == \"variable_declaration\"), None)\n if vd is None:\n continue\n type_node = self._first_type_child(vd)\n for decl in vd.children:\n if decl.type != \"variable_declarator\":\n continue\n ident = next((c for c in decl.children if c.type == \"identifier\"), None)\n if not (ident and ident.text.decode() == variable_name):\n continue\n if type_node is not None and type_node.type != \"implicit_type\":\n return self._unwrap_type(type_node)\n # `var` β€” recover the type only from a `new T()` initializer.\n init = next((c for c in decl.children if c.type == \"object_creation_expression\"), None)\n if init is not None:\n return self._unwrap_type(init.child_by_field_name(\"type\"))\n return None\n elif child.type in (\n \"block\", \"if_statement\", \"else_clause\", \"for_statement\",\n \"foreach_statement\", \"while_statement\", \"do_statement\",\n \"using_statement\", \"try_statement\", \"catch_clause\",\n \"finally_clause\", \"switch_statement\", \"lock_statement\",\n \"switch_section\",\n ):\n result = self._search_variable_declaration(child, variable_name)\n if result:\n return result\n return None", - "start_line": 652, - "end_line": 682, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "block_node", - "variable_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterCSharpAnalyzer", - "display_name": "method TreeSitterCSharpAnalyzer._search_variable_declaration", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer._search_variable_declaration", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::analyze_csharp_file": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::analyze_csharp_file", - "name": "analyze_csharp_file", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::TreeSitterCSharpAnalyzer" - ], - "source_code": "def analyze_csharp_file(file_path: str, content: str, repo_path: str = None) -> Tuple[List[Node], List[CallRelationship]]:\n analyzer = TreeSitterCSharpAnalyzer(file_path, content, repo_path)\n return analyzer.nodes, analyzer.call_relationships", - "start_line": 685, - "end_line": 687, - "has_docstring": false, - "docstring": "", - "parameters": [ - "file_path", - "content", - "repo_path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function analyze_csharp_file", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/csharp.py::analyze_csharp_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer", - "name": "TreeSitterJavaAnalyzer", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [], - "source_code": "class TreeSitterJavaAnalyzer:\n\tdef __init__(self, file_path: str, content: str, repo_path: str = None):\n\t\tself.file_path = Path(file_path)\n\t\tself.content = content\n\t\tself.repo_path = repo_path or \"\"\n\t\tself.nodes: List[Node] = []\n\t\tself.call_relationships: List[CallRelationship] = []\n\t\tself.package_name = self._extract_package_name()\n\t\tself.import_map, self.wildcard_imports = self._extract_imports()\n\t\tself._analyze()\n\t\n\tdef _get_module_path(self) -> str:\n\t\tif self.repo_path:\n\t\t\ttry:\n\t\t\t\trel_path = os.path.relpath(str(self.file_path), self.repo_path)\n\t\t\texcept ValueError:\n\t\t\t\trel_path = str(self.file_path)\n\t\telse:\n\t\t\trel_path = str(self.file_path)\n\t\t\n\t\tfor ext in ['.java']:\n\t\t\tif rel_path.endswith(ext):\n\t\t\t\trel_path = rel_path[:-len(ext)]\n\t\t\t\tbreak\n\t\treturn rel_path.replace('/', '.').replace('\\\\', '.')\n\t\n\tdef _get_relative_path(self) -> str:\n\t\t\"\"\"Get relative path from repo root.\"\"\"\n\t\tif self.repo_path:\n\t\t\ttry:\n\t\t\t\treturn os.path.relpath(str(self.file_path), self.repo_path)\n\t\t\texcept ValueError:\n\t\t\t\treturn str(self.file_path)\n\t\telse:\n\t\t\treturn str(self.file_path)\n\t\n\tdef _get_component_id(self, name: str, parent_class: str = None) -> str:\n\t\trel_path = self._get_relative_path()\n\t\tif parent_class:\n\t\t\treturn f\"{rel_path}::{parent_class}.{name}\"\n\t\telse:\n\t\t\treturn f\"{rel_path}::{name}\"\n\n\tdef _extract_package_name(self) -> str:\n\t\tmatch = re.search(r\"^\\s*package\\s+([\\w.]+)\\s*;\", self.content, re.MULTILINE)\n\t\treturn match.group(1) if match else \"\"\n\n\tdef _extract_imports(self) -> tuple[dict[str, str], list[str]]:\n\t\timport_map: dict[str, str] = {}\n\t\twildcards: list[str] = []\n\t\tfor match in re.finditer(r\"^\\s*import\\s+(?:static\\s+)?([\\w.]+)(\\.\\*)?\\s*;\", self.content, re.MULTILINE):\n\t\t\timport_name = match.group(1)\n\t\t\tif match.group(2):\n\t\t\t\twildcards.append(import_name)\n\t\t\telse:\n\t\t\t\timport_map[import_name.rsplit(\".\", 1)[-1]] = import_name\n\t\treturn import_map, wildcards\n\n\tdef _analyze(self):\n\t\tlanguage_capsule = tree_sitter_java.language()\n\t\tjava_language = Language(language_capsule)\n\t\tparser = Parser(java_language)\n\t\ttree = parser.parse(bytes(self.content, \"utf8\"))\n\t\troot = tree.root_node\n\t\tlines = self.content.splitlines()\n\t\t\n\t\ttop_level_nodes = {}\n\t\t\n\t\tself._extract_nodes(root, top_level_nodes, lines)\n\t\t\n\t\tself._extract_relationships(root, top_level_nodes)\n\t\n\tdef _extract_nodes(self, node, top_level_nodes, lines):\n\t\tnode_type = None\n\t\tnode_name = None\n\t\tqualified_name = None\n\t\tclass_name = None\n\t\t\n\t\tif node.type == \"class_declaration\":\n\t\t\tis_abstract = any(c.type == \"modifier\" and c.text.decode() == \"abstract\" for c in node.children)\n\t\t\tnode_type = \"abstract class\" if is_abstract else \"class\"\n\t\t\tname_node = next((c for c in node.children if c.type == \"identifier\"), None)\n\t\t\tnode_name = name_node.text.decode() if name_node else None\n\t\t\tqualified_name = self._qualified_type_name(node_name, self._find_containing_type_names(node))\n\t\telif node.type == \"interface_declaration\":\n\t\t\tnode_type = \"interface\"\n\t\t\tname_node = next((c for c in node.children if c.type == \"identifier\"), None)\n\t\t\tnode_name = name_node.text.decode() if name_node else None\n\t\t\tqualified_name = self._qualified_type_name(node_name, self._find_containing_type_names(node))\n\t\telif node.type == \"enum_declaration\":\n\t\t\tnode_type = \"enum\"\n\t\t\tname_node = next((c for c in node.children if c.type == \"identifier\"), None)\n\t\t\tnode_name = name_node.text.decode() if name_node else None\n\t\t\tqualified_name = self._qualified_type_name(node_name, self._find_containing_type_names(node))\n\t\telif node.type == \"record_declaration\":\n\t\t\tnode_type = \"record\"\n\t\t\tname_node = next((c for c in node.children if c.type == \"identifier\"), None)\n\t\t\tnode_name = name_node.text.decode() if name_node else None\n\t\t\tqualified_name = self._qualified_type_name(node_name, self._find_containing_type_names(node))\n\t\telif node.type == \"annotation_type_declaration\":\n\t\t\tnode_type = \"annotation\"\n\t\t\tname_node = next((c for c in node.children if c.type == \"identifier\"), None)\n\t\t\tnode_name = name_node.text.decode() if name_node else None\n\t\t\tqualified_name = self._qualified_type_name(node_name, self._find_containing_type_names(node))\n\t\telif node.type == \"method_declaration\":\n\t\t\tnode_type = \"method\"\n\t\t\tname_node = next((c for c in node.children if c.type == \"identifier\"), None)\n\t\t\tif name_node:\n\t\t\t\tmethod_name = name_node.text.decode()\n\t\t\t\tcontaining_types = self._find_containing_type_names(node)\n\t\t\t\tif containing_types:\n\t\t\t\t\tclass_name = containing_types[-1]\n\t\t\t\t\tnode_name = f\"{class_name}.{method_name}\"\n\t\t\t\t\tqualified_name = self._qualified_member_name(containing_types, method_name)\n\t\t\t\telse:\n\t\t\t\t\tnode_name = method_name\n\t\t\t\t\tqualified_name = self._qualify_name(method_name)\n\t\t\n\t\tif node_type and node_name:\n\t\t\tcomponent_id = self._get_component_id(node_name)\n\t\t\trelative_path = self._get_relative_path()\n\t\t\tnode_obj = Node(\n\t\t\t\tid=component_id,\n\t\t\t\tname=node_name,\n\t\t\t\tcomponent_type=node_type,\n\t\t\t\tfile_path=str(self.file_path),\n\t\t\t\trelative_path=relative_path,\n\t\t\t\tsource_code=\"\\n\".join(lines[node.start_point[0]:node.end_point[0]+1]),\n\t\t\t\tstart_line=node.start_point[0]+1,\n\t\t\t\tend_line=node.end_point[0]+1,\n\t\t\t\thas_docstring=False,\n\t\t\t\tdocstring=\"\",\n\t\t\t\tparameters=None,\n\t\t\t\tnode_type=node_type,\n\t\t\t\tbase_classes=None,\n\t\t\t\tclass_name=class_name,\n\t\t\t\tdisplay_name=f\"{node_type} {node_name}\",\n\t\t\t\tcomponent_id=component_id,\n\t\t\t\tlanguage=\"java\",\n\t\t\t\tqualified_name=qualified_name\n\t\t\t)\n\t\t\tself.nodes.append(node_obj)\n\t\t\ttop_level_nodes[node_name] = node_obj\n\t\t\ttop_level_nodes[component_id] = node_obj\n\t\t\tif qualified_name:\n\t\t\t\ttop_level_nodes[qualified_name] = node_obj\n\t\t\t\ttop_level_nodes.setdefault(qualified_name.split(\".\")[-1], node_obj)\n\t\t\n\t\t# Recursively process children\n\t\tfor child in node.children:\n\t\t\tself._extract_nodes(child, top_level_nodes, lines)\n\t\n\tdef _extract_relationships(self, node, top_level_nodes):\n\t\t# 1. Inheritance: Class extends another class\n\t\tif node.type == \"class_declaration\":\n\t\t\tclass_name = self._get_identifier_name(node)\n\t\t\tchildren_types = [c.type for c in node.children]\n\t\t\t\n\t\t\textends_node = next((c for c in node.children if c.type == \"superclass\"), None)\n\t\t\tif extends_node:\n\t\t\t\tbase_class_name = self._get_type_name(extends_node)\n\t\t\t\tif class_name and base_class_name and not self._skip_type(base_class_name, node):\n\t\t\t\t\tcaller_id = self._get_component_id(class_name)\n\t\t\t\t\tcallee_id = self._resolve_java_type(base_class_name, node, top_level_nodes)\n\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\tcaller=caller_id,\n\t\t\t\t\t\tcallee=callee_id, \n\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\tis_resolved=False \n\t\t\t\t\t))\n\t\t\telse:\n\t\t\t\tlogger.debug(f\" No superclass found for {class_name}\")\n\t\t\n\t\t# 2. Interface Implementation: Class/enum/record implements interface\n\t\tif node.type in [\"class_declaration\", \"enum_declaration\", \"record_declaration\"]:\n\t\t\timplementer_name = self._get_identifier_name(node)\n\t\t\timplements_node = next((c for c in node.children if c.type == \"super_interfaces\"), None)\n\t\t\tif implements_node and implementer_name:\n\t\t\t\tfor child in implements_node.children:\n\t\t\t\t\tif child.type == \"type_list\":\n\t\t\t\t\t\tfor type_child in child.children:\n\t\t\t\t\t\t\tif type_child.type in [\"type_identifier\", \"generic_type\"]:\n\t\t\t\t\t\t\t\tinterface_name = self._get_type_name(type_child)\n\t\t\t\t\t\t\t\tif interface_name and not self._skip_type(interface_name, node):\n\t\t\t\t\t\t\t\t\tcaller_id = self._get_component_id(implementer_name)\n\t\t\t\t\t\t\t\t\tcallee_id = self._resolve_java_type(interface_name, node, top_level_nodes)\n\t\t\t\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\t\t\t\tcaller=caller_id,\n\t\t\t\t\t\t\t\t\t\tcallee=callee_id, \n\t\t\t\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\t\t\t\tis_resolved=False\n\t\t\t\t\t\t\t\t\t))\n\t\t\n\t\t# 3. Field Type Use: Class has field of another class/interface type\n\t\tif node.type == \"field_declaration\":\n\t\t\tcontaining_class = self._find_containing_class(node, top_level_nodes)\n\t\t\ttype_node = next((c for c in node.children if c.type in [\"type_identifier\", \"generic_type\"]), None)\n\t\t\tif containing_class and type_node:\n\t\t\t\tfield_type_name = self._get_type_name(type_node)\n\t\t\t\tif field_type_name and not self._skip_type(field_type_name, node):\n\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\tcaller=containing_class,\n\t\t\t\t\t\tcallee=self._resolve_java_type(field_type_name, node, top_level_nodes),\n\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\tis_resolved=False\n\t\t\t\t\t))\n\t\t\n\t\t# 4. Method Calls: Method calls on objects\n\t\tif node.type == \"method_invocation\":\n\t\t\tcontaining_class = self._find_containing_class(node, top_level_nodes)\n\t\t\tcontaining_method = self._find_containing_method(node)\n\t\t\tif containing_class:\n\t\t\t\tobject_name = None\n\t\t\t\tmethod_name = None\n\t\t\t\t\n\t\t\t\tidentifiers = [child.text.decode() for child in node.children if child.type == \"identifier\"]\n\t\t\t\tif len(identifiers) >= 2:\n\t\t\t\t\tobject_name = identifiers[0]\n\t\t\t\t\tmethod_name = identifiers[1]\n\t\t\t\telif identifiers:\n\t\t\t\t\tmethod_name = identifiers[0]\n\t\t\t\t\n\t\t\t\tif method_name:\n\t\t\t\t\ttarget_type = None\n\n\t\t\t\t\tcaller_id = containing_method or containing_class\n\n\t\t\t\t\tif object_name and object_name[:1].isupper() and object_name in top_level_nodes:\n\t\t\t\t\t\ttarget_type = object_name\n\t\t\t\t\telif object_name:\n\t\t\t\t\t\ttarget_type = self._find_variable_type(node, object_name, top_level_nodes)\n\t\t\t\t\t\tif not target_type and object_name in top_level_nodes:\n\t\t\t\t\t\t\ttarget_type = object_name\n\t\t\t\t\t\tif not target_type and object_name[:1].isupper() and not object_name.isupper():\n\t\t\t\t\t\t\t# CamelCase receiver with no matching variable reads\n\t\t\t\t\t\t\t# as a static call on a type from another file or an\n\t\t\t\t\t\t\t# import; ALL_CAPS receivers are constants, not types.\n\t\t\t\t\t\t\ttarget_type = object_name\n\n\t\t\t\t\tif target_type and not self._skip_type(target_type, node):\n\t\t\t\t\t\tcallee = self._resolve_java_member(method_name, node, top_level_nodes, target_type)\n\t\t\t\t\t\tif callee not in top_level_nodes and method_name in JAVA_OBJECT_METHODS:\n\t\t\t\t\t\t\t# Inherited java.lang.Object method that the project\n\t\t\t\t\t\t\t# type does not override locally β€” never a project edge.\n\t\t\t\t\t\t\tcallee = None\n\t\t\t\t\t\tif callee:\n\t\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\t\tcaller=caller_id,\n\t\t\t\t\t\t\t\tcallee=callee,\n\t\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\t\tis_resolved=False\n\t\t\t\t\t\t\t))\n\t\t\t\t\telif not object_name:\n\t\t\t\t\t\tcallee = self._resolve_java_member(method_name, node, top_level_nodes)\n\t\t\t\t\t\tif callee in top_level_nodes or self.import_map.get(method_name) == callee:\n\t\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\t\tcaller=caller_id,\n\t\t\t\t\t\t\t\tcallee=callee,\n\t\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\t\tis_resolved=False\n\t\t\t\t\t\t\t))\n\t\t\n\t\t# 5. Object Creation\n\t\tif node.type == \"object_creation_expression\":\n\t\t\tcontaining_class = self._find_containing_class(node, top_level_nodes)\n\t\t\ttype_node = next((c for c in node.children if c.type in [\"type_identifier\", \"generic_type\"]), None)\n\t\t\tif containing_class and type_node:\n\t\t\t\tcreated_type = self._get_type_name(type_node)\n\t\t\t\tif created_type and not self._skip_type(created_type, node):\n\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\tcaller=containing_class,\n\t\t\t\t\t\t\tcallee=self._resolve_java_type(created_type, node, top_level_nodes),\n\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\tis_resolved=False\n\t\t\t\t\t\t))\n\t\t\n\t\t# Recursively process children\n\t\tfor child in node.children:\n\t\t\tself._extract_relationships(child, top_level_nodes)\n\t\n\tdef _is_primitive_type(self, type_name: str) -> bool:\n\t\t\"\"\"Check if type is a Java primitive or a JDK/runtime type.\"\"\"\n\t\tprimitives = {\n\t\t\t\"boolean\", \"byte\", \"char\", \"double\", \"float\", \"int\", \"long\", \"short\",\n\t\t\t\"void\", \"var\",\n\t\t}\n\t\tsimple = self._simple_type_name(type_name)\n\t\tif simple in primitives:\n\t\t\treturn True\n\t\t# Resolve through the import map first so a runtime type written with its\n\t\t# simple name (imported from a `javax.*`/`java.*` package) is judged by its\n\t\t# fully-qualified origin. The prefix rules in is_external_symbol then\n\t\t# filter JDK/runtime packages, while project types β€” including sibling\n\t\t# packages like `com.other.Bar` β€” fall through and resolve cross-file. This\n\t\t# generalizes JDK filtering to any repository without enumerating types.\n\t\t# java.lang types (no import to consult) are covered by the curated set\n\t\t# inside is_external_symbol.\n\t\tqualified = self.import_map.get(simple)\n\t\tif qualified is None:\n\t\t\t# A wildcard import of a JDK package (`import java.util.*;`) is the\n\t\t\t# only way a JDK type outside java.lang appears with no explicit\n\t\t\t# import; project wildcard packages fall through to resolution.\n\t\t\tfor wildcard in self.wildcard_imports:\n\t\t\t\tif is_external_symbol(\"java\", f\"{wildcard}.{simple}\"):\n\t\t\t\t\treturn True\n\t\t\tqualified = simple\n\t\treturn is_external_symbol(\"java\", qualified)\n\n\tdef _resolve_java_type(self, type_name: str, context_node=None, top_level_nodes=None) -> str:\n\t\tif not type_name:\n\t\t\treturn type_name\n\t\ttype_name = self._simple_type_name(type_name)\n\t\tif \".\" in type_name:\n\t\t\treturn type_name\n\t\tif type_name in self.import_map:\n\t\t\treturn self.import_map[type_name]\n\t\tif context_node is not None and top_level_nodes is not None:\n\t\t\tcontaining_types = self._find_containing_type_names(context_node)\n\t\t\tfor idx in range(len(containing_types), 0, -1):\n\t\t\t\tcandidate = self._qualify_name(\".\".join([*containing_types[:idx], type_name]))\n\t\t\t\tif candidate in top_level_nodes:\n\t\t\t\t\treturn candidate\n\t\tif self.package_name:\n\t\t\treturn f\"{self.package_name}.{type_name}\"\n\t\treturn type_name\n\n\tdef _resolve_java_member(self, member_name: str, context_node, top_level_nodes, target_type: str = None) -> str:\n\t\tif target_type:\n\t\t\tqualified_type = self._resolve_java_type(target_type, context_node, top_level_nodes)\n\t\t\tcandidate = f\"{qualified_type}.{member_name}\"\n\t\t\tif candidate in top_level_nodes:\n\t\t\t\treturn candidate\n\t\t\tsimple_type = qualified_type.split(\".\")[-1]\n\t\t\tsimple_candidate = f\"{simple_type}.{member_name}\"\n\t\t\tif simple_candidate in top_level_nodes:\n\t\t\t\treturn simple_candidate\n\t\t\treturn candidate\n\n\t\tcontaining_types = self._find_containing_type_names(context_node)\n\t\tfor idx in range(len(containing_types), 0, -1):\n\t\t\tcandidate = self._qualified_member_name(containing_types[:idx], member_name)\n\t\t\tif candidate in top_level_nodes:\n\t\t\t\treturn candidate\n\t\t# A static import maps the bare call to its declaring type, whether\n\t\t# project (`com.foo.Util.checkNotNull`) or JDK (`java.util.Objects.requireNonNull`).\n\t\tif member_name in self.import_map:\n\t\t\treturn self.import_map[member_name]\n\t\treturn self._qualify_name(member_name)\n\n\tdef _skip_type(self, type_name: str, context_node) -> bool:\n\t\t\"\"\"Types that can never be project components: primitives, JDK/runtime\n\t\ttypes, and generic type parameters in scope (e.g. the `K`/`V` of an\n\t\tenclosing `class Cache`).\"\"\"\n\t\tif self._is_primitive_type(type_name):\n\t\t\treturn True\n\t\treturn self._simple_type_name(type_name) in self._find_type_parameters(context_node)\n\n\tdef _find_type_parameters(self, node) -> set:\n\t\tparams = set()\n\t\tcurrent = node\n\t\twhile current:\n\t\t\tif current.type in [\n\t\t\t\t\"class_declaration\",\n\t\t\t\t\"interface_declaration\",\n\t\t\t\t\"record_declaration\",\n\t\t\t\t\"method_declaration\",\n\t\t\t]:\n\t\t\t\ttype_parameters = next(\n\t\t\t\t\t(c for c in current.children if c.type == \"type_parameters\"), None\n\t\t\t\t)\n\t\t\t\tif type_parameters:\n\t\t\t\t\tfor param in type_parameters.children:\n\t\t\t\t\t\tif param.type == \"type_parameter\":\n\t\t\t\t\t\t\tfor child in param.children:\n\t\t\t\t\t\t\t\tif child.type in [\"type_identifier\", \"identifier\"]:\n\t\t\t\t\t\t\t\t\tparams.add(child.text.decode())\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\tcurrent = current.parent\n\t\treturn params\n\n\tdef _simple_type_name(self, type_name: str) -> str:\n\t\treturn type_name.strip().split(\"<\", 1)[0].strip()\n\n\tdef _qualify_name(self, name: str) -> str:\n\t\treturn f\"{self.package_name}.{name}\" if self.package_name else name\n\n\tdef _qualified_type_name(self, name: str, containing_types: list[str]) -> str:\n\t\tparts = [*containing_types, name] if name else containing_types\n\t\treturn self._qualify_name(\".\".join(parts)) if parts else \"\"\n\n\tdef _qualified_member_name(self, containing_types: list[str], member_name: str) -> str:\n\t\treturn self._qualify_name(\".\".join([*containing_types, member_name]))\n\t\n\tdef _get_identifier_name(self, node):\n\t\t\"\"\"Get identifier name from a node.\"\"\"\n\t\tname_node = next((c for c in node.children if c.type == \"identifier\"), None)\n\t\treturn name_node.text.decode() if name_node else None\n\t\n\tdef _get_type_name(self, node):\n\t\t\"\"\"Get type name from a type node.\"\"\"\n\t\tif node.type == \"type_identifier\":\n\t\t\treturn node.text.decode()\n\t\telif node.type == \"generic_type\":\n\t\t\ttype_node = next((c for c in node.children if c.type == \"type_identifier\"), None)\n\t\t\treturn type_node.text.decode() if type_node else None\n\t\telif node.type == \"superclass\":\n\t\t\ttype_node = next((c for c in node.children if c.type == \"type_identifier\"), None)\n\t\t\treturn type_node.text.decode() if type_node else None\n\t\treturn None\n\t\n\tdef _find_containing_class(self, node, top_level_nodes):\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type in [\"class_declaration\", \"interface_declaration\", \"enum_declaration\", \"record_declaration\", \"annotation_type_declaration\"]:\n\t\t\t\tclass_name = self._get_identifier_name(current)\n\t\t\t\tif class_name and class_name in top_level_nodes:\n\t\t\t\t\treturn self._get_component_id(class_name) \n\t\t\tcurrent = current.parent\n\t\treturn None\n\t\n\tdef _find_variable_type(self, node, variable_name, top_level_nodes):\n\t\tmethod_node = node.parent\n\t\twhile method_node and method_node.type not in [\"method_declaration\", \"constructor_declaration\"]:\n\t\t\tmethod_node = method_node.parent\n\n\t\tif method_node:\n\t\t\tfor child in method_node.children:\n\t\t\t\tif child.type == \"block\" or child.type == \"constructor_body\":\n\t\t\t\t\tvariable_type = self._search_variable_declaration(child, variable_name)\n\t\t\t\t\tif variable_type:\n\t\t\t\t\t\treturn variable_type\n\t\t\t\telif child.type == \"formal_parameters\":\n\t\t\t\t\tfor param in child.children:\n\t\t\t\t\t\tif param.type in [\"formal_parameter\", \"spread_parameter\"]:\n\t\t\t\t\t\t\ttype_node = next(\n\t\t\t\t\t\t\t\t(c for c in param.children if c.type in [\"type_identifier\", \"generic_type\"]),\n\t\t\t\t\t\t\t\tNone,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tidentifier_node = next(\n\t\t\t\t\t\t\t\t(c for c in param.children if c.type == \"identifier\"), None\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\ttype_node\n\t\t\t\t\t\t\t\tand identifier_node\n\t\t\t\t\t\t\t\tand identifier_node.text.decode() == variable_name\n\t\t\t\t\t\t\t):\n\t\t\t\t\t\t\t\treturn self._get_type_name(type_node)\n\t\t\n\t\tclass_node = node.parent\n\t\twhile class_node and class_node.type != \"class_declaration\":\n\t\t\tclass_node = class_node.parent\n\t\t\t\n\t\tif class_node:\n\t\t\tfor child in class_node.children:\n\t\t\t\tif child.type == \"class_body\":\n\t\t\t\t\tfor body_child in child.children:\n\t\t\t\t\t\tif body_child.type == \"field_declaration\":\n\t\t\t\t\t\t\tidentifier_node = None\n\t\t\t\t\t\t\ttype_node = None\n\t\t\t\t\t\t\tfor field_child in body_child.children:\n\t\t\t\t\t\t\t\tif field_child.type in [\"type_identifier\", \"generic_type\"]:\n\t\t\t\t\t\t\t\t\ttype_node = field_child\n\t\t\t\t\t\t\t\telif field_child.type == \"variable_declarator\":\n\t\t\t\t\t\t\t\t\tidentifier_node = next((c for c in field_child.children if c.type == \"identifier\"), None)\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif identifier_node and type_node and identifier_node.text.decode() == variable_name:\n\t\t\t\t\t\t\t\tfield_type = self._get_type_name(type_node)\n\t\t\t\t\t\t\t\treturn field_type\n\t\t\n\t\treturn None\n\t\n\tdef _search_variable_declaration(self, block_node, variable_name):\n\t\tfor child in block_node.children:\n\t\t\tif child.type == \"local_variable_declaration\":\n\t\t\t\ttype_node = None\n\t\t\t\tidentifier_node = None\n\t\t\t\tfor decl_child in child.children:\n\t\t\t\t\tif decl_child.type in [\"type_identifier\", \"generic_type\"]:\n\t\t\t\t\t\ttype_node = decl_child\n\t\t\t\t\telif decl_child.type == \"variable_declarator\":\n\t\t\t\t\t\tidentifier_node = next((c for c in decl_child.children if c.type == \"identifier\"), None)\n\t\t\t\t\n\t\t\t\tif identifier_node and type_node and identifier_node.text.decode() == variable_name:\n\t\t\t\t\treturn self._get_type_name(type_node)\n\t\t\t\n\t\t\telif child.type == \"block\":\n\t\t\t\tresult = self._search_variable_declaration(child, variable_name)\n\t\t\t\tif result:\n\t\t\t\t\treturn result\n\t\t\n\t\treturn None\n\t\n\tdef _find_containing_class_name(self, node):\n\t\tnames = self._find_containing_type_names(node)\n\t\treturn names[-1] if names else None\n\n\tdef _find_containing_type_names(self, node) -> list[str]:\n\t\tnames = []\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type in [\"class_declaration\", \"interface_declaration\", \"enum_declaration\", \"record_declaration\", \"annotation_type_declaration\"]:\n\t\t\t\tname_node = next((c for c in current.children if c.type == \"identifier\"), None)\n\t\t\t\tif name_node:\n\t\t\t\t\tnames.append(name_node.text.decode())\n\t\t\tcurrent = current.parent\n\t\treturn list(reversed(names))\n\t\n\tdef _find_containing_method(self, node):\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type == \"method_declaration\":\n\t\t\t\tmethod_name = self._get_identifier_name(current)\n\t\t\t\tclass_name = self._find_containing_class_name(current)\n\t\t\t\tif method_name and class_name:\n\t\t\t\t\treturn self._get_component_id(f\"{class_name}.{method_name}\")\n\t\t\tcurrent = current.parent\n\t\treturn None", - "start_line": 18, - "end_line": 534, - "has_docstring": false, - "docstring": "", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class TreeSitterJavaAnalyzer", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer.__init__": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer.__init__", - "name": "TreeSitterJavaAnalyzer.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._extract_package_name", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._analyze", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._extract_imports" - ], - "source_code": "\tdef __init__(self, file_path: str, content: str, repo_path: str = None):\n\t\tself.file_path = Path(file_path)\n\t\tself.content = content\n\t\tself.repo_path = repo_path or \"\"\n\t\tself.nodes: List[Node] = []\n\t\tself.call_relationships: List[CallRelationship] = []\n\t\tself.package_name = self._extract_package_name()\n\t\tself.import_map, self.wildcard_imports = self._extract_imports()\n\t\tself._analyze()", - "start_line": 19, - "end_line": 27, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "file_path", - "content", - "repo_path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer.__init__", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_module_path": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_module_path", - "name": "TreeSitterJavaAnalyzer._get_module_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [], - "source_code": "\tdef _get_module_path(self) -> str:\n\t\tif self.repo_path:\n\t\t\ttry:\n\t\t\t\trel_path = os.path.relpath(str(self.file_path), self.repo_path)\n\t\t\texcept ValueError:\n\t\t\t\trel_path = str(self.file_path)\n\t\telse:\n\t\t\trel_path = str(self.file_path)\n\t\t\n\t\tfor ext in ['.java']:\n\t\t\tif rel_path.endswith(ext):\n\t\t\t\trel_path = rel_path[:-len(ext)]\n\t\t\t\tbreak\n\t\treturn rel_path.replace('/', '.').replace('\\\\', '.')", - "start_line": 29, - "end_line": 42, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._get_module_path", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_module_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_relative_path": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_relative_path", - "name": "TreeSitterJavaAnalyzer._get_relative_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [], - "source_code": "\tdef _get_relative_path(self) -> str:\n\t\t\"\"\"Get relative path from repo root.\"\"\"\n\t\tif self.repo_path:\n\t\t\ttry:\n\t\t\t\treturn os.path.relpath(str(self.file_path), self.repo_path)\n\t\t\texcept ValueError:\n\t\t\t\treturn str(self.file_path)\n\t\telse:\n\t\t\treturn str(self.file_path)", - "start_line": 44, - "end_line": 52, - "has_docstring": true, - "docstring": "Get relative path from repo root.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._get_relative_path", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_relative_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_component_id": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_component_id", - "name": "TreeSitterJavaAnalyzer._get_component_id", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_relative_path" - ], - "source_code": "\tdef _get_component_id(self, name: str, parent_class: str = None) -> str:\n\t\trel_path = self._get_relative_path()\n\t\tif parent_class:\n\t\t\treturn f\"{rel_path}::{parent_class}.{name}\"\n\t\telse:\n\t\t\treturn f\"{rel_path}::{name}\"", - "start_line": 54, - "end_line": 59, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "name", - "parent_class" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._get_component_id", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_component_id", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._extract_package_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._extract_package_name", - "name": "TreeSitterJavaAnalyzer._extract_package_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [], - "source_code": "\tdef _extract_package_name(self) -> str:\n\t\tmatch = re.search(r\"^\\s*package\\s+([\\w.]+)\\s*;\", self.content, re.MULTILINE)\n\t\treturn match.group(1) if match else \"\"", - "start_line": 61, - "end_line": 63, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._extract_package_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._extract_package_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._extract_imports": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._extract_imports", - "name": "TreeSitterJavaAnalyzer._extract_imports", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [], - "source_code": "\tdef _extract_imports(self) -> tuple[dict[str, str], list[str]]:\n\t\timport_map: dict[str, str] = {}\n\t\twildcards: list[str] = []\n\t\tfor match in re.finditer(r\"^\\s*import\\s+(?:static\\s+)?([\\w.]+)(\\.\\*)?\\s*;\", self.content, re.MULTILINE):\n\t\t\timport_name = match.group(1)\n\t\t\tif match.group(2):\n\t\t\t\twildcards.append(import_name)\n\t\t\telse:\n\t\t\t\timport_map[import_name.rsplit(\".\", 1)[-1]] = import_name\n\t\treturn import_map, wildcards", - "start_line": 65, - "end_line": 74, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._extract_imports", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._extract_imports", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._analyze": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._analyze", - "name": "TreeSitterJavaAnalyzer._analyze", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._extract_relationships", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._extract_nodes" - ], - "source_code": "\tdef _analyze(self):\n\t\tlanguage_capsule = tree_sitter_java.language()\n\t\tjava_language = Language(language_capsule)\n\t\tparser = Parser(java_language)\n\t\ttree = parser.parse(bytes(self.content, \"utf8\"))\n\t\troot = tree.root_node\n\t\tlines = self.content.splitlines()\n\t\t\n\t\ttop_level_nodes = {}\n\t\t\n\t\tself._extract_nodes(root, top_level_nodes, lines)\n\t\t\n\t\tself._extract_relationships(root, top_level_nodes)", - "start_line": 76, - "end_line": 88, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._analyze", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._analyze", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._extract_nodes": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._extract_nodes", - "name": "TreeSitterJavaAnalyzer._extract_nodes", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._qualified_member_name", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._qualify_name", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_component_id", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._qualified_type_name", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._extract_nodes", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_relative_path", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_containing_type_names" - ], - "source_code": "\tdef _extract_nodes(self, node, top_level_nodes, lines):\n\t\tnode_type = None\n\t\tnode_name = None\n\t\tqualified_name = None\n\t\tclass_name = None\n\t\t\n\t\tif node.type == \"class_declaration\":\n\t\t\tis_abstract = any(c.type == \"modifier\" and c.text.decode() == \"abstract\" for c in node.children)\n\t\t\tnode_type = \"abstract class\" if is_abstract else \"class\"\n\t\t\tname_node = next((c for c in node.children if c.type == \"identifier\"), None)\n\t\t\tnode_name = name_node.text.decode() if name_node else None\n\t\t\tqualified_name = self._qualified_type_name(node_name, self._find_containing_type_names(node))\n\t\telif node.type == \"interface_declaration\":\n\t\t\tnode_type = \"interface\"\n\t\t\tname_node = next((c for c in node.children if c.type == \"identifier\"), None)\n\t\t\tnode_name = name_node.text.decode() if name_node else None\n\t\t\tqualified_name = self._qualified_type_name(node_name, self._find_containing_type_names(node))\n\t\telif node.type == \"enum_declaration\":\n\t\t\tnode_type = \"enum\"\n\t\t\tname_node = next((c for c in node.children if c.type == \"identifier\"), None)\n\t\t\tnode_name = name_node.text.decode() if name_node else None\n\t\t\tqualified_name = self._qualified_type_name(node_name, self._find_containing_type_names(node))\n\t\telif node.type == \"record_declaration\":\n\t\t\tnode_type = \"record\"\n\t\t\tname_node = next((c for c in node.children if c.type == \"identifier\"), None)\n\t\t\tnode_name = name_node.text.decode() if name_node else None\n\t\t\tqualified_name = self._qualified_type_name(node_name, self._find_containing_type_names(node))\n\t\telif node.type == \"annotation_type_declaration\":\n\t\t\tnode_type = \"annotation\"\n\t\t\tname_node = next((c for c in node.children if c.type == \"identifier\"), None)\n\t\t\tnode_name = name_node.text.decode() if name_node else None\n\t\t\tqualified_name = self._qualified_type_name(node_name, self._find_containing_type_names(node))\n\t\telif node.type == \"method_declaration\":\n\t\t\tnode_type = \"method\"\n\t\t\tname_node = next((c for c in node.children if c.type == \"identifier\"), None)\n\t\t\tif name_node:\n\t\t\t\tmethod_name = name_node.text.decode()\n\t\t\t\tcontaining_types = self._find_containing_type_names(node)\n\t\t\t\tif containing_types:\n\t\t\t\t\tclass_name = containing_types[-1]\n\t\t\t\t\tnode_name = f\"{class_name}.{method_name}\"\n\t\t\t\t\tqualified_name = self._qualified_member_name(containing_types, method_name)\n\t\t\t\telse:\n\t\t\t\t\tnode_name = method_name\n\t\t\t\t\tqualified_name = self._qualify_name(method_name)\n\t\t\n\t\tif node_type and node_name:\n\t\t\tcomponent_id = self._get_component_id(node_name)\n\t\t\trelative_path = self._get_relative_path()\n\t\t\tnode_obj = Node(\n\t\t\t\tid=component_id,\n\t\t\t\tname=node_name,\n\t\t\t\tcomponent_type=node_type,\n\t\t\t\tfile_path=str(self.file_path),\n\t\t\t\trelative_path=relative_path,\n\t\t\t\tsource_code=\"\\n\".join(lines[node.start_point[0]:node.end_point[0]+1]),\n\t\t\t\tstart_line=node.start_point[0]+1,\n\t\t\t\tend_line=node.end_point[0]+1,\n\t\t\t\thas_docstring=False,\n\t\t\t\tdocstring=\"\",\n\t\t\t\tparameters=None,\n\t\t\t\tnode_type=node_type,\n\t\t\t\tbase_classes=None,\n\t\t\t\tclass_name=class_name,\n\t\t\t\tdisplay_name=f\"{node_type} {node_name}\",\n\t\t\t\tcomponent_id=component_id,\n\t\t\t\tlanguage=\"java\",\n\t\t\t\tqualified_name=qualified_name\n\t\t\t)\n\t\t\tself.nodes.append(node_obj)\n\t\t\ttop_level_nodes[node_name] = node_obj\n\t\t\ttop_level_nodes[component_id] = node_obj\n\t\t\tif qualified_name:\n\t\t\t\ttop_level_nodes[qualified_name] = node_obj\n\t\t\t\ttop_level_nodes.setdefault(qualified_name.split(\".\")[-1], node_obj)\n\t\t\n\t\t# Recursively process children\n\t\tfor child in node.children:\n\t\t\tself._extract_nodes(child, top_level_nodes, lines)", - "start_line": 90, - "end_line": 168, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "top_level_nodes", - "lines" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._extract_nodes", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._extract_nodes", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._extract_relationships": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._extract_relationships", - "name": "TreeSitterJavaAnalyzer._extract_relationships", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_containing_class", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_identifier_name", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_component_id", - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._extract_relationships", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_containing_method", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._resolve_java_type", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_type_name", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_variable_type", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._resolve_java_member", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._skip_type" - ], - "source_code": "\tdef _extract_relationships(self, node, top_level_nodes):\n\t\t# 1. Inheritance: Class extends another class\n\t\tif node.type == \"class_declaration\":\n\t\t\tclass_name = self._get_identifier_name(node)\n\t\t\tchildren_types = [c.type for c in node.children]\n\t\t\t\n\t\t\textends_node = next((c for c in node.children if c.type == \"superclass\"), None)\n\t\t\tif extends_node:\n\t\t\t\tbase_class_name = self._get_type_name(extends_node)\n\t\t\t\tif class_name and base_class_name and not self._skip_type(base_class_name, node):\n\t\t\t\t\tcaller_id = self._get_component_id(class_name)\n\t\t\t\t\tcallee_id = self._resolve_java_type(base_class_name, node, top_level_nodes)\n\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\tcaller=caller_id,\n\t\t\t\t\t\tcallee=callee_id, \n\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\tis_resolved=False \n\t\t\t\t\t))\n\t\t\telse:\n\t\t\t\tlogger.debug(f\" No superclass found for {class_name}\")\n\t\t\n\t\t# 2. Interface Implementation: Class/enum/record implements interface\n\t\tif node.type in [\"class_declaration\", \"enum_declaration\", \"record_declaration\"]:\n\t\t\timplementer_name = self._get_identifier_name(node)\n\t\t\timplements_node = next((c for c in node.children if c.type == \"super_interfaces\"), None)\n\t\t\tif implements_node and implementer_name:\n\t\t\t\tfor child in implements_node.children:\n\t\t\t\t\tif child.type == \"type_list\":\n\t\t\t\t\t\tfor type_child in child.children:\n\t\t\t\t\t\t\tif type_child.type in [\"type_identifier\", \"generic_type\"]:\n\t\t\t\t\t\t\t\tinterface_name = self._get_type_name(type_child)\n\t\t\t\t\t\t\t\tif interface_name and not self._skip_type(interface_name, node):\n\t\t\t\t\t\t\t\t\tcaller_id = self._get_component_id(implementer_name)\n\t\t\t\t\t\t\t\t\tcallee_id = self._resolve_java_type(interface_name, node, top_level_nodes)\n\t\t\t\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\t\t\t\tcaller=caller_id,\n\t\t\t\t\t\t\t\t\t\tcallee=callee_id, \n\t\t\t\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\t\t\t\tis_resolved=False\n\t\t\t\t\t\t\t\t\t))\n\t\t\n\t\t# 3. Field Type Use: Class has field of another class/interface type\n\t\tif node.type == \"field_declaration\":\n\t\t\tcontaining_class = self._find_containing_class(node, top_level_nodes)\n\t\t\ttype_node = next((c for c in node.children if c.type in [\"type_identifier\", \"generic_type\"]), None)\n\t\t\tif containing_class and type_node:\n\t\t\t\tfield_type_name = self._get_type_name(type_node)\n\t\t\t\tif field_type_name and not self._skip_type(field_type_name, node):\n\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\tcaller=containing_class,\n\t\t\t\t\t\tcallee=self._resolve_java_type(field_type_name, node, top_level_nodes),\n\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\tis_resolved=False\n\t\t\t\t\t))\n\t\t\n\t\t# 4. Method Calls: Method calls on objects\n\t\tif node.type == \"method_invocation\":\n\t\t\tcontaining_class = self._find_containing_class(node, top_level_nodes)\n\t\t\tcontaining_method = self._find_containing_method(node)\n\t\t\tif containing_class:\n\t\t\t\tobject_name = None\n\t\t\t\tmethod_name = None\n\t\t\t\t\n\t\t\t\tidentifiers = [child.text.decode() for child in node.children if child.type == \"identifier\"]\n\t\t\t\tif len(identifiers) >= 2:\n\t\t\t\t\tobject_name = identifiers[0]\n\t\t\t\t\tmethod_name = identifiers[1]\n\t\t\t\telif identifiers:\n\t\t\t\t\tmethod_name = identifiers[0]\n\t\t\t\t\n\t\t\t\tif method_name:\n\t\t\t\t\ttarget_type = None\n\n\t\t\t\t\tcaller_id = containing_method or containing_class\n\n\t\t\t\t\tif object_name and object_name[:1].isupper() and object_name in top_level_nodes:\n\t\t\t\t\t\ttarget_type = object_name\n\t\t\t\t\telif object_name:\n\t\t\t\t\t\ttarget_type = self._find_variable_type(node, object_name, top_level_nodes)\n\t\t\t\t\t\tif not target_type and object_name in top_level_nodes:\n\t\t\t\t\t\t\ttarget_type = object_name\n\t\t\t\t\t\tif not target_type and object_name[:1].isupper() and not object_name.isupper():\n\t\t\t\t\t\t\t# CamelCase receiver with no matching variable reads\n\t\t\t\t\t\t\t# as a static call on a type from another file or an\n\t\t\t\t\t\t\t# import; ALL_CAPS receivers are constants, not types.\n\t\t\t\t\t\t\ttarget_type = object_name\n\n\t\t\t\t\tif target_type and not self._skip_type(target_type, node):\n\t\t\t\t\t\tcallee = self._resolve_java_member(method_name, node, top_level_nodes, target_type)\n\t\t\t\t\t\tif callee not in top_level_nodes and method_name in JAVA_OBJECT_METHODS:\n\t\t\t\t\t\t\t# Inherited java.lang.Object method that the project\n\t\t\t\t\t\t\t# type does not override locally β€” never a project edge.\n\t\t\t\t\t\t\tcallee = None\n\t\t\t\t\t\tif callee:\n\t\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\t\tcaller=caller_id,\n\t\t\t\t\t\t\t\tcallee=callee,\n\t\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\t\tis_resolved=False\n\t\t\t\t\t\t\t))\n\t\t\t\t\telif not object_name:\n\t\t\t\t\t\tcallee = self._resolve_java_member(method_name, node, top_level_nodes)\n\t\t\t\t\t\tif callee in top_level_nodes or self.import_map.get(method_name) == callee:\n\t\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\t\tcaller=caller_id,\n\t\t\t\t\t\t\t\tcallee=callee,\n\t\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\t\tis_resolved=False\n\t\t\t\t\t\t\t))\n\t\t\n\t\t# 5. Object Creation\n\t\tif node.type == \"object_creation_expression\":\n\t\t\tcontaining_class = self._find_containing_class(node, top_level_nodes)\n\t\t\ttype_node = next((c for c in node.children if c.type in [\"type_identifier\", \"generic_type\"]), None)\n\t\t\tif containing_class and type_node:\n\t\t\t\tcreated_type = self._get_type_name(type_node)\n\t\t\t\tif created_type and not self._skip_type(created_type, node):\n\t\t\t\t\t\tself.call_relationships.append(CallRelationship(\n\t\t\t\t\t\t\tcaller=containing_class,\n\t\t\t\t\t\t\tcallee=self._resolve_java_type(created_type, node, top_level_nodes),\n\t\t\t\t\t\t\tcall_line=node.start_point[0]+1,\n\t\t\t\t\t\t\tis_resolved=False\n\t\t\t\t\t\t))\n\t\t\n\t\t# Recursively process children\n\t\tfor child in node.children:\n\t\t\tself._extract_relationships(child, top_level_nodes)", - "start_line": 170, - "end_line": 296, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "top_level_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._extract_relationships", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._extract_relationships", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._is_primitive_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._is_primitive_type", - "name": "TreeSitterJavaAnalyzer._is_primitive_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._simple_type_name", - "codewiki/src/be/dependency_analyzer/utils/external_symbols.py::is_external_symbol" - ], - "source_code": "\tdef _is_primitive_type(self, type_name: str) -> bool:\n\t\t\"\"\"Check if type is a Java primitive or a JDK/runtime type.\"\"\"\n\t\tprimitives = {\n\t\t\t\"boolean\", \"byte\", \"char\", \"double\", \"float\", \"int\", \"long\", \"short\",\n\t\t\t\"void\", \"var\",\n\t\t}\n\t\tsimple = self._simple_type_name(type_name)\n\t\tif simple in primitives:\n\t\t\treturn True\n\t\t# Resolve through the import map first so a runtime type written with its\n\t\t# simple name (imported from a `javax.*`/`java.*` package) is judged by its\n\t\t# fully-qualified origin. The prefix rules in is_external_symbol then\n\t\t# filter JDK/runtime packages, while project types β€” including sibling\n\t\t# packages like `com.other.Bar` β€” fall through and resolve cross-file. This\n\t\t# generalizes JDK filtering to any repository without enumerating types.\n\t\t# java.lang types (no import to consult) are covered by the curated set\n\t\t# inside is_external_symbol.\n\t\tqualified = self.import_map.get(simple)\n\t\tif qualified is None:\n\t\t\t# A wildcard import of a JDK package (`import java.util.*;`) is the\n\t\t\t# only way a JDK type outside java.lang appears with no explicit\n\t\t\t# import; project wildcard packages fall through to resolution.\n\t\t\tfor wildcard in self.wildcard_imports:\n\t\t\t\tif is_external_symbol(\"java\", f\"{wildcard}.{simple}\"):\n\t\t\t\t\treturn True\n\t\t\tqualified = simple\n\t\treturn is_external_symbol(\"java\", qualified)", - "start_line": 298, - "end_line": 324, - "has_docstring": true, - "docstring": "Check if type is a Java primitive or a JDK/runtime type.", - "parameters": [ - "self", - "type_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._is_primitive_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._is_primitive_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._resolve_java_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._resolve_java_type", - "name": "TreeSitterJavaAnalyzer._resolve_java_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._qualify_name", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._simple_type_name", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_containing_type_names" - ], - "source_code": "\tdef _resolve_java_type(self, type_name: str, context_node=None, top_level_nodes=None) -> str:\n\t\tif not type_name:\n\t\t\treturn type_name\n\t\ttype_name = self._simple_type_name(type_name)\n\t\tif \".\" in type_name:\n\t\t\treturn type_name\n\t\tif type_name in self.import_map:\n\t\t\treturn self.import_map[type_name]\n\t\tif context_node is not None and top_level_nodes is not None:\n\t\t\tcontaining_types = self._find_containing_type_names(context_node)\n\t\t\tfor idx in range(len(containing_types), 0, -1):\n\t\t\t\tcandidate = self._qualify_name(\".\".join([*containing_types[:idx], type_name]))\n\t\t\t\tif candidate in top_level_nodes:\n\t\t\t\t\treturn candidate\n\t\tif self.package_name:\n\t\t\treturn f\"{self.package_name}.{type_name}\"\n\t\treturn type_name", - "start_line": 326, - "end_line": 342, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "type_name", - "context_node", - "top_level_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._resolve_java_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._resolve_java_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._resolve_java_member": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._resolve_java_member", - "name": "TreeSitterJavaAnalyzer._resolve_java_member", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._resolve_java_type", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._qualified_member_name", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._qualify_name", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_containing_type_names" - ], - "source_code": "\tdef _resolve_java_member(self, member_name: str, context_node, top_level_nodes, target_type: str = None) -> str:\n\t\tif target_type:\n\t\t\tqualified_type = self._resolve_java_type(target_type, context_node, top_level_nodes)\n\t\t\tcandidate = f\"{qualified_type}.{member_name}\"\n\t\t\tif candidate in top_level_nodes:\n\t\t\t\treturn candidate\n\t\t\tsimple_type = qualified_type.split(\".\")[-1]\n\t\t\tsimple_candidate = f\"{simple_type}.{member_name}\"\n\t\t\tif simple_candidate in top_level_nodes:\n\t\t\t\treturn simple_candidate\n\t\t\treturn candidate\n\n\t\tcontaining_types = self._find_containing_type_names(context_node)\n\t\tfor idx in range(len(containing_types), 0, -1):\n\t\t\tcandidate = self._qualified_member_name(containing_types[:idx], member_name)\n\t\t\tif candidate in top_level_nodes:\n\t\t\t\treturn candidate\n\t\t# A static import maps the bare call to its declaring type, whether\n\t\t# project (`com.foo.Util.checkNotNull`) or JDK (`java.util.Objects.requireNonNull`).\n\t\tif member_name in self.import_map:\n\t\t\treturn self.import_map[member_name]\n\t\treturn self._qualify_name(member_name)", - "start_line": 344, - "end_line": 365, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "member_name", - "context_node", - "top_level_nodes", - "target_type" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._resolve_java_member", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._resolve_java_member", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._skip_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._skip_type", - "name": "TreeSitterJavaAnalyzer._skip_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._simple_type_name", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_type_parameters", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._is_primitive_type" - ], - "source_code": "\tdef _skip_type(self, type_name: str, context_node) -> bool:\n\t\t\"\"\"Types that can never be project components: primitives, JDK/runtime\n\t\ttypes, and generic type parameters in scope (e.g. the `K`/`V` of an\n\t\tenclosing `class Cache`).\"\"\"\n\t\tif self._is_primitive_type(type_name):\n\t\t\treturn True\n\t\treturn self._simple_type_name(type_name) in self._find_type_parameters(context_node)", - "start_line": 367, - "end_line": 373, - "has_docstring": true, - "docstring": "Types that can never be project components: primitives, JDK/runtime\ntypes, and generic type parameters in scope (e.g. the `K`/`V` of an\nenclosing `class Cache`).", - "parameters": [ - "self", - "type_name", - "context_node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._skip_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._skip_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_type_parameters": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_type_parameters", - "name": "TreeSitterJavaAnalyzer._find_type_parameters", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [], - "source_code": "\tdef _find_type_parameters(self, node) -> set:\n\t\tparams = set()\n\t\tcurrent = node\n\t\twhile current:\n\t\t\tif current.type in [\n\t\t\t\t\"class_declaration\",\n\t\t\t\t\"interface_declaration\",\n\t\t\t\t\"record_declaration\",\n\t\t\t\t\"method_declaration\",\n\t\t\t]:\n\t\t\t\ttype_parameters = next(\n\t\t\t\t\t(c for c in current.children if c.type == \"type_parameters\"), None\n\t\t\t\t)\n\t\t\t\tif type_parameters:\n\t\t\t\t\tfor param in type_parameters.children:\n\t\t\t\t\t\tif param.type == \"type_parameter\":\n\t\t\t\t\t\t\tfor child in param.children:\n\t\t\t\t\t\t\t\tif child.type in [\"type_identifier\", \"identifier\"]:\n\t\t\t\t\t\t\t\t\tparams.add(child.text.decode())\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\tcurrent = current.parent\n\t\treturn params", - "start_line": 375, - "end_line": 396, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._find_type_parameters", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_type_parameters", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._simple_type_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._simple_type_name", - "name": "TreeSitterJavaAnalyzer._simple_type_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [], - "source_code": "\tdef _simple_type_name(self, type_name: str) -> str:\n\t\treturn type_name.strip().split(\"<\", 1)[0].strip()", - "start_line": 398, - "end_line": 399, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "type_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._simple_type_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._simple_type_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._qualify_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._qualify_name", - "name": "TreeSitterJavaAnalyzer._qualify_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [], - "source_code": "\tdef _qualify_name(self, name: str) -> str:\n\t\treturn f\"{self.package_name}.{name}\" if self.package_name else name", - "start_line": 401, - "end_line": 402, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._qualify_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._qualify_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._qualified_type_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._qualified_type_name", - "name": "TreeSitterJavaAnalyzer._qualified_type_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._qualify_name" - ], - "source_code": "\tdef _qualified_type_name(self, name: str, containing_types: list[str]) -> str:\n\t\tparts = [*containing_types, name] if name else containing_types\n\t\treturn self._qualify_name(\".\".join(parts)) if parts else \"\"", - "start_line": 404, - "end_line": 406, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "name", - "containing_types" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._qualified_type_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._qualified_type_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._qualified_member_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._qualified_member_name", - "name": "TreeSitterJavaAnalyzer._qualified_member_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._qualify_name" - ], - "source_code": "\tdef _qualified_member_name(self, containing_types: list[str], member_name: str) -> str:\n\t\treturn self._qualify_name(\".\".join([*containing_types, member_name]))", - "start_line": 408, - "end_line": 409, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "containing_types", - "member_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._qualified_member_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._qualified_member_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_identifier_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_identifier_name", - "name": "TreeSitterJavaAnalyzer._get_identifier_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [], - "source_code": "\tdef _get_identifier_name(self, node):\n\t\t\"\"\"Get identifier name from a node.\"\"\"\n\t\tname_node = next((c for c in node.children if c.type == \"identifier\"), None)\n\t\treturn name_node.text.decode() if name_node else None", - "start_line": 411, - "end_line": 414, - "has_docstring": true, - "docstring": "Get identifier name from a node.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._get_identifier_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_identifier_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_type_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_type_name", - "name": "TreeSitterJavaAnalyzer._get_type_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [], - "source_code": "\tdef _get_type_name(self, node):\n\t\t\"\"\"Get type name from a type node.\"\"\"\n\t\tif node.type == \"type_identifier\":\n\t\t\treturn node.text.decode()\n\t\telif node.type == \"generic_type\":\n\t\t\ttype_node = next((c for c in node.children if c.type == \"type_identifier\"), None)\n\t\t\treturn type_node.text.decode() if type_node else None\n\t\telif node.type == \"superclass\":\n\t\t\ttype_node = next((c for c in node.children if c.type == \"type_identifier\"), None)\n\t\t\treturn type_node.text.decode() if type_node else None\n\t\treturn None", - "start_line": 416, - "end_line": 426, - "has_docstring": true, - "docstring": "Get type name from a type node.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._get_type_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_type_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_containing_class": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_containing_class", - "name": "TreeSitterJavaAnalyzer._find_containing_class", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_identifier_name", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_component_id" - ], - "source_code": "\tdef _find_containing_class(self, node, top_level_nodes):\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type in [\"class_declaration\", \"interface_declaration\", \"enum_declaration\", \"record_declaration\", \"annotation_type_declaration\"]:\n\t\t\t\tclass_name = self._get_identifier_name(current)\n\t\t\t\tif class_name and class_name in top_level_nodes:\n\t\t\t\t\treturn self._get_component_id(class_name) \n\t\t\tcurrent = current.parent\n\t\treturn None", - "start_line": 428, - "end_line": 436, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "top_level_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._find_containing_class", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_containing_class", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_variable_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_variable_type", - "name": "TreeSitterJavaAnalyzer._find_variable_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._search_variable_declaration", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_type_name" - ], - "source_code": "\tdef _find_variable_type(self, node, variable_name, top_level_nodes):\n\t\tmethod_node = node.parent\n\t\twhile method_node and method_node.type not in [\"method_declaration\", \"constructor_declaration\"]:\n\t\t\tmethod_node = method_node.parent\n\n\t\tif method_node:\n\t\t\tfor child in method_node.children:\n\t\t\t\tif child.type == \"block\" or child.type == \"constructor_body\":\n\t\t\t\t\tvariable_type = self._search_variable_declaration(child, variable_name)\n\t\t\t\t\tif variable_type:\n\t\t\t\t\t\treturn variable_type\n\t\t\t\telif child.type == \"formal_parameters\":\n\t\t\t\t\tfor param in child.children:\n\t\t\t\t\t\tif param.type in [\"formal_parameter\", \"spread_parameter\"]:\n\t\t\t\t\t\t\ttype_node = next(\n\t\t\t\t\t\t\t\t(c for c in param.children if c.type in [\"type_identifier\", \"generic_type\"]),\n\t\t\t\t\t\t\t\tNone,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tidentifier_node = next(\n\t\t\t\t\t\t\t\t(c for c in param.children if c.type == \"identifier\"), None\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\ttype_node\n\t\t\t\t\t\t\t\tand identifier_node\n\t\t\t\t\t\t\t\tand identifier_node.text.decode() == variable_name\n\t\t\t\t\t\t\t):\n\t\t\t\t\t\t\t\treturn self._get_type_name(type_node)\n\t\t\n\t\tclass_node = node.parent\n\t\twhile class_node and class_node.type != \"class_declaration\":\n\t\t\tclass_node = class_node.parent\n\t\t\t\n\t\tif class_node:\n\t\t\tfor child in class_node.children:\n\t\t\t\tif child.type == \"class_body\":\n\t\t\t\t\tfor body_child in child.children:\n\t\t\t\t\t\tif body_child.type == \"field_declaration\":\n\t\t\t\t\t\t\tidentifier_node = None\n\t\t\t\t\t\t\ttype_node = None\n\t\t\t\t\t\t\tfor field_child in body_child.children:\n\t\t\t\t\t\t\t\tif field_child.type in [\"type_identifier\", \"generic_type\"]:\n\t\t\t\t\t\t\t\t\ttype_node = field_child\n\t\t\t\t\t\t\t\telif field_child.type == \"variable_declarator\":\n\t\t\t\t\t\t\t\t\tidentifier_node = next((c for c in field_child.children if c.type == \"identifier\"), None)\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif identifier_node and type_node and identifier_node.text.decode() == variable_name:\n\t\t\t\t\t\t\t\tfield_type = self._get_type_name(type_node)\n\t\t\t\t\t\t\t\treturn field_type\n\t\t\n\t\treturn None", - "start_line": 438, - "end_line": 487, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "variable_name", - "top_level_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._find_variable_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_variable_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._search_variable_declaration": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._search_variable_declaration", - "name": "TreeSitterJavaAnalyzer._search_variable_declaration", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._search_variable_declaration", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_type_name" - ], - "source_code": "\tdef _search_variable_declaration(self, block_node, variable_name):\n\t\tfor child in block_node.children:\n\t\t\tif child.type == \"local_variable_declaration\":\n\t\t\t\ttype_node = None\n\t\t\t\tidentifier_node = None\n\t\t\t\tfor decl_child in child.children:\n\t\t\t\t\tif decl_child.type in [\"type_identifier\", \"generic_type\"]:\n\t\t\t\t\t\ttype_node = decl_child\n\t\t\t\t\telif decl_child.type == \"variable_declarator\":\n\t\t\t\t\t\tidentifier_node = next((c for c in decl_child.children if c.type == \"identifier\"), None)\n\t\t\t\t\n\t\t\t\tif identifier_node and type_node and identifier_node.text.decode() == variable_name:\n\t\t\t\t\treturn self._get_type_name(type_node)\n\t\t\t\n\t\t\telif child.type == \"block\":\n\t\t\t\tresult = self._search_variable_declaration(child, variable_name)\n\t\t\t\tif result:\n\t\t\t\t\treturn result\n\t\t\n\t\treturn None", - "start_line": 489, - "end_line": 508, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "block_node", - "variable_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._search_variable_declaration", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._search_variable_declaration", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_containing_class_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_containing_class_name", - "name": "TreeSitterJavaAnalyzer._find_containing_class_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_containing_type_names" - ], - "source_code": "\tdef _find_containing_class_name(self, node):\n\t\tnames = self._find_containing_type_names(node)\n\t\treturn names[-1] if names else None", - "start_line": 510, - "end_line": 512, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._find_containing_class_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_containing_class_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_containing_type_names": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_containing_type_names", - "name": "TreeSitterJavaAnalyzer._find_containing_type_names", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [], - "source_code": "\tdef _find_containing_type_names(self, node) -> list[str]:\n\t\tnames = []\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type in [\"class_declaration\", \"interface_declaration\", \"enum_declaration\", \"record_declaration\", \"annotation_type_declaration\"]:\n\t\t\t\tname_node = next((c for c in current.children if c.type == \"identifier\"), None)\n\t\t\t\tif name_node:\n\t\t\t\t\tnames.append(name_node.text.decode())\n\t\t\tcurrent = current.parent\n\t\treturn list(reversed(names))", - "start_line": 514, - "end_line": 523, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._find_containing_type_names", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_containing_type_names", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_containing_method": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_containing_method", - "name": "TreeSitterJavaAnalyzer._find_containing_method", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_containing_class_name", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_identifier_name", - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._get_component_id" - ], - "source_code": "\tdef _find_containing_method(self, node):\n\t\tcurrent = node.parent\n\t\twhile current:\n\t\t\tif current.type == \"method_declaration\":\n\t\t\t\tmethod_name = self._get_identifier_name(current)\n\t\t\t\tclass_name = self._find_containing_class_name(current)\n\t\t\t\tif method_name and class_name:\n\t\t\t\t\treturn self._get_component_id(f\"{class_name}.{method_name}\")\n\t\t\tcurrent = current.parent\n\t\treturn None", - "start_line": 525, - "end_line": 534, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJavaAnalyzer", - "display_name": "method TreeSitterJavaAnalyzer._find_containing_method", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer._find_containing_method", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/java.py::analyze_java_file": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::analyze_java_file", - "name": "analyze_java_file", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/java.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/java.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/java.py::TreeSitterJavaAnalyzer" - ], - "source_code": "def analyze_java_file(file_path: str, content: str, repo_path: str = None) -> Tuple[List[Node], List[CallRelationship]]:\n\tanalyzer = TreeSitterJavaAnalyzer(file_path, content, repo_path)\n\treturn analyzer.nodes, analyzer.call_relationships", - "start_line": 536, - "end_line": 538, - "has_docstring": false, - "docstring": "", - "parameters": [ - "file_path", - "content", - "repo_path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function analyze_java_file", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/java.py::analyze_java_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer", - "name": "TreeSitterJSAnalyzer", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [], - "source_code": "class TreeSitterJSAnalyzer:\n def __init__(self, file_path: str, content: str, repo_path: str = None):\n self.file_path = Path(file_path)\n self.content = content\n self.repo_path = repo_path or \"\"\n self.nodes: List[Node] = []\n self.call_relationships: List[CallRelationship] = []\n \n self.top_level_nodes = {}\n \n self.seen_relationships = set()\n\n try:\n language_capsule = tree_sitter_javascript.language()\n self.js_language = Language(language_capsule)\n self.parser = Parser(self.js_language)\n\n except Exception as e:\n logger.error(f\"Failed to initialize JavaScript parser: {e}\")\n logger.error(f\"Traceback: {traceback.format_exc()}\")\n self.parser = None\n self.js_language = None\n\n\n def _add_relationship(self, relationship: CallRelationship) -> bool:\n rel_key = (relationship.caller, relationship.callee, relationship.call_line)\n \n if rel_key not in self.seen_relationships:\n self.seen_relationships.add(rel_key)\n self.call_relationships.append(relationship)\n return True\n return False\n\n def analyze(self) -> None:\n if self.parser is None:\n logger.warning(f\"Skipping {self.file_path} - parser initialization failed\")\n return\n\n try:\n tree = self.parser.parse(bytes(self.content, \"utf8\"))\n root_node = tree.root_node\n\n logger.debug(f\"Parsed AST with root node type: {root_node.type}\")\n\n self._extract_functions(root_node)\n self._extract_call_relationships(root_node)\n\n logger.debug(\n f\"Analysis complete: {len(self.nodes)} nodes, {len(self.call_relationships)} relationships\"\n )\n\n except Exception as e:\n logger.error(f\"Error analyzing JavaScript file {self.file_path}: {e}\", exc_info=True)\n\n def _get_module_path(self) -> str:\n if self.repo_path:\n try:\n rel_path = os.path.relpath(str(self.file_path), self.repo_path)\n except ValueError:\n rel_path = str(self.file_path)\n else:\n rel_path = str(self.file_path)\n \n for ext in ['.js', '.ts', '.jsx', '.tsx', '.mjs', '.cjs']:\n if rel_path.endswith(ext):\n rel_path = rel_path[:-len(ext)]\n break\n return rel_path.replace('/', '.').replace('\\\\', '.')\n \n def _get_relative_path(self) -> str:\n if self.repo_path:\n try:\n return os.path.relpath(str(self.file_path), self.repo_path)\n except ValueError:\n return str(self.file_path)\n else:\n return str(self.file_path)\n\n def _get_component_id(self, name: str, class_name: str = None, is_method: bool = False) -> str:\n relative_path = self._get_relative_path()\n\n if is_method and class_name:\n return f\"{relative_path}::{class_name}.{name}\"\n elif class_name and not is_method:\n return f\"{relative_path}::{name}\"\n else:\n return f\"{relative_path}::{name}\"\n\n def _find_containing_class(self, node) -> Optional[str]:\n parent = node.parent\n while parent:\n if parent.type in [\"class_declaration\", \"abstract_class_declaration\", \"interface_declaration\"]:\n name_node = self._find_child_by_type(parent, \"type_identifier\")\n if not name_node:\n name_node = self._find_child_by_type(parent, \"identifier\")\n if name_node:\n return self._get_node_text(name_node)\n parent = parent.parent\n return None\n\n def _extract_functions(self, node) -> None:\n self._traverse_for_functions(node)\n self.nodes.sort(key=lambda n: n.start_line)\n\n def _traverse_for_functions(self, node) -> None:\n if node.type in [\"class_declaration\", \"abstract_class_declaration\", \"interface_declaration\"]:\n cls = self._extract_class_declaration(node)\n if cls:\n self.nodes.append(cls)\n self.top_level_nodes[cls.name] = cls\n \n self._extract_methods_from_class(node, cls.name)\n \n elif node.type == \"function_declaration\":\n containing_class = self._find_containing_class(node)\n if containing_class is None:\n func = self._extract_function_declaration(node)\n if func and self._should_include_function(func):\n self.nodes.append(func)\n self.top_level_nodes[func.name] = func\n elif node.type == \"generator_function_declaration\":\n containing_class = self._find_containing_class(node)\n if containing_class is None:\n func = self._extract_function_declaration(node)\n if func and self._should_include_function(func):\n self.nodes.append(func)\n self.top_level_nodes[func.name] = func\n elif node.type == \"export_statement\":\n func = self._extract_exported_function(node)\n if func and self._should_include_function(func):\n self.nodes.append(func)\n self.top_level_nodes[func.name] = func\n elif node.type == \"lexical_declaration\":\n containing_class = self._find_containing_class(node)\n if containing_class is None:\n func = self._extract_arrow_function_from_declaration(node)\n if func and self._should_include_function(func):\n self.nodes.append(func)\n self.top_level_nodes[func.name] = func\n \n for child in node.children:\n self._traverse_for_functions(child)\n\n def _extract_methods_from_class(self, class_node, class_name: str) -> None:\n class_body = self._find_child_by_type(class_node, \"class_body\")\n if not class_body:\n return\n \n for child in class_body.children:\n if child.type == \"method_definition\":\n method_name = self._get_method_name(child)\n if method_name:\n method_node = self._create_method_node(child, method_name, class_name)\n if method_node:\n if method_name != \"constructor\":\n self.nodes.append(method_node)\n self.top_level_nodes[method_node.name] = method_node\n elif child.type == \"field_definition\":\n # Handle arrow function properties\n field_name = self._get_field_name(child)\n if field_name and self._is_arrow_function_field(child):\n method_node = self._create_method_node(child, field_name, class_name)\n if method_node:\n self.nodes.append(method_node)\n self.top_level_nodes[method_node.name] = method_node\n\n def _get_method_name(self, method_node) -> Optional[str]:\n \"\"\"Get method name from method_definition node.\"\"\"\n if method_node.type != \"method_definition\":\n return None\n \n for child in method_node.children:\n if child.type == \"property_identifier\":\n return self._get_node_text(child)\n return None\n\n def _get_field_name(self, field_node) -> Optional[str]:\n \"\"\"Get field name from field_definition node.\"\"\"\n if field_node.type != \"field_definition\":\n return None\n \n for child in field_node.children:\n if child.type == \"property_identifier\":\n return self._get_node_text(child)\n return None\n\n def _is_arrow_function_field(self, field_node) -> bool:\n \"\"\"Check if field_definition contains an arrow function.\"\"\"\n for child in field_node.children:\n if child.type == \"arrow_function\":\n return True\n return False\n\n def _create_method_node(self, node, method_name: str, class_name: str) -> Optional[Node]:\n \"\"\"Create a method node for relationship mapping.\"\"\"\n try:\n line_start = node.start_point[0] + 1\n line_end = node.end_point[0] + 1\n component_id = self._get_component_id(method_name, class_name, is_method=True)\n relative_path = self._get_relative_path()\n qualified = f\"{class_name}.{method_name}\"\n\n return Node(\n id=component_id,\n name=qualified,\n component_type=\"method\",\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=\"\\n\".join(self.content.splitlines()[line_start - 1 : line_end]),\n start_line=line_start,\n end_line=line_end,\n has_docstring=False,\n docstring=\"\",\n parameters=None,\n node_type=\"method\",\n base_classes=None,\n class_name=class_name,\n display_name=f\"method {qualified}\",\n component_id=component_id,\n language=\"javascript\",\n qualified_name=qualified,\n )\n except Exception as e:\n logger.debug(f\"Error creating method node for {method_name}: {e}\")\n return None\n\n def _extract_class_declaration(self, node) -> Optional[Node]:\n \"\"\"Extract class/abstract class/interface declaration.\"\"\"\n try:\n name_node = self._find_child_by_type(node, \"type_identifier\")\n if not name_node:\n name_node = self._find_child_by_type(node, \"identifier\")\n if not name_node:\n return None\n name = self._get_node_text(name_node)\n line_start = node.start_point[0] + 1\n line_end = node.end_point[0] + 1\n docstring = None\n base_classes = []\n heritage_node = self._find_child_by_type(node, \"class_heritage\")\n if heritage_node:\n for child in heritage_node.children:\n if child.type in [\"identifier\", \"type_identifier\"]:\n base_classes.append(self._get_node_text(child))\n code_snippet = \"\\n\".join(self.content.splitlines()[line_start - 1 : line_end])\n \n if node.type == \"abstract_class_declaration\":\n node_type = \"abstract class\"\n display_name = f\"abstract class {name}\"\n elif node.type == \"interface_declaration\":\n node_type = \"interface\"\n display_name = f\"interface {name}\"\n else:\n node_type = \"class\"\n display_name = f\"class {name}\"\n \n component_id = self._get_component_id(name, is_method=False)\n relative_path = self._get_relative_path()\n \n return Node(\n id=component_id,\n name=name,\n component_type=node_type,\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=code_snippet,\n start_line=line_start,\n end_line=line_end,\n has_docstring=bool(docstring),\n docstring=docstring or \"\",\n parameters=None,\n node_type=node_type,\n base_classes=base_classes if base_classes else None,\n class_name=None,\n display_name=display_name,\n component_id=component_id,\n )\n except Exception:\n return None\n\n def _extract_function_declaration(self, node) -> Optional[Node]:\n try:\n name_node = self._find_child_by_type(node, \"identifier\")\n if not name_node:\n return None\n\n func_name = self._get_node_text(name_node)\n line_start = node.start_point[0] + 1\n line_end = node.end_point[0] + 1\n parameters = self._extract_parameters(node)\n code_snippet = self._get_node_text(node)\n\n # Check for async and generator from code snippet\n is_async = \"async function\" in code_snippet\n is_generator = \"function*\" in code_snippet or \"*\" in func_name\n \n if is_async and is_generator:\n display_name = f\"async generator {func_name}\"\n elif is_async:\n display_name = f\"async function {func_name}\"\n elif is_generator:\n display_name = f\"generator function {func_name}\"\n else:\n display_name = f\"function {func_name}\"\n\n component_id = self._get_component_id(func_name, is_method=False)\n relative_path = self._get_relative_path()\n\n return Node(\n id=component_id,\n name=func_name,\n component_type=\"function\",\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=code_snippet,\n start_line=line_start,\n end_line=line_end,\n has_docstring=False,\n docstring=\"\",\n parameters=parameters,\n node_type=\"function\",\n base_classes=None,\n class_name=None,\n display_name=display_name,\n component_id=component_id,\n )\n except Exception as e:\n logger.debug(f\"Error extracting function declaration: {e}\")\n return None\n def _extract_exported_function(self, node) -> Optional[Node]:\n \"\"\"Extract export function or export default function\"\"\"\n try:\n func_decl = self._find_child_by_type(node, \"function_declaration\")\n if func_decl:\n func = self._extract_function_declaration(func_decl)\n if func:\n export_text = self._get_node_text(node)\n if \"export default\" in export_text and \"function (\" in export_text:\n func.name = \"default\"\n return func\n except Exception as e:\n logger.debug(f\"Error extracting exported function: {e}\")\n return None\n\n def _extract_arrow_function_from_declaration(self, node) -> Optional[Node]:\n \"\"\"Extract arrow function or function expression from const/let/var declarations.\"\"\"\n try:\n for child in node.children:\n if child.type == \"variable_declarator\":\n name_node = self._find_child_by_type(child, \"identifier\")\n func_node = self._find_child_by_type(\n child, \"arrow_function\"\n ) or self._find_child_by_type(child, \"function_expression\")\n\n if name_node and func_node:\n func_name = self._get_node_text(name_node)\n line_start = func_node.start_point[0] + 1\n line_end = func_node.end_point[0] + 1\n parameters = self._extract_parameters(func_node)\n code_snippet = self._get_node_text(child)\n\n component_id = self._get_component_id(func_name, is_method=False)\n relative_path = self._get_relative_path()\n\n return Node(\n id=component_id,\n name=func_name,\n component_type=\"function\",\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=code_snippet,\n start_line=line_start,\n end_line=line_end,\n has_docstring=False,\n docstring=\"\",\n parameters=parameters,\n node_type=\"function\",\n base_classes=None,\n class_name=None,\n display_name=f\"function {func_name}\",\n component_id=component_id,\n )\n return None\n except Exception as e:\n logger.debug(f\"Error extracting function from declaration: {e}\")\n return None\n\n def _should_include_function(self, func: Node) -> bool:\n excluded_names = {}\n\n if func.name.lower() in excluded_names:\n logger.debug(f\"Skipping excluded function: {func.name}\")\n return False\n\n return True\n\n def _extract_parameters(self, node) -> List[str]:\n parameters = []\n params_node = self._find_child_by_type(node, \"formal_parameters\")\n if params_node:\n for child in params_node.children:\n if child.type == \"identifier\":\n parameters.append(self._get_node_text(child))\n return parameters\n\n def _extract_call_relationships(self, node) -> None:\n current_top_level = None\n self._traverse_for_calls(node, current_top_level)\n\n def _traverse_for_calls(self, node, current_top_level) -> None:\n if current_top_level:\n self._extract_jsdoc_type_dependencies(node, current_top_level)\n \n if node.type in [\"class_declaration\", \"abstract_class_declaration\", \"interface_declaration\"]:\n name_node = self._find_child_by_type(node, \"type_identifier\") or self._find_child_by_type(node, \"identifier\")\n if name_node:\n current_top_level = self._get_node_text(name_node)\n \n heritage_node = self._find_child_by_type(node, \"class_heritage\")\n if heritage_node:\n for child in heritage_node.children:\n if child.type in [\"identifier\", \"type_identifier\"]:\n base_class = self._get_node_text(child)\n caller_id = self._get_component_id(current_top_level)\n resolved = base_class in self.top_level_nodes\n callee_id = self._get_component_id(base_class) if resolved else base_class\n inheritance_rel = CallRelationship(\n caller=caller_id,\n callee=callee_id,\n call_line=node.start_point[0] + 1,\n is_resolved=resolved\n )\n self._add_relationship(inheritance_rel)\n\n elif node.type in (\"method_definition\", \"field_definition\"):\n name = self._get_method_name(node) if node.type == \"method_definition\" else self._get_field_name(node)\n containing_class = self._find_containing_class(node)\n if name and containing_class and f\"{containing_class}.{name}\" in self.top_level_nodes:\n current_top_level = f\"{containing_class}.{name}\"\n\n elif node.type == \"function_declaration\":\n name_node = self._find_child_by_type(node, \"identifier\")\n if name_node:\n current_top_level = self._get_node_text(name_node)\n elif node.type == \"generator_function_declaration\":\n name_node = self._find_child_by_type(node, \"identifier\")\n if name_node:\n current_top_level = self._get_node_text(name_node)\n elif node.type == \"lexical_declaration\":\n for child in node.children:\n if child.type == \"variable_declarator\":\n name_node = self._find_child_by_type(child, \"identifier\")\n func_node = self._find_child_by_type(child, \"arrow_function\") or self._find_child_by_type(child, \"function_expression\")\n if name_node and func_node:\n current_top_level = self._get_node_text(name_node)\n\n if node.type == \"call_expression\" and current_top_level:\n call_info = self._extract_call_from_node(node, current_top_level)\n if call_info:\n self._add_relationship(call_info)\n \n elif node.type == \"await_expression\" and current_top_level:\n call_expr = self._find_child_by_type(node, \"call_expression\")\n if call_expr:\n call_info = self._extract_call_from_node(call_expr, current_top_level)\n if call_info:\n self._add_relationship(call_info)\n \n elif node.type == \"new_expression\" and current_top_level:\n constructor_node = self._find_child_by_type(node, \"identifier\")\n if constructor_node is not None:\n callee_name = self._get_node_text(constructor_node)\n resolved = callee_name in self.top_level_nodes\n call_info = CallRelationship(\n caller=f\"{self._get_relative_path()}::{current_top_level}\",\n callee=self._get_component_id(callee_name) if resolved else callee_name,\n call_line=node.start_point[0] + 1,\n is_resolved=resolved\n )\n self._add_relationship(call_info)\n\n for child in node.children:\n self._traverse_for_calls(child, current_top_level)\n\n def _extract_call_from_node(self, node, caller_name: str) -> Optional[CallRelationship]:\n \"\"\"Extract one relationship from a call_expression node.\n\n Plain identifier calls resolve against same-file components; member\n calls resolve receiver-first (this/super against the enclosing class,\n new-ed variables against their class). Unresolved callees stay bare\n logical names, never file-prefixed.\n \"\"\"\n try:\n call_line = node.start_point[0] + 1\n caller_id = f\"{self._get_relative_path()}::{caller_name}\"\n func_node = node.children[0] if node.children else None\n if func_node is None:\n return None\n\n def make(callee_name: str, resolved: bool) -> CallRelationship:\n return CallRelationship(\n caller=caller_id,\n callee=self._get_component_id(callee_name) if resolved else callee_name,\n call_line=call_line,\n is_resolved=resolved,\n )\n\n if func_node.type == \"identifier\":\n name = self._get_node_text(func_node)\n if not name:\n return None\n return make(name, name in self.top_level_nodes)\n\n if func_node.type != \"member_expression\":\n return None\n\n property_node = func_node.child_by_field_name(\"property\")\n obj = func_node.child_by_field_name(\"object\")\n if property_node is None or property_node.type != \"property_identifier\" or obj is None:\n return None\n tail = self._get_node_text(property_node)\n\n if obj.type in (\"this\", \"super\"):\n class_name = caller_name.split(\".\")[0]\n candidates = [] if obj.type == \"super\" else [class_name]\n class_node = self.top_level_nodes.get(class_name)\n if class_node is not None and class_node.base_classes:\n candidates.extend(class_node.base_classes)\n for candidate in candidates:\n if f\"{candidate}.{tail}\" in self.top_level_nodes:\n return make(f\"{candidate}.{tail}\", True)\n target = candidates[0] if candidates else class_name\n return make(f\"{target}.{tail}\", False)\n\n if obj.type == \"identifier\":\n receiver = self._get_node_text(obj)\n if receiver in self.top_level_nodes or self._receiver_class(node, receiver):\n cls = receiver if receiver in self.top_level_nodes else self._receiver_class(node, receiver)\n return make(f\"{cls}.{tail}\", f\"{cls}.{tail}\" in self.top_level_nodes)\n return make(f\"{receiver}.{tail}\", False)\n\n if obj.type == \"member_expression\":\n chain = self._identifier_chain(obj)\n if chain:\n return make(f\"{chain}.{tail}\", False)\n\n # Composite or literal receiver: a builtin-prototype method on an\n # unknowable receiver can never resolve to a project component.\n if tail not in JS_TS_PROTOTYPE_METHODS:\n return make(tail, False)\n return None\n\n except Exception as e:\n logger.debug(f\"Error extracting call relationship: {e}\")\n return None\n\n def _identifier_chain(self, node) -> Optional[str]:\n \"\"\"Flatten a member expression into dotted text when it is a pure\n identifier chain; None when any link is computed.\"\"\"\n parts = []\n current = node\n while current.type == \"member_expression\":\n property_node = current.child_by_field_name(\"property\")\n if property_node is None or property_node.type != \"property_identifier\":\n return None\n parts.append(self._get_node_text(property_node))\n current = current.child_by_field_name(\"object\")\n if current is None:\n return None\n if current.type != \"identifier\":\n return None\n parts.append(self._get_node_text(current))\n return \".\".join(reversed(parts))\n\n def _receiver_class(self, call_node, identifier: str) -> Optional[str]:\n \"\"\"Find the class of a local identifier from a `new X()` initializer\n in an enclosing scope.\"\"\"\n scope = call_node.parent\n while scope:\n if scope.type in (\n \"method_definition\", \"function_declaration\",\n \"generator_function_declaration\", \"arrow_function\",\n \"function_expression\", \"program\",\n ):\n found = self._find_new_initializer(scope, identifier)\n if found:\n return found\n scope = scope.parent\n return None\n\n def _find_new_initializer(self, scope_node, identifier: str) -> Optional[str]:\n stack = [scope_node]\n while stack:\n current = stack.pop()\n if current.type == \"variable_declarator\":\n name_node = self._find_child_by_type(current, \"identifier\")\n if name_node is not None and self._get_node_text(name_node) == identifier:\n new_expr = self._find_child_by_type(current, \"new_expression\")\n if new_expr is not None:\n ctor = self._find_child_by_type(new_expr, \"identifier\")\n if ctor is not None:\n return self._get_node_text(ctor)\n stack.extend(current.children)\n return None\n\n def _extract_jsdoc_type_dependencies(self, node, caller_name: str) -> None:\n \"\"\"Extract type dependencies from JSDoc comments.\"\"\"\n try:\n if hasattr(node, 'prev_sibling') and node.prev_sibling:\n prev = node.prev_sibling\n if prev.type == \"comment\":\n comment_text = self._get_node_text(prev)\n self._parse_jsdoc_types(comment_text, caller_name, node.start_point[0] + 1)\n \n for child in node.children:\n if child.type == \"comment\":\n comment_text = self._get_node_text(child)\n self._parse_jsdoc_types(comment_text, caller_name, node.start_point[0] + 1)\n \n except Exception as e:\n logger.debug(f\"Error extracting JSDoc dependencies: {e}\")\n\n def _parse_jsdoc_types(self, comment_text: str, caller_name: str, line_number: int) -> None:\n \"\"\"Parse JSDoc comment text and extract type references.\"\"\"\n import re\n try:\n type_patterns = [\n r'@param\\s*\\{([^}]+)\\}', # @param {Type}\n r'@returns?\\s*\\{([^}]+)\\}', # @return {Type} or @returns {Type}\n r'@type\\s*\\{([^}]+)\\}', # @type {Type}\n r'@typedef\\s*\\{[^}]*\\}\\s*(\\w+)', # @typedef {Object} TypeName\n r'@interface\\s+(\\w+)', # @interface InterfaceName\n ]\n \n for pattern in type_patterns:\n matches = re.findall(pattern, comment_text)\n for match in matches:\n type_name = match.strip()\n \n base_types = self._extract_base_types_from_jsdoc(type_name)\n \n for base_type in base_types:\n if base_type and not self._is_builtin_type_js(base_type):\n caller_id = f\"{self._get_relative_path()}::{caller_name}\"\n resolved = base_type in self.top_level_nodes\n callee_id = self._get_component_id(base_type) if resolved else base_type\n\n type_rel = CallRelationship(\n caller=caller_id,\n callee=callee_id,\n call_line=line_number,\n is_resolved=resolved\n )\n \n if self._add_relationship(type_rel):\n pass\n \n except Exception as e:\n logger.debug(f\"Error parsing JSDoc types: {e}\")\n\n def _extract_base_types_from_jsdoc(self, type_str: str) -> list:\n import re\n type_str = type_str.strip()\n \n base_types = []\n \n main_type_match = re.match(r'^(\\w+)', type_str)\n if main_type_match:\n base_types.append(main_type_match.group(1))\n \n generic_matches = re.findall(r'<([^<>]+)>', type_str)\n for generic in generic_matches:\n subtypes = re.findall(r'\\b(\\w+)\\b', generic)\n base_types.extend(subtypes)\n \n if '|' in type_str:\n union_types = type_str.split('|')\n for union_type in union_types:\n clean_type = re.match(r'\\b(\\w+)\\b', union_type.strip())\n if clean_type:\n base_types.append(clean_type.group(1))\n \n return base_types\n\n def _is_builtin_type_js(self, name: str) -> bool:\n \"\"\"Check if type name is a JavaScript/JSDoc built-in type.\"\"\"\n builtin_types = {\n # JavaScript primitive types\n \"string\", \"number\", \"boolean\", \"object\", \"undefined\", \"null\", \"void\", \"any\",\n \n # Global JavaScript types\n \"Array\", \"Promise\", \"Date\", \"RegExp\", \"Error\", \"Map\", \"Set\", \"WeakMap\", \"WeakSet\",\n \"Function\", \"Object\", \"String\", \"Number\", \"Boolean\", \"Symbol\", \"BigInt\",\n \n \"Element\", \"HTMLElement\", \"Document\", \"Window\", \"Event\", \"EventTarget\", \"Node\",\n \"Response\", \"Request\", \"Headers\", \"URL\", \"URLSearchParams\", \"FormData\", \"Blob\", \"File\",\n \n # Common JSDoc generic parameters\n \"T\", \"U\", \"V\", \"K\", \"P\", \"R\", \"E\"\n }\n return name in builtin_types\n\n def _extract_callee_name(self, call_node) -> Optional[str]:\n if not call_node.children:\n return None\n \n callee_node = call_node.children[0]\n\n if callee_node.type == \"identifier\":\n return self._get_node_text(callee_node)\n elif callee_node.type == \"member_expression\":\n property_node = self._find_child_by_type(callee_node, \"property_identifier\")\n if property_node:\n return self._get_node_text(property_node)\n \n computed_property = self._find_child_by_type(callee_node, \"computed_property_name\")\n if computed_property:\n for child in computed_property.children:\n if child.type == \"identifier\":\n return self._get_node_text(child)\n elif callee_node.type == \"super\":\n return \"super\"\n elif callee_node.type == \"this\":\n return \"this\"\n \n return None\n\n def _find_child_by_type(self, node, node_type: str):\n \"\"\"Find first child node of specified type.\"\"\"\n for child in node.children:\n if child.type == node_type:\n return child\n return None\n\n def _get_node_text(self, node) -> str:\n start_byte = node.start_byte\n end_byte = node.end_byte\n return self.content.encode(\"utf8\")[start_byte:end_byte].decode(\"utf8\")\n\n def _find_containing_class_name(self, method_node) -> Optional[str]:\n current = method_node.parent\n while current:\n if current.type == \"class_declaration\":\n name_node = self._find_child_by_type(current, \"identifier\")\n if name_node:\n return self._get_node_text(name_node)\n current = current.parent\n return None\n\n def _extract_assignment_name(self, node) -> Optional[str]:\n if node.type == \"identifier\":\n return self._get_node_text(node)\n elif node.type == \"member_expression\":\n property_node = self._find_child_by_type(node, \"property_identifier\")\n if property_node:\n return self._get_node_text(property_node)\n return None", - "start_line": 21, - "end_line": 777, - "has_docstring": false, - "docstring": "", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class TreeSitterJSAnalyzer", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer.__init__": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer.__init__", - "name": "TreeSitterJSAnalyzer.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": " def __init__(self, file_path: str, content: str, repo_path: str = None):\n self.file_path = Path(file_path)\n self.content = content\n self.repo_path = repo_path or \"\"\n self.nodes: List[Node] = []\n self.call_relationships: List[CallRelationship] = []\n \n self.top_level_nodes = {}\n \n self.seen_relationships = set()\n\n try:\n language_capsule = tree_sitter_javascript.language()\n self.js_language = Language(language_capsule)\n self.parser = Parser(self.js_language)\n\n except Exception as e:\n logger.error(f\"Failed to initialize JavaScript parser: {e}\")\n logger.error(f\"Traceback: {traceback.format_exc()}\")\n self.parser = None\n self.js_language = None", - "start_line": 22, - "end_line": 42, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "file_path", - "content", - "repo_path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer.__init__", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._add_relationship": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._add_relationship", - "name": "TreeSitterJSAnalyzer._add_relationship", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [], - "source_code": " def _add_relationship(self, relationship: CallRelationship) -> bool:\n rel_key = (relationship.caller, relationship.callee, relationship.call_line)\n \n if rel_key not in self.seen_relationships:\n self.seen_relationships.add(rel_key)\n self.call_relationships.append(relationship)\n return True\n return False", - "start_line": 45, - "end_line": 52, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "relationship" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._add_relationship", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._add_relationship", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer.analyze": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer.analyze", - "name": "TreeSitterJSAnalyzer.analyze", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_call_relationships", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_functions", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": " def analyze(self) -> None:\n if self.parser is None:\n logger.warning(f\"Skipping {self.file_path} - parser initialization failed\")\n return\n\n try:\n tree = self.parser.parse(bytes(self.content, \"utf8\"))\n root_node = tree.root_node\n\n logger.debug(f\"Parsed AST with root node type: {root_node.type}\")\n\n self._extract_functions(root_node)\n self._extract_call_relationships(root_node)\n\n logger.debug(\n f\"Analysis complete: {len(self.nodes)} nodes, {len(self.call_relationships)} relationships\"\n )\n\n except Exception as e:\n logger.error(f\"Error analyzing JavaScript file {self.file_path}: {e}\", exc_info=True)", - "start_line": 54, - "end_line": 73, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer.analyze", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer.analyze", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_module_path": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_module_path", - "name": "TreeSitterJSAnalyzer._get_module_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [], - "source_code": " def _get_module_path(self) -> str:\n if self.repo_path:\n try:\n rel_path = os.path.relpath(str(self.file_path), self.repo_path)\n except ValueError:\n rel_path = str(self.file_path)\n else:\n rel_path = str(self.file_path)\n \n for ext in ['.js', '.ts', '.jsx', '.tsx', '.mjs', '.cjs']:\n if rel_path.endswith(ext):\n rel_path = rel_path[:-len(ext)]\n break\n return rel_path.replace('/', '.').replace('\\\\', '.')", - "start_line": 75, - "end_line": 88, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._get_module_path", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_module_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_relative_path": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_relative_path", - "name": "TreeSitterJSAnalyzer._get_relative_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [], - "source_code": " def _get_relative_path(self) -> str:\n if self.repo_path:\n try:\n return os.path.relpath(str(self.file_path), self.repo_path)\n except ValueError:\n return str(self.file_path)\n else:\n return str(self.file_path)", - "start_line": 90, - "end_line": 97, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._get_relative_path", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_relative_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_component_id": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_component_id", - "name": "TreeSitterJSAnalyzer._get_component_id", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_relative_path" - ], - "source_code": " def _get_component_id(self, name: str, class_name: str = None, is_method: bool = False) -> str:\n relative_path = self._get_relative_path()\n\n if is_method and class_name:\n return f\"{relative_path}::{class_name}.{name}\"\n elif class_name and not is_method:\n return f\"{relative_path}::{name}\"\n else:\n return f\"{relative_path}::{name}\"", - "start_line": 99, - "end_line": 107, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "name", - "class_name", - "is_method" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._get_component_id", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_component_id", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_containing_class": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_containing_class", - "name": "TreeSitterJSAnalyzer._find_containing_class", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_node_text" - ], - "source_code": " def _find_containing_class(self, node) -> Optional[str]:\n parent = node.parent\n while parent:\n if parent.type in [\"class_declaration\", \"abstract_class_declaration\", \"interface_declaration\"]:\n name_node = self._find_child_by_type(parent, \"type_identifier\")\n if not name_node:\n name_node = self._find_child_by_type(parent, \"identifier\")\n if name_node:\n return self._get_node_text(name_node)\n parent = parent.parent\n return None", - "start_line": 109, - "end_line": 119, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._find_containing_class", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_containing_class", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_functions": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_functions", - "name": "TreeSitterJSAnalyzer._extract_functions", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._traverse_for_functions" - ], - "source_code": " def _extract_functions(self, node) -> None:\n self._traverse_for_functions(node)\n self.nodes.sort(key=lambda n: n.start_line)", - "start_line": 121, - "end_line": 123, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._extract_functions", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_functions", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._traverse_for_functions": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._traverse_for_functions", - "name": "TreeSitterJSAnalyzer._traverse_for_functions", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_containing_class", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_exported_function", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_function_declaration", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_methods_from_class", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_arrow_function_from_declaration", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._should_include_function", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_class_declaration", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._traverse_for_functions" - ], - "source_code": " def _traverse_for_functions(self, node) -> None:\n if node.type in [\"class_declaration\", \"abstract_class_declaration\", \"interface_declaration\"]:\n cls = self._extract_class_declaration(node)\n if cls:\n self.nodes.append(cls)\n self.top_level_nodes[cls.name] = cls\n \n self._extract_methods_from_class(node, cls.name)\n \n elif node.type == \"function_declaration\":\n containing_class = self._find_containing_class(node)\n if containing_class is None:\n func = self._extract_function_declaration(node)\n if func and self._should_include_function(func):\n self.nodes.append(func)\n self.top_level_nodes[func.name] = func\n elif node.type == \"generator_function_declaration\":\n containing_class = self._find_containing_class(node)\n if containing_class is None:\n func = self._extract_function_declaration(node)\n if func and self._should_include_function(func):\n self.nodes.append(func)\n self.top_level_nodes[func.name] = func\n elif node.type == \"export_statement\":\n func = self._extract_exported_function(node)\n if func and self._should_include_function(func):\n self.nodes.append(func)\n self.top_level_nodes[func.name] = func\n elif node.type == \"lexical_declaration\":\n containing_class = self._find_containing_class(node)\n if containing_class is None:\n func = self._extract_arrow_function_from_declaration(node)\n if func and self._should_include_function(func):\n self.nodes.append(func)\n self.top_level_nodes[func.name] = func\n \n for child in node.children:\n self._traverse_for_functions(child)", - "start_line": 125, - "end_line": 162, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._traverse_for_functions", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._traverse_for_functions", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_methods_from_class": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_methods_from_class", - "name": "TreeSitterJSAnalyzer._extract_methods_from_class", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._create_method_node", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_method_name", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._is_arrow_function_field", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_field_name" - ], - "source_code": " def _extract_methods_from_class(self, class_node, class_name: str) -> None:\n class_body = self._find_child_by_type(class_node, \"class_body\")\n if not class_body:\n return\n \n for child in class_body.children:\n if child.type == \"method_definition\":\n method_name = self._get_method_name(child)\n if method_name:\n method_node = self._create_method_node(child, method_name, class_name)\n if method_node:\n if method_name != \"constructor\":\n self.nodes.append(method_node)\n self.top_level_nodes[method_node.name] = method_node\n elif child.type == \"field_definition\":\n # Handle arrow function properties\n field_name = self._get_field_name(child)\n if field_name and self._is_arrow_function_field(child):\n method_node = self._create_method_node(child, field_name, class_name)\n if method_node:\n self.nodes.append(method_node)\n self.top_level_nodes[method_node.name] = method_node", - "start_line": 164, - "end_line": 185, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "class_node", - "class_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._extract_methods_from_class", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_methods_from_class", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_method_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_method_name", - "name": "TreeSitterJSAnalyzer._get_method_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_node_text" - ], - "source_code": " def _get_method_name(self, method_node) -> Optional[str]:\n \"\"\"Get method name from method_definition node.\"\"\"\n if method_node.type != \"method_definition\":\n return None\n \n for child in method_node.children:\n if child.type == \"property_identifier\":\n return self._get_node_text(child)\n return None", - "start_line": 187, - "end_line": 195, - "has_docstring": true, - "docstring": "Get method name from method_definition node.", - "parameters": [ - "self", - "method_node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._get_method_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_method_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_field_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_field_name", - "name": "TreeSitterJSAnalyzer._get_field_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_node_text" - ], - "source_code": " def _get_field_name(self, field_node) -> Optional[str]:\n \"\"\"Get field name from field_definition node.\"\"\"\n if field_node.type != \"field_definition\":\n return None\n \n for child in field_node.children:\n if child.type == \"property_identifier\":\n return self._get_node_text(child)\n return None", - "start_line": 197, - "end_line": 205, - "has_docstring": true, - "docstring": "Get field name from field_definition node.", - "parameters": [ - "self", - "field_node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._get_field_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_field_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._is_arrow_function_field": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._is_arrow_function_field", - "name": "TreeSitterJSAnalyzer._is_arrow_function_field", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [], - "source_code": " def _is_arrow_function_field(self, field_node) -> bool:\n \"\"\"Check if field_definition contains an arrow function.\"\"\"\n for child in field_node.children:\n if child.type == \"arrow_function\":\n return True\n return False", - "start_line": 207, - "end_line": 212, - "has_docstring": true, - "docstring": "Check if field_definition contains an arrow function.", - "parameters": [ - "self", - "field_node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._is_arrow_function_field", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._is_arrow_function_field", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._create_method_node": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._create_method_node", - "name": "TreeSitterJSAnalyzer._create_method_node", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_relative_path", - "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_component_id", - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": " def _create_method_node(self, node, method_name: str, class_name: str) -> Optional[Node]:\n \"\"\"Create a method node for relationship mapping.\"\"\"\n try:\n line_start = node.start_point[0] + 1\n line_end = node.end_point[0] + 1\n component_id = self._get_component_id(method_name, class_name, is_method=True)\n relative_path = self._get_relative_path()\n qualified = f\"{class_name}.{method_name}\"\n\n return Node(\n id=component_id,\n name=qualified,\n component_type=\"method\",\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=\"\\n\".join(self.content.splitlines()[line_start - 1 : line_end]),\n start_line=line_start,\n end_line=line_end,\n has_docstring=False,\n docstring=\"\",\n parameters=None,\n node_type=\"method\",\n base_classes=None,\n class_name=class_name,\n display_name=f\"method {qualified}\",\n component_id=component_id,\n language=\"javascript\",\n qualified_name=qualified,\n )\n except Exception as e:\n logger.debug(f\"Error creating method node for {method_name}: {e}\")\n return None", - "start_line": 214, - "end_line": 245, - "has_docstring": true, - "docstring": "Create a method node for relationship mapping.", - "parameters": [ - "self", - "node", - "method_name", - "class_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._create_method_node", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._create_method_node", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_class_declaration": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_class_declaration", - "name": "TreeSitterJSAnalyzer._extract_class_declaration", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_relative_path", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_component_id", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_node_text" - ], - "source_code": " def _extract_class_declaration(self, node) -> Optional[Node]:\n \"\"\"Extract class/abstract class/interface declaration.\"\"\"\n try:\n name_node = self._find_child_by_type(node, \"type_identifier\")\n if not name_node:\n name_node = self._find_child_by_type(node, \"identifier\")\n if not name_node:\n return None\n name = self._get_node_text(name_node)\n line_start = node.start_point[0] + 1\n line_end = node.end_point[0] + 1\n docstring = None\n base_classes = []\n heritage_node = self._find_child_by_type(node, \"class_heritage\")\n if heritage_node:\n for child in heritage_node.children:\n if child.type in [\"identifier\", \"type_identifier\"]:\n base_classes.append(self._get_node_text(child))\n code_snippet = \"\\n\".join(self.content.splitlines()[line_start - 1 : line_end])\n \n if node.type == \"abstract_class_declaration\":\n node_type = \"abstract class\"\n display_name = f\"abstract class {name}\"\n elif node.type == \"interface_declaration\":\n node_type = \"interface\"\n display_name = f\"interface {name}\"\n else:\n node_type = \"class\"\n display_name = f\"class {name}\"\n \n component_id = self._get_component_id(name, is_method=False)\n relative_path = self._get_relative_path()\n \n return Node(\n id=component_id,\n name=name,\n component_type=node_type,\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=code_snippet,\n start_line=line_start,\n end_line=line_end,\n has_docstring=bool(docstring),\n docstring=docstring or \"\",\n parameters=None,\n node_type=node_type,\n base_classes=base_classes if base_classes else None,\n class_name=None,\n display_name=display_name,\n component_id=component_id,\n )\n except Exception:\n return None", - "start_line": 247, - "end_line": 299, - "has_docstring": true, - "docstring": "Extract class/abstract class/interface declaration.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._extract_class_declaration", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_class_declaration", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_function_declaration": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_function_declaration", - "name": "TreeSitterJSAnalyzer._extract_function_declaration", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_relative_path", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_parameters", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_component_id", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_node_text" - ], - "source_code": " def _extract_function_declaration(self, node) -> Optional[Node]:\n try:\n name_node = self._find_child_by_type(node, \"identifier\")\n if not name_node:\n return None\n\n func_name = self._get_node_text(name_node)\n line_start = node.start_point[0] + 1\n line_end = node.end_point[0] + 1\n parameters = self._extract_parameters(node)\n code_snippet = self._get_node_text(node)\n\n # Check for async and generator from code snippet\n is_async = \"async function\" in code_snippet\n is_generator = \"function*\" in code_snippet or \"*\" in func_name\n \n if is_async and is_generator:\n display_name = f\"async generator {func_name}\"\n elif is_async:\n display_name = f\"async function {func_name}\"\n elif is_generator:\n display_name = f\"generator function {func_name}\"\n else:\n display_name = f\"function {func_name}\"\n\n component_id = self._get_component_id(func_name, is_method=False)\n relative_path = self._get_relative_path()\n\n return Node(\n id=component_id,\n name=func_name,\n component_type=\"function\",\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=code_snippet,\n start_line=line_start,\n end_line=line_end,\n has_docstring=False,\n docstring=\"\",\n parameters=parameters,\n node_type=\"function\",\n base_classes=None,\n class_name=None,\n display_name=display_name,\n component_id=component_id,\n )\n except Exception as e:\n logger.debug(f\"Error extracting function declaration: {e}\")\n return None", - "start_line": 301, - "end_line": 349, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._extract_function_declaration", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_function_declaration", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_exported_function": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_exported_function", - "name": "TreeSitterJSAnalyzer._extract_exported_function", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_function_declaration", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_node_text" - ], - "source_code": " def _extract_exported_function(self, node) -> Optional[Node]:\n \"\"\"Extract export function or export default function\"\"\"\n try:\n func_decl = self._find_child_by_type(node, \"function_declaration\")\n if func_decl:\n func = self._extract_function_declaration(func_decl)\n if func:\n export_text = self._get_node_text(node)\n if \"export default\" in export_text and \"function (\" in export_text:\n func.name = \"default\"\n return func\n except Exception as e:\n logger.debug(f\"Error extracting exported function: {e}\")\n return None", - "start_line": 350, - "end_line": 363, - "has_docstring": true, - "docstring": "Extract export function or export default function", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._extract_exported_function", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_exported_function", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_arrow_function_from_declaration": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_arrow_function_from_declaration", - "name": "TreeSitterJSAnalyzer._extract_arrow_function_from_declaration", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_relative_path", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_parameters", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_component_id", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_node_text" - ], - "source_code": " def _extract_arrow_function_from_declaration(self, node) -> Optional[Node]:\n \"\"\"Extract arrow function or function expression from const/let/var declarations.\"\"\"\n try:\n for child in node.children:\n if child.type == \"variable_declarator\":\n name_node = self._find_child_by_type(child, \"identifier\")\n func_node = self._find_child_by_type(\n child, \"arrow_function\"\n ) or self._find_child_by_type(child, \"function_expression\")\n\n if name_node and func_node:\n func_name = self._get_node_text(name_node)\n line_start = func_node.start_point[0] + 1\n line_end = func_node.end_point[0] + 1\n parameters = self._extract_parameters(func_node)\n code_snippet = self._get_node_text(child)\n\n component_id = self._get_component_id(func_name, is_method=False)\n relative_path = self._get_relative_path()\n\n return Node(\n id=component_id,\n name=func_name,\n component_type=\"function\",\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=code_snippet,\n start_line=line_start,\n end_line=line_end,\n has_docstring=False,\n docstring=\"\",\n parameters=parameters,\n node_type=\"function\",\n base_classes=None,\n class_name=None,\n display_name=f\"function {func_name}\",\n component_id=component_id,\n )\n return None\n except Exception as e:\n logger.debug(f\"Error extracting function from declaration: {e}\")\n return None", - "start_line": 365, - "end_line": 406, - "has_docstring": true, - "docstring": "Extract arrow function or function expression from const/let/var declarations.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._extract_arrow_function_from_declaration", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_arrow_function_from_declaration", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._should_include_function": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._should_include_function", - "name": "TreeSitterJSAnalyzer._should_include_function", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": " def _should_include_function(self, func: Node) -> bool:\n excluded_names = {}\n\n if func.name.lower() in excluded_names:\n logger.debug(f\"Skipping excluded function: {func.name}\")\n return False\n\n return True", - "start_line": 408, - "end_line": 415, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "func" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._should_include_function", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._should_include_function", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_parameters": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_parameters", - "name": "TreeSitterJSAnalyzer._extract_parameters", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_node_text" - ], - "source_code": " def _extract_parameters(self, node) -> List[str]:\n parameters = []\n params_node = self._find_child_by_type(node, \"formal_parameters\")\n if params_node:\n for child in params_node.children:\n if child.type == \"identifier\":\n parameters.append(self._get_node_text(child))\n return parameters", - "start_line": 417, - "end_line": 424, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._extract_parameters", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_parameters", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_call_relationships": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_call_relationships", - "name": "TreeSitterJSAnalyzer._extract_call_relationships", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._traverse_for_calls" - ], - "source_code": " def _extract_call_relationships(self, node) -> None:\n current_top_level = None\n self._traverse_for_calls(node, current_top_level)", - "start_line": 426, - "end_line": 428, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._extract_call_relationships", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_call_relationships", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._traverse_for_calls": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._traverse_for_calls", - "name": "TreeSitterJSAnalyzer._traverse_for_calls", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_containing_class", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_call_from_node", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_jsdoc_type_dependencies", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_relative_path", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_field_name", - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_component_id", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_method_name", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._add_relationship", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._traverse_for_calls", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_node_text" - ], - "source_code": " def _traverse_for_calls(self, node, current_top_level) -> None:\n if current_top_level:\n self._extract_jsdoc_type_dependencies(node, current_top_level)\n \n if node.type in [\"class_declaration\", \"abstract_class_declaration\", \"interface_declaration\"]:\n name_node = self._find_child_by_type(node, \"type_identifier\") or self._find_child_by_type(node, \"identifier\")\n if name_node:\n current_top_level = self._get_node_text(name_node)\n \n heritage_node = self._find_child_by_type(node, \"class_heritage\")\n if heritage_node:\n for child in heritage_node.children:\n if child.type in [\"identifier\", \"type_identifier\"]:\n base_class = self._get_node_text(child)\n caller_id = self._get_component_id(current_top_level)\n resolved = base_class in self.top_level_nodes\n callee_id = self._get_component_id(base_class) if resolved else base_class\n inheritance_rel = CallRelationship(\n caller=caller_id,\n callee=callee_id,\n call_line=node.start_point[0] + 1,\n is_resolved=resolved\n )\n self._add_relationship(inheritance_rel)\n\n elif node.type in (\"method_definition\", \"field_definition\"):\n name = self._get_method_name(node) if node.type == \"method_definition\" else self._get_field_name(node)\n containing_class = self._find_containing_class(node)\n if name and containing_class and f\"{containing_class}.{name}\" in self.top_level_nodes:\n current_top_level = f\"{containing_class}.{name}\"\n\n elif node.type == \"function_declaration\":\n name_node = self._find_child_by_type(node, \"identifier\")\n if name_node:\n current_top_level = self._get_node_text(name_node)\n elif node.type == \"generator_function_declaration\":\n name_node = self._find_child_by_type(node, \"identifier\")\n if name_node:\n current_top_level = self._get_node_text(name_node)\n elif node.type == \"lexical_declaration\":\n for child in node.children:\n if child.type == \"variable_declarator\":\n name_node = self._find_child_by_type(child, \"identifier\")\n func_node = self._find_child_by_type(child, \"arrow_function\") or self._find_child_by_type(child, \"function_expression\")\n if name_node and func_node:\n current_top_level = self._get_node_text(name_node)\n\n if node.type == \"call_expression\" and current_top_level:\n call_info = self._extract_call_from_node(node, current_top_level)\n if call_info:\n self._add_relationship(call_info)\n \n elif node.type == \"await_expression\" and current_top_level:\n call_expr = self._find_child_by_type(node, \"call_expression\")\n if call_expr:\n call_info = self._extract_call_from_node(call_expr, current_top_level)\n if call_info:\n self._add_relationship(call_info)\n \n elif node.type == \"new_expression\" and current_top_level:\n constructor_node = self._find_child_by_type(node, \"identifier\")\n if constructor_node is not None:\n callee_name = self._get_node_text(constructor_node)\n resolved = callee_name in self.top_level_nodes\n call_info = CallRelationship(\n caller=f\"{self._get_relative_path()}::{current_top_level}\",\n callee=self._get_component_id(callee_name) if resolved else callee_name,\n call_line=node.start_point[0] + 1,\n is_resolved=resolved\n )\n self._add_relationship(call_info)\n\n for child in node.children:\n self._traverse_for_calls(child, current_top_level)", - "start_line": 430, - "end_line": 503, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "current_top_level" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._traverse_for_calls", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._traverse_for_calls", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_call_from_node": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_call_from_node", - "name": "TreeSitterJSAnalyzer._extract_call_from_node", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._receiver_class", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_relative_path", - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._identifier_chain", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_component_id", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_node_text" - ], - "source_code": " def _extract_call_from_node(self, node, caller_name: str) -> Optional[CallRelationship]:\n \"\"\"Extract one relationship from a call_expression node.\n\n Plain identifier calls resolve against same-file components; member\n calls resolve receiver-first (this/super against the enclosing class,\n new-ed variables against their class). Unresolved callees stay bare\n logical names, never file-prefixed.\n \"\"\"\n try:\n call_line = node.start_point[0] + 1\n caller_id = f\"{self._get_relative_path()}::{caller_name}\"\n func_node = node.children[0] if node.children else None\n if func_node is None:\n return None\n\n def make(callee_name: str, resolved: bool) -> CallRelationship:\n return CallRelationship(\n caller=caller_id,\n callee=self._get_component_id(callee_name) if resolved else callee_name,\n call_line=call_line,\n is_resolved=resolved,\n )\n\n if func_node.type == \"identifier\":\n name = self._get_node_text(func_node)\n if not name:\n return None\n return make(name, name in self.top_level_nodes)\n\n if func_node.type != \"member_expression\":\n return None\n\n property_node = func_node.child_by_field_name(\"property\")\n obj = func_node.child_by_field_name(\"object\")\n if property_node is None or property_node.type != \"property_identifier\" or obj is None:\n return None\n tail = self._get_node_text(property_node)\n\n if obj.type in (\"this\", \"super\"):\n class_name = caller_name.split(\".\")[0]\n candidates = [] if obj.type == \"super\" else [class_name]\n class_node = self.top_level_nodes.get(class_name)\n if class_node is not None and class_node.base_classes:\n candidates.extend(class_node.base_classes)\n for candidate in candidates:\n if f\"{candidate}.{tail}\" in self.top_level_nodes:\n return make(f\"{candidate}.{tail}\", True)\n target = candidates[0] if candidates else class_name\n return make(f\"{target}.{tail}\", False)\n\n if obj.type == \"identifier\":\n receiver = self._get_node_text(obj)\n if receiver in self.top_level_nodes or self._receiver_class(node, receiver):\n cls = receiver if receiver in self.top_level_nodes else self._receiver_class(node, receiver)\n return make(f\"{cls}.{tail}\", f\"{cls}.{tail}\" in self.top_level_nodes)\n return make(f\"{receiver}.{tail}\", False)\n\n if obj.type == \"member_expression\":\n chain = self._identifier_chain(obj)\n if chain:\n return make(f\"{chain}.{tail}\", False)\n\n # Composite or literal receiver: a builtin-prototype method on an\n # unknowable receiver can never resolve to a project component.\n if tail not in JS_TS_PROTOTYPE_METHODS:\n return make(tail, False)\n return None\n\n except Exception as e:\n logger.debug(f\"Error extracting call relationship: {e}\")\n return None", - "start_line": 505, - "end_line": 575, - "has_docstring": true, - "docstring": "Extract one relationship from a call_expression node.\n\nPlain identifier calls resolve against same-file components; member\ncalls resolve receiver-first (this/super against the enclosing class,\nnew-ed variables against their class). Unresolved callees stay bare\nlogical names, never file-prefixed.", - "parameters": [ - "self", - "node", - "caller_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._extract_call_from_node", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_call_from_node", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._identifier_chain": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._identifier_chain", - "name": "TreeSitterJSAnalyzer._identifier_chain", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_node_text" - ], - "source_code": " def _identifier_chain(self, node) -> Optional[str]:\n \"\"\"Flatten a member expression into dotted text when it is a pure\n identifier chain; None when any link is computed.\"\"\"\n parts = []\n current = node\n while current.type == \"member_expression\":\n property_node = current.child_by_field_name(\"property\")\n if property_node is None or property_node.type != \"property_identifier\":\n return None\n parts.append(self._get_node_text(property_node))\n current = current.child_by_field_name(\"object\")\n if current is None:\n return None\n if current.type != \"identifier\":\n return None\n parts.append(self._get_node_text(current))\n return \".\".join(reversed(parts))", - "start_line": 577, - "end_line": 593, - "has_docstring": true, - "docstring": "Flatten a member expression into dotted text when it is a pure\nidentifier chain; None when any link is computed.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._identifier_chain", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._identifier_chain", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._receiver_class": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._receiver_class", - "name": "TreeSitterJSAnalyzer._receiver_class", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_new_initializer" - ], - "source_code": " def _receiver_class(self, call_node, identifier: str) -> Optional[str]:\n \"\"\"Find the class of a local identifier from a `new X()` initializer\n in an enclosing scope.\"\"\"\n scope = call_node.parent\n while scope:\n if scope.type in (\n \"method_definition\", \"function_declaration\",\n \"generator_function_declaration\", \"arrow_function\",\n \"function_expression\", \"program\",\n ):\n found = self._find_new_initializer(scope, identifier)\n if found:\n return found\n scope = scope.parent\n return None", - "start_line": 595, - "end_line": 609, - "has_docstring": true, - "docstring": "Find the class of a local identifier from a `new X()` initializer\nin an enclosing scope.", - "parameters": [ - "self", - "call_node", - "identifier" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._receiver_class", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._receiver_class", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_new_initializer": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_new_initializer", - "name": "TreeSitterJSAnalyzer._find_new_initializer", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_node_text" - ], - "source_code": " def _find_new_initializer(self, scope_node, identifier: str) -> Optional[str]:\n stack = [scope_node]\n while stack:\n current = stack.pop()\n if current.type == \"variable_declarator\":\n name_node = self._find_child_by_type(current, \"identifier\")\n if name_node is not None and self._get_node_text(name_node) == identifier:\n new_expr = self._find_child_by_type(current, \"new_expression\")\n if new_expr is not None:\n ctor = self._find_child_by_type(new_expr, \"identifier\")\n if ctor is not None:\n return self._get_node_text(ctor)\n stack.extend(current.children)\n return None", - "start_line": 611, - "end_line": 624, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "scope_node", - "identifier" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._find_new_initializer", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_new_initializer", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_jsdoc_type_dependencies": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_jsdoc_type_dependencies", - "name": "TreeSitterJSAnalyzer._extract_jsdoc_type_dependencies", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._parse_jsdoc_types", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_node_text" - ], - "source_code": " def _extract_jsdoc_type_dependencies(self, node, caller_name: str) -> None:\n \"\"\"Extract type dependencies from JSDoc comments.\"\"\"\n try:\n if hasattr(node, 'prev_sibling') and node.prev_sibling:\n prev = node.prev_sibling\n if prev.type == \"comment\":\n comment_text = self._get_node_text(prev)\n self._parse_jsdoc_types(comment_text, caller_name, node.start_point[0] + 1)\n \n for child in node.children:\n if child.type == \"comment\":\n comment_text = self._get_node_text(child)\n self._parse_jsdoc_types(comment_text, caller_name, node.start_point[0] + 1)\n \n except Exception as e:\n logger.debug(f\"Error extracting JSDoc dependencies: {e}\")", - "start_line": 626, - "end_line": 641, - "has_docstring": true, - "docstring": "Extract type dependencies from JSDoc comments.", - "parameters": [ - "self", - "node", - "caller_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._extract_jsdoc_type_dependencies", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_jsdoc_type_dependencies", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._parse_jsdoc_types": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._parse_jsdoc_types", - "name": "TreeSitterJSAnalyzer._parse_jsdoc_types", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_base_types_from_jsdoc", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_relative_path", - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_component_id", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._add_relationship", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._is_builtin_type_js", - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": " def _parse_jsdoc_types(self, comment_text: str, caller_name: str, line_number: int) -> None:\n \"\"\"Parse JSDoc comment text and extract type references.\"\"\"\n import re\n try:\n type_patterns = [\n r'@param\\s*\\{([^}]+)\\}', # @param {Type}\n r'@returns?\\s*\\{([^}]+)\\}', # @return {Type} or @returns {Type}\n r'@type\\s*\\{([^}]+)\\}', # @type {Type}\n r'@typedef\\s*\\{[^}]*\\}\\s*(\\w+)', # @typedef {Object} TypeName\n r'@interface\\s+(\\w+)', # @interface InterfaceName\n ]\n \n for pattern in type_patterns:\n matches = re.findall(pattern, comment_text)\n for match in matches:\n type_name = match.strip()\n \n base_types = self._extract_base_types_from_jsdoc(type_name)\n \n for base_type in base_types:\n if base_type and not self._is_builtin_type_js(base_type):\n caller_id = f\"{self._get_relative_path()}::{caller_name}\"\n resolved = base_type in self.top_level_nodes\n callee_id = self._get_component_id(base_type) if resolved else base_type\n\n type_rel = CallRelationship(\n caller=caller_id,\n callee=callee_id,\n call_line=line_number,\n is_resolved=resolved\n )\n \n if self._add_relationship(type_rel):\n pass\n \n except Exception as e:\n logger.debug(f\"Error parsing JSDoc types: {e}\")", - "start_line": 643, - "end_line": 679, - "has_docstring": true, - "docstring": "Parse JSDoc comment text and extract type references.", - "parameters": [ - "self", - "comment_text", - "caller_name", - "line_number" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._parse_jsdoc_types", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._parse_jsdoc_types", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_base_types_from_jsdoc": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_base_types_from_jsdoc", - "name": "TreeSitterJSAnalyzer._extract_base_types_from_jsdoc", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [], - "source_code": " def _extract_base_types_from_jsdoc(self, type_str: str) -> list:\n import re\n type_str = type_str.strip()\n \n base_types = []\n \n main_type_match = re.match(r'^(\\w+)', type_str)\n if main_type_match:\n base_types.append(main_type_match.group(1))\n \n generic_matches = re.findall(r'<([^<>]+)>', type_str)\n for generic in generic_matches:\n subtypes = re.findall(r'\\b(\\w+)\\b', generic)\n base_types.extend(subtypes)\n \n if '|' in type_str:\n union_types = type_str.split('|')\n for union_type in union_types:\n clean_type = re.match(r'\\b(\\w+)\\b', union_type.strip())\n if clean_type:\n base_types.append(clean_type.group(1))\n \n return base_types", - "start_line": 681, - "end_line": 703, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "type_str" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._extract_base_types_from_jsdoc", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_base_types_from_jsdoc", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._is_builtin_type_js": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._is_builtin_type_js", - "name": "TreeSitterJSAnalyzer._is_builtin_type_js", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [], - "source_code": " def _is_builtin_type_js(self, name: str) -> bool:\n \"\"\"Check if type name is a JavaScript/JSDoc built-in type.\"\"\"\n builtin_types = {\n # JavaScript primitive types\n \"string\", \"number\", \"boolean\", \"object\", \"undefined\", \"null\", \"void\", \"any\",\n \n # Global JavaScript types\n \"Array\", \"Promise\", \"Date\", \"RegExp\", \"Error\", \"Map\", \"Set\", \"WeakMap\", \"WeakSet\",\n \"Function\", \"Object\", \"String\", \"Number\", \"Boolean\", \"Symbol\", \"BigInt\",\n \n \"Element\", \"HTMLElement\", \"Document\", \"Window\", \"Event\", \"EventTarget\", \"Node\",\n \"Response\", \"Request\", \"Headers\", \"URL\", \"URLSearchParams\", \"FormData\", \"Blob\", \"File\",\n \n # Common JSDoc generic parameters\n \"T\", \"U\", \"V\", \"K\", \"P\", \"R\", \"E\"\n }\n return name in builtin_types", - "start_line": 705, - "end_line": 721, - "has_docstring": true, - "docstring": "Check if type name is a JavaScript/JSDoc built-in type.", - "parameters": [ - "self", - "name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._is_builtin_type_js", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._is_builtin_type_js", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_callee_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_callee_name", - "name": "TreeSitterJSAnalyzer._extract_callee_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_node_text" - ], - "source_code": " def _extract_callee_name(self, call_node) -> Optional[str]:\n if not call_node.children:\n return None\n \n callee_node = call_node.children[0]\n\n if callee_node.type == \"identifier\":\n return self._get_node_text(callee_node)\n elif callee_node.type == \"member_expression\":\n property_node = self._find_child_by_type(callee_node, \"property_identifier\")\n if property_node:\n return self._get_node_text(property_node)\n \n computed_property = self._find_child_by_type(callee_node, \"computed_property_name\")\n if computed_property:\n for child in computed_property.children:\n if child.type == \"identifier\":\n return self._get_node_text(child)\n elif callee_node.type == \"super\":\n return \"super\"\n elif callee_node.type == \"this\":\n return \"this\"\n \n return None", - "start_line": 723, - "end_line": 746, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "call_node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._extract_callee_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_callee_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_child_by_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_child_by_type", - "name": "TreeSitterJSAnalyzer._find_child_by_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [], - "source_code": " def _find_child_by_type(self, node, node_type: str):\n \"\"\"Find first child node of specified type.\"\"\"\n for child in node.children:\n if child.type == node_type:\n return child\n return None", - "start_line": 748, - "end_line": 753, - "has_docstring": true, - "docstring": "Find first child node of specified type.", - "parameters": [ - "self", - "node", - "node_type" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._find_child_by_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_child_by_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_node_text": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_node_text", - "name": "TreeSitterJSAnalyzer._get_node_text", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [], - "source_code": " def _get_node_text(self, node) -> str:\n start_byte = node.start_byte\n end_byte = node.end_byte\n return self.content.encode(\"utf8\")[start_byte:end_byte].decode(\"utf8\")", - "start_line": 755, - "end_line": 758, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._get_node_text", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_node_text", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_containing_class_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_containing_class_name", - "name": "TreeSitterJSAnalyzer._find_containing_class_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_node_text" - ], - "source_code": " def _find_containing_class_name(self, method_node) -> Optional[str]:\n current = method_node.parent\n while current:\n if current.type == \"class_declaration\":\n name_node = self._find_child_by_type(current, \"identifier\")\n if name_node:\n return self._get_node_text(name_node)\n current = current.parent\n return None", - "start_line": 760, - "end_line": 768, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "method_node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._find_containing_class_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_containing_class_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_assignment_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_assignment_name", - "name": "TreeSitterJSAnalyzer._extract_assignment_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._get_node_text" - ], - "source_code": " def _extract_assignment_name(self, node) -> Optional[str]:\n if node.type == \"identifier\":\n return self._get_node_text(node)\n elif node.type == \"member_expression\":\n property_node = self._find_child_by_type(node, \"property_identifier\")\n if property_node:\n return self._get_node_text(property_node)\n return None", - "start_line": 770, - "end_line": 777, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterJSAnalyzer", - "display_name": "method TreeSitterJSAnalyzer._extract_assignment_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer._extract_assignment_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::analyze_javascript_file_treesitter": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::analyze_javascript_file_treesitter", - "name": "analyze_javascript_file_treesitter", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::TreeSitterJSAnalyzer.analyze", - "codewiki/cli/utils/logging.py::CLILogger.error", - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": "def analyze_javascript_file_treesitter(\n file_path: str, content: str, repo_path: str = None\n) -> Tuple[List[Node], List[CallRelationship]]:\n \"\"\"Analyze a JavaScript file using tree-sitter.\"\"\"\n try:\n logger.debug(f\"Tree-sitter JS analysis for {file_path}\")\n analyzer = TreeSitterJSAnalyzer(file_path, content, repo_path)\n analyzer.analyze()\n logger.debug(\n f\"Found {len(analyzer.nodes)} top-level nodes, {len(analyzer.call_relationships)} calls\"\n )\n return analyzer.nodes, analyzer.call_relationships\n except Exception as e:\n logger.error(f\"Error in tree-sitter JS analysis for {file_path}: {e}\", exc_info=True)\n return [], []", - "start_line": 779, - "end_line": 793, - "has_docstring": true, - "docstring": "Analyze a JavaScript file using tree-sitter.", - "parameters": [ - "file_path", - "content", - "repo_path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function analyze_javascript_file_treesitter", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/javascript.py::analyze_javascript_file_treesitter", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer", - "name": "TreeSitterKotlinAnalyzer", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "depends_on": [], - "source_code": "class TreeSitterKotlinAnalyzer:\n def __init__(self, file_path: str, content: str, repo_path: Optional[str] = None):\n self.file_path = Path(file_path)\n self.content = content\n self.repo_path = repo_path or \"\"\n self.nodes: List[Node] = []\n self.call_relationships: List[CallRelationship] = []\n self._analyze()\n \n def _get_module_path(self) -> str:\n if self.repo_path:\n try:\n rel_path = os.path.relpath(str(self.file_path), self.repo_path)\n except ValueError:\n rel_path = str(self.file_path)\n else:\n rel_path = str(self.file_path)\n \n for ext in ['.kt', '.kts']:\n if rel_path.endswith(ext):\n rel_path = rel_path[:-len(ext)]\n break\n return rel_path.replace('/', '.').replace('\\\\', '.')\n \n def _get_relative_path(self) -> str:\n \"\"\"Get relative path from repo root.\"\"\"\n if self.repo_path:\n try:\n return os.path.relpath(str(self.file_path), self.repo_path)\n except ValueError:\n return str(self.file_path)\n else:\n return str(self.file_path)\n \n def _get_component_id(self, name: str, parent_class: Optional[str] = None) -> str:\n rel_path = self._get_relative_path()\n if parent_class:\n return f\"{rel_path}::{parent_class}.{name}\"\n else:\n return f\"{rel_path}::{name}\"\n\n def _analyze(self):\n try:\n language_capsule = tree_sitter_kotlin.language()\n kotlin_language = Language(language_capsule)\n parser = Parser(kotlin_language)\n tree = parser.parse(bytes(self.content, \"utf8\"))\n root = tree.root_node\n lines = self.content.splitlines()\n \n top_level_nodes = {}\n \n self._extract_nodes(root, top_level_nodes, lines)\n self._extract_relationships(root, top_level_nodes)\n except Exception as e:\n logger.error(f\"Error parsing Kotlin file {self.file_path}: {e}\")\n \n def _extract_nodes(self, node, top_level_nodes, lines):\n node_type = None\n node_name = None\n \n if node.type == \"class_declaration\":\n is_interface = any(c.type == \"interface\" for c in node.children)\n \n if is_interface:\n node_type = \"interface\"\n else:\n modifiers = self._get_class_modifiers(node)\n if \"abstract\" in modifiers:\n node_type = \"abstract class\"\n elif \"data\" in modifiers:\n node_type = \"data class\"\n elif \"enum\" in modifiers:\n node_type = \"enum class\"\n elif \"annotation\" in modifiers:\n node_type = \"annotation class\"\n else:\n node_type = \"class\"\n \n name_node = next((c for c in node.children if c.type == \"identifier\"), None)\n node_name = name_node.text.decode() if name_node else None\n \n elif node.type == \"object_declaration\":\n node_type = \"object\"\n name_node = next((c for c in node.children if c.type == \"identifier\"), None)\n node_name = name_node.text.decode() if name_node else None\n \n elif node.type == \"function_declaration\":\n name_node = next((c for c in node.children if c.type == \"identifier\"), None)\n if name_node:\n method_name = name_node.text.decode()\n containing_class = self._find_containing_class_name(node)\n if containing_class:\n node_type = \"method\"\n node_name = f\"{containing_class}.{method_name}\"\n else:\n node_type = \"function\"\n node_name = method_name\n \n if node_type and node_name:\n component_id = self._get_component_id(node_name)\n relative_path = self._get_relative_path()\n \n # Extract docstring if present\n docstring = \"\"\n if node.prev_sibling and hasattr(node.prev_sibling, \"type\"):\n if node.prev_sibling.type in (\"line_comment\", \"block_comment\"):\n docstring = node.prev_sibling.text.decode().strip()\n \n # Safely extract code lines\n start_line_idx = node.start_point[0]\n end_line_idx = node.end_point[0] + 1\n code_snippet = \"\\n\".join(lines[start_line_idx:end_line_idx]) if start_line_idx < len(lines) else \"\"\n \n node_obj = Node(\n id=component_id,\n name=node_name,\n component_type=node_type,\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=code_snippet,\n start_line=node.start_point[0]+1,\n end_line=node.end_point[0]+1,\n has_docstring=bool(docstring),\n docstring=docstring,\n parameters=None,\n node_type=node_type,\n base_classes=None,\n class_name=None,\n display_name=f\"{node_type} {node_name}\",\n component_id=component_id\n )\n self.nodes.append(node_obj)\n top_level_nodes[node_name] = node_obj\n \n for child in node.children:\n self._extract_nodes(child, top_level_nodes, lines)\n \n def _get_class_modifiers(self, class_node) -> set:\n \"\"\"Extract class modifiers (abstract, data, enum, annotation, etc.).\"\"\"\n modifiers = set()\n modifiers_node = next((c for c in class_node.children if c.type == \"modifiers\"), None)\n if modifiers_node:\n for mod in modifiers_node.children:\n if mod.type in (\"class_modifier\", \"inheritance_modifier\", \"visibility_modifier\"):\n for inner in mod.children:\n modifiers.add(inner.type)\n return modifiers\n \n def _extract_relationships(self, node, top_level_nodes):\n # 1. Inheritance and Interface Implementation via delegation_specifiers\n if node.type == \"class_declaration\":\n class_name = self._get_identifier_name(node)\n delegation_specifiers = next(\n (c for c in node.children if c.type == \"delegation_specifiers\"), None\n )\n if delegation_specifiers and class_name:\n for spec in delegation_specifiers.children:\n if spec.type == \"delegation_specifier\":\n for child in spec.children:\n type_name = None\n if child.type == \"constructor_invocation\":\n user_type = next(\n (c for c in child.children if c.type == \"user_type\"), None\n )\n if user_type:\n type_name = self._get_type_name(user_type)\n elif child.type == \"user_type\":\n type_name = self._get_type_name(child)\n \n if type_name and not self._is_primitive_type(type_name):\n caller_id = self._get_component_id(class_name)\n callee_id = self._get_component_id(type_name)\n self.call_relationships.append(CallRelationship(\n caller=caller_id,\n callee=callee_id,\n call_line=node.start_point[0]+1,\n is_resolved=False\n ))\n \n # 2. Property Type Use (field types)\n if node.type == \"property_declaration\":\n containing_class = self._find_containing_class(node, top_level_nodes)\n var_decl = next((c for c in node.children if c.type == \"variable_declaration\"), None)\n if containing_class and var_decl:\n type_node = next(\n (c for c in var_decl.children if c.type == \"user_type\"), None\n )\n if type_node:\n prop_type_name = self._get_type_name(type_node)\n if prop_type_name and not self._is_primitive_type(prop_type_name):\n self.call_relationships.append(CallRelationship(\n caller=containing_class,\n callee=prop_type_name,\n call_line=node.start_point[0]+1,\n is_resolved=False\n ))\n \n # 3. Constructor parameter type use\n if node.type == \"class_parameter\":\n containing_class_node = node.parent\n while containing_class_node and containing_class_node.type != \"class_declaration\":\n containing_class_node = containing_class_node.parent\n if containing_class_node:\n class_name = self._get_identifier_name(containing_class_node)\n if class_name and class_name in top_level_nodes:\n type_node = next(\n (c for c in node.children if c.type == \"user_type\"), None\n )\n if type_node:\n param_type = self._get_type_name(type_node)\n if param_type and not self._is_primitive_type(param_type):\n caller_id = self._get_component_id(class_name)\n self.call_relationships.append(CallRelationship(\n caller=caller_id,\n callee=param_type,\n call_line=node.start_point[0]+1,\n is_resolved=False\n ))\n \n # 4. Method Calls / Function invocations\n if node.type == \"call_expression\":\n caller_id = self._find_containing_method(node) or self._find_containing_class(node, top_level_nodes)\n \n target_expr = next(\n (c for c in node.children if c.type in [\"identifier\", \"navigation_expression\"]), None\n )\n \n if target_expr and caller_id:\n if target_expr.type == \"identifier\":\n callee_name = target_expr.text.decode()\n if callee_name and callee_name[0].isupper() and not self._is_primitive_type(callee_name):\n callee_id = self._get_component_id(callee_name)\n self.call_relationships.append(CallRelationship(\n caller=caller_id,\n callee=callee_id,\n call_line=node.start_point[0]+1,\n is_resolved=False\n ))\n elif callee_name and not self._is_primitive_type(callee_name):\n self.call_relationships.append(CallRelationship(\n caller=caller_id,\n callee=callee_name,\n call_line=node.start_point[0]+1,\n is_resolved=False\n ))\n \n elif target_expr.type == \"navigation_expression\":\n children = list(target_expr.children)\n object_node = next(\n (c for c in children if c.type == \"identifier\"), None\n )\n method_node = None\n identifiers = [c for c in children if c.type == \"identifier\"]\n if len(identifiers) >= 2:\n object_node = identifiers[0]\n method_node = identifiers[-1]\n elif len(identifiers) == 1:\n method_node = identifiers[0]\n nav_child = next(\n (c for c in children if c.type == \"navigation_expression\"), None\n )\n if nav_child:\n object_node = self._get_root_identifier(nav_child)\n else:\n object_node = None\n \n if object_node and method_node:\n object_name = object_node.text.decode() if hasattr(object_node, 'text') else str(object_node)\n method_name = method_node.text.decode()\n \n target_type = None\n if object_name in top_level_nodes:\n target_type = object_name\n else:\n target_type = self._find_variable_type(node, object_name, top_level_nodes)\n \n if target_type and not self._is_primitive_type(target_type):\n callee_id = self._get_component_id(target_type)\n self.call_relationships.append(CallRelationship(\n caller=caller_id,\n callee=callee_id,\n call_line=node.start_point[0]+1,\n is_resolved=False\n ))\n elif method_node and not object_node:\n callee_name = method_node.text.decode()\n self.call_relationships.append(CallRelationship(\n caller=caller_id,\n callee=callee_name,\n call_line=node.start_point[0]+1,\n is_resolved=False\n ))\n \n for child in node.children:\n self._extract_relationships(child, top_level_nodes)\n\n def _is_primitive_type(self, type_name: str) -> bool:\n \"\"\"Check if type is a Kotlin primitive or common built-in type.\"\"\"\n primitives = {\n \"Boolean\", \"Byte\", \"Char\", \"Double\", \"Float\", \"Int\", \"Long\", \"Short\",\n \"String\", \"Unit\", \"Nothing\", \"Any\",\n \"List\", \"Set\", \"Map\", \"Collection\", \"Iterable\", \"Sequence\",\n \"MutableList\", \"MutableSet\", \"MutableMap\", \"MutableCollection\",\n \"Array\", \"IntArray\", \"LongArray\", \"FloatArray\", \"DoubleArray\",\n \"BooleanArray\", \"ByteArray\", \"CharArray\", \"ShortArray\",\n \"Pair\", \"Triple\",\n }\n return type_name in primitives\n\n def _get_identifier_name(self, node):\n \"\"\"Get identifier name from a node.\"\"\"\n name_node = next((c for c in node.children if c.type == \"identifier\"), None)\n return name_node.text.decode() if name_node else None\n \n def _get_type_name(self, node) -> Optional[str]:\n \"\"\"Get the primary type name from a type node, stripping generics.\"\"\"\n if node.type == \"user_type\":\n id_node = next((c for c in node.children if c.type == \"identifier\"), None)\n return id_node.text.decode() if id_node else None\n elif node.type == \"nullable_type\":\n inner = next((c for c in node.children if c.type == \"user_type\"), None)\n if inner:\n return self._get_type_name(inner)\n elif node.type == \"identifier\":\n return node.text.decode()\n return None\n \n def _get_root_identifier(self, nav_node):\n \"\"\"Get the root identifier from a chain of navigation_expressions.\"\"\"\n first_child = nav_node.children[0] if nav_node.children else None\n if first_child:\n if first_child.type == \"identifier\":\n return first_child\n elif first_child.type == \"navigation_expression\":\n return self._get_root_identifier(first_child)\n return None\n\n def _find_containing_class_name(self, node):\n \"\"\"Walk up to find the containing class/object/interface name.\"\"\"\n current = node.parent\n while current:\n if current.type in (\"class_declaration\", \"object_declaration\"):\n name_node = next((c for c in current.children if c.type == \"identifier\"), None)\n if name_node:\n return name_node.text.decode()\n current = current.parent\n return None\n \n def _find_containing_class(self, node, top_level_nodes):\n \"\"\"Find the component ID of the containing class.\"\"\"\n class_name = self._find_containing_class_name(node)\n if class_name and class_name in top_level_nodes:\n return self._get_component_id(class_name)\n return None\n\n def _find_containing_method(self, node):\n \"\"\"Find the component ID of the containing function/method.\"\"\"\n current = node.parent\n while current:\n if current.type == \"function_declaration\":\n method_name = self._get_identifier_name(current)\n class_name = self._find_containing_class_name(current)\n if method_name:\n if class_name:\n return self._get_component_id(f\"{class_name}.{method_name}\")\n return self._get_component_id(method_name)\n current = current.parent\n return None\n\n def _find_variable_type(self, node, variable_name: str, top_level_nodes) -> Optional[str]:\n \"\"\"\n Try to resolve the type of a variable by searching local declarations,\n function parameters, constructor parameters, and class properties.\n \"\"\"\n func_node = node.parent\n while func_node and func_node.type != \"function_declaration\":\n func_node = func_node.parent\n \n if func_node:\n params_node = next(\n (c for c in func_node.children if c.type == \"function_value_parameters\"), None\n )\n if params_node:\n for param in params_node.children:\n if param.type == \"parameter\":\n param_name_node = next(\n (c for c in param.children if c.type == \"identifier\"), None\n )\n if param_name_node and param_name_node.text.decode() == variable_name:\n type_node = next(\n (c for c in param.children if c.type in (\"user_type\", \"nullable_type\")), None\n )\n if type_node:\n return self._get_type_name(type_node)\n \n body_node = next(\n (c for c in func_node.children if c.type == \"function_body\"), None\n )\n if body_node:\n block = next((c for c in body_node.children if c.type == \"block\"), None)\n if block:\n result = self._search_variable_declaration(block, variable_name)\n if result:\n return result\n \n class_node = node.parent\n while class_node and class_node.type not in (\"class_declaration\", \"object_declaration\"):\n class_node = class_node.parent\n \n if class_node:\n primary_ctor = next(\n (c for c in class_node.children if c.type == \"primary_constructor\"), None\n )\n if primary_ctor:\n class_params = next(\n (c for c in primary_ctor.children if c.type == \"class_parameters\"), None\n )\n if class_params:\n for param in class_params.children:\n if param.type == \"class_parameter\":\n param_name = next(\n (c for c in param.children if c.type == \"identifier\"), None\n )\n if param_name and param_name.text.decode() == variable_name:\n type_node = next(\n (c for c in param.children if c.type in (\"user_type\", \"nullable_type\")), None\n )\n if type_node:\n return self._get_type_name(type_node)\n \n class_body = next(\n (c for c in class_node.children if c.type in (\"class_body\", \"enum_class_body\")), None\n )\n if class_body:\n for body_child in class_body.children:\n if body_child.type == \"property_declaration\":\n var_decl = next(\n (c for c in body_child.children if c.type == \"variable_declaration\"), None\n )\n if var_decl:\n prop_name = next(\n (c for c in var_decl.children if c.type == \"identifier\"), None\n )\n if prop_name and prop_name.text.decode() == variable_name:\n type_node = next(\n (c for c in var_decl.children if c.type in (\"user_type\", \"nullable_type\")), None\n )\n if type_node:\n return self._get_type_name(type_node)\n \n return None\n \n def _search_variable_declaration(self, block_node, variable_name: str) -> Optional[str]:\n \"\"\"Search for a local variable declaration with explicit type annotation in a block.\"\"\"\n for child in block_node.children:\n if child.type == \"property_declaration\":\n var_decl = next(\n (c for c in child.children if c.type == \"variable_declaration\"), None\n )\n if var_decl:\n name_node = next(\n (c for c in var_decl.children if c.type == \"identifier\"), None\n )\n if name_node and name_node.text.decode() == variable_name:\n type_node = next(\n (c for c in var_decl.children if c.type in (\"user_type\", \"nullable_type\")), None\n )\n if type_node:\n return self._get_type_name(type_node)\n \n init_expr = next(\n (c for c in child.children if c.type == \"call_expression\"), None\n )\n if init_expr:\n call_id = next(\n (c for c in init_expr.children if c.type == \"identifier\"), None\n )\n if call_id:\n inferred = call_id.text.decode()\n if inferred and inferred[0].isupper():\n return inferred\n \n elif child.type == \"block\":\n result = self._search_variable_declaration(child, variable_name)\n if result:\n return result\n \n return None", - "start_line": 13, - "end_line": 501, - "has_docstring": false, - "docstring": "", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class TreeSitterKotlinAnalyzer", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer.__init__": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer.__init__", - "name": "TreeSitterKotlinAnalyzer.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._analyze" - ], - "source_code": " def __init__(self, file_path: str, content: str, repo_path: Optional[str] = None):\n self.file_path = Path(file_path)\n self.content = content\n self.repo_path = repo_path or \"\"\n self.nodes: List[Node] = []\n self.call_relationships: List[CallRelationship] = []\n self._analyze()", - "start_line": 14, - "end_line": 20, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "file_path", - "content", - "repo_path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterKotlinAnalyzer", - "display_name": "method TreeSitterKotlinAnalyzer.__init__", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_module_path": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_module_path", - "name": "TreeSitterKotlinAnalyzer._get_module_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "depends_on": [], - "source_code": " def _get_module_path(self) -> str:\n if self.repo_path:\n try:\n rel_path = os.path.relpath(str(self.file_path), self.repo_path)\n except ValueError:\n rel_path = str(self.file_path)\n else:\n rel_path = str(self.file_path)\n \n for ext in ['.kt', '.kts']:\n if rel_path.endswith(ext):\n rel_path = rel_path[:-len(ext)]\n break\n return rel_path.replace('/', '.').replace('\\\\', '.')", - "start_line": 22, - "end_line": 35, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterKotlinAnalyzer", - "display_name": "method TreeSitterKotlinAnalyzer._get_module_path", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_module_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_relative_path": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_relative_path", - "name": "TreeSitterKotlinAnalyzer._get_relative_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "depends_on": [], - "source_code": " def _get_relative_path(self) -> str:\n \"\"\"Get relative path from repo root.\"\"\"\n if self.repo_path:\n try:\n return os.path.relpath(str(self.file_path), self.repo_path)\n except ValueError:\n return str(self.file_path)\n else:\n return str(self.file_path)", - "start_line": 37, - "end_line": 45, - "has_docstring": true, - "docstring": "Get relative path from repo root.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterKotlinAnalyzer", - "display_name": "method TreeSitterKotlinAnalyzer._get_relative_path", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_relative_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_component_id": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_component_id", - "name": "TreeSitterKotlinAnalyzer._get_component_id", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_relative_path" - ], - "source_code": " def _get_component_id(self, name: str, parent_class: Optional[str] = None) -> str:\n rel_path = self._get_relative_path()\n if parent_class:\n return f\"{rel_path}::{parent_class}.{name}\"\n else:\n return f\"{rel_path}::{name}\"", - "start_line": 47, - "end_line": 52, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "name", - "parent_class" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterKotlinAnalyzer", - "display_name": "method TreeSitterKotlinAnalyzer._get_component_id", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_component_id", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._analyze": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._analyze", - "name": "TreeSitterKotlinAnalyzer._analyze", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._extract_nodes", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._extract_relationships", - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": " def _analyze(self):\n try:\n language_capsule = tree_sitter_kotlin.language()\n kotlin_language = Language(language_capsule)\n parser = Parser(kotlin_language)\n tree = parser.parse(bytes(self.content, \"utf8\"))\n root = tree.root_node\n lines = self.content.splitlines()\n \n top_level_nodes = {}\n \n self._extract_nodes(root, top_level_nodes, lines)\n self._extract_relationships(root, top_level_nodes)\n except Exception as e:\n logger.error(f\"Error parsing Kotlin file {self.file_path}: {e}\")", - "start_line": 54, - "end_line": 68, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterKotlinAnalyzer", - "display_name": "method TreeSitterKotlinAnalyzer._analyze", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._analyze", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._extract_nodes": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._extract_nodes", - "name": "TreeSitterKotlinAnalyzer._extract_nodes", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._find_containing_class_name", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._extract_nodes", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_relative_path", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_class_modifiers", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_component_id" - ], - "source_code": " def _extract_nodes(self, node, top_level_nodes, lines):\n node_type = None\n node_name = None\n \n if node.type == \"class_declaration\":\n is_interface = any(c.type == \"interface\" for c in node.children)\n \n if is_interface:\n node_type = \"interface\"\n else:\n modifiers = self._get_class_modifiers(node)\n if \"abstract\" in modifiers:\n node_type = \"abstract class\"\n elif \"data\" in modifiers:\n node_type = \"data class\"\n elif \"enum\" in modifiers:\n node_type = \"enum class\"\n elif \"annotation\" in modifiers:\n node_type = \"annotation class\"\n else:\n node_type = \"class\"\n \n name_node = next((c for c in node.children if c.type == \"identifier\"), None)\n node_name = name_node.text.decode() if name_node else None\n \n elif node.type == \"object_declaration\":\n node_type = \"object\"\n name_node = next((c for c in node.children if c.type == \"identifier\"), None)\n node_name = name_node.text.decode() if name_node else None\n \n elif node.type == \"function_declaration\":\n name_node = next((c for c in node.children if c.type == \"identifier\"), None)\n if name_node:\n method_name = name_node.text.decode()\n containing_class = self._find_containing_class_name(node)\n if containing_class:\n node_type = \"method\"\n node_name = f\"{containing_class}.{method_name}\"\n else:\n node_type = \"function\"\n node_name = method_name\n \n if node_type and node_name:\n component_id = self._get_component_id(node_name)\n relative_path = self._get_relative_path()\n \n # Extract docstring if present\n docstring = \"\"\n if node.prev_sibling and hasattr(node.prev_sibling, \"type\"):\n if node.prev_sibling.type in (\"line_comment\", \"block_comment\"):\n docstring = node.prev_sibling.text.decode().strip()\n \n # Safely extract code lines\n start_line_idx = node.start_point[0]\n end_line_idx = node.end_point[0] + 1\n code_snippet = \"\\n\".join(lines[start_line_idx:end_line_idx]) if start_line_idx < len(lines) else \"\"\n \n node_obj = Node(\n id=component_id,\n name=node_name,\n component_type=node_type,\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=code_snippet,\n start_line=node.start_point[0]+1,\n end_line=node.end_point[0]+1,\n has_docstring=bool(docstring),\n docstring=docstring,\n parameters=None,\n node_type=node_type,\n base_classes=None,\n class_name=None,\n display_name=f\"{node_type} {node_name}\",\n component_id=component_id\n )\n self.nodes.append(node_obj)\n top_level_nodes[node_name] = node_obj\n \n for child in node.children:\n self._extract_nodes(child, top_level_nodes, lines)", - "start_line": 70, - "end_line": 149, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "top_level_nodes", - "lines" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterKotlinAnalyzer", - "display_name": "method TreeSitterKotlinAnalyzer._extract_nodes", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._extract_nodes", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_class_modifiers": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_class_modifiers", - "name": "TreeSitterKotlinAnalyzer._get_class_modifiers", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "depends_on": [], - "source_code": " def _get_class_modifiers(self, class_node) -> set:\n \"\"\"Extract class modifiers (abstract, data, enum, annotation, etc.).\"\"\"\n modifiers = set()\n modifiers_node = next((c for c in class_node.children if c.type == \"modifiers\"), None)\n if modifiers_node:\n for mod in modifiers_node.children:\n if mod.type in (\"class_modifier\", \"inheritance_modifier\", \"visibility_modifier\"):\n for inner in mod.children:\n modifiers.add(inner.type)\n return modifiers", - "start_line": 151, - "end_line": 160, - "has_docstring": true, - "docstring": "Extract class modifiers (abstract, data, enum, annotation, etc.).", - "parameters": [ - "self", - "class_node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterKotlinAnalyzer", - "display_name": "method TreeSitterKotlinAnalyzer._get_class_modifiers", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_class_modifiers", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._extract_relationships": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._extract_relationships", - "name": "TreeSitterKotlinAnalyzer._extract_relationships", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._extract_relationships", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_type_name", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_root_identifier", - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_identifier_name", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._is_primitive_type", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._find_variable_type", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._find_containing_method", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_component_id", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._find_containing_class" - ], - "source_code": " def _extract_relationships(self, node, top_level_nodes):\n # 1. Inheritance and Interface Implementation via delegation_specifiers\n if node.type == \"class_declaration\":\n class_name = self._get_identifier_name(node)\n delegation_specifiers = next(\n (c for c in node.children if c.type == \"delegation_specifiers\"), None\n )\n if delegation_specifiers and class_name:\n for spec in delegation_specifiers.children:\n if spec.type == \"delegation_specifier\":\n for child in spec.children:\n type_name = None\n if child.type == \"constructor_invocation\":\n user_type = next(\n (c for c in child.children if c.type == \"user_type\"), None\n )\n if user_type:\n type_name = self._get_type_name(user_type)\n elif child.type == \"user_type\":\n type_name = self._get_type_name(child)\n \n if type_name and not self._is_primitive_type(type_name):\n caller_id = self._get_component_id(class_name)\n callee_id = self._get_component_id(type_name)\n self.call_relationships.append(CallRelationship(\n caller=caller_id,\n callee=callee_id,\n call_line=node.start_point[0]+1,\n is_resolved=False\n ))\n \n # 2. Property Type Use (field types)\n if node.type == \"property_declaration\":\n containing_class = self._find_containing_class(node, top_level_nodes)\n var_decl = next((c for c in node.children if c.type == \"variable_declaration\"), None)\n if containing_class and var_decl:\n type_node = next(\n (c for c in var_decl.children if c.type == \"user_type\"), None\n )\n if type_node:\n prop_type_name = self._get_type_name(type_node)\n if prop_type_name and not self._is_primitive_type(prop_type_name):\n self.call_relationships.append(CallRelationship(\n caller=containing_class,\n callee=prop_type_name,\n call_line=node.start_point[0]+1,\n is_resolved=False\n ))\n \n # 3. Constructor parameter type use\n if node.type == \"class_parameter\":\n containing_class_node = node.parent\n while containing_class_node and containing_class_node.type != \"class_declaration\":\n containing_class_node = containing_class_node.parent\n if containing_class_node:\n class_name = self._get_identifier_name(containing_class_node)\n if class_name and class_name in top_level_nodes:\n type_node = next(\n (c for c in node.children if c.type == \"user_type\"), None\n )\n if type_node:\n param_type = self._get_type_name(type_node)\n if param_type and not self._is_primitive_type(param_type):\n caller_id = self._get_component_id(class_name)\n self.call_relationships.append(CallRelationship(\n caller=caller_id,\n callee=param_type,\n call_line=node.start_point[0]+1,\n is_resolved=False\n ))\n \n # 4. Method Calls / Function invocations\n if node.type == \"call_expression\":\n caller_id = self._find_containing_method(node) or self._find_containing_class(node, top_level_nodes)\n \n target_expr = next(\n (c for c in node.children if c.type in [\"identifier\", \"navigation_expression\"]), None\n )\n \n if target_expr and caller_id:\n if target_expr.type == \"identifier\":\n callee_name = target_expr.text.decode()\n if callee_name and callee_name[0].isupper() and not self._is_primitive_type(callee_name):\n callee_id = self._get_component_id(callee_name)\n self.call_relationships.append(CallRelationship(\n caller=caller_id,\n callee=callee_id,\n call_line=node.start_point[0]+1,\n is_resolved=False\n ))\n elif callee_name and not self._is_primitive_type(callee_name):\n self.call_relationships.append(CallRelationship(\n caller=caller_id,\n callee=callee_name,\n call_line=node.start_point[0]+1,\n is_resolved=False\n ))\n \n elif target_expr.type == \"navigation_expression\":\n children = list(target_expr.children)\n object_node = next(\n (c for c in children if c.type == \"identifier\"), None\n )\n method_node = None\n identifiers = [c for c in children if c.type == \"identifier\"]\n if len(identifiers) >= 2:\n object_node = identifiers[0]\n method_node = identifiers[-1]\n elif len(identifiers) == 1:\n method_node = identifiers[0]\n nav_child = next(\n (c for c in children if c.type == \"navigation_expression\"), None\n )\n if nav_child:\n object_node = self._get_root_identifier(nav_child)\n else:\n object_node = None\n \n if object_node and method_node:\n object_name = object_node.text.decode() if hasattr(object_node, 'text') else str(object_node)\n method_name = method_node.text.decode()\n \n target_type = None\n if object_name in top_level_nodes:\n target_type = object_name\n else:\n target_type = self._find_variable_type(node, object_name, top_level_nodes)\n \n if target_type and not self._is_primitive_type(target_type):\n callee_id = self._get_component_id(target_type)\n self.call_relationships.append(CallRelationship(\n caller=caller_id,\n callee=callee_id,\n call_line=node.start_point[0]+1,\n is_resolved=False\n ))\n elif method_node and not object_node:\n callee_name = method_node.text.decode()\n self.call_relationships.append(CallRelationship(\n caller=caller_id,\n callee=callee_name,\n call_line=node.start_point[0]+1,\n is_resolved=False\n ))\n \n for child in node.children:\n self._extract_relationships(child, top_level_nodes)", - "start_line": 162, - "end_line": 308, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "top_level_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterKotlinAnalyzer", - "display_name": "method TreeSitterKotlinAnalyzer._extract_relationships", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._extract_relationships", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._is_primitive_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._is_primitive_type", - "name": "TreeSitterKotlinAnalyzer._is_primitive_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "depends_on": [], - "source_code": " def _is_primitive_type(self, type_name: str) -> bool:\n \"\"\"Check if type is a Kotlin primitive or common built-in type.\"\"\"\n primitives = {\n \"Boolean\", \"Byte\", \"Char\", \"Double\", \"Float\", \"Int\", \"Long\", \"Short\",\n \"String\", \"Unit\", \"Nothing\", \"Any\",\n \"List\", \"Set\", \"Map\", \"Collection\", \"Iterable\", \"Sequence\",\n \"MutableList\", \"MutableSet\", \"MutableMap\", \"MutableCollection\",\n \"Array\", \"IntArray\", \"LongArray\", \"FloatArray\", \"DoubleArray\",\n \"BooleanArray\", \"ByteArray\", \"CharArray\", \"ShortArray\",\n \"Pair\", \"Triple\",\n }\n return type_name in primitives", - "start_line": 310, - "end_line": 321, - "has_docstring": true, - "docstring": "Check if type is a Kotlin primitive or common built-in type.", - "parameters": [ - "self", - "type_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterKotlinAnalyzer", - "display_name": "method TreeSitterKotlinAnalyzer._is_primitive_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._is_primitive_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_identifier_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_identifier_name", - "name": "TreeSitterKotlinAnalyzer._get_identifier_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "depends_on": [], - "source_code": " def _get_identifier_name(self, node):\n \"\"\"Get identifier name from a node.\"\"\"\n name_node = next((c for c in node.children if c.type == \"identifier\"), None)\n return name_node.text.decode() if name_node else None", - "start_line": 323, - "end_line": 326, - "has_docstring": true, - "docstring": "Get identifier name from a node.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterKotlinAnalyzer", - "display_name": "method TreeSitterKotlinAnalyzer._get_identifier_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_identifier_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_type_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_type_name", - "name": "TreeSitterKotlinAnalyzer._get_type_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_type_name" - ], - "source_code": " def _get_type_name(self, node) -> Optional[str]:\n \"\"\"Get the primary type name from a type node, stripping generics.\"\"\"\n if node.type == \"user_type\":\n id_node = next((c for c in node.children if c.type == \"identifier\"), None)\n return id_node.text.decode() if id_node else None\n elif node.type == \"nullable_type\":\n inner = next((c for c in node.children if c.type == \"user_type\"), None)\n if inner:\n return self._get_type_name(inner)\n elif node.type == \"identifier\":\n return node.text.decode()\n return None", - "start_line": 328, - "end_line": 339, - "has_docstring": true, - "docstring": "Get the primary type name from a type node, stripping generics.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterKotlinAnalyzer", - "display_name": "method TreeSitterKotlinAnalyzer._get_type_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_type_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_root_identifier": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_root_identifier", - "name": "TreeSitterKotlinAnalyzer._get_root_identifier", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_root_identifier" - ], - "source_code": " def _get_root_identifier(self, nav_node):\n \"\"\"Get the root identifier from a chain of navigation_expressions.\"\"\"\n first_child = nav_node.children[0] if nav_node.children else None\n if first_child:\n if first_child.type == \"identifier\":\n return first_child\n elif first_child.type == \"navigation_expression\":\n return self._get_root_identifier(first_child)\n return None", - "start_line": 341, - "end_line": 349, - "has_docstring": true, - "docstring": "Get the root identifier from a chain of navigation_expressions.", - "parameters": [ - "self", - "nav_node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterKotlinAnalyzer", - "display_name": "method TreeSitterKotlinAnalyzer._get_root_identifier", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_root_identifier", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._find_containing_class_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._find_containing_class_name", - "name": "TreeSitterKotlinAnalyzer._find_containing_class_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "depends_on": [], - "source_code": " def _find_containing_class_name(self, node):\n \"\"\"Walk up to find the containing class/object/interface name.\"\"\"\n current = node.parent\n while current:\n if current.type in (\"class_declaration\", \"object_declaration\"):\n name_node = next((c for c in current.children if c.type == \"identifier\"), None)\n if name_node:\n return name_node.text.decode()\n current = current.parent\n return None", - "start_line": 351, - "end_line": 360, - "has_docstring": true, - "docstring": "Walk up to find the containing class/object/interface name.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterKotlinAnalyzer", - "display_name": "method TreeSitterKotlinAnalyzer._find_containing_class_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._find_containing_class_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._find_containing_class": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._find_containing_class", - "name": "TreeSitterKotlinAnalyzer._find_containing_class", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._find_containing_class_name", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_component_id" - ], - "source_code": " def _find_containing_class(self, node, top_level_nodes):\n \"\"\"Find the component ID of the containing class.\"\"\"\n class_name = self._find_containing_class_name(node)\n if class_name and class_name in top_level_nodes:\n return self._get_component_id(class_name)\n return None", - "start_line": 362, - "end_line": 367, - "has_docstring": true, - "docstring": "Find the component ID of the containing class.", - "parameters": [ - "self", - "node", - "top_level_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterKotlinAnalyzer", - "display_name": "method TreeSitterKotlinAnalyzer._find_containing_class", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._find_containing_class", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._find_containing_method": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._find_containing_method", - "name": "TreeSitterKotlinAnalyzer._find_containing_method", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._find_containing_class_name", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_component_id", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_identifier_name" - ], - "source_code": " def _find_containing_method(self, node):\n \"\"\"Find the component ID of the containing function/method.\"\"\"\n current = node.parent\n while current:\n if current.type == \"function_declaration\":\n method_name = self._get_identifier_name(current)\n class_name = self._find_containing_class_name(current)\n if method_name:\n if class_name:\n return self._get_component_id(f\"{class_name}.{method_name}\")\n return self._get_component_id(method_name)\n current = current.parent\n return None", - "start_line": 369, - "end_line": 381, - "has_docstring": true, - "docstring": "Find the component ID of the containing function/method.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterKotlinAnalyzer", - "display_name": "method TreeSitterKotlinAnalyzer._find_containing_method", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._find_containing_method", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._find_variable_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._find_variable_type", - "name": "TreeSitterKotlinAnalyzer._find_variable_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._search_variable_declaration", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_type_name" - ], - "source_code": " def _find_variable_type(self, node, variable_name: str, top_level_nodes) -> Optional[str]:\n \"\"\"\n Try to resolve the type of a variable by searching local declarations,\n function parameters, constructor parameters, and class properties.\n \"\"\"\n func_node = node.parent\n while func_node and func_node.type != \"function_declaration\":\n func_node = func_node.parent\n \n if func_node:\n params_node = next(\n (c for c in func_node.children if c.type == \"function_value_parameters\"), None\n )\n if params_node:\n for param in params_node.children:\n if param.type == \"parameter\":\n param_name_node = next(\n (c for c in param.children if c.type == \"identifier\"), None\n )\n if param_name_node and param_name_node.text.decode() == variable_name:\n type_node = next(\n (c for c in param.children if c.type in (\"user_type\", \"nullable_type\")), None\n )\n if type_node:\n return self._get_type_name(type_node)\n \n body_node = next(\n (c for c in func_node.children if c.type == \"function_body\"), None\n )\n if body_node:\n block = next((c for c in body_node.children if c.type == \"block\"), None)\n if block:\n result = self._search_variable_declaration(block, variable_name)\n if result:\n return result\n \n class_node = node.parent\n while class_node and class_node.type not in (\"class_declaration\", \"object_declaration\"):\n class_node = class_node.parent\n \n if class_node:\n primary_ctor = next(\n (c for c in class_node.children if c.type == \"primary_constructor\"), None\n )\n if primary_ctor:\n class_params = next(\n (c for c in primary_ctor.children if c.type == \"class_parameters\"), None\n )\n if class_params:\n for param in class_params.children:\n if param.type == \"class_parameter\":\n param_name = next(\n (c for c in param.children if c.type == \"identifier\"), None\n )\n if param_name and param_name.text.decode() == variable_name:\n type_node = next(\n (c for c in param.children if c.type in (\"user_type\", \"nullable_type\")), None\n )\n if type_node:\n return self._get_type_name(type_node)\n \n class_body = next(\n (c for c in class_node.children if c.type in (\"class_body\", \"enum_class_body\")), None\n )\n if class_body:\n for body_child in class_body.children:\n if body_child.type == \"property_declaration\":\n var_decl = next(\n (c for c in body_child.children if c.type == \"variable_declaration\"), None\n )\n if var_decl:\n prop_name = next(\n (c for c in var_decl.children if c.type == \"identifier\"), None\n )\n if prop_name and prop_name.text.decode() == variable_name:\n type_node = next(\n (c for c in var_decl.children if c.type in (\"user_type\", \"nullable_type\")), None\n )\n if type_node:\n return self._get_type_name(type_node)\n \n return None", - "start_line": 383, - "end_line": 464, - "has_docstring": true, - "docstring": "Try to resolve the type of a variable by searching local declarations,\nfunction parameters, constructor parameters, and class properties.", - "parameters": [ - "self", - "node", - "variable_name", - "top_level_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterKotlinAnalyzer", - "display_name": "method TreeSitterKotlinAnalyzer._find_variable_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._find_variable_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._search_variable_declaration": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._search_variable_declaration", - "name": "TreeSitterKotlinAnalyzer._search_variable_declaration", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._search_variable_declaration", - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._get_type_name" - ], - "source_code": " def _search_variable_declaration(self, block_node, variable_name: str) -> Optional[str]:\n \"\"\"Search for a local variable declaration with explicit type annotation in a block.\"\"\"\n for child in block_node.children:\n if child.type == \"property_declaration\":\n var_decl = next(\n (c for c in child.children if c.type == \"variable_declaration\"), None\n )\n if var_decl:\n name_node = next(\n (c for c in var_decl.children if c.type == \"identifier\"), None\n )\n if name_node and name_node.text.decode() == variable_name:\n type_node = next(\n (c for c in var_decl.children if c.type in (\"user_type\", \"nullable_type\")), None\n )\n if type_node:\n return self._get_type_name(type_node)\n \n init_expr = next(\n (c for c in child.children if c.type == \"call_expression\"), None\n )\n if init_expr:\n call_id = next(\n (c for c in init_expr.children if c.type == \"identifier\"), None\n )\n if call_id:\n inferred = call_id.text.decode()\n if inferred and inferred[0].isupper():\n return inferred\n \n elif child.type == \"block\":\n result = self._search_variable_declaration(child, variable_name)\n if result:\n return result\n \n return None", - "start_line": 466, - "end_line": 501, - "has_docstring": true, - "docstring": "Search for a local variable declaration with explicit type annotation in a block.", - "parameters": [ - "self", - "block_node", - "variable_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterKotlinAnalyzer", - "display_name": "method TreeSitterKotlinAnalyzer._search_variable_declaration", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer._search_variable_declaration", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::analyze_kotlin_file": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::analyze_kotlin_file", - "name": "analyze_kotlin_file", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::TreeSitterKotlinAnalyzer" - ], - "source_code": "def analyze_kotlin_file(file_path: str, content: str, repo_path: Optional[str] = None) -> Tuple[List[Node], List[CallRelationship]]:\n analyzer = TreeSitterKotlinAnalyzer(file_path, content, repo_path)\n return analyzer.nodes, analyzer.call_relationships", - "start_line": 503, - "end_line": 505, - "has_docstring": false, - "docstring": "", - "parameters": [ - "file_path", - "content", - "repo_path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function analyze_kotlin_file", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/kotlin.py::analyze_kotlin_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver", - "name": "NamespaceResolver", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [], - "source_code": "class NamespaceResolver:\n \"\"\"Resolves PHP class names to fully qualified names using use statements.\"\"\"\n\n def __init__(self):\n self.current_namespace: str = \"\"\n self.use_map: Dict[str, str] = {} # alias -> fully_qualified_name\n\n def register_namespace(self, ns: str):\n \"\"\"Set the current namespace.\"\"\"\n self.current_namespace = ns.replace(\"\\\\\\\\\", \"\\\\\")\n\n def register_use(self, fqn: str, alias: str = None):\n \"\"\"Register a use statement with optional alias.\"\"\"\n fqn = fqn.replace(\"\\\\\\\\\", \"\\\\\").lstrip(\"\\\\\")\n alias = alias or fqn.split(\"\\\\\")[-1]\n self.use_map[alias] = fqn\n\n def resolve(self, name: str) -> str:\n \"\"\"Resolve a name to its fully qualified form.\"\"\"\n if not name:\n return name\n\n name = name.replace(\"\\\\\\\\\", \"\\\\\")\n\n # Already fully qualified\n if name.startswith(\"\\\\\"):\n return name[1:]\n\n # Check use map for alias\n if name in self.use_map:\n return self.use_map[name]\n\n # Check if first part is an alias (for partial qualified names)\n parts = name.split(\"\\\\\")\n if parts[0] in self.use_map:\n base = self.use_map[parts[0]]\n if len(parts) > 1:\n return f\"{base}\\\\{'\\\\'.join(parts[1:])}\"\n return base\n\n # Prepend current namespace\n if self.current_namespace:\n return f\"{self.current_namespace}\\\\{name}\"\n\n return name", - "start_line": 40, - "end_line": 84, - "has_docstring": true, - "docstring": "Resolves PHP class names to fully qualified names using use statements.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class NamespaceResolver", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.__init__": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.__init__", - "name": "NamespaceResolver.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [], - "source_code": " def __init__(self):\n self.current_namespace: str = \"\"\n self.use_map: Dict[str, str] = {} # alias -> fully_qualified_name", - "start_line": 43, - "end_line": 45, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "NamespaceResolver", - "display_name": "method NamespaceResolver.__init__", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.register_namespace": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.register_namespace", - "name": "NamespaceResolver.register_namespace", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [], - "source_code": " def register_namespace(self, ns: str):\n \"\"\"Set the current namespace.\"\"\"\n self.current_namespace = ns.replace(\"\\\\\\\\\", \"\\\\\")", - "start_line": 47, - "end_line": 49, - "has_docstring": true, - "docstring": "Set the current namespace.", - "parameters": [ - "self", - "ns" - ], - "node_type": "method", - "base_classes": null, - "class_name": "NamespaceResolver", - "display_name": "method NamespaceResolver.register_namespace", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.register_namespace", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.register_use": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.register_use", - "name": "NamespaceResolver.register_use", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [], - "source_code": " def register_use(self, fqn: str, alias: str = None):\n \"\"\"Register a use statement with optional alias.\"\"\"\n fqn = fqn.replace(\"\\\\\\\\\", \"\\\\\").lstrip(\"\\\\\")\n alias = alias or fqn.split(\"\\\\\")[-1]\n self.use_map[alias] = fqn", - "start_line": 51, - "end_line": 55, - "has_docstring": true, - "docstring": "Register a use statement with optional alias.", - "parameters": [ - "self", - "fqn", - "alias" - ], - "node_type": "method", - "base_classes": null, - "class_name": "NamespaceResolver", - "display_name": "method NamespaceResolver.register_use", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.register_use", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "name": "NamespaceResolver.resolve", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [], - "source_code": " def resolve(self, name: str) -> str:\n \"\"\"Resolve a name to its fully qualified form.\"\"\"\n if not name:\n return name\n\n name = name.replace(\"\\\\\\\\\", \"\\\\\")\n\n # Already fully qualified\n if name.startswith(\"\\\\\"):\n return name[1:]\n\n # Check use map for alias\n if name in self.use_map:\n return self.use_map[name]\n\n # Check if first part is an alias (for partial qualified names)\n parts = name.split(\"\\\\\")\n if parts[0] in self.use_map:\n base = self.use_map[parts[0]]\n if len(parts) > 1:\n return f\"{base}\\\\{'\\\\'.join(parts[1:])}\"\n return base\n\n # Prepend current namespace\n if self.current_namespace:\n return f\"{self.current_namespace}\\\\{name}\"\n\n return name", - "start_line": 57, - "end_line": 84, - "has_docstring": true, - "docstring": "Resolve a name to its fully qualified form.", - "parameters": [ - "self", - "name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "NamespaceResolver", - "display_name": "method NamespaceResolver.resolve", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer", - "name": "TreeSitterPHPAnalyzer", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [], - "source_code": "class TreeSitterPHPAnalyzer:\n \"\"\"Analyzes PHP files using tree-sitter to extract nodes and relationships.\"\"\"\n\n def __init__(self, file_path: str, content: str, repo_path: str = None):\n self.file_path = Path(file_path)\n self.content = content\n self.repo_path = repo_path or \"\"\n self.nodes: List[Node] = []\n self.call_relationships: List[CallRelationship] = []\n self.namespace_resolver = NamespaceResolver()\n self._top_level_nodes: Dict[str, Node] = {}\n\n # Check if this is a template file that should be skipped\n if self._is_template_file():\n logger.debug(f\"Skipping template file: {file_path}\")\n return\n\n self._analyze()\n\n def _is_template_file(self) -> bool:\n \"\"\"Check if file is a PHP template that should be skipped.\"\"\"\n file_str = str(self.file_path)\n\n # Check extension patterns\n for pattern in TEMPLATE_PATTERNS:\n if file_str.endswith(pattern):\n return True\n\n # Check directory patterns\n for dir_pattern in TEMPLATE_DIRECTORIES:\n if f\"/{dir_pattern}/\" in file_str or f\"\\\\{dir_pattern}\\\\\" in file_str:\n return True\n\n return False\n\n def _get_module_path(self) -> str:\n \"\"\"Get module path for the file.\"\"\"\n if self.repo_path:\n try:\n rel_path = os.path.relpath(str(self.file_path), self.repo_path)\n except ValueError:\n rel_path = str(self.file_path)\n else:\n rel_path = str(self.file_path)\n\n # Remove .php extension\n for ext in ['.php', '.phtml', '.inc']:\n if rel_path.endswith(ext):\n rel_path = rel_path[:-len(ext)]\n break\n\n return rel_path.replace('/', '.').replace('\\\\', '.')\n\n def _get_relative_path(self) -> str:\n \"\"\"Get relative path from repo root.\"\"\"\n if self.repo_path:\n try:\n return os.path.relpath(str(self.file_path), self.repo_path)\n except ValueError:\n return str(self.file_path)\n return str(self.file_path)\n\n def _get_component_id(self, name: str, parent_class: str = None) -> str:\n \"\"\"Generate component ID for a node.\"\"\"\n rel_path = self._get_relative_path()\n if parent_class:\n return f\"{rel_path}::{parent_class}.{name}\"\n return f\"{rel_path}::{name}\"\n\n def _analyze(self):\n \"\"\"Parse and analyze the PHP file.\"\"\"\n try:\n # Use language_php for mixed PHP/HTML files (most common)\n php_lang_capsule = tree_sitter_php.language_php()\n php_language = Language(php_lang_capsule)\n parser = Parser(php_language)\n\n tree = parser.parse(bytes(self.content, \"utf8\"))\n root = tree.root_node\n lines = self.content.splitlines()\n\n # First pass: extract namespace and use statements\n self._extract_namespace_info(root)\n\n # Second pass: extract nodes\n self._extract_nodes(root, lines, depth=0)\n\n # Third pass: extract relationships\n self._extract_relationships(root, depth=0)\n\n except RecursionError:\n logger.warning(f\"Max recursion depth exceeded in {self.file_path}\")\n except Exception as e:\n logger.error(f\"Error parsing PHP file {self.file_path}: {e}\")\n\n def _extract_namespace_info(self, node, depth: int = 0):\n \"\"\"Extract namespace and use statements from the AST.\"\"\"\n if depth > MAX_RECURSION_DEPTH:\n return\n\n if node.type == \"namespace_definition\":\n # Get namespace name\n name_node = self._find_child_by_type(node, \"namespace_name\")\n if name_node:\n self.namespace_resolver.register_namespace(name_node.text.decode())\n\n elif node.type == \"namespace_use_declaration\":\n self._extract_use_statement(node)\n\n for child in node.children:\n self._extract_namespace_info(child, depth + 1)\n\n def _extract_use_statement(self, node):\n \"\"\"Extract use statement(s) from a namespace_use_declaration node.\"\"\"\n # Handle group use: use App\\{User, Post};\n group_node = self._find_child_by_type(node, \"namespace_use_group\")\n if group_node:\n prefix_node = self._find_child_by_type(node, \"namespace_name\")\n prefix = prefix_node.text.decode() if prefix_node else \"\"\n\n for child in group_node.children:\n if child.type == \"namespace_use_group_clause\":\n name_node = self._find_child_by_type(child, \"namespace_name\")\n alias_node = self._find_child_by_type(child, \"namespace_aliasing_clause\")\n\n if name_node:\n fqn = f\"{prefix}\\\\{name_node.text.decode()}\" if prefix else name_node.text.decode()\n alias = None\n if alias_node:\n alias_name = self._find_child_by_type(alias_node, \"name\")\n if alias_name:\n alias = alias_name.text.decode()\n self.namespace_resolver.register_use(fqn, alias)\n else:\n # Handle simple use: use App\\User; or use App\\User as U;\n for child in node.children:\n if child.type == \"namespace_use_clause\":\n name_node = self._find_child_by_type(child, \"qualified_name\") or \\\n self._find_child_by_type(child, \"namespace_name\")\n alias_node = self._find_child_by_type(child, \"namespace_aliasing_clause\")\n\n if name_node:\n fqn = name_node.text.decode()\n alias = None\n if alias_node:\n alias_name = self._find_child_by_type(alias_node, \"name\")\n if alias_name:\n alias = alias_name.text.decode()\n self.namespace_resolver.register_use(fqn, alias)\n\n def _extract_nodes(self, node, lines: List[str], depth: int = 0, parent_class: str = None):\n \"\"\"Extract class, interface, trait, enum, function, and method nodes.\"\"\"\n if depth > MAX_RECURSION_DEPTH:\n logger.warning(f\"Max recursion depth reached in {self.file_path}\")\n return\n\n node_type = None\n node_name = None\n docstring = \"\"\n\n # Get preceding docstring (PHPDoc)\n docstring = self._get_preceding_docstring(node, lines)\n\n if node.type == \"class_declaration\":\n # Check for abstract class\n is_abstract = any(\n c.type == \"abstract_modifier\" or\n (c.type == \"modifier\" and c.text.decode() == \"abstract\")\n for c in node.children\n )\n node_type = \"abstract class\" if is_abstract else \"class\"\n name_node = self._find_child_by_type(node, \"name\")\n node_name = name_node.text.decode() if name_node else None\n\n elif node.type == \"interface_declaration\":\n node_type = \"interface\"\n name_node = self._find_child_by_type(node, \"name\")\n node_name = name_node.text.decode() if name_node else None\n\n elif node.type == \"trait_declaration\":\n node_type = \"trait\"\n name_node = self._find_child_by_type(node, \"name\")\n node_name = name_node.text.decode() if name_node else None\n\n elif node.type == \"enum_declaration\":\n node_type = \"enum\"\n name_node = self._find_child_by_type(node, \"name\")\n node_name = name_node.text.decode() if name_node else None\n\n elif node.type == \"function_definition\":\n node_type = \"function\"\n name_node = self._find_child_by_type(node, \"name\")\n node_name = name_node.text.decode() if name_node else None\n\n elif node.type == \"method_declaration\":\n node_type = \"method\"\n name_node = self._find_child_by_type(node, \"name\")\n if name_node:\n method_name = name_node.text.decode()\n containing_class = parent_class or self._find_containing_class_name(node)\n if containing_class:\n node_name = f\"{containing_class}.{method_name}\"\n else:\n node_name = method_name\n\n if node_type and node_name:\n component_id = self._get_component_id(node_name)\n relative_path = self._get_relative_path()\n\n # Extract parameters for functions/methods\n parameters = None\n if node_type in (\"function\", \"method\"):\n parameters = self._extract_parameters(node)\n\n # Extract base classes for classes\n base_classes = None\n if node_type in (\"class\", \"abstract class\"):\n base_classes = self._extract_base_classes(node)\n\n node_obj = Node(\n id=component_id,\n name=node_name,\n component_type=node_type,\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=\"\\n\".join(lines[node.start_point[0]:node.end_point[0]+1]),\n start_line=node.start_point[0] + 1,\n end_line=node.end_point[0] + 1,\n has_docstring=bool(docstring),\n docstring=docstring,\n parameters=parameters,\n node_type=node_type,\n base_classes=base_classes,\n class_name=parent_class,\n display_name=f\"{node_type} {node_name}\",\n component_id=component_id\n )\n self.nodes.append(node_obj)\n self._top_level_nodes[node_name] = node_obj\n\n # Track current class for method extraction\n if node_type in (\"class\", \"abstract class\", \"interface\", \"trait\", \"enum\"):\n parent_class = node_name\n\n # Recursively process children\n for child in node.children:\n self._extract_nodes(child, lines, depth + 1, parent_class)\n\n def _extract_relationships(self, node, depth: int = 0):\n \"\"\"Extract dependency relationships from the AST.\"\"\"\n if depth > MAX_RECURSION_DEPTH:\n return\n\n # 1. Use statements (already registered, now create relationships)\n if node.type == \"namespace_use_declaration\":\n self._add_use_relationships(node)\n\n # 2. Class inheritance (extends)\n if node.type == \"class_declaration\":\n class_name = self._get_name_from_node(node)\n base_clause = self._find_child_by_type(node, \"base_clause\")\n if base_clause and class_name:\n base_name = self._get_type_from_clause(base_clause)\n if base_name and not self._is_primitive(base_name):\n resolved_base = self.namespace_resolver.resolve(base_name)\n self.call_relationships.append(CallRelationship(\n caller=self._get_component_id(class_name),\n callee=resolved_base.replace(\"\\\\\", \".\"),\n call_line=node.start_point[0] + 1,\n is_resolved=False\n ))\n\n # 3. Interface implementation (implements)\n if node.type in (\"class_declaration\", \"enum_declaration\"):\n implementer_name = self._get_name_from_node(node)\n interface_clause = self._find_child_by_type(node, \"class_interface_clause\")\n if interface_clause and implementer_name:\n for child in interface_clause.children:\n if child.type in (\"name\", \"qualified_name\"):\n interface_name = child.text.decode()\n if not self._is_primitive(interface_name):\n resolved_interface = self.namespace_resolver.resolve(interface_name)\n self.call_relationships.append(CallRelationship(\n caller=self._get_component_id(implementer_name),\n callee=resolved_interface.replace(\"\\\\\", \".\"),\n call_line=node.start_point[0] + 1,\n is_resolved=False\n ))\n\n # 4. Object creation (new)\n if node.type == \"object_creation_expression\":\n containing_class = self._find_containing_class_name(node)\n type_node = self._find_child_by_type(node, \"name\") or \\\n self._find_child_by_type(node, \"qualified_name\")\n if type_node:\n created_type = type_node.text.decode()\n if not self._is_primitive(created_type) and containing_class:\n resolved_type = self.namespace_resolver.resolve(created_type)\n self.call_relationships.append(CallRelationship(\n caller=self._get_component_id(containing_class),\n callee=resolved_type.replace(\"\\\\\", \".\"),\n call_line=node.start_point[0] + 1,\n is_resolved=False\n ))\n\n # 5. Static method calls (::)\n if node.type == \"scoped_call_expression\":\n containing_class = self._find_containing_class_name(node)\n scope_node = self._find_child_by_type(node, \"name\") or \\\n self._find_child_by_type(node, \"qualified_name\")\n if scope_node and containing_class:\n target_class = scope_node.text.decode()\n if not self._is_primitive(target_class):\n resolved_target = self.namespace_resolver.resolve(target_class)\n self.call_relationships.append(CallRelationship(\n caller=self._get_component_id(containing_class),\n callee=resolved_target.replace(\"\\\\\", \".\"),\n call_line=node.start_point[0] + 1,\n is_resolved=False\n ))\n\n # 6. Property promotion in constructor (PHP 8+)\n if node.type == \"property_promotion_parameter\":\n containing_class = self._find_containing_class_name(node)\n type_node = self._find_child_by_type(node, \"type_list\") or \\\n self._find_child_by_type(node, \"named_type\")\n if type_node and containing_class:\n type_name = self._extract_type_name(type_node)\n if type_name and not self._is_primitive(type_name):\n resolved_type = self.namespace_resolver.resolve(type_name)\n self.call_relationships.append(CallRelationship(\n caller=self._get_component_id(containing_class),\n callee=resolved_type.replace(\"\\\\\", \".\"),\n call_line=node.start_point[0] + 1,\n is_resolved=False\n ))\n\n # Recursively process children\n for child in node.children:\n self._extract_relationships(child, depth + 1)\n\n def _add_use_relationships(self, node):\n \"\"\"Add relationships for use statements.\"\"\"\n # Get all use clauses from the declaration\n for child in node.children:\n if child.type == \"namespace_use_clause\":\n name_node = self._find_child_by_type(child, \"qualified_name\") or \\\n self._find_child_by_type(child, \"namespace_name\")\n if name_node:\n fqn = name_node.text.decode().replace(\"\\\\\", \".\")\n # Add relationship from file to imported class\n file_id = self._get_relative_path()\n self.call_relationships.append(CallRelationship(\n caller=file_id,\n callee=fqn,\n call_line=node.start_point[0] + 1,\n is_resolved=False\n ))\n elif child.type == \"namespace_use_group\":\n prefix_node = self._find_child_by_type(node, \"namespace_name\")\n prefix = prefix_node.text.decode() if prefix_node else \"\"\n\n for group_child in child.children:\n if group_child.type == \"namespace_use_group_clause\":\n name_node = self._find_child_by_type(group_child, \"namespace_name\")\n if name_node:\n fqn = f\"{prefix}\\\\{name_node.text.decode()}\" if prefix else name_node.text.decode()\n file_id = self._get_relative_path()\n self.call_relationships.append(CallRelationship(\n caller=file_id,\n callee=fqn.replace(\"\\\\\", \".\"),\n call_line=node.start_point[0] + 1,\n is_resolved=False\n ))\n\n def _find_child_by_type(self, node, child_type: str):\n \"\"\"Find first child of a specific type.\"\"\"\n for child in node.children:\n if child.type == child_type:\n return child\n return None\n\n def _get_name_from_node(self, node) -> Optional[str]:\n \"\"\"Get name from a declaration node.\"\"\"\n name_node = self._find_child_by_type(node, \"name\")\n return name_node.text.decode() if name_node else None\n\n def _get_type_from_clause(self, clause_node) -> Optional[str]:\n \"\"\"Extract type name from a base_clause or interface_clause.\"\"\"\n for child in clause_node.children:\n if child.type in (\"name\", \"qualified_name\"):\n return child.text.decode()\n return None\n\n def _extract_type_name(self, type_node) -> Optional[str]:\n \"\"\"Extract type name from a type node.\"\"\"\n if type_node.type == \"named_type\":\n name_node = self._find_child_by_type(type_node, \"name\") or \\\n self._find_child_by_type(type_node, \"qualified_name\")\n if name_node:\n return name_node.text.decode()\n elif type_node.type in (\"name\", \"qualified_name\"):\n return type_node.text.decode()\n elif type_node.type == \"type_list\":\n # Get first type from union/intersection\n for child in type_node.children:\n if child.type == \"named_type\":\n return self._extract_type_name(child)\n return type_node.text.decode() if hasattr(type_node, 'text') else None\n\n def _find_containing_class_name(self, node) -> Optional[str]:\n \"\"\"Find the name of the containing class/interface/trait/enum.\"\"\"\n current = node.parent\n while current:\n if current.type in (\"class_declaration\", \"interface_declaration\",\n \"trait_declaration\", \"enum_declaration\"):\n name_node = self._find_child_by_type(current, \"name\")\n if name_node:\n return name_node.text.decode()\n current = current.parent\n return None\n\n def _get_preceding_docstring(self, node, lines: List[str]) -> str:\n \"\"\"Extract PHPDoc comment preceding a node.\"\"\"\n if node.start_point[0] == 0:\n return \"\"\n\n # Look at previous sibling or check lines before\n prev_sibling = node.prev_named_sibling\n if prev_sibling and prev_sibling.type == \"comment\":\n comment_text = prev_sibling.text.decode()\n if comment_text.startswith(\"/**\"):\n return comment_text\n\n # Check lines directly before the node\n start_line = node.start_point[0]\n if start_line > 0:\n for i in range(start_line - 1, max(0, start_line - 10), -1):\n line = lines[i].strip() if i < len(lines) else \"\"\n if line.endswith(\"*/\"):\n # Found end of docblock, now find start\n docblock_lines = []\n for j in range(i, max(0, i - 50), -1):\n docblock_lines.insert(0, lines[j] if j < len(lines) else \"\")\n if \"/**\" in (lines[j] if j < len(lines) else \"\"):\n return \"\\n\".join(docblock_lines)\n elif line and not line.startswith(\"*\") and not line.startswith(\"/**\"):\n break\n\n return \"\"\n\n def _extract_parameters(self, node) -> Optional[List[str]]:\n \"\"\"Extract function/method parameters as list of strings.\"\"\"\n params_node = self._find_child_by_type(node, \"formal_parameters\")\n if params_node:\n params = []\n for child in params_node.children:\n if child.type in (\"simple_parameter\", \"property_promotion_parameter\", \"variadic_parameter\"):\n # Get the variable name\n var_node = self._find_child_by_type(child, \"variable_name\")\n if var_node:\n param_text = var_node.text.decode()\n # Get type if present\n type_node = self._find_child_by_type(child, \"named_type\") or \\\n self._find_child_by_type(child, \"primitive_type\")\n if type_node:\n param_text = f\"{type_node.text.decode()} {param_text}\"\n params.append(param_text)\n return params if params else None\n return None\n\n def _extract_base_classes(self, node) -> Optional[List[str]]:\n \"\"\"Extract base class names from a class declaration.\"\"\"\n base_classes = []\n\n base_clause = self._find_child_by_type(node, \"base_clause\")\n if base_clause:\n for child in base_clause.children:\n if child.type in (\"name\", \"qualified_name\"):\n base_classes.append(child.text.decode())\n\n interface_clause = self._find_child_by_type(node, \"class_interface_clause\")\n if interface_clause:\n for child in interface_clause.children:\n if child.type in (\"name\", \"qualified_name\"):\n base_classes.append(child.text.decode())\n\n return base_classes if base_classes else None\n\n def _is_primitive(self, type_name: str) -> bool:\n \"\"\"Check if type is a PHP primitive or built-in type.\"\"\"\n if not type_name:\n return True\n # Remove leading backslash and check\n clean_name = type_name.lstrip(\"\\\\\").split(\"\\\\\")[-1]\n return clean_name.lower() in {p.lower() for p in PHP_PRIMITIVES}", - "start_line": 87, - "end_line": 582, - "has_docstring": true, - "docstring": "Analyzes PHP files using tree-sitter to extract nodes and relationships.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class TreeSitterPHPAnalyzer", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer.__init__": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer.__init__", - "name": "TreeSitterPHPAnalyzer.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._analyze", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._is_template_file", - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": " def __init__(self, file_path: str, content: str, repo_path: str = None):\n self.file_path = Path(file_path)\n self.content = content\n self.repo_path = repo_path or \"\"\n self.nodes: List[Node] = []\n self.call_relationships: List[CallRelationship] = []\n self.namespace_resolver = NamespaceResolver()\n self._top_level_nodes: Dict[str, Node] = {}\n\n # Check if this is a template file that should be skipped\n if self._is_template_file():\n logger.debug(f\"Skipping template file: {file_path}\")\n return\n\n self._analyze()", - "start_line": 90, - "end_line": 104, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "file_path", - "content", - "repo_path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer.__init__", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._is_template_file": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._is_template_file", - "name": "TreeSitterPHPAnalyzer._is_template_file", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [], - "source_code": " def _is_template_file(self) -> bool:\n \"\"\"Check if file is a PHP template that should be skipped.\"\"\"\n file_str = str(self.file_path)\n\n # Check extension patterns\n for pattern in TEMPLATE_PATTERNS:\n if file_str.endswith(pattern):\n return True\n\n # Check directory patterns\n for dir_pattern in TEMPLATE_DIRECTORIES:\n if f\"/{dir_pattern}/\" in file_str or f\"\\\\{dir_pattern}\\\\\" in file_str:\n return True\n\n return False", - "start_line": 106, - "end_line": 120, - "has_docstring": true, - "docstring": "Check if file is a PHP template that should be skipped.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer._is_template_file", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._is_template_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_module_path": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_module_path", - "name": "TreeSitterPHPAnalyzer._get_module_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [], - "source_code": " def _get_module_path(self) -> str:\n \"\"\"Get module path for the file.\"\"\"\n if self.repo_path:\n try:\n rel_path = os.path.relpath(str(self.file_path), self.repo_path)\n except ValueError:\n rel_path = str(self.file_path)\n else:\n rel_path = str(self.file_path)\n\n # Remove .php extension\n for ext in ['.php', '.phtml', '.inc']:\n if rel_path.endswith(ext):\n rel_path = rel_path[:-len(ext)]\n break\n\n return rel_path.replace('/', '.').replace('\\\\', '.')", - "start_line": 122, - "end_line": 138, - "has_docstring": true, - "docstring": "Get module path for the file.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer._get_module_path", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_module_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_relative_path": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_relative_path", - "name": "TreeSitterPHPAnalyzer._get_relative_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [], - "source_code": " def _get_relative_path(self) -> str:\n \"\"\"Get relative path from repo root.\"\"\"\n if self.repo_path:\n try:\n return os.path.relpath(str(self.file_path), self.repo_path)\n except ValueError:\n return str(self.file_path)\n return str(self.file_path)", - "start_line": 140, - "end_line": 147, - "has_docstring": true, - "docstring": "Get relative path from repo root.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer._get_relative_path", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_relative_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_component_id": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_component_id", - "name": "TreeSitterPHPAnalyzer._get_component_id", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_relative_path" - ], - "source_code": " def _get_component_id(self, name: str, parent_class: str = None) -> str:\n \"\"\"Generate component ID for a node.\"\"\"\n rel_path = self._get_relative_path()\n if parent_class:\n return f\"{rel_path}::{parent_class}.{name}\"\n return f\"{rel_path}::{name}\"", - "start_line": 149, - "end_line": 154, - "has_docstring": true, - "docstring": "Generate component ID for a node.", - "parameters": [ - "self", - "name", - "parent_class" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer._get_component_id", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_component_id", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._analyze": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._analyze", - "name": "TreeSitterPHPAnalyzer._analyze", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_relationships", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_nodes", - "codewiki/cli/utils/logging.py::CLILogger.error", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_namespace_info" - ], - "source_code": " def _analyze(self):\n \"\"\"Parse and analyze the PHP file.\"\"\"\n try:\n # Use language_php for mixed PHP/HTML files (most common)\n php_lang_capsule = tree_sitter_php.language_php()\n php_language = Language(php_lang_capsule)\n parser = Parser(php_language)\n\n tree = parser.parse(bytes(self.content, \"utf8\"))\n root = tree.root_node\n lines = self.content.splitlines()\n\n # First pass: extract namespace and use statements\n self._extract_namespace_info(root)\n\n # Second pass: extract nodes\n self._extract_nodes(root, lines, depth=0)\n\n # Third pass: extract relationships\n self._extract_relationships(root, depth=0)\n\n except RecursionError:\n logger.warning(f\"Max recursion depth exceeded in {self.file_path}\")\n except Exception as e:\n logger.error(f\"Error parsing PHP file {self.file_path}: {e}\")", - "start_line": 156, - "end_line": 180, - "has_docstring": true, - "docstring": "Parse and analyze the PHP file.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer._analyze", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._analyze", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_namespace_info": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_namespace_info", - "name": "TreeSitterPHPAnalyzer._extract_namespace_info", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_namespace_info", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_use_statement", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.register_namespace", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._find_child_by_type" - ], - "source_code": " def _extract_namespace_info(self, node, depth: int = 0):\n \"\"\"Extract namespace and use statements from the AST.\"\"\"\n if depth > MAX_RECURSION_DEPTH:\n return\n\n if node.type == \"namespace_definition\":\n # Get namespace name\n name_node = self._find_child_by_type(node, \"namespace_name\")\n if name_node:\n self.namespace_resolver.register_namespace(name_node.text.decode())\n\n elif node.type == \"namespace_use_declaration\":\n self._extract_use_statement(node)\n\n for child in node.children:\n self._extract_namespace_info(child, depth + 1)", - "start_line": 182, - "end_line": 197, - "has_docstring": true, - "docstring": "Extract namespace and use statements from the AST.", - "parameters": [ - "self", - "node", - "depth" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer._extract_namespace_info", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_namespace_info", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_use_statement": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_use_statement", - "name": "TreeSitterPHPAnalyzer._extract_use_statement", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.register_use", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._find_child_by_type" - ], - "source_code": " def _extract_use_statement(self, node):\n \"\"\"Extract use statement(s) from a namespace_use_declaration node.\"\"\"\n # Handle group use: use App\\{User, Post};\n group_node = self._find_child_by_type(node, \"namespace_use_group\")\n if group_node:\n prefix_node = self._find_child_by_type(node, \"namespace_name\")\n prefix = prefix_node.text.decode() if prefix_node else \"\"\n\n for child in group_node.children:\n if child.type == \"namespace_use_group_clause\":\n name_node = self._find_child_by_type(child, \"namespace_name\")\n alias_node = self._find_child_by_type(child, \"namespace_aliasing_clause\")\n\n if name_node:\n fqn = f\"{prefix}\\\\{name_node.text.decode()}\" if prefix else name_node.text.decode()\n alias = None\n if alias_node:\n alias_name = self._find_child_by_type(alias_node, \"name\")\n if alias_name:\n alias = alias_name.text.decode()\n self.namespace_resolver.register_use(fqn, alias)\n else:\n # Handle simple use: use App\\User; or use App\\User as U;\n for child in node.children:\n if child.type == \"namespace_use_clause\":\n name_node = self._find_child_by_type(child, \"qualified_name\") or \\\n self._find_child_by_type(child, \"namespace_name\")\n alias_node = self._find_child_by_type(child, \"namespace_aliasing_clause\")\n\n if name_node:\n fqn = name_node.text.decode()\n alias = None\n if alias_node:\n alias_name = self._find_child_by_type(alias_node, \"name\")\n if alias_name:\n alias = alias_name.text.decode()\n self.namespace_resolver.register_use(fqn, alias)", - "start_line": 199, - "end_line": 235, - "has_docstring": true, - "docstring": "Extract use statement(s) from a namespace_use_declaration node.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer._extract_use_statement", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_use_statement", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_nodes": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_nodes", - "name": "TreeSitterPHPAnalyzer._extract_nodes", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_base_classes", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_parameters", - "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_preceding_docstring", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._find_containing_class_name", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_component_id", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_relative_path", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_nodes" - ], - "source_code": " def _extract_nodes(self, node, lines: List[str], depth: int = 0, parent_class: str = None):\n \"\"\"Extract class, interface, trait, enum, function, and method nodes.\"\"\"\n if depth > MAX_RECURSION_DEPTH:\n logger.warning(f\"Max recursion depth reached in {self.file_path}\")\n return\n\n node_type = None\n node_name = None\n docstring = \"\"\n\n # Get preceding docstring (PHPDoc)\n docstring = self._get_preceding_docstring(node, lines)\n\n if node.type == \"class_declaration\":\n # Check for abstract class\n is_abstract = any(\n c.type == \"abstract_modifier\" or\n (c.type == \"modifier\" and c.text.decode() == \"abstract\")\n for c in node.children\n )\n node_type = \"abstract class\" if is_abstract else \"class\"\n name_node = self._find_child_by_type(node, \"name\")\n node_name = name_node.text.decode() if name_node else None\n\n elif node.type == \"interface_declaration\":\n node_type = \"interface\"\n name_node = self._find_child_by_type(node, \"name\")\n node_name = name_node.text.decode() if name_node else None\n\n elif node.type == \"trait_declaration\":\n node_type = \"trait\"\n name_node = self._find_child_by_type(node, \"name\")\n node_name = name_node.text.decode() if name_node else None\n\n elif node.type == \"enum_declaration\":\n node_type = \"enum\"\n name_node = self._find_child_by_type(node, \"name\")\n node_name = name_node.text.decode() if name_node else None\n\n elif node.type == \"function_definition\":\n node_type = \"function\"\n name_node = self._find_child_by_type(node, \"name\")\n node_name = name_node.text.decode() if name_node else None\n\n elif node.type == \"method_declaration\":\n node_type = \"method\"\n name_node = self._find_child_by_type(node, \"name\")\n if name_node:\n method_name = name_node.text.decode()\n containing_class = parent_class or self._find_containing_class_name(node)\n if containing_class:\n node_name = f\"{containing_class}.{method_name}\"\n else:\n node_name = method_name\n\n if node_type and node_name:\n component_id = self._get_component_id(node_name)\n relative_path = self._get_relative_path()\n\n # Extract parameters for functions/methods\n parameters = None\n if node_type in (\"function\", \"method\"):\n parameters = self._extract_parameters(node)\n\n # Extract base classes for classes\n base_classes = None\n if node_type in (\"class\", \"abstract class\"):\n base_classes = self._extract_base_classes(node)\n\n node_obj = Node(\n id=component_id,\n name=node_name,\n component_type=node_type,\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=\"\\n\".join(lines[node.start_point[0]:node.end_point[0]+1]),\n start_line=node.start_point[0] + 1,\n end_line=node.end_point[0] + 1,\n has_docstring=bool(docstring),\n docstring=docstring,\n parameters=parameters,\n node_type=node_type,\n base_classes=base_classes,\n class_name=parent_class,\n display_name=f\"{node_type} {node_name}\",\n component_id=component_id\n )\n self.nodes.append(node_obj)\n self._top_level_nodes[node_name] = node_obj\n\n # Track current class for method extraction\n if node_type in (\"class\", \"abstract class\", \"interface\", \"trait\", \"enum\"):\n parent_class = node_name\n\n # Recursively process children\n for child in node.children:\n self._extract_nodes(child, lines, depth + 1, parent_class)", - "start_line": 237, - "end_line": 333, - "has_docstring": true, - "docstring": "Extract class, interface, trait, enum, function, and method nodes.", - "parameters": [ - "self", - "node", - "lines", - "depth", - "parent_class" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer._extract_nodes", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_nodes", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_relationships": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_relationships", - "name": "TreeSitterPHPAnalyzer._extract_relationships", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_type_name", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_name_from_node", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._is_primitive", - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_component_id", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._find_containing_class_name", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._add_use_relationships", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_relationships", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_type_from_clause" - ], - "source_code": " def _extract_relationships(self, node, depth: int = 0):\n \"\"\"Extract dependency relationships from the AST.\"\"\"\n if depth > MAX_RECURSION_DEPTH:\n return\n\n # 1. Use statements (already registered, now create relationships)\n if node.type == \"namespace_use_declaration\":\n self._add_use_relationships(node)\n\n # 2. Class inheritance (extends)\n if node.type == \"class_declaration\":\n class_name = self._get_name_from_node(node)\n base_clause = self._find_child_by_type(node, \"base_clause\")\n if base_clause and class_name:\n base_name = self._get_type_from_clause(base_clause)\n if base_name and not self._is_primitive(base_name):\n resolved_base = self.namespace_resolver.resolve(base_name)\n self.call_relationships.append(CallRelationship(\n caller=self._get_component_id(class_name),\n callee=resolved_base.replace(\"\\\\\", \".\"),\n call_line=node.start_point[0] + 1,\n is_resolved=False\n ))\n\n # 3. Interface implementation (implements)\n if node.type in (\"class_declaration\", \"enum_declaration\"):\n implementer_name = self._get_name_from_node(node)\n interface_clause = self._find_child_by_type(node, \"class_interface_clause\")\n if interface_clause and implementer_name:\n for child in interface_clause.children:\n if child.type in (\"name\", \"qualified_name\"):\n interface_name = child.text.decode()\n if not self._is_primitive(interface_name):\n resolved_interface = self.namespace_resolver.resolve(interface_name)\n self.call_relationships.append(CallRelationship(\n caller=self._get_component_id(implementer_name),\n callee=resolved_interface.replace(\"\\\\\", \".\"),\n call_line=node.start_point[0] + 1,\n is_resolved=False\n ))\n\n # 4. Object creation (new)\n if node.type == \"object_creation_expression\":\n containing_class = self._find_containing_class_name(node)\n type_node = self._find_child_by_type(node, \"name\") or \\\n self._find_child_by_type(node, \"qualified_name\")\n if type_node:\n created_type = type_node.text.decode()\n if not self._is_primitive(created_type) and containing_class:\n resolved_type = self.namespace_resolver.resolve(created_type)\n self.call_relationships.append(CallRelationship(\n caller=self._get_component_id(containing_class),\n callee=resolved_type.replace(\"\\\\\", \".\"),\n call_line=node.start_point[0] + 1,\n is_resolved=False\n ))\n\n # 5. Static method calls (::)\n if node.type == \"scoped_call_expression\":\n containing_class = self._find_containing_class_name(node)\n scope_node = self._find_child_by_type(node, \"name\") or \\\n self._find_child_by_type(node, \"qualified_name\")\n if scope_node and containing_class:\n target_class = scope_node.text.decode()\n if not self._is_primitive(target_class):\n resolved_target = self.namespace_resolver.resolve(target_class)\n self.call_relationships.append(CallRelationship(\n caller=self._get_component_id(containing_class),\n callee=resolved_target.replace(\"\\\\\", \".\"),\n call_line=node.start_point[0] + 1,\n is_resolved=False\n ))\n\n # 6. Property promotion in constructor (PHP 8+)\n if node.type == \"property_promotion_parameter\":\n containing_class = self._find_containing_class_name(node)\n type_node = self._find_child_by_type(node, \"type_list\") or \\\n self._find_child_by_type(node, \"named_type\")\n if type_node and containing_class:\n type_name = self._extract_type_name(type_node)\n if type_name and not self._is_primitive(type_name):\n resolved_type = self.namespace_resolver.resolve(type_name)\n self.call_relationships.append(CallRelationship(\n caller=self._get_component_id(containing_class),\n callee=resolved_type.replace(\"\\\\\", \".\"),\n call_line=node.start_point[0] + 1,\n is_resolved=False\n ))\n\n # Recursively process children\n for child in node.children:\n self._extract_relationships(child, depth + 1)", - "start_line": 335, - "end_line": 426, - "has_docstring": true, - "docstring": "Extract dependency relationships from the AST.", - "parameters": [ - "self", - "node", - "depth" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer._extract_relationships", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_relationships", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._add_use_relationships": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._add_use_relationships", - "name": "TreeSitterPHPAnalyzer._add_use_relationships", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_relative_path", - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._find_child_by_type" - ], - "source_code": " def _add_use_relationships(self, node):\n \"\"\"Add relationships for use statements.\"\"\"\n # Get all use clauses from the declaration\n for child in node.children:\n if child.type == \"namespace_use_clause\":\n name_node = self._find_child_by_type(child, \"qualified_name\") or \\\n self._find_child_by_type(child, \"namespace_name\")\n if name_node:\n fqn = name_node.text.decode().replace(\"\\\\\", \".\")\n # Add relationship from file to imported class\n file_id = self._get_relative_path()\n self.call_relationships.append(CallRelationship(\n caller=file_id,\n callee=fqn,\n call_line=node.start_point[0] + 1,\n is_resolved=False\n ))\n elif child.type == \"namespace_use_group\":\n prefix_node = self._find_child_by_type(node, \"namespace_name\")\n prefix = prefix_node.text.decode() if prefix_node else \"\"\n\n for group_child in child.children:\n if group_child.type == \"namespace_use_group_clause\":\n name_node = self._find_child_by_type(group_child, \"namespace_name\")\n if name_node:\n fqn = f\"{prefix}\\\\{name_node.text.decode()}\" if prefix else name_node.text.decode()\n file_id = self._get_relative_path()\n self.call_relationships.append(CallRelationship(\n caller=file_id,\n callee=fqn.replace(\"\\\\\", \".\"),\n call_line=node.start_point[0] + 1,\n is_resolved=False\n ))", - "start_line": 428, - "end_line": 460, - "has_docstring": true, - "docstring": "Add relationships for use statements.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer._add_use_relationships", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._add_use_relationships", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._find_child_by_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._find_child_by_type", - "name": "TreeSitterPHPAnalyzer._find_child_by_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [], - "source_code": " def _find_child_by_type(self, node, child_type: str):\n \"\"\"Find first child of a specific type.\"\"\"\n for child in node.children:\n if child.type == child_type:\n return child\n return None", - "start_line": 462, - "end_line": 467, - "has_docstring": true, - "docstring": "Find first child of a specific type.", - "parameters": [ - "self", - "node", - "child_type" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer._find_child_by_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._find_child_by_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_name_from_node": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_name_from_node", - "name": "TreeSitterPHPAnalyzer._get_name_from_node", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._find_child_by_type" - ], - "source_code": " def _get_name_from_node(self, node) -> Optional[str]:\n \"\"\"Get name from a declaration node.\"\"\"\n name_node = self._find_child_by_type(node, \"name\")\n return name_node.text.decode() if name_node else None", - "start_line": 469, - "end_line": 472, - "has_docstring": true, - "docstring": "Get name from a declaration node.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer._get_name_from_node", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_name_from_node", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_type_from_clause": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_type_from_clause", - "name": "TreeSitterPHPAnalyzer._get_type_from_clause", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [], - "source_code": " def _get_type_from_clause(self, clause_node) -> Optional[str]:\n \"\"\"Extract type name from a base_clause or interface_clause.\"\"\"\n for child in clause_node.children:\n if child.type in (\"name\", \"qualified_name\"):\n return child.text.decode()\n return None", - "start_line": 474, - "end_line": 479, - "has_docstring": true, - "docstring": "Extract type name from a base_clause or interface_clause.", - "parameters": [ - "self", - "clause_node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer._get_type_from_clause", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_type_from_clause", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_type_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_type_name", - "name": "TreeSitterPHPAnalyzer._extract_type_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_type_name", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._find_child_by_type" - ], - "source_code": " def _extract_type_name(self, type_node) -> Optional[str]:\n \"\"\"Extract type name from a type node.\"\"\"\n if type_node.type == \"named_type\":\n name_node = self._find_child_by_type(type_node, \"name\") or \\\n self._find_child_by_type(type_node, \"qualified_name\")\n if name_node:\n return name_node.text.decode()\n elif type_node.type in (\"name\", \"qualified_name\"):\n return type_node.text.decode()\n elif type_node.type == \"type_list\":\n # Get first type from union/intersection\n for child in type_node.children:\n if child.type == \"named_type\":\n return self._extract_type_name(child)\n return type_node.text.decode() if hasattr(type_node, 'text') else None", - "start_line": 481, - "end_line": 495, - "has_docstring": true, - "docstring": "Extract type name from a type node.", - "parameters": [ - "self", - "type_node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer._extract_type_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_type_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._find_containing_class_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._find_containing_class_name", - "name": "TreeSitterPHPAnalyzer._find_containing_class_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._find_child_by_type" - ], - "source_code": " def _find_containing_class_name(self, node) -> Optional[str]:\n \"\"\"Find the name of the containing class/interface/trait/enum.\"\"\"\n current = node.parent\n while current:\n if current.type in (\"class_declaration\", \"interface_declaration\",\n \"trait_declaration\", \"enum_declaration\"):\n name_node = self._find_child_by_type(current, \"name\")\n if name_node:\n return name_node.text.decode()\n current = current.parent\n return None", - "start_line": 497, - "end_line": 507, - "has_docstring": true, - "docstring": "Find the name of the containing class/interface/trait/enum.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer._find_containing_class_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._find_containing_class_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_preceding_docstring": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_preceding_docstring", - "name": "TreeSitterPHPAnalyzer._get_preceding_docstring", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [ - "codewiki/src/be/agent_tools/str_replace_editor.py::EditTool.insert" - ], - "source_code": " def _get_preceding_docstring(self, node, lines: List[str]) -> str:\n \"\"\"Extract PHPDoc comment preceding a node.\"\"\"\n if node.start_point[0] == 0:\n return \"\"\n\n # Look at previous sibling or check lines before\n prev_sibling = node.prev_named_sibling\n if prev_sibling and prev_sibling.type == \"comment\":\n comment_text = prev_sibling.text.decode()\n if comment_text.startswith(\"/**\"):\n return comment_text\n\n # Check lines directly before the node\n start_line = node.start_point[0]\n if start_line > 0:\n for i in range(start_line - 1, max(0, start_line - 10), -1):\n line = lines[i].strip() if i < len(lines) else \"\"\n if line.endswith(\"*/\"):\n # Found end of docblock, now find start\n docblock_lines = []\n for j in range(i, max(0, i - 50), -1):\n docblock_lines.insert(0, lines[j] if j < len(lines) else \"\")\n if \"/**\" in (lines[j] if j < len(lines) else \"\"):\n return \"\\n\".join(docblock_lines)\n elif line and not line.startswith(\"*\") and not line.startswith(\"/**\"):\n break\n\n return \"\"", - "start_line": 509, - "end_line": 536, - "has_docstring": true, - "docstring": "Extract PHPDoc comment preceding a node.", - "parameters": [ - "self", - "node", - "lines" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer._get_preceding_docstring", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._get_preceding_docstring", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_parameters": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_parameters", - "name": "TreeSitterPHPAnalyzer._extract_parameters", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._find_child_by_type" - ], - "source_code": " def _extract_parameters(self, node) -> Optional[List[str]]:\n \"\"\"Extract function/method parameters as list of strings.\"\"\"\n params_node = self._find_child_by_type(node, \"formal_parameters\")\n if params_node:\n params = []\n for child in params_node.children:\n if child.type in (\"simple_parameter\", \"property_promotion_parameter\", \"variadic_parameter\"):\n # Get the variable name\n var_node = self._find_child_by_type(child, \"variable_name\")\n if var_node:\n param_text = var_node.text.decode()\n # Get type if present\n type_node = self._find_child_by_type(child, \"named_type\") or \\\n self._find_child_by_type(child, \"primitive_type\")\n if type_node:\n param_text = f\"{type_node.text.decode()} {param_text}\"\n params.append(param_text)\n return params if params else None\n return None", - "start_line": 538, - "end_line": 556, - "has_docstring": true, - "docstring": "Extract function/method parameters as list of strings.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer._extract_parameters", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_parameters", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_base_classes": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_base_classes", - "name": "TreeSitterPHPAnalyzer._extract_base_classes", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._find_child_by_type" - ], - "source_code": " def _extract_base_classes(self, node) -> Optional[List[str]]:\n \"\"\"Extract base class names from a class declaration.\"\"\"\n base_classes = []\n\n base_clause = self._find_child_by_type(node, \"base_clause\")\n if base_clause:\n for child in base_clause.children:\n if child.type in (\"name\", \"qualified_name\"):\n base_classes.append(child.text.decode())\n\n interface_clause = self._find_child_by_type(node, \"class_interface_clause\")\n if interface_clause:\n for child in interface_clause.children:\n if child.type in (\"name\", \"qualified_name\"):\n base_classes.append(child.text.decode())\n\n return base_classes if base_classes else None", - "start_line": 558, - "end_line": 574, - "has_docstring": true, - "docstring": "Extract base class names from a class declaration.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer._extract_base_classes", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._extract_base_classes", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._is_primitive": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._is_primitive", - "name": "TreeSitterPHPAnalyzer._is_primitive", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [], - "source_code": " def _is_primitive(self, type_name: str) -> bool:\n \"\"\"Check if type is a PHP primitive or built-in type.\"\"\"\n if not type_name:\n return True\n # Remove leading backslash and check\n clean_name = type_name.lstrip(\"\\\\\").split(\"\\\\\")[-1]\n return clean_name.lower() in {p.lower() for p in PHP_PRIMITIVES}", - "start_line": 576, - "end_line": 582, - "has_docstring": true, - "docstring": "Check if type is a PHP primitive or built-in type.", - "parameters": [ - "self", - "type_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterPHPAnalyzer", - "display_name": "method TreeSitterPHPAnalyzer._is_primitive", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer._is_primitive", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/php.py::analyze_php_file": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::analyze_php_file", - "name": "analyze_php_file", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/php.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/php.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::TreeSitterPHPAnalyzer" - ], - "source_code": "def analyze_php_file(file_path: str, content: str, repo_path: str = None) -> Tuple[List[Node], List[CallRelationship]]:\n \"\"\"\n Analyze a PHP file and extract nodes and call relationships.\n\n Args:\n file_path: Path to the PHP file\n content: Content of the PHP file\n repo_path: Optional path to the repository root\n\n Returns:\n Tuple of (nodes, call_relationships)\n \"\"\"\n analyzer = TreeSitterPHPAnalyzer(file_path, content, repo_path)\n return analyzer.nodes, analyzer.call_relationships", - "start_line": 585, - "end_line": 598, - "has_docstring": true, - "docstring": "Analyze a PHP file and extract nodes and call relationships.\n\nArgs:\n file_path: Path to the PHP file\n content: Content of the PHP file\n repo_path: Optional path to the repository root\n\nReturns:\n Tuple of (nodes, call_relationships)", - "parameters": [ - "file_path", - "content", - "repo_path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function analyze_php_file", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/php.py::analyze_php_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::_dotted_contains": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::_dotted_contains", - "name": "_dotted_contains", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [], - "source_code": "def _dotted_contains(project_module: str, target: str) -> bool:\n \"\"\"Dotted-boundary containment: does `target` align with some segment run\n of `project_module`? Tolerates src-layouts where the import root differs\n from the repo root (import `pkg.util` vs project module `src.pkg.util`).\"\"\"\n return f\".{target}.\" in f\".{project_module}.\"", - "start_line": 16, - "end_line": 20, - "has_docstring": true, - "docstring": "Dotted-boundary containment: does `target` align with some segment run\nof `project_module`? Tolerates src-layouts where the import root differs\nfrom the repo root (import `pkg.util` vs project module `src.pkg.util`).", - "parameters": [ - "project_module", - "target" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _dotted_contains", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::_dotted_contains", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::is_project_import": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::is_project_import", - "name": "is_project_import", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/python.py::_dotted_contains" - ], - "source_code": "def is_project_import(target: str, project_modules: Set[str]) -> bool:\n return any(_dotted_contains(module, target) for module in project_modules)", - "start_line": 23, - "end_line": 24, - "has_docstring": false, - "docstring": "", - "parameters": [ - "target", - "project_modules" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function is_project_import", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::is_project_import", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer", - "name": "PythonASTAnalyzer", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [], - "source_code": "class PythonASTAnalyzer(ast.NodeVisitor):\n\n def __init__(\n self,\n file_path: str,\n content: str,\n repo_path: Optional[str] = None,\n project_modules: Optional[Set[str]] = None,\n ):\n \"\"\"\n Initialize the Python AST analyzer.\n\n Args:\n file_path: Path to the Python file being analyzed\n content: Raw content of the Python file\n repo_path: Repository root path for calculating relative paths\n project_modules: Dotted module paths of every Python file in the\n repository, used to classify imports as project vs third-party\n \"\"\"\n self.file_path = file_path\n self.repo_path = repo_path\n self.content = content\n self.lines = content.splitlines()\n self.project_modules = project_modules\n self.nodes: List[Node] = []\n self.call_relationships: List[CallRelationship] = []\n\n # Scope tracking: (\"class\"|\"function\", name) entries, plus the ids of\n # extracted components for caller attribution.\n self.scope_stack: List[Tuple[str, str]] = []\n self.component_stack: List[str] = []\n\n # Same-file definitions by bare name (top-level functions and classes).\n self.top_level_nodes: Dict[str, Node] = {}\n\n # Per-class knowledge, keyed by dotted class name (\"Outer.Inner\").\n self.class_methods: Dict[str, Set[str]] = {}\n self.class_bases: Dict[str, List[str]] = {}\n\n # Import bindings: local alias -> canonical dotted target.\n self.module_imports: Dict[str, str] = {}\n self.from_imports: Dict[str, str] = {}\n self.external_import_roots: Set[str] = set()\n\n # Shallow receiver knowledge: variable -> same-file class dotted name,\n # and variable -> dotted origin expression (\"logging.getLogger\").\n self.var_types: Dict[str, str] = {}\n self.var_origins: Dict[str, str] = {}\n\n # Names of functions nested inside the current function scopes. A\n # call to one is internal to its enclosing component, not an edge.\n self.local_function_names: List[Set[str]] = []\n\n def _get_relative_path(self) -> str:\n \"\"\"Get relative path from repo root.\"\"\"\n if self.repo_path:\n return os.path.relpath(self.file_path, self.repo_path)\n return str(self.file_path)\n\n def _get_module_path(self) -> str:\n try:\n path = self._get_relative_path()\n for ext in ['.py', '.pyx']:\n if path.endswith(ext):\n path = path[:-len(ext)]\n break\n module = path.replace('/', '.').replace('\\\\', '.')\n except Exception:\n module = str(self.file_path).replace('/', '.').replace('\\\\', '.')\n if module.endswith('.__init__'):\n module = module[: -len('.__init__')]\n return module\n\n def _current_class_dotted(self) -> Optional[str]:\n names = [name for kind, name in self.scope_stack if kind == \"class\"]\n return \".\".join(names) if names else None\n\n def _inside_function(self) -> bool:\n return any(kind == \"function\" for kind, _ in self.scope_stack)\n\n def _caller_id(self) -> Optional[str]:\n return self.component_stack[-1] if self.component_stack else None\n\n def _add_relationship(self, callee: str, is_resolved: bool, line: int) -> None:\n caller = self._caller_id()\n if not caller:\n return\n self.call_relationships.append(CallRelationship(\n caller=caller,\n callee=callee,\n call_line=line,\n is_resolved=is_resolved,\n ))\n\n # ------------------------------------------------------------------\n # Imports\n # ------------------------------------------------------------------\n\n def visit_Import(self, node: ast.Import):\n for alias in node.names:\n if alias.asname:\n self.module_imports[alias.asname] = alias.name\n else:\n # `import a.b.c` binds `a`; attribute chains rebuild the rest.\n head = alias.name.split(\".\")[0]\n self.module_imports[head] = head\n self._note_import_root(alias.name)\n self.generic_visit(node)\n\n def visit_ImportFrom(self, node: ast.ImportFrom):\n base = node.module or \"\"\n if node.level:\n package_parts = self._get_module_path().split(\".\")[:-1]\n if node.level > 1:\n package_parts = package_parts[: -(node.level - 1)] or package_parts[:1]\n prefix = \".\".join(package_parts)\n base = f\"{prefix}.{base}\" if base else prefix\n for alias in node.names:\n if alias.name == \"*\":\n continue\n target = f\"{base}.{alias.name}\" if base else alias.name\n self.from_imports[alias.asname or alias.name] = target\n if base:\n self._note_import_root(base)\n self.generic_visit(node)\n\n def _note_import_root(self, target: str) -> None:\n root = target.split(\".\")[0]\n if not root or root in PYTHON_STDLIB_MODULES:\n return\n if self.project_modules is not None and not is_project_import(\n target, self.project_modules\n ):\n self.external_import_roots.add(root)\n\n # ------------------------------------------------------------------\n # Definitions\n # ------------------------------------------------------------------\n\n def visit_ClassDef(self, node: ast.ClassDef):\n \"\"\"Visit class definition, extract it and its method table.\"\"\"\n if self._inside_function():\n # Classes local to a function body are implementation details:\n # traverse for calls, but do not extract components for them.\n self.scope_stack.append((\"class\", node.name))\n self.generic_visit(node)\n self.scope_stack.pop()\n return\n\n base_classes = [self._extract_base_class_name(base) for base in node.bases]\n base_classes = [name for name in base_classes if name is not None]\n\n enclosing = self._current_class_dotted()\n class_dotted = f\"{enclosing}.{node.name}\" if enclosing else node.name\n relative_path = self._get_relative_path()\n component_id = f\"{relative_path}::{class_dotted}\"\n\n self.class_methods[class_dotted] = {\n child.name\n for child in node.body\n if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef))\n }\n self.class_bases[class_dotted] = base_classes\n\n class_node = Node(\n id=component_id,\n name=class_dotted,\n component_type=\"class\",\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=\"\\n\".join(self.lines[node.lineno - 1 : node.end_lineno or node.lineno]),\n start_line=node.lineno,\n end_line=node.end_lineno,\n has_docstring=bool(ast.get_docstring(node)),\n docstring=ast.get_docstring(node) or \"\",\n parameters=None,\n node_type=\"class\",\n base_classes=base_classes if base_classes else None,\n class_name=enclosing,\n display_name=f\"class {class_dotted}\",\n component_id=component_id,\n language=\"python\",\n qualified_name=f\"{self._get_module_path()}.{class_dotted}\",\n )\n self.nodes.append(class_node)\n if not enclosing:\n self.top_level_nodes[node.name] = class_node\n\n for base_name in base_classes:\n resolved = self._resolve_name_reference(base_name)\n if resolved:\n self.call_relationships.append(CallRelationship(\n caller=component_id,\n callee=resolved[0],\n call_line=node.lineno,\n is_resolved=resolved[1],\n ))\n\n self.scope_stack.append((\"class\", node.name))\n self.component_stack.append(component_id)\n self.generic_visit(node)\n self.component_stack.pop()\n self.scope_stack.pop()\n\n def _extract_base_class_name(self, base):\n \"\"\"Extract base class name from AST node.\"\"\"\n if isinstance(base, ast.Name):\n return base.id\n elif isinstance(base, ast.Attribute):\n parts = []\n node = base\n while isinstance(node, ast.Attribute):\n parts.append(node.attr)\n node = node.value\n if isinstance(node, ast.Name):\n parts.append(node.id)\n return \".\".join(reversed(parts))\n return None\n\n def _process_function_node(self, node: ast.FunctionDef | ast.AsyncFunctionDef):\n \"\"\"Process a function definition: top-level functions and class\n methods become components; functions nested inside functions only\n contribute calls to their enclosing component.\"\"\"\n relative_path = self._get_relative_path()\n is_method = (\n bool(self.scope_stack)\n and self.scope_stack[-1][0] == \"class\"\n and self._current_class_dotted() in self.class_methods\n )\n is_top_level = not self.scope_stack\n\n func_node = None\n if is_top_level:\n component_id = f\"{relative_path}::{node.name}\"\n func_node = Node(\n id=component_id,\n name=node.name,\n component_type=\"function\",\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=\"\\n\".join(self.lines[node.lineno - 1 : node.end_lineno or node.lineno]),\n start_line=node.lineno,\n end_line=node.end_lineno,\n has_docstring=bool(ast.get_docstring(node)),\n docstring=ast.get_docstring(node) or \"\",\n parameters=[arg.arg for arg in node.args.args],\n node_type=\"function\",\n base_classes=None,\n class_name=None,\n display_name=f\"function {node.name}\",\n component_id=component_id,\n language=\"python\",\n qualified_name=f\"{self._get_module_path()}.{node.name}\",\n )\n if self._should_include_function(func_node):\n self.nodes.append(func_node)\n self.top_level_nodes[node.name] = func_node\n else:\n func_node = None\n elif is_method:\n class_dotted = self._current_class_dotted()\n method_dotted = f\"{class_dotted}.{node.name}\"\n component_id = f\"{relative_path}::{method_dotted}\"\n func_node = Node(\n id=component_id,\n name=method_dotted,\n component_type=\"method\",\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=\"\\n\".join(self.lines[node.lineno - 1 : node.end_lineno or node.lineno]),\n start_line=node.lineno,\n end_line=node.end_lineno,\n has_docstring=bool(ast.get_docstring(node)),\n docstring=ast.get_docstring(node) or \"\",\n parameters=[arg.arg for arg in node.args.args],\n node_type=\"method\",\n base_classes=None,\n class_name=class_dotted,\n display_name=f\"method {method_dotted}\",\n component_id=component_id,\n language=\"python\",\n qualified_name=f\"{self._get_module_path()}.{method_dotted}\",\n )\n if self._should_include_function(func_node):\n self.nodes.append(func_node)\n else:\n func_node = None\n\n if not func_node and self.local_function_names:\n self.local_function_names[-1].add(node.name)\n\n self.scope_stack.append((\"function\", node.name))\n self.local_function_names.append(set())\n if func_node:\n self.component_stack.append(func_node.id)\n self.generic_visit(node)\n if func_node:\n self.component_stack.pop()\n self.local_function_names.pop()\n self.scope_stack.pop()\n\n def _should_include_function(self, func: Node) -> bool:\n bare_name = func.name.split(\".\")[-1]\n if bare_name.startswith(\"_test_\"):\n return False\n return True\n\n def visit_FunctionDef(self, node: ast.FunctionDef):\n \"\"\"Visit function definition and extract function information.\"\"\"\n self._process_function_node(node)\n\n def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef):\n \"\"\"Visit async function definition and extract function information.\"\"\"\n self._process_function_node(node)\n\n # ------------------------------------------------------------------\n # Assignments (shallow receiver knowledge)\n # ------------------------------------------------------------------\n\n def visit_Assign(self, node: ast.Assign):\n self._track_assignment(node.targets, node.value)\n self.generic_visit(node)\n\n def visit_AnnAssign(self, node: ast.AnnAssign):\n if node.value is not None:\n self._track_assignment([node.target], node.value)\n self.generic_visit(node)\n\n def _track_assignment(self, targets, value) -> None:\n if len(targets) != 1 or not isinstance(targets[0], ast.Name):\n return\n name = targets[0].id\n if not isinstance(value, ast.Call):\n return\n chain = self._attribute_chain(value.func)\n if not chain:\n return\n root, rest = chain[0], chain[1:]\n if root in self.top_level_nodes and not rest:\n if self.top_level_nodes[root].component_type == \"class\":\n self.var_types[name] = root\n elif root in self.from_imports:\n self.var_origins[name] = \".\".join([self.from_imports[root], *rest])\n elif root in self.module_imports:\n self.var_origins[name] = \".\".join([self.module_imports[root], *rest])\n\n # ------------------------------------------------------------------\n # Calls\n # ------------------------------------------------------------------\n\n def visit_Call(self, node: ast.Call):\n \"\"\"Visit a call and emit at most one relationship for it.\"\"\"\n if self._caller_id():\n classified = self._classify_call(node.func)\n if classified:\n callee, is_resolved = classified\n self._add_relationship(callee, is_resolved, node.lineno)\n self.generic_visit(node)\n\n def _classify_call(self, func) -> Optional[Tuple[str, bool]]:\n \"\"\"Map a call target to (callee, is_resolved).\n\n Bare names check same-file definitions, then imports. Attribute calls\n are resolved receiver-first: self/cls/super against the enclosing\n class (with same-file inheritance), known classes and typed variables\n against their method tables, imported modules to canonical dotted\n names. Built-in filtering happens after global resolution, never here.\n \"\"\"\n if isinstance(func, ast.Name):\n return self._resolve_name_reference(func.id)\n\n if not isinstance(func, ast.Attribute):\n return None\n\n chain = self._attribute_chain(func)\n if chain is None:\n # Composite receiver (call result, subscript, literal): only the\n # method name is knowable. A core-object method on an unknowable\n # receiver could never resolve to a project component; anything\n # else is kept as an honest unresolved bare name.\n if func.attr in PYTHON_OBJECT_METHODS:\n return None\n return (func.attr, False)\n\n root, rest = chain[0], chain[1:]\n\n if root in (\"self\", \"cls\") and len(rest) == 1:\n return self._resolve_method_on_class(self._current_class_dotted(), rest[0])\n\n if root == \"super()\" and len(rest) == 1:\n class_dotted = self._current_class_dotted()\n if class_dotted:\n resolved = self._resolve_method_via_bases(class_dotted, rest[0])\n if resolved:\n return resolved\n return (rest[0], False)\n\n if rest:\n method = rest[-1]\n if root in self.var_types:\n return self._resolve_method_on_class(self.var_types[root], method) if len(rest) == 1 else (\n \".\".join([self.var_types[root], *rest]), False)\n if root in self.class_methods and len(rest) == 1:\n return self._resolve_method_on_class(root, method)\n if root in self.from_imports:\n return (\".\".join([self.from_imports[root], *rest]), False)\n if root in self.module_imports:\n return (\".\".join([self.module_imports[root], *rest]), False)\n if root in self.var_origins:\n return (\".\".join([self.var_origins[root], *rest]), False)\n\n return (\".\".join(chain), False)\n\n def _resolve_name_reference(self, name: str) -> Optional[Tuple[str, bool]]:\n \"\"\"Resolve a bare name reference (call target or base class).\"\"\"\n if not name:\n return None\n if any(name in local for local in self.local_function_names):\n return None\n if \".\" in name:\n # Dotted base-class names route through the attribute logic.\n head, *rest = name.split(\".\")\n if head in self.module_imports:\n return (\".\".join([self.module_imports[head], *rest]), False)\n if head in self.from_imports:\n return (\".\".join([self.from_imports[head], *rest]), False)\n return (name, False)\n if name in self.top_level_nodes:\n return (f\"{self._get_relative_path()}::{name}\", True)\n if name in self.from_imports:\n return (self.from_imports[name], False)\n if name in self.module_imports:\n return (self.module_imports[name], False)\n return (name, False)\n\n def _resolve_method_on_class(self, class_dotted: Optional[str], method: str) -> Tuple[str, bool]:\n if class_dotted:\n if method in self.class_methods.get(class_dotted, ()):\n return (f\"{self._get_relative_path()}::{class_dotted}.{method}\", True)\n inherited = self._resolve_method_via_bases(class_dotted, method)\n if inherited:\n return inherited\n return (f\"{self._get_module_path()}.{class_dotted}.{method}\", False)\n return (method, False)\n\n def _resolve_method_via_bases(self, class_dotted: str, method: str) -> Optional[Tuple[str, bool]]:\n seen = set()\n queue = list(self.class_bases.get(class_dotted, ()))\n while queue:\n base = queue.pop(0)\n if base in seen:\n continue\n seen.add(base)\n if method in self.class_methods.get(base, ()):\n return (f\"{self._get_relative_path()}::{base}.{method}\", True)\n if base in self.class_bases:\n queue.extend(self.class_bases[base])\n continue\n resolved_base = self._resolve_name_reference(base)\n if resolved_base and not resolved_base[1] and \".\" in resolved_base[0]:\n # Imported base: emit the canonical dotted method for the\n # global resolver to match against qualified names.\n return (f\"{resolved_base[0]}.{method}\", False)\n return None\n\n def _attribute_chain(self, node) -> Optional[List[str]]:\n \"\"\"Flatten an attribute chain to its dotted parts.\n\n Returns None when the receiver is not a simple name chain (a call\n result, subscript, literal, ...), except `super()` which is folded\n into a \"super()\" root so override calls can resolve.\n \"\"\"\n parts: List[str] = []\n while isinstance(node, ast.Attribute):\n parts.append(node.attr)\n node = node.value\n if isinstance(node, ast.Name):\n parts.append(node.id)\n elif (\n isinstance(node, ast.Call)\n and isinstance(node.func, ast.Name)\n and node.func.id == \"super\"\n ):\n parts.append(\"super()\")\n else:\n return None\n return list(reversed(parts))\n\n def analyze(self):\n \"\"\"Analyze the Python file and extract functions and relationships.\"\"\"\n\n try:\n # Suppress SyntaxWarnings about invalid escape sequences in source code\n # These warnings come from regex patterns like '\\(' or '\\.' in the analyzed files\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=SyntaxWarning)\n tree = ast.parse(self.content)\n self.visit(tree)\n\n logger.debug(\n f\"Python analysis complete for {self.file_path}: {len(self.nodes)} nodes, \"\n f\"{len(self.call_relationships)} relationships\"\n )\n except SyntaxError as e:\n logger.warning(f\"Could not parse {self.file_path}: {e}\")\n except Exception as e:\n logger.error(f\"Error analyzing {self.file_path}: {e}\", exc_info=True)", - "start_line": 27, - "end_line": 533, - "has_docstring": false, - "docstring": "", - "parameters": null, - "node_type": "class", - "base_classes": [ - "ast.NodeVisitor" - ], - "class_name": null, - "display_name": "class PythonASTAnalyzer", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.__init__": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.__init__", - "name": "PythonASTAnalyzer.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [], - "source_code": " def __init__(\n self,\n file_path: str,\n content: str,\n repo_path: Optional[str] = None,\n project_modules: Optional[Set[str]] = None,\n ):\n \"\"\"\n Initialize the Python AST analyzer.\n\n Args:\n file_path: Path to the Python file being analyzed\n content: Raw content of the Python file\n repo_path: Repository root path for calculating relative paths\n project_modules: Dotted module paths of every Python file in the\n repository, used to classify imports as project vs third-party\n \"\"\"\n self.file_path = file_path\n self.repo_path = repo_path\n self.content = content\n self.lines = content.splitlines()\n self.project_modules = project_modules\n self.nodes: List[Node] = []\n self.call_relationships: List[CallRelationship] = []\n\n # Scope tracking: (\"class\"|\"function\", name) entries, plus the ids of\n # extracted components for caller attribution.\n self.scope_stack: List[Tuple[str, str]] = []\n self.component_stack: List[str] = []\n\n # Same-file definitions by bare name (top-level functions and classes).\n self.top_level_nodes: Dict[str, Node] = {}\n\n # Per-class knowledge, keyed by dotted class name (\"Outer.Inner\").\n self.class_methods: Dict[str, Set[str]] = {}\n self.class_bases: Dict[str, List[str]] = {}\n\n # Import bindings: local alias -> canonical dotted target.\n self.module_imports: Dict[str, str] = {}\n self.from_imports: Dict[str, str] = {}\n self.external_import_roots: Set[str] = set()\n\n # Shallow receiver knowledge: variable -> same-file class dotted name,\n # and variable -> dotted origin expression (\"logging.getLogger\").\n self.var_types: Dict[str, str] = {}\n self.var_origins: Dict[str, str] = {}\n\n # Names of functions nested inside the current function scopes. A\n # call to one is internal to its enclosing component, not an edge.\n self.local_function_names: List[Set[str]] = []", - "start_line": 29, - "end_line": 78, - "has_docstring": true, - "docstring": "Initialize the Python AST analyzer.\n\nArgs:\n file_path: Path to the Python file being analyzed\n content: Raw content of the Python file\n repo_path: Repository root path for calculating relative paths\n project_modules: Dotted module paths of every Python file in the\n repository, used to classify imports as project vs third-party", - "parameters": [ - "self", - "file_path", - "content", - "repo_path", - "project_modules" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer.__init__", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._get_relative_path": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._get_relative_path", - "name": "PythonASTAnalyzer._get_relative_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [], - "source_code": " def _get_relative_path(self) -> str:\n \"\"\"Get relative path from repo root.\"\"\"\n if self.repo_path:\n return os.path.relpath(self.file_path, self.repo_path)\n return str(self.file_path)", - "start_line": 80, - "end_line": 84, - "has_docstring": true, - "docstring": "Get relative path from repo root.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer._get_relative_path", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._get_relative_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._get_module_path": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._get_module_path", - "name": "PythonASTAnalyzer._get_module_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._get_relative_path" - ], - "source_code": " def _get_module_path(self) -> str:\n try:\n path = self._get_relative_path()\n for ext in ['.py', '.pyx']:\n if path.endswith(ext):\n path = path[:-len(ext)]\n break\n module = path.replace('/', '.').replace('\\\\', '.')\n except Exception:\n module = str(self.file_path).replace('/', '.').replace('\\\\', '.')\n if module.endswith('.__init__'):\n module = module[: -len('.__init__')]\n return module", - "start_line": 86, - "end_line": 98, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer._get_module_path", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._get_module_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._current_class_dotted": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._current_class_dotted", - "name": "PythonASTAnalyzer._current_class_dotted", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [], - "source_code": " def _current_class_dotted(self) -> Optional[str]:\n names = [name for kind, name in self.scope_stack if kind == \"class\"]\n return \".\".join(names) if names else None", - "start_line": 100, - "end_line": 102, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer._current_class_dotted", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._current_class_dotted", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._inside_function": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._inside_function", - "name": "PythonASTAnalyzer._inside_function", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [], - "source_code": " def _inside_function(self) -> bool:\n return any(kind == \"function\" for kind, _ in self.scope_stack)", - "start_line": 104, - "end_line": 105, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer._inside_function", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._inside_function", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._caller_id": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._caller_id", - "name": "PythonASTAnalyzer._caller_id", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [], - "source_code": " def _caller_id(self) -> Optional[str]:\n return self.component_stack[-1] if self.component_stack else None", - "start_line": 107, - "end_line": 108, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer._caller_id", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._caller_id", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._add_relationship": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._add_relationship", - "name": "PythonASTAnalyzer._add_relationship", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._caller_id", - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship" - ], - "source_code": " def _add_relationship(self, callee: str, is_resolved: bool, line: int) -> None:\n caller = self._caller_id()\n if not caller:\n return\n self.call_relationships.append(CallRelationship(\n caller=caller,\n callee=callee,\n call_line=line,\n is_resolved=is_resolved,\n ))", - "start_line": 110, - "end_line": 119, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "callee", - "is_resolved", - "line" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer._add_relationship", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._add_relationship", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_Import": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_Import", - "name": "PythonASTAnalyzer.visit_Import", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._note_import_root" - ], - "source_code": " def visit_Import(self, node: ast.Import):\n for alias in node.names:\n if alias.asname:\n self.module_imports[alias.asname] = alias.name\n else:\n # `import a.b.c` binds `a`; attribute chains rebuild the rest.\n head = alias.name.split(\".\")[0]\n self.module_imports[head] = head\n self._note_import_root(alias.name)\n self.generic_visit(node)", - "start_line": 125, - "end_line": 134, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer.visit_Import", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_Import", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_ImportFrom": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_ImportFrom", - "name": "PythonASTAnalyzer.visit_ImportFrom", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._get_module_path", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._note_import_root" - ], - "source_code": " def visit_ImportFrom(self, node: ast.ImportFrom):\n base = node.module or \"\"\n if node.level:\n package_parts = self._get_module_path().split(\".\")[:-1]\n if node.level > 1:\n package_parts = package_parts[: -(node.level - 1)] or package_parts[:1]\n prefix = \".\".join(package_parts)\n base = f\"{prefix}.{base}\" if base else prefix\n for alias in node.names:\n if alias.name == \"*\":\n continue\n target = f\"{base}.{alias.name}\" if base else alias.name\n self.from_imports[alias.asname or alias.name] = target\n if base:\n self._note_import_root(base)\n self.generic_visit(node)", - "start_line": 136, - "end_line": 151, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer.visit_ImportFrom", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_ImportFrom", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._note_import_root": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._note_import_root", - "name": "PythonASTAnalyzer._note_import_root", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/python.py::is_project_import" - ], - "source_code": " def _note_import_root(self, target: str) -> None:\n root = target.split(\".\")[0]\n if not root or root in PYTHON_STDLIB_MODULES:\n return\n if self.project_modules is not None and not is_project_import(\n target, self.project_modules\n ):\n self.external_import_roots.add(root)", - "start_line": 153, - "end_line": 160, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "target" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer._note_import_root", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._note_import_root", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_ClassDef": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_ClassDef", - "name": "PythonASTAnalyzer.visit_ClassDef", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._extract_base_class_name", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._resolve_name_reference", - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._get_relative_path", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._current_class_dotted", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._get_module_path", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._inside_function" - ], - "source_code": " def visit_ClassDef(self, node: ast.ClassDef):\n \"\"\"Visit class definition, extract it and its method table.\"\"\"\n if self._inside_function():\n # Classes local to a function body are implementation details:\n # traverse for calls, but do not extract components for them.\n self.scope_stack.append((\"class\", node.name))\n self.generic_visit(node)\n self.scope_stack.pop()\n return\n\n base_classes = [self._extract_base_class_name(base) for base in node.bases]\n base_classes = [name for name in base_classes if name is not None]\n\n enclosing = self._current_class_dotted()\n class_dotted = f\"{enclosing}.{node.name}\" if enclosing else node.name\n relative_path = self._get_relative_path()\n component_id = f\"{relative_path}::{class_dotted}\"\n\n self.class_methods[class_dotted] = {\n child.name\n for child in node.body\n if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef))\n }\n self.class_bases[class_dotted] = base_classes\n\n class_node = Node(\n id=component_id,\n name=class_dotted,\n component_type=\"class\",\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=\"\\n\".join(self.lines[node.lineno - 1 : node.end_lineno or node.lineno]),\n start_line=node.lineno,\n end_line=node.end_lineno,\n has_docstring=bool(ast.get_docstring(node)),\n docstring=ast.get_docstring(node) or \"\",\n parameters=None,\n node_type=\"class\",\n base_classes=base_classes if base_classes else None,\n class_name=enclosing,\n display_name=f\"class {class_dotted}\",\n component_id=component_id,\n language=\"python\",\n qualified_name=f\"{self._get_module_path()}.{class_dotted}\",\n )\n self.nodes.append(class_node)\n if not enclosing:\n self.top_level_nodes[node.name] = class_node\n\n for base_name in base_classes:\n resolved = self._resolve_name_reference(base_name)\n if resolved:\n self.call_relationships.append(CallRelationship(\n caller=component_id,\n callee=resolved[0],\n call_line=node.lineno,\n is_resolved=resolved[1],\n ))\n\n self.scope_stack.append((\"class\", node.name))\n self.component_stack.append(component_id)\n self.generic_visit(node)\n self.component_stack.pop()\n self.scope_stack.pop()", - "start_line": 166, - "end_line": 229, - "has_docstring": true, - "docstring": "Visit class definition, extract it and its method table.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer.visit_ClassDef", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_ClassDef", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._extract_base_class_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._extract_base_class_name", - "name": "PythonASTAnalyzer._extract_base_class_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [], - "source_code": " def _extract_base_class_name(self, base):\n \"\"\"Extract base class name from AST node.\"\"\"\n if isinstance(base, ast.Name):\n return base.id\n elif isinstance(base, ast.Attribute):\n parts = []\n node = base\n while isinstance(node, ast.Attribute):\n parts.append(node.attr)\n node = node.value\n if isinstance(node, ast.Name):\n parts.append(node.id)\n return \".\".join(reversed(parts))\n return None", - "start_line": 231, - "end_line": 244, - "has_docstring": true, - "docstring": "Extract base class name from AST node.", - "parameters": [ - "self", - "base" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer._extract_base_class_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._extract_base_class_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._process_function_node": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._process_function_node", - "name": "PythonASTAnalyzer._process_function_node", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._get_relative_path", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._current_class_dotted", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._get_module_path", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._should_include_function" - ], - "source_code": " def _process_function_node(self, node: ast.FunctionDef | ast.AsyncFunctionDef):\n \"\"\"Process a function definition: top-level functions and class\n methods become components; functions nested inside functions only\n contribute calls to their enclosing component.\"\"\"\n relative_path = self._get_relative_path()\n is_method = (\n bool(self.scope_stack)\n and self.scope_stack[-1][0] == \"class\"\n and self._current_class_dotted() in self.class_methods\n )\n is_top_level = not self.scope_stack\n\n func_node = None\n if is_top_level:\n component_id = f\"{relative_path}::{node.name}\"\n func_node = Node(\n id=component_id,\n name=node.name,\n component_type=\"function\",\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=\"\\n\".join(self.lines[node.lineno - 1 : node.end_lineno or node.lineno]),\n start_line=node.lineno,\n end_line=node.end_lineno,\n has_docstring=bool(ast.get_docstring(node)),\n docstring=ast.get_docstring(node) or \"\",\n parameters=[arg.arg for arg in node.args.args],\n node_type=\"function\",\n base_classes=None,\n class_name=None,\n display_name=f\"function {node.name}\",\n component_id=component_id,\n language=\"python\",\n qualified_name=f\"{self._get_module_path()}.{node.name}\",\n )\n if self._should_include_function(func_node):\n self.nodes.append(func_node)\n self.top_level_nodes[node.name] = func_node\n else:\n func_node = None\n elif is_method:\n class_dotted = self._current_class_dotted()\n method_dotted = f\"{class_dotted}.{node.name}\"\n component_id = f\"{relative_path}::{method_dotted}\"\n func_node = Node(\n id=component_id,\n name=method_dotted,\n component_type=\"method\",\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=\"\\n\".join(self.lines[node.lineno - 1 : node.end_lineno or node.lineno]),\n start_line=node.lineno,\n end_line=node.end_lineno,\n has_docstring=bool(ast.get_docstring(node)),\n docstring=ast.get_docstring(node) or \"\",\n parameters=[arg.arg for arg in node.args.args],\n node_type=\"method\",\n base_classes=None,\n class_name=class_dotted,\n display_name=f\"method {method_dotted}\",\n component_id=component_id,\n language=\"python\",\n qualified_name=f\"{self._get_module_path()}.{method_dotted}\",\n )\n if self._should_include_function(func_node):\n self.nodes.append(func_node)\n else:\n func_node = None\n\n if not func_node and self.local_function_names:\n self.local_function_names[-1].add(node.name)\n\n self.scope_stack.append((\"function\", node.name))\n self.local_function_names.append(set())\n if func_node:\n self.component_stack.append(func_node.id)\n self.generic_visit(node)\n if func_node:\n self.component_stack.pop()\n self.local_function_names.pop()\n self.scope_stack.pop()", - "start_line": 246, - "end_line": 326, - "has_docstring": true, - "docstring": "Process a function definition: top-level functions and class\nmethods become components; functions nested inside functions only\ncontribute calls to their enclosing component.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer._process_function_node", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._process_function_node", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._should_include_function": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._should_include_function", - "name": "PythonASTAnalyzer._should_include_function", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [], - "source_code": " def _should_include_function(self, func: Node) -> bool:\n bare_name = func.name.split(\".\")[-1]\n if bare_name.startswith(\"_test_\"):\n return False\n return True", - "start_line": 328, - "end_line": 332, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "func" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer._should_include_function", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._should_include_function", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_FunctionDef": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_FunctionDef", - "name": "PythonASTAnalyzer.visit_FunctionDef", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._process_function_node" - ], - "source_code": " def visit_FunctionDef(self, node: ast.FunctionDef):\n \"\"\"Visit function definition and extract function information.\"\"\"\n self._process_function_node(node)", - "start_line": 334, - "end_line": 336, - "has_docstring": true, - "docstring": "Visit function definition and extract function information.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer.visit_FunctionDef", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_FunctionDef", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_AsyncFunctionDef": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_AsyncFunctionDef", - "name": "PythonASTAnalyzer.visit_AsyncFunctionDef", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._process_function_node" - ], - "source_code": " def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef):\n \"\"\"Visit async function definition and extract function information.\"\"\"\n self._process_function_node(node)", - "start_line": 338, - "end_line": 340, - "has_docstring": true, - "docstring": "Visit async function definition and extract function information.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer.visit_AsyncFunctionDef", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_AsyncFunctionDef", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_Assign": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_Assign", - "name": "PythonASTAnalyzer.visit_Assign", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._track_assignment" - ], - "source_code": " def visit_Assign(self, node: ast.Assign):\n self._track_assignment(node.targets, node.value)\n self.generic_visit(node)", - "start_line": 346, - "end_line": 348, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer.visit_Assign", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_Assign", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_AnnAssign": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_AnnAssign", - "name": "PythonASTAnalyzer.visit_AnnAssign", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._track_assignment" - ], - "source_code": " def visit_AnnAssign(self, node: ast.AnnAssign):\n if node.value is not None:\n self._track_assignment([node.target], node.value)\n self.generic_visit(node)", - "start_line": 350, - "end_line": 353, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer.visit_AnnAssign", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_AnnAssign", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._track_assignment": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._track_assignment", - "name": "PythonASTAnalyzer._track_assignment", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._attribute_chain" - ], - "source_code": " def _track_assignment(self, targets, value) -> None:\n if len(targets) != 1 or not isinstance(targets[0], ast.Name):\n return\n name = targets[0].id\n if not isinstance(value, ast.Call):\n return\n chain = self._attribute_chain(value.func)\n if not chain:\n return\n root, rest = chain[0], chain[1:]\n if root in self.top_level_nodes and not rest:\n if self.top_level_nodes[root].component_type == \"class\":\n self.var_types[name] = root\n elif root in self.from_imports:\n self.var_origins[name] = \".\".join([self.from_imports[root], *rest])\n elif root in self.module_imports:\n self.var_origins[name] = \".\".join([self.module_imports[root], *rest])", - "start_line": 355, - "end_line": 371, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "targets", - "value" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer._track_assignment", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._track_assignment", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_Call": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_Call", - "name": "PythonASTAnalyzer.visit_Call", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._classify_call", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._caller_id", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._add_relationship" - ], - "source_code": " def visit_Call(self, node: ast.Call):\n \"\"\"Visit a call and emit at most one relationship for it.\"\"\"\n if self._caller_id():\n classified = self._classify_call(node.func)\n if classified:\n callee, is_resolved = classified\n self._add_relationship(callee, is_resolved, node.lineno)\n self.generic_visit(node)", - "start_line": 377, - "end_line": 384, - "has_docstring": true, - "docstring": "Visit a call and emit at most one relationship for it.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer.visit_Call", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.visit_Call", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._classify_call": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._classify_call", - "name": "PythonASTAnalyzer._classify_call", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._resolve_name_reference", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._resolve_method_on_class", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._current_class_dotted", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._resolve_method_via_bases", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._attribute_chain" - ], - "source_code": " def _classify_call(self, func) -> Optional[Tuple[str, bool]]:\n \"\"\"Map a call target to (callee, is_resolved).\n\n Bare names check same-file definitions, then imports. Attribute calls\n are resolved receiver-first: self/cls/super against the enclosing\n class (with same-file inheritance), known classes and typed variables\n against their method tables, imported modules to canonical dotted\n names. Built-in filtering happens after global resolution, never here.\n \"\"\"\n if isinstance(func, ast.Name):\n return self._resolve_name_reference(func.id)\n\n if not isinstance(func, ast.Attribute):\n return None\n\n chain = self._attribute_chain(func)\n if chain is None:\n # Composite receiver (call result, subscript, literal): only the\n # method name is knowable. A core-object method on an unknowable\n # receiver could never resolve to a project component; anything\n # else is kept as an honest unresolved bare name.\n if func.attr in PYTHON_OBJECT_METHODS:\n return None\n return (func.attr, False)\n\n root, rest = chain[0], chain[1:]\n\n if root in (\"self\", \"cls\") and len(rest) == 1:\n return self._resolve_method_on_class(self._current_class_dotted(), rest[0])\n\n if root == \"super()\" and len(rest) == 1:\n class_dotted = self._current_class_dotted()\n if class_dotted:\n resolved = self._resolve_method_via_bases(class_dotted, rest[0])\n if resolved:\n return resolved\n return (rest[0], False)\n\n if rest:\n method = rest[-1]\n if root in self.var_types:\n return self._resolve_method_on_class(self.var_types[root], method) if len(rest) == 1 else (\n \".\".join([self.var_types[root], *rest]), False)\n if root in self.class_methods and len(rest) == 1:\n return self._resolve_method_on_class(root, method)\n if root in self.from_imports:\n return (\".\".join([self.from_imports[root], *rest]), False)\n if root in self.module_imports:\n return (\".\".join([self.module_imports[root], *rest]), False)\n if root in self.var_origins:\n return (\".\".join([self.var_origins[root], *rest]), False)\n\n return (\".\".join(chain), False)", - "start_line": 386, - "end_line": 438, - "has_docstring": true, - "docstring": "Map a call target to (callee, is_resolved).\n\nBare names check same-file definitions, then imports. Attribute calls\nare resolved receiver-first: self/cls/super against the enclosing\nclass (with same-file inheritance), known classes and typed variables\nagainst their method tables, imported modules to canonical dotted\nnames. Built-in filtering happens after global resolution, never here.", - "parameters": [ - "self", - "func" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer._classify_call", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._classify_call", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._resolve_name_reference": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._resolve_name_reference", - "name": "PythonASTAnalyzer._resolve_name_reference", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._get_relative_path" - ], - "source_code": " def _resolve_name_reference(self, name: str) -> Optional[Tuple[str, bool]]:\n \"\"\"Resolve a bare name reference (call target or base class).\"\"\"\n if not name:\n return None\n if any(name in local for local in self.local_function_names):\n return None\n if \".\" in name:\n # Dotted base-class names route through the attribute logic.\n head, *rest = name.split(\".\")\n if head in self.module_imports:\n return (\".\".join([self.module_imports[head], *rest]), False)\n if head in self.from_imports:\n return (\".\".join([self.from_imports[head], *rest]), False)\n return (name, False)\n if name in self.top_level_nodes:\n return (f\"{self._get_relative_path()}::{name}\", True)\n if name in self.from_imports:\n return (self.from_imports[name], False)\n if name in self.module_imports:\n return (self.module_imports[name], False)\n return (name, False)", - "start_line": 440, - "end_line": 460, - "has_docstring": true, - "docstring": "Resolve a bare name reference (call target or base class).", - "parameters": [ - "self", - "name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer._resolve_name_reference", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._resolve_name_reference", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._resolve_method_on_class": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._resolve_method_on_class", - "name": "PythonASTAnalyzer._resolve_method_on_class", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._get_module_path", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._resolve_method_via_bases", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._get_relative_path" - ], - "source_code": " def _resolve_method_on_class(self, class_dotted: Optional[str], method: str) -> Tuple[str, bool]:\n if class_dotted:\n if method in self.class_methods.get(class_dotted, ()):\n return (f\"{self._get_relative_path()}::{class_dotted}.{method}\", True)\n inherited = self._resolve_method_via_bases(class_dotted, method)\n if inherited:\n return inherited\n return (f\"{self._get_module_path()}.{class_dotted}.{method}\", False)\n return (method, False)", - "start_line": 462, - "end_line": 470, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "class_dotted", - "method" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer._resolve_method_on_class", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._resolve_method_on_class", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._resolve_method_via_bases": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._resolve_method_via_bases", - "name": "PythonASTAnalyzer._resolve_method_via_bases", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._resolve_name_reference", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._get_relative_path" - ], - "source_code": " def _resolve_method_via_bases(self, class_dotted: str, method: str) -> Optional[Tuple[str, bool]]:\n seen = set()\n queue = list(self.class_bases.get(class_dotted, ()))\n while queue:\n base = queue.pop(0)\n if base in seen:\n continue\n seen.add(base)\n if method in self.class_methods.get(base, ()):\n return (f\"{self._get_relative_path()}::{base}.{method}\", True)\n if base in self.class_bases:\n queue.extend(self.class_bases[base])\n continue\n resolved_base = self._resolve_name_reference(base)\n if resolved_base and not resolved_base[1] and \".\" in resolved_base[0]:\n # Imported base: emit the canonical dotted method for the\n # global resolver to match against qualified names.\n return (f\"{resolved_base[0]}.{method}\", False)\n return None", - "start_line": 472, - "end_line": 490, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "class_dotted", - "method" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer._resolve_method_via_bases", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._resolve_method_via_bases", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._attribute_chain": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._attribute_chain", - "name": "PythonASTAnalyzer._attribute_chain", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [], - "source_code": " def _attribute_chain(self, node) -> Optional[List[str]]:\n \"\"\"Flatten an attribute chain to its dotted parts.\n\n Returns None when the receiver is not a simple name chain (a call\n result, subscript, literal, ...), except `super()` which is folded\n into a \"super()\" root so override calls can resolve.\n \"\"\"\n parts: List[str] = []\n while isinstance(node, ast.Attribute):\n parts.append(node.attr)\n node = node.value\n if isinstance(node, ast.Name):\n parts.append(node.id)\n elif (\n isinstance(node, ast.Call)\n and isinstance(node.func, ast.Name)\n and node.func.id == \"super\"\n ):\n parts.append(\"super()\")\n else:\n return None\n return list(reversed(parts))", - "start_line": 492, - "end_line": 513, - "has_docstring": true, - "docstring": "Flatten an attribute chain to its dotted parts.\n\nReturns None when the receiver is not a simple name chain (a call\nresult, subscript, literal, ...), except `super()` which is folded\ninto a \"super()\" root so override calls can resolve.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer._attribute_chain", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer._attribute_chain", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.analyze": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.analyze", - "name": "PythonASTAnalyzer.analyze", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": " def analyze(self):\n \"\"\"Analyze the Python file and extract functions and relationships.\"\"\"\n\n try:\n # Suppress SyntaxWarnings about invalid escape sequences in source code\n # These warnings come from regex patterns like '\\(' or '\\.' in the analyzed files\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=SyntaxWarning)\n tree = ast.parse(self.content)\n self.visit(tree)\n\n logger.debug(\n f\"Python analysis complete for {self.file_path}: {len(self.nodes)} nodes, \"\n f\"{len(self.call_relationships)} relationships\"\n )\n except SyntaxError as e:\n logger.warning(f\"Could not parse {self.file_path}: {e}\")\n except Exception as e:\n logger.error(f\"Error analyzing {self.file_path}: {e}\", exc_info=True)", - "start_line": 515, - "end_line": 533, - "has_docstring": true, - "docstring": "Analyze the Python file and extract functions and relationships.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PythonASTAnalyzer", - "display_name": "method PythonASTAnalyzer.analyze", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.analyze", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/python.py::analyze_python_file": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::analyze_python_file", - "name": "analyze_python_file", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/python.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/python.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer", - "codewiki/src/be/dependency_analyzer/analyzers/python.py::PythonASTAnalyzer.analyze" - ], - "source_code": "def analyze_python_file(\n file_path: str,\n content: str,\n repo_path: Optional[str] = None,\n project_modules: Optional[Set[str]] = None,\n) -> Tuple[List[Node], List[CallRelationship], Set[str]]:\n \"\"\"\n Analyze a Python file and return components, relationships, and the\n third-party import roots observed in the file.\n\n Args:\n file_path: Path to the Python file\n content: Content of the Python file\n repo_path: Repository root path for calculating relative paths\n project_modules: Dotted module paths of all Python files in the repo\n\n Returns:\n tuple: (nodes, call_relationships, external_import_roots)\n \"\"\"\n\n analyzer = PythonASTAnalyzer(file_path, content, repo_path, project_modules)\n analyzer.analyze()\n return analyzer.nodes, analyzer.call_relationships, analyzer.external_import_roots", - "start_line": 536, - "end_line": 558, - "has_docstring": true, - "docstring": "Analyze a Python file and return components, relationships, and the\nthird-party import roots observed in the file.\n\nArgs:\n file_path: Path to the Python file\n content: Content of the Python file\n repo_path: Repository root path for calculating relative paths\n project_modules: Dotted module paths of all Python files in the repo\n\nReturns:\n tuple: (nodes, call_relationships, external_import_roots)", - "parameters": [ - "file_path", - "content", - "repo_path", - "project_modules" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function analyze_python_file", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/python.py::analyze_python_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer", - "name": "TreeSitterTSAnalyzer", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [], - "source_code": "class TreeSitterTSAnalyzer:\n\n def __init__(self, file_path: str, content: str, repo_path: str = None):\n self.file_path = Path(file_path)\n self.content = content\n self.repo_path = repo_path or \"\"\n self.nodes: List[Node] = []\n self.call_relationships: List[CallRelationship] = []\n self.seen_relationships: Set[Tuple[str, str]] = set()\n\n self.top_level_nodes = {}\n\n try:\n language_capsule = tree_sitter_typescript.language_typescript()\n self.ts_language = Language(language_capsule)\n self.parser = Parser(self.ts_language)\n\n except Exception as e:\n logger.error(f\"Failed to initialize TypeScript parser: {e}\")\n logger.error(f\"Traceback: {traceback.format_exc()}\")\n self.parser = None\n self.ts_language = None\n\n def analyze(self) -> None:\n if self.parser is None:\n logger.debug(f\"Skipping {self.file_path} - parser initialization failed\")\n return\n\n try:\n tree = self.parser.parse(bytes(self.content, \"utf8\"))\n root_node = tree.root_node\n\n logger.debug(f\"Parsed AST with root node type: {root_node.type}\")\n\n all_entities = {} \n self._extract_all_entities(root_node, all_entities)\n \n self._filter_top_level_declarations(all_entities)\n \n self._extract_all_relationships(root_node, all_entities)\n\n except Exception as e:\n logger.error(f\"Error analyzing TypeScript file {self.file_path}: {e}\", exc_info=True)\n\n def _extract_all_entities(self, node, all_entities: dict, depth=0) -> None:\n entity = None\n entity_name = None\n \n if node.type == \"function_declaration\":\n entity = self._extract_function_entity(node, \"function\", depth)\n elif node.type == \"generator_function_declaration\":\n entity = self._extract_function_entity(node, \"generator_function\", depth)\n elif node.type == \"arrow_function\":\n entity = self._extract_arrow_function_entity(node, depth)\n elif node.type == \"method_definition\":\n entity = self._extract_method_entity(node, depth)\n elif node.type == \"class_declaration\":\n entity = self._extract_class_entity(node, \"class\", depth)\n elif node.type == \"abstract_class_declaration\":\n entity = self._extract_class_entity(node, \"abstract_class\", depth)\n elif node.type == \"interface_declaration\":\n entity = self._extract_interface_entity(node, depth)\n elif node.type == \"type_alias_declaration\":\n entity = self._extract_type_alias_entity(node, depth)\n elif node.type == \"enum_declaration\":\n entity = self._extract_enum_entity(node, depth)\n elif node.type == \"variable_declarator\":\n entity = self._extract_variable_entity(node, depth)\n elif node.type == \"export_statement\":\n entity = self._extract_export_statement_entity(node, depth)\n elif node.type == \"lexical_declaration\":\n entity = self._extract_lexical_declaration_entity(node, depth)\n elif node.type == \"variable_declaration\":\n entity = self._extract_variable_declaration_entity(node, depth)\n elif node.type == \"ambient_declaration\":\n entity = self._extract_ambient_declaration_entity(node, depth)\n \n if entity and entity.get('name'):\n entity_name = entity['name']\n entity['depth'] = depth \n entity['node'] = node \n entity['parent_context'] = self._get_parent_context(node) \n all_entities[entity_name] = entity\n \n for child in node.children:\n self._extract_all_entities(child, all_entities, depth + 1)\n \n def _filter_top_level_declarations(self, all_entities: dict) -> None:\n for entity_name, entity_data in all_entities.items():\n if self._is_actually_top_level(entity_data):\n node_obj = self._create_node_from_entity(entity_data)\n if node_obj and self._should_include_node(node_obj):\n self.nodes.append(node_obj)\n self.top_level_nodes[entity_name] = node_obj\n \n if entity_data[\"type\"] in [\"class_declaration\", \"abstract_class_declaration\"]:\n self._extract_constructor_dependencies(entity_data[\"node\"], entity_name)\n \n def _is_actually_top_level(self, entity_data: dict) -> bool:\n node = entity_data.get('node')\n if not node or not node.parent:\n return True\n \n entity_type = entity_data.get('type')\n if self._is_inside_function_body(node):\n return False\n \n current = node.parent\n while current:\n parent_type = current.type\n \n if parent_type == \"program\":\n return True\n \n if parent_type == \"export_statement\":\n return True\n \n if parent_type == \"ambient_declaration\":\n return True\n \n if parent_type == \"module\":\n return True\n \n if parent_type == \"statement_block\":\n grandparent = current.parent\n if grandparent and grandparent.type in [\"module\", \"ambient_declaration\"]:\n return True\n \n current = current.parent\n \n return False\n \n def _is_inside_function_body(self, node) -> bool:\n current = node.parent\n while current:\n if current.type == \"statement_block\":\n if current.parent and current.parent.type in [\n \"function_declaration\", \"generator_function_declaration\", \n \"arrow_function\", \"function_expression\", \"method_definition\"\n ]:\n return True\n current = current.parent\n return False\n\n def _extract_ambient_declaration_entity(self, node, depth: int) -> dict:\n name = \"\"\n for child in node.children:\n if child.type == \"module\":\n for grandchild in child.children:\n if grandchild.type == \"string\":\n name = self._get_node_text(grandchild).strip(\"'\\\"\")\n break\n break\n elif child.type == \"namespace\":\n name = self._get_node_text(child.children[1]) if len(child.children) > 1 else \"unknown_namespace\"\n break\n \n return {\n 'name': f\"{name}\",\n 'type': 'ambient_declaration',\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'parameters': [],\n 'return_type': None,\n 'modifiers': ['ambient'],\n 'complexity': 1\n }\n \n def _get_parent_context(self, node) -> str:\n \"\"\"Get the parent context of a node for better top-level detection\"\"\"\n if not node.parent:\n return \"root\"\n \n parent_type = node.parent.type\n if parent_type in [\"program\", \"source_file\"]:\n return \"program\"\n elif parent_type == \"export_statement\":\n return \"export\"\n elif parent_type == \"ambient_declaration\":\n return \"ambient\"\n elif parent_type == \"module\":\n return \"module\"\n elif parent_type == \"statement_block\":\n if node.parent.parent and node.parent.parent.type in [\"module\", \"ambient_declaration\"]:\n return \"module_block\"\n return \"statement_block\"\n def _extract_function_entity(self, node, func_type: str, depth: int) -> dict:\n name_node = self._find_child_by_type(node, \"identifier\")\n if not name_node:\n return None\n \n func_name = self._get_node_text(name_node)\n parameters = self._extract_parameters(node)\n code_snippet = self._get_node_text(node)\n \n is_async = \"async\" in code_snippet.split(\"function\")[0] if \"function\" in code_snippet else False\n display_name = f\"{'async ' if is_async else ''}{func_type} {func_name}\"\n \n return {\n 'name': func_name,\n 'type': 'function',\n 'subtype': func_type,\n 'parameters': parameters,\n 'code_snippet': code_snippet,\n 'display_name': display_name,\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'is_async': is_async\n }\n \n def _extract_arrow_function_entity(self, node, depth: int) -> dict:\n \"\"\"Extract arrow function\"\"\"\n parent = node.parent\n if parent and parent.type == \"variable_declarator\":\n name_node = self._find_child_by_type(parent, \"identifier\")\n if name_node:\n func_name = self._get_node_text(name_node)\n parameters = self._extract_parameters(node)\n code_snippet = self._get_node_text(parent)\n \n is_async = \"async\" in code_snippet.split(\"=\")[0] if \"=\" in code_snippet else False\n display_name = f\"{'async ' if is_async else ''}arrow function {func_name}\"\n \n return {\n 'name': func_name,\n 'type': 'function',\n 'subtype': 'arrow_function',\n 'parameters': parameters,\n 'code_snippet': code_snippet,\n 'display_name': display_name,\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'is_async': is_async\n }\n return None\n \n def _extract_method_entity(self, node, depth: int) -> dict:\n \"\"\"Extract method entity (at any depth), qualified by its class.\"\"\"\n name_node = self._find_child_by_type(node, \"property_identifier\")\n if not name_node:\n return None\n\n method_name = self._get_node_text(name_node)\n class_name = self._enclosing_class_name(node)\n qualified = f\"{class_name}.{method_name}\" if class_name else method_name\n parameters = self._extract_parameters(node)\n code_snippet = self._get_node_text(node)\n\n is_async = \"async\" in code_snippet\n is_static = \"static\" in code_snippet\n\n display_name = f\"{'static ' if is_static else ''}{'async ' if is_async else ''}method {qualified}\"\n\n return {\n 'name': qualified,\n 'type': 'function',\n 'subtype': 'method',\n 'class_name': class_name,\n 'parameters': parameters,\n 'code_snippet': code_snippet,\n 'display_name': display_name,\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'is_async': is_async,\n 'is_static': is_static\n }\n\n def _enclosing_class_name(self, node) -> Optional[str]:\n current = node.parent\n while current:\n if current.type in (\"class_declaration\", \"abstract_class_declaration\"):\n name_node = self._find_child_by_type(current, \"type_identifier\") or self._find_child_by_type(current, \"identifier\")\n return self._get_node_text(name_node) if name_node else None\n current = current.parent\n return None\n \n def _extract_class_entity(self, node, class_type: str, depth: int) -> dict:\n name_node = self._find_child_by_type(node, \"type_identifier\") or self._find_child_by_type(node, \"identifier\")\n if not name_node:\n return None\n \n class_name = self._get_node_text(name_node)\n base_classes = self._extract_inheritance(node)\n code_snippet = self._get_node_text(node)\n \n display_name = f\"{class_type} {class_name}\"\n if base_classes:\n display_name += f\" extends {', '.join(base_classes)}\"\n \n return {\n 'name': class_name,\n 'type': 'class',\n 'subtype': class_type,\n 'base_classes': base_classes,\n 'code_snippet': code_snippet,\n 'display_name': display_name,\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1\n }\n \n def _extract_interface_entity(self, node, depth: int) -> dict:\n name_node = self._find_child_by_type(node, \"type_identifier\")\n if not name_node:\n return None\n \n interface_name = self._get_node_text(name_node)\n base_classes = self._extract_inheritance(node)\n code_snippet = self._get_node_text(node)\n \n display_name = f\"interface {interface_name}\"\n if base_classes:\n display_name += f\" extends {', '.join(base_classes)}\"\n \n return {\n 'name': interface_name,\n 'type': 'interface',\n 'subtype': 'interface',\n 'base_classes': base_classes,\n 'code_snippet': code_snippet,\n 'display_name': display_name,\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1\n }\n \n def _extract_type_alias_entity(self, node, depth: int) -> dict:\n name_node = self._find_child_by_type(node, \"type_identifier\")\n if not name_node:\n return None\n \n type_name = self._get_node_text(name_node)\n code_snippet = self._get_node_text(node)\n \n return {\n 'name': type_name,\n 'type': 'type',\n 'subtype': 'type_alias',\n 'code_snippet': code_snippet,\n 'display_name': f\"type {type_name}\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1\n }\n \n def _extract_enum_entity(self, node, depth: int) -> dict:\n name_node = self._find_child_by_type(node, \"identifier\")\n if not name_node:\n return None\n \n enum_name = self._get_node_text(name_node)\n code_snippet = self._get_node_text(node)\n \n return {\n 'name': enum_name,\n 'type': 'enum',\n 'subtype': 'enum',\n 'code_snippet': code_snippet,\n 'display_name': f\"enum {enum_name}\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1\n }\n \n def _extract_variable_entity(self, node, depth: int) -> dict:\n name_node = self._find_child_by_type(node, \"identifier\")\n if not name_node:\n return None\n \n var_name = self._get_node_text(name_node)\n code_snippet = self._get_node_text(node)\n \n has_function = self._find_child_by_type(node, \"arrow_function\") or self._find_child_by_type(node, \"function_expression\")\n \n return {\n 'name': var_name,\n 'type': 'variable',\n 'subtype': 'variable',\n 'code_snippet': code_snippet,\n 'display_name': f\"variable {var_name}\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'has_function': bool(has_function)\n }\n \n def _extract_export_statement_entity(self, node, depth: int) -> dict:\n code_snippet = self._get_node_text(node)\n \n func_decl = self._find_child_by_type(node, \"function_declaration\")\n class_decl = self._find_child_by_type(node, \"class_declaration\")\n interface_decl = self._find_child_by_type(node, \"interface_declaration\")\n lexical_decl = self._find_child_by_type(node, \"lexical_declaration\")\n \n if func_decl:\n name_node = self._find_child_by_type(func_decl, \"identifier\")\n if name_node:\n func_name = self._get_node_text(name_node)\n return {\n 'name': func_name, \n 'type': 'function', \n 'subtype': 'export_function',\n 'code_snippet': code_snippet,\n 'display_name': f\"export function {func_name}\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'parameters': self._extract_parameters(func_decl),\n 'is_export': True\n }\n elif class_decl:\n name_node = self._find_child_by_type(class_decl, \"type_identifier\")\n if name_node:\n class_name = self._get_node_text(name_node)\n return {\n 'name': class_name, \n 'type': 'class', \n 'subtype': 'export_class',\n 'code_snippet': code_snippet,\n 'display_name': f\"export class {class_name}\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'base_classes': self._extract_inheritance(class_decl),\n 'is_export': True\n }\n elif interface_decl:\n name_node = self._find_child_by_type(interface_decl, \"type_identifier\")\n if name_node:\n interface_name = self._get_node_text(name_node)\n return {\n 'name': interface_name, \n 'type': 'interface', \n 'subtype': 'export_interface',\n 'code_snippet': code_snippet,\n 'display_name': f\"export interface {interface_name}\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'base_classes': self._extract_inheritance(interface_decl),\n 'is_export': True\n }\n elif lexical_decl:\n var_declarator = self._find_child_by_type(lexical_decl, \"variable_declarator\")\n if var_declarator:\n name_node = self._find_child_by_type(var_declarator, \"identifier\")\n func_expr = self._find_child_by_type(var_declarator, \"arrow_function\") or self._find_child_by_type(var_declarator, \"function_expression\")\n if name_node and func_expr:\n var_name = self._get_node_text(name_node)\n return {\n 'name': var_name,\n 'type': 'function',\n 'subtype': 'export_arrow_function',\n 'code_snippet': code_snippet,\n 'display_name': f\"export const {var_name}\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'parameters': self._extract_parameters(func_expr),\n 'is_export': True\n }\n \n default_keyword = None\n call_expr = None\n for child in node.children:\n if child.type == \"default\":\n default_keyword = child\n elif child.type == \"call_expression\":\n call_expr = child\n \n if default_keyword and call_expr:\n callee = call_expr.children[0] if call_expr.children else None\n if callee:\n callee_name = self._get_node_text(callee)\n return {\n 'name': callee_name,\n 'type': 'function',\n 'subtype': 'export_default_call',\n 'code_snippet': code_snippet,\n 'display_name': f\"export default {callee_name}(...)\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'parameters': [],\n 'is_export': True\n }\n \n return None \n \n def _extract_lexical_declaration_entity(self, node, depth: int) -> dict:\n \"\"\"Extract lexical declaration entity (const/let).\"\"\"\n # Find the variable declarator\n var_declarator = self._find_child_by_type(node, \"variable_declarator\")\n if not var_declarator:\n return None\n \n name_node = self._find_child_by_type(var_declarator, \"identifier\")\n if not name_node:\n return None\n \n var_name = self._get_node_text(name_node)\n code_snippet = self._get_node_text(node)\n \n # Check declaration type (const/let)\n decl_type = \"const\" if \"const\" in code_snippet else \"let\"\n \n has_function = (self._find_child_by_type(var_declarator, \"arrow_function\") or \n self._find_child_by_type(var_declarator, \"function_expression\"))\n \n return {\n 'name': var_name,\n 'type': 'variable',\n 'subtype': f'{decl_type}_declaration',\n 'code_snippet': code_snippet,\n 'display_name': f\"{decl_type} {var_name}\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'has_function': bool(has_function),\n 'declaration_type': decl_type\n }\n \n def _extract_variable_declaration_entity(self, node, depth: int) -> dict:\n var_declarator = self._find_child_by_type(node, \"variable_declarator\")\n if not var_declarator:\n return None\n \n name_node = self._find_child_by_type(var_declarator, \"identifier\")\n if not name_node:\n return None\n \n var_name = self._get_node_text(name_node)\n code_snippet = self._get_node_text(node)\n \n has_function = (self._find_child_by_type(var_declarator, \"arrow_function\") or \n self._find_child_by_type(var_declarator, \"function_expression\"))\n \n return {\n 'name': var_name,\n 'type': 'variable',\n 'subtype': 'var_declaration',\n 'code_snippet': code_snippet,\n 'display_name': f\"var {var_name}\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'has_function': bool(has_function),\n 'declaration_type': 'var'\n }\n \n def _create_node_from_entity(self, entity_data: dict) -> Optional[Node]:\n \"\"\"Create Node object from entity data.\"\"\"\n try:\n component_type = entity_data['type']\n name = entity_data['name']\n node_type = entity_data.get('subtype', entity_data['type'])\n \n component_id = self._get_component_id(name)\n relative_path = self._get_relative_path()\n \n return Node(\n id=component_id,\n name=name,\n component_type=component_type,\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=entity_data['code_snippet'],\n start_line=entity_data['start_line'],\n end_line=entity_data['end_line'],\n has_docstring=False,\n docstring=\"\",\n parameters=entity_data.get('parameters', []),\n node_type=node_type,\n base_classes=entity_data.get('base_classes'),\n class_name=entity_data.get('class_name'),\n display_name=entity_data['display_name'],\n component_id=component_id,\n language=\"typescript\",\n qualified_name=name,\n )\n except Exception as e:\n logger.debug(f\"Error creating node from entity: {e}\")\n return None\n\n def _should_include_node(self, node: Node) -> bool:\n excluded_names = {\"constructor\", \"__proto__\", \"prototype\"}\n\n if node.component_type == \"variable\":\n return False\n\n return node.name.split(\".\")[-1].lower() not in excluded_names\n\n def _extract_constructor_dependencies(self, class_node, class_name: str) -> None:\n \"\"\"Extract dependencies from constructor parameters.\"\"\"\n try:\n class_body = self._find_child_by_type(class_node, \"class_body\")\n if not class_body:\n return\n \n for child in class_body.children:\n if child.type == \"method_definition\":\n property_name = self._find_child_by_type(child, \"property_identifier\")\n if property_name and self._get_node_text(property_name) == \"constructor\":\n # Extract parameter types\n formal_params = self._find_child_by_type(child, \"formal_parameters\")\n if formal_params:\n self._extract_parameter_dependencies(formal_params, class_name)\n break\n except Exception as e:\n logger.debug(f\"Error extracting constructor dependencies: {e}\")\n\n def _extract_parameter_dependencies(self, formal_params, caller_name: str) -> None:\n try:\n for child in formal_params.children:\n if child.type in [\"required_parameter\", \"optional_parameter\"]:\n type_annotation = self._find_child_by_type(child, \"type_annotation\")\n if type_annotation:\n type_id = self._find_child_by_type(type_annotation, \"type_identifier\")\n if type_id:\n dependency_name = self._get_node_text(type_id)\n if dependency_name and dependency_name != caller_name:\n self._add_relationship(\n caller_name,\n dependency_name,\n child.start_point[0] + 1,\n resolved=dependency_name in self.top_level_nodes,\n )\n except Exception as e:\n logger.debug(f\"Error extracting parameter dependencies: {e}\")\n\n\n def _get_module_path(self) -> str:\n if self.repo_path:\n try:\n rel_path = os.path.relpath(str(self.file_path), self.repo_path)\n except ValueError:\n rel_path = str(self.file_path)\n else:\n rel_path = str(self.file_path)\n \n for ext in ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']:\n if rel_path.endswith(ext):\n rel_path = rel_path[:-len(ext)]\n break\n return rel_path.replace('/', '.').replace('\\\\', '.')\n \n def _get_relative_path(self) -> str:\n if self.repo_path:\n try:\n return os.path.relpath(str(self.file_path), self.repo_path)\n except ValueError:\n return str(self.file_path)\n else:\n return str(self.file_path)\n\n def _get_component_id(self, name: str) -> str:\n return f\"{self._get_relative_path()}::{name}\"\n\n def _extract_inheritance(self, node) -> List[str]:\n \"\"\"Extract inheritance/implementation relationships.\"\"\"\n base_classes = []\n \n extends_clause = self._find_child_by_type(node, \"extends_clause\")\n if extends_clause:\n for child in extends_clause.children:\n if child.type in [\"identifier\", \"type_identifier\"]:\n base_classes.append(self._get_node_text(child))\n \n implements_clause = self._find_child_by_type(node, \"implements_clause\") \n if implements_clause:\n for child in implements_clause.children:\n if child.type in [\"identifier\", \"type_identifier\"]:\n base_classes.append(self._get_node_text(child))\n \n return base_classes\n\n def _extract_parameters(self, node) -> List[str]:\n parameters = []\n params_node = self._find_child_by_type(node, \"formal_parameters\")\n if params_node:\n for child in params_node.children:\n if child.type in [\"identifier\", \"required_parameter\", \"optional_parameter\"]:\n if child.type == \"identifier\":\n parameters.append(self._get_node_text(child))\n else:\n param_name = self._find_child_by_type(child, \"identifier\")\n if param_name:\n parameters.append(self._get_node_text(param_name))\n return parameters\n\n def _extract_all_relationships(self, node, all_entities: dict) -> None:\n self._traverse_for_relationships(node, all_entities, current_top_level=None)\n\n def _traverse_for_relationships(self, node, all_entities: dict, current_top_level: str = None) -> None:\n if current_top_level is None or self._is_new_top_level(node):\n new_top_level = self._get_top_level_name(node)\n if new_top_level and new_top_level in self.top_level_nodes:\n current_top_level = new_top_level\n\n \n if current_top_level:\n if node.type == \"call_expression\":\n self._extract_call_relationship(node, current_top_level, all_entities)\n elif node.type == \"new_expression\":\n self._extract_new_relationship(node, current_top_level, all_entities)\n \n elif node.type == \"type_annotation\":\n self._extract_type_relationship(node, current_top_level, all_entities)\n elif node.type == \"type_arguments\":\n self._extract_type_arguments_relationship(node, current_top_level, all_entities)\n \n elif node.type == \"extends_clause\":\n self._extract_inheritance_relationship(node, current_top_level, all_entities)\n elif node.type == \"implements_clause\":\n self._extract_inheritance_relationship(node, current_top_level, all_entities)\n\n for child in node.children:\n self._traverse_for_relationships(child, all_entities, current_top_level)\n \n def _is_new_top_level(self, node) -> bool:\n return node.type in [\n \"function_declaration\", \"generator_function_declaration\",\n \"class_declaration\", \"abstract_class_declaration\",\n \"interface_declaration\", \"type_alias_declaration\", \"enum_declaration\",\n \"export_statement\", \"method_definition\"\n ]\n\n def _get_top_level_name(self, node) -> Optional[str]:\n result = None\n if node.type == \"method_definition\":\n name_node = self._find_child_by_type(node, \"property_identifier\")\n if name_node:\n method_name = self._get_node_text(name_node)\n class_name = self._enclosing_class_name(node)\n result = f\"{class_name}.{method_name}\" if class_name else method_name\n elif node.type in [\"function_declaration\", \"generator_function_declaration\"]:\n name_node = self._find_child_by_type(node, \"identifier\")\n result = self._get_node_text(name_node) if name_node else None\n elif node.type in [\"class_declaration\", \"abstract_class_declaration\", \"interface_declaration\", \"type_alias_declaration\"]:\n name_node = self._find_child_by_type(node, \"type_identifier\") or self._find_child_by_type(node, \"identifier\")\n result = self._get_node_text(name_node) if name_node else None\n elif node.type == \"enum_declaration\":\n name_node = self._find_child_by_type(node, \"identifier\")\n result = self._get_node_text(name_node) if name_node else None\n elif node.type == \"export_statement\":\n if self._find_child_by_type(node, \"default\"):\n call_expr = self._find_child_by_type(node, \"call_expression\")\n if call_expr:\n identifier = self._find_child_by_type(call_expr, \"identifier\")\n if identifier:\n return self._get_node_text(identifier)\n return \"default_export\"\n else:\n func_decl = self._find_child_by_type(node, \"function_declaration\")\n class_decl = self._find_child_by_type(node, \"class_declaration\")\n lexical_decl = self._find_child_by_type(node, \"lexical_declaration\")\n \n if func_decl:\n name_node = self._find_child_by_type(func_decl, \"identifier\")\n if name_node:\n result = self._get_node_text(name_node) \n elif class_decl:\n name_node = self._find_child_by_type(class_decl, \"type_identifier\")\n if name_node:\n result = self._get_node_text(name_node) \n elif lexical_decl:\n var_declarator = self._find_child_by_type(lexical_decl, \"variable_declarator\")\n if var_declarator:\n name_node = self._find_child_by_type(var_declarator, \"identifier\")\n if name_node:\n result = self._get_node_text(name_node) \n else:\n result = \"unnamed_export\"\n elif node.type in [\"lexical_declaration\", \"variable_declaration\"]:\n # const/let/var declarations\n var_declarator = self._find_child_by_type(node, \"variable_declarator\")\n if var_declarator:\n name_node = self._find_child_by_type(var_declarator, \"identifier\")\n result = self._get_node_text(name_node) if name_node else None\n else:\n result = None\n else:\n result = None\n \n return result\n\n def _extract_call_relationship(self, node, caller_name: str, all_entities: dict) -> None:\n \"\"\"Emit at most one relationship per call expression.\n\n Plain identifier calls resolve against same-file components; member\n calls are resolved receiver-first (this/super against the enclosing\n class, class names and typed variables against their methods).\n Unresolved callees are emitted as bare logical names for the global\n resolver, never file-prefixed.\n \"\"\"\n try:\n call_line = node.start_point[0] + 1\n func_node = node.children[0] if node.children else None\n if func_node is None:\n return\n\n if func_node.type == \"identifier\":\n name = self._get_node_text(func_node)\n if not name:\n return\n if name in self.top_level_nodes:\n self._add_relationship(caller_name, name, call_line, resolved=True)\n elif name in all_entities and not self._is_actually_top_level(all_entities[name]):\n logger.debug(f\"Ignoring nested call: {caller_name} -> {name} (local/nested)\")\n else:\n self._add_relationship(caller_name, name, call_line, resolved=False)\n return\n\n if func_node.type != \"member_expression\":\n return\n\n parts = self._member_call_parts(func_node)\n if parts is None:\n return\n receiver_kind, receiver_text, tail = parts\n if not tail:\n return\n\n if receiver_kind in (\"this\", \"super\"):\n self._emit_instance_method_call(caller_name, tail, call_line, prefer_bases=(receiver_kind == \"super\"))\n elif receiver_kind == \"identifier\":\n self._emit_receiver_method_call(node, caller_name, receiver_text, tail, call_line)\n elif receiver_kind == \"chain\":\n self._add_relationship(caller_name, f\"{receiver_text}.{tail}\", call_line, resolved=False)\n else:\n # Composite or literal receiver: a builtin-prototype method on\n # an unknowable receiver can never resolve to a project\n # component; anything else stays an honest bare name.\n if receiver_kind == \"composite\" and tail not in JS_TS_PROTOTYPE_METHODS:\n self._add_relationship(caller_name, tail, call_line, resolved=False)\n\n except Exception as e:\n logger.debug(f\"Error extracting call relationship: {e}\")\n\n def _member_call_parts(self, member_node) -> Optional[Tuple[str, Optional[str], str]]:\n \"\"\"Split a member expression callee into (receiver_kind, receiver_text, method_tail).\n\n receiver_kind is one of: \"this\", \"super\", \"identifier\", \"chain\" (a\n pure dotted identifier chain), \"composite\" (call result, subscript,\n parenthesized, new expression), or \"literal\".\n \"\"\"\n property_node = member_node.child_by_field_name(\"property\") or self._find_child_by_type(member_node, \"property_identifier\")\n tail = self._get_node_text(property_node) if property_node else \"\"\n obj = member_node.child_by_field_name(\"object\")\n if obj is None and member_node.children:\n obj = member_node.children[0]\n if obj is None:\n return None\n\n if obj.type == \"this\":\n return (\"this\", None, tail)\n if obj.type == \"super\":\n return (\"super\", None, tail)\n if obj.type == \"identifier\":\n return (\"identifier\", self._get_node_text(obj), tail)\n if obj.type == \"member_expression\":\n chain = self._identifier_chain(obj)\n if chain:\n return (\"chain\", chain, tail)\n return (\"composite\", None, tail)\n if obj.type in (\"array\", \"string\", \"template_string\", \"number\", \"object\", \"regex\", \"true\", \"false\"):\n return (\"literal\", None, tail)\n return (\"composite\", None, tail)\n\n def _identifier_chain(self, node) -> Optional[str]:\n \"\"\"Flatten a member expression into dotted text when it is a pure\n identifier chain; None when any link is computed.\"\"\"\n parts = []\n current = node\n while current.type == \"member_expression\":\n property_node = current.child_by_field_name(\"property\")\n if property_node is None or property_node.type != \"property_identifier\":\n return None\n parts.append(self._get_node_text(property_node))\n current = current.child_by_field_name(\"object\")\n if current is None:\n return None\n if current.type != \"identifier\":\n return None\n parts.append(self._get_node_text(current))\n return \".\".join(reversed(parts))\n\n def _emit_instance_method_call(self, caller_name: str, tail: str, call_line: int, prefer_bases: bool = False) -> None:\n \"\"\"Resolve this.m()/super.m() against the enclosing class and its bases.\"\"\"\n class_name = caller_name.split(\".\")[0] if caller_name else None\n if not class_name:\n self._add_relationship(caller_name, tail, call_line, resolved=False)\n return\n\n candidates = [] if prefer_bases else [class_name]\n class_node = self.top_level_nodes.get(class_name)\n if class_node and class_node.base_classes:\n candidates.extend(class_node.base_classes)\n\n for candidate in candidates:\n if f\"{candidate}.{tail}\" in self.top_level_nodes:\n self._add_relationship(caller_name, f\"{candidate}.{tail}\", call_line, resolved=True)\n return\n\n # Not defined in this file: emit the qualified form for the global\n # resolver (an inherited method defined in another file).\n target = candidates[0] if candidates else class_name\n self._add_relationship(caller_name, f\"{target}.{tail}\", call_line, resolved=False)\n\n def _emit_receiver_method_call(self, call_node, caller_name: str, receiver: str, tail: str, call_line: int) -> None:\n \"\"\"Resolve recv.m() where recv is a simple identifier.\"\"\"\n if not receiver:\n return\n # Static call or enum/namespace access on a known component.\n if receiver in self.top_level_nodes:\n if f\"{receiver}.{tail}\" in self.top_level_nodes:\n self._add_relationship(caller_name, f\"{receiver}.{tail}\", call_line, resolved=True)\n else:\n self._add_relationship(caller_name, f\"{receiver}.{tail}\", call_line, resolved=False)\n return\n\n inferred = self._infer_identifier_type(call_node, receiver)\n if inferred:\n if f\"{inferred}.{tail}\" in self.top_level_nodes:\n self._add_relationship(caller_name, f\"{inferred}.{tail}\", call_line, resolved=True)\n else:\n self._add_relationship(caller_name, f\"{inferred}.{tail}\", call_line, resolved=False)\n return\n\n self._add_relationship(caller_name, f\"{receiver}.{tail}\", call_line, resolved=False)\n\n def _infer_identifier_type(self, call_node, identifier: str) -> Optional[str]:\n \"\"\"Find the type of a local identifier from `new X()` initializers or\n TS type annotations within the enclosing function/method/class.\"\"\"\n scope = call_node.parent\n scopes = []\n while scope:\n if scope.type in (\n \"method_definition\", \"function_declaration\",\n \"generator_function_declaration\", \"arrow_function\",\n \"function_expression\", \"class_declaration\",\n \"abstract_class_declaration\", \"program\",\n ):\n scopes.append(scope)\n scope = scope.parent\n\n for scope_node in scopes:\n found = self._find_declared_type(scope_node, identifier)\n if found:\n return found\n return None\n\n def _find_declared_type(self, scope_node, identifier: str) -> Optional[str]:\n stack = [scope_node]\n while stack:\n current = stack.pop()\n if current.type == \"variable_declarator\":\n name_node = self._find_child_by_type(current, \"identifier\")\n if name_node is not None and self._get_node_text(name_node) == identifier:\n new_expr = self._find_child_by_type(current, \"new_expression\")\n if new_expr is not None:\n for child in new_expr.children:\n if child.type in (\"identifier\", \"type_identifier\"):\n return self._get_node_text(child)\n annotation = self._find_child_by_type(current, \"type_annotation\")\n if annotation is not None:\n type_id = self._find_child_by_type(annotation, \"type_identifier\")\n if type_id is not None:\n return self._get_node_text(type_id)\n elif current.type in (\"required_parameter\", \"optional_parameter\"):\n name_node = self._find_child_by_type(current, \"identifier\")\n if name_node is not None and self._get_node_text(name_node) == identifier:\n annotation = self._find_child_by_type(current, \"type_annotation\")\n if annotation is not None:\n type_id = self._find_child_by_type(annotation, \"type_identifier\")\n if type_id is not None:\n return self._get_node_text(type_id)\n stack.extend(current.children)\n return None\n\n def _extract_new_relationship(self, node, caller_name: str, all_entities: dict) -> None:\n try:\n call_line = node.start_point[0] + 1\n if node.children:\n constructor_node = None\n for child in node.children:\n if child.type not in ['new', 'type_arguments', 'arguments']:\n constructor_node = child\n break\n\n if constructor_node:\n constructor_name = self._get_node_text(constructor_node)\n\n if constructor_name:\n resolved = constructor_name in self.top_level_nodes\n self._add_relationship(caller_name, constructor_name, call_line, resolved=resolved)\n\n except Exception as e:\n logger.debug(f\"Error extracting new relationship: {e}\")\n\n def _extract_type_relationship(self, node, caller_name: str, all_entities: dict) -> None:\n try:\n type_identifiers = []\n self._find_all_type_identifiers(node, type_identifiers)\n \n call_line = node.start_point[0] + 1\n \n for type_node in type_identifiers:\n type_name = self._get_node_text(type_node)\n \n if self._is_builtin_type(type_name):\n continue\n \n if type_name in all_entities:\n target_name = self._resolve_to_top_level(type_name, all_entities)\n if target_name and target_name in self.top_level_nodes:\n self._add_relationship(caller_name, target_name, call_line, resolved=True)\n else:\n self._add_relationship(caller_name, type_name, call_line, resolved=False)\n \n except Exception as e:\n logger.debug(f\"Error extracting type relationship: {e}\")\n \n def _find_all_type_identifiers(self, node, type_identifiers: list) -> None:\n if node.type == \"type_identifier\":\n type_identifiers.append(node)\n \n for child in node.children:\n self._find_all_type_identifiers(child, type_identifiers)\n \n def _extract_type_arguments_relationship(self, node, caller_name: str, all_entities: dict) -> None:\n try:\n for child in node.children:\n if child.type == \"type_identifier\":\n type_name = self._get_node_text(child)\n if type_name in all_entities:\n target_name = self._resolve_to_top_level(type_name, all_entities)\n if target_name and target_name in self.top_level_nodes:\n call_line = node.start_point[0] + 1\n self._add_relationship(caller_name, target_name, call_line, resolved=True)\n except Exception as e:\n logger.debug(f\"Error extracting type arguments relationship: {e}\")\n \n def _extract_inheritance_relationship(self, node, caller_name: str, all_entities: dict) -> None:\n \"\"\"Extract inheritance/implementation relationships\"\"\"\n try:\n for child in node.children:\n if child.type in [\"identifier\", \"type_identifier\"]:\n base_name = self._get_node_text(child)\n if base_name in all_entities:\n target_name = self._resolve_to_top_level(base_name, all_entities)\n if target_name and target_name in self.top_level_nodes:\n call_line = node.start_point[0] + 1\n self._add_relationship(caller_name, target_name, call_line, resolved=True)\n else:\n self._add_relationship(caller_name, base_name, call_line=node.start_point[0] + 1, resolved=False)\n except Exception as e:\n logger.debug(f\"Error extracting inheritance relationship: {e}\")\n\n def _resolve_to_top_level(self, entity_name: str, all_entities: dict) -> Optional[str]:\n if entity_name in self.top_level_nodes:\n return entity_name\n \n entity_data = all_entities.get(entity_name)\n if entity_data and entity_data.get('depth', 0) > 2:\n return None\n \n return entity_name if entity_name in self.top_level_nodes else None\n\n def _add_relationship(self, caller_name: str, callee_name: str, call_line: int, resolved: bool = False) -> None:\n \"\"\"Record one relationship. Resolved callees are component ids in this\n file; unresolved callees stay bare logical names so they never look\n like project components they are not.\"\"\"\n caller_id = f\"{self._get_relative_path()}::{caller_name}\"\n callee_id = self._get_component_id(callee_name) if resolved else callee_name\n\n key = (caller_id, callee_id)\n if key in self.seen_relationships:\n return\n self.seen_relationships.add(key)\n\n relationship = CallRelationship(\n caller=caller_id,\n callee=callee_id,\n call_line=call_line,\n is_resolved=resolved,\n )\n self.call_relationships.append(relationship)\n\n def _is_builtin_type(self, name: str) -> bool:\n \"\"\"Check if type name is a TypeScript/JavaScript built-in type.\"\"\"\n builtin_types = {\n # Primitive types\n \"string\", \"number\", \"boolean\", \"object\", \"undefined\", \"null\", \"void\", \"never\", \"any\", \"unknown\"\n }\n return name in builtin_types\n\n def _is_builtin_function(self, name: str) -> bool:\n builtins = {}\n return name in builtins\n\n def _find_child_by_type(self, node, node_type: str):\n for child in node.children:\n if child.type == node_type:\n return child\n return None\n\n def _get_node_text(self, node) -> str:\n start_byte = node.start_byte\n end_byte = node.end_byte\n return self.content.encode(\"utf8\")[start_byte:end_byte].decode(\"utf8\")", - "start_line": 20, - "end_line": 1118, - "has_docstring": false, - "docstring": "", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class TreeSitterTSAnalyzer", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer.__init__": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer.__init__", - "name": "TreeSitterTSAnalyzer.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": " def __init__(self, file_path: str, content: str, repo_path: str = None):\n self.file_path = Path(file_path)\n self.content = content\n self.repo_path = repo_path or \"\"\n self.nodes: List[Node] = []\n self.call_relationships: List[CallRelationship] = []\n self.seen_relationships: Set[Tuple[str, str]] = set()\n\n self.top_level_nodes = {}\n\n try:\n language_capsule = tree_sitter_typescript.language_typescript()\n self.ts_language = Language(language_capsule)\n self.parser = Parser(self.ts_language)\n\n except Exception as e:\n logger.error(f\"Failed to initialize TypeScript parser: {e}\")\n logger.error(f\"Traceback: {traceback.format_exc()}\")\n self.parser = None\n self.ts_language = None", - "start_line": 22, - "end_line": 41, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "file_path", - "content", - "repo_path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer.__init__", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer.analyze": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer.analyze", - "name": "TreeSitterTSAnalyzer.analyze", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_all_entities", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._filter_top_level_declarations", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_all_relationships", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": " def analyze(self) -> None:\n if self.parser is None:\n logger.debug(f\"Skipping {self.file_path} - parser initialization failed\")\n return\n\n try:\n tree = self.parser.parse(bytes(self.content, \"utf8\"))\n root_node = tree.root_node\n\n logger.debug(f\"Parsed AST with root node type: {root_node.type}\")\n\n all_entities = {} \n self._extract_all_entities(root_node, all_entities)\n \n self._filter_top_level_declarations(all_entities)\n \n self._extract_all_relationships(root_node, all_entities)\n\n except Exception as e:\n logger.error(f\"Error analyzing TypeScript file {self.file_path}: {e}\", exc_info=True)", - "start_line": 43, - "end_line": 62, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer.analyze", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer.analyze", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_all_entities": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_all_entities", - "name": "TreeSitterTSAnalyzer._extract_all_entities", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_enum_entity", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_all_entities", - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_function_entity", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_export_statement_entity", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_variable_entity", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_class_entity", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_arrow_function_entity", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_variable_declaration_entity", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_interface_entity", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_parent_context", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_ambient_declaration_entity", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_type_alias_entity", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_lexical_declaration_entity", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_method_entity" - ], - "source_code": " def _extract_all_entities(self, node, all_entities: dict, depth=0) -> None:\n entity = None\n entity_name = None\n \n if node.type == \"function_declaration\":\n entity = self._extract_function_entity(node, \"function\", depth)\n elif node.type == \"generator_function_declaration\":\n entity = self._extract_function_entity(node, \"generator_function\", depth)\n elif node.type == \"arrow_function\":\n entity = self._extract_arrow_function_entity(node, depth)\n elif node.type == \"method_definition\":\n entity = self._extract_method_entity(node, depth)\n elif node.type == \"class_declaration\":\n entity = self._extract_class_entity(node, \"class\", depth)\n elif node.type == \"abstract_class_declaration\":\n entity = self._extract_class_entity(node, \"abstract_class\", depth)\n elif node.type == \"interface_declaration\":\n entity = self._extract_interface_entity(node, depth)\n elif node.type == \"type_alias_declaration\":\n entity = self._extract_type_alias_entity(node, depth)\n elif node.type == \"enum_declaration\":\n entity = self._extract_enum_entity(node, depth)\n elif node.type == \"variable_declarator\":\n entity = self._extract_variable_entity(node, depth)\n elif node.type == \"export_statement\":\n entity = self._extract_export_statement_entity(node, depth)\n elif node.type == \"lexical_declaration\":\n entity = self._extract_lexical_declaration_entity(node, depth)\n elif node.type == \"variable_declaration\":\n entity = self._extract_variable_declaration_entity(node, depth)\n elif node.type == \"ambient_declaration\":\n entity = self._extract_ambient_declaration_entity(node, depth)\n \n if entity and entity.get('name'):\n entity_name = entity['name']\n entity['depth'] = depth \n entity['node'] = node \n entity['parent_context'] = self._get_parent_context(node) \n all_entities[entity_name] = entity\n \n for child in node.children:\n self._extract_all_entities(child, all_entities, depth + 1)", - "start_line": 64, - "end_line": 105, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "all_entities", - "depth" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_all_entities", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_all_entities", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._filter_top_level_declarations": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._filter_top_level_declarations", - "name": "TreeSitterTSAnalyzer._filter_top_level_declarations", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_actually_top_level", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_constructor_dependencies", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._create_node_from_entity", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._should_include_node" - ], - "source_code": " def _filter_top_level_declarations(self, all_entities: dict) -> None:\n for entity_name, entity_data in all_entities.items():\n if self._is_actually_top_level(entity_data):\n node_obj = self._create_node_from_entity(entity_data)\n if node_obj and self._should_include_node(node_obj):\n self.nodes.append(node_obj)\n self.top_level_nodes[entity_name] = node_obj\n \n if entity_data[\"type\"] in [\"class_declaration\", \"abstract_class_declaration\"]:\n self._extract_constructor_dependencies(entity_data[\"node\"], entity_name)", - "start_line": 107, - "end_line": 116, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "all_entities" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._filter_top_level_declarations", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._filter_top_level_declarations", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_actually_top_level": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_actually_top_level", - "name": "TreeSitterTSAnalyzer._is_actually_top_level", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_inside_function_body" - ], - "source_code": " def _is_actually_top_level(self, entity_data: dict) -> bool:\n node = entity_data.get('node')\n if not node or not node.parent:\n return True\n \n entity_type = entity_data.get('type')\n if self._is_inside_function_body(node):\n return False\n \n current = node.parent\n while current:\n parent_type = current.type\n \n if parent_type == \"program\":\n return True\n \n if parent_type == \"export_statement\":\n return True\n \n if parent_type == \"ambient_declaration\":\n return True\n \n if parent_type == \"module\":\n return True\n \n if parent_type == \"statement_block\":\n grandparent = current.parent\n if grandparent and grandparent.type in [\"module\", \"ambient_declaration\"]:\n return True\n \n current = current.parent\n \n return False", - "start_line": 118, - "end_line": 150, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "entity_data" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._is_actually_top_level", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_actually_top_level", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_inside_function_body": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_inside_function_body", - "name": "TreeSitterTSAnalyzer._is_inside_function_body", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [], - "source_code": " def _is_inside_function_body(self, node) -> bool:\n current = node.parent\n while current:\n if current.type == \"statement_block\":\n if current.parent and current.parent.type in [\n \"function_declaration\", \"generator_function_declaration\", \n \"arrow_function\", \"function_expression\", \"method_definition\"\n ]:\n return True\n current = current.parent\n return False", - "start_line": 152, - "end_line": 162, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._is_inside_function_body", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_inside_function_body", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_ambient_declaration_entity": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_ambient_declaration_entity", - "name": "TreeSitterTSAnalyzer._extract_ambient_declaration_entity", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text" - ], - "source_code": " def _extract_ambient_declaration_entity(self, node, depth: int) -> dict:\n name = \"\"\n for child in node.children:\n if child.type == \"module\":\n for grandchild in child.children:\n if grandchild.type == \"string\":\n name = self._get_node_text(grandchild).strip(\"'\\\"\")\n break\n break\n elif child.type == \"namespace\":\n name = self._get_node_text(child.children[1]) if len(child.children) > 1 else \"unknown_namespace\"\n break\n \n return {\n 'name': f\"{name}\",\n 'type': 'ambient_declaration',\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'parameters': [],\n 'return_type': None,\n 'modifiers': ['ambient'],\n 'complexity': 1\n }", - "start_line": 164, - "end_line": 186, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "depth" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_ambient_declaration_entity", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_ambient_declaration_entity", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_parent_context": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_parent_context", - "name": "TreeSitterTSAnalyzer._get_parent_context", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [], - "source_code": " def _get_parent_context(self, node) -> str:\n \"\"\"Get the parent context of a node for better top-level detection\"\"\"\n if not node.parent:\n return \"root\"\n \n parent_type = node.parent.type\n if parent_type in [\"program\", \"source_file\"]:\n return \"program\"\n elif parent_type == \"export_statement\":\n return \"export\"\n elif parent_type == \"ambient_declaration\":\n return \"ambient\"\n elif parent_type == \"module\":\n return \"module\"\n elif parent_type == \"statement_block\":\n if node.parent.parent and node.parent.parent.type in [\"module\", \"ambient_declaration\"]:\n return \"module_block\"\n return \"statement_block\"", - "start_line": 188, - "end_line": 205, - "has_docstring": true, - "docstring": "Get the parent context of a node for better top-level detection", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._get_parent_context", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_parent_context", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_function_entity": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_function_entity", - "name": "TreeSitterTSAnalyzer._extract_function_entity", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_parameters", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type" - ], - "source_code": " def _extract_function_entity(self, node, func_type: str, depth: int) -> dict:\n name_node = self._find_child_by_type(node, \"identifier\")\n if not name_node:\n return None\n \n func_name = self._get_node_text(name_node)\n parameters = self._extract_parameters(node)\n code_snippet = self._get_node_text(node)\n \n is_async = \"async\" in code_snippet.split(\"function\")[0] if \"function\" in code_snippet else False\n display_name = f\"{'async ' if is_async else ''}{func_type} {func_name}\"\n \n return {\n 'name': func_name,\n 'type': 'function',\n 'subtype': func_type,\n 'parameters': parameters,\n 'code_snippet': code_snippet,\n 'display_name': display_name,\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'is_async': is_async\n }", - "start_line": 206, - "end_line": 228, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "func_type", - "depth" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_function_entity", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_function_entity", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_arrow_function_entity": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_arrow_function_entity", - "name": "TreeSitterTSAnalyzer._extract_arrow_function_entity", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_parameters", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type" - ], - "source_code": " def _extract_arrow_function_entity(self, node, depth: int) -> dict:\n \"\"\"Extract arrow function\"\"\"\n parent = node.parent\n if parent and parent.type == \"variable_declarator\":\n name_node = self._find_child_by_type(parent, \"identifier\")\n if name_node:\n func_name = self._get_node_text(name_node)\n parameters = self._extract_parameters(node)\n code_snippet = self._get_node_text(parent)\n \n is_async = \"async\" in code_snippet.split(\"=\")[0] if \"=\" in code_snippet else False\n display_name = f\"{'async ' if is_async else ''}arrow function {func_name}\"\n \n return {\n 'name': func_name,\n 'type': 'function',\n 'subtype': 'arrow_function',\n 'parameters': parameters,\n 'code_snippet': code_snippet,\n 'display_name': display_name,\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'is_async': is_async\n }\n return None", - "start_line": 230, - "end_line": 254, - "has_docstring": true, - "docstring": "Extract arrow function", - "parameters": [ - "self", - "node", - "depth" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_arrow_function_entity", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_arrow_function_entity", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_method_entity": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_method_entity", - "name": "TreeSitterTSAnalyzer._extract_method_entity", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_parameters", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._enclosing_class_name" - ], - "source_code": " def _extract_method_entity(self, node, depth: int) -> dict:\n \"\"\"Extract method entity (at any depth), qualified by its class.\"\"\"\n name_node = self._find_child_by_type(node, \"property_identifier\")\n if not name_node:\n return None\n\n method_name = self._get_node_text(name_node)\n class_name = self._enclosing_class_name(node)\n qualified = f\"{class_name}.{method_name}\" if class_name else method_name\n parameters = self._extract_parameters(node)\n code_snippet = self._get_node_text(node)\n\n is_async = \"async\" in code_snippet\n is_static = \"static\" in code_snippet\n\n display_name = f\"{'static ' if is_static else ''}{'async ' if is_async else ''}method {qualified}\"\n\n return {\n 'name': qualified,\n 'type': 'function',\n 'subtype': 'method',\n 'class_name': class_name,\n 'parameters': parameters,\n 'code_snippet': code_snippet,\n 'display_name': display_name,\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'is_async': is_async,\n 'is_static': is_static\n }", - "start_line": 256, - "end_line": 285, - "has_docstring": true, - "docstring": "Extract method entity (at any depth), qualified by its class.", - "parameters": [ - "self", - "node", - "depth" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_method_entity", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_method_entity", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._enclosing_class_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._enclosing_class_name", - "name": "TreeSitterTSAnalyzer._enclosing_class_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type" - ], - "source_code": " def _enclosing_class_name(self, node) -> Optional[str]:\n current = node.parent\n while current:\n if current.type in (\"class_declaration\", \"abstract_class_declaration\"):\n name_node = self._find_child_by_type(current, \"type_identifier\") or self._find_child_by_type(current, \"identifier\")\n return self._get_node_text(name_node) if name_node else None\n current = current.parent\n return None", - "start_line": 287, - "end_line": 294, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._enclosing_class_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._enclosing_class_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_class_entity": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_class_entity", - "name": "TreeSitterTSAnalyzer._extract_class_entity", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_inheritance" - ], - "source_code": " def _extract_class_entity(self, node, class_type: str, depth: int) -> dict:\n name_node = self._find_child_by_type(node, \"type_identifier\") or self._find_child_by_type(node, \"identifier\")\n if not name_node:\n return None\n \n class_name = self._get_node_text(name_node)\n base_classes = self._extract_inheritance(node)\n code_snippet = self._get_node_text(node)\n \n display_name = f\"{class_type} {class_name}\"\n if base_classes:\n display_name += f\" extends {', '.join(base_classes)}\"\n \n return {\n 'name': class_name,\n 'type': 'class',\n 'subtype': class_type,\n 'base_classes': base_classes,\n 'code_snippet': code_snippet,\n 'display_name': display_name,\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1\n }", - "start_line": 296, - "end_line": 318, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "class_type", - "depth" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_class_entity", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_class_entity", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_interface_entity": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_interface_entity", - "name": "TreeSitterTSAnalyzer._extract_interface_entity", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_inheritance" - ], - "source_code": " def _extract_interface_entity(self, node, depth: int) -> dict:\n name_node = self._find_child_by_type(node, \"type_identifier\")\n if not name_node:\n return None\n \n interface_name = self._get_node_text(name_node)\n base_classes = self._extract_inheritance(node)\n code_snippet = self._get_node_text(node)\n \n display_name = f\"interface {interface_name}\"\n if base_classes:\n display_name += f\" extends {', '.join(base_classes)}\"\n \n return {\n 'name': interface_name,\n 'type': 'interface',\n 'subtype': 'interface',\n 'base_classes': base_classes,\n 'code_snippet': code_snippet,\n 'display_name': display_name,\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1\n }", - "start_line": 320, - "end_line": 342, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "depth" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_interface_entity", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_interface_entity", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_type_alias_entity": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_type_alias_entity", - "name": "TreeSitterTSAnalyzer._extract_type_alias_entity", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type" - ], - "source_code": " def _extract_type_alias_entity(self, node, depth: int) -> dict:\n name_node = self._find_child_by_type(node, \"type_identifier\")\n if not name_node:\n return None\n \n type_name = self._get_node_text(name_node)\n code_snippet = self._get_node_text(node)\n \n return {\n 'name': type_name,\n 'type': 'type',\n 'subtype': 'type_alias',\n 'code_snippet': code_snippet,\n 'display_name': f\"type {type_name}\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1\n }", - "start_line": 344, - "end_line": 360, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "depth" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_type_alias_entity", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_type_alias_entity", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_enum_entity": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_enum_entity", - "name": "TreeSitterTSAnalyzer._extract_enum_entity", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type" - ], - "source_code": " def _extract_enum_entity(self, node, depth: int) -> dict:\n name_node = self._find_child_by_type(node, \"identifier\")\n if not name_node:\n return None\n \n enum_name = self._get_node_text(name_node)\n code_snippet = self._get_node_text(node)\n \n return {\n 'name': enum_name,\n 'type': 'enum',\n 'subtype': 'enum',\n 'code_snippet': code_snippet,\n 'display_name': f\"enum {enum_name}\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1\n }", - "start_line": 362, - "end_line": 378, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "depth" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_enum_entity", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_enum_entity", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_variable_entity": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_variable_entity", - "name": "TreeSitterTSAnalyzer._extract_variable_entity", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type" - ], - "source_code": " def _extract_variable_entity(self, node, depth: int) -> dict:\n name_node = self._find_child_by_type(node, \"identifier\")\n if not name_node:\n return None\n \n var_name = self._get_node_text(name_node)\n code_snippet = self._get_node_text(node)\n \n has_function = self._find_child_by_type(node, \"arrow_function\") or self._find_child_by_type(node, \"function_expression\")\n \n return {\n 'name': var_name,\n 'type': 'variable',\n 'subtype': 'variable',\n 'code_snippet': code_snippet,\n 'display_name': f\"variable {var_name}\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'has_function': bool(has_function)\n }", - "start_line": 380, - "end_line": 399, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "depth" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_variable_entity", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_variable_entity", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_export_statement_entity": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_export_statement_entity", - "name": "TreeSitterTSAnalyzer._extract_export_statement_entity", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_parameters", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_inheritance" - ], - "source_code": " def _extract_export_statement_entity(self, node, depth: int) -> dict:\n code_snippet = self._get_node_text(node)\n \n func_decl = self._find_child_by_type(node, \"function_declaration\")\n class_decl = self._find_child_by_type(node, \"class_declaration\")\n interface_decl = self._find_child_by_type(node, \"interface_declaration\")\n lexical_decl = self._find_child_by_type(node, \"lexical_declaration\")\n \n if func_decl:\n name_node = self._find_child_by_type(func_decl, \"identifier\")\n if name_node:\n func_name = self._get_node_text(name_node)\n return {\n 'name': func_name, \n 'type': 'function', \n 'subtype': 'export_function',\n 'code_snippet': code_snippet,\n 'display_name': f\"export function {func_name}\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'parameters': self._extract_parameters(func_decl),\n 'is_export': True\n }\n elif class_decl:\n name_node = self._find_child_by_type(class_decl, \"type_identifier\")\n if name_node:\n class_name = self._get_node_text(name_node)\n return {\n 'name': class_name, \n 'type': 'class', \n 'subtype': 'export_class',\n 'code_snippet': code_snippet,\n 'display_name': f\"export class {class_name}\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'base_classes': self._extract_inheritance(class_decl),\n 'is_export': True\n }\n elif interface_decl:\n name_node = self._find_child_by_type(interface_decl, \"type_identifier\")\n if name_node:\n interface_name = self._get_node_text(name_node)\n return {\n 'name': interface_name, \n 'type': 'interface', \n 'subtype': 'export_interface',\n 'code_snippet': code_snippet,\n 'display_name': f\"export interface {interface_name}\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'base_classes': self._extract_inheritance(interface_decl),\n 'is_export': True\n }\n elif lexical_decl:\n var_declarator = self._find_child_by_type(lexical_decl, \"variable_declarator\")\n if var_declarator:\n name_node = self._find_child_by_type(var_declarator, \"identifier\")\n func_expr = self._find_child_by_type(var_declarator, \"arrow_function\") or self._find_child_by_type(var_declarator, \"function_expression\")\n if name_node and func_expr:\n var_name = self._get_node_text(name_node)\n return {\n 'name': var_name,\n 'type': 'function',\n 'subtype': 'export_arrow_function',\n 'code_snippet': code_snippet,\n 'display_name': f\"export const {var_name}\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'parameters': self._extract_parameters(func_expr),\n 'is_export': True\n }\n \n default_keyword = None\n call_expr = None\n for child in node.children:\n if child.type == \"default\":\n default_keyword = child\n elif child.type == \"call_expression\":\n call_expr = child\n \n if default_keyword and call_expr:\n callee = call_expr.children[0] if call_expr.children else None\n if callee:\n callee_name = self._get_node_text(callee)\n return {\n 'name': callee_name,\n 'type': 'function',\n 'subtype': 'export_default_call',\n 'code_snippet': code_snippet,\n 'display_name': f\"export default {callee_name}(...)\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'parameters': [],\n 'is_export': True\n }\n \n return None ", - "start_line": 401, - "end_line": 497, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "depth" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_export_statement_entity", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_export_statement_entity", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_lexical_declaration_entity": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_lexical_declaration_entity", - "name": "TreeSitterTSAnalyzer._extract_lexical_declaration_entity", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type" - ], - "source_code": " def _extract_lexical_declaration_entity(self, node, depth: int) -> dict:\n \"\"\"Extract lexical declaration entity (const/let).\"\"\"\n # Find the variable declarator\n var_declarator = self._find_child_by_type(node, \"variable_declarator\")\n if not var_declarator:\n return None\n \n name_node = self._find_child_by_type(var_declarator, \"identifier\")\n if not name_node:\n return None\n \n var_name = self._get_node_text(name_node)\n code_snippet = self._get_node_text(node)\n \n # Check declaration type (const/let)\n decl_type = \"const\" if \"const\" in code_snippet else \"let\"\n \n has_function = (self._find_child_by_type(var_declarator, \"arrow_function\") or \n self._find_child_by_type(var_declarator, \"function_expression\"))\n \n return {\n 'name': var_name,\n 'type': 'variable',\n 'subtype': f'{decl_type}_declaration',\n 'code_snippet': code_snippet,\n 'display_name': f\"{decl_type} {var_name}\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'has_function': bool(has_function),\n 'declaration_type': decl_type\n }", - "start_line": 499, - "end_line": 529, - "has_docstring": true, - "docstring": "Extract lexical declaration entity (const/let).", - "parameters": [ - "self", - "node", - "depth" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_lexical_declaration_entity", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_lexical_declaration_entity", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_variable_declaration_entity": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_variable_declaration_entity", - "name": "TreeSitterTSAnalyzer._extract_variable_declaration_entity", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type" - ], - "source_code": " def _extract_variable_declaration_entity(self, node, depth: int) -> dict:\n var_declarator = self._find_child_by_type(node, \"variable_declarator\")\n if not var_declarator:\n return None\n \n name_node = self._find_child_by_type(var_declarator, \"identifier\")\n if not name_node:\n return None\n \n var_name = self._get_node_text(name_node)\n code_snippet = self._get_node_text(node)\n \n has_function = (self._find_child_by_type(var_declarator, \"arrow_function\") or \n self._find_child_by_type(var_declarator, \"function_expression\"))\n \n return {\n 'name': var_name,\n 'type': 'variable',\n 'subtype': 'var_declaration',\n 'code_snippet': code_snippet,\n 'display_name': f\"var {var_name}\",\n 'start_line': node.start_point[0] + 1,\n 'end_line': node.end_point[0] + 1,\n 'has_function': bool(has_function),\n 'declaration_type': 'var'\n }", - "start_line": 531, - "end_line": 556, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "depth" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_variable_declaration_entity", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_variable_declaration_entity", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._create_node_from_entity": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._create_node_from_entity", - "name": "TreeSitterTSAnalyzer._create_node_from_entity", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_component_id", - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_relative_path" - ], - "source_code": " def _create_node_from_entity(self, entity_data: dict) -> Optional[Node]:\n \"\"\"Create Node object from entity data.\"\"\"\n try:\n component_type = entity_data['type']\n name = entity_data['name']\n node_type = entity_data.get('subtype', entity_data['type'])\n \n component_id = self._get_component_id(name)\n relative_path = self._get_relative_path()\n \n return Node(\n id=component_id,\n name=name,\n component_type=component_type,\n file_path=str(self.file_path),\n relative_path=relative_path,\n source_code=entity_data['code_snippet'],\n start_line=entity_data['start_line'],\n end_line=entity_data['end_line'],\n has_docstring=False,\n docstring=\"\",\n parameters=entity_data.get('parameters', []),\n node_type=node_type,\n base_classes=entity_data.get('base_classes'),\n class_name=entity_data.get('class_name'),\n display_name=entity_data['display_name'],\n component_id=component_id,\n language=\"typescript\",\n qualified_name=name,\n )\n except Exception as e:\n logger.debug(f\"Error creating node from entity: {e}\")\n return None", - "start_line": 558, - "end_line": 590, - "has_docstring": true, - "docstring": "Create Node object from entity data.", - "parameters": [ - "self", - "entity_data" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._create_node_from_entity", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._create_node_from_entity", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._should_include_node": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._should_include_node", - "name": "TreeSitterTSAnalyzer._should_include_node", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [], - "source_code": " def _should_include_node(self, node: Node) -> bool:\n excluded_names = {\"constructor\", \"__proto__\", \"prototype\"}\n\n if node.component_type == \"variable\":\n return False\n\n return node.name.split(\".\")[-1].lower() not in excluded_names", - "start_line": 592, - "end_line": 598, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._should_include_node", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._should_include_node", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_constructor_dependencies": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_constructor_dependencies", - "name": "TreeSitterTSAnalyzer._extract_constructor_dependencies", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_parameter_dependencies" - ], - "source_code": " def _extract_constructor_dependencies(self, class_node, class_name: str) -> None:\n \"\"\"Extract dependencies from constructor parameters.\"\"\"\n try:\n class_body = self._find_child_by_type(class_node, \"class_body\")\n if not class_body:\n return\n \n for child in class_body.children:\n if child.type == \"method_definition\":\n property_name = self._find_child_by_type(child, \"property_identifier\")\n if property_name and self._get_node_text(property_name) == \"constructor\":\n # Extract parameter types\n formal_params = self._find_child_by_type(child, \"formal_parameters\")\n if formal_params:\n self._extract_parameter_dependencies(formal_params, class_name)\n break\n except Exception as e:\n logger.debug(f\"Error extracting constructor dependencies: {e}\")", - "start_line": 600, - "end_line": 617, - "has_docstring": true, - "docstring": "Extract dependencies from constructor parameters.", - "parameters": [ - "self", - "class_node", - "class_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_constructor_dependencies", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_constructor_dependencies", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_parameter_dependencies": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_parameter_dependencies", - "name": "TreeSitterTSAnalyzer._extract_parameter_dependencies", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._add_relationship" - ], - "source_code": " def _extract_parameter_dependencies(self, formal_params, caller_name: str) -> None:\n try:\n for child in formal_params.children:\n if child.type in [\"required_parameter\", \"optional_parameter\"]:\n type_annotation = self._find_child_by_type(child, \"type_annotation\")\n if type_annotation:\n type_id = self._find_child_by_type(type_annotation, \"type_identifier\")\n if type_id:\n dependency_name = self._get_node_text(type_id)\n if dependency_name and dependency_name != caller_name:\n self._add_relationship(\n caller_name,\n dependency_name,\n child.start_point[0] + 1,\n resolved=dependency_name in self.top_level_nodes,\n )\n except Exception as e:\n logger.debug(f\"Error extracting parameter dependencies: {e}\")", - "start_line": 619, - "end_line": 636, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "formal_params", - "caller_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_parameter_dependencies", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_parameter_dependencies", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_module_path": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_module_path", - "name": "TreeSitterTSAnalyzer._get_module_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [], - "source_code": " def _get_module_path(self) -> str:\n if self.repo_path:\n try:\n rel_path = os.path.relpath(str(self.file_path), self.repo_path)\n except ValueError:\n rel_path = str(self.file_path)\n else:\n rel_path = str(self.file_path)\n \n for ext in ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']:\n if rel_path.endswith(ext):\n rel_path = rel_path[:-len(ext)]\n break\n return rel_path.replace('/', '.').replace('\\\\', '.')", - "start_line": 639, - "end_line": 652, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._get_module_path", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_module_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_relative_path": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_relative_path", - "name": "TreeSitterTSAnalyzer._get_relative_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [], - "source_code": " def _get_relative_path(self) -> str:\n if self.repo_path:\n try:\n return os.path.relpath(str(self.file_path), self.repo_path)\n except ValueError:\n return str(self.file_path)\n else:\n return str(self.file_path)", - "start_line": 654, - "end_line": 661, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._get_relative_path", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_relative_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_component_id": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_component_id", - "name": "TreeSitterTSAnalyzer._get_component_id", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_relative_path" - ], - "source_code": " def _get_component_id(self, name: str) -> str:\n return f\"{self._get_relative_path()}::{name}\"", - "start_line": 663, - "end_line": 664, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._get_component_id", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_component_id", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_inheritance": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_inheritance", - "name": "TreeSitterTSAnalyzer._extract_inheritance", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type" - ], - "source_code": " def _extract_inheritance(self, node) -> List[str]:\n \"\"\"Extract inheritance/implementation relationships.\"\"\"\n base_classes = []\n \n extends_clause = self._find_child_by_type(node, \"extends_clause\")\n if extends_clause:\n for child in extends_clause.children:\n if child.type in [\"identifier\", \"type_identifier\"]:\n base_classes.append(self._get_node_text(child))\n \n implements_clause = self._find_child_by_type(node, \"implements_clause\") \n if implements_clause:\n for child in implements_clause.children:\n if child.type in [\"identifier\", \"type_identifier\"]:\n base_classes.append(self._get_node_text(child))\n \n return base_classes", - "start_line": 666, - "end_line": 682, - "has_docstring": true, - "docstring": "Extract inheritance/implementation relationships.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_inheritance", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_inheritance", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_parameters": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_parameters", - "name": "TreeSitterTSAnalyzer._extract_parameters", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type" - ], - "source_code": " def _extract_parameters(self, node) -> List[str]:\n parameters = []\n params_node = self._find_child_by_type(node, \"formal_parameters\")\n if params_node:\n for child in params_node.children:\n if child.type in [\"identifier\", \"required_parameter\", \"optional_parameter\"]:\n if child.type == \"identifier\":\n parameters.append(self._get_node_text(child))\n else:\n param_name = self._find_child_by_type(child, \"identifier\")\n if param_name:\n parameters.append(self._get_node_text(param_name))\n return parameters", - "start_line": 684, - "end_line": 696, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_parameters", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_parameters", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_all_relationships": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_all_relationships", - "name": "TreeSitterTSAnalyzer._extract_all_relationships", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._traverse_for_relationships" - ], - "source_code": " def _extract_all_relationships(self, node, all_entities: dict) -> None:\n self._traverse_for_relationships(node, all_entities, current_top_level=None)", - "start_line": 698, - "end_line": 699, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "all_entities" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_all_relationships", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_all_relationships", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._traverse_for_relationships": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._traverse_for_relationships", - "name": "TreeSitterTSAnalyzer._traverse_for_relationships", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_type_relationship", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_new_top_level", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_new_relationship", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._traverse_for_relationships", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_inheritance_relationship", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_top_level_name", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_call_relationship", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_type_arguments_relationship" - ], - "source_code": " def _traverse_for_relationships(self, node, all_entities: dict, current_top_level: str = None) -> None:\n if current_top_level is None or self._is_new_top_level(node):\n new_top_level = self._get_top_level_name(node)\n if new_top_level and new_top_level in self.top_level_nodes:\n current_top_level = new_top_level\n\n \n if current_top_level:\n if node.type == \"call_expression\":\n self._extract_call_relationship(node, current_top_level, all_entities)\n elif node.type == \"new_expression\":\n self._extract_new_relationship(node, current_top_level, all_entities)\n \n elif node.type == \"type_annotation\":\n self._extract_type_relationship(node, current_top_level, all_entities)\n elif node.type == \"type_arguments\":\n self._extract_type_arguments_relationship(node, current_top_level, all_entities)\n \n elif node.type == \"extends_clause\":\n self._extract_inheritance_relationship(node, current_top_level, all_entities)\n elif node.type == \"implements_clause\":\n self._extract_inheritance_relationship(node, current_top_level, all_entities)\n\n for child in node.children:\n self._traverse_for_relationships(child, all_entities, current_top_level)", - "start_line": 701, - "end_line": 725, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "all_entities", - "current_top_level" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._traverse_for_relationships", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._traverse_for_relationships", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_new_top_level": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_new_top_level", - "name": "TreeSitterTSAnalyzer._is_new_top_level", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [], - "source_code": " def _is_new_top_level(self, node) -> bool:\n return node.type in [\n \"function_declaration\", \"generator_function_declaration\",\n \"class_declaration\", \"abstract_class_declaration\",\n \"interface_declaration\", \"type_alias_declaration\", \"enum_declaration\",\n \"export_statement\", \"method_definition\"\n ]", - "start_line": 727, - "end_line": 733, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._is_new_top_level", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_new_top_level", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_top_level_name": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_top_level_name", - "name": "TreeSitterTSAnalyzer._get_top_level_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._enclosing_class_name" - ], - "source_code": " def _get_top_level_name(self, node) -> Optional[str]:\n result = None\n if node.type == \"method_definition\":\n name_node = self._find_child_by_type(node, \"property_identifier\")\n if name_node:\n method_name = self._get_node_text(name_node)\n class_name = self._enclosing_class_name(node)\n result = f\"{class_name}.{method_name}\" if class_name else method_name\n elif node.type in [\"function_declaration\", \"generator_function_declaration\"]:\n name_node = self._find_child_by_type(node, \"identifier\")\n result = self._get_node_text(name_node) if name_node else None\n elif node.type in [\"class_declaration\", \"abstract_class_declaration\", \"interface_declaration\", \"type_alias_declaration\"]:\n name_node = self._find_child_by_type(node, \"type_identifier\") or self._find_child_by_type(node, \"identifier\")\n result = self._get_node_text(name_node) if name_node else None\n elif node.type == \"enum_declaration\":\n name_node = self._find_child_by_type(node, \"identifier\")\n result = self._get_node_text(name_node) if name_node else None\n elif node.type == \"export_statement\":\n if self._find_child_by_type(node, \"default\"):\n call_expr = self._find_child_by_type(node, \"call_expression\")\n if call_expr:\n identifier = self._find_child_by_type(call_expr, \"identifier\")\n if identifier:\n return self._get_node_text(identifier)\n return \"default_export\"\n else:\n func_decl = self._find_child_by_type(node, \"function_declaration\")\n class_decl = self._find_child_by_type(node, \"class_declaration\")\n lexical_decl = self._find_child_by_type(node, \"lexical_declaration\")\n \n if func_decl:\n name_node = self._find_child_by_type(func_decl, \"identifier\")\n if name_node:\n result = self._get_node_text(name_node) \n elif class_decl:\n name_node = self._find_child_by_type(class_decl, \"type_identifier\")\n if name_node:\n result = self._get_node_text(name_node) \n elif lexical_decl:\n var_declarator = self._find_child_by_type(lexical_decl, \"variable_declarator\")\n if var_declarator:\n name_node = self._find_child_by_type(var_declarator, \"identifier\")\n if name_node:\n result = self._get_node_text(name_node) \n else:\n result = \"unnamed_export\"\n elif node.type in [\"lexical_declaration\", \"variable_declaration\"]:\n # const/let/var declarations\n var_declarator = self._find_child_by_type(node, \"variable_declarator\")\n if var_declarator:\n name_node = self._find_child_by_type(var_declarator, \"identifier\")\n result = self._get_node_text(name_node) if name_node else None\n else:\n result = None\n else:\n result = None\n \n return result", - "start_line": 735, - "end_line": 792, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._get_top_level_name", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_top_level_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_call_relationship": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_call_relationship", - "name": "TreeSitterTSAnalyzer._extract_call_relationship", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._emit_instance_method_call", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_actually_top_level", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._emit_receiver_method_call", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._add_relationship", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._member_call_parts", - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": " def _extract_call_relationship(self, node, caller_name: str, all_entities: dict) -> None:\n \"\"\"Emit at most one relationship per call expression.\n\n Plain identifier calls resolve against same-file components; member\n calls are resolved receiver-first (this/super against the enclosing\n class, class names and typed variables against their methods).\n Unresolved callees are emitted as bare logical names for the global\n resolver, never file-prefixed.\n \"\"\"\n try:\n call_line = node.start_point[0] + 1\n func_node = node.children[0] if node.children else None\n if func_node is None:\n return\n\n if func_node.type == \"identifier\":\n name = self._get_node_text(func_node)\n if not name:\n return\n if name in self.top_level_nodes:\n self._add_relationship(caller_name, name, call_line, resolved=True)\n elif name in all_entities and not self._is_actually_top_level(all_entities[name]):\n logger.debug(f\"Ignoring nested call: {caller_name} -> {name} (local/nested)\")\n else:\n self._add_relationship(caller_name, name, call_line, resolved=False)\n return\n\n if func_node.type != \"member_expression\":\n return\n\n parts = self._member_call_parts(func_node)\n if parts is None:\n return\n receiver_kind, receiver_text, tail = parts\n if not tail:\n return\n\n if receiver_kind in (\"this\", \"super\"):\n self._emit_instance_method_call(caller_name, tail, call_line, prefer_bases=(receiver_kind == \"super\"))\n elif receiver_kind == \"identifier\":\n self._emit_receiver_method_call(node, caller_name, receiver_text, tail, call_line)\n elif receiver_kind == \"chain\":\n self._add_relationship(caller_name, f\"{receiver_text}.{tail}\", call_line, resolved=False)\n else:\n # Composite or literal receiver: a builtin-prototype method on\n # an unknowable receiver can never resolve to a project\n # component; anything else stays an honest bare name.\n if receiver_kind == \"composite\" and tail not in JS_TS_PROTOTYPE_METHODS:\n self._add_relationship(caller_name, tail, call_line, resolved=False)\n\n except Exception as e:\n logger.debug(f\"Error extracting call relationship: {e}\")", - "start_line": 794, - "end_line": 845, - "has_docstring": true, - "docstring": "Emit at most one relationship per call expression.\n\nPlain identifier calls resolve against same-file components; member\ncalls are resolved receiver-first (this/super against the enclosing\nclass, class names and typed variables against their methods).\nUnresolved callees are emitted as bare logical names for the global\nresolver, never file-prefixed.", - "parameters": [ - "self", - "node", - "caller_name", - "all_entities" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_call_relationship", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_call_relationship", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._member_call_parts": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._member_call_parts", - "name": "TreeSitterTSAnalyzer._member_call_parts", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._identifier_chain" - ], - "source_code": " def _member_call_parts(self, member_node) -> Optional[Tuple[str, Optional[str], str]]:\n \"\"\"Split a member expression callee into (receiver_kind, receiver_text, method_tail).\n\n receiver_kind is one of: \"this\", \"super\", \"identifier\", \"chain\" (a\n pure dotted identifier chain), \"composite\" (call result, subscript,\n parenthesized, new expression), or \"literal\".\n \"\"\"\n property_node = member_node.child_by_field_name(\"property\") or self._find_child_by_type(member_node, \"property_identifier\")\n tail = self._get_node_text(property_node) if property_node else \"\"\n obj = member_node.child_by_field_name(\"object\")\n if obj is None and member_node.children:\n obj = member_node.children[0]\n if obj is None:\n return None\n\n if obj.type == \"this\":\n return (\"this\", None, tail)\n if obj.type == \"super\":\n return (\"super\", None, tail)\n if obj.type == \"identifier\":\n return (\"identifier\", self._get_node_text(obj), tail)\n if obj.type == \"member_expression\":\n chain = self._identifier_chain(obj)\n if chain:\n return (\"chain\", chain, tail)\n return (\"composite\", None, tail)\n if obj.type in (\"array\", \"string\", \"template_string\", \"number\", \"object\", \"regex\", \"true\", \"false\"):\n return (\"literal\", None, tail)\n return (\"composite\", None, tail)", - "start_line": 847, - "end_line": 875, - "has_docstring": true, - "docstring": "Split a member expression callee into (receiver_kind, receiver_text, method_tail).\n\nreceiver_kind is one of: \"this\", \"super\", \"identifier\", \"chain\" (a\npure dotted identifier chain), \"composite\" (call result, subscript,\nparenthesized, new expression), or \"literal\".", - "parameters": [ - "self", - "member_node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._member_call_parts", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._member_call_parts", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._identifier_chain": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._identifier_chain", - "name": "TreeSitterTSAnalyzer._identifier_chain", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text" - ], - "source_code": " def _identifier_chain(self, node) -> Optional[str]:\n \"\"\"Flatten a member expression into dotted text when it is a pure\n identifier chain; None when any link is computed.\"\"\"\n parts = []\n current = node\n while current.type == \"member_expression\":\n property_node = current.child_by_field_name(\"property\")\n if property_node is None or property_node.type != \"property_identifier\":\n return None\n parts.append(self._get_node_text(property_node))\n current = current.child_by_field_name(\"object\")\n if current is None:\n return None\n if current.type != \"identifier\":\n return None\n parts.append(self._get_node_text(current))\n return \".\".join(reversed(parts))", - "start_line": 877, - "end_line": 893, - "has_docstring": true, - "docstring": "Flatten a member expression into dotted text when it is a pure\nidentifier chain; None when any link is computed.", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._identifier_chain", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._identifier_chain", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._emit_instance_method_call": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._emit_instance_method_call", - "name": "TreeSitterTSAnalyzer._emit_instance_method_call", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._add_relationship" - ], - "source_code": " def _emit_instance_method_call(self, caller_name: str, tail: str, call_line: int, prefer_bases: bool = False) -> None:\n \"\"\"Resolve this.m()/super.m() against the enclosing class and its bases.\"\"\"\n class_name = caller_name.split(\".\")[0] if caller_name else None\n if not class_name:\n self._add_relationship(caller_name, tail, call_line, resolved=False)\n return\n\n candidates = [] if prefer_bases else [class_name]\n class_node = self.top_level_nodes.get(class_name)\n if class_node and class_node.base_classes:\n candidates.extend(class_node.base_classes)\n\n for candidate in candidates:\n if f\"{candidate}.{tail}\" in self.top_level_nodes:\n self._add_relationship(caller_name, f\"{candidate}.{tail}\", call_line, resolved=True)\n return\n\n # Not defined in this file: emit the qualified form for the global\n # resolver (an inherited method defined in another file).\n target = candidates[0] if candidates else class_name\n self._add_relationship(caller_name, f\"{target}.{tail}\", call_line, resolved=False)", - "start_line": 895, - "end_line": 915, - "has_docstring": true, - "docstring": "Resolve this.m()/super.m() against the enclosing class and its bases.", - "parameters": [ - "self", - "caller_name", - "tail", - "call_line", - "prefer_bases" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._emit_instance_method_call", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._emit_instance_method_call", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._emit_receiver_method_call": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._emit_receiver_method_call", - "name": "TreeSitterTSAnalyzer._emit_receiver_method_call", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._infer_identifier_type", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._add_relationship" - ], - "source_code": " def _emit_receiver_method_call(self, call_node, caller_name: str, receiver: str, tail: str, call_line: int) -> None:\n \"\"\"Resolve recv.m() where recv is a simple identifier.\"\"\"\n if not receiver:\n return\n # Static call or enum/namespace access on a known component.\n if receiver in self.top_level_nodes:\n if f\"{receiver}.{tail}\" in self.top_level_nodes:\n self._add_relationship(caller_name, f\"{receiver}.{tail}\", call_line, resolved=True)\n else:\n self._add_relationship(caller_name, f\"{receiver}.{tail}\", call_line, resolved=False)\n return\n\n inferred = self._infer_identifier_type(call_node, receiver)\n if inferred:\n if f\"{inferred}.{tail}\" in self.top_level_nodes:\n self._add_relationship(caller_name, f\"{inferred}.{tail}\", call_line, resolved=True)\n else:\n self._add_relationship(caller_name, f\"{inferred}.{tail}\", call_line, resolved=False)\n return\n\n self._add_relationship(caller_name, f\"{receiver}.{tail}\", call_line, resolved=False)", - "start_line": 917, - "end_line": 937, - "has_docstring": true, - "docstring": "Resolve recv.m() where recv is a simple identifier.", - "parameters": [ - "self", - "call_node", - "caller_name", - "receiver", - "tail", - "call_line" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._emit_receiver_method_call", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._emit_receiver_method_call", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._infer_identifier_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._infer_identifier_type", - "name": "TreeSitterTSAnalyzer._infer_identifier_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_declared_type" - ], - "source_code": " def _infer_identifier_type(self, call_node, identifier: str) -> Optional[str]:\n \"\"\"Find the type of a local identifier from `new X()` initializers or\n TS type annotations within the enclosing function/method/class.\"\"\"\n scope = call_node.parent\n scopes = []\n while scope:\n if scope.type in (\n \"method_definition\", \"function_declaration\",\n \"generator_function_declaration\", \"arrow_function\",\n \"function_expression\", \"class_declaration\",\n \"abstract_class_declaration\", \"program\",\n ):\n scopes.append(scope)\n scope = scope.parent\n\n for scope_node in scopes:\n found = self._find_declared_type(scope_node, identifier)\n if found:\n return found\n return None", - "start_line": 939, - "end_line": 958, - "has_docstring": true, - "docstring": "Find the type of a local identifier from `new X()` initializers or\nTS type annotations within the enclosing function/method/class.", - "parameters": [ - "self", - "call_node", - "identifier" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._infer_identifier_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._infer_identifier_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_declared_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_declared_type", - "name": "TreeSitterTSAnalyzer._find_declared_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type" - ], - "source_code": " def _find_declared_type(self, scope_node, identifier: str) -> Optional[str]:\n stack = [scope_node]\n while stack:\n current = stack.pop()\n if current.type == \"variable_declarator\":\n name_node = self._find_child_by_type(current, \"identifier\")\n if name_node is not None and self._get_node_text(name_node) == identifier:\n new_expr = self._find_child_by_type(current, \"new_expression\")\n if new_expr is not None:\n for child in new_expr.children:\n if child.type in (\"identifier\", \"type_identifier\"):\n return self._get_node_text(child)\n annotation = self._find_child_by_type(current, \"type_annotation\")\n if annotation is not None:\n type_id = self._find_child_by_type(annotation, \"type_identifier\")\n if type_id is not None:\n return self._get_node_text(type_id)\n elif current.type in (\"required_parameter\", \"optional_parameter\"):\n name_node = self._find_child_by_type(current, \"identifier\")\n if name_node is not None and self._get_node_text(name_node) == identifier:\n annotation = self._find_child_by_type(current, \"type_annotation\")\n if annotation is not None:\n type_id = self._find_child_by_type(annotation, \"type_identifier\")\n if type_id is not None:\n return self._get_node_text(type_id)\n stack.extend(current.children)\n return None", - "start_line": 960, - "end_line": 986, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "scope_node", - "identifier" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._find_declared_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_declared_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_new_relationship": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_new_relationship", - "name": "TreeSitterTSAnalyzer._extract_new_relationship", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._add_relationship" - ], - "source_code": " def _extract_new_relationship(self, node, caller_name: str, all_entities: dict) -> None:\n try:\n call_line = node.start_point[0] + 1\n if node.children:\n constructor_node = None\n for child in node.children:\n if child.type not in ['new', 'type_arguments', 'arguments']:\n constructor_node = child\n break\n\n if constructor_node:\n constructor_name = self._get_node_text(constructor_node)\n\n if constructor_name:\n resolved = constructor_name in self.top_level_nodes\n self._add_relationship(caller_name, constructor_name, call_line, resolved=resolved)\n\n except Exception as e:\n logger.debug(f\"Error extracting new relationship: {e}\")", - "start_line": 988, - "end_line": 1006, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "caller_name", - "all_entities" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_new_relationship", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_new_relationship", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_type_relationship": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_type_relationship", - "name": "TreeSitterTSAnalyzer._extract_type_relationship", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._resolve_to_top_level", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._add_relationship", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_all_type_identifiers", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_builtin_type", - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": " def _extract_type_relationship(self, node, caller_name: str, all_entities: dict) -> None:\n try:\n type_identifiers = []\n self._find_all_type_identifiers(node, type_identifiers)\n \n call_line = node.start_point[0] + 1\n \n for type_node in type_identifiers:\n type_name = self._get_node_text(type_node)\n \n if self._is_builtin_type(type_name):\n continue\n \n if type_name in all_entities:\n target_name = self._resolve_to_top_level(type_name, all_entities)\n if target_name and target_name in self.top_level_nodes:\n self._add_relationship(caller_name, target_name, call_line, resolved=True)\n else:\n self._add_relationship(caller_name, type_name, call_line, resolved=False)\n \n except Exception as e:\n logger.debug(f\"Error extracting type relationship: {e}\")", - "start_line": 1008, - "end_line": 1029, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "caller_name", - "all_entities" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_type_relationship", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_type_relationship", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_all_type_identifiers": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_all_type_identifiers", - "name": "TreeSitterTSAnalyzer._find_all_type_identifiers", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_all_type_identifiers" - ], - "source_code": " def _find_all_type_identifiers(self, node, type_identifiers: list) -> None:\n if node.type == \"type_identifier\":\n type_identifiers.append(node)\n \n for child in node.children:\n self._find_all_type_identifiers(child, type_identifiers)", - "start_line": 1031, - "end_line": 1036, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "type_identifiers" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._find_all_type_identifiers", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_all_type_identifiers", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_type_arguments_relationship": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_type_arguments_relationship", - "name": "TreeSitterTSAnalyzer._extract_type_arguments_relationship", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._resolve_to_top_level", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._add_relationship" - ], - "source_code": " def _extract_type_arguments_relationship(self, node, caller_name: str, all_entities: dict) -> None:\n try:\n for child in node.children:\n if child.type == \"type_identifier\":\n type_name = self._get_node_text(child)\n if type_name in all_entities:\n target_name = self._resolve_to_top_level(type_name, all_entities)\n if target_name and target_name in self.top_level_nodes:\n call_line = node.start_point[0] + 1\n self._add_relationship(caller_name, target_name, call_line, resolved=True)\n except Exception as e:\n logger.debug(f\"Error extracting type arguments relationship: {e}\")", - "start_line": 1038, - "end_line": 1049, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "caller_name", - "all_entities" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_type_arguments_relationship", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_type_arguments_relationship", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_inheritance_relationship": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_inheritance_relationship", - "name": "TreeSitterTSAnalyzer._extract_inheritance_relationship", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._resolve_to_top_level", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._add_relationship" - ], - "source_code": " def _extract_inheritance_relationship(self, node, caller_name: str, all_entities: dict) -> None:\n \"\"\"Extract inheritance/implementation relationships\"\"\"\n try:\n for child in node.children:\n if child.type in [\"identifier\", \"type_identifier\"]:\n base_name = self._get_node_text(child)\n if base_name in all_entities:\n target_name = self._resolve_to_top_level(base_name, all_entities)\n if target_name and target_name in self.top_level_nodes:\n call_line = node.start_point[0] + 1\n self._add_relationship(caller_name, target_name, call_line, resolved=True)\n else:\n self._add_relationship(caller_name, base_name, call_line=node.start_point[0] + 1, resolved=False)\n except Exception as e:\n logger.debug(f\"Error extracting inheritance relationship: {e}\")", - "start_line": 1051, - "end_line": 1065, - "has_docstring": true, - "docstring": "Extract inheritance/implementation relationships", - "parameters": [ - "self", - "node", - "caller_name", - "all_entities" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._extract_inheritance_relationship", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._extract_inheritance_relationship", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._resolve_to_top_level": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._resolve_to_top_level", - "name": "TreeSitterTSAnalyzer._resolve_to_top_level", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def _resolve_to_top_level(self, entity_name: str, all_entities: dict) -> Optional[str]:\n if entity_name in self.top_level_nodes:\n return entity_name\n \n entity_data = all_entities.get(entity_name)\n if entity_data and entity_data.get('depth', 0) > 2:\n return None\n \n return entity_name if entity_name in self.top_level_nodes else None", - "start_line": 1067, - "end_line": 1075, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "entity_name", - "all_entities" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._resolve_to_top_level", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._resolve_to_top_level", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._add_relationship": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._add_relationship", - "name": "TreeSitterTSAnalyzer._add_relationship", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_component_id", - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_relative_path" - ], - "source_code": " def _add_relationship(self, caller_name: str, callee_name: str, call_line: int, resolved: bool = False) -> None:\n \"\"\"Record one relationship. Resolved callees are component ids in this\n file; unresolved callees stay bare logical names so they never look\n like project components they are not.\"\"\"\n caller_id = f\"{self._get_relative_path()}::{caller_name}\"\n callee_id = self._get_component_id(callee_name) if resolved else callee_name\n\n key = (caller_id, callee_id)\n if key in self.seen_relationships:\n return\n self.seen_relationships.add(key)\n\n relationship = CallRelationship(\n caller=caller_id,\n callee=callee_id,\n call_line=call_line,\n is_resolved=resolved,\n )\n self.call_relationships.append(relationship)", - "start_line": 1077, - "end_line": 1095, - "has_docstring": true, - "docstring": "Record one relationship. Resolved callees are component ids in this\nfile; unresolved callees stay bare logical names so they never look\nlike project components they are not.", - "parameters": [ - "self", - "caller_name", - "callee_name", - "call_line", - "resolved" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._add_relationship", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._add_relationship", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_builtin_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_builtin_type", - "name": "TreeSitterTSAnalyzer._is_builtin_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [], - "source_code": " def _is_builtin_type(self, name: str) -> bool:\n \"\"\"Check if type name is a TypeScript/JavaScript built-in type.\"\"\"\n builtin_types = {\n # Primitive types\n \"string\", \"number\", \"boolean\", \"object\", \"undefined\", \"null\", \"void\", \"never\", \"any\", \"unknown\"\n }\n return name in builtin_types", - "start_line": 1097, - "end_line": 1103, - "has_docstring": true, - "docstring": "Check if type name is a TypeScript/JavaScript built-in type.", - "parameters": [ - "self", - "name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._is_builtin_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_builtin_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_builtin_function": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_builtin_function", - "name": "TreeSitterTSAnalyzer._is_builtin_function", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [], - "source_code": " def _is_builtin_function(self, name: str) -> bool:\n builtins = {}\n return name in builtins", - "start_line": 1105, - "end_line": 1107, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._is_builtin_function", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._is_builtin_function", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type", - "name": "TreeSitterTSAnalyzer._find_child_by_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [], - "source_code": " def _find_child_by_type(self, node, node_type: str):\n for child in node.children:\n if child.type == node_type:\n return child\n return None", - "start_line": 1109, - "end_line": 1113, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node", - "node_type" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._find_child_by_type", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._find_child_by_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "name": "TreeSitterTSAnalyzer._get_node_text", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [], - "source_code": " def _get_node_text(self, node) -> str:\n start_byte = node.start_byte\n end_byte = node.end_byte\n return self.content.encode(\"utf8\")[start_byte:end_byte].decode(\"utf8\")", - "start_line": 1115, - "end_line": 1118, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "node" - ], - "node_type": "method", - "base_classes": null, - "class_name": "TreeSitterTSAnalyzer", - "display_name": "method TreeSitterTSAnalyzer._get_node_text", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer._get_node_text", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::analyze_typescript_file_treesitter": { - "id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::analyze_typescript_file_treesitter", - "name": "analyze_typescript_file_treesitter", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "relative_path": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py", - "depends_on": [ - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/cli/utils/logging.py::CLILogger.error", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer.analyze", - "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::TreeSitterTSAnalyzer" - ], - "source_code": "def analyze_typescript_file_treesitter(\n file_path: str, content: str, repo_path: str = None\n) -> Tuple[List[Node], List[CallRelationship]]:\n try:\n logger.debug(f\"Tree-sitter TS analysis for {file_path}\")\n analyzer = TreeSitterTSAnalyzer(file_path, content, repo_path)\n analyzer.analyze()\n logger.debug(\n f\"Found {len(analyzer.nodes)} top-level nodes, {len(analyzer.call_relationships)} calls\"\n )\n return analyzer.nodes, analyzer.call_relationships\n except Exception as e:\n logger.error(f\"Error in tree-sitter TS analysis for {file_path}: {e}\", exc_info=True)\n return [], []", - "start_line": 1122, - "end_line": 1135, - "has_docstring": false, - "docstring": "", - "parameters": [ - "file_path", - "content", - "repo_path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function analyze_typescript_file_treesitter", - "component_id": "codewiki/src/be/dependency_analyzer/analyzers/typescript.py::analyze_typescript_file_treesitter", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser": { - "id": "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser", - "name": "DependencyParser", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/ast_parser.py", - "relative_path": "codewiki/src/be/dependency_analyzer/ast_parser.py", - "depends_on": [], - "source_code": "class DependencyParser:\n \"\"\"Parser for extracting code components from multi-language repositories.\"\"\"\n \n def __init__(\n self,\n repo_path: str,\n include_patterns: List[str] = None,\n exclude_patterns: List[str] = None,\n use_gitignore: bool = True,\n ):\n \"\"\"\n Initialize the dependency parser.\n \n Args:\n repo_path: Path to the repository\n include_patterns: File patterns to include (e.g., [\"*.cs\", \"*.py\"])\n exclude_patterns: File/directory patterns to exclude (e.g., [\"*Tests*\"])\n use_gitignore: Whether to apply Git ignore rules\n \"\"\"\n self.repo_path = os.path.abspath(repo_path)\n self.components: Dict[str, Node] = {}\n self.modules: Set[str] = set()\n self.include_patterns = include_patterns\n self.exclude_patterns = exclude_patterns\n self.use_gitignore = use_gitignore\n \n self.analysis_service = AnalysisService()\n\n def parse_repository(self, filtered_folders: List[str] = None) -> Dict[str, Node]:\n logger.debug(f\"Parsing repository at {self.repo_path}\")\n \n # Log custom patterns if set\n if self.include_patterns:\n logger.info(f\"Using custom include patterns: {self.include_patterns}\")\n if self.exclude_patterns:\n logger.info(f\"Using custom exclude patterns: {self.exclude_patterns}\")\n \n structure_result = self.analysis_service._analyze_structure(\n self.repo_path, \n include_patterns=self.include_patterns,\n exclude_patterns=self.exclude_patterns,\n use_gitignore=self.use_gitignore,\n )\n \n call_graph_result = self.analysis_service._analyze_call_graph(\n structure_result[\"file_tree\"], \n self.repo_path\n )\n \n self._build_components_from_analysis(call_graph_result)\n \n logger.debug(f\"Found {len(self.components)} components across {len(self.modules)} modules\")\n return self.components\n \n def _build_components_from_analysis(self, call_graph_result: Dict):\n functions = call_graph_result.get(\"functions\", [])\n relationships = call_graph_result.get(\"relationships\", [])\n \n component_id_mapping = {}\n \n for func_dict in functions:\n component_id = func_dict.get(\"id\", \"\")\n if not component_id:\n continue\n \n node = Node(\n id=component_id,\n name=func_dict.get(\"name\", \"\"),\n component_type=func_dict.get(\"component_type\", func_dict.get(\"node_type\", \"function\")),\n file_path=func_dict.get(\"file_path\", \"\"),\n relative_path=func_dict.get(\"relative_path\", \"\"),\n source_code=func_dict.get(\"source_code\", func_dict.get(\"code_snippet\", \"\")),\n start_line=func_dict.get(\"start_line\", 0),\n end_line=func_dict.get(\"end_line\", 0),\n has_docstring=func_dict.get(\"has_docstring\", bool(func_dict.get(\"docstring\", \"\"))),\n docstring=func_dict.get(\"docstring\", \"\") or \"\",\n parameters=func_dict.get(\"parameters\", []),\n node_type=func_dict.get(\"node_type\", \"function\"),\n base_classes=func_dict.get(\"base_classes\"),\n class_name=func_dict.get(\"class_name\"),\n display_name=func_dict.get(\"display_name\", \"\"),\n component_id=component_id\n )\n \n self.components[component_id] = node\n \n component_id_mapping[component_id] = component_id\n legacy_id = f\"{func_dict.get('file_path', '')}:{func_dict.get('name', '')}\"\n if legacy_id and legacy_id != component_id:\n component_id_mapping[legacy_id] = component_id\n \n if \"::\" in component_id:\n file_path_part = component_id.split(\"::\")[0]\n if file_path_part:\n self.modules.add(file_path_part)\n elif \".\" in component_id:\n module_parts = component_id.split(\".\")[:-1]\n module_path = \".\".join(module_parts)\n if module_path:\n self.modules.add(module_path)\n \n processed_relationships = 0\n for rel_dict in relationships:\n caller_id = rel_dict.get(\"caller\", \"\")\n callee_id = rel_dict.get(\"callee\", \"\")\n is_resolved = rel_dict.get(\"is_resolved\", False)\n \n caller_component_id = component_id_mapping.get(caller_id)\n \n callee_component_id = component_id_mapping.get(callee_id)\n if not callee_component_id:\n for comp_id, comp_node in self.components.items():\n if comp_node.name == callee_id:\n callee_component_id = comp_id\n break\n \n if caller_component_id and caller_component_id in self.components:\n if callee_component_id:\n self.components[caller_component_id].depends_on.add(callee_component_id)\n processed_relationships += 1\n \n def _determine_component_type(self, func_dict: Dict) -> str:\n if func_dict.get(\"is_method\", False):\n return \"method\"\n \n node_type = func_dict.get(\"node_type\", \"\")\n if node_type in [\"class\", \"interface\", \"struct\", \"enum\", \"record\", \"abstract class\", \"annotation\", \"delegate\"]:\n return node_type\n \n return \"function\"\n \n def _file_to_module_path(self, file_path: str) -> str:\n path = file_path\n extensions = ['.py', '.js', '.ts', '.java', '.cs', '.cpp', '.hpp', '.h', '.c', '.tsx', '.jsx', '.cc', '.mjs', '.cxx', '.cc', '.cjs', '.kt', '.kts']\n for ext in extensions:\n if path.endswith(ext):\n path = path[:-len(ext)]\n break\n return path.replace(os.path.sep, \".\")\n \n def save_dependency_graph(self, output_path: str):\n result = {}\n for component_id, component in self.components.items():\n component_dict = component.model_dump()\n if 'depends_on' in component_dict and isinstance(component_dict['depends_on'], set):\n component_dict['depends_on'] = list(component_dict['depends_on'])\n result[component_id] = component_dict\n \n dir_name = os.path.dirname(output_path)\n if dir_name:\n os.makedirs(dir_name, exist_ok=True)\n \n with open(output_path, 'w', encoding='utf-8') as f:\n json.dump(result, f, indent=2, ensure_ascii=False)\n \n logger.debug(f\"Saved {len(self.components)} components to {output_path}\")\n return result", - "start_line": 18, - "end_line": 174, - "has_docstring": true, - "docstring": "Parser for extracting code components from multi-language repositories.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class DependencyParser", - "component_id": "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser.__init__": { - "id": "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser.__init__", - "name": "DependencyParser.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/ast_parser.py", - "relative_path": "codewiki/src/be/dependency_analyzer/ast_parser.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService" - ], - "source_code": " def __init__(\n self,\n repo_path: str,\n include_patterns: List[str] = None,\n exclude_patterns: List[str] = None,\n use_gitignore: bool = True,\n ):\n \"\"\"\n Initialize the dependency parser.\n \n Args:\n repo_path: Path to the repository\n include_patterns: File patterns to include (e.g., [\"*.cs\", \"*.py\"])\n exclude_patterns: File/directory patterns to exclude (e.g., [\"*Tests*\"])\n use_gitignore: Whether to apply Git ignore rules\n \"\"\"\n self.repo_path = os.path.abspath(repo_path)\n self.components: Dict[str, Node] = {}\n self.modules: Set[str] = set()\n self.include_patterns = include_patterns\n self.exclude_patterns = exclude_patterns\n self.use_gitignore = use_gitignore\n \n self.analysis_service = AnalysisService()", - "start_line": 21, - "end_line": 44, - "has_docstring": true, - "docstring": "Initialize the dependency parser.\n\nArgs:\n repo_path: Path to the repository\n include_patterns: File patterns to include (e.g., [\"*.cs\", \"*.py\"])\n exclude_patterns: File/directory patterns to exclude (e.g., [\"*Tests*\"])\n use_gitignore: Whether to apply Git ignore rules", - "parameters": [ - "self", - "repo_path", - "include_patterns", - "exclude_patterns", - "use_gitignore" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DependencyParser", - "display_name": "method DependencyParser.__init__", - "component_id": "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser.parse_repository": { - "id": "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser.parse_repository", - "name": "DependencyParser.parse_repository", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/ast_parser.py", - "relative_path": "codewiki/src/be/dependency_analyzer/ast_parser.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser._build_components_from_analysis", - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._analyze_structure", - "codewiki/src/be/dependency_analyzer/analysis/analysis_service.py::AnalysisService._analyze_call_graph", - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": " def parse_repository(self, filtered_folders: List[str] = None) -> Dict[str, Node]:\n logger.debug(f\"Parsing repository at {self.repo_path}\")\n \n # Log custom patterns if set\n if self.include_patterns:\n logger.info(f\"Using custom include patterns: {self.include_patterns}\")\n if self.exclude_patterns:\n logger.info(f\"Using custom exclude patterns: {self.exclude_patterns}\")\n \n structure_result = self.analysis_service._analyze_structure(\n self.repo_path, \n include_patterns=self.include_patterns,\n exclude_patterns=self.exclude_patterns,\n use_gitignore=self.use_gitignore,\n )\n \n call_graph_result = self.analysis_service._analyze_call_graph(\n structure_result[\"file_tree\"], \n self.repo_path\n )\n \n self._build_components_from_analysis(call_graph_result)\n \n logger.debug(f\"Found {len(self.components)} components across {len(self.modules)} modules\")\n return self.components", - "start_line": 46, - "end_line": 70, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "filtered_folders" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DependencyParser", - "display_name": "method DependencyParser.parse_repository", - "component_id": "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser.parse_repository", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser._build_components_from_analysis": { - "id": "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser._build_components_from_analysis", - "name": "DependencyParser._build_components_from_analysis", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/ast_parser.py", - "relative_path": "codewiki/src/be/dependency_analyzer/ast_parser.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/models/core.py::Node" - ], - "source_code": " def _build_components_from_analysis(self, call_graph_result: Dict):\n functions = call_graph_result.get(\"functions\", [])\n relationships = call_graph_result.get(\"relationships\", [])\n \n component_id_mapping = {}\n \n for func_dict in functions:\n component_id = func_dict.get(\"id\", \"\")\n if not component_id:\n continue\n \n node = Node(\n id=component_id,\n name=func_dict.get(\"name\", \"\"),\n component_type=func_dict.get(\"component_type\", func_dict.get(\"node_type\", \"function\")),\n file_path=func_dict.get(\"file_path\", \"\"),\n relative_path=func_dict.get(\"relative_path\", \"\"),\n source_code=func_dict.get(\"source_code\", func_dict.get(\"code_snippet\", \"\")),\n start_line=func_dict.get(\"start_line\", 0),\n end_line=func_dict.get(\"end_line\", 0),\n has_docstring=func_dict.get(\"has_docstring\", bool(func_dict.get(\"docstring\", \"\"))),\n docstring=func_dict.get(\"docstring\", \"\") or \"\",\n parameters=func_dict.get(\"parameters\", []),\n node_type=func_dict.get(\"node_type\", \"function\"),\n base_classes=func_dict.get(\"base_classes\"),\n class_name=func_dict.get(\"class_name\"),\n display_name=func_dict.get(\"display_name\", \"\"),\n component_id=component_id\n )\n \n self.components[component_id] = node\n \n component_id_mapping[component_id] = component_id\n legacy_id = f\"{func_dict.get('file_path', '')}:{func_dict.get('name', '')}\"\n if legacy_id and legacy_id != component_id:\n component_id_mapping[legacy_id] = component_id\n \n if \"::\" in component_id:\n file_path_part = component_id.split(\"::\")[0]\n if file_path_part:\n self.modules.add(file_path_part)\n elif \".\" in component_id:\n module_parts = component_id.split(\".\")[:-1]\n module_path = \".\".join(module_parts)\n if module_path:\n self.modules.add(module_path)\n \n processed_relationships = 0\n for rel_dict in relationships:\n caller_id = rel_dict.get(\"caller\", \"\")\n callee_id = rel_dict.get(\"callee\", \"\")\n is_resolved = rel_dict.get(\"is_resolved\", False)\n \n caller_component_id = component_id_mapping.get(caller_id)\n \n callee_component_id = component_id_mapping.get(callee_id)\n if not callee_component_id:\n for comp_id, comp_node in self.components.items():\n if comp_node.name == callee_id:\n callee_component_id = comp_id\n break\n \n if caller_component_id and caller_component_id in self.components:\n if callee_component_id:\n self.components[caller_component_id].depends_on.add(callee_component_id)\n processed_relationships += 1", - "start_line": 72, - "end_line": 137, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "call_graph_result" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DependencyParser", - "display_name": "method DependencyParser._build_components_from_analysis", - "component_id": "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser._build_components_from_analysis", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser._determine_component_type": { - "id": "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser._determine_component_type", - "name": "DependencyParser._determine_component_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/ast_parser.py", - "relative_path": "codewiki/src/be/dependency_analyzer/ast_parser.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def _determine_component_type(self, func_dict: Dict) -> str:\n if func_dict.get(\"is_method\", False):\n return \"method\"\n \n node_type = func_dict.get(\"node_type\", \"\")\n if node_type in [\"class\", \"interface\", \"struct\", \"enum\", \"record\", \"abstract class\", \"annotation\", \"delegate\"]:\n return node_type\n \n return \"function\"", - "start_line": 139, - "end_line": 147, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "func_dict" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DependencyParser", - "display_name": "method DependencyParser._determine_component_type", - "component_id": "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser._determine_component_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser._file_to_module_path": { - "id": "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser._file_to_module_path", - "name": "DependencyParser._file_to_module_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/ast_parser.py", - "relative_path": "codewiki/src/be/dependency_analyzer/ast_parser.py", - "depends_on": [], - "source_code": " def _file_to_module_path(self, file_path: str) -> str:\n path = file_path\n extensions = ['.py', '.js', '.ts', '.java', '.cs', '.cpp', '.hpp', '.h', '.c', '.tsx', '.jsx', '.cc', '.mjs', '.cxx', '.cc', '.cjs', '.kt', '.kts']\n for ext in extensions:\n if path.endswith(ext):\n path = path[:-len(ext)]\n break\n return path.replace(os.path.sep, \".\")", - "start_line": 149, - "end_line": 156, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "file_path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DependencyParser", - "display_name": "method DependencyParser._file_to_module_path", - "component_id": "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser._file_to_module_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser.save_dependency_graph": { - "id": "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser.save_dependency_graph", - "name": "DependencyParser.save_dependency_graph", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/ast_parser.py", - "relative_path": "codewiki/src/be/dependency_analyzer/ast_parser.py", - "depends_on": [ - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": " def save_dependency_graph(self, output_path: str):\n result = {}\n for component_id, component in self.components.items():\n component_dict = component.model_dump()\n if 'depends_on' in component_dict and isinstance(component_dict['depends_on'], set):\n component_dict['depends_on'] = list(component_dict['depends_on'])\n result[component_id] = component_dict\n \n dir_name = os.path.dirname(output_path)\n if dir_name:\n os.makedirs(dir_name, exist_ok=True)\n \n with open(output_path, 'w', encoding='utf-8') as f:\n json.dump(result, f, indent=2, ensure_ascii=False)\n \n logger.debug(f\"Saved {len(self.components)} components to {output_path}\")\n return result", - "start_line": 158, - "end_line": 174, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "output_path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DependencyParser", - "display_name": "method DependencyParser.save_dependency_graph", - "component_id": "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser.save_dependency_graph", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py::DependencyGraphBuilder": { - "id": "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py::DependencyGraphBuilder", - "name": "DependencyGraphBuilder", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py", - "relative_path": "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py", - "depends_on": [], - "source_code": "class DependencyGraphBuilder:\n \"\"\"Handles dependency analysis and graph building.\"\"\"\n \n def __init__(self, config: Config):\n self.config = config\n \n def build_dependency_graph(self) -> tuple[Dict[str, Any], List[str]]:\n \"\"\"\n Build and save dependency graph, returning components and leaf nodes.\n \n Returns:\n Tuple of (components, leaf_nodes)\n \"\"\"\n # Ensure output directory exists\n file_manager.ensure_directory(self.config.dependency_graph_dir)\n\n # Prepare dependency graph path\n repo_name = os.path.basename(os.path.normpath(self.config.repo_path))\n sanitized_repo_name = ''.join(c if c.isalnum() else '_' for c in repo_name)\n dependency_graph_path = os.path.join(\n self.config.dependency_graph_dir, \n f\"{sanitized_repo_name}_dependency_graph.json\"\n )\n filtered_folders_path = os.path.join(\n self.config.dependency_graph_dir, \n f\"{sanitized_repo_name}_filtered_folders.json\"\n )\n\n # Get custom include/exclude patterns from config\n include_patterns = self.config.include_patterns if self.config.include_patterns else None\n exclude_patterns = self.config.exclude_patterns if self.config.exclude_patterns else None\n \n parser = DependencyParser(\n self.config.repo_path,\n include_patterns=include_patterns,\n exclude_patterns=exclude_patterns,\n use_gitignore=self.config.use_gitignore,\n )\n\n filtered_folders = None\n # if os.path.exists(filtered_folders_path):\n # logger.debug(f\"Loading filtered folders from {filtered_folders_path}\")\n # filtered_folders = file_manager.load_json(filtered_folders_path)\n # else:\n # # Parse repository\n # filtered_folders = parser.filter_folders()\n # # Save filtered folders\n # file_manager.save_json(filtered_folders, filtered_folders_path)\n\n # Parse repository\n components = parser.parse_repository(filtered_folders)\n \n # Save dependency graph\n parser.save_dependency_graph(dependency_graph_path)\n \n # Build graph for traversal\n graph = build_graph_from_components(components)\n \n # Get leaf nodes\n leaf_nodes = get_leaf_nodes(graph, components)\n\n # check if leaf_nodes are in components, only keep the ones that are in components\n # and type is one of the following: class, interface, struct (or function when\n # functions carry the architecture β€” see leaf_selection)\n valid_types = compute_valid_leaf_types(components)\n keep_leaf_nodes = filter_leaf_nodes(leaf_nodes, components, valid_types)\n\n return components, keep_leaf_nodes", - "start_line": 13, - "end_line": 80, - "has_docstring": true, - "docstring": "Handles dependency analysis and graph building.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class DependencyGraphBuilder", - "component_id": "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py::DependencyGraphBuilder", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py::DependencyGraphBuilder.__init__": { - "id": "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py::DependencyGraphBuilder.__init__", - "name": "DependencyGraphBuilder.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py", - "relative_path": "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py", - "depends_on": [], - "source_code": " def __init__(self, config: Config):\n self.config = config", - "start_line": 16, - "end_line": 17, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "config" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DependencyGraphBuilder", - "display_name": "method DependencyGraphBuilder.__init__", - "component_id": "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py::DependencyGraphBuilder.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py::DependencyGraphBuilder.build_dependency_graph": { - "id": "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py::DependencyGraphBuilder.build_dependency_graph", - "name": "DependencyGraphBuilder.build_dependency_graph", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py", - "relative_path": "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/topo_sort.py::build_graph_from_components", - "codewiki/src/be/dependency_analyzer/leaf_selection.py::filter_leaf_nodes", - "codewiki/src/be/dependency_analyzer/topo_sort.py::get_leaf_nodes", - "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser.save_dependency_graph", - "codewiki/src/be/dependency_analyzer/leaf_selection.py::compute_valid_leaf_types", - "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser", - "codewiki/src/be/dependency_analyzer/ast_parser.py::DependencyParser.parse_repository" - ], - "source_code": " def build_dependency_graph(self) -> tuple[Dict[str, Any], List[str]]:\n \"\"\"\n Build and save dependency graph, returning components and leaf nodes.\n \n Returns:\n Tuple of (components, leaf_nodes)\n \"\"\"\n # Ensure output directory exists\n file_manager.ensure_directory(self.config.dependency_graph_dir)\n\n # Prepare dependency graph path\n repo_name = os.path.basename(os.path.normpath(self.config.repo_path))\n sanitized_repo_name = ''.join(c if c.isalnum() else '_' for c in repo_name)\n dependency_graph_path = os.path.join(\n self.config.dependency_graph_dir, \n f\"{sanitized_repo_name}_dependency_graph.json\"\n )\n filtered_folders_path = os.path.join(\n self.config.dependency_graph_dir, \n f\"{sanitized_repo_name}_filtered_folders.json\"\n )\n\n # Get custom include/exclude patterns from config\n include_patterns = self.config.include_patterns if self.config.include_patterns else None\n exclude_patterns = self.config.exclude_patterns if self.config.exclude_patterns else None\n \n parser = DependencyParser(\n self.config.repo_path,\n include_patterns=include_patterns,\n exclude_patterns=exclude_patterns,\n use_gitignore=self.config.use_gitignore,\n )\n\n filtered_folders = None\n # if os.path.exists(filtered_folders_path):\n # logger.debug(f\"Loading filtered folders from {filtered_folders_path}\")\n # filtered_folders = file_manager.load_json(filtered_folders_path)\n # else:\n # # Parse repository\n # filtered_folders = parser.filter_folders()\n # # Save filtered folders\n # file_manager.save_json(filtered_folders, filtered_folders_path)\n\n # Parse repository\n components = parser.parse_repository(filtered_folders)\n \n # Save dependency graph\n parser.save_dependency_graph(dependency_graph_path)\n \n # Build graph for traversal\n graph = build_graph_from_components(components)\n \n # Get leaf nodes\n leaf_nodes = get_leaf_nodes(graph, components)\n\n # check if leaf_nodes are in components, only keep the ones that are in components\n # and type is one of the following: class, interface, struct (or function when\n # functions carry the architecture β€” see leaf_selection)\n valid_types = compute_valid_leaf_types(components)\n keep_leaf_nodes = filter_leaf_nodes(leaf_nodes, components, valid_types)\n\n return components, keep_leaf_nodes", - "start_line": 19, - "end_line": 80, - "has_docstring": true, - "docstring": "Build and save dependency graph, returning components and leaf nodes.\n\nReturns:\n Tuple of (components, leaf_nodes)", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DependencyGraphBuilder", - "display_name": "method DependencyGraphBuilder.build_dependency_graph", - "component_id": "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py::DependencyGraphBuilder.build_dependency_graph", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/leaf_selection.py::compute_valid_leaf_types": { - "id": "codewiki/src/be/dependency_analyzer/leaf_selection.py::compute_valid_leaf_types", - "name": "compute_valid_leaf_types", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/leaf_selection.py", - "relative_path": "codewiki/src/be/dependency_analyzer/leaf_selection.py", - "depends_on": [], - "source_code": "def compute_valid_leaf_types(components: Dict[str, Node]) -> Set[str]:\n \"\"\"\n Determine which component types qualify as leaf nodes.\n\n Classes/interfaces/structs always qualify. Free functions qualify when\n they carry the architecture: pure-C style repos with no OOP components,\n or mixed repos (C/C++/Go) where OOP components are a small minority.\n OOP-heavy repos keep the class-only behavior so node counts stay bounded.\n \"\"\"\n n_oop = 0\n n_func = 0\n for comp in components.values():\n if comp.component_type in OOP_TYPES:\n n_oop += 1\n elif comp.component_type == \"function\":\n n_func += 1\n\n valid_types = set(OOP_TYPES)\n include_functions = (\n n_oop == 0\n or (n_oop < MIN_OOP_COMPONENTS and n_func > n_oop)\n or (n_func > 0 and n_oop / (n_oop + n_func) < OOP_MINORITY_RATIO)\n )\n if include_functions:\n valid_types.add(\"function\")\n if n_oop > 0:\n logger.info(\n \"Including function components as leaf candidates: %d class/interface/struct \"\n \"components vs %d functions β€” functions carry most of this codebase.\",\n n_oop,\n n_func,\n )\n return valid_types", - "start_line": 20, - "end_line": 52, - "has_docstring": true, - "docstring": "Determine which component types qualify as leaf nodes.\n\nClasses/interfaces/structs always qualify. Free functions qualify when\nthey carry the architecture: pure-C style repos with no OOP components,\nor mixed repos (C/C++/Go) where OOP components are a small minority.\nOOP-heavy repos keep the class-only behavior so node counts stay bounded.", - "parameters": [ - "components" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function compute_valid_leaf_types", - "component_id": "codewiki/src/be/dependency_analyzer/leaf_selection.py::compute_valid_leaf_types", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/leaf_selection.py::filter_leaf_nodes": { - "id": "codewiki/src/be/dependency_analyzer/leaf_selection.py::filter_leaf_nodes", - "name": "filter_leaf_nodes", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/leaf_selection.py", - "relative_path": "codewiki/src/be/dependency_analyzer/leaf_selection.py", - "depends_on": [ - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": "def filter_leaf_nodes(\n leaf_nodes,\n components: Dict[str, Node],\n valid_types: Set[str],\n) -> List[str]:\n \"\"\"Keep leaf nodes that are known components of a valid type.\"\"\"\n keep_leaf_nodes = []\n for leaf_node in leaf_nodes:\n # Skip any leaf nodes that are clearly error strings or invalid identifiers\n if not isinstance(leaf_node, str) or leaf_node.strip() == \"\" or any(err_keyword in leaf_node.lower() for err_keyword in ['error', 'exception', 'failed', 'invalid']):\n logger.debug(f\"Skipping invalid leaf node identifier: '{leaf_node}'\")\n continue\n\n if leaf_node in components:\n if components[leaf_node].component_type in valid_types:\n keep_leaf_nodes.append(leaf_node)\n\n return keep_leaf_nodes", - "start_line": 55, - "end_line": 72, - "has_docstring": true, - "docstring": "Keep leaf nodes that are known components of a valid type.", - "parameters": [ - "leaf_nodes", - "components", - "valid_types" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function filter_leaf_nodes", - "component_id": "codewiki/src/be/dependency_analyzer/leaf_selection.py::filter_leaf_nodes", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/models/analysis.py::AnalysisResult": { - "id": "codewiki/src/be/dependency_analyzer/models/analysis.py::AnalysisResult", - "name": "AnalysisResult", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/models/analysis.py", - "relative_path": "codewiki/src/be/dependency_analyzer/models/analysis.py", - "depends_on": [], - "source_code": "class AnalysisResult(BaseModel):\n \"\"\"Result of analyzing a repository\"\"\"\n\n repository: Repository\n functions: List[Node]\n relationships: List[CallRelationship]\n file_tree: Dict[str, Any]\n summary: Dict[str, Any]\n visualization: Dict[str, Any] = {}\n readme_content: Optional[str] = None", - "start_line": 6, - "end_line": 15, - "has_docstring": true, - "docstring": "Result of analyzing a repository", - "parameters": null, - "node_type": "class", - "base_classes": [ - "BaseModel" - ], - "class_name": null, - "display_name": "class AnalysisResult", - "component_id": "codewiki/src/be/dependency_analyzer/models/analysis.py::AnalysisResult", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/models/analysis.py::NodeSelection": { - "id": "codewiki/src/be/dependency_analyzer/models/analysis.py::NodeSelection", - "name": "NodeSelection", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/models/analysis.py", - "relative_path": "codewiki/src/be/dependency_analyzer/models/analysis.py", - "depends_on": [], - "source_code": "class NodeSelection(BaseModel):\n \"\"\"Selected nodes for partial export\"\"\"\n\n selected_nodes: List[str] = []\n include_relationships: bool = True\n custom_names: Dict[str, str] = {}", - "start_line": 18, - "end_line": 23, - "has_docstring": true, - "docstring": "Selected nodes for partial export", - "parameters": null, - "node_type": "class", - "base_classes": [ - "BaseModel" - ], - "class_name": null, - "display_name": "class NodeSelection", - "component_id": "codewiki/src/be/dependency_analyzer/models/analysis.py::NodeSelection", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/models/core.py::Node": { - "id": "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "name": "Node", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/models/core.py", - "relative_path": "codewiki/src/be/dependency_analyzer/models/core.py", - "depends_on": [], - "source_code": "class Node(BaseModel):\n id: str\n\n name: str\n \n component_type: str\n \n file_path: str\n \n relative_path: str\n \n depends_on: Set[str] = set()\n \n source_code: Optional[str] = None\n \n start_line: int = 0\n\n end_line: int = 0\n \n has_docstring: bool = False\n \n docstring: str = \"\"\n \n parameters: Optional[List[str]] = None\n\n node_type: Optional[str] = None \n\n base_classes: Optional[List[str]] = None\n\n class_name: Optional[str] = None\n\n display_name: Optional[str] = None\n\n component_id: Optional[str] = None\n\n language: Optional[str] = None\n\n qualified_name: Optional[str] = None\n\n def get_display_name(self) -> str:\n return self.display_name or self.name", - "start_line": 7, - "end_line": 47, - "has_docstring": false, - "docstring": "", - "parameters": null, - "node_type": "class", - "base_classes": [ - "BaseModel" - ], - "class_name": null, - "display_name": "class Node", - "component_id": "codewiki/src/be/dependency_analyzer/models/core.py::Node", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/models/core.py::Node.get_display_name": { - "id": "codewiki/src/be/dependency_analyzer/models/core.py::Node.get_display_name", - "name": "Node.get_display_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/models/core.py", - "relative_path": "codewiki/src/be/dependency_analyzer/models/core.py", - "depends_on": [], - "source_code": " def get_display_name(self) -> str:\n return self.display_name or self.name", - "start_line": 46, - "end_line": 47, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "Node", - "display_name": "method Node.get_display_name", - "component_id": "codewiki/src/be/dependency_analyzer/models/core.py::Node.get_display_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship": { - "id": "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "name": "CallRelationship", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/models/core.py", - "relative_path": "codewiki/src/be/dependency_analyzer/models/core.py", - "depends_on": [], - "source_code": "class CallRelationship(BaseModel):\n caller: str\n\n callee: str\n\n call_line: Optional[int] = None\n\n is_resolved: bool = False", - "start_line": 50, - "end_line": 57, - "has_docstring": false, - "docstring": "", - "parameters": null, - "node_type": "class", - "base_classes": [ - "BaseModel" - ], - "class_name": null, - "display_name": "class CallRelationship", - "component_id": "codewiki/src/be/dependency_analyzer/models/core.py::CallRelationship", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/models/core.py::Repository": { - "id": "codewiki/src/be/dependency_analyzer/models/core.py::Repository", - "name": "Repository", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/models/core.py", - "relative_path": "codewiki/src/be/dependency_analyzer/models/core.py", - "depends_on": [], - "source_code": "class Repository(BaseModel):\n url: str\n\n name: str\n\n clone_path: str\n \n analysis_id: str", - "start_line": 60, - "end_line": 67, - "has_docstring": false, - "docstring": "", - "parameters": null, - "node_type": "class", - "base_classes": [ - "BaseModel" - ], - "class_name": null, - "display_name": "class Repository", - "component_id": "codewiki/src/be/dependency_analyzer/models/core.py::Repository", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/topo_sort.py::detect_cycles": { - "id": "codewiki/src/be/dependency_analyzer/topo_sort.py::detect_cycles", - "name": "detect_cycles", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/topo_sort.py", - "relative_path": "codewiki/src/be/dependency_analyzer/topo_sort.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/mcp/session.py::SessionStore.remove" - ], - "source_code": "def detect_cycles(graph: Dict[str, Set[str]]) -> List[List[str]]:\n \"\"\"\n Detect cycles in a dependency graph using Tarjan's algorithm to find\n strongly connected components.\n \n Args:\n graph: A dependency graph represented as adjacency lists\n (node -> set of dependencies)\n \n Returns:\n A list of lists, where each inner list contains the nodes in a cycle\n \"\"\"\n # Implementation of Tarjan's algorithm\n index_counter = [0]\n index = {} # node -> index\n lowlink = {} # node -> lowlink value\n onstack = set() # nodes currently on the stack\n stack = [] # stack of nodes\n result = [] # list of cycles (strongly connected components)\n \n def strongconnect(node):\n # Set the depth index for node\n index[node] = index_counter[0]\n lowlink[node] = index_counter[0]\n index_counter[0] += 1\n stack.append(node)\n onstack.add(node)\n \n # Consider successors\n for successor in graph.get(node, set()):\n if successor not in index:\n # Successor has not yet been visited; recurse on it\n strongconnect(successor)\n lowlink[node] = min(lowlink[node], lowlink[successor])\n elif successor in onstack:\n # Successor is on the stack and hence in the current SCC\n lowlink[node] = min(lowlink[node], index[successor])\n \n # If node is a root node, pop the stack and generate an SCC\n if lowlink[node] == index[node]:\n # Start a new strongly connected component\n scc = []\n while True:\n successor = stack.pop()\n onstack.remove(successor)\n scc.append(successor)\n if successor == node:\n break\n \n # Only include SCCs with more than one node (actual cycles)\n if len(scc) > 1:\n result.append(scc)\n \n # Visit each node\n for node in graph:\n if node not in index:\n strongconnect(node)\n \n return result", - "start_line": 23, - "end_line": 81, - "has_docstring": true, - "docstring": "Detect cycles in a dependency graph using Tarjan's algorithm to find\nstrongly connected components.\n\nArgs:\n graph: A dependency graph represented as adjacency lists\n (node -> set of dependencies)\n\nReturns:\n A list of lists, where each inner list contains the nodes in a cycle", - "parameters": [ - "graph" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function detect_cycles", - "component_id": "codewiki/src/be/dependency_analyzer/topo_sort.py::detect_cycles", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/topo_sort.py::resolve_cycles": { - "id": "codewiki/src/be/dependency_analyzer/topo_sort.py::resolve_cycles", - "name": "resolve_cycles", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/topo_sort.py", - "relative_path": "codewiki/src/be/dependency_analyzer/topo_sort.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/topo_sort.py::detect_cycles", - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": "def resolve_cycles(graph: Dict[str, Set[str]]) -> Dict[str, Set[str]]:\n \"\"\"\n Resolve cycles in a dependency graph by identifying strongly connected\n components and breaking cycles.\n \n Args:\n graph: A dependency graph represented as adjacency lists\n (node -> set of dependencies)\n \n Returns:\n A new acyclic graph with the same nodes but with cycles broken\n \"\"\"\n # Detect cycles (SCCs)\n cycles = detect_cycles(graph)\n \n if not cycles:\n logger.debug(\"No cycles detected in the dependency graph\")\n return graph\n \n logger.debug(f\"Detected {len(cycles)} cycles in the dependency graph\")\n \n # Create a copy of the graph to modify\n new_graph = {node: deps.copy() for node, deps in graph.items()}\n \n # Process each cycle\n for i, cycle in enumerate(cycles):\n logger.debug(f\"Cycle {i+1}: {' -> '.join(cycle)}\")\n \n # Strategy: Break the cycle by removing the \"weakest\" dependency\n # Here, we just arbitrarily remove the last edge to make the graph acyclic\n # In a real-world scenario, you might use heuristics to determine which edge to break\n # For example, removing edges between different modules before edges within the same module\n for j in range(len(cycle) - 1):\n current = cycle[j]\n next_node = cycle[j + 1]\n \n if next_node in new_graph[current]:\n logger.debug(f\"Breaking cycle by removing dependency: {current} -> {next_node}\")\n new_graph[current].remove(next_node)\n break\n \n return new_graph", - "start_line": 83, - "end_line": 124, - "has_docstring": true, - "docstring": "Resolve cycles in a dependency graph by identifying strongly connected\ncomponents and breaking cycles.\n\nArgs:\n graph: A dependency graph represented as adjacency lists\n (node -> set of dependencies)\n\nReturns:\n A new acyclic graph with the same nodes but with cycles broken", - "parameters": [ - "graph" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function resolve_cycles", - "component_id": "codewiki/src/be/dependency_analyzer/topo_sort.py::resolve_cycles", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/topo_sort.py::topological_sort": { - "id": "codewiki/src/be/dependency_analyzer/topo_sort.py::topological_sort", - "name": "topological_sort", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/topo_sort.py", - "relative_path": "codewiki/src/be/dependency_analyzer/topo_sort.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/topo_sort.py::resolve_cycles" - ], - "source_code": "def topological_sort(graph: Dict[str, Set[str]]) -> List[str]:\n \"\"\"\n Perform a topological sort on a dependency graph.\n \n Args:\n graph: A dependency graph represented as adjacency lists\n (node -> set of dependencies)\n \n Returns:\n A list of nodes in topological order (dependencies first)\n \"\"\"\n # First, check for and resolve cycles\n acyclic_graph = resolve_cycles(graph)\n \n # Initialize in-degree counter for all nodes\n in_degree = {node: 0 for node in acyclic_graph}\n \n # Count in-degrees\n for node, dependencies in acyclic_graph.items():\n for dep in dependencies:\n if dep in in_degree:\n in_degree[dep] += 1\n \n # Queue of nodes with no dependencies (in-degree of 0)\n queue = deque([node for node, degree in in_degree.items() if degree == 0])\n \n # Result list to store the topological order\n result = []\n \n # Process nodes in topological order\n while queue:\n node = queue.popleft()\n result.append(node)\n \n # Reduce in-degree for each node that depends on the current node\n for dependent, deps in acyclic_graph.items():\n if node in deps:\n in_degree[dependent] -= 1\n if in_degree[dependent] == 0:\n queue.append(dependent)\n \n # Check if the sort was successful (all nodes included)\n if len(result) != len(acyclic_graph):\n logger.warning(\"Topological sort failed: graph has cycles that weren't resolved\")\n # Return all nodes in some order to avoid breaking the process\n return list(acyclic_graph.keys())\n \n # Reverse the result to get dependencies first\n return result[::-1]", - "start_line": 126, - "end_line": 174, - "has_docstring": true, - "docstring": "Perform a topological sort on a dependency graph.\n\nArgs:\n graph: A dependency graph represented as adjacency lists\n (node -> set of dependencies)\n\nReturns:\n A list of nodes in topological order (dependencies first)", - "parameters": [ - "graph" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function topological_sort", - "component_id": "codewiki/src/be/dependency_analyzer/topo_sort.py::topological_sort", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/topo_sort.py::dependency_first_dfs": { - "id": "codewiki/src/be/dependency_analyzer/topo_sort.py::dependency_first_dfs", - "name": "dependency_first_dfs", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/topo_sort.py", - "relative_path": "codewiki/src/be/dependency_analyzer/topo_sort.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/dependency_analyzer/topo_sort.py::resolve_cycles" - ], - "source_code": "def dependency_first_dfs(graph: Dict[str, Set[str]]) -> List[str]:\n \"\"\"\n Perform a depth-first traversal of the dependency graph, starting from root nodes\n that have no dependencies.\n \n The graph uses natural dependency direction:\n - If A depends on B, the graph has an edge A β†’ B\n - This means an edge from X to Y represents \"X depends on Y\"\n - Root nodes (nodes with no incoming edges/dependencies) are processed first,\n followed by nodes that depend on them\n \n Args:\n graph: A dependency graph with natural direction (Aβ†’B if A depends on B)\n \n Returns:\n A list of nodes in an order where dependencies come before their dependents\n \"\"\"\n # First, resolve cycles to ensure we have a DAG\n acyclic_graph = resolve_cycles(graph)\n \n # Find root nodes (nodes with no dependencies)\n root_nodes = []\n # Create a reverse graph to easily check if a node has incoming edges\n has_incoming_edge = {node: False for node in acyclic_graph}\n \n for node, deps in acyclic_graph.items():\n for dep in deps:\n has_incoming_edge[dep] = True\n \n # Nodes with no incoming edges are root nodes\n for node in acyclic_graph:\n if not has_incoming_edge.get(node, False) and node in acyclic_graph:\n root_nodes.append(node)\n \n if not root_nodes:\n logger.warning(\"No root nodes found in the graph, using arbitrary starting point\")\n root_nodes = list(acyclic_graph.keys())[:1] # Use the first node as starting point\n \n # Track visited nodes\n visited = set()\n result = []\n \n # DFS function that processes dependencies first\n def dfs(node):\n if node in visited:\n return\n visited.add(node)\n \n # Visit all dependencies first\n for dep in sorted(acyclic_graph.get(node, set())):\n dfs(dep)\n \n # Add this node to the result after all its dependencies\n result.append(node)\n \n # Start DFS from each root node\n for root in sorted(root_nodes):\n dfs(root)\n \n # Check if all nodes were visited\n if len(result) != len(acyclic_graph):\n # Some nodes weren't visited - try to visit remaining nodes\n for node in sorted(acyclic_graph.keys()):\n if node not in visited:\n dfs(node)\n \n return result", - "start_line": 176, - "end_line": 242, - "has_docstring": true, - "docstring": "Perform a depth-first traversal of the dependency graph, starting from root nodes\nthat have no dependencies.\n\nThe graph uses natural dependency direction:\n- If A depends on B, the graph has an edge A β†’ B\n- This means an edge from X to Y represents \"X depends on Y\"\n- Root nodes (nodes with no incoming edges/dependencies) are processed first,\n followed by nodes that depend on them\n\nArgs:\n graph: A dependency graph with natural direction (Aβ†’B if A depends on B)\n\nReturns:\n A list of nodes in an order where dependencies come before their dependents", - "parameters": [ - "graph" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function dependency_first_dfs", - "component_id": "codewiki/src/be/dependency_analyzer/topo_sort.py::dependency_first_dfs", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/topo_sort.py::build_graph_from_components": { - "id": "codewiki/src/be/dependency_analyzer/topo_sort.py::build_graph_from_components", - "name": "build_graph_from_components", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/topo_sort.py", - "relative_path": "codewiki/src/be/dependency_analyzer/topo_sort.py", - "depends_on": [], - "source_code": "def build_graph_from_components(components: Dict[str, Any]) -> Dict[str, Set[str]]:\n \"\"\"\n Build a dependency graph from a collection of code components.\n \n The graph uses the natural dependency direction:\n - If A depends on B, we create an edge A β†’ B\n - This means an edge from node X to node Y represents \"X depends on Y\"\n - Root nodes (nodes with no dependencies) are components that don't depend on anything\n \n Args:\n components: A dictionary of code components, where each component\n has a 'depends_on' attribute\n \n Returns:\n A dependency graph with natural dependency direction\n \"\"\"\n graph = {}\n \n for comp_id, component in components.items():\n # Initialize the node's adjacency list\n if comp_id not in graph:\n graph[comp_id] = set()\n \n # Add dependencies\n for dep_id in component.depends_on:\n # Only include dependencies that are actual components in our repository\n if dep_id in components:\n graph[comp_id].add(dep_id)\n \n return graph ", - "start_line": 244, - "end_line": 273, - "has_docstring": true, - "docstring": "Build a dependency graph from a collection of code components.\n\nThe graph uses the natural dependency direction:\n- If A depends on B, we create an edge A β†’ B\n- This means an edge from node X to node Y represents \"X depends on Y\"\n- Root nodes (nodes with no dependencies) are components that don't depend on anything\n\nArgs:\n components: A dictionary of code components, where each component\n has a 'depends_on' attribute\n\nReturns:\n A dependency graph with natural dependency direction", - "parameters": [ - "components" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function build_graph_from_components", - "component_id": "codewiki/src/be/dependency_analyzer/topo_sort.py::build_graph_from_components", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/topo_sort.py::get_leaf_nodes": { - "id": "codewiki/src/be/dependency_analyzer/topo_sort.py::get_leaf_nodes", - "name": "get_leaf_nodes", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/topo_sort.py", - "relative_path": "codewiki/src/be/dependency_analyzer/topo_sort.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/topo_sort.py::resolve_cycles", - "codewiki/src/be/dependency_analyzer/leaf_selection.py::compute_valid_leaf_types", - "codewiki/src/be/dependency_analyzer/leaf_selection.py::filter_leaf_nodes", - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": "def get_leaf_nodes(graph: Dict[str, Set[str]], components: Dict[str, Node]) -> List[str]:\n \"\"\"\n Find leaf nodes (nodes that no other nodes depend on) and build dependency trees\n showing the full dependency chain from each leaf back to the ultimate dependencies.\n \n The graph uses natural dependency direction:\n - If A depends on B, the graph has an edge A β†’ B\n - Leaf nodes are nodes that appear in no other node's dependency set\n - Each tree shows the dependency chain: leaf β†’ its dependencies β†’ their dependencies, etc.\n \n Args:\n graph: A dependency graph with natural direction (Aβ†’B if A depends on B)\n \n Returns:\n A list of leaf nodes\n \"\"\"\n # First, resolve cycles to ensure we have a DAG\n acyclic_graph = resolve_cycles(graph)\n \n # Find leaf nodes (nodes that no other nodes depend on)\n leaf_nodes = set(acyclic_graph.keys())\n\n valid_types = compute_valid_leaf_types(components)\n\n def concise_node(leaf_nodes: Set[str]) -> Set[str]:\n concise_leaf_nodes = set()\n for node in leaf_nodes:\n if node.endswith(\"__init__\"):\n # replace by class name\n concise_leaf_nodes.add(node.replace(\".__init__\", \"\"))\n else:\n concise_leaf_nodes.add(node)\n\n return filter_leaf_nodes(concise_leaf_nodes, components, valid_types)\n\n concise_leaf_nodes = concise_node(leaf_nodes)\n if len(concise_leaf_nodes) >= LEAF_REDUCTION_THRESHOLD:\n logger.debug(f\"Leaf nodes are too many ({len(concise_leaf_nodes)}), removing dependencies of other nodes\")\n # Remove nodes that are dependencies of other nodes\n for node, deps in acyclic_graph.items():\n for dep in deps:\n leaf_nodes.discard(dep)\n \n concise_leaf_nodes = concise_node(leaf_nodes)\n \n if not leaf_nodes:\n logger.warning(\"No leaf nodes found in the graph\")\n return []\n \n return concise_leaf_nodes ", - "start_line": 276, - "end_line": 325, - "has_docstring": true, - "docstring": "Find leaf nodes (nodes that no other nodes depend on) and build dependency trees\nshowing the full dependency chain from each leaf back to the ultimate dependencies.\n\nThe graph uses natural dependency direction:\n- If A depends on B, the graph has an edge A β†’ B\n- Leaf nodes are nodes that appear in no other node's dependency set\n- Each tree shows the dependency chain: leaf β†’ its dependencies β†’ their dependencies, etc.\n\nArgs:\n graph: A dependency graph with natural direction (Aβ†’B if A depends on B)\n\nReturns:\n A list of leaf nodes", - "parameters": [ - "graph", - "components" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function get_leaf_nodes", - "component_id": "codewiki/src/be/dependency_analyzer/topo_sort.py::get_leaf_nodes", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/utils/external_symbols.py::is_macro_name": { - "id": "codewiki/src/be/dependency_analyzer/utils/external_symbols.py::is_macro_name", - "name": "is_macro_name", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/utils/external_symbols.py", - "relative_path": "codewiki/src/be/dependency_analyzer/utils/external_symbols.py", - "depends_on": [], - "source_code": "def is_macro_name(token: str) -> bool:\n \"\"\"Heuristic: an ALL_CAPS identifier (with an underscore or 4+ chars) reads\n as a macro by C/C++ naming convention, not a function or type. Macros are\n never extracted as components, so a call to one can never resolve to a\n project function. This is consulted only after project resolution has had\n its chance, so a genuine ALL_CAPS project component still matches first.\"\"\"\n if not token or not _ALL_CAPS_RE.match(token):\n return False\n return (len(token) >= 4 or \"_\" in token) and token not in NON_MACRO_UPPER", - "start_line": 635, - "end_line": 643, - "has_docstring": true, - "docstring": "Heuristic: an ALL_CAPS identifier (with an underscore or 4+ chars) reads\nas a macro by C/C++ naming convention, not a function or type. Macros are\nnever extracted as components, so a call to one can never resolve to a\nproject function. This is consulted only after project resolution has had\nits chance, so a genuine ALL_CAPS project component still matches first.", - "parameters": [ - "token" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function is_macro_name", - "component_id": "codewiki/src/be/dependency_analyzer/utils/external_symbols.py::is_macro_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/utils/external_symbols.py::normalize_symbol": { - "id": "codewiki/src/be/dependency_analyzer/utils/external_symbols.py::normalize_symbol", - "name": "normalize_symbol", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/utils/external_symbols.py", - "relative_path": "codewiki/src/be/dependency_analyzer/utils/external_symbols.py", - "depends_on": [], - "source_code": "def normalize_symbol(symbol: str) -> str:\n \"\"\"Return a comparable symbol name from an ID, qualified name, or call target.\"\"\"\n if not symbol:\n return \"\"\n normalized = symbol.strip()\n if \"::\" in normalized and not normalized.startswith(\"std::\"):\n normalized = normalized.split(\"::\")[-1]\n normalized = normalized.split(\"(\")[0]\n normalized = normalized.strip(\"&*[] \")\n if \".\" in normalized:\n normalized = normalized.split(\".\")[-1]\n if \"::\" in normalized:\n normalized = normalized.split(\"::\")[-1]\n return normalized", - "start_line": 646, - "end_line": 659, - "has_docstring": true, - "docstring": "Return a comparable symbol name from an ID, qualified name, or call target.", - "parameters": [ - "symbol" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function normalize_symbol", - "component_id": "codewiki/src/be/dependency_analyzer/utils/external_symbols.py::normalize_symbol", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/utils/external_symbols.py::is_external_symbol": { - "id": "codewiki/src/be/dependency_analyzer/utils/external_symbols.py::is_external_symbol", - "name": "is_external_symbol", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/utils/external_symbols.py", - "relative_path": "codewiki/src/be/dependency_analyzer/utils/external_symbols.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/utils/external_symbols.py::normalize_symbol" - ], - "source_code": "def is_external_symbol(language: str | None, symbol: str) -> bool:\n \"\"\"Check whether a callee is a known external/runtime symbol.\n\n Classification is layered, from most general to most specific:\n 1. Namespace prefix rules (``java.``/``javax.``/``std::``/...), which hold\n for any project regardless of which third-party libraries it uses.\n 2. The curated language standard-library sets, which encode only true\n language-level knowledge (libc, STL members, java.lang types).\n\n A dotted Java name that survives the prefix rules is qualified to some\n non-JDK package; whether that package belongs to the project is decided by\n the resolver's project-package check, not by simple-name matching here.\n \"\"\"\n if not symbol:\n return False\n\n if symbol.startswith((\"java.\", \"javax.\", \"jdk.\", \"sun.\")):\n return True\n if symbol.startswith(\"std::\"):\n return True\n\n if language == \"java\":\n if \".\" in symbol:\n return False\n return symbol in JAVA_EXTERNAL_SYMBOLS\n\n if language == \"csharp\":\n # `System.`/`Microsoft.` are kept inside the csharp branch rather than as\n # a global prefix rule (unlike `java.`): those reverse-DNS prefixes are\n # globally unambiguous, but another language can legitimately own a\n # `System.*` symbol. A dotted name that survives the prefix check is\n # qualified to some non-framework namespace; whether it belongs to the\n # project is decided by the resolver's namespace-origin check, not here.\n if symbol.startswith((\"System.\", \"Microsoft.\")):\n return True\n if \".\" in symbol:\n return False\n return symbol in CSHARP_EXTERNAL_SYMBOLS\n\n if language == \"python\":\n # Operate on the raw dotted symbol: the head identifies the module\n # (`os.path.relpath`, `logging.getLogger.debug`), which tail\n # normalization would destroy.\n if \".\" in symbol:\n return symbol.split(\".\")[0] in PYTHON_STDLIB_MODULES\n return symbol in PYTHON_BUILTINS or symbol in PYTHON_STDLIB_MODULES\n\n if language in (\"javascript\", \"typescript\"):\n if \".\" in symbol:\n head = symbol.split(\".\")[0]\n tail = symbol.rsplit(\".\", 1)[-1]\n return head in JS_TS_GLOBAL_OBJECTS or tail in JS_TS_PROTOTYPE_METHODS\n return symbol in JS_TS_GLOBAL_FUNCTIONS or symbol in JS_TS_GLOBAL_OBJECTS\n\n normalized = normalize_symbol(symbol)\n if language == \"cpp\":\n return normalized in CPP_EXTERNAL_SYMBOLS\n if language == \"c\":\n return normalized in C_EXTERNAL_SYMBOLS\n return False", - "start_line": 662, - "end_line": 721, - "has_docstring": true, - "docstring": "Check whether a callee is a known external/runtime symbol.\n\nClassification is layered, from most general to most specific:\n 1. Namespace prefix rules (``java.``/``javax.``/``std::``/...), which hold\n for any project regardless of which third-party libraries it uses.\n 2. The curated language standard-library sets, which encode only true\n language-level knowledge (libc, STL members, java.lang types).\n\nA dotted Java name that survives the prefix rules is qualified to some\nnon-JDK package; whether that package belongs to the project is decided by\nthe resolver's project-package check, not by simple-name matching here.", - "parameters": [ - "language", - "symbol" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function is_external_symbol", - "component_id": "codewiki/src/be/dependency_analyzer/utils/external_symbols.py::is_external_symbol", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter": { - "id": "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter", - "name": "ColoredFormatter", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/utils/logging_config.py", - "relative_path": "codewiki/src/be/dependency_analyzer/utils/logging_config.py", - "depends_on": [], - "source_code": "class ColoredFormatter(logging.Formatter):\n \"\"\"Custom formatter with colored output for better readability.\n \n This formatter adds colors to different log levels and components:\n - Log levels are colored based on severity\n - Timestamps are shown in blue\n - Module names are shown in magenta\n - Messages are shown in the default terminal color\n \"\"\"\n \n # Define colors for different log levels\n COLORS = {\n 'DEBUG': Fore.BLUE,\n 'INFO': Fore.CYAN,\n 'WARNING': Fore.YELLOW,\n 'ERROR': Fore.RED,\n 'CRITICAL': Fore.RED + Style.BRIGHT,\n }\n \n # Define colors for different components\n COMPONENT_COLORS = {\n 'timestamp': Fore.BLUE,\n 'module': Fore.MAGENTA,\n 'reset': Style.RESET_ALL,\n }\n \n def format(self, record):\n \"\"\"Format log record with colors.\"\"\"\n # Get the color for this log level\n level_color = self.COLORS.get(record.levelname, '')\n \n # Format timestamp\n timestamp = self.formatTime(record, '%H:%M:%S')\n colored_timestamp = f\"{self.COMPONENT_COLORS['timestamp']}[{timestamp}]{self.COMPONENT_COLORS['reset']}\"\n \n # Format log level with color\n colored_level = f\"{level_color}{record.levelname:8}{self.COMPONENT_COLORS['reset']}\"\n \n # Format the message with the same color as the log level\n message = record.getMessage()\n colored_message = f\"{level_color}{message}{self.COMPONENT_COLORS['reset']}\"\n \n # Combine all parts (without module name column)\n log_line = f\"{colored_timestamp} {colored_level} {colored_message}\"\n \n # Handle exceptions\n if record.exc_info:\n log_line += \"\\n\" + self.formatException(record.exc_info)\n \n return log_line", - "start_line": 35, - "end_line": 84, - "has_docstring": true, - "docstring": "Custom formatter with colored output for better readability.\n\nThis formatter adds colors to different log levels and components:\n- Log levels are colored based on severity\n- Timestamps are shown in blue\n- Module names are shown in magenta\n- Messages are shown in the default terminal color", - "parameters": null, - "node_type": "class", - "base_classes": [ - "logging.Formatter" - ], - "class_name": null, - "display_name": "class ColoredFormatter", - "component_id": "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter.format": { - "id": "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter.format", - "name": "ColoredFormatter.format", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/utils/logging_config.py", - "relative_path": "codewiki/src/be/dependency_analyzer/utils/logging_config.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def format(self, record):\n \"\"\"Format log record with colors.\"\"\"\n # Get the color for this log level\n level_color = self.COLORS.get(record.levelname, '')\n \n # Format timestamp\n timestamp = self.formatTime(record, '%H:%M:%S')\n colored_timestamp = f\"{self.COMPONENT_COLORS['timestamp']}[{timestamp}]{self.COMPONENT_COLORS['reset']}\"\n \n # Format log level with color\n colored_level = f\"{level_color}{record.levelname:8}{self.COMPONENT_COLORS['reset']}\"\n \n # Format the message with the same color as the log level\n message = record.getMessage()\n colored_message = f\"{level_color}{message}{self.COMPONENT_COLORS['reset']}\"\n \n # Combine all parts (without module name column)\n log_line = f\"{colored_timestamp} {colored_level} {colored_message}\"\n \n # Handle exceptions\n if record.exc_info:\n log_line += \"\\n\" + self.formatException(record.exc_info)\n \n return log_line", - "start_line": 61, - "end_line": 84, - "has_docstring": true, - "docstring": "Format log record with colors.", - "parameters": [ - "self", - "record" - ], - "node_type": "method", - "base_classes": null, - "class_name": "ColoredFormatter", - "display_name": "method ColoredFormatter.format", - "component_id": "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter.format", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::setup_logging": { - "id": "codewiki/src/be/dependency_analyzer/utils/logging_config.py::setup_logging", - "name": "setup_logging", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/utils/logging_config.py", - "relative_path": "codewiki/src/be/dependency_analyzer/utils/logging_config.py", - "depends_on": [ - "codewiki/cli/config_manager.py::ConfigManager.clear", - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter" - ], - "source_code": "def setup_logging(level=logging.INFO):\n \"\"\"\n Set up logging configuration with colored output.\n \n Args:\n level: Logging level (default: logging.INFO)\n \"\"\"\n # Create console handler\n console_handler = logging.StreamHandler(sys.stdout)\n console_handler.setLevel(level)\n \n # Set colored formatter\n colored_formatter = ColoredFormatter()\n console_handler.setFormatter(colored_formatter)\n \n # Configure root logger\n root_logger = logging.getLogger()\n root_logger.setLevel(level)\n \n # Remove existing handlers to avoid duplicates\n root_logger.handlers.clear()\n \n # Add our console handler\n root_logger.addHandler(console_handler)", - "start_line": 87, - "end_line": 110, - "has_docstring": true, - "docstring": "Set up logging configuration with colored output.\n\nArgs:\n level: Logging level (default: logging.INFO)", - "parameters": [ - "level" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function setup_logging", - "component_id": "codewiki/src/be/dependency_analyzer/utils/logging_config.py::setup_logging", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::setup_module_logging": { - "id": "codewiki/src/be/dependency_analyzer/utils/logging_config.py::setup_module_logging", - "name": "setup_module_logging", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/utils/logging_config.py", - "relative_path": "codewiki/src/be/dependency_analyzer/utils/logging_config.py", - "depends_on": [ - "codewiki/cli/config_manager.py::ConfigManager.clear", - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter" - ], - "source_code": "def setup_module_logging(module_name: str, level=logging.INFO):\n \"\"\"\n Set up logging for a specific module with colored output.\n \n Args:\n module_name: Name of the module to configure logging for\n level: Logging level (default: logging.INFO)\n \"\"\"\n logger = logging.getLogger(module_name)\n logger.setLevel(level)\n \n # Create console handler\n console_handler = logging.StreamHandler(sys.stdout)\n console_handler.setLevel(level)\n \n # Set colored formatter\n colored_formatter = ColoredFormatter()\n console_handler.setFormatter(colored_formatter)\n \n # Remove existing handlers\n logger.handlers.clear()\n \n # Add console handler\n logger.addHandler(console_handler)\n \n # Prevent propagation to avoid duplicate logs\n logger.propagate = False\n \n return logger", - "start_line": 113, - "end_line": 141, - "has_docstring": true, - "docstring": "Set up logging for a specific module with colored output.\n\nArgs:\n module_name: Name of the module to configure logging for\n level: Logging level (default: logging.INFO)", - "parameters": [ - "module_name", - "level" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function setup_module_logging", - "component_id": "codewiki/src/be/dependency_analyzer/utils/logging_config.py::setup_module_logging", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/utils/patterns.py::get_function_patterns_for_language": { - "id": "codewiki/src/be/dependency_analyzer/utils/patterns.py::get_function_patterns_for_language", - "name": "get_function_patterns_for_language", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/utils/patterns.py", - "relative_path": "codewiki/src/be/dependency_analyzer/utils/patterns.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": "def get_function_patterns_for_language(language: str) -> list:\n \"\"\"\n Get function definition patterns for a specific language.\n\n Args:\n language: Programming language name\n\n Returns:\n List of function definition patterns for the language\n \"\"\"\n return FUNCTION_DEFINITION_PATTERNS.get(\n language.lower(), FUNCTION_DEFINITION_PATTERNS[\"general\"]\n )", - "start_line": 460, - "end_line": 472, - "has_docstring": true, - "docstring": "Get function definition patterns for a specific language.\n\nArgs:\n language: Programming language name\n\nReturns:\n List of function definition patterns for the language", - "parameters": [ - "language" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function get_function_patterns_for_language", - "component_id": "codewiki/src/be/dependency_analyzer/utils/patterns.py::get_function_patterns_for_language", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/utils/patterns.py::is_entry_point_file": { - "id": "codewiki/src/be/dependency_analyzer/utils/patterns.py::is_entry_point_file", - "name": "is_entry_point_file", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/utils/patterns.py", - "relative_path": "codewiki/src/be/dependency_analyzer/utils/patterns.py", - "depends_on": [], - "source_code": "def is_entry_point_file(filename: str) -> bool:\n \"\"\"\n Check if a filename matches entry point patterns.\n\n Args:\n filename: Name of the file to check\n\n Returns:\n True if the file is likely an entry point\n \"\"\"\n filename_lower = filename.lower()\n\n # Exact match\n if filename_lower in ENTRY_POINT_PATTERNS:\n return True\n\n # Partial name matching for flexibility\n for pattern in ENTRY_POINT_NAME_PATTERNS:\n if pattern in filename_lower and any(\n ext in filename_lower for ext in [\".py\", \".js\", \".ts\", \".go\", \".rs\", \".c\", \".cpp\"]\n ):\n return True\n\n return False", - "start_line": 475, - "end_line": 498, - "has_docstring": true, - "docstring": "Check if a filename matches entry point patterns.\n\nArgs:\n filename: Name of the file to check\n\nReturns:\n True if the file is likely an entry point", - "parameters": [ - "filename" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function is_entry_point_file", - "component_id": "codewiki/src/be/dependency_analyzer/utils/patterns.py::is_entry_point_file", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/utils/patterns.py::is_entry_point_path": { - "id": "codewiki/src/be/dependency_analyzer/utils/patterns.py::is_entry_point_path", - "name": "is_entry_point_path", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/utils/patterns.py", - "relative_path": "codewiki/src/be/dependency_analyzer/utils/patterns.py", - "depends_on": [], - "source_code": "def is_entry_point_path(filepath: str) -> bool:\n \"\"\"\n Check if a file path matches entry point path patterns.\n\n Args:\n filepath: Full path of the file to check\n\n Returns:\n True if the path suggests an entry point\n \"\"\"\n filepath_lower = filepath.lower()\n\n for pattern in ENTRY_POINT_PATH_PATTERNS:\n if pattern in filepath_lower:\n return True\n\n return False", - "start_line": 501, - "end_line": 517, - "has_docstring": true, - "docstring": "Check if a file path matches entry point path patterns.\n\nArgs:\n filepath: Full path of the file to check\n\nReturns:\n True if the path suggests an entry point", - "parameters": [ - "filepath" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function is_entry_point_path", - "component_id": "codewiki/src/be/dependency_analyzer/utils/patterns.py::is_entry_point_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/utils/patterns.py::has_high_connectivity_potential": { - "id": "codewiki/src/be/dependency_analyzer/utils/patterns.py::has_high_connectivity_potential", - "name": "has_high_connectivity_potential", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/utils/patterns.py", - "relative_path": "codewiki/src/be/dependency_analyzer/utils/patterns.py", - "depends_on": [], - "source_code": "def has_high_connectivity_potential(filename: str, filepath: str) -> bool:\n \"\"\"\n Check if a file has high connectivity potential based on name and path.\n\n Args:\n filename: Name of the file\n filepath: Full path of the file\n\n Returns:\n True if the file likely has high connectivity\n \"\"\"\n filename_lower = filename.lower()\n filepath_lower = filepath.lower()\n\n # Check filename patterns\n if any(pattern in filename_lower for pattern in HIGH_CONNECTIVITY_PATTERNS):\n return True\n\n # Check filepath patterns\n if any(pattern in filepath_lower for pattern in HIGH_CONNECTIVITY_PATTERNS):\n return True\n\n # Check source directory patterns\n if any(pattern in filepath_lower for pattern in SOURCE_DIRECTORY_PATTERNS):\n return True\n\n return False", - "start_line": 520, - "end_line": 546, - "has_docstring": true, - "docstring": "Check if a file has high connectivity potential based on name and path.\n\nArgs:\n filename: Name of the file\n filepath: Full path of the file\n\nReturns:\n True if the file likely has high connectivity", - "parameters": [ - "filename", - "filepath" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function has_high_connectivity_potential", - "component_id": "codewiki/src/be/dependency_analyzer/utils/patterns.py::has_high_connectivity_potential", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/utils/patterns.py::is_critical_function": { - "id": "codewiki/src/be/dependency_analyzer/utils/patterns.py::is_critical_function", - "name": "is_critical_function", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/utils/patterns.py", - "relative_path": "codewiki/src/be/dependency_analyzer/utils/patterns.py", - "depends_on": [], - "source_code": "def is_critical_function(func_name: str, code_snippet: Optional[str] = None) -> bool:\n \"\"\"\n Check if a function is critical based on name and code patterns.\n\n Args:\n func_name: Name of the function\n code_snippet: Optional code snippet to analyze\n\n Returns:\n True if the function is considered critical\n \"\"\"\n # Check critical function names\n if func_name.lower() in CRITICAL_FUNCTION_NAMES:\n return True\n\n # Check export patterns in code snippet\n if code_snippet:\n snippet_lower = code_snippet.lower()\n if any(pattern in snippet_lower for pattern in EXPORT_PATTERNS):\n return True\n\n return False", - "start_line": 549, - "end_line": 570, - "has_docstring": true, - "docstring": "Check if a function is critical based on name and code patterns.\n\nArgs:\n func_name: Name of the function\n code_snippet: Optional code snippet to analyze\n\nReturns:\n True if the function is considered critical", - "parameters": [ - "func_name", - "code_snippet" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function is_critical_function", - "component_id": "codewiki/src/be/dependency_analyzer/utils/patterns.py::is_critical_function", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/utils/patterns.py::find_fallback_entry_points": { - "id": "codewiki/src/be/dependency_analyzer/utils/patterns.py::find_fallback_entry_points", - "name": "find_fallback_entry_points", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/utils/patterns.py", - "relative_path": "codewiki/src/be/dependency_analyzer/utils/patterns.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/utils/patterns.py::is_entry_point_path" - ], - "source_code": "def find_fallback_entry_points(code_files: List[Dict], max_files: int = 5) -> List[Dict]:\n \"\"\"\n Find fallback entry points when standard patterns don't match.\n\n Args:\n code_files: List of all code files\n max_files: Maximum number of fallback files to return\n\n Returns:\n List of files that could serve as entry points\n \"\"\"\n fallback_files = []\n\n # Try fallback name patterns\n for file_info in code_files:\n filename = file_info[\"name\"].lower()\n filepath = file_info[\"path\"].lower()\n\n # Check for any main-like files\n if any(pattern in filename for pattern in [\"main\", \"app\", \"server\", \"start\", \"index\"]):\n fallback_files.append(file_info)\n\n # Check for entry point paths\n elif is_entry_point_path(filepath):\n fallback_files.append(file_info)\n\n # If still nothing, try files in root or common directories\n if not fallback_files:\n for file_info in code_files:\n filepath = file_info[\"path\"]\n # Files in root directory or immediate subdirectories\n if filepath.count(\"/\") <= 1:\n fallback_files.append(file_info)\n\n # Sort by likelihood (prefer shorter paths, common names)\n def fallback_priority(file_info):\n path = file_info[\"path\"].lower()\n name = file_info[\"name\"].lower()\n\n score = 0\n # Prefer shorter paths (closer to root)\n score -= path.count(\"/\")\n # Prefer common entry point names\n if any(pattern in name for pattern in [\"main\", \"app\", \"index\"]):\n score -= 10\n # Prefer certain extensions\n if any(ext in name for ext in [\".py\", \".js\", \".go\", \".rs\"]):\n score -= 5\n\n return score\n\n fallback_files.sort(key=fallback_priority)\n return fallback_files[:max_files]", - "start_line": 573, - "end_line": 625, - "has_docstring": true, - "docstring": "Find fallback entry points when standard patterns don't match.\n\nArgs:\n code_files: List of all code files\n max_files: Maximum number of fallback files to return\n\nReturns:\n List of files that could serve as entry points", - "parameters": [ - "code_files", - "max_files" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function find_fallback_entry_points", - "component_id": "codewiki/src/be/dependency_analyzer/utils/patterns.py::find_fallback_entry_points", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/utils/patterns.py::find_fallback_connectivity_files": { - "id": "codewiki/src/be/dependency_analyzer/utils/patterns.py::find_fallback_connectivity_files", - "name": "find_fallback_connectivity_files", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/utils/patterns.py", - "relative_path": "codewiki/src/be/dependency_analyzer/utils/patterns.py", - "depends_on": [], - "source_code": "def find_fallback_connectivity_files(code_files: List[Dict], max_files: int = 10) -> List[Dict]:\n \"\"\"\n Find fallback high-connectivity files when standard patterns don't match.\n\n Args:\n code_files: List of all code files\n max_files: Maximum number of fallback files to return\n\n Returns:\n List of files that likely have good connectivity\n \"\"\"\n fallback_files = []\n\n # Include all files from common source directories\n for file_info in code_files:\n filepath = file_info[\"path\"].lower()\n\n # Any file in src, lib, or similar directories\n if any(pattern in filepath for pattern in [\"src/\", \"lib/\", \"app/\", \"pkg/\", \"core/\"]):\n fallback_files.append(file_info)\n\n # If still not enough, include files with certain extensions\n if len(fallback_files) < max_files:\n for file_info in code_files:\n if file_info not in fallback_files:\n name = file_info[\"name\"].lower()\n # Include common source file extensions\n if any(ext in name for ext in [\".py\", \".js\", \".ts\", \".go\", \".rs\", \".c\", \".cpp\"]):\n # Skip test files\n if not any(test_pattern in name for test_pattern in [\"test\", \"spec\", \"_test\"]):\n fallback_files.append(file_info)\n\n return fallback_files[:max_files]", - "start_line": 628, - "end_line": 660, - "has_docstring": true, - "docstring": "Find fallback high-connectivity files when standard patterns don't match.\n\nArgs:\n code_files: List of all code files\n max_files: Maximum number of fallback files to return\n\nReturns:\n List of files that likely have good connectivity", - "parameters": [ - "code_files", - "max_files" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function find_fallback_connectivity_files", - "component_id": "codewiki/src/be/dependency_analyzer/utils/patterns.py::find_fallback_connectivity_files", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/utils/security.py::_inside": { - "id": "codewiki/src/be/dependency_analyzer/utils/security.py::_inside", - "name": "_inside", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/utils/security.py", - "relative_path": "codewiki/src/be/dependency_analyzer/utils/security.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve" - ], - "source_code": "def _inside(base: Path, target: Path) -> bool:\n base_r = base.resolve()\n try:\n target_r = target.resolve()\n return target_r.is_relative_to(base_r) # py>=3.9\n except AttributeError:\n return str(target.resolve()).startswith(str(base_r))", - "start_line": 4, - "end_line": 10, - "has_docstring": false, - "docstring": "", - "parameters": [ - "base", - "target" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _inside", - "component_id": "codewiki/src/be/dependency_analyzer/utils/security.py::_inside", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/utils/security.py::assert_safe_path": { - "id": "codewiki/src/be/dependency_analyzer/utils/security.py::assert_safe_path", - "name": "assert_safe_path", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/utils/security.py", - "relative_path": "codewiki/src/be/dependency_analyzer/utils/security.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/utils/security.py::_inside", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve" - ], - "source_code": "def assert_safe_path(base_dir: Path, target: Path):\n # Block symlinks (file or dir)\n if target.is_symlink():\n raise PermissionError(f\"Symlink blocked: {target}\")\n # Block paths that escape repo\n if not _inside(base_dir, target):\n raise PermissionError(f\"Path escapes repo: {target} -> {target.resolve()}\")", - "start_line": 12, - "end_line": 18, - "has_docstring": false, - "docstring": "", - "parameters": [ - "base_dir", - "target" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function assert_safe_path", - "component_id": "codewiki/src/be/dependency_analyzer/utils/security.py::assert_safe_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/dependency_analyzer/utils/security.py::safe_open_text": { - "id": "codewiki/src/be/dependency_analyzer/utils/security.py::safe_open_text", - "name": "safe_open_text", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/dependency_analyzer/utils/security.py", - "relative_path": "codewiki/src/be/dependency_analyzer/utils/security.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/utils/security.py::assert_safe_path" - ], - "source_code": "def safe_open_text(base_dir: Path, target: Path, encoding=\"utf-8\"):\n assert_safe_path(base_dir, target)\n flags = os.O_RDONLY\n if hasattr(os, \"O_NOFOLLOW\"):\n flags |= os.O_NOFOLLOW\n fd = os.open(str(target), flags)\n try:\n with os.fdopen(fd, \"r\", encoding=encoding, errors=\"replace\") as f:\n return f.read()\n finally:\n try:\n os.close(fd)\n except OSError:\n pass", - "start_line": 20, - "end_line": 33, - "has_docstring": false, - "docstring": "", - "parameters": [ - "base_dir", - "target", - "encoding" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function safe_open_text", - "component_id": "codewiki/src/be/dependency_analyzer/utils/security.py::safe_open_text", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/documentation_generator.py::IncompleteDocumentationError": { - "id": "codewiki/src/be/documentation_generator.py::IncompleteDocumentationError", - "name": "IncompleteDocumentationError", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/documentation_generator.py", - "relative_path": "codewiki/src/be/documentation_generator.py", - "depends_on": [], - "source_code": "class IncompleteDocumentationError(Exception):\n \"\"\"Raised when generation finishes but some modules have no doc file on disk.\"\"\"\n\n def __init__(self, missing_modules: List[str]):\n self.missing_modules = missing_modules\n super().__init__(\n f\"Documentation generation finished but {len(missing_modules)} module doc(s) \"\n f\"are missing: {', '.join(missing_modules)}\"\n )", - "start_line": 36, - "end_line": 44, - "has_docstring": true, - "docstring": "Raised when generation finishes but some modules have no doc file on disk.", - "parameters": null, - "node_type": "class", - "base_classes": [ - "Exception" - ], - "class_name": null, - "display_name": "class IncompleteDocumentationError", - "component_id": "codewiki/src/be/documentation_generator.py::IncompleteDocumentationError", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/documentation_generator.py::IncompleteDocumentationError.__init__": { - "id": "codewiki/src/be/documentation_generator.py::IncompleteDocumentationError.__init__", - "name": "IncompleteDocumentationError.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/documentation_generator.py", - "relative_path": "codewiki/src/be/documentation_generator.py", - "depends_on": [], - "source_code": " def __init__(self, missing_modules: List[str]):\n self.missing_modules = missing_modules\n super().__init__(\n f\"Documentation generation finished but {len(missing_modules)} module doc(s) \"\n f\"are missing: {', '.join(missing_modules)}\"\n )", - "start_line": 39, - "end_line": 44, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "missing_modules" - ], - "node_type": "method", - "base_classes": null, - "class_name": "IncompleteDocumentationError", - "display_name": "method IncompleteDocumentationError.__init__", - "component_id": "codewiki/src/be/documentation_generator.py::IncompleteDocumentationError.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/documentation_generator.py::DocumentationGenerator": { - "id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator", - "name": "DocumentationGenerator", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/documentation_generator.py", - "relative_path": "codewiki/src/be/documentation_generator.py", - "depends_on": [], - "source_code": "class DocumentationGenerator:\n \"\"\"Main documentation generation orchestrator.\"\"\"\n\n def __init__(self, config: Config, commit_id: str = None, backend: LLMBackend = None):\n self.config = config\n self.commit_id = commit_id\n self.graph_builder = DependencyGraphBuilder(config)\n self.backend: LLMBackend = backend or get_backend(config)\n \n def create_documentation_metadata(self, working_dir: str, components: Dict[str, Any], num_leaf_nodes: int):\n \"\"\"Create a metadata file with documentation generation information.\"\"\"\n from datetime import datetime\n \n metadata = {\n \"generation_info\": {\n \"timestamp\": datetime.now().isoformat(),\n \"main_model\": self.config.main_model,\n \"generator_version\": \"1.0.1\",\n \"repo_path\": self.config.repo_path,\n \"commit_id\": self.commit_id\n },\n \"statistics\": {\n \"total_components\": len(components),\n \"leaf_nodes\": num_leaf_nodes,\n \"max_depth\": self.config.max_depth\n },\n \"files_generated\": [\n \"overview.md\",\n \"module_tree.json\",\n \"first_module_tree.json\"\n ]\n }\n \n # Add generated markdown files to the metadata\n try:\n for file_path in os.listdir(working_dir):\n if file_path.endswith('.md') and file_path not in metadata[\"files_generated\"]:\n metadata[\"files_generated\"].append(file_path)\n except Exception as e:\n logger.warning(f\"Could not list generated files: {e}\")\n \n metadata_path = os.path.join(working_dir, \"metadata.json\")\n file_manager.save_json(metadata, metadata_path)\n\n \n def get_processing_order(self, module_tree: Dict[str, Any], parent_path: List[str] = []) -> List[tuple[List[str], str]]:\n \"\"\"Get the processing order using topological sort (leaf modules first).\"\"\"\n processing_order = []\n \n def collect_modules(tree: Dict[str, Any], path: List[str]):\n for module_name, module_info in tree.items():\n current_path = path + [module_name]\n \n # If this module has children, process them first\n if module_info.get(\"children\") and isinstance(module_info[\"children\"], dict) and module_info[\"children\"]:\n collect_modules(module_info[\"children\"], current_path)\n # Add this parent module after its children\n processing_order.append((current_path, module_name))\n else:\n # This is a leaf module, add it immediately\n processing_order.append((current_path, module_name))\n \n collect_modules(module_tree, parent_path)\n return processing_order\n\n def is_leaf_module(self, module_info: Dict[str, Any]) -> bool:\n \"\"\"Check if a module is a leaf module (has no children or empty children).\"\"\"\n children = module_info.get(\"children\", {})\n return not children or (isinstance(children, dict) and len(children) == 0)\n\n def build_overview_structure(self, module_tree: Dict[str, Any], module_path: List[str],\n working_dir: str) -> Dict[str, Any]:\n \"\"\"Build structure for overview generation with 1-depth children docs and target indicator.\"\"\"\n \n processed_module_tree = deepcopy(module_tree)\n module_info = processed_module_tree\n for path_part in module_path:\n module_info = module_info[path_part]\n if path_part != module_path[-1]:\n module_info = module_info.get(\"children\", {})\n else:\n module_info[\"is_target_for_overview_generation\"] = True\n\n if \"children\" in module_info:\n module_info = module_info[\"children\"]\n\n for child_name, child_info in module_info.items():\n child_docs_path = self._resolve_child_docs_path(working_dir, child_name)\n if child_docs_path is not None:\n child_info[\"docs\"] = file_manager.load_text(child_docs_path)\n else:\n logger.warning(f\"Module docs not found at {os.path.join(working_dir, f'{child_name}.md')}\")\n child_info[\"docs\"] = \"\"\n\n return processed_module_tree\n\n @staticmethod\n def _resolve_child_docs_path(working_dir: str, child_name: str) -> str | None:\n \"\"\"Resolve the on-disk path for a child module's .md doc.\n\n Sub-agents sometimes save files under a sanitized variant of the\n module name (spaces β†’ underscores, lowercased, etc.) rather than the\n exact key in the module tree. Try a small set of common variants\n before giving up so the overview prompt still gets the children's\n content as context.\n \"\"\"\n return resolve_module_doc_path(working_dir, child_name)\n\n def validate_generated_docs(self, working_dir: str) -> List[str]:\n \"\"\"Check the final module tree against the docs on disk.\n\n Returns the names of modules whose .md file is missing (plus\n \"overview\" if overview.md was never written).\n \"\"\"\n module_tree_path = os.path.join(working_dir, MODULE_TREE_FILENAME)\n if not os.path.exists(module_tree_path):\n return []\n module_tree = file_manager.load_json(module_tree_path)\n return find_missing_module_docs(module_tree, working_dir)\n\n async def generate_module_documentation(self, components: Dict[str, Any], leaf_nodes: List[str]) -> str:\n \"\"\"Generate documentation for all modules using dynamic programming approach.\"\"\"\n # Prepare output directory\n working_dir = os.path.abspath(self.config.docs_dir)\n file_manager.ensure_directory(working_dir)\n\n module_tree_path = os.path.join(working_dir, MODULE_TREE_FILENAME)\n first_module_tree_path = os.path.join(working_dir, FIRST_MODULE_TREE_FILENAME)\n module_tree = file_manager.load_json(module_tree_path)\n first_module_tree = file_manager.load_json(first_module_tree_path)\n \n # Get processing order (leaf modules first)\n processing_order = self.get_processing_order(first_module_tree)\n\n \n # Process modules in dependency order\n final_module_tree = module_tree\n processed_modules = set()\n\n if len(module_tree) > 0:\n for module_path, module_name in processing_order:\n try:\n # Reload module tree to get latest hierarchical structure from sub-agent modifications\n module_tree = file_manager.load_json(module_tree_path)\n \n # Get the module info from the tree\n module_info = module_tree\n for path_part in module_path:\n module_info = module_info[path_part]\n if path_part != module_path[-1]: # Not the last part\n module_info = module_info.get(\"children\", {})\n \n # Skip if already processed\n module_key = \"/\".join(module_path)\n if module_key in processed_modules:\n continue\n \n # Process the module\n if self.is_leaf_module(module_info):\n logger.info(f\"πŸ“„ Processing leaf module: {module_key}\")\n final_module_tree = await self.backend.run_module_agent(\n module_name=module_name,\n components=components,\n core_component_ids=module_info[\"components\"],\n module_path=module_path,\n working_dir=working_dir,\n )\n else:\n logger.info(f\"πŸ“ Processing parent module: {module_key}\")\n final_module_tree = await self.generate_parent_module_docs(\n module_path, working_dir\n )\n \n processed_modules.add(module_key)\n \n except Exception as e:\n logger.error(f\"Failed to process module {module_key}: {str(e)}\")\n logger.error(f\"Traceback: {traceback.format_exc()}\")\n continue\n\n # Generate repo overview\n logger.info(f\"πŸ“š Generating repository overview\")\n final_module_tree = await self.generate_parent_module_docs(\n [], working_dir\n )\n else:\n logger.info(f\"Processing whole repo because repo can fit in the context window\")\n repo_name = os.path.basename(os.path.normpath(self.config.repo_path))\n final_module_tree = await self.backend.run_module_agent(\n module_name=repo_name,\n components=components,\n core_component_ids=leaf_nodes,\n module_path=[],\n working_dir=working_dir,\n )\n\n # save final_module_tree to module_tree.json\n file_manager.save_json(final_module_tree, os.path.join(working_dir, MODULE_TREE_FILENAME))\n\n # rename repo_name.md to overview.md\n repo_overview_path = os.path.join(working_dir, f\"{repo_name}.md\")\n if os.path.exists(repo_overview_path):\n os.rename(repo_overview_path, os.path.join(working_dir, OVERVIEW_FILENAME))\n \n return working_dir\n\n async def generate_parent_module_docs(self, module_path: List[str], \n working_dir: str) -> Dict[str, Any]:\n \"\"\"Generate documentation for a parent module based on its children's documentation.\"\"\"\n module_name = module_path[-1] if len(module_path) >= 1 else os.path.basename(os.path.normpath(self.config.repo_path))\n\n logger.info(f\"Generating parent documentation for: {module_name}\")\n \n # Load module tree\n module_tree_path = os.path.join(working_dir, MODULE_TREE_FILENAME)\n module_tree = file_manager.load_json(module_tree_path)\n\n # check if overview docs already exists\n overview_docs_path = os.path.join(working_dir, OVERVIEW_FILENAME)\n if os.path.exists(overview_docs_path):\n logger.info(f\"βœ“ Overview docs already exists at {overview_docs_path}\")\n return module_tree\n\n # check if parent docs already exists\n parent_docs_path = os.path.join(working_dir, f\"{module_name if len(module_path) >= 1 else OVERVIEW_FILENAME.replace('.md', '')}.md\")\n if os.path.exists(parent_docs_path):\n logger.info(f\"βœ“ Parent docs already exists at {parent_docs_path}\")\n return module_tree\n\n # Create repo structure with 1-depth children docs and target indicator\n repo_structure = self.build_overview_structure(module_tree, module_path, working_dir)\n\n prompt = MODULE_OVERVIEW_PROMPT.format(\n module_name=module_name,\n repo_structure=json.dumps(repo_structure, indent=4)\n ) if len(module_path) >= 1 else REPO_OVERVIEW_PROMPT.format(\n repo_name=module_name,\n repo_structure=json.dumps(repo_structure, indent=4)\n )\n \n try:\n parent_docs = self.backend.complete(prompt)\n\n # Parse and save parent documentation. Subscription-CLI backends\n # (claude-code / codex) sometimes ignore the wrapper and\n # return raw markdown; fall back to the response as-is in that case\n # rather than crashing with an index error.\n if \"\" in parent_docs and \"\" in parent_docs:\n parent_content = parent_docs.split(\"\")[1].split(\"\")[0].strip()\n else:\n logger.warning(\n f\"Overview response for {module_name} missing wrapper; \"\n f\"using raw response as markdown.\"\n )\n parent_content = parent_docs.strip()\n file_manager.save_text(parent_content, parent_docs_path)\n \n logger.debug(f\"Successfully generated parent documentation for: {module_name}\")\n return module_tree\n \n except Exception as e:\n logger.error(f\"Error generating parent documentation for {module_name}: {str(e)}\")\n logger.error(f\"Traceback: {traceback.format_exc()}\")\n raise\n \n async def run(self) -> None:\n \"\"\"Run the complete documentation generation process using dynamic programming.\"\"\"\n try:\n # Build dependency graph\n components, leaf_nodes = self.graph_builder.build_dependency_graph()\n\n logger.debug(f\"Found {len(leaf_nodes)} leaf nodes\")\n # logger.debug(f\"Leaf nodes:\\n{'\\n'.join(sorted(leaf_nodes)[:200])}\")\n # exit()\n \n # Cluster modules\n working_dir = os.path.abspath(self.config.docs_dir)\n file_manager.ensure_directory(working_dir)\n first_module_tree_path = os.path.join(working_dir, FIRST_MODULE_TREE_FILENAME)\n module_tree_path = os.path.join(working_dir, MODULE_TREE_FILENAME)\n \n # Check if module tree exists\n if os.path.exists(first_module_tree_path):\n logger.debug(f\"Module tree found at {first_module_tree_path}\")\n module_tree = file_manager.load_json(first_module_tree_path)\n else:\n logger.debug(f\"Module tree not found at {module_tree_path}, clustering modules\")\n clustering_tokens = get_clustering_input_token_count(\n leaf_nodes, components\n )\n logger.info(\n \"Preparing %d leaf nodes for module clustering (%d tokens, threshold %d)\",\n len(leaf_nodes),\n clustering_tokens,\n self.config.max_token_per_module,\n )\n # Bind cluster_model into the completer so the backend uses the\n # configured clustering model (separate from main_model) when\n # one is set. Caw mode's cluster_model is typically empty β€”\n # complete() falls back to its own _model in that case.\n cluster_model = self.config.cluster_model or None\n module_tree = cluster_modules(\n leaf_nodes,\n components,\n self.config,\n completer=lambda p: self.backend.complete(p, model=cluster_model),\n )\n # Only freshly clustered trees are deduped: renaming a cached\n # key whose .md already exists would orphan the doc.\n module_tree = dedupe_module_tree_names(module_tree)\n file_manager.save_json(module_tree, first_module_tree_path)\n \n file_manager.save_json(module_tree, module_tree_path)\n \n if len(module_tree) == 0:\n logger.info(\n \"Module clustering produced no top-level modules; continuing in \"\n \"whole-repository documentation mode\"\n )\n else:\n logger.info(\n \"Grouped components into %d top-level modules\",\n len(module_tree),\n )\n \n # Generate module documentation using dynamic programming approach\n # This processes leaf modules first, then parent modules\n working_dir = await self.generate_module_documentation(components, leaf_nodes)\n \n # Create documentation metadata\n self.create_documentation_metadata(working_dir, components, len(leaf_nodes))\n\n # Reconcile the final module tree against the docs on disk so\n # name collisions or failed sub-agents can't pass silently (issue #76)\n missing_docs = self.validate_generated_docs(working_dir)\n if missing_docs:\n for module_name in missing_docs:\n logger.error(f\"Module doc missing after generation: {module_name}.md\")\n raise IncompleteDocumentationError(missing_docs)\n\n logger.debug(f\"Documentation generation completed successfully using dynamic programming!\")\n logger.debug(f\"Processing order: leaf modules β†’ parent modules β†’ repository overview\")\n logger.debug(f\"Documentation saved to: {working_dir}\")\n \n except Exception as e:\n logger.error(f\"Documentation generation failed: {str(e)}\")\n logger.error(f\"Traceback: {traceback.format_exc()}\")\n raise", - "start_line": 47, - "end_line": 394, - "has_docstring": true, - "docstring": "Main documentation generation orchestrator.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class DocumentationGenerator", - "component_id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.__init__": { - "id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator.__init__", - "name": "DocumentationGenerator.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/documentation_generator.py", - "relative_path": "codewiki/src/be/documentation_generator.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py::DependencyGraphBuilder", - "codewiki/src/be/backend.py::get_backend" - ], - "source_code": " def __init__(self, config: Config, commit_id: str = None, backend: LLMBackend = None):\n self.config = config\n self.commit_id = commit_id\n self.graph_builder = DependencyGraphBuilder(config)\n self.backend: LLMBackend = backend or get_backend(config)", - "start_line": 50, - "end_line": 54, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "config", - "commit_id", - "backend" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DocumentationGenerator", - "display_name": "method DocumentationGenerator.__init__", - "component_id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.create_documentation_metadata": { - "id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator.create_documentation_metadata", - "name": "DocumentationGenerator.create_documentation_metadata", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/documentation_generator.py", - "relative_path": "codewiki/src/be/documentation_generator.py", - "depends_on": [ - "codewiki/src/utils.py::FileManager.save_json" - ], - "source_code": " def create_documentation_metadata(self, working_dir: str, components: Dict[str, Any], num_leaf_nodes: int):\n \"\"\"Create a metadata file with documentation generation information.\"\"\"\n from datetime import datetime\n \n metadata = {\n \"generation_info\": {\n \"timestamp\": datetime.now().isoformat(),\n \"main_model\": self.config.main_model,\n \"generator_version\": \"1.0.1\",\n \"repo_path\": self.config.repo_path,\n \"commit_id\": self.commit_id\n },\n \"statistics\": {\n \"total_components\": len(components),\n \"leaf_nodes\": num_leaf_nodes,\n \"max_depth\": self.config.max_depth\n },\n \"files_generated\": [\n \"overview.md\",\n \"module_tree.json\",\n \"first_module_tree.json\"\n ]\n }\n \n # Add generated markdown files to the metadata\n try:\n for file_path in os.listdir(working_dir):\n if file_path.endswith('.md') and file_path not in metadata[\"files_generated\"]:\n metadata[\"files_generated\"].append(file_path)\n except Exception as e:\n logger.warning(f\"Could not list generated files: {e}\")\n \n metadata_path = os.path.join(working_dir, \"metadata.json\")\n file_manager.save_json(metadata, metadata_path)", - "start_line": 56, - "end_line": 89, - "has_docstring": true, - "docstring": "Create a metadata file with documentation generation information.", - "parameters": [ - "self", - "working_dir", - "components", - "num_leaf_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DocumentationGenerator", - "display_name": "method DocumentationGenerator.create_documentation_metadata", - "component_id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator.create_documentation_metadata", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.get_processing_order": { - "id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator.get_processing_order", - "name": "DocumentationGenerator.get_processing_order", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/documentation_generator.py", - "relative_path": "codewiki/src/be/documentation_generator.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def get_processing_order(self, module_tree: Dict[str, Any], parent_path: List[str] = []) -> List[tuple[List[str], str]]:\n \"\"\"Get the processing order using topological sort (leaf modules first).\"\"\"\n processing_order = []\n \n def collect_modules(tree: Dict[str, Any], path: List[str]):\n for module_name, module_info in tree.items():\n current_path = path + [module_name]\n \n # If this module has children, process them first\n if module_info.get(\"children\") and isinstance(module_info[\"children\"], dict) and module_info[\"children\"]:\n collect_modules(module_info[\"children\"], current_path)\n # Add this parent module after its children\n processing_order.append((current_path, module_name))\n else:\n # This is a leaf module, add it immediately\n processing_order.append((current_path, module_name))\n \n collect_modules(module_tree, parent_path)\n return processing_order", - "start_line": 92, - "end_line": 110, - "has_docstring": true, - "docstring": "Get the processing order using topological sort (leaf modules first).", - "parameters": [ - "self", - "module_tree", - "parent_path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DocumentationGenerator", - "display_name": "method DocumentationGenerator.get_processing_order", - "component_id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator.get_processing_order", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.is_leaf_module": { - "id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator.is_leaf_module", - "name": "DocumentationGenerator.is_leaf_module", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/documentation_generator.py", - "relative_path": "codewiki/src/be/documentation_generator.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def is_leaf_module(self, module_info: Dict[str, Any]) -> bool:\n \"\"\"Check if a module is a leaf module (has no children or empty children).\"\"\"\n children = module_info.get(\"children\", {})\n return not children or (isinstance(children, dict) and len(children) == 0)", - "start_line": 112, - "end_line": 115, - "has_docstring": true, - "docstring": "Check if a module is a leaf module (has no children or empty children).", - "parameters": [ - "self", - "module_info" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DocumentationGenerator", - "display_name": "method DocumentationGenerator.is_leaf_module", - "component_id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator.is_leaf_module", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.build_overview_structure": { - "id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator.build_overview_structure", - "name": "DocumentationGenerator.build_overview_structure", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/documentation_generator.py", - "relative_path": "codewiki/src/be/documentation_generator.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/utils.py::FileManager.load_text", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator._resolve_child_docs_path" - ], - "source_code": " def build_overview_structure(self, module_tree: Dict[str, Any], module_path: List[str],\n working_dir: str) -> Dict[str, Any]:\n \"\"\"Build structure for overview generation with 1-depth children docs and target indicator.\"\"\"\n \n processed_module_tree = deepcopy(module_tree)\n module_info = processed_module_tree\n for path_part in module_path:\n module_info = module_info[path_part]\n if path_part != module_path[-1]:\n module_info = module_info.get(\"children\", {})\n else:\n module_info[\"is_target_for_overview_generation\"] = True\n\n if \"children\" in module_info:\n module_info = module_info[\"children\"]\n\n for child_name, child_info in module_info.items():\n child_docs_path = self._resolve_child_docs_path(working_dir, child_name)\n if child_docs_path is not None:\n child_info[\"docs\"] = file_manager.load_text(child_docs_path)\n else:\n logger.warning(f\"Module docs not found at {os.path.join(working_dir, f'{child_name}.md')}\")\n child_info[\"docs\"] = \"\"\n\n return processed_module_tree", - "start_line": 117, - "end_line": 141, - "has_docstring": true, - "docstring": "Build structure for overview generation with 1-depth children docs and target indicator.", - "parameters": [ - "self", - "module_tree", - "module_path", - "working_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DocumentationGenerator", - "display_name": "method DocumentationGenerator.build_overview_structure", - "component_id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator.build_overview_structure", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/documentation_generator.py::DocumentationGenerator._resolve_child_docs_path": { - "id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator._resolve_child_docs_path", - "name": "DocumentationGenerator._resolve_child_docs_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/documentation_generator.py", - "relative_path": "codewiki/src/be/documentation_generator.py", - "depends_on": [ - "codewiki/src/be/module_naming.py::resolve_module_doc_path" - ], - "source_code": " def _resolve_child_docs_path(working_dir: str, child_name: str) -> str | None:\n \"\"\"Resolve the on-disk path for a child module's .md doc.\n\n Sub-agents sometimes save files under a sanitized variant of the\n module name (spaces β†’ underscores, lowercased, etc.) rather than the\n exact key in the module tree. Try a small set of common variants\n before giving up so the overview prompt still gets the children's\n content as context.\n \"\"\"\n return resolve_module_doc_path(working_dir, child_name)", - "start_line": 144, - "end_line": 153, - "has_docstring": true, - "docstring": "Resolve the on-disk path for a child module's .md doc.\n\nSub-agents sometimes save files under a sanitized variant of the\nmodule name (spaces β†’ underscores, lowercased, etc.) rather than the\nexact key in the module tree. Try a small set of common variants\nbefore giving up so the overview prompt still gets the children's\ncontent as context.", - "parameters": [ - "working_dir", - "child_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DocumentationGenerator", - "display_name": "method DocumentationGenerator._resolve_child_docs_path", - "component_id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator._resolve_child_docs_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.validate_generated_docs": { - "id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator.validate_generated_docs", - "name": "DocumentationGenerator.validate_generated_docs", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/documentation_generator.py", - "relative_path": "codewiki/src/be/documentation_generator.py", - "depends_on": [ - "codewiki/src/utils.py::FileManager.load_json", - "codewiki/src/be/module_naming.py::find_missing_module_docs" - ], - "source_code": " def validate_generated_docs(self, working_dir: str) -> List[str]:\n \"\"\"Check the final module tree against the docs on disk.\n\n Returns the names of modules whose .md file is missing (plus\n \"overview\" if overview.md was never written).\n \"\"\"\n module_tree_path = os.path.join(working_dir, MODULE_TREE_FILENAME)\n if not os.path.exists(module_tree_path):\n return []\n module_tree = file_manager.load_json(module_tree_path)\n return find_missing_module_docs(module_tree, working_dir)", - "start_line": 155, - "end_line": 165, - "has_docstring": true, - "docstring": "Check the final module tree against the docs on disk.\n\nReturns the names of modules whose .md file is missing (plus\n\"overview\" if overview.md was never written).", - "parameters": [ - "self", - "working_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DocumentationGenerator", - "display_name": "method DocumentationGenerator.validate_generated_docs", - "component_id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator.validate_generated_docs", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.generate_module_documentation": { - "id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator.generate_module_documentation", - "name": "DocumentationGenerator.generate_module_documentation", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/documentation_generator.py", - "relative_path": "codewiki/src/be/documentation_generator.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.is_leaf_module", - "codewiki/src/utils.py::FileManager.load_json", - "codewiki/src/utils.py::FileManager.save_json", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.get_processing_order", - "codewiki/cli/utils/logging.py::CLILogger.error", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.generate_parent_module_docs" - ], - "source_code": " async def generate_module_documentation(self, components: Dict[str, Any], leaf_nodes: List[str]) -> str:\n \"\"\"Generate documentation for all modules using dynamic programming approach.\"\"\"\n # Prepare output directory\n working_dir = os.path.abspath(self.config.docs_dir)\n file_manager.ensure_directory(working_dir)\n\n module_tree_path = os.path.join(working_dir, MODULE_TREE_FILENAME)\n first_module_tree_path = os.path.join(working_dir, FIRST_MODULE_TREE_FILENAME)\n module_tree = file_manager.load_json(module_tree_path)\n first_module_tree = file_manager.load_json(first_module_tree_path)\n \n # Get processing order (leaf modules first)\n processing_order = self.get_processing_order(first_module_tree)\n\n \n # Process modules in dependency order\n final_module_tree = module_tree\n processed_modules = set()\n\n if len(module_tree) > 0:\n for module_path, module_name in processing_order:\n try:\n # Reload module tree to get latest hierarchical structure from sub-agent modifications\n module_tree = file_manager.load_json(module_tree_path)\n \n # Get the module info from the tree\n module_info = module_tree\n for path_part in module_path:\n module_info = module_info[path_part]\n if path_part != module_path[-1]: # Not the last part\n module_info = module_info.get(\"children\", {})\n \n # Skip if already processed\n module_key = \"/\".join(module_path)\n if module_key in processed_modules:\n continue\n \n # Process the module\n if self.is_leaf_module(module_info):\n logger.info(f\"πŸ“„ Processing leaf module: {module_key}\")\n final_module_tree = await self.backend.run_module_agent(\n module_name=module_name,\n components=components,\n core_component_ids=module_info[\"components\"],\n module_path=module_path,\n working_dir=working_dir,\n )\n else:\n logger.info(f\"πŸ“ Processing parent module: {module_key}\")\n final_module_tree = await self.generate_parent_module_docs(\n module_path, working_dir\n )\n \n processed_modules.add(module_key)\n \n except Exception as e:\n logger.error(f\"Failed to process module {module_key}: {str(e)}\")\n logger.error(f\"Traceback: {traceback.format_exc()}\")\n continue\n\n # Generate repo overview\n logger.info(f\"πŸ“š Generating repository overview\")\n final_module_tree = await self.generate_parent_module_docs(\n [], working_dir\n )\n else:\n logger.info(f\"Processing whole repo because repo can fit in the context window\")\n repo_name = os.path.basename(os.path.normpath(self.config.repo_path))\n final_module_tree = await self.backend.run_module_agent(\n module_name=repo_name,\n components=components,\n core_component_ids=leaf_nodes,\n module_path=[],\n working_dir=working_dir,\n )\n\n # save final_module_tree to module_tree.json\n file_manager.save_json(final_module_tree, os.path.join(working_dir, MODULE_TREE_FILENAME))\n\n # rename repo_name.md to overview.md\n repo_overview_path = os.path.join(working_dir, f\"{repo_name}.md\")\n if os.path.exists(repo_overview_path):\n os.rename(repo_overview_path, os.path.join(working_dir, OVERVIEW_FILENAME))\n \n return working_dir", - "start_line": 167, - "end_line": 251, - "has_docstring": true, - "docstring": "Generate documentation for all modules using dynamic programming approach.", - "parameters": [ - "self", - "components", - "leaf_nodes" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DocumentationGenerator", - "display_name": "method DocumentationGenerator.generate_module_documentation", - "component_id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator.generate_module_documentation", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.generate_parent_module_docs": { - "id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator.generate_parent_module_docs", - "name": "DocumentationGenerator.generate_parent_module_docs", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/documentation_generator.py", - "relative_path": "codewiki/src/be/documentation_generator.py", - "depends_on": [ - "codewiki/src/utils.py::FileManager.save_text", - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter.format", - "codewiki/src/utils.py::FileManager.load_json", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.build_overview_structure", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": " async def generate_parent_module_docs(self, module_path: List[str], \n working_dir: str) -> Dict[str, Any]:\n \"\"\"Generate documentation for a parent module based on its children's documentation.\"\"\"\n module_name = module_path[-1] if len(module_path) >= 1 else os.path.basename(os.path.normpath(self.config.repo_path))\n\n logger.info(f\"Generating parent documentation for: {module_name}\")\n \n # Load module tree\n module_tree_path = os.path.join(working_dir, MODULE_TREE_FILENAME)\n module_tree = file_manager.load_json(module_tree_path)\n\n # check if overview docs already exists\n overview_docs_path = os.path.join(working_dir, OVERVIEW_FILENAME)\n if os.path.exists(overview_docs_path):\n logger.info(f\"βœ“ Overview docs already exists at {overview_docs_path}\")\n return module_tree\n\n # check if parent docs already exists\n parent_docs_path = os.path.join(working_dir, f\"{module_name if len(module_path) >= 1 else OVERVIEW_FILENAME.replace('.md', '')}.md\")\n if os.path.exists(parent_docs_path):\n logger.info(f\"βœ“ Parent docs already exists at {parent_docs_path}\")\n return module_tree\n\n # Create repo structure with 1-depth children docs and target indicator\n repo_structure = self.build_overview_structure(module_tree, module_path, working_dir)\n\n prompt = MODULE_OVERVIEW_PROMPT.format(\n module_name=module_name,\n repo_structure=json.dumps(repo_structure, indent=4)\n ) if len(module_path) >= 1 else REPO_OVERVIEW_PROMPT.format(\n repo_name=module_name,\n repo_structure=json.dumps(repo_structure, indent=4)\n )\n \n try:\n parent_docs = self.backend.complete(prompt)\n\n # Parse and save parent documentation. Subscription-CLI backends\n # (claude-code / codex) sometimes ignore the wrapper and\n # return raw markdown; fall back to the response as-is in that case\n # rather than crashing with an index error.\n if \"\" in parent_docs and \"\" in parent_docs:\n parent_content = parent_docs.split(\"\")[1].split(\"\")[0].strip()\n else:\n logger.warning(\n f\"Overview response for {module_name} missing wrapper; \"\n f\"using raw response as markdown.\"\n )\n parent_content = parent_docs.strip()\n file_manager.save_text(parent_content, parent_docs_path)\n \n logger.debug(f\"Successfully generated parent documentation for: {module_name}\")\n return module_tree\n \n except Exception as e:\n logger.error(f\"Error generating parent documentation for {module_name}: {str(e)}\")\n logger.error(f\"Traceback: {traceback.format_exc()}\")\n raise", - "start_line": 253, - "end_line": 310, - "has_docstring": true, - "docstring": "Generate documentation for a parent module based on its children's documentation.", - "parameters": [ - "self", - "module_path", - "working_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DocumentationGenerator", - "display_name": "method DocumentationGenerator.generate_parent_module_docs", - "component_id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator.generate_parent_module_docs", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.run": { - "id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator.run", - "name": "DocumentationGenerator.run", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/documentation_generator.py", - "relative_path": "codewiki/src/be/documentation_generator.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/dependency_graphs_builder.py::DependencyGraphBuilder.build_dependency_graph", - "codewiki/src/be/module_naming.py::dedupe_module_tree_names", - "codewiki/src/be/cluster_modules.py::cluster_modules", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.generate_module_documentation", - "codewiki/src/utils.py::FileManager.load_json", - "codewiki/src/be/cluster_modules.py::get_clustering_input_token_count", - "codewiki/src/utils.py::FileManager.save_json", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.create_documentation_metadata", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.validate_generated_docs", - "codewiki/src/be/documentation_generator.py::IncompleteDocumentationError", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": " async def run(self) -> None:\n \"\"\"Run the complete documentation generation process using dynamic programming.\"\"\"\n try:\n # Build dependency graph\n components, leaf_nodes = self.graph_builder.build_dependency_graph()\n\n logger.debug(f\"Found {len(leaf_nodes)} leaf nodes\")\n # logger.debug(f\"Leaf nodes:\\n{'\\n'.join(sorted(leaf_nodes)[:200])}\")\n # exit()\n \n # Cluster modules\n working_dir = os.path.abspath(self.config.docs_dir)\n file_manager.ensure_directory(working_dir)\n first_module_tree_path = os.path.join(working_dir, FIRST_MODULE_TREE_FILENAME)\n module_tree_path = os.path.join(working_dir, MODULE_TREE_FILENAME)\n \n # Check if module tree exists\n if os.path.exists(first_module_tree_path):\n logger.debug(f\"Module tree found at {first_module_tree_path}\")\n module_tree = file_manager.load_json(first_module_tree_path)\n else:\n logger.debug(f\"Module tree not found at {module_tree_path}, clustering modules\")\n clustering_tokens = get_clustering_input_token_count(\n leaf_nodes, components\n )\n logger.info(\n \"Preparing %d leaf nodes for module clustering (%d tokens, threshold %d)\",\n len(leaf_nodes),\n clustering_tokens,\n self.config.max_token_per_module,\n )\n # Bind cluster_model into the completer so the backend uses the\n # configured clustering model (separate from main_model) when\n # one is set. Caw mode's cluster_model is typically empty β€”\n # complete() falls back to its own _model in that case.\n cluster_model = self.config.cluster_model or None\n module_tree = cluster_modules(\n leaf_nodes,\n components,\n self.config,\n completer=lambda p: self.backend.complete(p, model=cluster_model),\n )\n # Only freshly clustered trees are deduped: renaming a cached\n # key whose .md already exists would orphan the doc.\n module_tree = dedupe_module_tree_names(module_tree)\n file_manager.save_json(module_tree, first_module_tree_path)\n \n file_manager.save_json(module_tree, module_tree_path)\n \n if len(module_tree) == 0:\n logger.info(\n \"Module clustering produced no top-level modules; continuing in \"\n \"whole-repository documentation mode\"\n )\n else:\n logger.info(\n \"Grouped components into %d top-level modules\",\n len(module_tree),\n )\n \n # Generate module documentation using dynamic programming approach\n # This processes leaf modules first, then parent modules\n working_dir = await self.generate_module_documentation(components, leaf_nodes)\n \n # Create documentation metadata\n self.create_documentation_metadata(working_dir, components, len(leaf_nodes))\n\n # Reconcile the final module tree against the docs on disk so\n # name collisions or failed sub-agents can't pass silently (issue #76)\n missing_docs = self.validate_generated_docs(working_dir)\n if missing_docs:\n for module_name in missing_docs:\n logger.error(f\"Module doc missing after generation: {module_name}.md\")\n raise IncompleteDocumentationError(missing_docs)\n\n logger.debug(f\"Documentation generation completed successfully using dynamic programming!\")\n logger.debug(f\"Processing order: leaf modules β†’ parent modules β†’ repository overview\")\n logger.debug(f\"Documentation saved to: {working_dir}\")\n \n except Exception as e:\n logger.error(f\"Documentation generation failed: {str(e)}\")\n logger.error(f\"Traceback: {traceback.format_exc()}\")\n raise", - "start_line": 312, - "end_line": 394, - "has_docstring": true, - "docstring": "Run the complete documentation generation process using dynamic programming.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "DocumentationGenerator", - "display_name": "method DocumentationGenerator.run", - "component_id": "codewiki/src/be/documentation_generator.py::DocumentationGenerator.run", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::_add_cache_control_to_message": { - "id": "codewiki/src/be/llm_services.py::_add_cache_control_to_message", - "name": "_add_cache_control_to_message", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": "def _add_cache_control_to_message(message) -> None:\n \"\"\"Attach an ephemeral ``cache_control`` marker to an OpenAI-format message in place.\n\n Tool messages get the marker at message level: OpenAI-compatible proxies\n (e.g. LiteLLM) map that onto the Anthropic ``tool_result`` block, whereas a\n part-level marker would land on a nested block, which Anthropic rejects.\n Other roles get it on the last content part (string content is converted to\n a single text part).\n \"\"\"\n if message.get(\"role\") == \"tool\":\n message.setdefault(\"cache_control\", dict(_EPHEMERAL_CACHE))\n return\n content = message.get(\"content\")\n if isinstance(content, str) and content:\n message[\"content\"] = [\n {\"type\": \"text\", \"text\": content, \"cache_control\": dict(_EPHEMERAL_CACHE)}\n ]\n elif isinstance(content, list) and content:\n last_part = content[-1]\n if isinstance(last_part, dict):\n last_part.setdefault(\"cache_control\", dict(_EPHEMERAL_CACHE))", - "start_line": 31, - "end_line": 51, - "has_docstring": true, - "docstring": "Attach an ephemeral ``cache_control`` marker to an OpenAI-format message in place.\n\nTool messages get the marker at message level: OpenAI-compatible proxies\n(e.g. LiteLLM) map that onto the Anthropic ``tool_result`` block, whereas a\npart-level marker would land on a nested block, which Anthropic rejects.\nOther roles get it on the last content part (string content is converted to\na single text part).", - "parameters": [ - "message" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _add_cache_control_to_message", - "component_id": "codewiki/src/be/llm_services.py::_add_cache_control_to_message", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::_should_use_max_completion_tokens": { - "id": "codewiki/src/be/llm_services.py::_should_use_max_completion_tokens", - "name": "_should_use_max_completion_tokens", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [], - "source_code": "def _should_use_max_completion_tokens(model_name: str, base_url: str) -> bool:\n \"\"\"\n Determine whether to use max_completion_tokens instead of max_tokens.\n\n Newer OpenAI models (o1, o3, o4, gpt-4o, gpt-5, etc.) require\n max_completion_tokens. Anthropic and other providers still use max_tokens.\n \"\"\"\n model_lower = model_name.lower()\n # OpenAI models that require max_completion_tokens\n new_openai_patterns = (\"o1\", \"o3\", \"o4\", \"gpt-4o\", \"gpt-4-turbo\", \"gpt-5\")\n if any(pattern in model_lower for pattern in new_openai_patterns):\n return True\n # If base_url points to OpenAI directly, newer models may need it\n if base_url and \"api.openai.com\" in base_url:\n return True\n return False", - "start_line": 54, - "end_line": 69, - "has_docstring": true, - "docstring": "Determine whether to use max_completion_tokens instead of max_tokens.\n\nNewer OpenAI models (o1, o3, o4, gpt-4o, gpt-5, etc.) require\nmax_completion_tokens. Anthropic and other providers still use max_tokens.", - "parameters": [ - "model_name", - "base_url" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _should_use_max_completion_tokens", - "component_id": "codewiki/src/be/llm_services.py::_should_use_max_completion_tokens", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::_build_model_settings": { - "id": "codewiki/src/be/llm_services.py::_build_model_settings", - "name": "_build_model_settings", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [ - "codewiki/src/be/llm_services.py::_should_use_max_completion_tokens" - ], - "source_code": "def _build_model_settings(config: Config, model_name: str) -> OpenAIChatModelSettings:\n \"\"\"Build model settings with the correct token parameter.\n\n No temperature is sent: some providers/models (e.g. reasoning models that\n only accept temperature=1) reject explicit values, so requests rely on the\n provider default.\n \"\"\"\n if _should_use_max_completion_tokens(model_name, config.llm_base_url):\n return OpenAIChatModelSettings(\n max_completion_tokens=config.max_tokens\n )\n return OpenAIChatModelSettings(\n max_tokens=config.max_tokens\n )", - "start_line": 72, - "end_line": 85, - "has_docstring": true, - "docstring": "Build model settings with the correct token parameter.\n\nNo temperature is sent: some providers/models (e.g. reasoning models that\nonly accept temperature=1) reject explicit values, so requests rely on the\nprovider default.", - "parameters": [ - "config", - "model_name" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _build_model_settings", - "component_id": "codewiki/src/be/llm_services.py::_build_model_settings", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::_get_litellm_model_name": { - "id": "codewiki/src/be/llm_services.py::_get_litellm_model_name", - "name": "_get_litellm_model_name", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [], - "source_code": "def _get_litellm_model_name(model_name: str, provider: str) -> str:\n \"\"\"\n Get the litellm-compatible model name for a given provider.\n\n For Bedrock, prefixes the model name with 'bedrock/' if not already prefixed.\n For Anthropic, prefixes with 'anthropic/' if not already prefixed.\n \"\"\"\n if provider == \"bedrock\":\n if not model_name.startswith(\"bedrock/\"):\n return f\"bedrock/{model_name}\"\n elif provider == \"anthropic\":\n if not model_name.startswith(\"anthropic/\"):\n return f\"anthropic/{model_name}\"\n return model_name", - "start_line": 88, - "end_line": 101, - "has_docstring": true, - "docstring": "Get the litellm-compatible model name for a given provider.\n\nFor Bedrock, prefixes the model name with 'bedrock/' if not already prefixed.\nFor Anthropic, prefixes with 'anthropic/' if not already prefixed.", - "parameters": [ - "model_name", - "provider" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _get_litellm_model_name", - "component_id": "codewiki/src/be/llm_services.py::_get_litellm_model_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::CompatibleOpenAIModel": { - "id": "codewiki/src/be/llm_services.py::CompatibleOpenAIModel", - "name": "CompatibleOpenAIModel", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [], - "source_code": "class CompatibleOpenAIModel(OpenAIChatModel):\n \"\"\"OpenAIChatModel subclass that patches non-standard API proxy responses.\n\n Some OpenAI-compatible proxies return responses with fields like\n choices[].index set to None instead of an integer. This subclass\n fixes those fields before pydantic validation runs.\n \"\"\"\n\n def _validate_completion(self, response: chat.ChatCompletion) -> chat.ChatCompletion:\n # Patch choices[].index: None -> sequential integer (0, 1, 2, ...)\n if response.choices:\n for i, choice in enumerate(response.choices):\n if choice.index is None:\n choice.index = i\n return super()._validate_completion(response)", - "start_line": 104, - "end_line": 118, - "has_docstring": true, - "docstring": "OpenAIChatModel subclass that patches non-standard API proxy responses.\n\nSome OpenAI-compatible proxies return responses with fields like\nchoices[].index set to None instead of an integer. This subclass\nfixes those fields before pydantic validation runs.", - "parameters": null, - "node_type": "class", - "base_classes": [ - "OpenAIChatModel" - ], - "class_name": null, - "display_name": "class CompatibleOpenAIModel", - "component_id": "codewiki/src/be/llm_services.py::CompatibleOpenAIModel", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::CompatibleOpenAIModel._validate_completion": { - "id": "codewiki/src/be/llm_services.py::CompatibleOpenAIModel._validate_completion", - "name": "CompatibleOpenAIModel._validate_completion", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [ - "codewiki/src/be/llm_services.py::CompatibleOpenAIModel._validate_completion" - ], - "source_code": " def _validate_completion(self, response: chat.ChatCompletion) -> chat.ChatCompletion:\n # Patch choices[].index: None -> sequential integer (0, 1, 2, ...)\n if response.choices:\n for i, choice in enumerate(response.choices):\n if choice.index is None:\n choice.index = i\n return super()._validate_completion(response)", - "start_line": 112, - "end_line": 118, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "response" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CompatibleOpenAIModel", - "display_name": "method CompatibleOpenAIModel._validate_completion", - "component_id": "codewiki/src/be/llm_services.py::CompatibleOpenAIModel._validate_completion", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::CachingOpenAIModel": { - "id": "codewiki/src/be/llm_services.py::CachingOpenAIModel", - "name": "CachingOpenAIModel", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [ - "codewiki/src/be/llm_services.py::CompatibleOpenAIModel" - ], - "source_code": "class CachingOpenAIModel(CompatibleOpenAIModel):\n \"\"\"CompatibleOpenAIModel that adds Anthropic-style prompt-cache breakpoints.\n\n Injects ``cache_control: {\"type\": \"ephemeral\"}`` markers into the\n OpenAI-format payload at two points: the last system message (on Anthropic\n this caches the tools + system prefix) and the final message (incremental\n multi-turn caching β€” each turn reads the longest previously cached prefix\n and extends it). OpenAI-compatible proxies such as LiteLLM forward the\n markers to providers that support prompt caching; providers that don't\n either ignore the field or reject the request with a 4xx, in which case the\n request is retried once without markers and the (base_url, model) pair is\n remembered so later calls skip injection entirely.\n \"\"\"\n\n # Plain class attributes (not dataclass fields) so instances copied without\n # __init__ still resolve them.\n _prompt_caching_enabled = False\n _cache_registry_key = (\"\", \"\")\n\n def __init__(self, model_name, *, prompt_caching=True, cache_registry_key=\"\", **kwargs):\n super().__init__(model_name, **kwargs)\n self._prompt_caching_enabled = prompt_caching\n self._cache_registry_key = (cache_registry_key, model_name)\n\n @property\n def _prompt_caching_active(self) -> bool:\n return self._prompt_caching_enabled and self._cache_registry_key not in _CACHE_UNSUPPORTED\n\n async def _map_messages(self, messages, model_request_parameters, *, model_settings=None):\n openai_messages = await super()._map_messages(\n messages, model_request_parameters, model_settings=model_settings\n )\n if self._prompt_caching_active:\n # Breakpoint 1: last system/developer message (covers tools + system).\n for message in reversed(openai_messages):\n if message.get(\"role\") in (\"system\", \"developer\"):\n _add_cache_control_to_message(message)\n break\n # Breakpoint 2: final message (covers the whole conversation prefix).\n if openai_messages:\n _add_cache_control_to_message(openai_messages[-1])\n return openai_messages\n\n async def _completions_create(self, messages, stream, model_settings, model_request_parameters):\n if not self._prompt_caching_active:\n return await super()._completions_create(\n messages, stream, model_settings, model_request_parameters\n )\n try:\n return await super()._completions_create(\n messages, stream, model_settings, model_request_parameters\n )\n except ModelHTTPError as e:\n if e.status_code not in (400, 422):\n raise\n _CACHE_UNSUPPORTED.add(self._cache_registry_key)\n logger.warning(\n \"Provider rejected prompt caching markers for model %s (HTTP %s); \"\n \"retrying without prompt caching.\",\n self.model_name,\n e.status_code,\n )\n try:\n result = await super()._completions_create(\n messages, stream, model_settings, model_request_parameters\n )\n except ModelHTTPError:\n # The failure wasn't (only) about caching β€” don't blame the markers.\n _CACHE_UNSUPPORTED.discard(self._cache_registry_key)\n raise\n logger.warning(\n \"Prompt caching disabled for model %s at this endpoint; \"\n \"continuing with normal calls.\",\n self.model_name,\n )\n return result", - "start_line": 121, - "end_line": 196, - "has_docstring": true, - "docstring": "CompatibleOpenAIModel that adds Anthropic-style prompt-cache breakpoints.\n\nInjects ``cache_control: {\"type\": \"ephemeral\"}`` markers into the\nOpenAI-format payload at two points: the last system message (on Anthropic\nthis caches the tools + system prefix) and the final message (incremental\nmulti-turn caching β€” each turn reads the longest previously cached prefix\nand extends it). OpenAI-compatible proxies such as LiteLLM forward the\nmarkers to providers that support prompt caching; providers that don't\neither ignore the field or reject the request with a 4xx, in which case the\nrequest is retried once without markers and the (base_url, model) pair is\nremembered so later calls skip injection entirely.", - "parameters": null, - "node_type": "class", - "base_classes": [ - "CompatibleOpenAIModel" - ], - "class_name": null, - "display_name": "class CachingOpenAIModel", - "component_id": "codewiki/src/be/llm_services.py::CachingOpenAIModel", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::CachingOpenAIModel.__init__": { - "id": "codewiki/src/be/llm_services.py::CachingOpenAIModel.__init__", - "name": "CachingOpenAIModel.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [], - "source_code": " def __init__(self, model_name, *, prompt_caching=True, cache_registry_key=\"\", **kwargs):\n super().__init__(model_name, **kwargs)\n self._prompt_caching_enabled = prompt_caching\n self._cache_registry_key = (cache_registry_key, model_name)", - "start_line": 140, - "end_line": 143, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "model_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CachingOpenAIModel", - "display_name": "method CachingOpenAIModel.__init__", - "component_id": "codewiki/src/be/llm_services.py::CachingOpenAIModel.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::CachingOpenAIModel._prompt_caching_active": { - "id": "codewiki/src/be/llm_services.py::CachingOpenAIModel._prompt_caching_active", - "name": "CachingOpenAIModel._prompt_caching_active", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [], - "source_code": " def _prompt_caching_active(self) -> bool:\n return self._prompt_caching_enabled and self._cache_registry_key not in _CACHE_UNSUPPORTED", - "start_line": 146, - "end_line": 147, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CachingOpenAIModel", - "display_name": "method CachingOpenAIModel._prompt_caching_active", - "component_id": "codewiki/src/be/llm_services.py::CachingOpenAIModel._prompt_caching_active", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::CachingOpenAIModel._map_messages": { - "id": "codewiki/src/be/llm_services.py::CachingOpenAIModel._map_messages", - "name": "CachingOpenAIModel._map_messages", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/llm_services.py::CachingOpenAIModel._map_messages", - "codewiki/src/be/llm_services.py::_add_cache_control_to_message" - ], - "source_code": " async def _map_messages(self, messages, model_request_parameters, *, model_settings=None):\n openai_messages = await super()._map_messages(\n messages, model_request_parameters, model_settings=model_settings\n )\n if self._prompt_caching_active:\n # Breakpoint 1: last system/developer message (covers tools + system).\n for message in reversed(openai_messages):\n if message.get(\"role\") in (\"system\", \"developer\"):\n _add_cache_control_to_message(message)\n break\n # Breakpoint 2: final message (covers the whole conversation prefix).\n if openai_messages:\n _add_cache_control_to_message(openai_messages[-1])\n return openai_messages", - "start_line": 149, - "end_line": 162, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "messages", - "model_request_parameters" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CachingOpenAIModel", - "display_name": "method CachingOpenAIModel._map_messages", - "component_id": "codewiki/src/be/llm_services.py::CachingOpenAIModel._map_messages", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::CachingOpenAIModel._completions_create": { - "id": "codewiki/src/be/llm_services.py::CachingOpenAIModel._completions_create", - "name": "CachingOpenAIModel._completions_create", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [ - "codewiki/src/be/llm_services.py::CachingOpenAIModel._completions_create" - ], - "source_code": " async def _completions_create(self, messages, stream, model_settings, model_request_parameters):\n if not self._prompt_caching_active:\n return await super()._completions_create(\n messages, stream, model_settings, model_request_parameters\n )\n try:\n return await super()._completions_create(\n messages, stream, model_settings, model_request_parameters\n )\n except ModelHTTPError as e:\n if e.status_code not in (400, 422):\n raise\n _CACHE_UNSUPPORTED.add(self._cache_registry_key)\n logger.warning(\n \"Provider rejected prompt caching markers for model %s (HTTP %s); \"\n \"retrying without prompt caching.\",\n self.model_name,\n e.status_code,\n )\n try:\n result = await super()._completions_create(\n messages, stream, model_settings, model_request_parameters\n )\n except ModelHTTPError:\n # The failure wasn't (only) about caching β€” don't blame the markers.\n _CACHE_UNSUPPORTED.discard(self._cache_registry_key)\n raise\n logger.warning(\n \"Prompt caching disabled for model %s at this endpoint; \"\n \"continuing with normal calls.\",\n self.model_name,\n )\n return result", - "start_line": 164, - "end_line": 196, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "messages", - "stream", - "model_settings", - "model_request_parameters" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CachingOpenAIModel", - "display_name": "method CachingOpenAIModel._completions_create", - "component_id": "codewiki/src/be/llm_services.py::CachingOpenAIModel._completions_create", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::_create_litellm_openai_client": { - "id": "codewiki/src/be/llm_services.py::_create_litellm_openai_client", - "name": "_create_litellm_openai_client", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [], - "source_code": "def _create_litellm_openai_client(config: Config) -> OpenAI:\n \"\"\"\n Create an OpenAI-compatible client backed by litellm's proxy.\n\n litellm translates OpenAI API calls to Bedrock, Anthropic, etc.\n \"\"\"\n # Configure litellm for the provider\n if config.provider == \"bedrock\":\n import os\n os.environ.setdefault(\"AWS_DEFAULT_REGION\", config.aws_region)\n os.environ.setdefault(\"AWS_REGION_NAME\", config.aws_region)\n\n # litellm exposes an OpenAI-compatible Router we can use,\n # but the simplest path is to use litellm.completion() directly.\n # For pydantic-ai integration, we create a proxy client.\n return OpenAI(\n api_key=config.llm_api_key or \"not-needed-for-bedrock\",\n base_url=config.llm_base_url or \"https://api.openai.com/v1\",\n )", - "start_line": 199, - "end_line": 217, - "has_docstring": true, - "docstring": "Create an OpenAI-compatible client backed by litellm's proxy.\n\nlitellm translates OpenAI API calls to Bedrock, Anthropic, etc.", - "parameters": [ - "config" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _create_litellm_openai_client", - "component_id": "codewiki/src/be/llm_services.py::_create_litellm_openai_client", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::create_main_model": { - "id": "codewiki/src/be/llm_services.py::create_main_model", - "name": "create_main_model", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [ - "codewiki/src/be/llm_services.py::CachingOpenAIModel", - "codewiki/src/be/llm_services.py::_build_model_settings" - ], - "source_code": "def create_main_model(config: Config) -> CachingOpenAIModel:\n \"\"\"Create the main LLM model from configuration.\"\"\"\n return CachingOpenAIModel(\n model_name=config.main_model,\n prompt_caching=config.prompt_caching,\n cache_registry_key=config.llm_base_url or \"\",\n provider=OpenAIProvider(\n base_url=config.llm_base_url,\n api_key=config.llm_api_key\n ),\n settings=_build_model_settings(config, config.main_model)\n )", - "start_line": 220, - "end_line": 231, - "has_docstring": true, - "docstring": "Create the main LLM model from configuration.", - "parameters": [ - "config" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function create_main_model", - "component_id": "codewiki/src/be/llm_services.py::create_main_model", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::create_fallback_model": { - "id": "codewiki/src/be/llm_services.py::create_fallback_model", - "name": "create_fallback_model", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [ - "codewiki/src/be/llm_services.py::CachingOpenAIModel", - "codewiki/src/be/llm_services.py::_build_model_settings" - ], - "source_code": "def create_fallback_model(config: Config) -> CachingOpenAIModel:\n \"\"\"Create the fallback LLM model from configuration.\"\"\"\n return CachingOpenAIModel(\n model_name=config.fallback_model,\n prompt_caching=config.prompt_caching,\n cache_registry_key=config.llm_base_url or \"\",\n provider=OpenAIProvider(\n base_url=config.llm_base_url,\n api_key=config.llm_api_key\n ),\n settings=_build_model_settings(config, config.fallback_model)\n )", - "start_line": 234, - "end_line": 245, - "has_docstring": true, - "docstring": "Create the fallback LLM model from configuration.", - "parameters": [ - "config" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function create_fallback_model", - "component_id": "codewiki/src/be/llm_services.py::create_fallback_model", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::create_fallback_models": { - "id": "codewiki/src/be/llm_services.py::create_fallback_models", - "name": "create_fallback_models", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [ - "codewiki/src/be/llm_services.py::create_main_model", - "codewiki/src/be/llm_services.py::create_fallback_model" - ], - "source_code": "def create_fallback_models(config: Config) -> FallbackModel:\n \"\"\"Create fallback models chain from configuration.\"\"\"\n main = create_main_model(config)\n fallback = create_fallback_model(config)\n return FallbackModel(main, fallback)", - "start_line": 248, - "end_line": 252, - "has_docstring": true, - "docstring": "Create fallback models chain from configuration.", - "parameters": [ - "config" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function create_fallback_models", - "component_id": "codewiki/src/be/llm_services.py::create_fallback_models", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::create_openai_client": { - "id": "codewiki/src/be/llm_services.py::create_openai_client", - "name": "create_openai_client", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [], - "source_code": "def create_openai_client(config: Config) -> OpenAI:\n \"\"\"Create OpenAI client from configuration.\"\"\"\n return OpenAI(\n base_url=config.llm_base_url,\n api_key=config.llm_api_key\n )", - "start_line": 255, - "end_line": 260, - "has_docstring": true, - "docstring": "Create OpenAI client from configuration.", - "parameters": [ - "config" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function create_openai_client", - "component_id": "codewiki/src/be/llm_services.py::create_openai_client", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::call_llm": { - "id": "codewiki/src/be/llm_services.py::call_llm", - "name": "call_llm", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.create", - "codewiki/src/be/llm_services.py::create_openai_client", - "codewiki/src/be/llm_services.py::_call_llm_via_azure", - "codewiki/src/be/llm_services.py::_is_unsupported_token_param_error", - "codewiki/src/be/llm_services.py::_should_use_max_completion_tokens", - "codewiki/src/be/llm_services.py::_call_llm_via_litellm" - ], - "source_code": "def call_llm(\n prompt: str,\n config: Config,\n model: str = None\n) -> str:\n \"\"\"\n Call LLM with the given prompt.\n\n Supports openai-compatible, anthropic, and bedrock providers.\n For bedrock/anthropic, uses litellm to translate the API call.\n\n No temperature is sent; requests rely on the provider default (some\n models reject explicit values).\n\n Args:\n prompt: The prompt to send\n config: Configuration containing LLM settings\n model: Model name (defaults to config.main_model)\n\n Returns:\n LLM response text\n \"\"\"\n if model is None:\n model = config.main_model\n\n provider = getattr(config, \"provider\", \"openai-compatible\")\n\n if provider in (\"bedrock\", \"anthropic\"):\n return _call_llm_via_litellm(prompt, config, model)\n\n if provider == \"azure-openai\":\n return _call_llm_via_azure(prompt, config, model)\n\n # Default: OpenAI-compatible\n client = create_openai_client(config)\n\n # Use the correct token parameter based on model/provider; if the server\n # rejects our choice, swap to the other token kwarg and retry once.\n use_completion_tokens = _should_use_max_completion_tokens(model, config.llm_base_url)\n primary_key = \"max_completion_tokens\" if use_completion_tokens else \"max_tokens\"\n fallback_key = \"max_tokens\" if use_completion_tokens else \"max_completion_tokens\"\n\n base_kwargs = {\n \"model\": model,\n \"messages\": [{\"role\": \"user\", \"content\": prompt}],\n }\n\n try:\n response = client.chat.completions.create(\n **base_kwargs,\n **{primary_key: config.max_tokens},\n )\n except BadRequestError as e:\n if _is_unsupported_token_param_error(e, primary_key):\n logger.info(\n \"Provider rejected %s for model %s; retrying with %s.\",\n primary_key, model, fallback_key,\n )\n response = client.chat.completions.create(\n **base_kwargs,\n **{fallback_key: config.max_tokens},\n )\n else:\n raise\n return response.choices[0].message.content", - "start_line": 263, - "end_line": 327, - "has_docstring": true, - "docstring": "Call LLM with the given prompt.\n\nSupports openai-compatible, anthropic, and bedrock providers.\nFor bedrock/anthropic, uses litellm to translate the API call.\n\nNo temperature is sent; requests rely on the provider default (some\nmodels reject explicit values).\n\nArgs:\n prompt: The prompt to send\n config: Configuration containing LLM settings\n model: Model name (defaults to config.main_model)\n\nReturns:\n LLM response text", - "parameters": [ - "prompt", - "config", - "model" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function call_llm", - "component_id": "codewiki/src/be/llm_services.py::call_llm", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::_is_unsupported_token_param_error": { - "id": "codewiki/src/be/llm_services.py::_is_unsupported_token_param_error", - "name": "_is_unsupported_token_param_error", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": "def _is_unsupported_token_param_error(err: BadRequestError, param: str) -> bool:\n \"\"\"Return True if *err* is the OpenAI \"unsupported_parameter\" error for *param*.\"\"\"\n body = getattr(err, \"body\", None) or {}\n if isinstance(body, dict):\n error = body.get(\"error\") or {}\n if isinstance(error, dict):\n if error.get(\"param\") == param and error.get(\"code\") == \"unsupported_parameter\":\n return True\n # Fallback: message-based sniff for proxies that don't preserve structure\n msg = str(err).lower()\n return \"unsupported parameter\" in msg and param in msg", - "start_line": 330, - "end_line": 340, - "has_docstring": true, - "docstring": "Return True if *err* is the OpenAI \"unsupported_parameter\" error for *param*.", - "parameters": [ - "err", - "param" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _is_unsupported_token_param_error", - "component_id": "codewiki/src/be/llm_services.py::_is_unsupported_token_param_error", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::_call_llm_via_litellm": { - "id": "codewiki/src/be/llm_services.py::_call_llm_via_litellm", - "name": "_call_llm_via_litellm", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [ - "codewiki/src/be/llm_services.py::_get_litellm_model_name", - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": "def _call_llm_via_litellm(\n prompt: str,\n config: Config,\n model: str\n) -> str:\n \"\"\"\n Call LLM via litellm for Bedrock/Anthropic providers.\n\n litellm handles the provider-specific API translation automatically.\n \"\"\"\n import litellm\n import os\n\n litellm_model = _get_litellm_model_name(model, config.provider)\n\n if config.provider == \"bedrock\":\n os.environ.setdefault(\"AWS_DEFAULT_REGION\", config.aws_region)\n os.environ.setdefault(\"AWS_REGION_NAME\", config.aws_region)\n logger.debug(\"Calling Bedrock model %s in region %s\", litellm_model, config.aws_region)\n elif config.provider == \"anthropic\":\n logger.debug(\"Calling Anthropic model %s via litellm\", litellm_model)\n\n response = litellm.completion(\n model=litellm_model,\n messages=[{\"role\": \"user\", \"content\": prompt}],\n max_tokens=config.max_tokens,\n api_key=config.llm_api_key if config.provider != \"bedrock\" else None,\n )\n return response.choices[0].message.content", - "start_line": 343, - "end_line": 371, - "has_docstring": true, - "docstring": "Call LLM via litellm for Bedrock/Anthropic providers.\n\nlitellm handles the provider-specific API translation automatically.", - "parameters": [ - "prompt", - "config", - "model" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _call_llm_via_litellm", - "component_id": "codewiki/src/be/llm_services.py::_call_llm_via_litellm", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/llm_services.py::_call_llm_via_azure": { - "id": "codewiki/src/be/llm_services.py::_call_llm_via_azure", - "name": "_call_llm_via_azure", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/llm_services.py", - "relative_path": "codewiki/src/be/llm_services.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.create", - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": "def _call_llm_via_azure(\n prompt: str,\n config: Config,\n model: str\n) -> str:\n \"\"\"\n Call LLM via Azure OpenAI.\n\n Uses the AzureOpenAI client from the openai package with\n azure_endpoint, api_version, and deployment name.\n \"\"\"\n from openai import AzureOpenAI\n\n client = AzureOpenAI(\n api_key=config.llm_api_key,\n api_version=config.api_version,\n azure_endpoint=config.llm_base_url,\n )\n\n deployment = config.azure_deployment or model\n logger.debug(\"Calling Azure OpenAI deployment %s (api_version=%s)\", deployment, config.api_version)\n\n response = client.chat.completions.create(\n model=deployment,\n messages=[{\"role\": \"user\", \"content\": prompt}],\n max_tokens=config.max_tokens,\n )\n return response.choices[0].message.content", - "start_line": 374, - "end_line": 401, - "has_docstring": true, - "docstring": "Call LLM via Azure OpenAI.\n\nUses the AzureOpenAI client from the openai package with\nazure_endpoint, api_version, and deployment name.", - "parameters": [ - "prompt", - "config", - "model" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _call_llm_via_azure", - "component_id": "codewiki/src/be/llm_services.py::_call_llm_via_azure", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/main.py::parse_arguments": { - "id": "codewiki/src/be/main.py::parse_arguments", - "name": "parse_arguments", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/main.py", - "relative_path": "codewiki/src/be/main.py", - "depends_on": [], - "source_code": "def parse_arguments() -> argparse.Namespace:\n \"\"\"Parse command line arguments.\"\"\"\n parser = argparse.ArgumentParser(\n description='Generate comprehensive documentation for Python components in dependency order.'\n )\n parser.add_argument(\n '--repo-path',\n type=str,\n required=True,\n help='Path to the repository'\n )\n \n return parser.parse_args()", - "start_line": 31, - "end_line": 43, - "has_docstring": true, - "docstring": "Parse command line arguments.", - "parameters": [], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function parse_arguments", - "component_id": "codewiki/src/be/main.py::parse_arguments", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/main.py::main": { - "id": "codewiki/src/be/main.py::main", - "name": "main", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/main.py", - "relative_path": "codewiki/src/be/main.py", - "depends_on": [ - "codewiki/src/be/documentation_generator.py::DocumentationGenerator", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.run", - "codewiki/src/config.py::Config.from_args", - "codewiki/src/be/main.py::parse_arguments", - "codewiki/cli/utils/logging.py::CLILogger.debug", - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": "async def main() -> None:\n \"\"\"Main entry point for the documentation generation process.\"\"\"\n try:\n # Parse arguments and create configuration\n args = parse_arguments()\n config = Config.from_args(args)\n \n # Create and run documentation generator\n doc_generator = DocumentationGenerator(config)\n await doc_generator.run()\n \n except KeyboardInterrupt:\n logger.debug(\"Documentation generation interrupted by user\")\n except Exception as e:\n logger.error(f\"Unexpected error: {str(e)}\")\n logger.error(f\"Traceback: {traceback.format_exc()}\")\n raise", - "start_line": 46, - "end_line": 62, - "has_docstring": true, - "docstring": "Main entry point for the documentation generation process.", - "parameters": [], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function main", - "component_id": "codewiki/src/be/main.py::main", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/module_naming.py::sanitize_module_name": { - "id": "codewiki/src/be/module_naming.py::sanitize_module_name", - "name": "sanitize_module_name", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/module_naming.py", - "relative_path": "codewiki/src/be/module_naming.py", - "depends_on": [], - "source_code": "def sanitize_module_name(name: str) -> str:\n \"\"\"Make a module name safe to use as a filename stem (no case changes).\"\"\"\n cleaned = \"\".join(\"_\" if c in _UNSAFE_FILENAME_CHARS else c for c in str(name).strip())\n cleaned = cleaned.replace(\" \", \"_\").strip(\"._\")\n return cleaned or \"module\"", - "start_line": 22, - "end_line": 26, - "has_docstring": true, - "docstring": "Make a module name safe to use as a filename stem (no case changes).", - "parameters": [ - "name" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function sanitize_module_name", - "component_id": "codewiki/src/be/module_naming.py::sanitize_module_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/module_naming.py::collect_module_tree_names": { - "id": "codewiki/src/be/module_naming.py::collect_module_tree_names", - "name": "collect_module_tree_names", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/module_naming.py", - "relative_path": "codewiki/src/be/module_naming.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": "def collect_module_tree_names(module_tree: Dict[str, Any]) -> Set[str]:\n \"\"\"Collect all module names at every depth of the tree.\"\"\"\n names = set()\n stack = [module_tree]\n while stack:\n level = stack.pop()\n if not isinstance(level, dict):\n continue\n for name, info in level.items():\n names.add(name)\n if isinstance(info, dict) and isinstance(info.get(\"children\"), dict):\n stack.append(info[\"children\"])\n return names", - "start_line": 29, - "end_line": 41, - "has_docstring": true, - "docstring": "Collect all module names at every depth of the tree.", - "parameters": [ - "module_tree" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function collect_module_tree_names", - "component_id": "codewiki/src/be/module_naming.py::collect_module_tree_names", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/module_naming.py::resolve_unique_name": { - "id": "codewiki/src/be/module_naming.py::resolve_unique_name", - "name": "resolve_unique_name", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/module_naming.py", - "relative_path": "codewiki/src/be/module_naming.py", - "depends_on": [ - "codewiki/src/be/module_naming.py::sanitize_module_name" - ], - "source_code": "def resolve_unique_name(name: str, parent_name: Optional[str], taken: Set[str]) -> str:\n \"\"\"Return ``name`` if free, else prefix with parent, else add a numeric suffix.\"\"\"\n if name not in taken:\n return name\n if parent_name:\n prefixed = f\"{sanitize_module_name(parent_name)}_{name}\"\n if prefixed not in taken:\n return prefixed\n else:\n prefixed = name\n n = 2\n while f\"{prefixed}_{n}\" in taken:\n n += 1\n return f\"{prefixed}_{n}\"", - "start_line": 44, - "end_line": 57, - "has_docstring": true, - "docstring": "Return ``name`` if free, else prefix with parent, else add a numeric suffix.", - "parameters": [ - "name", - "parent_name", - "taken" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function resolve_unique_name", - "component_id": "codewiki/src/be/module_naming.py::resolve_unique_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/module_naming.py::_existing_doc_stems": { - "id": "codewiki/src/be/module_naming.py::_existing_doc_stems", - "name": "_existing_doc_stems", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/module_naming.py", - "relative_path": "codewiki/src/be/module_naming.py", - "depends_on": [], - "source_code": "def _existing_doc_stems(working_dir: str) -> Set[str]:\n try:\n return {\n os.path.splitext(entry)[0]\n for entry in os.listdir(working_dir)\n if entry.endswith(\".md\")\n }\n except OSError:\n return set()", - "start_line": 60, - "end_line": 68, - "has_docstring": false, - "docstring": "", - "parameters": [ - "working_dir" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _existing_doc_stems", - "component_id": "codewiki/src/be/module_naming.py::_existing_doc_stems", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/module_naming.py::normalize_sub_module_specs": { - "id": "codewiki/src/be/module_naming.py::normalize_sub_module_specs", - "name": "normalize_sub_module_specs", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/module_naming.py", - "relative_path": "codewiki/src/be/module_naming.py", - "depends_on": [ - "codewiki/src/be/module_naming.py::resolve_unique_name", - "codewiki/src/be/module_naming.py::sanitize_module_name", - "codewiki/src/be/module_naming.py::collect_module_tree_names", - "codewiki/src/be/module_naming.py::_existing_doc_stems" - ], - "source_code": "def normalize_sub_module_specs(\n sub_module_specs: Dict[str, Any],\n parent_name: Optional[str],\n module_tree: Dict[str, Any],\n working_dir: str,\n) -> Dict[str, str]:\n \"\"\"Map requested sub-module names to unique, file-safe final names.\n\n A name is taken if it already appears anywhere in the module tree, if a\n ``.md`` with that stem exists in the flat docs dir, if it is reserved, or\n if it was assigned earlier in this batch.\n \"\"\"\n taken = collect_module_tree_names(module_tree)\n taken |= _existing_doc_stems(working_dir)\n taken |= RESERVED_STEMS\n\n name_map: Dict[str, str] = {}\n for requested_name in sub_module_specs:\n final_name = resolve_unique_name(sanitize_module_name(requested_name), parent_name, taken)\n taken.add(final_name)\n name_map[requested_name] = final_name\n if final_name != requested_name:\n logger.info(\n \"Sub-module name '%s' collides with an existing module or file; renamed to '%s'.\",\n requested_name,\n final_name,\n )\n return name_map", - "start_line": 71, - "end_line": 98, - "has_docstring": true, - "docstring": "Map requested sub-module names to unique, file-safe final names.\n\nA name is taken if it already appears anywhere in the module tree, if a\n``.md`` with that stem exists in the flat docs dir, if it is reserved, or\nif it was assigned earlier in this batch.", - "parameters": [ - "sub_module_specs", - "parent_name", - "module_tree", - "working_dir" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function normalize_sub_module_specs", - "component_id": "codewiki/src/be/module_naming.py::normalize_sub_module_specs", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/module_naming.py::dedupe_module_tree_names": { - "id": "codewiki/src/be/module_naming.py::dedupe_module_tree_names", - "name": "dedupe_module_tree_names", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/module_naming.py", - "relative_path": "codewiki/src/be/module_naming.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/be/module_naming.py::resolve_unique_name", - "codewiki/src/be/module_naming.py::sanitize_module_name" - ], - "source_code": "def dedupe_module_tree_names(module_tree: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Sanitize and uniquify all module names in a freshly clustered tree.\n\n Must only run on trees whose docs have not been generated yet β€” renaming\n a key whose ``.md`` already exists would orphan the doc.\n \"\"\"\n taken: Set[str] = set(RESERVED_STEMS)\n\n def dedupe_level(level: Dict[str, Any], parent_name: Optional[str]) -> Dict[str, Any]:\n result: Dict[str, Any] = {}\n for name, info in level.items():\n final_name = resolve_unique_name(sanitize_module_name(name), parent_name, taken)\n taken.add(final_name)\n if final_name != name:\n logger.info(\"Module name '%s' collides; renamed to '%s'.\", name, final_name)\n if isinstance(info, dict) and isinstance(info.get(\"children\"), dict):\n info = {**info, \"children\": dedupe_level(info[\"children\"], final_name)}\n result[final_name] = info\n return result\n\n return dedupe_level(module_tree, None)", - "start_line": 101, - "end_line": 121, - "has_docstring": true, - "docstring": "Sanitize and uniquify all module names in a freshly clustered tree.\n\nMust only run on trees whose docs have not been generated yet β€” renaming\na key whose ``.md`` already exists would orphan the doc.", - "parameters": [ - "module_tree" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function dedupe_module_tree_names", - "component_id": "codewiki/src/be/module_naming.py::dedupe_module_tree_names", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/module_naming.py::resolve_module_doc_path": { - "id": "codewiki/src/be/module_naming.py::resolve_module_doc_path", - "name": "resolve_module_doc_path", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/module_naming.py", - "relative_path": "codewiki/src/be/module_naming.py", - "depends_on": [], - "source_code": "def resolve_module_doc_path(working_dir: str, module_name: str) -> Optional[str]:\n \"\"\"Resolve the on-disk path for a module's .md doc.\n\n Sub-agents sometimes save files under a sanitized variant of the module\n name (spaces β†’ underscores, lowercased, etc.) rather than the exact key\n in the module tree. Try a small set of common variants before giving up.\n \"\"\"\n candidates = []\n seen = set()\n base_variants = [\n module_name,\n module_name.replace(\" \", \"_\"),\n module_name.replace(\" \", \"-\"),\n module_name.replace(\" \", \"\"),\n ]\n for variant in base_variants:\n for cased in (variant, variant.lower()):\n if cased not in seen:\n seen.add(cased)\n candidates.append(f\"{cased}.md\")\n\n for filename in candidates:\n candidate_path = os.path.join(working_dir, filename)\n if os.path.exists(candidate_path):\n return candidate_path\n return None", - "start_line": 124, - "end_line": 149, - "has_docstring": true, - "docstring": "Resolve the on-disk path for a module's .md doc.\n\nSub-agents sometimes save files under a sanitized variant of the module\nname (spaces β†’ underscores, lowercased, etc.) rather than the exact key\nin the module tree. Try a small set of common variants before giving up.", - "parameters": [ - "working_dir", - "module_name" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function resolve_module_doc_path", - "component_id": "codewiki/src/be/module_naming.py::resolve_module_doc_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/module_naming.py::find_missing_module_docs": { - "id": "codewiki/src/be/module_naming.py::find_missing_module_docs", - "name": "find_missing_module_docs", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/module_naming.py", - "relative_path": "codewiki/src/be/module_naming.py", - "depends_on": [ - "codewiki/src/be/module_naming.py::resolve_module_doc_path", - "codewiki/src/be/module_naming.py::collect_module_tree_names" - ], - "source_code": "def find_missing_module_docs(\n module_tree: Dict[str, Any],\n working_dir: str,\n overview_required: bool = True,\n) -> List[str]:\n \"\"\"Return module names from the tree whose docs are missing on disk.\"\"\"\n missing = []\n for name in sorted(collect_module_tree_names(module_tree)):\n if resolve_module_doc_path(working_dir, name) is None:\n missing.append(name)\n if overview_required and not os.path.exists(os.path.join(working_dir, \"overview.md\")):\n missing.append(\"overview\")\n return missing", - "start_line": 152, - "end_line": 164, - "has_docstring": true, - "docstring": "Return module names from the tree whose docs are missing on disk.", - "parameters": [ - "module_tree", - "working_dir", - "overview_required" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function find_missing_module_docs", - "component_id": "codewiki/src/be/module_naming.py::find_missing_module_docs", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/prompt_template.py::format_user_prompt": { - "id": "codewiki/src/be/prompt_template.py::format_user_prompt", - "name": "format_user_prompt", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/prompt_template.py", - "relative_path": "codewiki/src/be/prompt_template.py", - "depends_on": [ - "codewiki/src/utils.py::FileManager.load_text", - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter.format" - ], - "source_code": "def format_user_prompt(module_name: str, core_component_ids: list[str], components: Dict[str, Any], module_tree: dict[str, any]) -> str:\n \"\"\"\n Format the user prompt with module name and organized core component codes.\n \n Args:\n module_name: Name of the module to document\n core_component_ids: List of component IDs to include\n components: Dictionary mapping component IDs to CodeComponent objects\n \n Returns:\n Formatted user prompt string\n \"\"\"\n\n # format module tree\n lines = []\n \n def _format_module_tree(module_tree: dict[str, any], indent: int = 0):\n for key, value in module_tree.items():\n if key == module_name:\n lines.append(f\"{' ' * indent}{key} (current module)\")\n else:\n lines.append(f\"{' ' * indent}{key}\")\n\n # Group components by file\n from collections import defaultdict\n by_file = defaultdict(list)\n for c in value['components']:\n if \"::\" in c:\n fpath, name = c.split(\"::\", 1)\n by_file[fpath].append(name)\n else:\n by_file[\"\"].append(c)\n for fpath, names in by_file.items():\n if fpath:\n lines.append(f\"{' ' * (indent + 1)} {fpath}: {', '.join(names)}\")\n else:\n lines.append(f\"{' ' * (indent + 1)} {', '.join(names)}\")\n\n if isinstance(value[\"children\"], dict) and len(value[\"children\"]) > 0:\n lines.append(f\"{' ' * (indent + 1)} Children:\")\n _format_module_tree(value[\"children\"], indent + 2)\n\n _format_module_tree(module_tree, 0)\n formatted_module_tree = \"\\n\".join(lines)\n\n # print(f\"Formatted module tree:\\n{formatted_module_tree}\")\n\n # Group core component IDs by their file path\n grouped_components: dict[str, list[str]] = {}\n for component_id in core_component_ids:\n if component_id not in components:\n continue\n component = components[component_id]\n path = component.relative_path\n if path not in grouped_components:\n grouped_components[path] = []\n grouped_components[path].append(component_id)\n\n core_component_codes = \"\"\n for path, component_ids_in_file in grouped_components.items():\n core_component_codes += f\"# File: {path}\\n\\n\"\n core_component_codes += f\"## Core Components in this file:\\n\"\n \n for component_id in component_ids_in_file:\n core_component_codes += f\"- {component_id}\\n\"\n \n core_component_codes += f\"\\n## File Content:\\n```{EXTENSION_TO_LANGUAGE['.'+path.split('.')[-1]]}\\n\"\n \n # Read content of the file using the first component's file path\n try:\n core_component_codes += file_manager.load_text(components[component_ids_in_file[0]].file_path)\n except (FileNotFoundError, IOError) as e:\n core_component_codes += f\"# Error reading file: {e}\\n\"\n \n core_component_codes += \"```\\n\\n\"\n \n return USER_PROMPT.format(module_name=module_name, formatted_core_component_codes=core_component_codes, module_tree=formatted_module_tree)", - "start_line": 251, - "end_line": 327, - "has_docstring": true, - "docstring": "Format the user prompt with module name and organized core component codes.\n\nArgs:\n module_name: Name of the module to document\n core_component_ids: List of component IDs to include\n components: Dictionary mapping component IDs to CodeComponent objects\n\nReturns:\n Formatted user prompt string", - "parameters": [ - "module_name", - "core_component_ids", - "components", - "module_tree" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function format_user_prompt", - "component_id": "codewiki/src/be/prompt_template.py::format_user_prompt", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/prompt_template.py::format_cluster_prompt": { - "id": "codewiki/src/be/prompt_template.py::format_cluster_prompt", - "name": "format_cluster_prompt", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/prompt_template.py", - "relative_path": "codewiki/src/be/prompt_template.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter.format" - ], - "source_code": "def format_cluster_prompt(potential_core_components: str, module_tree: dict[str, any] = {}, module_name: str = None) -> str:\n \"\"\"\n Format the cluster prompt with potential core components and module tree.\n \"\"\"\n\n # format module tree\n lines = []\n\n # print(f\"Module tree:\\n{json.dumps(module_tree, indent=2)}\")\n \n def _format_module_tree(module_tree: dict[str, any], indent: int = 0):\n for key, value in module_tree.items():\n if key == module_name:\n lines.append(f\"{' ' * indent}{key} (current module)\")\n else:\n lines.append(f\"{' ' * indent}{key}\")\n \n # Group components by file\n from collections import defaultdict\n by_file = defaultdict(list)\n for c in value['components']:\n if \"::\" in c:\n fpath, name = c.split(\"::\", 1)\n by_file[fpath].append(name)\n else:\n by_file[\"\"].append(c)\n for fpath, names in by_file.items():\n if fpath:\n lines.append(f\"{' ' * (indent + 1)} {fpath}: {', '.join(names)}\")\n else:\n lines.append(f\"{' ' * (indent + 1)} {', '.join(names)}\")\n\n if (\"children\" in value) and isinstance(value[\"children\"], dict) and len(value[\"children\"]) > 0:\n lines.append(f\"{' ' * (indent + 1)} Children:\")\n _format_module_tree(value[\"children\"], indent + 2)\n \n _format_module_tree(module_tree, 0)\n formatted_module_tree = \"\\n\".join(lines)\n\n\n if module_tree == {}:\n return CLUSTER_REPO_PROMPT.format(potential_core_components=potential_core_components)\n else:\n return CLUSTER_MODULE_PROMPT.format(potential_core_components=potential_core_components, module_tree=formatted_module_tree, module_name=module_name)", - "start_line": 331, - "end_line": 374, - "has_docstring": true, - "docstring": "Format the cluster prompt with potential core components and module tree.", - "parameters": [ - "potential_core_components", - "module_tree", - "module_name" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function format_cluster_prompt", - "component_id": "codewiki/src/be/prompt_template.py::format_cluster_prompt", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/prompt_template.py::format_system_prompt": { - "id": "codewiki/src/be/prompt_template.py::format_system_prompt", - "name": "format_system_prompt", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/prompt_template.py", - "relative_path": "codewiki/src/be/prompt_template.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter.format" - ], - "source_code": "def format_system_prompt(module_name: str, custom_instructions: str = None) -> str:\n \"\"\"\n Format the system prompt with module name and optional custom instructions.\n \n Args:\n module_name: Name of the module to document\n custom_instructions: Optional custom instructions to append\n \n Returns:\n Formatted system prompt string\n \"\"\"\n custom_section = \"\"\n if custom_instructions:\n custom_section = f\"\\n\\n\\n{custom_instructions}\\n\"\n \n return SYSTEM_PROMPT.format(module_name=module_name, custom_instructions=custom_section).strip()", - "start_line": 377, - "end_line": 392, - "has_docstring": true, - "docstring": "Format the system prompt with module name and optional custom instructions.\n\nArgs:\n module_name: Name of the module to document\n custom_instructions: Optional custom instructions to append\n \nReturns:\n Formatted system prompt string", - "parameters": [ - "module_name", - "custom_instructions" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function format_system_prompt", - "component_id": "codewiki/src/be/prompt_template.py::format_system_prompt", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/prompt_template.py::format_leaf_system_prompt": { - "id": "codewiki/src/be/prompt_template.py::format_leaf_system_prompt", - "name": "format_leaf_system_prompt", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/prompt_template.py", - "relative_path": "codewiki/src/be/prompt_template.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/utils/logging_config.py::ColoredFormatter.format" - ], - "source_code": "def format_leaf_system_prompt(module_name: str, custom_instructions: str = None) -> str:\n \"\"\"\n Format the leaf system prompt with module name and optional custom instructions.\n \n Args:\n module_name: Name of the module to document\n custom_instructions: Optional custom instructions to append\n \n Returns:\n Formatted leaf system prompt string\n \"\"\"\n custom_section = \"\"\n if custom_instructions:\n custom_section = f\"\\n\\n\\n{custom_instructions}\\n\"\n \n return LEAF_SYSTEM_PROMPT.format(module_name=module_name, custom_instructions=custom_section).strip()", - "start_line": 395, - "end_line": 410, - "has_docstring": true, - "docstring": "Format the leaf system prompt with module name and optional custom instructions.\n\nArgs:\n module_name: Name of the module to document\n custom_instructions: Optional custom instructions to append\n \nReturns:\n Formatted leaf system prompt string", - "parameters": [ - "module_name", - "custom_instructions" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function format_leaf_system_prompt", - "component_id": "codewiki/src/be/prompt_template.py::format_leaf_system_prompt", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/pydantic_ai_backend.py::PydanticAIBackend": { - "id": "codewiki/src/be/pydantic_ai_backend.py::PydanticAIBackend", - "name": "PydanticAIBackend", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/pydantic_ai_backend.py", - "relative_path": "codewiki/src/be/pydantic_ai_backend.py", - "depends_on": [ - "codewiki/src/be/backend.py::LLMBackend" - ], - "source_code": "class PydanticAIBackend(LLMBackend):\n \"\"\"API-key based backend using pydantic-ai + openai/litellm clients.\"\"\"\n\n def __init__(self, config: Config) -> None:\n self._config = config\n self._fallback_models = create_fallback_models(config)\n self._custom_instructions = config.get_prompt_addition()\n\n def complete(\n self,\n prompt: str,\n *,\n model: str | None = None,\n ) -> str:\n return call_llm(prompt, self._config, model=model)\n\n async def run_module_agent(\n self,\n module_name: str,\n components: Dict[str, Node],\n core_component_ids: List[str],\n module_path: List[str],\n working_dir: str,\n ) -> Dict[str, Any]:\n config = self._config\n module_tree_path = os.path.join(working_dir, MODULE_TREE_FILENAME)\n module_tree = file_manager.load_json(module_tree_path)\n\n overview_docs_path = os.path.join(working_dir, OVERVIEW_FILENAME)\n if os.path.exists(overview_docs_path):\n logger.info(\"βœ“ Overview docs already exists at %s\", overview_docs_path)\n return module_tree\n docs_path = os.path.join(working_dir, f\"{module_name}.md\")\n if os.path.exists(docs_path):\n logger.info(\"βœ“ Module docs already exists at %s\", docs_path)\n return module_tree\n\n if is_complex_module(components, core_component_ids):\n agent = Agent(\n self._fallback_models,\n name=module_name,\n deps_type=CodeWikiDeps,\n tools=[\n read_code_components_tool,\n str_replace_editor_tool,\n generate_sub_module_documentation_tool,\n ],\n system_prompt=format_system_prompt(module_name, self._custom_instructions),\n )\n else:\n agent = Agent(\n self._fallback_models,\n name=module_name,\n deps_type=CodeWikiDeps,\n tools=[read_code_components_tool, str_replace_editor_tool],\n system_prompt=format_leaf_system_prompt(module_name, self._custom_instructions),\n )\n\n deps = CodeWikiDeps(\n absolute_docs_path=working_dir,\n absolute_repo_path=str(os.path.abspath(config.repo_path)),\n registry={},\n components=components,\n path_to_current_module=module_path,\n current_module_name=module_name,\n module_tree=module_tree,\n max_depth=config.max_depth,\n current_depth=1,\n config=config,\n custom_instructions=self._custom_instructions,\n )\n\n try:\n await agent.run(\n format_user_prompt(\n module_name=module_name,\n core_component_ids=core_component_ids,\n components=components,\n module_tree=deps.module_tree,\n ),\n deps=deps,\n )\n file_manager.save_json(deps.module_tree, module_tree_path)\n return deps.module_tree\n except Exception as e:\n logger.error(\"Error processing module %s: %s\", module_name, e)\n logger.error(\"Traceback: %s\", traceback.format_exc())\n raise", - "start_line": 39, - "end_line": 126, - "has_docstring": true, - "docstring": "API-key based backend using pydantic-ai + openai/litellm clients.", - "parameters": null, - "node_type": "class", - "base_classes": [ - "LLMBackend" - ], - "class_name": null, - "display_name": "class PydanticAIBackend", - "component_id": "codewiki/src/be/pydantic_ai_backend.py::PydanticAIBackend", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/pydantic_ai_backend.py::PydanticAIBackend.__init__": { - "id": "codewiki/src/be/pydantic_ai_backend.py::PydanticAIBackend.__init__", - "name": "PydanticAIBackend.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/pydantic_ai_backend.py", - "relative_path": "codewiki/src/be/pydantic_ai_backend.py", - "depends_on": [ - "codewiki/src/be/llm_services.py::create_fallback_models" - ], - "source_code": " def __init__(self, config: Config) -> None:\n self._config = config\n self._fallback_models = create_fallback_models(config)\n self._custom_instructions = config.get_prompt_addition()", - "start_line": 42, - "end_line": 45, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "config" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PydanticAIBackend", - "display_name": "method PydanticAIBackend.__init__", - "component_id": "codewiki/src/be/pydantic_ai_backend.py::PydanticAIBackend.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/pydantic_ai_backend.py::PydanticAIBackend.complete": { - "id": "codewiki/src/be/pydantic_ai_backend.py::PydanticAIBackend.complete", - "name": "PydanticAIBackend.complete", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/pydantic_ai_backend.py", - "relative_path": "codewiki/src/be/pydantic_ai_backend.py", - "depends_on": [ - "codewiki/src/be/llm_services.py::call_llm" - ], - "source_code": " def complete(\n self,\n prompt: str,\n *,\n model: str | None = None,\n ) -> str:\n return call_llm(prompt, self._config, model=model)", - "start_line": 47, - "end_line": 53, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "prompt" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PydanticAIBackend", - "display_name": "method PydanticAIBackend.complete", - "component_id": "codewiki/src/be/pydantic_ai_backend.py::PydanticAIBackend.complete", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/pydantic_ai_backend.py::PydanticAIBackend.run_module_agent": { - "id": "codewiki/src/be/pydantic_ai_backend.py::PydanticAIBackend.run_module_agent", - "name": "PydanticAIBackend.run_module_agent", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/pydantic_ai_backend.py", - "relative_path": "codewiki/src/be/pydantic_ai_backend.py", - "depends_on": [ - "codewiki/src/be/prompt_template.py::format_leaf_system_prompt", - "codewiki/src/be/agent_tools/deps.py::CodeWikiDeps", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.run", - "codewiki/src/utils.py::FileManager.load_json", - "codewiki/src/be/prompt_template.py::format_system_prompt", - "codewiki/src/be/utils.py::is_complex_module", - "codewiki/src/utils.py::FileManager.save_json", - "codewiki/src/be/prompt_template.py::format_user_prompt", - "codewiki/cli/utils/logging.py::CLILogger.error" - ], - "source_code": " async def run_module_agent(\n self,\n module_name: str,\n components: Dict[str, Node],\n core_component_ids: List[str],\n module_path: List[str],\n working_dir: str,\n ) -> Dict[str, Any]:\n config = self._config\n module_tree_path = os.path.join(working_dir, MODULE_TREE_FILENAME)\n module_tree = file_manager.load_json(module_tree_path)\n\n overview_docs_path = os.path.join(working_dir, OVERVIEW_FILENAME)\n if os.path.exists(overview_docs_path):\n logger.info(\"βœ“ Overview docs already exists at %s\", overview_docs_path)\n return module_tree\n docs_path = os.path.join(working_dir, f\"{module_name}.md\")\n if os.path.exists(docs_path):\n logger.info(\"βœ“ Module docs already exists at %s\", docs_path)\n return module_tree\n\n if is_complex_module(components, core_component_ids):\n agent = Agent(\n self._fallback_models,\n name=module_name,\n deps_type=CodeWikiDeps,\n tools=[\n read_code_components_tool,\n str_replace_editor_tool,\n generate_sub_module_documentation_tool,\n ],\n system_prompt=format_system_prompt(module_name, self._custom_instructions),\n )\n else:\n agent = Agent(\n self._fallback_models,\n name=module_name,\n deps_type=CodeWikiDeps,\n tools=[read_code_components_tool, str_replace_editor_tool],\n system_prompt=format_leaf_system_prompt(module_name, self._custom_instructions),\n )\n\n deps = CodeWikiDeps(\n absolute_docs_path=working_dir,\n absolute_repo_path=str(os.path.abspath(config.repo_path)),\n registry={},\n components=components,\n path_to_current_module=module_path,\n current_module_name=module_name,\n module_tree=module_tree,\n max_depth=config.max_depth,\n current_depth=1,\n config=config,\n custom_instructions=self._custom_instructions,\n )\n\n try:\n await agent.run(\n format_user_prompt(\n module_name=module_name,\n core_component_ids=core_component_ids,\n components=components,\n module_tree=deps.module_tree,\n ),\n deps=deps,\n )\n file_manager.save_json(deps.module_tree, module_tree_path)\n return deps.module_tree\n except Exception as e:\n logger.error(\"Error processing module %s: %s\", module_name, e)\n logger.error(\"Traceback: %s\", traceback.format_exc())\n raise", - "start_line": 55, - "end_line": 126, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "module_name", - "components", - "core_component_ids", - "module_path", - "working_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "PydanticAIBackend", - "display_name": "method PydanticAIBackend.run_module_agent", - "component_id": "codewiki/src/be/pydantic_ai_backend.py::PydanticAIBackend.run_module_agent", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/utils.py::set_main_loop": { - "id": "codewiki/src/be/utils.py::set_main_loop", - "name": "set_main_loop", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/utils.py", - "relative_path": "codewiki/src/be/utils.py", - "depends_on": [], - "source_code": "def set_main_loop(loop: asyncio.AbstractEventLoop) -> None:\n global _main_loop, _main_loop_thread_ident\n _main_loop = loop\n _main_loop_thread_ident = threading.get_ident()", - "start_line": 27, - "end_line": 30, - "has_docstring": false, - "docstring": "", - "parameters": [ - "loop" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function set_main_loop", - "component_id": "codewiki/src/be/utils.py::set_main_loop", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/utils.py::is_complex_module": { - "id": "codewiki/src/be/utils.py::is_complex_module", - "name": "is_complex_module", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/utils.py", - "relative_path": "codewiki/src/be/utils.py", - "depends_on": [], - "source_code": "def is_complex_module(components: dict[str, any], core_component_ids: list[str]) -> bool:\n files = set()\n for component_id in core_component_ids:\n if component_id in components:\n files.add(components[component_id].file_path)\n\n result = len(files) > 1\n\n return result", - "start_line": 36, - "end_line": 44, - "has_docstring": false, - "docstring": "", - "parameters": [ - "components", - "core_component_ids" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function is_complex_module", - "component_id": "codewiki/src/be/utils.py::is_complex_module", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/utils.py::count_tokens": { - "id": "codewiki/src/be/utils.py::count_tokens", - "name": "count_tokens", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/utils.py", - "relative_path": "codewiki/src/be/utils.py", - "depends_on": [], - "source_code": "def count_tokens(text: str) -> int:\n \"\"\"\n Count the number of tokens in a text.\n \"\"\"\n length = len(enc.encode(text))\n # logger.debug(f\"Number of tokens: {length}\")\n return length", - "start_line": 53, - "end_line": 59, - "has_docstring": true, - "docstring": "Count the number of tokens in a text.", - "parameters": [ - "text" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function count_tokens", - "component_id": "codewiki/src/be/utils.py::count_tokens", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/utils.py::validate_mermaid_diagrams": { - "id": "codewiki/src/be/utils.py::validate_mermaid_diagrams", - "name": "validate_mermaid_diagrams", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/utils.py", - "relative_path": "codewiki/src/be/utils.py", - "depends_on": [ - "codewiki/src/be/utils.py::validate_single_diagram", - "codewiki/src/be/utils.py::extract_mermaid_blocks" - ], - "source_code": "async def validate_mermaid_diagrams(md_file_path: str, relative_path: str) -> str:\n \"\"\"\n Validate all Mermaid diagrams in a markdown file.\n \n Args:\n md_file_path: Path to the markdown file to check\n relative_path: Relative path to the markdown file\n Returns:\n \"All mermaid diagrams are syntax correct\" if all diagrams are valid,\n otherwise returns error message with details about invalid diagrams\n \"\"\"\n\n try:\n # Read the markdown file\n file_path = Path(md_file_path)\n if not file_path.exists():\n return f\"Error: File '{md_file_path}' does not exist\"\n \n content = file_path.read_text(encoding='utf-8')\n \n # Extract all mermaid code blocks\n mermaid_blocks = extract_mermaid_blocks(content)\n \n if not mermaid_blocks:\n return \"No mermaid diagrams found in the file\"\n \n # Validate each mermaid diagram sequentially to avoid segfaults\n errors = []\n for i, (line_start, diagram_content) in enumerate(mermaid_blocks, 1):\n error_msg = await validate_single_diagram(diagram_content, i, line_start)\n if error_msg:\n errors.append(\"\\n\")\n errors.append(error_msg)\n \n # if errors:\n # logger.debug(f\"Mermaid syntax errors found in file: {md_file_path}: {errors}\")\n \n if errors:\n return \"Mermaid syntax errors found in file: \" + relative_path + \"\\n\" + \"\\n\".join(errors)\n else:\n return \"All mermaid diagrams in file: \" + relative_path + \" are syntax correct\"\n \n except Exception as e:\n return f\"Error processing file: {str(e)}\"", - "start_line": 66, - "end_line": 109, - "has_docstring": true, - "docstring": "Validate all Mermaid diagrams in a markdown file.\n\nArgs:\n md_file_path: Path to the markdown file to check\n relative_path: Relative path to the markdown file\nReturns:\n \"All mermaid diagrams are syntax correct\" if all diagrams are valid,\n otherwise returns error message with details about invalid diagrams", - "parameters": [ - "md_file_path", - "relative_path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function validate_mermaid_diagrams", - "component_id": "codewiki/src/be/utils.py::validate_mermaid_diagrams", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/utils.py::extract_mermaid_blocks": { - "id": "codewiki/src/be/utils.py::extract_mermaid_blocks", - "name": "extract_mermaid_blocks", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/utils.py", - "relative_path": "codewiki/src/be/utils.py", - "depends_on": [], - "source_code": "def extract_mermaid_blocks(content: str) -> List[Tuple[int, str]]:\n \"\"\"\n Extract all mermaid code blocks from markdown content.\n \n Returns:\n List of tuples containing (line_number, diagram_content)\n \"\"\"\n mermaid_blocks = []\n lines = content.split('\\n')\n i = 0\n \n while i < len(lines):\n line = lines[i].strip()\n \n # Look for mermaid code block start\n if line == '```mermaid' or line.startswith('```mermaid'):\n start_line = i + 1\n diagram_lines = []\n i += 1\n \n # Collect lines until we find the closing ```\n while i < len(lines):\n if lines[i].strip() == '```':\n break\n diagram_lines.append(lines[i])\n i += 1\n \n if diagram_lines: # Only add non-empty diagrams\n diagram_content = '\\n'.join(diagram_lines)\n mermaid_blocks.append((start_line, diagram_content))\n \n i += 1\n \n return mermaid_blocks", - "start_line": 112, - "end_line": 145, - "has_docstring": true, - "docstring": "Extract all mermaid code blocks from markdown content.\n\nReturns:\n List of tuples containing (line_number, diagram_content)", - "parameters": [ - "content" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function extract_mermaid_blocks", - "component_id": "codewiki/src/be/utils.py::extract_mermaid_blocks", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/utils.py::_try_pythonmonkey_parse": { - "id": "codewiki/src/be/utils.py::_try_pythonmonkey_parse", - "name": "_try_pythonmonkey_parse", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/utils.py", - "relative_path": "codewiki/src/be/utils.py", - "depends_on": [], - "source_code": "async def _try_pythonmonkey_parse(diagram_content: str) -> str | None:\n \"\"\"Attempt to parse via PythonMonkey/mermaid-parser-py.\n\n Returns the extracted parse-error message, \"\" on success, or None when\n PythonMonkey itself is unusable (broken JS event loop binding on\n Python 3.13+) so the caller can fall back to mermaid-py.\n \"\"\"\n global _PYTHONMONKEY_BROKEN\n if _PYTHONMONKEY_BROKEN:\n return None\n\n import os\n\n try:\n from mermaid_parser.parser import parse_mermaid_py\n except Exception:\n _PYTHONMONKEY_BROKEN = True\n return None\n\n old_stderr = sys.stderr\n sys.stderr = open(os.devnull, 'w')\n try:\n if (\n _main_loop is not None\n and _main_loop.is_running()\n and threading.get_ident() != _main_loop_thread_ident\n ):\n fut = asyncio.run_coroutine_threadsafe(\n parse_mermaid_py(diagram_content), _main_loop\n )\n await asyncio.wrap_future(fut)\n else:\n await parse_mermaid_py(diagram_content)\n return \"\"\n except Exception as e:\n error_str = str(e)\n # PythonMonkey 1.3.1 only supports Python 3.8-3.11; on newer Pythons\n # every JS call raises this. Latch the failure once so subsequent\n # diagrams skip the broken path and go straight to mermaid-py.\n if \"cannot find a running Python event-loop\" in error_str:\n _PYTHONMONKEY_BROKEN = True\n return None\n match = re.search(r\"Error:(.*?)(?=Stack Trace:|$)\", error_str, re.DOTALL)\n if match:\n return match.group(0).strip()\n # Unknown error from the JS parser β€” fall back rather than surface it.\n return None\n finally:\n sys.stderr.close()\n sys.stderr = old_stderr", - "start_line": 161, - "end_line": 210, - "has_docstring": true, - "docstring": "Attempt to parse via PythonMonkey/mermaid-parser-py.\n\nReturns the extracted parse-error message, \"\" on success, or None when\nPythonMonkey itself is unusable (broken JS event loop binding on\nPython 3.13+) so the caller can fall back to mermaid-py.", - "parameters": [ - "diagram_content" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _try_pythonmonkey_parse", - "component_id": "codewiki/src/be/utils.py::_try_pythonmonkey_parse", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/utils.py::_parse_via_mermaid_py": { - "id": "codewiki/src/be/utils.py::_parse_via_mermaid_py", - "name": "_parse_via_mermaid_py", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/utils.py", - "relative_path": "codewiki/src/be/utils.py", - "depends_on": [], - "source_code": "def _parse_via_mermaid_py(diagram_content: str) -> str:\n \"\"\"Validate via mermaid-py. Returns parse-error text, or \"\" if valid.\n\n mermaid-py raises MermaidError on parse failure and returns an SVG body\n on success β€” we must drive the result off the exception, not the body\n text, otherwise a successful SVG gets reported as a parse error.\n \"\"\"\n import mermaid as md\n try:\n md.Mermaid(diagram_content)\n return \"\"\n except Exception as e:\n return str(e)", - "start_line": 213, - "end_line": 225, - "has_docstring": true, - "docstring": "Validate via mermaid-py. Returns parse-error text, or \"\" if valid.\n\nmermaid-py raises MermaidError on parse failure and returns an SVG body\non success β€” we must drive the result off the exception, not the body\ntext, otherwise a successful SVG gets reported as a parse error.", - "parameters": [ - "diagram_content" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function _parse_via_mermaid_py", - "component_id": "codewiki/src/be/utils.py::_parse_via_mermaid_py", - "language": null, - "qualified_name": null - }, - "codewiki/src/be/utils.py::validate_single_diagram": { - "id": "codewiki/src/be/utils.py::validate_single_diagram", - "name": "validate_single_diagram", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/be/utils.py", - "relative_path": "codewiki/src/be/utils.py", - "depends_on": [ - "codewiki/src/be/utils.py::_try_pythonmonkey_parse", - "codewiki/cli/utils/logging.py::CLILogger.debug" - ], - "source_code": "async def validate_single_diagram(diagram_content: str, diagram_num: int, line_start: int) -> str:\n \"\"\"\n Validate a single mermaid diagram.\n\n Args:\n diagram_content: The mermaid diagram content\n diagram_num: Diagram number for error reporting\n line_start: Starting line number in the file\n\n Returns:\n Error message if invalid, empty string if valid\n \"\"\"\n global _MERMAID_PY_BROKEN\n core_error = await _try_pythonmonkey_parse(diagram_content)\n if core_error is None:\n if _MERMAID_PY_BROKEN:\n # Validation disabled/unavailable is not a syntax error β€” a\n # non-empty return here would make callers report valid diagrams\n # as broken and send agents into fix loops.\n logger.debug(\"Diagram %d: validation skipped (mermaid-py disabled or unavailable)\", diagram_num)\n return \"\"\n try:\n core_error = await asyncio.wait_for(\n asyncio.to_thread(_parse_via_mermaid_py, diagram_content),\n timeout=15.0,\n )\n except asyncio.TimeoutError:\n # Inconclusive, not a parse failure. Latch so the remaining\n # diagrams (and later calls) don't each block 15s on the same\n # broken Node.js setup.\n _MERMAID_PY_BROKEN = True\n logger.warning(\"Diagram %d: mermaid validation timed out (15s); skipping further validation\", diagram_num)\n return \"\"\n except Exception as e:\n return f\" Diagram {diagram_num}: Exception during validation - {str(e)}\"\n\n if not core_error:\n return \"\"\n\n line_match = re.search(r'line (\\d+)', core_error)\n if line_match:\n error_line_in_diagram = int(line_match.group(1))\n actual_line_in_file = line_start + error_line_in_diagram\n newline = '\\n'\n return f\"Diagram {diagram_num}: Parse error on line {actual_line_in_file}:{newline}{newline.join(core_error.split(newline)[1:])}\"\n return f\"Diagram {diagram_num}: {core_error}\"", - "start_line": 228, - "end_line": 273, - "has_docstring": true, - "docstring": "Validate a single mermaid diagram.\n\nArgs:\n diagram_content: The mermaid diagram content\n diagram_num: Diagram number for error reporting\n line_start: Starting line number in the file\n\nReturns:\n Error message if invalid, empty string if valid", - "parameters": [ - "diagram_content", - "diagram_num", - "line_start" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function validate_single_diagram", - "component_id": "codewiki/src/be/utils.py::validate_single_diagram", - "language": null, - "qualified_name": null - }, - "codewiki/src/config.py::set_cli_context": { - "id": "codewiki/src/config.py::set_cli_context", - "name": "set_cli_context", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/config.py", - "relative_path": "codewiki/src/config.py", - "depends_on": [], - "source_code": "def set_cli_context(enabled: bool = True):\n \"\"\"Set whether we're running in CLI context (vs web app).\"\"\"\n global _CLI_CONTEXT\n _CLI_CONTEXT = enabled", - "start_line": 28, - "end_line": 31, - "has_docstring": true, - "docstring": "Set whether we're running in CLI context (vs web app).", - "parameters": [ - "enabled" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function set_cli_context", - "component_id": "codewiki/src/config.py::set_cli_context", - "language": null, - "qualified_name": null - }, - "codewiki/src/config.py::is_cli_context": { - "id": "codewiki/src/config.py::is_cli_context", - "name": "is_cli_context", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/config.py", - "relative_path": "codewiki/src/config.py", - "depends_on": [], - "source_code": "def is_cli_context() -> bool:\n \"\"\"Check if running in CLI context.\"\"\"\n return _CLI_CONTEXT", - "start_line": 33, - "end_line": 35, - "has_docstring": true, - "docstring": "Check if running in CLI context.", - "parameters": [], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function is_cli_context", - "component_id": "codewiki/src/config.py::is_cli_context", - "language": null, - "qualified_name": null - }, - "codewiki/src/config.py::Config": { - "id": "codewiki/src/config.py::Config", - "name": "Config", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/config.py", - "relative_path": "codewiki/src/config.py", - "depends_on": [], - "source_code": "class Config:\n \"\"\"Configuration class for CodeWiki.\"\"\"\n repo_path: str\n output_dir: str\n dependency_graph_dir: str\n docs_dir: str\n max_depth: int\n # LLM configuration\n llm_base_url: str\n llm_api_key: str\n main_model: str\n cluster_model: str\n fallback_model: str = FALLBACK_MODEL_1\n # Provider configuration\n provider: str = \"openai-compatible\" # openai-compatible, atlas-cloud, anthropic, bedrock, azure-openai\n aws_region: str = \"us-east-1\"\n api_version: str = \"2024-12-01-preview\" # Azure OpenAI API version\n azure_deployment: str = \"\" # Azure OpenAI deployment name\n # Max token settings\n max_tokens: int = DEFAULT_MAX_TOKENS\n max_token_per_module: int = DEFAULT_MAX_TOKEN_PER_MODULE\n max_token_per_leaf_module: int = DEFAULT_MAX_TOKEN_PER_LEAF_MODULE\n # Prompt caching for agentic/multi-turn calls (auto-disables per model if\n # the provider rejects cache_control markers)\n prompt_caching: bool = True\n # Agent instructions for customization\n agent_instructions: Optional[Dict[str, Any]] = None\n # Apply Git ignore rules before dependency analysis\n use_gitignore: bool = True\n \n @property\n def include_patterns(self) -> Optional[List[str]]:\n \"\"\"Get file include patterns from agent instructions.\"\"\"\n if self.agent_instructions:\n return self.agent_instructions.get('include_patterns')\n return None\n \n @property\n def exclude_patterns(self) -> Optional[List[str]]:\n \"\"\"Get file exclude patterns from agent instructions.\"\"\"\n if self.agent_instructions:\n return self.agent_instructions.get('exclude_patterns')\n return None\n \n @property\n def focus_modules(self) -> Optional[List[str]]:\n \"\"\"Get focus modules from agent instructions.\"\"\"\n if self.agent_instructions:\n return self.agent_instructions.get('focus_modules')\n return None\n \n @property\n def doc_type(self) -> Optional[str]:\n \"\"\"Get documentation type from agent instructions.\"\"\"\n if self.agent_instructions:\n return self.agent_instructions.get('doc_type')\n return None\n \n @property\n def custom_instructions(self) -> Optional[str]:\n \"\"\"Get custom instructions from agent instructions.\"\"\"\n if self.agent_instructions:\n return self.agent_instructions.get('custom_instructions')\n return None\n \n def get_prompt_addition(self) -> str:\n \"\"\"Generate prompt additions based on agent instructions.\"\"\"\n if not self.agent_instructions:\n return \"\"\n \n additions = []\n \n if self.doc_type:\n doc_type_instructions = {\n 'api': \"Focus on API documentation: endpoints, parameters, return types, and usage examples.\",\n 'architecture': \"Focus on architecture documentation: system design, component relationships, and data flow.\",\n 'user-guide': \"Focus on user guide documentation: how to use features, step-by-step tutorials.\",\n 'developer': \"Focus on developer documentation: code structure, contribution guidelines, and implementation details.\",\n }\n if self.doc_type.lower() in doc_type_instructions:\n additions.append(doc_type_instructions[self.doc_type.lower()])\n else:\n additions.append(f\"Focus on generating {self.doc_type} documentation.\")\n \n if self.focus_modules:\n additions.append(f\"Pay special attention to and provide more detailed documentation for these modules: {', '.join(self.focus_modules)}\")\n \n if self.custom_instructions:\n additions.append(f\"Additional instructions: {self.custom_instructions}\")\n \n return \"\\n\".join(additions) if additions else \"\"\n \n @classmethod\n def from_args(cls, args: argparse.Namespace) -> 'Config':\n \"\"\"Create configuration from parsed arguments.\"\"\"\n repo_name = os.path.basename(os.path.normpath(args.repo_path))\n sanitized_repo_name = ''.join(c if c.isalnum() else '_' for c in repo_name)\n \n return cls(\n repo_path=args.repo_path,\n output_dir=OUTPUT_BASE_DIR,\n dependency_graph_dir=os.path.join(OUTPUT_BASE_DIR, DEPENDENCY_GRAPHS_DIR),\n docs_dir=os.path.join(OUTPUT_BASE_DIR, DOCS_DIR, f\"{sanitized_repo_name}-docs\"),\n max_depth=MAX_DEPTH,\n llm_base_url=LLM_BASE_URL,\n llm_api_key=LLM_API_KEY,\n main_model=MAIN_MODEL,\n cluster_model=CLUSTER_MODEL,\n fallback_model=FALLBACK_MODEL_1,\n use_gitignore=getattr(args, \"use_gitignore\", True),\n )\n \n @classmethod\n def from_cli(\n cls,\n repo_path: str,\n output_dir: str,\n llm_base_url: str,\n llm_api_key: str,\n main_model: str,\n cluster_model: str,\n fallback_model: str = FALLBACK_MODEL_1,\n provider: str = \"openai-compatible\",\n aws_region: str = \"us-east-1\",\n api_version: str = \"2024-12-01-preview\",\n azure_deployment: str = \"\",\n max_tokens: int = DEFAULT_MAX_TOKENS,\n max_token_per_module: int = DEFAULT_MAX_TOKEN_PER_MODULE,\n max_token_per_leaf_module: int = DEFAULT_MAX_TOKEN_PER_LEAF_MODULE,\n max_depth: int = MAX_DEPTH,\n agent_instructions: Optional[Dict[str, Any]] = None,\n use_gitignore: bool = True,\n prompt_caching: bool = True,\n ) -> 'Config':\n \"\"\"\n Create configuration for CLI context.\n\n Args:\n repo_path: Repository path\n output_dir: Output directory for generated docs\n llm_base_url: LLM API base URL\n llm_api_key: LLM API key\n main_model: Primary model\n cluster_model: Clustering model\n fallback_model: Fallback model\n provider: LLM provider type (openai-compatible, atlas-cloud, anthropic, bedrock, azure-openai)\n aws_region: AWS region for Bedrock provider\n api_version: Azure OpenAI API version\n azure_deployment: Azure OpenAI deployment name\n max_tokens: Maximum tokens for LLM response\n max_token_per_module: Maximum tokens per module for clustering\n max_token_per_leaf_module: Maximum tokens per leaf module\n max_depth: Maximum depth for hierarchical decomposition\n agent_instructions: Custom agent instructions dict\n use_gitignore: Whether to apply Git ignore rules\n prompt_caching: Whether to add prompt-cache breakpoints to agentic calls\n\n Returns:\n Config instance\n \"\"\"\n repo_name = os.path.basename(os.path.normpath(repo_path))\n base_output_dir = os.path.join(output_dir, \"temp\")\n\n return cls(\n repo_path=repo_path,\n output_dir=base_output_dir,\n dependency_graph_dir=os.path.join(base_output_dir, DEPENDENCY_GRAPHS_DIR),\n docs_dir=output_dir,\n max_depth=max_depth,\n llm_base_url=llm_base_url,\n llm_api_key=llm_api_key,\n main_model=main_model,\n cluster_model=cluster_model,\n fallback_model=fallback_model,\n provider=provider,\n aws_region=aws_region,\n api_version=api_version,\n azure_deployment=azure_deployment,\n max_tokens=max_tokens,\n max_token_per_module=max_token_per_module,\n max_token_per_leaf_module=max_token_per_leaf_module,\n agent_instructions=agent_instructions,\n use_gitignore=use_gitignore,\n prompt_caching=prompt_caching,\n )", - "start_line": 51, - "end_line": 235, - "has_docstring": true, - "docstring": "Configuration class for CodeWiki.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class Config", - "component_id": "codewiki/src/config.py::Config", - "language": null, - "qualified_name": null - }, - "codewiki/src/config.py::Config.include_patterns": { - "id": "codewiki/src/config.py::Config.include_patterns", - "name": "Config.include_patterns", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/config.py", - "relative_path": "codewiki/src/config.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def include_patterns(self) -> Optional[List[str]]:\n \"\"\"Get file include patterns from agent instructions.\"\"\"\n if self.agent_instructions:\n return self.agent_instructions.get('include_patterns')\n return None", - "start_line": 82, - "end_line": 86, - "has_docstring": true, - "docstring": "Get file include patterns from agent instructions.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "Config", - "display_name": "method Config.include_patterns", - "component_id": "codewiki/src/config.py::Config.include_patterns", - "language": null, - "qualified_name": null - }, - "codewiki/src/config.py::Config.exclude_patterns": { - "id": "codewiki/src/config.py::Config.exclude_patterns", - "name": "Config.exclude_patterns", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/config.py", - "relative_path": "codewiki/src/config.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def exclude_patterns(self) -> Optional[List[str]]:\n \"\"\"Get file exclude patterns from agent instructions.\"\"\"\n if self.agent_instructions:\n return self.agent_instructions.get('exclude_patterns')\n return None", - "start_line": 89, - "end_line": 93, - "has_docstring": true, - "docstring": "Get file exclude patterns from agent instructions.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "Config", - "display_name": "method Config.exclude_patterns", - "component_id": "codewiki/src/config.py::Config.exclude_patterns", - "language": null, - "qualified_name": null - }, - "codewiki/src/config.py::Config.focus_modules": { - "id": "codewiki/src/config.py::Config.focus_modules", - "name": "Config.focus_modules", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/config.py", - "relative_path": "codewiki/src/config.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def focus_modules(self) -> Optional[List[str]]:\n \"\"\"Get focus modules from agent instructions.\"\"\"\n if self.agent_instructions:\n return self.agent_instructions.get('focus_modules')\n return None", - "start_line": 96, - "end_line": 100, - "has_docstring": true, - "docstring": "Get focus modules from agent instructions.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "Config", - "display_name": "method Config.focus_modules", - "component_id": "codewiki/src/config.py::Config.focus_modules", - "language": null, - "qualified_name": null - }, - "codewiki/src/config.py::Config.doc_type": { - "id": "codewiki/src/config.py::Config.doc_type", - "name": "Config.doc_type", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/config.py", - "relative_path": "codewiki/src/config.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def doc_type(self) -> Optional[str]:\n \"\"\"Get documentation type from agent instructions.\"\"\"\n if self.agent_instructions:\n return self.agent_instructions.get('doc_type')\n return None", - "start_line": 103, - "end_line": 107, - "has_docstring": true, - "docstring": "Get documentation type from agent instructions.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "Config", - "display_name": "method Config.doc_type", - "component_id": "codewiki/src/config.py::Config.doc_type", - "language": null, - "qualified_name": null - }, - "codewiki/src/config.py::Config.custom_instructions": { - "id": "codewiki/src/config.py::Config.custom_instructions", - "name": "Config.custom_instructions", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/config.py", - "relative_path": "codewiki/src/config.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def custom_instructions(self) -> Optional[str]:\n \"\"\"Get custom instructions from agent instructions.\"\"\"\n if self.agent_instructions:\n return self.agent_instructions.get('custom_instructions')\n return None", - "start_line": 110, - "end_line": 114, - "has_docstring": true, - "docstring": "Get custom instructions from agent instructions.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "Config", - "display_name": "method Config.custom_instructions", - "component_id": "codewiki/src/config.py::Config.custom_instructions", - "language": null, - "qualified_name": null - }, - "codewiki/src/config.py::Config.get_prompt_addition": { - "id": "codewiki/src/config.py::Config.get_prompt_addition", - "name": "Config.get_prompt_addition", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/config.py", - "relative_path": "codewiki/src/config.py", - "depends_on": [], - "source_code": " def get_prompt_addition(self) -> str:\n \"\"\"Generate prompt additions based on agent instructions.\"\"\"\n if not self.agent_instructions:\n return \"\"\n \n additions = []\n \n if self.doc_type:\n doc_type_instructions = {\n 'api': \"Focus on API documentation: endpoints, parameters, return types, and usage examples.\",\n 'architecture': \"Focus on architecture documentation: system design, component relationships, and data flow.\",\n 'user-guide': \"Focus on user guide documentation: how to use features, step-by-step tutorials.\",\n 'developer': \"Focus on developer documentation: code structure, contribution guidelines, and implementation details.\",\n }\n if self.doc_type.lower() in doc_type_instructions:\n additions.append(doc_type_instructions[self.doc_type.lower()])\n else:\n additions.append(f\"Focus on generating {self.doc_type} documentation.\")\n \n if self.focus_modules:\n additions.append(f\"Pay special attention to and provide more detailed documentation for these modules: {', '.join(self.focus_modules)}\")\n \n if self.custom_instructions:\n additions.append(f\"Additional instructions: {self.custom_instructions}\")\n \n return \"\\n\".join(additions) if additions else \"\"", - "start_line": 116, - "end_line": 141, - "has_docstring": true, - "docstring": "Generate prompt additions based on agent instructions.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "Config", - "display_name": "method Config.get_prompt_addition", - "component_id": "codewiki/src/config.py::Config.get_prompt_addition", - "language": null, - "qualified_name": null - }, - "codewiki/src/config.py::Config.from_args": { - "id": "codewiki/src/config.py::Config.from_args", - "name": "Config.from_args", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/config.py", - "relative_path": "codewiki/src/config.py", - "depends_on": [], - "source_code": " def from_args(cls, args: argparse.Namespace) -> 'Config':\n \"\"\"Create configuration from parsed arguments.\"\"\"\n repo_name = os.path.basename(os.path.normpath(args.repo_path))\n sanitized_repo_name = ''.join(c if c.isalnum() else '_' for c in repo_name)\n \n return cls(\n repo_path=args.repo_path,\n output_dir=OUTPUT_BASE_DIR,\n dependency_graph_dir=os.path.join(OUTPUT_BASE_DIR, DEPENDENCY_GRAPHS_DIR),\n docs_dir=os.path.join(OUTPUT_BASE_DIR, DOCS_DIR, f\"{sanitized_repo_name}-docs\"),\n max_depth=MAX_DEPTH,\n llm_base_url=LLM_BASE_URL,\n llm_api_key=LLM_API_KEY,\n main_model=MAIN_MODEL,\n cluster_model=CLUSTER_MODEL,\n fallback_model=FALLBACK_MODEL_1,\n use_gitignore=getattr(args, \"use_gitignore\", True),\n )", - "start_line": 144, - "end_line": 161, - "has_docstring": true, - "docstring": "Create configuration from parsed arguments.", - "parameters": [ - "cls", - "args" - ], - "node_type": "method", - "base_classes": null, - "class_name": "Config", - "display_name": "method Config.from_args", - "component_id": "codewiki/src/config.py::Config.from_args", - "language": null, - "qualified_name": null - }, - "codewiki/src/config.py::Config.from_cli": { - "id": "codewiki/src/config.py::Config.from_cli", - "name": "Config.from_cli", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/config.py", - "relative_path": "codewiki/src/config.py", - "depends_on": [], - "source_code": " def from_cli(\n cls,\n repo_path: str,\n output_dir: str,\n llm_base_url: str,\n llm_api_key: str,\n main_model: str,\n cluster_model: str,\n fallback_model: str = FALLBACK_MODEL_1,\n provider: str = \"openai-compatible\",\n aws_region: str = \"us-east-1\",\n api_version: str = \"2024-12-01-preview\",\n azure_deployment: str = \"\",\n max_tokens: int = DEFAULT_MAX_TOKENS,\n max_token_per_module: int = DEFAULT_MAX_TOKEN_PER_MODULE,\n max_token_per_leaf_module: int = DEFAULT_MAX_TOKEN_PER_LEAF_MODULE,\n max_depth: int = MAX_DEPTH,\n agent_instructions: Optional[Dict[str, Any]] = None,\n use_gitignore: bool = True,\n prompt_caching: bool = True,\n ) -> 'Config':\n \"\"\"\n Create configuration for CLI context.\n\n Args:\n repo_path: Repository path\n output_dir: Output directory for generated docs\n llm_base_url: LLM API base URL\n llm_api_key: LLM API key\n main_model: Primary model\n cluster_model: Clustering model\n fallback_model: Fallback model\n provider: LLM provider type (openai-compatible, atlas-cloud, anthropic, bedrock, azure-openai)\n aws_region: AWS region for Bedrock provider\n api_version: Azure OpenAI API version\n azure_deployment: Azure OpenAI deployment name\n max_tokens: Maximum tokens for LLM response\n max_token_per_module: Maximum tokens per module for clustering\n max_token_per_leaf_module: Maximum tokens per leaf module\n max_depth: Maximum depth for hierarchical decomposition\n agent_instructions: Custom agent instructions dict\n use_gitignore: Whether to apply Git ignore rules\n prompt_caching: Whether to add prompt-cache breakpoints to agentic calls\n\n Returns:\n Config instance\n \"\"\"\n repo_name = os.path.basename(os.path.normpath(repo_path))\n base_output_dir = os.path.join(output_dir, \"temp\")\n\n return cls(\n repo_path=repo_path,\n output_dir=base_output_dir,\n dependency_graph_dir=os.path.join(base_output_dir, DEPENDENCY_GRAPHS_DIR),\n docs_dir=output_dir,\n max_depth=max_depth,\n llm_base_url=llm_base_url,\n llm_api_key=llm_api_key,\n main_model=main_model,\n cluster_model=cluster_model,\n fallback_model=fallback_model,\n provider=provider,\n aws_region=aws_region,\n api_version=api_version,\n azure_deployment=azure_deployment,\n max_tokens=max_tokens,\n max_token_per_module=max_token_per_module,\n max_token_per_leaf_module=max_token_per_leaf_module,\n agent_instructions=agent_instructions,\n use_gitignore=use_gitignore,\n prompt_caching=prompt_caching,\n )", - "start_line": 164, - "end_line": 235, - "has_docstring": true, - "docstring": "Create configuration for CLI context.\n\nArgs:\n repo_path: Repository path\n output_dir: Output directory for generated docs\n llm_base_url: LLM API base URL\n llm_api_key: LLM API key\n main_model: Primary model\n cluster_model: Clustering model\n fallback_model: Fallback model\n provider: LLM provider type (openai-compatible, atlas-cloud, anthropic, bedrock, azure-openai)\n aws_region: AWS region for Bedrock provider\n api_version: Azure OpenAI API version\n azure_deployment: Azure OpenAI deployment name\n max_tokens: Maximum tokens for LLM response\n max_token_per_module: Maximum tokens per module for clustering\n max_token_per_leaf_module: Maximum tokens per leaf module\n max_depth: Maximum depth for hierarchical decomposition\n agent_instructions: Custom agent instructions dict\n use_gitignore: Whether to apply Git ignore rules\n prompt_caching: Whether to add prompt-cache breakpoints to agentic calls\n\nReturns:\n Config instance", - "parameters": [ - "cls", - "repo_path", - "output_dir", - "llm_base_url", - "llm_api_key", - "main_model", - "cluster_model", - "fallback_model", - "provider", - "aws_region", - "api_version", - "azure_deployment", - "max_tokens", - "max_token_per_module", - "max_token_per_leaf_module", - "max_depth", - "agent_instructions", - "use_gitignore", - "prompt_caching" - ], - "node_type": "method", - "base_classes": null, - "class_name": "Config", - "display_name": "method Config.from_cli", - "component_id": "codewiki/src/config.py::Config.from_cli", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/background_worker.py::BackgroundWorker": { - "id": "codewiki/src/fe/background_worker.py::BackgroundWorker", - "name": "BackgroundWorker", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/background_worker.py", - "relative_path": "codewiki/src/fe/background_worker.py", - "depends_on": [], - "source_code": "class BackgroundWorker:\n \"\"\"Background worker for processing documentation generation jobs.\"\"\"\n \n def __init__(self, cache_manager: CacheManager, temp_dir: str = None):\n self.cache_manager = cache_manager\n self.temp_dir = temp_dir or WebAppConfig.TEMP_DIR\n self.running = False\n self.processing_queue = Queue(maxsize=WebAppConfig.QUEUE_SIZE)\n self.job_status: Dict[str, JobStatus] = {}\n self.jobs_file = Path(WebAppConfig.CACHE_DIR) / \"jobs.json\"\n self.load_job_statuses()\n \n def start(self):\n \"\"\"Start the background worker thread.\"\"\"\n if not self.running:\n self.running = True\n thread = threading.Thread(target=self._worker_loop, daemon=True)\n thread.start()\n print(\"Background worker started\")\n \n def stop(self):\n \"\"\"Stop the background worker.\"\"\"\n self.running = False\n \n def add_job(self, job_id: str, job: JobStatus):\n \"\"\"Add a job to the processing queue.\"\"\"\n self.job_status[job_id] = job\n self.processing_queue.put(job_id)\n \n def get_job_status(self, job_id: str) -> JobStatus:\n \"\"\"Get job status by ID.\"\"\"\n return self.job_status.get(job_id)\n \n def get_all_jobs(self) -> Dict[str, JobStatus]:\n \"\"\"Get all job statuses.\"\"\"\n return self.job_status\n \n def load_job_statuses(self):\n \"\"\"Load job statuses from disk.\"\"\"\n if not self.jobs_file.exists():\n # Try to reconstruct from cache if no job file exists\n self._reconstruct_jobs_from_cache()\n return\n \n try:\n data = file_manager.load_json(self.jobs_file)\n \n for job_id, job_data in data.items():\n # Only load completed jobs to avoid inconsistent state\n if job_data.get('status') == 'completed':\n self.job_status[job_id] = JobStatus(\n job_id=job_data['job_id'],\n repo_url=job_data['repo_url'],\n status=job_data['status'],\n created_at=datetime.fromisoformat(job_data['created_at']),\n started_at=datetime.fromisoformat(job_data['started_at']) if job_data.get('started_at') else None,\n completed_at=datetime.fromisoformat(job_data['completed_at']) if job_data.get('completed_at') else None,\n error_message=job_data.get('error_message'),\n progress=job_data.get('progress', ''),\n docs_path=job_data.get('docs_path')\n )\n print(f\"Loaded {len([j for j in self.job_status.values() if j.status == 'completed'])} completed jobs from disk\")\n except Exception as e:\n print(f\"Error loading job statuses: {e}\")\n \n def _reconstruct_jobs_from_cache(self):\n \"\"\"Reconstruct job statuses from cache entries for backward compatibility.\"\"\"\n try:\n cache_entries = self.cache_manager.cache_index\n reconstructed_count = 0\n \n for repo_hash, cache_entry in cache_entries.items():\n # Extract repo info to create job_id\n from .github_processor import GitHubRepoProcessor\n try:\n repo_info = GitHubRepoProcessor.get_repo_info(cache_entry.repo_url)\n job_id = repo_info['full_name'].replace('/', '--')\n \n # Only add if job doesn't already exist\n if job_id not in self.job_status:\n self.job_status[job_id] = JobStatus(\n job_id=job_id,\n repo_url=cache_entry.repo_url,\n status='completed',\n created_at=cache_entry.created_at,\n completed_at=cache_entry.created_at,\n docs_path=cache_entry.docs_path,\n progress=\"Reconstructed from cache\"\n )\n reconstructed_count += 1\n except Exception as e:\n print(f\"Failed to reconstruct job for {cache_entry.repo_url}: {e}\")\n \n if reconstructed_count > 0:\n print(f\"Reconstructed {reconstructed_count} job statuses from cache\")\n self.save_job_statuses()\n \n except Exception as e:\n print(f\"Error reconstructing jobs from cache: {e}\")\n \n def save_job_statuses(self):\n \"\"\"Save job statuses to disk.\"\"\"\n try:\n # Ensure cache directory exists\n self.jobs_file.parent.mkdir(parents=True, exist_ok=True)\n \n data = {}\n for job_id, job in self.job_status.items():\n data[job_id] = {\n 'job_id': job.job_id,\n 'repo_url': job.repo_url,\n 'status': job.status,\n 'created_at': job.created_at.isoformat(),\n 'started_at': job.started_at.isoformat() if job.started_at else None,\n 'completed_at': job.completed_at.isoformat() if job.completed_at else None,\n 'error_message': job.error_message,\n 'progress': job.progress,\n 'docs_path': job.docs_path\n }\n \n file_manager.save_json(data, self.jobs_file)\n except Exception as e:\n print(f\"Error saving job statuses: {e}\")\n \n def _worker_loop(self):\n \"\"\"Main worker loop.\"\"\"\n while self.running:\n try:\n if not self.processing_queue.empty():\n job_id = self.processing_queue.get(timeout=1)\n self._process_job(job_id)\n else:\n time.sleep(1)\n except Exception as e:\n print(f\"Worker error: {e}\")\n time.sleep(1)\n \n def _process_job(self, job_id: str):\n \"\"\"Process a single documentation generation job.\"\"\"\n if job_id not in self.job_status:\n return\n \n job = self.job_status[job_id]\n \n try:\n # Update job status\n job.status = 'processing'\n job.started_at = datetime.now()\n job.progress = \"Starting repository clone...\"\n job.main_model = MAIN_MODEL\n \n # Check cache first\n cached_docs = self.cache_manager.get_cached_docs(job.repo_url)\n if cached_docs and Path(cached_docs).exists():\n job.status = 'completed'\n job.completed_at = datetime.now()\n job.docs_path = cached_docs\n job.progress = \"Documentation retrieved from cache\"\n if not job.main_model: # Only set if not already set\n job.main_model = MAIN_MODEL\n \n # Save job status to disk\n self.save_job_statuses()\n \n print(f\"Job {job_id}: Using cached documentation\")\n return\n \n # Clone repository\n repo_info = GitHubRepoProcessor.get_repo_info(job.repo_url)\n # Use repo full name for temp directory (already URL-safe since job_id is URL-safe)\n temp_repo_dir = os.path.join(self.temp_dir, job_id)\n \n job.progress = f\"Cloning repository {repo_info['full_name']}...\"\n \n if not GitHubRepoProcessor.clone_repository(repo_info['clone_url'], temp_repo_dir, job.commit_id):\n raise Exception(\"Failed to clone repository\")\n \n # Generate documentation\n job.progress = \"Analyzing repository structure...\"\n \n # Create config for documentation generation (using env vars)\n import argparse\n args = argparse.Namespace(repo_path=temp_repo_dir)\n config = Config.from_args(args)\n # Override docs_dir with job-specific directory\n config.docs_dir = os.path.join(\"output\", \"docs\", f\"{job_id}-docs\")\n \n job.progress = \"Generating documentation...\"\n \n # Generate documentation\n doc_generator = DocumentationGenerator(config, job.commit_id)\n \n # Run the async documentation generation in a new event loop\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n try:\n loop.run_until_complete(doc_generator.run())\n finally:\n loop.close()\n \n # Cache the results\n docs_path = os.path.abspath(config.docs_dir)\n self.cache_manager.add_to_cache(job.repo_url, docs_path)\n \n # Update job status\n job.status = 'completed'\n job.completed_at = datetime.now()\n job.docs_path = docs_path\n job.progress = \"Documentation generation completed\"\n \n # Save job status to disk\n self.save_job_statuses()\n \n print(f\"Job {job_id}: Documentation generated successfully\")\n \n except Exception as e:\n # Update job status with error\n job.status = 'failed'\n job.completed_at = datetime.now()\n job.error_message = str(e)\n job.progress = f\"Failed: {str(e)}\"\n \n print(f\"Job {job_id}: Failed with error: {e}\")\n \n finally:\n # Cleanup temporary repository\n if 'temp_repo_dir' in locals() and os.path.exists(temp_repo_dir):\n try:\n subprocess.run(['rm', '-rf', temp_repo_dir], check=True)\n except Exception as e:\n print(f\"Failed to cleanup temp directory: {e}\")", - "start_line": 26, - "end_line": 256, - "has_docstring": true, - "docstring": "Background worker for processing documentation generation jobs.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class BackgroundWorker", - "component_id": "codewiki/src/fe/background_worker.py::BackgroundWorker", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/background_worker.py::BackgroundWorker.__init__": { - "id": "codewiki/src/fe/background_worker.py::BackgroundWorker.__init__", - "name": "BackgroundWorker.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/background_worker.py", - "relative_path": "codewiki/src/fe/background_worker.py", - "depends_on": [ - "codewiki/src/fe/background_worker.py::BackgroundWorker.load_job_statuses" - ], - "source_code": " def __init__(self, cache_manager: CacheManager, temp_dir: str = None):\n self.cache_manager = cache_manager\n self.temp_dir = temp_dir or WebAppConfig.TEMP_DIR\n self.running = False\n self.processing_queue = Queue(maxsize=WebAppConfig.QUEUE_SIZE)\n self.job_status: Dict[str, JobStatus] = {}\n self.jobs_file = Path(WebAppConfig.CACHE_DIR) / \"jobs.json\"\n self.load_job_statuses()", - "start_line": 29, - "end_line": 36, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "cache_manager", - "temp_dir" - ], - "node_type": "method", - "base_classes": null, - "class_name": "BackgroundWorker", - "display_name": "method BackgroundWorker.__init__", - "component_id": "codewiki/src/fe/background_worker.py::BackgroundWorker.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/background_worker.py::BackgroundWorker.start": { - "id": "codewiki/src/fe/background_worker.py::BackgroundWorker.start", - "name": "BackgroundWorker.start", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/background_worker.py", - "relative_path": "codewiki/src/fe/background_worker.py", - "depends_on": [], - "source_code": " def start(self):\n \"\"\"Start the background worker thread.\"\"\"\n if not self.running:\n self.running = True\n thread = threading.Thread(target=self._worker_loop, daemon=True)\n thread.start()\n print(\"Background worker started\")", - "start_line": 38, - "end_line": 44, - "has_docstring": true, - "docstring": "Start the background worker thread.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "BackgroundWorker", - "display_name": "method BackgroundWorker.start", - "component_id": "codewiki/src/fe/background_worker.py::BackgroundWorker.start", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/background_worker.py::BackgroundWorker.stop": { - "id": "codewiki/src/fe/background_worker.py::BackgroundWorker.stop", - "name": "BackgroundWorker.stop", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/background_worker.py", - "relative_path": "codewiki/src/fe/background_worker.py", - "depends_on": [], - "source_code": " def stop(self):\n \"\"\"Stop the background worker.\"\"\"\n self.running = False", - "start_line": 46, - "end_line": 48, - "has_docstring": true, - "docstring": "Stop the background worker.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "BackgroundWorker", - "display_name": "method BackgroundWorker.stop", - "component_id": "codewiki/src/fe/background_worker.py::BackgroundWorker.stop", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/background_worker.py::BackgroundWorker.add_job": { - "id": "codewiki/src/fe/background_worker.py::BackgroundWorker.add_job", - "name": "BackgroundWorker.add_job", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/background_worker.py", - "relative_path": "codewiki/src/fe/background_worker.py", - "depends_on": [], - "source_code": " def add_job(self, job_id: str, job: JobStatus):\n \"\"\"Add a job to the processing queue.\"\"\"\n self.job_status[job_id] = job\n self.processing_queue.put(job_id)", - "start_line": 50, - "end_line": 53, - "has_docstring": true, - "docstring": "Add a job to the processing queue.", - "parameters": [ - "self", - "job_id", - "job" - ], - "node_type": "method", - "base_classes": null, - "class_name": "BackgroundWorker", - "display_name": "method BackgroundWorker.add_job", - "component_id": "codewiki/src/fe/background_worker.py::BackgroundWorker.add_job", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/background_worker.py::BackgroundWorker.get_job_status": { - "id": "codewiki/src/fe/background_worker.py::BackgroundWorker.get_job_status", - "name": "BackgroundWorker.get_job_status", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/background_worker.py", - "relative_path": "codewiki/src/fe/background_worker.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def get_job_status(self, job_id: str) -> JobStatus:\n \"\"\"Get job status by ID.\"\"\"\n return self.job_status.get(job_id)", - "start_line": 55, - "end_line": 57, - "has_docstring": true, - "docstring": "Get job status by ID.", - "parameters": [ - "self", - "job_id" - ], - "node_type": "method", - "base_classes": null, - "class_name": "BackgroundWorker", - "display_name": "method BackgroundWorker.get_job_status", - "component_id": "codewiki/src/fe/background_worker.py::BackgroundWorker.get_job_status", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/background_worker.py::BackgroundWorker.get_all_jobs": { - "id": "codewiki/src/fe/background_worker.py::BackgroundWorker.get_all_jobs", - "name": "BackgroundWorker.get_all_jobs", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/background_worker.py", - "relative_path": "codewiki/src/fe/background_worker.py", - "depends_on": [], - "source_code": " def get_all_jobs(self) -> Dict[str, JobStatus]:\n \"\"\"Get all job statuses.\"\"\"\n return self.job_status", - "start_line": 59, - "end_line": 61, - "has_docstring": true, - "docstring": "Get all job statuses.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "BackgroundWorker", - "display_name": "method BackgroundWorker.get_all_jobs", - "component_id": "codewiki/src/fe/background_worker.py::BackgroundWorker.get_all_jobs", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/background_worker.py::BackgroundWorker.load_job_statuses": { - "id": "codewiki/src/fe/background_worker.py::BackgroundWorker.load_job_statuses", - "name": "BackgroundWorker.load_job_statuses", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/background_worker.py", - "relative_path": "codewiki/src/fe/background_worker.py", - "depends_on": [ - "codewiki/src/utils.py::FileManager.load_json", - "codewiki/src/fe/background_worker.py::BackgroundWorker._reconstruct_jobs_from_cache", - "codewiki/src/fe/models.py::JobStatus", - "codewiki/mcp/session.py::SessionStore.get" - ], - "source_code": " def load_job_statuses(self):\n \"\"\"Load job statuses from disk.\"\"\"\n if not self.jobs_file.exists():\n # Try to reconstruct from cache if no job file exists\n self._reconstruct_jobs_from_cache()\n return\n \n try:\n data = file_manager.load_json(self.jobs_file)\n \n for job_id, job_data in data.items():\n # Only load completed jobs to avoid inconsistent state\n if job_data.get('status') == 'completed':\n self.job_status[job_id] = JobStatus(\n job_id=job_data['job_id'],\n repo_url=job_data['repo_url'],\n status=job_data['status'],\n created_at=datetime.fromisoformat(job_data['created_at']),\n started_at=datetime.fromisoformat(job_data['started_at']) if job_data.get('started_at') else None,\n completed_at=datetime.fromisoformat(job_data['completed_at']) if job_data.get('completed_at') else None,\n error_message=job_data.get('error_message'),\n progress=job_data.get('progress', ''),\n docs_path=job_data.get('docs_path')\n )\n print(f\"Loaded {len([j for j in self.job_status.values() if j.status == 'completed'])} completed jobs from disk\")\n except Exception as e:\n print(f\"Error loading job statuses: {e}\")", - "start_line": 63, - "end_line": 89, - "has_docstring": true, - "docstring": "Load job statuses from disk.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "BackgroundWorker", - "display_name": "method BackgroundWorker.load_job_statuses", - "component_id": "codewiki/src/fe/background_worker.py::BackgroundWorker.load_job_statuses", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/background_worker.py::BackgroundWorker._reconstruct_jobs_from_cache": { - "id": "codewiki/src/fe/background_worker.py::BackgroundWorker._reconstruct_jobs_from_cache", - "name": "BackgroundWorker._reconstruct_jobs_from_cache", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/background_worker.py", - "relative_path": "codewiki/src/fe/background_worker.py", - "depends_on": [ - "codewiki/src/fe/github_processor.py::GitHubRepoProcessor.get_repo_info", - "codewiki/src/fe/background_worker.py::BackgroundWorker.save_job_statuses", - "codewiki/src/fe/models.py::JobStatus" - ], - "source_code": " def _reconstruct_jobs_from_cache(self):\n \"\"\"Reconstruct job statuses from cache entries for backward compatibility.\"\"\"\n try:\n cache_entries = self.cache_manager.cache_index\n reconstructed_count = 0\n \n for repo_hash, cache_entry in cache_entries.items():\n # Extract repo info to create job_id\n from .github_processor import GitHubRepoProcessor\n try:\n repo_info = GitHubRepoProcessor.get_repo_info(cache_entry.repo_url)\n job_id = repo_info['full_name'].replace('/', '--')\n \n # Only add if job doesn't already exist\n if job_id not in self.job_status:\n self.job_status[job_id] = JobStatus(\n job_id=job_id,\n repo_url=cache_entry.repo_url,\n status='completed',\n created_at=cache_entry.created_at,\n completed_at=cache_entry.created_at,\n docs_path=cache_entry.docs_path,\n progress=\"Reconstructed from cache\"\n )\n reconstructed_count += 1\n except Exception as e:\n print(f\"Failed to reconstruct job for {cache_entry.repo_url}: {e}\")\n \n if reconstructed_count > 0:\n print(f\"Reconstructed {reconstructed_count} job statuses from cache\")\n self.save_job_statuses()\n \n except Exception as e:\n print(f\"Error reconstructing jobs from cache: {e}\")", - "start_line": 91, - "end_line": 124, - "has_docstring": true, - "docstring": "Reconstruct job statuses from cache entries for backward compatibility.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "BackgroundWorker", - "display_name": "method BackgroundWorker._reconstruct_jobs_from_cache", - "component_id": "codewiki/src/fe/background_worker.py::BackgroundWorker._reconstruct_jobs_from_cache", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/background_worker.py::BackgroundWorker.save_job_statuses": { - "id": "codewiki/src/fe/background_worker.py::BackgroundWorker.save_job_statuses", - "name": "BackgroundWorker.save_job_statuses", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/background_worker.py", - "relative_path": "codewiki/src/fe/background_worker.py", - "depends_on": [ - "codewiki/src/utils.py::FileManager.save_json" - ], - "source_code": " def save_job_statuses(self):\n \"\"\"Save job statuses to disk.\"\"\"\n try:\n # Ensure cache directory exists\n self.jobs_file.parent.mkdir(parents=True, exist_ok=True)\n \n data = {}\n for job_id, job in self.job_status.items():\n data[job_id] = {\n 'job_id': job.job_id,\n 'repo_url': job.repo_url,\n 'status': job.status,\n 'created_at': job.created_at.isoformat(),\n 'started_at': job.started_at.isoformat() if job.started_at else None,\n 'completed_at': job.completed_at.isoformat() if job.completed_at else None,\n 'error_message': job.error_message,\n 'progress': job.progress,\n 'docs_path': job.docs_path\n }\n \n file_manager.save_json(data, self.jobs_file)\n except Exception as e:\n print(f\"Error saving job statuses: {e}\")", - "start_line": 126, - "end_line": 148, - "has_docstring": true, - "docstring": "Save job statuses to disk.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "BackgroundWorker", - "display_name": "method BackgroundWorker.save_job_statuses", - "component_id": "codewiki/src/fe/background_worker.py::BackgroundWorker.save_job_statuses", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/background_worker.py::BackgroundWorker._worker_loop": { - "id": "codewiki/src/fe/background_worker.py::BackgroundWorker._worker_loop", - "name": "BackgroundWorker._worker_loop", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/background_worker.py", - "relative_path": "codewiki/src/fe/background_worker.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/fe/background_worker.py::BackgroundWorker._process_job" - ], - "source_code": " def _worker_loop(self):\n \"\"\"Main worker loop.\"\"\"\n while self.running:\n try:\n if not self.processing_queue.empty():\n job_id = self.processing_queue.get(timeout=1)\n self._process_job(job_id)\n else:\n time.sleep(1)\n except Exception as e:\n print(f\"Worker error: {e}\")\n time.sleep(1)", - "start_line": 150, - "end_line": 161, - "has_docstring": true, - "docstring": "Main worker loop.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "BackgroundWorker", - "display_name": "method BackgroundWorker._worker_loop", - "component_id": "codewiki/src/fe/background_worker.py::BackgroundWorker._worker_loop", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/background_worker.py::BackgroundWorker._process_job": { - "id": "codewiki/src/fe/background_worker.py::BackgroundWorker._process_job", - "name": "BackgroundWorker._process_job", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/background_worker.py", - "relative_path": "codewiki/src/fe/background_worker.py", - "depends_on": [ - "codewiki/src/fe/github_processor.py::GitHubRepoProcessor.get_repo_info", - "codewiki/src/fe/cache_manager.py::CacheManager.get_cached_docs", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.run", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator", - "codewiki/src/fe/cache_manager.py::CacheManager.add_to_cache", - "codewiki/src/config.py::Config.from_args", - "codewiki/src/fe/github_processor.py::GitHubRepoProcessor.clone_repository", - "codewiki/src/fe/background_worker.py::BackgroundWorker.save_job_statuses" - ], - "source_code": " def _process_job(self, job_id: str):\n \"\"\"Process a single documentation generation job.\"\"\"\n if job_id not in self.job_status:\n return\n \n job = self.job_status[job_id]\n \n try:\n # Update job status\n job.status = 'processing'\n job.started_at = datetime.now()\n job.progress = \"Starting repository clone...\"\n job.main_model = MAIN_MODEL\n \n # Check cache first\n cached_docs = self.cache_manager.get_cached_docs(job.repo_url)\n if cached_docs and Path(cached_docs).exists():\n job.status = 'completed'\n job.completed_at = datetime.now()\n job.docs_path = cached_docs\n job.progress = \"Documentation retrieved from cache\"\n if not job.main_model: # Only set if not already set\n job.main_model = MAIN_MODEL\n \n # Save job status to disk\n self.save_job_statuses()\n \n print(f\"Job {job_id}: Using cached documentation\")\n return\n \n # Clone repository\n repo_info = GitHubRepoProcessor.get_repo_info(job.repo_url)\n # Use repo full name for temp directory (already URL-safe since job_id is URL-safe)\n temp_repo_dir = os.path.join(self.temp_dir, job_id)\n \n job.progress = f\"Cloning repository {repo_info['full_name']}...\"\n \n if not GitHubRepoProcessor.clone_repository(repo_info['clone_url'], temp_repo_dir, job.commit_id):\n raise Exception(\"Failed to clone repository\")\n \n # Generate documentation\n job.progress = \"Analyzing repository structure...\"\n \n # Create config for documentation generation (using env vars)\n import argparse\n args = argparse.Namespace(repo_path=temp_repo_dir)\n config = Config.from_args(args)\n # Override docs_dir with job-specific directory\n config.docs_dir = os.path.join(\"output\", \"docs\", f\"{job_id}-docs\")\n \n job.progress = \"Generating documentation...\"\n \n # Generate documentation\n doc_generator = DocumentationGenerator(config, job.commit_id)\n \n # Run the async documentation generation in a new event loop\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n try:\n loop.run_until_complete(doc_generator.run())\n finally:\n loop.close()\n \n # Cache the results\n docs_path = os.path.abspath(config.docs_dir)\n self.cache_manager.add_to_cache(job.repo_url, docs_path)\n \n # Update job status\n job.status = 'completed'\n job.completed_at = datetime.now()\n job.docs_path = docs_path\n job.progress = \"Documentation generation completed\"\n \n # Save job status to disk\n self.save_job_statuses()\n \n print(f\"Job {job_id}: Documentation generated successfully\")\n \n except Exception as e:\n # Update job status with error\n job.status = 'failed'\n job.completed_at = datetime.now()\n job.error_message = str(e)\n job.progress = f\"Failed: {str(e)}\"\n \n print(f\"Job {job_id}: Failed with error: {e}\")\n \n finally:\n # Cleanup temporary repository\n if 'temp_repo_dir' in locals() and os.path.exists(temp_repo_dir):\n try:\n subprocess.run(['rm', '-rf', temp_repo_dir], check=True)\n except Exception as e:\n print(f\"Failed to cleanup temp directory: {e}\")", - "start_line": 163, - "end_line": 256, - "has_docstring": true, - "docstring": "Process a single documentation generation job.", - "parameters": [ - "self", - "job_id" - ], - "node_type": "method", - "base_classes": null, - "class_name": "BackgroundWorker", - "display_name": "method BackgroundWorker._process_job", - "component_id": "codewiki/src/fe/background_worker.py::BackgroundWorker._process_job", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/cache_manager.py::CacheManager": { - "id": "codewiki/src/fe/cache_manager.py::CacheManager", - "name": "CacheManager", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/cache_manager.py", - "relative_path": "codewiki/src/fe/cache_manager.py", - "depends_on": [], - "source_code": "class CacheManager:\n \"\"\"Manages documentation cache.\"\"\"\n \n def __init__(self, cache_dir: str = None, cache_expiry_days: int = None):\n self.cache_dir = Path(cache_dir or WebAppConfig.CACHE_DIR)\n self.cache_expiry_days = cache_expiry_days or WebAppConfig.CACHE_EXPIRY_DAYS\n self.cache_dir.mkdir(parents=True, exist_ok=True)\n self.cache_index: Dict[str, CacheEntry] = {}\n self.load_cache_index()\n \n def load_cache_index(self):\n \"\"\"Load cache index from disk.\"\"\"\n index_file = self.cache_dir / \"cache_index.json\"\n if index_file.exists():\n try:\n data = file_manager.load_json(index_file)\n for key, value in data.items():\n self.cache_index[key] = CacheEntry(\n repo_url=value['repo_url'],\n repo_url_hash=value['repo_url_hash'],\n docs_path=value['docs_path'],\n created_at=datetime.fromisoformat(value['created_at']),\n last_accessed=datetime.fromisoformat(value['last_accessed'])\n )\n except Exception as e:\n print(f\"Error loading cache index: {e}\")\n \n def save_cache_index(self):\n \"\"\"Save cache index to disk.\"\"\"\n index_file = self.cache_dir / \"cache_index.json\"\n try:\n data = {}\n for key, entry in self.cache_index.items():\n data[key] = {\n 'repo_url': entry.repo_url,\n 'repo_url_hash': entry.repo_url_hash,\n 'docs_path': entry.docs_path,\n 'created_at': entry.created_at.isoformat(),\n 'last_accessed': entry.last_accessed.isoformat()\n }\n \n file_manager.save_json(data, index_file)\n except Exception as e:\n print(f\"Error saving cache index: {e}\")\n \n def get_repo_hash(self, repo_url: str) -> str:\n \"\"\"Generate hash for repository URL.\"\"\"\n return hashlib.sha256(repo_url.encode()).hexdigest()[:16]\n \n def get_cached_docs(self, repo_url: str) -> Optional[str]:\n \"\"\"Get cached documentation path if available.\"\"\"\n repo_hash = self.get_repo_hash(repo_url)\n \n if repo_hash in self.cache_index:\n entry = self.cache_index[repo_hash]\n \n # Check if cache is still valid\n if datetime.now() - entry.created_at < timedelta(days=self.cache_expiry_days):\n # Update last accessed\n entry.last_accessed = datetime.now()\n self.save_cache_index()\n return entry.docs_path\n else:\n # Cache expired, remove it\n self.remove_from_cache(repo_url)\n \n return None\n \n def add_to_cache(self, repo_url: str, docs_path: str):\n \"\"\"Add documentation to cache.\"\"\"\n repo_hash = self.get_repo_hash(repo_url)\n now = datetime.now()\n \n self.cache_index[repo_hash] = CacheEntry(\n repo_url=repo_url,\n repo_url_hash=repo_hash,\n docs_path=docs_path,\n created_at=now,\n last_accessed=now\n )\n \n self.save_cache_index()\n \n def remove_from_cache(self, repo_url: str):\n \"\"\"Remove documentation from cache.\"\"\"\n repo_hash = self.get_repo_hash(repo_url)\n if repo_hash in self.cache_index:\n del self.cache_index[repo_hash]\n self.save_cache_index()\n \n def cleanup_expired_cache(self):\n \"\"\"Remove expired cache entries.\"\"\"\n expired_entries = []\n cutoff = datetime.now() - timedelta(days=self.cache_expiry_days)\n \n for repo_hash, entry in self.cache_index.items():\n if entry.created_at < cutoff:\n expired_entries.append(repo_hash)\n \n for repo_hash in expired_entries:\n del self.cache_index[repo_hash]\n \n if expired_entries:\n self.save_cache_index()", - "start_line": 16, - "end_line": 119, - "has_docstring": true, - "docstring": "Manages documentation cache.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class CacheManager", - "component_id": "codewiki/src/fe/cache_manager.py::CacheManager", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/cache_manager.py::CacheManager.__init__": { - "id": "codewiki/src/fe/cache_manager.py::CacheManager.__init__", - "name": "CacheManager.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/cache_manager.py", - "relative_path": "codewiki/src/fe/cache_manager.py", - "depends_on": [ - "codewiki/src/fe/cache_manager.py::CacheManager.load_cache_index" - ], - "source_code": " def __init__(self, cache_dir: str = None, cache_expiry_days: int = None):\n self.cache_dir = Path(cache_dir or WebAppConfig.CACHE_DIR)\n self.cache_expiry_days = cache_expiry_days or WebAppConfig.CACHE_EXPIRY_DAYS\n self.cache_dir.mkdir(parents=True, exist_ok=True)\n self.cache_index: Dict[str, CacheEntry] = {}\n self.load_cache_index()", - "start_line": 19, - "end_line": 24, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "cache_dir", - "cache_expiry_days" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CacheManager", - "display_name": "method CacheManager.__init__", - "component_id": "codewiki/src/fe/cache_manager.py::CacheManager.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/cache_manager.py::CacheManager.load_cache_index": { - "id": "codewiki/src/fe/cache_manager.py::CacheManager.load_cache_index", - "name": "CacheManager.load_cache_index", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/cache_manager.py", - "relative_path": "codewiki/src/fe/cache_manager.py", - "depends_on": [ - "codewiki/src/utils.py::FileManager.load_json", - "codewiki/src/fe/models.py::CacheEntry" - ], - "source_code": " def load_cache_index(self):\n \"\"\"Load cache index from disk.\"\"\"\n index_file = self.cache_dir / \"cache_index.json\"\n if index_file.exists():\n try:\n data = file_manager.load_json(index_file)\n for key, value in data.items():\n self.cache_index[key] = CacheEntry(\n repo_url=value['repo_url'],\n repo_url_hash=value['repo_url_hash'],\n docs_path=value['docs_path'],\n created_at=datetime.fromisoformat(value['created_at']),\n last_accessed=datetime.fromisoformat(value['last_accessed'])\n )\n except Exception as e:\n print(f\"Error loading cache index: {e}\")", - "start_line": 26, - "end_line": 41, - "has_docstring": true, - "docstring": "Load cache index from disk.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CacheManager", - "display_name": "method CacheManager.load_cache_index", - "component_id": "codewiki/src/fe/cache_manager.py::CacheManager.load_cache_index", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/cache_manager.py::CacheManager.save_cache_index": { - "id": "codewiki/src/fe/cache_manager.py::CacheManager.save_cache_index", - "name": "CacheManager.save_cache_index", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/cache_manager.py", - "relative_path": "codewiki/src/fe/cache_manager.py", - "depends_on": [ - "codewiki/src/utils.py::FileManager.save_json" - ], - "source_code": " def save_cache_index(self):\n \"\"\"Save cache index to disk.\"\"\"\n index_file = self.cache_dir / \"cache_index.json\"\n try:\n data = {}\n for key, entry in self.cache_index.items():\n data[key] = {\n 'repo_url': entry.repo_url,\n 'repo_url_hash': entry.repo_url_hash,\n 'docs_path': entry.docs_path,\n 'created_at': entry.created_at.isoformat(),\n 'last_accessed': entry.last_accessed.isoformat()\n }\n \n file_manager.save_json(data, index_file)\n except Exception as e:\n print(f\"Error saving cache index: {e}\")", - "start_line": 43, - "end_line": 59, - "has_docstring": true, - "docstring": "Save cache index to disk.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CacheManager", - "display_name": "method CacheManager.save_cache_index", - "component_id": "codewiki/src/fe/cache_manager.py::CacheManager.save_cache_index", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/cache_manager.py::CacheManager.get_repo_hash": { - "id": "codewiki/src/fe/cache_manager.py::CacheManager.get_repo_hash", - "name": "CacheManager.get_repo_hash", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/cache_manager.py", - "relative_path": "codewiki/src/fe/cache_manager.py", - "depends_on": [], - "source_code": " def get_repo_hash(self, repo_url: str) -> str:\n \"\"\"Generate hash for repository URL.\"\"\"\n return hashlib.sha256(repo_url.encode()).hexdigest()[:16]", - "start_line": 61, - "end_line": 63, - "has_docstring": true, - "docstring": "Generate hash for repository URL.", - "parameters": [ - "self", - "repo_url" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CacheManager", - "display_name": "method CacheManager.get_repo_hash", - "component_id": "codewiki/src/fe/cache_manager.py::CacheManager.get_repo_hash", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/cache_manager.py::CacheManager.get_cached_docs": { - "id": "codewiki/src/fe/cache_manager.py::CacheManager.get_cached_docs", - "name": "CacheManager.get_cached_docs", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/cache_manager.py", - "relative_path": "codewiki/src/fe/cache_manager.py", - "depends_on": [ - "codewiki/src/fe/cache_manager.py::CacheManager.save_cache_index", - "codewiki/src/fe/cache_manager.py::CacheManager.remove_from_cache", - "codewiki/src/fe/cache_manager.py::CacheManager.get_repo_hash" - ], - "source_code": " def get_cached_docs(self, repo_url: str) -> Optional[str]:\n \"\"\"Get cached documentation path if available.\"\"\"\n repo_hash = self.get_repo_hash(repo_url)\n \n if repo_hash in self.cache_index:\n entry = self.cache_index[repo_hash]\n \n # Check if cache is still valid\n if datetime.now() - entry.created_at < timedelta(days=self.cache_expiry_days):\n # Update last accessed\n entry.last_accessed = datetime.now()\n self.save_cache_index()\n return entry.docs_path\n else:\n # Cache expired, remove it\n self.remove_from_cache(repo_url)\n \n return None", - "start_line": 65, - "end_line": 82, - "has_docstring": true, - "docstring": "Get cached documentation path if available.", - "parameters": [ - "self", - "repo_url" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CacheManager", - "display_name": "method CacheManager.get_cached_docs", - "component_id": "codewiki/src/fe/cache_manager.py::CacheManager.get_cached_docs", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/cache_manager.py::CacheManager.add_to_cache": { - "id": "codewiki/src/fe/cache_manager.py::CacheManager.add_to_cache", - "name": "CacheManager.add_to_cache", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/cache_manager.py", - "relative_path": "codewiki/src/fe/cache_manager.py", - "depends_on": [ - "codewiki/src/fe/cache_manager.py::CacheManager.save_cache_index", - "codewiki/src/fe/models.py::CacheEntry", - "codewiki/src/fe/cache_manager.py::CacheManager.get_repo_hash" - ], - "source_code": " def add_to_cache(self, repo_url: str, docs_path: str):\n \"\"\"Add documentation to cache.\"\"\"\n repo_hash = self.get_repo_hash(repo_url)\n now = datetime.now()\n \n self.cache_index[repo_hash] = CacheEntry(\n repo_url=repo_url,\n repo_url_hash=repo_hash,\n docs_path=docs_path,\n created_at=now,\n last_accessed=now\n )\n \n self.save_cache_index()", - "start_line": 84, - "end_line": 97, - "has_docstring": true, - "docstring": "Add documentation to cache.", - "parameters": [ - "self", - "repo_url", - "docs_path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CacheManager", - "display_name": "method CacheManager.add_to_cache", - "component_id": "codewiki/src/fe/cache_manager.py::CacheManager.add_to_cache", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/cache_manager.py::CacheManager.remove_from_cache": { - "id": "codewiki/src/fe/cache_manager.py::CacheManager.remove_from_cache", - "name": "CacheManager.remove_from_cache", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/cache_manager.py", - "relative_path": "codewiki/src/fe/cache_manager.py", - "depends_on": [ - "codewiki/src/fe/cache_manager.py::CacheManager.save_cache_index", - "codewiki/src/fe/cache_manager.py::CacheManager.get_repo_hash" - ], - "source_code": " def remove_from_cache(self, repo_url: str):\n \"\"\"Remove documentation from cache.\"\"\"\n repo_hash = self.get_repo_hash(repo_url)\n if repo_hash in self.cache_index:\n del self.cache_index[repo_hash]\n self.save_cache_index()", - "start_line": 99, - "end_line": 104, - "has_docstring": true, - "docstring": "Remove documentation from cache.", - "parameters": [ - "self", - "repo_url" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CacheManager", - "display_name": "method CacheManager.remove_from_cache", - "component_id": "codewiki/src/fe/cache_manager.py::CacheManager.remove_from_cache", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/cache_manager.py::CacheManager.cleanup_expired_cache": { - "id": "codewiki/src/fe/cache_manager.py::CacheManager.cleanup_expired_cache", - "name": "CacheManager.cleanup_expired_cache", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/cache_manager.py", - "relative_path": "codewiki/src/fe/cache_manager.py", - "depends_on": [ - "codewiki/src/fe/cache_manager.py::CacheManager.save_cache_index" - ], - "source_code": " def cleanup_expired_cache(self):\n \"\"\"Remove expired cache entries.\"\"\"\n expired_entries = []\n cutoff = datetime.now() - timedelta(days=self.cache_expiry_days)\n \n for repo_hash, entry in self.cache_index.items():\n if entry.created_at < cutoff:\n expired_entries.append(repo_hash)\n \n for repo_hash in expired_entries:\n del self.cache_index[repo_hash]\n \n if expired_entries:\n self.save_cache_index()", - "start_line": 106, - "end_line": 119, - "has_docstring": true, - "docstring": "Remove expired cache entries.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "CacheManager", - "display_name": "method CacheManager.cleanup_expired_cache", - "component_id": "codewiki/src/fe/cache_manager.py::CacheManager.cleanup_expired_cache", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/config.py::WebAppConfig": { - "id": "codewiki/src/fe/config.py::WebAppConfig", - "name": "WebAppConfig", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/config.py", - "relative_path": "codewiki/src/fe/config.py", - "depends_on": [], - "source_code": "class WebAppConfig:\n \"\"\"Configuration class for web application settings.\"\"\"\n \n # Directories\n CACHE_DIR = \"./output/cache\"\n TEMP_DIR = \"./output/temp\"\n OUTPUT_DIR = \"./output\"\n \n # Queue settings\n QUEUE_SIZE = 100\n \n # Cache settings\n CACHE_EXPIRY_DAYS = 365\n \n # Job cleanup settings\n JOB_CLEANUP_HOURS = 24000\n RETRY_COOLDOWN_MINUTES = 3\n \n # Server settings\n DEFAULT_HOST = \"127.0.0.1\"\n DEFAULT_PORT = 8000\n \n # Git settings\n CLONE_TIMEOUT = 300\n CLONE_DEPTH = 1\n \n @classmethod\n def ensure_directories(cls):\n \"\"\"Ensure all required directories exist.\"\"\"\n directories = [\n cls.CACHE_DIR,\n cls.TEMP_DIR,\n cls.OUTPUT_DIR\n ]\n \n for directory in directories:\n Path(directory).mkdir(parents=True, exist_ok=True)\n \n @classmethod\n def get_absolute_path(cls, path: str) -> str:\n \"\"\"Get absolute path for a given relative path.\"\"\"\n return os.path.abspath(path)", - "start_line": 10, - "end_line": 51, - "has_docstring": true, - "docstring": "Configuration class for web application settings.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class WebAppConfig", - "component_id": "codewiki/src/fe/config.py::WebAppConfig", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/config.py::WebAppConfig.ensure_directories": { - "id": "codewiki/src/fe/config.py::WebAppConfig.ensure_directories", - "name": "WebAppConfig.ensure_directories", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/config.py", - "relative_path": "codewiki/src/fe/config.py", - "depends_on": [], - "source_code": " def ensure_directories(cls):\n \"\"\"Ensure all required directories exist.\"\"\"\n directories = [\n cls.CACHE_DIR,\n cls.TEMP_DIR,\n cls.OUTPUT_DIR\n ]\n \n for directory in directories:\n Path(directory).mkdir(parents=True, exist_ok=True)", - "start_line": 37, - "end_line": 46, - "has_docstring": true, - "docstring": "Ensure all required directories exist.", - "parameters": [ - "cls" - ], - "node_type": "method", - "base_classes": null, - "class_name": "WebAppConfig", - "display_name": "method WebAppConfig.ensure_directories", - "component_id": "codewiki/src/fe/config.py::WebAppConfig.ensure_directories", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/config.py::WebAppConfig.get_absolute_path": { - "id": "codewiki/src/fe/config.py::WebAppConfig.get_absolute_path", - "name": "WebAppConfig.get_absolute_path", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/config.py", - "relative_path": "codewiki/src/fe/config.py", - "depends_on": [], - "source_code": " def get_absolute_path(cls, path: str) -> str:\n \"\"\"Get absolute path for a given relative path.\"\"\"\n return os.path.abspath(path)", - "start_line": 49, - "end_line": 51, - "has_docstring": true, - "docstring": "Get absolute path for a given relative path.", - "parameters": [ - "cls", - "path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "WebAppConfig", - "display_name": "method WebAppConfig.get_absolute_path", - "component_id": "codewiki/src/fe/config.py::WebAppConfig.get_absolute_path", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/github_processor.py::GitHubRepoProcessor": { - "id": "codewiki/src/fe/github_processor.py::GitHubRepoProcessor", - "name": "GitHubRepoProcessor", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/github_processor.py", - "relative_path": "codewiki/src/fe/github_processor.py", - "depends_on": [], - "source_code": "class GitHubRepoProcessor:\n \"\"\"Handles GitHub repository processing.\"\"\"\n \n @staticmethod\n def is_valid_github_url(url: str) -> bool:\n \"\"\"Validate if the URL is a valid GitHub repository URL.\"\"\"\n try:\n parsed = urlparse(url)\n if parsed.netloc.lower() not in ['github.com', 'www.github.com']:\n return False\n \n path_parts = parsed.path.strip('/').split('/')\n if len(path_parts) < 2:\n return False\n \n # Check if it's a valid repo path (owner/repo)\n return len(path_parts) >= 2 and all(part for part in path_parts[:2])\n except Exception:\n return False\n \n @staticmethod\n def get_repo_info(url: str) -> Dict[str, str]:\n \"\"\"Extract repository information from GitHub URL.\"\"\"\n parsed = urlparse(url)\n path_parts = parsed.path.strip('/').split('/')\n \n owner = path_parts[0]\n repo = path_parts[1]\n \n # Remove .git suffix if present\n if repo.endswith('.git'):\n repo = repo[:-4]\n \n return {\n 'owner': owner,\n 'repo': repo,\n 'full_name': f\"{owner}/{repo}\",\n 'clone_url': f\"https://github.com/{owner}/{repo}.git\"\n }\n \n @staticmethod\n def clone_repository(clone_url: str, target_dir: str, commit_id: str = None) -> bool:\n \"\"\"Clone a GitHub repository to the target directory, optionally checking out a specific commit.\"\"\"\n try:\n # Ensure target directory exists\n os.makedirs(os.path.dirname(target_dir), exist_ok=True)\n \n # If specific commit is requested, don't use shallow clone\n if commit_id:\n # Clone full repository to access specific commit\n result = subprocess.run([\n 'git', 'clone', clone_url, target_dir\n ], capture_output=True, text=True, timeout=WebAppConfig.CLONE_TIMEOUT)\n \n if result.returncode != 0:\n print(f\"Error cloning repository: {result.stderr}\")\n return False\n \n # Checkout specific commit\n result = subprocess.run([\n 'git', 'checkout', commit_id\n ], cwd=target_dir, capture_output=True, text=True, timeout=30)\n \n if result.returncode != 0:\n print(f\"Error checking out commit {commit_id}: {result.stderr}\")\n return False\n else:\n # Clone repository with shallow depth (default behavior)\n result = subprocess.run([\n 'git', 'clone', '--depth', str(WebAppConfig.CLONE_DEPTH), clone_url, target_dir\n ], capture_output=True, text=True, timeout=WebAppConfig.CLONE_TIMEOUT)\n \n if result.returncode != 0:\n print(f\"Error cloning repository: {result.stderr}\")\n return False\n \n return True\n except Exception as e:\n print(f\"Error cloning repository: {e}\")\n return False", - "start_line": 14, - "end_line": 93, - "has_docstring": true, - "docstring": "Handles GitHub repository processing.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class GitHubRepoProcessor", - "component_id": "codewiki/src/fe/github_processor.py::GitHubRepoProcessor", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/github_processor.py::GitHubRepoProcessor.is_valid_github_url": { - "id": "codewiki/src/fe/github_processor.py::GitHubRepoProcessor.is_valid_github_url", - "name": "GitHubRepoProcessor.is_valid_github_url", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/github_processor.py", - "relative_path": "codewiki/src/fe/github_processor.py", - "depends_on": [], - "source_code": " def is_valid_github_url(url: str) -> bool:\n \"\"\"Validate if the URL is a valid GitHub repository URL.\"\"\"\n try:\n parsed = urlparse(url)\n if parsed.netloc.lower() not in ['github.com', 'www.github.com']:\n return False\n \n path_parts = parsed.path.strip('/').split('/')\n if len(path_parts) < 2:\n return False\n \n # Check if it's a valid repo path (owner/repo)\n return len(path_parts) >= 2 and all(part for part in path_parts[:2])\n except Exception:\n return False", - "start_line": 18, - "end_line": 32, - "has_docstring": true, - "docstring": "Validate if the URL is a valid GitHub repository URL.", - "parameters": [ - "url" - ], - "node_type": "method", - "base_classes": null, - "class_name": "GitHubRepoProcessor", - "display_name": "method GitHubRepoProcessor.is_valid_github_url", - "component_id": "codewiki/src/fe/github_processor.py::GitHubRepoProcessor.is_valid_github_url", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/github_processor.py::GitHubRepoProcessor.get_repo_info": { - "id": "codewiki/src/fe/github_processor.py::GitHubRepoProcessor.get_repo_info", - "name": "GitHubRepoProcessor.get_repo_info", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/github_processor.py", - "relative_path": "codewiki/src/fe/github_processor.py", - "depends_on": [], - "source_code": " def get_repo_info(url: str) -> Dict[str, str]:\n \"\"\"Extract repository information from GitHub URL.\"\"\"\n parsed = urlparse(url)\n path_parts = parsed.path.strip('/').split('/')\n \n owner = path_parts[0]\n repo = path_parts[1]\n \n # Remove .git suffix if present\n if repo.endswith('.git'):\n repo = repo[:-4]\n \n return {\n 'owner': owner,\n 'repo': repo,\n 'full_name': f\"{owner}/{repo}\",\n 'clone_url': f\"https://github.com/{owner}/{repo}.git\"\n }", - "start_line": 35, - "end_line": 52, - "has_docstring": true, - "docstring": "Extract repository information from GitHub URL.", - "parameters": [ - "url" - ], - "node_type": "method", - "base_classes": null, - "class_name": "GitHubRepoProcessor", - "display_name": "method GitHubRepoProcessor.get_repo_info", - "component_id": "codewiki/src/fe/github_processor.py::GitHubRepoProcessor.get_repo_info", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/github_processor.py::GitHubRepoProcessor.clone_repository": { - "id": "codewiki/src/fe/github_processor.py::GitHubRepoProcessor.clone_repository", - "name": "GitHubRepoProcessor.clone_repository", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/github_processor.py", - "relative_path": "codewiki/src/fe/github_processor.py", - "depends_on": [ - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.run" - ], - "source_code": " def clone_repository(clone_url: str, target_dir: str, commit_id: str = None) -> bool:\n \"\"\"Clone a GitHub repository to the target directory, optionally checking out a specific commit.\"\"\"\n try:\n # Ensure target directory exists\n os.makedirs(os.path.dirname(target_dir), exist_ok=True)\n \n # If specific commit is requested, don't use shallow clone\n if commit_id:\n # Clone full repository to access specific commit\n result = subprocess.run([\n 'git', 'clone', clone_url, target_dir\n ], capture_output=True, text=True, timeout=WebAppConfig.CLONE_TIMEOUT)\n \n if result.returncode != 0:\n print(f\"Error cloning repository: {result.stderr}\")\n return False\n \n # Checkout specific commit\n result = subprocess.run([\n 'git', 'checkout', commit_id\n ], cwd=target_dir, capture_output=True, text=True, timeout=30)\n \n if result.returncode != 0:\n print(f\"Error checking out commit {commit_id}: {result.stderr}\")\n return False\n else:\n # Clone repository with shallow depth (default behavior)\n result = subprocess.run([\n 'git', 'clone', '--depth', str(WebAppConfig.CLONE_DEPTH), clone_url, target_dir\n ], capture_output=True, text=True, timeout=WebAppConfig.CLONE_TIMEOUT)\n \n if result.returncode != 0:\n print(f\"Error cloning repository: {result.stderr}\")\n return False\n \n return True\n except Exception as e:\n print(f\"Error cloning repository: {e}\")\n return False", - "start_line": 55, - "end_line": 93, - "has_docstring": true, - "docstring": "Clone a GitHub repository to the target directory, optionally checking out a specific commit.", - "parameters": [ - "clone_url", - "target_dir", - "commit_id" - ], - "node_type": "method", - "base_classes": null, - "class_name": "GitHubRepoProcessor", - "display_name": "method GitHubRepoProcessor.clone_repository", - "component_id": "codewiki/src/fe/github_processor.py::GitHubRepoProcessor.clone_repository", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/models.py::RepositorySubmission": { - "id": "codewiki/src/fe/models.py::RepositorySubmission", - "name": "RepositorySubmission", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/models.py", - "relative_path": "codewiki/src/fe/models.py", - "depends_on": [], - "source_code": "class RepositorySubmission(BaseModel):\n \"\"\"Pydantic model for repository submission form.\"\"\"\n repo_url: HttpUrl", - "start_line": 12, - "end_line": 14, - "has_docstring": true, - "docstring": "Pydantic model for repository submission form.", - "parameters": null, - "node_type": "class", - "base_classes": [ - "BaseModel" - ], - "class_name": null, - "display_name": "class RepositorySubmission", - "component_id": "codewiki/src/fe/models.py::RepositorySubmission", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/models.py::JobStatusResponse": { - "id": "codewiki/src/fe/models.py::JobStatusResponse", - "name": "JobStatusResponse", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/models.py", - "relative_path": "codewiki/src/fe/models.py", - "depends_on": [], - "source_code": "class JobStatusResponse(BaseModel):\n \"\"\"Pydantic model for job status API response.\"\"\"\n job_id: str\n repo_url: str\n status: str\n created_at: datetime\n started_at: Optional[datetime] = None\n completed_at: Optional[datetime] = None\n error_message: Optional[str] = None\n progress: str = \"\"\n docs_path: Optional[str] = None\n main_model: Optional[str] = None\n commit_id: Optional[str] = None", - "start_line": 17, - "end_line": 29, - "has_docstring": true, - "docstring": "Pydantic model for job status API response.", - "parameters": null, - "node_type": "class", - "base_classes": [ - "BaseModel" - ], - "class_name": null, - "display_name": "class JobStatusResponse", - "component_id": "codewiki/src/fe/models.py::JobStatusResponse", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/models.py::JobStatus": { - "id": "codewiki/src/fe/models.py::JobStatus", - "name": "JobStatus", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/models.py", - "relative_path": "codewiki/src/fe/models.py", - "depends_on": [], - "source_code": "class JobStatus:\n \"\"\"Tracks the status of a documentation generation job.\"\"\"\n job_id: str\n repo_url: str\n status: str # 'queued', 'processing', 'completed', 'failed'\n created_at: datetime\n started_at: Optional[datetime] = None\n completed_at: Optional[datetime] = None\n error_message: Optional[str] = None\n progress: str = \"\"\n docs_path: Optional[str] = None\n main_model: Optional[str] = None\n commit_id: Optional[str] = None", - "start_line": 33, - "end_line": 45, - "has_docstring": true, - "docstring": "Tracks the status of a documentation generation job.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class JobStatus", - "component_id": "codewiki/src/fe/models.py::JobStatus", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/models.py::CacheEntry": { - "id": "codewiki/src/fe/models.py::CacheEntry", - "name": "CacheEntry", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/models.py", - "relative_path": "codewiki/src/fe/models.py", - "depends_on": [], - "source_code": "class CacheEntry:\n \"\"\"Represents a cached documentation result.\"\"\"\n repo_url: str\n repo_url_hash: str\n docs_path: str\n created_at: datetime\n last_accessed: datetime", - "start_line": 49, - "end_line": 55, - "has_docstring": true, - "docstring": "Represents a cached documentation result.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class CacheEntry", - "component_id": "codewiki/src/fe/models.py::CacheEntry", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/routes.py::WebRoutes": { - "id": "codewiki/src/fe/routes.py::WebRoutes", - "name": "WebRoutes", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/routes.py", - "relative_path": "codewiki/src/fe/routes.py", - "depends_on": [], - "source_code": "class WebRoutes:\n \"\"\"Handles all web routes for the application.\"\"\"\n \n def __init__(self, background_worker: BackgroundWorker, cache_manager: CacheManager):\n self.background_worker = background_worker\n self.cache_manager = cache_manager\n \n async def index_get(self, request: Request) -> HTMLResponse:\n \"\"\"Main page with form for submitting GitHub repositories.\"\"\"\n # Clean up old jobs before displaying\n # self.cleanup_old_jobs()\n \n # Get recent jobs (last 10)\n all_jobs = self.background_worker.get_all_jobs()\n recent_jobs = sorted(\n all_jobs.values(),\n key=lambda x: x.created_at,\n reverse=True\n )[:100]\n \n context = {\n \"message\": None,\n \"message_type\": None,\n \"repo_url\": \"\",\n \"commit_id\": \"\",\n \"recent_jobs\": recent_jobs\n }\n \n return HTMLResponse(content=render_template(WEB_INTERFACE_TEMPLATE, context))\n \n async def index_post(self, request: Request, repo_url: str = Form(...), commit_id: str = Form(\"\")) -> HTMLResponse:\n \"\"\"Handle repository submission.\"\"\"\n # Clean up old jobs before processing\n self.cleanup_old_jobs()\n \n message = None\n message_type = None\n \n repo_url = repo_url.strip()\n commit_id = commit_id.strip() if commit_id else \"\"\n \n if not repo_url:\n message = \"Please enter a GitHub repository URL\"\n message_type = \"error\"\n elif not GitHubRepoProcessor.is_valid_github_url(repo_url):\n message = \"Please enter a valid GitHub repository URL\"\n message_type = \"error\"\n else:\n # Normalize the repo URL for comparison\n normalized_repo_url = self._normalize_github_url(repo_url)\n \n # Get repo info for job ID generation\n repo_info = GitHubRepoProcessor.get_repo_info(normalized_repo_url)\n job_id = self._repo_full_name_to_job_id(repo_info['full_name'])\n \n # Check if already in queue, processing, or recently failed\n existing_job = self.background_worker.get_job_status(job_id)\n recent_cutoff = datetime.now() - timedelta(minutes=WebAppConfig.RETRY_COOLDOWN_MINUTES)\n \n if existing_job:\n if existing_job.status in ['queued', 'processing']:\n pass # Will handle below\n elif existing_job.status == 'failed' and existing_job.created_at > recent_cutoff:\n pass # Will handle below\n else:\n existing_job = None # Job is old or completed, can reuse\n \n if existing_job:\n if existing_job.status in ['queued', 'processing']:\n message = f\"Repository is already being processed (Job ID: {existing_job.job_id})\"\n else:\n message = f\"Repository recently failed processing. Please wait a few minutes before retrying (Job ID: {existing_job.job_id})\"\n message_type = \"error\"\n else:\n # Check cache\n cached_docs = self.cache_manager.get_cached_docs(normalized_repo_url)\n if cached_docs and Path(cached_docs).exists():\n message = \"Documentation found in cache! Redirecting to view...\"\n message_type = \"success\"\n # Create a dummy completed job for display\n job = JobStatus(\n job_id=job_id,\n repo_url=normalized_repo_url, # Use normalized URL\n status='completed',\n created_at=datetime.now(),\n completed_at=datetime.now(),\n docs_path=cached_docs,\n progress=\"Retrieved from cache\",\n commit_id=commit_id if commit_id else None\n )\n self.background_worker.job_status[job_id] = job\n else:\n # Add to queue\n try:\n job = JobStatus(\n job_id=job_id,\n repo_url=normalized_repo_url, # Use normalized URL\n status='queued',\n created_at=datetime.now(),\n progress=\"Waiting in queue...\",\n commit_id=commit_id if commit_id else None\n )\n \n self.background_worker.add_job(job_id, job)\n message = f\"Repository added to processing queue! Job ID: {job_id}\"\n message_type = \"success\"\n repo_url = \"\" # Clear form\n \n except Exception as e:\n message = f\"Failed to add repository to queue: {str(e)}\\n{format_exc()}\"\n message_type = \"error\"\n \n # Get recent jobs (last 10)\n all_jobs = self.background_worker.get_all_jobs()\n recent_jobs = sorted(\n all_jobs.values(),\n key=lambda x: x.created_at,\n reverse=True\n )\n \n context = {\n \"message\": message,\n \"message_type\": message_type,\n \"repo_url\": repo_url or \"\",\n \"commit_id\": commit_id or \"\",\n \"recent_jobs\": recent_jobs\n }\n \n return HTMLResponse(content=render_template(WEB_INTERFACE_TEMPLATE, context))\n \n async def get_job_status(self, job_id: str) -> JobStatusResponse:\n \"\"\"API endpoint to get job status.\"\"\"\n job = self.background_worker.get_job_status(job_id)\n if not job:\n raise HTTPException(status_code=404, detail=\"Job not found\")\n \n return JobStatusResponse(**asdict(job))\n \n async def view_docs(self, job_id: str) -> RedirectResponse:\n \"\"\"View generated documentation.\"\"\"\n job = self.background_worker.get_job_status(job_id)\n if not job:\n raise HTTPException(status_code=404, detail=\"Job not found\")\n \n if job.status != 'completed' or not job.docs_path:\n raise HTTPException(status_code=404, detail=\"Documentation not available\")\n \n docs_path = Path(job.docs_path)\n if not docs_path.exists():\n raise HTTPException(status_code=404, detail=\"Documentation files not found\")\n \n # Redirect to the documentation viewer\n return RedirectResponse(url=f\"/static-docs/{job_id}/\", status_code=status.HTTP_302_FOUND)\n \n async def serve_generated_docs(self, job_id: str, filename: str = \"overview.md\") -> HTMLResponse:\n \"\"\"Serve generated documentation files.\"\"\"\n job = self.background_worker.get_job_status(job_id)\n docs_path = None\n repo_url = None\n \n if job:\n # Job status exists - use it\n if job.status != 'completed' or not job.docs_path:\n raise HTTPException(status_code=404, detail=\"Documentation not available\")\n docs_path = Path(job.docs_path)\n repo_url = job.repo_url\n else:\n # No job status - try to find documentation in cache by job_id\n # Convert job_id back to repo full name and construct potential paths\n repo_full_name = self._job_id_to_repo_full_name(job_id)\n potential_repo_url = f\"https://github.com/{repo_full_name}\"\n \n # Check if documentation exists in cache\n cached_docs = self.cache_manager.get_cached_docs(potential_repo_url)\n if cached_docs and Path(cached_docs).exists():\n docs_path = Path(cached_docs)\n repo_url = potential_repo_url\n \n # Recreate job status for consistency\n job = JobStatus(\n job_id=job_id,\n repo_url=potential_repo_url,\n status='completed',\n created_at=datetime.now(),\n completed_at=datetime.now(),\n docs_path=cached_docs,\n progress=\"Loaded from cache\",\n commit_id=None # No commit info available from cache\n )\n self.background_worker.job_status[job_id] = job\n self.background_worker.save_job_statuses()\n else:\n raise HTTPException(status_code=404, detail=\"Documentation not found\")\n \n if not docs_path or not docs_path.exists():\n raise HTTPException(status_code=404, detail=\"Documentation files not found\")\n \n # Load module tree\n module_tree = None\n module_tree_file = docs_path / \"module_tree.json\"\n if module_tree_file.exists():\n try:\n module_tree = file_manager.load_json(module_tree_file)\n except Exception:\n pass\n \n # Load metadata\n metadata = None\n metadata_file = docs_path / \"metadata.json\"\n if metadata_file.exists():\n try:\n metadata = file_manager.load_json(metadata_file)\n except Exception:\n pass\n \n # Serve the requested file\n file_path = docs_path / filename\n if not file_path.exists():\n raise HTTPException(status_code=404, detail=f\"File {filename} not found\")\n \n try:\n content = file_manager.load_text(file_path)\n \n # Convert markdown to HTML (reuse from visualise_docs.py)\n from .visualise_docs import markdown_to_html, get_file_title\n from .templates import DOCS_VIEW_TEMPLATE\n \n html_content = markdown_to_html(content)\n title = get_file_title(file_path)\n \n context = {\n \"repo_name\": repo_url.split(\"/\")[-1],\n \"title\": title,\n \"content\": html_content,\n \"navigation\": module_tree,\n \"current_page\": filename,\n \"job_id\": job_id,\n \"metadata\": metadata\n }\n \n return HTMLResponse(content=render_template(DOCS_VIEW_TEMPLATE, context))\n \n except Exception as e:\n raise HTTPException(status_code=500, detail=f\"Error reading {filename}: {e}\\n{format_exc()}\")\n \n def _normalize_github_url(self, url: str) -> str:\n \"\"\"Normalize GitHub URL for consistent comparison.\"\"\"\n try:\n # Get repo info to standardize the URL format\n repo_info = GitHubRepoProcessor.get_repo_info(url)\n return f\"https://github.com/{repo_info['full_name']}\"\n except Exception:\n # Fallback to basic normalization\n return url.rstrip('/').lower()\n \n def _repo_full_name_to_job_id(self, full_name: str) -> str:\n \"\"\"Convert repo full name to URL-safe job ID.\"\"\"\n return full_name.replace('/', '--')\n \n def _job_id_to_repo_full_name(self, job_id: str) -> str:\n \"\"\"Convert job ID back to repo full name.\"\"\"\n return job_id.replace('--', '/')\n \n def cleanup_old_jobs(self):\n \"\"\"Clean up old job status entries.\"\"\"\n cutoff = datetime.now() - timedelta(hours=WebAppConfig.JOB_CLEANUP_HOURS)\n all_jobs = self.background_worker.get_all_jobs()\n expired_jobs = [\n job_id for job_id, job in all_jobs.items()\n if job.created_at < cutoff and job.status in ['completed', 'failed']\n ]\n \n for job_id in expired_jobs:\n if job_id in self.background_worker.job_status:\n del self.background_worker.job_status[job_id]", - "start_line": 25, - "end_line": 299, - "has_docstring": true, - "docstring": "Handles all web routes for the application.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class WebRoutes", - "component_id": "codewiki/src/fe/routes.py::WebRoutes", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/routes.py::WebRoutes.__init__": { - "id": "codewiki/src/fe/routes.py::WebRoutes.__init__", - "name": "WebRoutes.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/routes.py", - "relative_path": "codewiki/src/fe/routes.py", - "depends_on": [], - "source_code": " def __init__(self, background_worker: BackgroundWorker, cache_manager: CacheManager):\n self.background_worker = background_worker\n self.cache_manager = cache_manager", - "start_line": 28, - "end_line": 30, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "background_worker", - "cache_manager" - ], - "node_type": "method", - "base_classes": null, - "class_name": "WebRoutes", - "display_name": "method WebRoutes.__init__", - "component_id": "codewiki/src/fe/routes.py::WebRoutes.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/routes.py::WebRoutes.index_get": { - "id": "codewiki/src/fe/routes.py::WebRoutes.index_get", - "name": "WebRoutes.index_get", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/routes.py", - "relative_path": "codewiki/src/fe/routes.py", - "depends_on": [ - "codewiki/src/fe/background_worker.py::BackgroundWorker.get_all_jobs", - "codewiki/src/fe/template_utils.py::render_template" - ], - "source_code": " async def index_get(self, request: Request) -> HTMLResponse:\n \"\"\"Main page with form for submitting GitHub repositories.\"\"\"\n # Clean up old jobs before displaying\n # self.cleanup_old_jobs()\n \n # Get recent jobs (last 10)\n all_jobs = self.background_worker.get_all_jobs()\n recent_jobs = sorted(\n all_jobs.values(),\n key=lambda x: x.created_at,\n reverse=True\n )[:100]\n \n context = {\n \"message\": None,\n \"message_type\": None,\n \"repo_url\": \"\",\n \"commit_id\": \"\",\n \"recent_jobs\": recent_jobs\n }\n \n return HTMLResponse(content=render_template(WEB_INTERFACE_TEMPLATE, context))", - "start_line": 32, - "end_line": 53, - "has_docstring": true, - "docstring": "Main page with form for submitting GitHub repositories.", - "parameters": [ - "self", - "request" - ], - "node_type": "method", - "base_classes": null, - "class_name": "WebRoutes", - "display_name": "method WebRoutes.index_get", - "component_id": "codewiki/src/fe/routes.py::WebRoutes.index_get", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/routes.py::WebRoutes.index_post": { - "id": "codewiki/src/fe/routes.py::WebRoutes.index_post", - "name": "WebRoutes.index_post", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/routes.py", - "relative_path": "codewiki/src/fe/routes.py", - "depends_on": [ - "codewiki/src/fe/routes.py::WebRoutes.cleanup_old_jobs", - "codewiki/src/fe/background_worker.py::BackgroundWorker.add_job", - "codewiki/src/fe/template_utils.py::render_template", - "codewiki/src/fe/background_worker.py::BackgroundWorker.get_all_jobs", - "codewiki/src/fe/github_processor.py::GitHubRepoProcessor.is_valid_github_url", - "codewiki/src/fe/github_processor.py::GitHubRepoProcessor.get_repo_info", - "codewiki/src/fe/cache_manager.py::CacheManager.get_cached_docs", - "codewiki/src/fe/routes.py::WebRoutes._normalize_github_url", - "codewiki/src/fe/routes.py::WebRoutes._repo_full_name_to_job_id", - "codewiki/src/fe/models.py::JobStatus" - ], - "source_code": " async def index_post(self, request: Request, repo_url: str = Form(...), commit_id: str = Form(\"\")) -> HTMLResponse:\n \"\"\"Handle repository submission.\"\"\"\n # Clean up old jobs before processing\n self.cleanup_old_jobs()\n \n message = None\n message_type = None\n \n repo_url = repo_url.strip()\n commit_id = commit_id.strip() if commit_id else \"\"\n \n if not repo_url:\n message = \"Please enter a GitHub repository URL\"\n message_type = \"error\"\n elif not GitHubRepoProcessor.is_valid_github_url(repo_url):\n message = \"Please enter a valid GitHub repository URL\"\n message_type = \"error\"\n else:\n # Normalize the repo URL for comparison\n normalized_repo_url = self._normalize_github_url(repo_url)\n \n # Get repo info for job ID generation\n repo_info = GitHubRepoProcessor.get_repo_info(normalized_repo_url)\n job_id = self._repo_full_name_to_job_id(repo_info['full_name'])\n \n # Check if already in queue, processing, or recently failed\n existing_job = self.background_worker.get_job_status(job_id)\n recent_cutoff = datetime.now() - timedelta(minutes=WebAppConfig.RETRY_COOLDOWN_MINUTES)\n \n if existing_job:\n if existing_job.status in ['queued', 'processing']:\n pass # Will handle below\n elif existing_job.status == 'failed' and existing_job.created_at > recent_cutoff:\n pass # Will handle below\n else:\n existing_job = None # Job is old or completed, can reuse\n \n if existing_job:\n if existing_job.status in ['queued', 'processing']:\n message = f\"Repository is already being processed (Job ID: {existing_job.job_id})\"\n else:\n message = f\"Repository recently failed processing. Please wait a few minutes before retrying (Job ID: {existing_job.job_id})\"\n message_type = \"error\"\n else:\n # Check cache\n cached_docs = self.cache_manager.get_cached_docs(normalized_repo_url)\n if cached_docs and Path(cached_docs).exists():\n message = \"Documentation found in cache! Redirecting to view...\"\n message_type = \"success\"\n # Create a dummy completed job for display\n job = JobStatus(\n job_id=job_id,\n repo_url=normalized_repo_url, # Use normalized URL\n status='completed',\n created_at=datetime.now(),\n completed_at=datetime.now(),\n docs_path=cached_docs,\n progress=\"Retrieved from cache\",\n commit_id=commit_id if commit_id else None\n )\n self.background_worker.job_status[job_id] = job\n else:\n # Add to queue\n try:\n job = JobStatus(\n job_id=job_id,\n repo_url=normalized_repo_url, # Use normalized URL\n status='queued',\n created_at=datetime.now(),\n progress=\"Waiting in queue...\",\n commit_id=commit_id if commit_id else None\n )\n \n self.background_worker.add_job(job_id, job)\n message = f\"Repository added to processing queue! Job ID: {job_id}\"\n message_type = \"success\"\n repo_url = \"\" # Clear form\n \n except Exception as e:\n message = f\"Failed to add repository to queue: {str(e)}\\n{format_exc()}\"\n message_type = \"error\"\n \n # Get recent jobs (last 10)\n all_jobs = self.background_worker.get_all_jobs()\n recent_jobs = sorted(\n all_jobs.values(),\n key=lambda x: x.created_at,\n reverse=True\n )\n \n context = {\n \"message\": message,\n \"message_type\": message_type,\n \"repo_url\": repo_url or \"\",\n \"commit_id\": commit_id or \"\",\n \"recent_jobs\": recent_jobs\n }\n \n return HTMLResponse(content=render_template(WEB_INTERFACE_TEMPLATE, context))", - "start_line": 55, - "end_line": 153, - "has_docstring": true, - "docstring": "Handle repository submission.", - "parameters": [ - "self", - "request", - "repo_url", - "commit_id" - ], - "node_type": "method", - "base_classes": null, - "class_name": "WebRoutes", - "display_name": "method WebRoutes.index_post", - "component_id": "codewiki/src/fe/routes.py::WebRoutes.index_post", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/routes.py::WebRoutes.get_job_status": { - "id": "codewiki/src/fe/routes.py::WebRoutes.get_job_status", - "name": "WebRoutes.get_job_status", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/routes.py", - "relative_path": "codewiki/src/fe/routes.py", - "depends_on": [ - "codewiki/src/fe/models.py::JobStatusResponse" - ], - "source_code": " async def get_job_status(self, job_id: str) -> JobStatusResponse:\n \"\"\"API endpoint to get job status.\"\"\"\n job = self.background_worker.get_job_status(job_id)\n if not job:\n raise HTTPException(status_code=404, detail=\"Job not found\")\n \n return JobStatusResponse(**asdict(job))", - "start_line": 155, - "end_line": 161, - "has_docstring": true, - "docstring": "API endpoint to get job status.", - "parameters": [ - "self", - "job_id" - ], - "node_type": "method", - "base_classes": null, - "class_name": "WebRoutes", - "display_name": "method WebRoutes.get_job_status", - "component_id": "codewiki/src/fe/routes.py::WebRoutes.get_job_status", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/routes.py::WebRoutes.view_docs": { - "id": "codewiki/src/fe/routes.py::WebRoutes.view_docs", - "name": "WebRoutes.view_docs", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/routes.py", - "relative_path": "codewiki/src/fe/routes.py", - "depends_on": [], - "source_code": " async def view_docs(self, job_id: str) -> RedirectResponse:\n \"\"\"View generated documentation.\"\"\"\n job = self.background_worker.get_job_status(job_id)\n if not job:\n raise HTTPException(status_code=404, detail=\"Job not found\")\n \n if job.status != 'completed' or not job.docs_path:\n raise HTTPException(status_code=404, detail=\"Documentation not available\")\n \n docs_path = Path(job.docs_path)\n if not docs_path.exists():\n raise HTTPException(status_code=404, detail=\"Documentation files not found\")\n \n # Redirect to the documentation viewer\n return RedirectResponse(url=f\"/static-docs/{job_id}/\", status_code=status.HTTP_302_FOUND)", - "start_line": 163, - "end_line": 177, - "has_docstring": true, - "docstring": "View generated documentation.", - "parameters": [ - "self", - "job_id" - ], - "node_type": "method", - "base_classes": null, - "class_name": "WebRoutes", - "display_name": "method WebRoutes.view_docs", - "component_id": "codewiki/src/fe/routes.py::WebRoutes.view_docs", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/routes.py::WebRoutes.serve_generated_docs": { - "id": "codewiki/src/fe/routes.py::WebRoutes.serve_generated_docs", - "name": "WebRoutes.serve_generated_docs", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/routes.py", - "relative_path": "codewiki/src/fe/routes.py", - "depends_on": [ - "codewiki/src/fe/visualise_docs.py::get_file_title", - "codewiki/src/fe/template_utils.py::render_template", - "codewiki/src/fe/visualise_docs.py::markdown_to_html", - "codewiki/src/fe/cache_manager.py::CacheManager.get_cached_docs", - "codewiki/src/utils.py::FileManager.load_text", - "codewiki/src/utils.py::FileManager.load_json", - "codewiki/src/fe/models.py::JobStatus", - "codewiki/src/fe/routes.py::WebRoutes._job_id_to_repo_full_name", - "codewiki/src/fe/background_worker.py::BackgroundWorker.save_job_statuses" - ], - "source_code": " async def serve_generated_docs(self, job_id: str, filename: str = \"overview.md\") -> HTMLResponse:\n \"\"\"Serve generated documentation files.\"\"\"\n job = self.background_worker.get_job_status(job_id)\n docs_path = None\n repo_url = None\n \n if job:\n # Job status exists - use it\n if job.status != 'completed' or not job.docs_path:\n raise HTTPException(status_code=404, detail=\"Documentation not available\")\n docs_path = Path(job.docs_path)\n repo_url = job.repo_url\n else:\n # No job status - try to find documentation in cache by job_id\n # Convert job_id back to repo full name and construct potential paths\n repo_full_name = self._job_id_to_repo_full_name(job_id)\n potential_repo_url = f\"https://github.com/{repo_full_name}\"\n \n # Check if documentation exists in cache\n cached_docs = self.cache_manager.get_cached_docs(potential_repo_url)\n if cached_docs and Path(cached_docs).exists():\n docs_path = Path(cached_docs)\n repo_url = potential_repo_url\n \n # Recreate job status for consistency\n job = JobStatus(\n job_id=job_id,\n repo_url=potential_repo_url,\n status='completed',\n created_at=datetime.now(),\n completed_at=datetime.now(),\n docs_path=cached_docs,\n progress=\"Loaded from cache\",\n commit_id=None # No commit info available from cache\n )\n self.background_worker.job_status[job_id] = job\n self.background_worker.save_job_statuses()\n else:\n raise HTTPException(status_code=404, detail=\"Documentation not found\")\n \n if not docs_path or not docs_path.exists():\n raise HTTPException(status_code=404, detail=\"Documentation files not found\")\n \n # Load module tree\n module_tree = None\n module_tree_file = docs_path / \"module_tree.json\"\n if module_tree_file.exists():\n try:\n module_tree = file_manager.load_json(module_tree_file)\n except Exception:\n pass\n \n # Load metadata\n metadata = None\n metadata_file = docs_path / \"metadata.json\"\n if metadata_file.exists():\n try:\n metadata = file_manager.load_json(metadata_file)\n except Exception:\n pass\n \n # Serve the requested file\n file_path = docs_path / filename\n if not file_path.exists():\n raise HTTPException(status_code=404, detail=f\"File {filename} not found\")\n \n try:\n content = file_manager.load_text(file_path)\n \n # Convert markdown to HTML (reuse from visualise_docs.py)\n from .visualise_docs import markdown_to_html, get_file_title\n from .templates import DOCS_VIEW_TEMPLATE\n \n html_content = markdown_to_html(content)\n title = get_file_title(file_path)\n \n context = {\n \"repo_name\": repo_url.split(\"/\")[-1],\n \"title\": title,\n \"content\": html_content,\n \"navigation\": module_tree,\n \"current_page\": filename,\n \"job_id\": job_id,\n \"metadata\": metadata\n }\n \n return HTMLResponse(content=render_template(DOCS_VIEW_TEMPLATE, context))\n \n except Exception as e:\n raise HTTPException(status_code=500, detail=f\"Error reading {filename}: {e}\\n{format_exc()}\")", - "start_line": 179, - "end_line": 268, - "has_docstring": true, - "docstring": "Serve generated documentation files.", - "parameters": [ - "self", - "job_id", - "filename" - ], - "node_type": "method", - "base_classes": null, - "class_name": "WebRoutes", - "display_name": "method WebRoutes.serve_generated_docs", - "component_id": "codewiki/src/fe/routes.py::WebRoutes.serve_generated_docs", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/routes.py::WebRoutes._normalize_github_url": { - "id": "codewiki/src/fe/routes.py::WebRoutes._normalize_github_url", - "name": "WebRoutes._normalize_github_url", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/routes.py", - "relative_path": "codewiki/src/fe/routes.py", - "depends_on": [ - "codewiki/src/fe/github_processor.py::GitHubRepoProcessor.get_repo_info" - ], - "source_code": " def _normalize_github_url(self, url: str) -> str:\n \"\"\"Normalize GitHub URL for consistent comparison.\"\"\"\n try:\n # Get repo info to standardize the URL format\n repo_info = GitHubRepoProcessor.get_repo_info(url)\n return f\"https://github.com/{repo_info['full_name']}\"\n except Exception:\n # Fallback to basic normalization\n return url.rstrip('/').lower()", - "start_line": 270, - "end_line": 278, - "has_docstring": true, - "docstring": "Normalize GitHub URL for consistent comparison.", - "parameters": [ - "self", - "url" - ], - "node_type": "method", - "base_classes": null, - "class_name": "WebRoutes", - "display_name": "method WebRoutes._normalize_github_url", - "component_id": "codewiki/src/fe/routes.py::WebRoutes._normalize_github_url", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/routes.py::WebRoutes._repo_full_name_to_job_id": { - "id": "codewiki/src/fe/routes.py::WebRoutes._repo_full_name_to_job_id", - "name": "WebRoutes._repo_full_name_to_job_id", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/routes.py", - "relative_path": "codewiki/src/fe/routes.py", - "depends_on": [], - "source_code": " def _repo_full_name_to_job_id(self, full_name: str) -> str:\n \"\"\"Convert repo full name to URL-safe job ID.\"\"\"\n return full_name.replace('/', '--')", - "start_line": 280, - "end_line": 282, - "has_docstring": true, - "docstring": "Convert repo full name to URL-safe job ID.", - "parameters": [ - "self", - "full_name" - ], - "node_type": "method", - "base_classes": null, - "class_name": "WebRoutes", - "display_name": "method WebRoutes._repo_full_name_to_job_id", - "component_id": "codewiki/src/fe/routes.py::WebRoutes._repo_full_name_to_job_id", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/routes.py::WebRoutes._job_id_to_repo_full_name": { - "id": "codewiki/src/fe/routes.py::WebRoutes._job_id_to_repo_full_name", - "name": "WebRoutes._job_id_to_repo_full_name", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/routes.py", - "relative_path": "codewiki/src/fe/routes.py", - "depends_on": [], - "source_code": " def _job_id_to_repo_full_name(self, job_id: str) -> str:\n \"\"\"Convert job ID back to repo full name.\"\"\"\n return job_id.replace('--', '/')", - "start_line": 284, - "end_line": 286, - "has_docstring": true, - "docstring": "Convert job ID back to repo full name.", - "parameters": [ - "self", - "job_id" - ], - "node_type": "method", - "base_classes": null, - "class_name": "WebRoutes", - "display_name": "method WebRoutes._job_id_to_repo_full_name", - "component_id": "codewiki/src/fe/routes.py::WebRoutes._job_id_to_repo_full_name", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/routes.py::WebRoutes.cleanup_old_jobs": { - "id": "codewiki/src/fe/routes.py::WebRoutes.cleanup_old_jobs", - "name": "WebRoutes.cleanup_old_jobs", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/routes.py", - "relative_path": "codewiki/src/fe/routes.py", - "depends_on": [ - "codewiki/src/fe/background_worker.py::BackgroundWorker.get_all_jobs" - ], - "source_code": " def cleanup_old_jobs(self):\n \"\"\"Clean up old job status entries.\"\"\"\n cutoff = datetime.now() - timedelta(hours=WebAppConfig.JOB_CLEANUP_HOURS)\n all_jobs = self.background_worker.get_all_jobs()\n expired_jobs = [\n job_id for job_id, job in all_jobs.items()\n if job.created_at < cutoff and job.status in ['completed', 'failed']\n ]\n \n for job_id in expired_jobs:\n if job_id in self.background_worker.job_status:\n del self.background_worker.job_status[job_id]", - "start_line": 288, - "end_line": 299, - "has_docstring": true, - "docstring": "Clean up old job status entries.", - "parameters": [ - "self" - ], - "node_type": "method", - "base_classes": null, - "class_name": "WebRoutes", - "display_name": "method WebRoutes.cleanup_old_jobs", - "component_id": "codewiki/src/fe/routes.py::WebRoutes.cleanup_old_jobs", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/template_utils.py::StringTemplateLoader": { - "id": "codewiki/src/fe/template_utils.py::StringTemplateLoader", - "name": "StringTemplateLoader", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/template_utils.py", - "relative_path": "codewiki/src/fe/template_utils.py", - "depends_on": [], - "source_code": "class StringTemplateLoader(BaseLoader):\n \"\"\"Custom Jinja2 loader for string templates.\"\"\"\n \n def __init__(self, template_string: str):\n self.template_string = template_string\n \n def get_source(self, environment, template):\n return self.template_string, None, lambda: True", - "start_line": 10, - "end_line": 17, - "has_docstring": true, - "docstring": "Custom Jinja2 loader for string templates.", - "parameters": null, - "node_type": "class", - "base_classes": [ - "BaseLoader" - ], - "class_name": null, - "display_name": "class StringTemplateLoader", - "component_id": "codewiki/src/fe/template_utils.py::StringTemplateLoader", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/template_utils.py::StringTemplateLoader.__init__": { - "id": "codewiki/src/fe/template_utils.py::StringTemplateLoader.__init__", - "name": "StringTemplateLoader.__init__", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/template_utils.py", - "relative_path": "codewiki/src/fe/template_utils.py", - "depends_on": [], - "source_code": " def __init__(self, template_string: str):\n self.template_string = template_string", - "start_line": 13, - "end_line": 14, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "template_string" - ], - "node_type": "method", - "base_classes": null, - "class_name": "StringTemplateLoader", - "display_name": "method StringTemplateLoader.__init__", - "component_id": "codewiki/src/fe/template_utils.py::StringTemplateLoader.__init__", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/template_utils.py::StringTemplateLoader.get_source": { - "id": "codewiki/src/fe/template_utils.py::StringTemplateLoader.get_source", - "name": "StringTemplateLoader.get_source", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/template_utils.py", - "relative_path": "codewiki/src/fe/template_utils.py", - "depends_on": [], - "source_code": " def get_source(self, environment, template):\n return self.template_string, None, lambda: True", - "start_line": 16, - "end_line": 17, - "has_docstring": false, - "docstring": "", - "parameters": [ - "self", - "environment", - "template" - ], - "node_type": "method", - "base_classes": null, - "class_name": "StringTemplateLoader", - "display_name": "method StringTemplateLoader.get_source", - "component_id": "codewiki/src/fe/template_utils.py::StringTemplateLoader.get_source", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/template_utils.py::render_template": { - "id": "codewiki/src/fe/template_utils.py::render_template", - "name": "render_template", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/template_utils.py", - "relative_path": "codewiki/src/fe/template_utils.py", - "depends_on": [ - "codewiki/src/fe/template_utils.py::StringTemplateLoader" - ], - "source_code": "def render_template(template: str, context: Dict[str, Any]) -> str:\n \"\"\"\n Render template using Jinja2.\n \n Args:\n template: HTML template string with Jinja2 syntax\n context: Dictionary of variables to substitute\n \n Returns:\n Rendered HTML string\n \"\"\"\n # Create Jinja2 environment with string template\n env = Environment(\n loader=StringTemplateLoader(template),\n autoescape=select_autoescape(['html', 'xml']),\n trim_blocks=True,\n lstrip_blocks=True\n )\n \n # Get template and render\n jinja_template = env.get_template('')\n return jinja_template.render(**context)", - "start_line": 20, - "end_line": 41, - "has_docstring": true, - "docstring": "Render template using Jinja2.\n\nArgs:\n template: HTML template string with Jinja2 syntax\n context: Dictionary of variables to substitute\n\nReturns:\n Rendered HTML string", - "parameters": [ - "template", - "context" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function render_template", - "component_id": "codewiki/src/fe/template_utils.py::render_template", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/template_utils.py::render_navigation": { - "id": "codewiki/src/fe/template_utils.py::render_navigation", - "name": "render_navigation", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/template_utils.py", - "relative_path": "codewiki/src/fe/template_utils.py", - "depends_on": [ - "codewiki/src/fe/template_utils.py::render_template" - ], - "source_code": "def render_navigation(module_tree: Dict[str, Any], current_page: str = \"\") -> str:\n \"\"\"\n Render navigation HTML from module tree structure.\n \n Args:\n module_tree: Dictionary representing the module tree\n current_page: Current page filename for highlighting\n \n Returns:\n HTML string for navigation\n \"\"\"\n if not module_tree:\n return \"\"\n \n nav_template = \"\"\"\n {%- for section_key, section_data in module_tree.items() %}\n
\n

{{ section_key.replace('_', ' ').title() }}

\n {%- if section_data.get('components') %}\n Overview\n {%- endif %}\n {%- if section_data.get('children') %}\n {%- for child_key, child_data in section_data['children'].items() %}\n \n {%- endfor %}\n {%- endif %}\n
\n {%- endfor %}\n \"\"\"\n \n return render_template(nav_template, {\n 'module_tree': module_tree,\n 'current_page': current_page\n })", - "start_line": 44, - "end_line": 79, - "has_docstring": true, - "docstring": "Render navigation HTML from module tree structure.\n\nArgs:\n module_tree: Dictionary representing the module tree\n current_page: Current page filename for highlighting\n\nReturns:\n HTML string for navigation", - "parameters": [ - "module_tree", - "current_page" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function render_navigation", - "component_id": "codewiki/src/fe/template_utils.py::render_navigation", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/template_utils.py::render_job_list": { - "id": "codewiki/src/fe/template_utils.py::render_job_list", - "name": "render_job_list", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/template_utils.py", - "relative_path": "codewiki/src/fe/template_utils.py", - "depends_on": [ - "codewiki/src/fe/template_utils.py::render_template" - ], - "source_code": "def render_job_list(jobs: list) -> str:\n \"\"\"\n Render job list HTML.\n \n Args:\n jobs: List of job objects\n \n Returns:\n HTML string for job list\n \"\"\"\n if not jobs:\n return \"\"\n \n job_list_template = \"\"\"\n {%- for job in jobs %}\n
\n
\n
{{ job.repo_url }}
\n
{{ job.status.title() }}
\n
\n {%- if job.progress %}\n
{{ job.progress }}
\n {%- endif %}\n {%- if job.status == 'completed' and job.docs_path %}\n \n {%- endif %}\n
\n {%- endfor %}\n \"\"\"\n \n return render_template(job_list_template, {'jobs': jobs})", - "start_line": 82, - "end_line": 114, - "has_docstring": true, - "docstring": "Render job list HTML.\n\nArgs:\n jobs: List of job objects\n\nReturns:\n HTML string for job list", - "parameters": [ - "jobs" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function render_job_list", - "component_id": "codewiki/src/fe/template_utils.py::render_job_list", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/visualise_docs.py::initialize_globals": { - "id": "codewiki/src/fe/visualise_docs.py::initialize_globals", - "name": "initialize_globals", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/visualise_docs.py", - "relative_path": "codewiki/src/fe/visualise_docs.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/fe/visualise_docs.py::load_module_tree" - ], - "source_code": "def initialize_globals():\n \"\"\"Initialize global variables from environment or command line args if not already set.\"\"\"\n global DOCS_FOLDER, MODULE_TREE\n \n if DOCS_FOLDER is None:\n # Try to get from environment variable or use a default\n import os\n docs_folder_path = os.environ.get('DOCS_FOLDER')\n if docs_folder_path and Path(docs_folder_path).exists():\n DOCS_FOLDER = docs_folder_path\n MODULE_TREE = load_module_tree(Path(docs_folder_path))\n else:\n # If no environment variable, we need to handle this gracefully\n # The FastAPI endpoints will need to check if DOCS_FOLDER is None\n pass", - "start_line": 34, - "end_line": 48, - "has_docstring": true, - "docstring": "Initialize global variables from environment or command line args if not already set.", - "parameters": [], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function initialize_globals", - "component_id": "codewiki/src/fe/visualise_docs.py::initialize_globals", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/visualise_docs.py::load_module_tree": { - "id": "codewiki/src/fe/visualise_docs.py::load_module_tree", - "name": "load_module_tree", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/visualise_docs.py", - "relative_path": "codewiki/src/fe/visualise_docs.py", - "depends_on": [ - "codewiki/src/utils.py::FileManager.load_json" - ], - "source_code": "def load_module_tree(docs_folder: Path) -> Optional[Dict]:\n \"\"\"Load the module tree structure from module_tree.json.\"\"\"\n tree_file = docs_folder / \"module_tree.json\"\n if not tree_file.exists():\n print(f\"Warning: module_tree.json not found in {docs_folder}\")\n return None\n \n try:\n return file_manager.load_json(tree_file)\n except Exception as e:\n print(f\"Error loading module_tree.json: {e}\")\n return None", - "start_line": 54, - "end_line": 65, - "has_docstring": true, - "docstring": "Load the module tree structure from module_tree.json.", - "parameters": [ - "docs_folder" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function load_module_tree", - "component_id": "codewiki/src/fe/visualise_docs.py::load_module_tree", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/visualise_docs.py::markdown_to_html": { - "id": "codewiki/src/fe/visualise_docs.py::markdown_to_html", - "name": "markdown_to_html", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/visualise_docs.py", - "relative_path": "codewiki/src/fe/visualise_docs.py", - "depends_on": [], - "source_code": "def markdown_to_html(content: str) -> str:\n \"\"\"Convert markdown content to HTML, with special handling for mermaid diagrams.\"\"\"\n # First, convert markdown to HTML\n html = md.render(content)\n \n # Post-process to ensure mermaid code blocks are properly formatted\n # Look for code blocks with language-mermaid class and convert them to mermaid divs\n import re\n \n # Pattern to match mermaid code blocks\n pattern = r'
(.*?)
'\n \n def replace_mermaid(match):\n mermaid_code = match.group(1)\n # Decode HTML entities that might have been encoded\n import html\n mermaid_code = html.unescape(mermaid_code)\n return f'
{mermaid_code}
'\n \n # Replace mermaid code blocks with proper mermaid divs\n html = re.sub(pattern, replace_mermaid, html, flags=re.DOTALL)\n \n return html", - "start_line": 68, - "end_line": 90, - "has_docstring": true, - "docstring": "Convert markdown content to HTML, with special handling for mermaid diagrams.", - "parameters": [ - "content" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function markdown_to_html", - "component_id": "codewiki/src/fe/visualise_docs.py::markdown_to_html", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/visualise_docs.py::get_file_title": { - "id": "codewiki/src/fe/visualise_docs.py::get_file_title", - "name": "get_file_title", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/visualise_docs.py", - "relative_path": "codewiki/src/fe/visualise_docs.py", - "depends_on": [ - "codewiki/src/utils.py::FileManager.load_text" - ], - "source_code": "def get_file_title(file_path: Path) -> str:\n \"\"\"Extract title from markdown file, fallback to filename.\"\"\"\n try:\n content = file_manager.load_text(file_path)\n first_line = content.split('\\n')[0].strip()\n if first_line.startswith('# '):\n return first_line[2:].strip()\n except Exception:\n pass\n \n # Fallback to filename without extension\n return file_path.stem.replace('_', ' ').title()", - "start_line": 93, - "end_line": 104, - "has_docstring": true, - "docstring": "Extract title from markdown file, fallback to filename.", - "parameters": [ - "file_path" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function get_file_title", - "component_id": "codewiki/src/fe/visualise_docs.py::get_file_title", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/visualise_docs.py::index": { - "id": "codewiki/src/fe/visualise_docs.py::index", - "name": "index", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/visualise_docs.py", - "relative_path": "codewiki/src/fe/visualise_docs.py", - "depends_on": [ - "codewiki/src/fe/visualise_docs.py::get_file_title", - "codewiki/src/fe/template_utils.py::render_template", - "codewiki/src/fe/visualise_docs.py::markdown_to_html", - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/utils.py::FileManager.load_text", - "codewiki/src/fe/visualise_docs.py::initialize_globals" - ], - "source_code": "async def index():\n \"\"\"Serve the overview page as the main page.\"\"\"\n initialize_globals()\n \n if DOCS_FOLDER is None:\n raise HTTPException(status_code=500, detail=\"Documentation folder not configured. Please set DOCS_FOLDER environment variable or run with --docs-folder argument.\")\n \n overview_file = Path(DOCS_FOLDER) / \"overview.md\"\n \n if not overview_file.exists():\n raise HTTPException(status_code=404, detail=\"overview.md not found in the documentation folder\")\n \n try:\n content = file_manager.load_text(overview_file)\n \n html_content = markdown_to_html(content)\n title = get_file_title(overview_file)\n \n context = {\n \"title\": title,\n \"content\": html_content,\n \"navigation\": MODULE_TREE,\n \"current_page\": \"overview.md\"\n }\n \n return HTMLResponse(content=render_template(DOCS_VIEW_TEMPLATE, context))\n \n except Exception as e:\n raise HTTPException(status_code=500, detail=f\"Error reading overview.md: {e}\")", - "start_line": 108, - "end_line": 136, - "has_docstring": true, - "docstring": "Serve the overview page as the main page.", - "parameters": [], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function index", - "component_id": "codewiki/src/fe/visualise_docs.py::index", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/visualise_docs.py::serve_doc": { - "id": "codewiki/src/fe/visualise_docs.py::serve_doc", - "name": "serve_doc", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/visualise_docs.py", - "relative_path": "codewiki/src/fe/visualise_docs.py", - "depends_on": [ - "codewiki/src/fe/visualise_docs.py::get_file_title", - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/src/fe/template_utils.py::render_template", - "codewiki/src/fe/visualise_docs.py::markdown_to_html", - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/utils.py::FileManager.load_text", - "codewiki/src/fe/visualise_docs.py::initialize_globals" - ], - "source_code": "async def serve_doc(filename: str):\n \"\"\"Serve individual documentation files.\"\"\"\n initialize_globals()\n \n if DOCS_FOLDER is None:\n raise HTTPException(status_code=500, detail=\"Documentation folder not configured. Please set DOCS_FOLDER environment variable or run with --docs-folder argument.\")\n \n # Security check: ensure we're only serving .md files and they exist in the docs folder\n if not filename.endswith('.md'):\n raise HTTPException(status_code=404, detail=\"Only markdown files are supported\")\n \n file_path = Path(DOCS_FOLDER) / filename\n \n # Ensure the file is within the docs folder (prevent directory traversal)\n try:\n file_path = file_path.resolve()\n docs_folder_resolved = Path(DOCS_FOLDER).resolve()\n if not str(file_path).startswith(str(docs_folder_resolved)):\n raise HTTPException(status_code=403, detail=\"Access denied\")\n except Exception:\n raise HTTPException(status_code=403, detail=\"Invalid file path\")\n \n if not file_path.exists():\n raise HTTPException(status_code=404, detail=f\"File {filename} not found\")\n \n try:\n content = file_manager.load_text(file_path)\n \n html_content = markdown_to_html(content)\n title = get_file_title(file_path)\n \n context = {\n \"title\": title,\n \"content\": html_content,\n \"navigation\": MODULE_TREE,\n \"current_page\": filename\n }\n \n return HTMLResponse(content=render_template(DOCS_VIEW_TEMPLATE, context))\n \n except Exception as e:\n raise HTTPException(status_code=500, detail=f\"Error reading {filename}: {e}\")", - "start_line": 140, - "end_line": 181, - "has_docstring": true, - "docstring": "Serve individual documentation files.", - "parameters": [ - "filename" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function serve_doc", - "component_id": "codewiki/src/fe/visualise_docs.py::serve_doc", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/visualise_docs.py::main": { - "id": "codewiki/src/fe/visualise_docs.py::main", - "name": "main", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/visualise_docs.py", - "relative_path": "codewiki/src/fe/visualise_docs.py", - "depends_on": [ - "codewiki/src/be/dependency_analyzer/analyzers/php.py::NamespaceResolver.resolve", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.run", - "codewiki/src/fe/visualise_docs.py::load_module_tree" - ], - "source_code": "def main():\n \"\"\"Main function to run the documentation server.\"\"\"\n parser = argparse.ArgumentParser(\n description=\"Simple documentation server for hosting markdown documentation folders\"\n )\n parser.add_argument(\n \"--docs-folder\",\n type=str,\n required=True,\n help=\"Path to the documentation folder containing markdown files and module_tree.json\"\n )\n parser.add_argument(\n \"--port\",\n type=int,\n default=8000,\n help=\"Port to run the server on (default: 8000)\"\n )\n parser.add_argument(\n \"--host\",\n type=str,\n default=\"127.0.0.1\",\n help=\"Host to bind the server to (default: 127.0.0.1)\"\n )\n parser.add_argument(\n \"--debug\",\n action=\"store_true\",\n help=\"Run the server in debug mode\"\n )\n \n args = parser.parse_args()\n \n # Validate docs folder\n docs_folder = Path(args.docs_folder)\n if not docs_folder.exists():\n print(f\"Error: Documentation folder '{docs_folder}' does not exist\")\n sys.exit(1)\n \n if not docs_folder.is_dir():\n print(f\"Error: '{docs_folder}' is not a directory\")\n sys.exit(1)\n \n # Check for overview.md\n overview_file = docs_folder / \"overview.md\"\n if not overview_file.exists():\n print(f\"Warning: overview.md not found in '{docs_folder}'\")\n \n # Set global variables and environment variable for uvicorn reload\n global DOCS_FOLDER, MODULE_TREE\n DOCS_FOLDER = str(docs_folder.resolve())\n MODULE_TREE = load_module_tree(docs_folder)\n \n # Set environment variable so uvicorn reload can pick it up\n import os\n os.environ['DOCS_FOLDER'] = DOCS_FOLDER\n \n print(f\"πŸ“š Starting documentation server...\")\n print(f\"πŸ“ Documentation folder: {DOCS_FOLDER}\")\n print(f\"🌐 Server running at: http://{args.host}:{args.port}\")\n print(f\"πŸ“– Main page: overview.md\")\n \n if MODULE_TREE:\n modules_count = len(MODULE_TREE)\n print(f\"πŸ—‚οΈ Found {modules_count} main modules in module_tree.json\")\n \n print(\"\\nPress Ctrl+C to stop the server\")\n \n try:\n import uvicorn\n uvicorn.run(\n \"visualise_docs:app\",\n host=args.host,\n port=args.port,\n reload=args.debug,\n log_level=\"debug\" if args.debug else \"info\"\n )\n except KeyboardInterrupt:\n print(\"\\nπŸ‘‹ Server stopped\")", - "start_line": 188, - "end_line": 264, - "has_docstring": true, - "docstring": "Main function to run the documentation server.", - "parameters": [], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function main", - "component_id": "codewiki/src/fe/visualise_docs.py::main", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/web_app.py::index_get": { - "id": "codewiki/src/fe/web_app.py::index_get", - "name": "index_get", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/web_app.py", - "relative_path": "codewiki/src/fe/web_app.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/fe/routes.py::WebRoutes.index_get" - ], - "source_code": "async def index_get(request: Request):\n \"\"\"Main page with form for submitting GitHub repositories.\"\"\"\n return await web_routes.index_get(request)", - "start_line": 43, - "end_line": 45, - "has_docstring": true, - "docstring": "Main page with form for submitting GitHub repositories.", - "parameters": [ - "request" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function index_get", - "component_id": "codewiki/src/fe/web_app.py::index_get", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/web_app.py::index_post": { - "id": "codewiki/src/fe/web_app.py::index_post", - "name": "index_post", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/web_app.py", - "relative_path": "codewiki/src/fe/web_app.py", - "depends_on": [ - "codewiki/src/fe/routes.py::WebRoutes.index_post" - ], - "source_code": "async def index_post(request: Request, repo_url: str = Form(...), commit_id: str = Form(\"\")):\n \"\"\"Handle repository submission.\"\"\"\n return await web_routes.index_post(request, repo_url, commit_id)", - "start_line": 49, - "end_line": 51, - "has_docstring": true, - "docstring": "Handle repository submission.", - "parameters": [ - "request", - "repo_url", - "commit_id" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function index_post", - "component_id": "codewiki/src/fe/web_app.py::index_post", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/web_app.py::get_job_status": { - "id": "codewiki/src/fe/web_app.py::get_job_status", - "name": "get_job_status", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/web_app.py", - "relative_path": "codewiki/src/fe/web_app.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/fe/routes.py::WebRoutes.get_job_status" - ], - "source_code": "async def get_job_status(job_id: str):\n \"\"\"API endpoint to get job status.\"\"\"\n return await web_routes.get_job_status(job_id)", - "start_line": 55, - "end_line": 57, - "has_docstring": true, - "docstring": "API endpoint to get job status.", - "parameters": [ - "job_id" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function get_job_status", - "component_id": "codewiki/src/fe/web_app.py::get_job_status", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/web_app.py::view_docs": { - "id": "codewiki/src/fe/web_app.py::view_docs", - "name": "view_docs", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/web_app.py", - "relative_path": "codewiki/src/fe/web_app.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/fe/routes.py::WebRoutes.view_docs" - ], - "source_code": "async def view_docs(job_id: str):\n \"\"\"View generated documentation.\"\"\"\n return await web_routes.view_docs(job_id)", - "start_line": 61, - "end_line": 63, - "has_docstring": true, - "docstring": "View generated documentation.", - "parameters": [ - "job_id" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function view_docs", - "component_id": "codewiki/src/fe/web_app.py::view_docs", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/web_app.py::serve_generated_docs": { - "id": "codewiki/src/fe/web_app.py::serve_generated_docs", - "name": "serve_generated_docs", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/web_app.py", - "relative_path": "codewiki/src/fe/web_app.py", - "depends_on": [ - "codewiki/mcp/session.py::SessionStore.get", - "codewiki/src/fe/routes.py::WebRoutes.serve_generated_docs" - ], - "source_code": "async def serve_generated_docs(job_id: str, filename: str = \"overview.md\"):\n \"\"\"Serve generated documentation files.\"\"\"\n if not filename: \n filename = \"overview.md\"\n return await web_routes.serve_generated_docs(job_id, filename)", - "start_line": 68, - "end_line": 72, - "has_docstring": true, - "docstring": "Serve generated documentation files.", - "parameters": [ - "job_id", - "filename" - ], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function serve_generated_docs", - "component_id": "codewiki/src/fe/web_app.py::serve_generated_docs", - "language": null, - "qualified_name": null - }, - "codewiki/src/fe/web_app.py::main": { - "id": "codewiki/src/fe/web_app.py::main", - "name": "main", - "component_type": "function", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/fe/web_app.py", - "relative_path": "codewiki/src/fe/web_app.py", - "depends_on": [ - "codewiki/src/fe/config.py::WebAppConfig.ensure_directories", - "codewiki/src/fe/config.py::WebAppConfig.get_absolute_path", - "codewiki/src/fe/background_worker.py::BackgroundWorker.start", - "codewiki/src/be/documentation_generator.py::DocumentationGenerator.run", - "codewiki/src/fe/background_worker.py::BackgroundWorker.stop" - ], - "source_code": "def main():\n \"\"\"Main function to run the web application.\"\"\"\n import uvicorn\n \n parser = argparse.ArgumentParser(\n description=\"CodeWiki Web Application - Generate documentation for GitHub repositories\"\n )\n parser.add_argument(\n \"--host\",\n type=str,\n default=WebAppConfig.DEFAULT_HOST,\n help=f\"Host to bind the server to (default: {WebAppConfig.DEFAULT_HOST})\"\n )\n parser.add_argument(\n \"--port\",\n type=int,\n default=WebAppConfig.DEFAULT_PORT,\n help=f\"Port to run the server on (default: {WebAppConfig.DEFAULT_PORT})\"\n )\n parser.add_argument(\n \"--debug\",\n action=\"store_true\",\n help=\"Run the server in debug mode\"\n )\n parser.add_argument(\n \"--reload\",\n action=\"store_true\",\n help=\"Enable auto-reload for development\"\n )\n \n args = parser.parse_args()\n \n # Ensure required directories exist\n WebAppConfig.ensure_directories()\n \n # Start background worker\n background_worker.start()\n \n print(f\"πŸš€ CodeWiki Web Application starting...\")\n print(f\"🌐 Server running at: http://{args.host}:{args.port}\")\n print(f\"πŸ“ Cache directory: {WebAppConfig.get_absolute_path(WebAppConfig.CACHE_DIR)}\")\n print(f\"πŸ—‚οΈ Temp directory: {WebAppConfig.get_absolute_path(WebAppConfig.TEMP_DIR)}\")\n print(\"\\nPress Ctrl+C to stop the server\")\n \n try:\n uvicorn.run(\n \"fe.web_app:app\",\n host=args.host,\n port=args.port,\n reload=args.reload,\n log_level=\"debug\" if args.debug else \"info\"\n )\n except KeyboardInterrupt:\n print(\"\\nπŸ‘‹ Server stopped\")\n background_worker.stop()", - "start_line": 75, - "end_line": 129, - "has_docstring": true, - "docstring": "Main function to run the web application.", - "parameters": [], - "node_type": "function", - "base_classes": null, - "class_name": null, - "display_name": "function main", - "component_id": "codewiki/src/fe/web_app.py::main", - "language": null, - "qualified_name": null - }, - "codewiki/src/utils.py::FileManager": { - "id": "codewiki/src/utils.py::FileManager", - "name": "FileManager", - "component_type": "class", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/utils.py", - "relative_path": "codewiki/src/utils.py", - "depends_on": [], - "source_code": "class FileManager:\n \"\"\"Handles file I/O operations.\"\"\"\n \n @staticmethod\n def ensure_directory(path: str) -> None:\n \"\"\"Create directory if it doesn't exist.\"\"\"\n os.makedirs(path, exist_ok=True)\n \n @staticmethod\n def save_json(data: Any, filepath: str) -> None:\n \"\"\"Save data as JSON to file.\"\"\"\n with open(filepath, 'w', encoding='utf-8') as f:\n json.dump(data, f, indent=4, ensure_ascii=False)\n\n @staticmethod\n def load_json(filepath: str) -> Optional[Dict[str, Any]]:\n \"\"\"Load JSON from file, return None if file doesn't exist.\"\"\"\n if not os.path.exists(filepath):\n return None\n\n with open(filepath, 'r', encoding='utf-8') as f:\n return json.load(f)\n\n @staticmethod\n def save_text(content: str, filepath: str) -> None:\n \"\"\"Save text content to file.\"\"\"\n with open(filepath, 'w', encoding='utf-8') as f:\n f.write(content)\n\n @staticmethod\n def load_text(filepath: str) -> str:\n \"\"\"Load text content from file.\"\"\"\n with open(filepath, 'r', encoding='utf-8') as f:\n return f.read()", - "start_line": 10, - "end_line": 43, - "has_docstring": true, - "docstring": "Handles file I/O operations.", - "parameters": null, - "node_type": "class", - "base_classes": null, - "class_name": null, - "display_name": "class FileManager", - "component_id": "codewiki/src/utils.py::FileManager", - "language": null, - "qualified_name": null - }, - "codewiki/src/utils.py::FileManager.ensure_directory": { - "id": "codewiki/src/utils.py::FileManager.ensure_directory", - "name": "FileManager.ensure_directory", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/utils.py", - "relative_path": "codewiki/src/utils.py", - "depends_on": [], - "source_code": " def ensure_directory(path: str) -> None:\n \"\"\"Create directory if it doesn't exist.\"\"\"\n os.makedirs(path, exist_ok=True)", - "start_line": 14, - "end_line": 16, - "has_docstring": true, - "docstring": "Create directory if it doesn't exist.", - "parameters": [ - "path" - ], - "node_type": "method", - "base_classes": null, - "class_name": "FileManager", - "display_name": "method FileManager.ensure_directory", - "component_id": "codewiki/src/utils.py::FileManager.ensure_directory", - "language": null, - "qualified_name": null - }, - "codewiki/src/utils.py::FileManager.save_json": { - "id": "codewiki/src/utils.py::FileManager.save_json", - "name": "FileManager.save_json", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/utils.py", - "relative_path": "codewiki/src/utils.py", - "depends_on": [], - "source_code": " def save_json(data: Any, filepath: str) -> None:\n \"\"\"Save data as JSON to file.\"\"\"\n with open(filepath, 'w', encoding='utf-8') as f:\n json.dump(data, f, indent=4, ensure_ascii=False)", - "start_line": 19, - "end_line": 22, - "has_docstring": true, - "docstring": "Save data as JSON to file.", - "parameters": [ - "data", - "filepath" - ], - "node_type": "method", - "base_classes": null, - "class_name": "FileManager", - "display_name": "method FileManager.save_json", - "component_id": "codewiki/src/utils.py::FileManager.save_json", - "language": null, - "qualified_name": null - }, - "codewiki/src/utils.py::FileManager.load_json": { - "id": "codewiki/src/utils.py::FileManager.load_json", - "name": "FileManager.load_json", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/utils.py", - "relative_path": "codewiki/src/utils.py", - "depends_on": [ - "codewiki/cli/config_manager.py::ConfigManager.load" - ], - "source_code": " def load_json(filepath: str) -> Optional[Dict[str, Any]]:\n \"\"\"Load JSON from file, return None if file doesn't exist.\"\"\"\n if not os.path.exists(filepath):\n return None\n\n with open(filepath, 'r', encoding='utf-8') as f:\n return json.load(f)", - "start_line": 25, - "end_line": 31, - "has_docstring": true, - "docstring": "Load JSON from file, return None if file doesn't exist.", - "parameters": [ - "filepath" - ], - "node_type": "method", - "base_classes": null, - "class_name": "FileManager", - "display_name": "method FileManager.load_json", - "component_id": "codewiki/src/utils.py::FileManager.load_json", - "language": null, - "qualified_name": null - }, - "codewiki/src/utils.py::FileManager.save_text": { - "id": "codewiki/src/utils.py::FileManager.save_text", - "name": "FileManager.save_text", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/utils.py", - "relative_path": "codewiki/src/utils.py", - "depends_on": [], - "source_code": " def save_text(content: str, filepath: str) -> None:\n \"\"\"Save text content to file.\"\"\"\n with open(filepath, 'w', encoding='utf-8') as f:\n f.write(content)", - "start_line": 34, - "end_line": 37, - "has_docstring": true, - "docstring": "Save text content to file.", - "parameters": [ - "content", - "filepath" - ], - "node_type": "method", - "base_classes": null, - "class_name": "FileManager", - "display_name": "method FileManager.save_text", - "component_id": "codewiki/src/utils.py::FileManager.save_text", - "language": null, - "qualified_name": null - }, - "codewiki/src/utils.py::FileManager.load_text": { - "id": "codewiki/src/utils.py::FileManager.load_text", - "name": "FileManager.load_text", - "component_type": "method", - "file_path": "/home/anhnh/CodeWiki-journal/tools/CodeWiki/codewiki/src/utils.py", - "relative_path": "codewiki/src/utils.py", - "depends_on": [], - "source_code": " def load_text(filepath: str) -> str:\n \"\"\"Load text content from file.\"\"\"\n with open(filepath, 'r', encoding='utf-8') as f:\n return f.read()", - "start_line": 40, - "end_line": 43, - "has_docstring": true, - "docstring": "Load text content from file.", - "parameters": [ - "filepath" - ], - "node_type": "method", - "base_classes": null, - "class_name": "FileManager", - "display_name": "method FileManager.load_text", - "component_id": "codewiki/src/utils.py::FileManager.load_text", - "language": null, - "qualified_name": null - } -} \ No newline at end of file diff --git a/guides/README.md b/guides/README.md index c034664b..7c46d526 100644 --- a/guides/README.md +++ b/guides/README.md @@ -4,8 +4,7 @@ # Guides -Hand-written guides for CodeWiki 2.0. The `docs/` folder next to this one is -CodeWiki's own generated documentation and is not edited by hand. +Hand-written guides for CodeWiki 2.0. | Guide | Read it when you want to | | --- | --- | @@ -16,7 +15,7 @@ CodeWiki's own generated documentation and is not edited by hand. | [MCP / IDE-driven mode](mcp-ide-mode.md) | Run CodeWiki as an MCP server inside Cursor, Claude Desktop, Claude Code, or CodeBuddy, with no LLM configuration | | [Backstage TechDocs](backstage-techdocs.md) | Publish the generated docs in Backstage with `--techdocs` or `codewiki techdocs` | | [Development guide](development.md) | Change CodeWiki: project layout, pipeline, adding a language, tests, releasing | -| [Docker setup](docker.md) | Run the web application in a container | +| [Docker setup](docker.md) | Run CLI jobs in a container | Also at the top level: [CHANGELOG](../CHANGELOG.md), [SECURITY](../SECURITY.md), [LICENSE](../LICENSE). diff --git a/guides/development.md b/guides/development.md index 73a1bcd5..5b8f30c3 100644 --- a/guides/development.md +++ b/guides/development.md @@ -37,29 +37,26 @@ codewiki/ β”‚ └── tools/ # analysis, code_reader, doc_writer, module_tree, prompt_server β”œβ”€β”€ src/ β”‚ β”œβ”€β”€ config.py # backend Config -β”‚ β”œβ”€β”€ be/ # generation pipeline -β”‚ β”‚ β”œβ”€β”€ dependency_analyzer/ -β”‚ β”‚ β”‚ β”œβ”€β”€ analyzers/ # one tree-sitter analyzer per language + artifact.py -β”‚ β”‚ β”‚ β”œβ”€β”€ analysis/ # repo walk, call-graph analysis, analysis service -β”‚ β”‚ β”‚ β”œβ”€β”€ models/ # Node, CallRelationship, ... -β”‚ β”‚ β”‚ β”œβ”€β”€ utils/ # patterns.py (extensions, ignore lists), external_symbols.py -β”‚ β”‚ β”‚ β”œβ”€β”€ ast_parser.py, dependency_graphs_builder.py -β”‚ β”‚ β”‚ β”œβ”€β”€ leaf_selection.py, topo_sort.py -β”‚ β”‚ β”œβ”€β”€ cluster_modules.py # hierarchical clustering, super-grouping, guaranteed artifact module -β”‚ β”‚ β”œβ”€β”€ documentation_generator.py # bottom-up page generation, overview, metadata -β”‚ β”‚ β”œβ”€β”€ updater/ # component-level incremental updater (2.0) -β”‚ β”‚ β”œβ”€β”€ agent_tools/ # read_code_components, str_replace_editor, sub-module delegation -β”‚ β”‚ β”œβ”€β”€ backend.py # LLMBackend abstraction + factory -β”‚ β”‚ β”œβ”€β”€ pydantic_ai_backend.py # API-key providers -β”‚ β”‚ β”œβ”€β”€ google_provider.py # google / google-vertex (Gemini API, Vertex AI) -β”‚ β”‚ β”œβ”€β”€ caw_backend.py, caw_toolkit.py # claude-code / codex subscription providers -β”‚ β”‚ β”œβ”€β”€ prompt_template.py, llm_services.py, module_naming.py -β”‚ └── fe/ # FastAPI web app (used by the Docker image) -β”œβ”€β”€ templates/ # HTML templates for the viewer and web app -└── run_web_app.py -docker/ # Dockerfile, docker-compose.yml, env.example +β”‚ └── be/ # generation pipeline +β”‚ β”œβ”€β”€ dependency_analyzer/ +β”‚ β”‚ β”œβ”€β”€ analyzers/ # one tree-sitter analyzer per language + artifact.py +β”‚ β”‚ β”œβ”€β”€ analysis/ # repo walk, call-graph analysis, analysis service +β”‚ β”‚ β”œβ”€β”€ models/ # Node, CallRelationship, ... +β”‚ β”‚ β”œβ”€β”€ utils/ # patterns.py (extensions, ignore lists), external_symbols.py +β”‚ β”‚ β”œβ”€β”€ ast_parser.py, dependency_graphs_builder.py +β”‚ β”‚ β”œβ”€β”€ leaf_selection.py, topo_sort.py +β”‚ β”œβ”€β”€ cluster_modules.py # hierarchical clustering, super-grouping, guaranteed artifact module +β”‚ β”œβ”€β”€ documentation_generator.py # bottom-up page generation, overview, metadata +β”‚ β”œβ”€β”€ updater/ # component-level incremental updater (2.0) +β”‚ β”œβ”€β”€ agent_tools/ # read_code_components, str_replace_editor, sub-module delegation +β”‚ β”œβ”€β”€ backend.py # LLMBackend abstraction + factory +β”‚ β”œβ”€β”€ pydantic_ai_backend.py # API-key providers +β”‚ β”œβ”€β”€ google_provider.py # google / google-vertex (Gemini API, Vertex AI) +β”‚ β”œβ”€β”€ caw_backend.py, caw_toolkit.py # claude-code / codex subscription providers +β”‚ β”œβ”€β”€ prompt_template.py, llm_services.py, module_naming.py +└── templates/ # static GitHub Pages viewer and assets +docker/ # CLI image, Compose jobs, env.example guides/ # these guides -docs/ # CodeWiki's own generated documentation (do not hand-edit) skills/ # Claude skill for MCP-driven generation tests/ ``` diff --git a/guides/docker.md b/guides/docker.md index 355bb502..6eac3606 100644 --- a/guides/docker.md +++ b/guides/docker.md @@ -1,435 +1,113 @@ -# Docker setup (web app) +# Run the CLI with Docker -This guide explains how to run the **CodeWiki web application** with Docker -and Docker Compose. The web app takes a GitHub URL and generates -documentation through a browser. It is not needed for the CLI or the MCP -server, which you install with `pip` (see the [README](../README.md)). +The Docker image runs CodeWiki CLI commands against a mounted Git repository. +The hosted web application and HTTP documentation server have been removed. +Generate documentation with the CLI, then publish its static HTML viewer with +GitHub Pages or export it to Backstage TechDocs. -## File Structure +## Build -All Docker-related files are located in the `docker/` directory: - -``` -docker/ -β”œβ”€β”€ Dockerfile # Container image definition -β”œβ”€β”€ docker-compose.yml # Service orchestration -└── env.example # Environment variables template -``` - -The Dockerfile builds from the project root context to include all necessary application code. - ---- - -## Quick Start - -### 1. Clone the Repository - -```bash -git clone https://github.com/FSoft-AI4Code/CodeWiki.git -cd CodeWiki -``` - -### 2. Set Up Environment Variables - -```bash -# Copy the example environment file -cp docker/env.example .env - -# Edit .env file with your configuration -nano .env # or use your preferred editor -``` - -Required configuration in `.env`: +From the CodeWiki checkout: ```bash -# LLM API Configuration -MAIN_MODEL=claude-sonnet-4 -FALLBACK_MODEL_1=glm-4p5 -CLUSTER_MODEL=claude-sonnet-4 -LLM_BASE_URL=https://api.anthropic.com # or your LiteLLM proxy -LLM_API_KEY=your-api-key-here - -# Application Port -APP_PORT=8000 - -# Optional: Logfire Configuration (for monitoring) -LOGFIRE_TOKEN= -LOGFIRE_PROJECT_NAME=codewiki -LOGFIRE_SERVICE_NAME=codewiki +docker compose -f docker/docker-compose.yml build +docker compose -f docker/docker-compose.yml run --rm codewiki ``` -### 3. Create Docker Network +The second command prints CLI help. The image includes Python 3.12, Git, +Node.js/npm for dependency installation, the CodeWiki package, and predownloaded +tree-sitter grammars. Its entry point is `python -m codewiki`; arguments passed +to the container are CodeWiki arguments. -```bash -docker network create codewiki-network -``` +## Mount the target repository -### 4. Start the Services +Copy the example and set `CODEWIKI_REPO` to the absolute path of the Git +repository you want to document: -**Option A: From project root** ```bash -docker-compose -f docker/docker-compose.yml up -d -``` - -### 5. Access the Application - -- Web Application: http://localhost:8000 - -The application will be available at the port specified in your `.env` file (default: 8000). - ---- - -## Docker Compose Configuration - -The `docker-compose.yml` file defines the CodeWiki service with the following features: - -### Service Configuration - -- **Image**: `codewiki:0.0.1` -- **Build Context**: Parent directory (`.` relative to docker/) -- **Container Name**: `codewiki` -- **Port Mapping**: `${APP_PORT:-8000}:8000` -- **Network**: `codewiki-network` (external) - -### Environment Variables - -The container uses environment variables from the `.env` file: -- `PYTHONPATH=/app/src` - Set Python module path -- `PYTHONUNBUFFERED=1` - Enable real-time logging -- All variables from `.env` file - -### Volume Mounts - -The following directories are mounted as volumes: - -```yaml -volumes: - - ./output:/app/output # Persistent storage for generated docs - - ~/.ssh:/root/.ssh:ro # SSH keys for private repos (read-only) -``` - -**Note**: Git credentials can be mounted if needed for private repositories: -```yaml - # Uncomment in docker-compose.yml if needed - - ~/.gitconfig:/root/.gitconfig:ro -``` - -### Health Check - -The service includes a health check that: -- Runs every 30 seconds -- Times out after 10 seconds -- Retries 3 times on failure -- Starts checking after 20 seconds - -### Restart Policy - -The container is set to restart automatically unless explicitly stopped (`restart: unless-stopped`). - ---- - -## Dockerfile Details - -The Dockerfile (`docker/Dockerfile`) builds the CodeWiki image with: - -### Base Image -- Python 3.12 slim image for smaller size - -### System Dependencies -- `git` - For repository cloning -- `curl` - For health checks -- `nodejs` and `npm` - For mermaid diagram validation - -### Application Setup -1. Copies `requirements.txt` first (for better caching) -2. Installs Python dependencies -3. Copies entire application code -4. Creates output directories: - - `output/cache` - - `output/temp` - - `output/docs` - - `output/dependency_graphs` - -### Runtime Configuration -- **Working Directory**: `/app` -- **Exposed Port**: `8000` -- **Entry Point**: `python codewiki/run_web_app.py --host 0.0.0.0 --port 8000` - ---- - -## Common Operations - -### View Logs - -```bash -# From project root -docker-compose -f docker/docker-compose.yml logs -f - -# From docker directory -cd docker -docker-compose logs -f - -# View specific service -docker logs codewiki -f -``` - -### Stop Services - -```bash -# From project root -docker-compose -f docker/docker-compose.yml stop - -# From docker directory -cd docker -docker-compose stop -``` - -### Stop and Remove Containers - -```bash -# From project root -docker-compose -f docker/docker-compose.yml down - -# From docker directory -cd docker -docker-compose down - -# Remove volumes as well -docker-compose down -v -``` - -### Rebuild Image - -If you've made changes to the code or Dockerfile: - -```bash -# From project root -docker-compose -f docker/docker-compose.yml build --no-cache - -# From docker directory -cd docker -docker-compose build --no-cache - -# Rebuild and restart -docker-compose up -d --build -``` - -### Access Container Shell - -```bash -docker exec -it codewiki /bin/bash -``` - ---- - -## Persistent Storage - -### Output Directory - -The `output/` directory is mounted as a volume, ensuring generated documentation persists across container restarts: - -``` -output/ -β”œβ”€β”€ cache/ # Cached dependency graphs and jobs -β”œβ”€β”€ docs/ # Generated documentation -β”œβ”€β”€ dependency_graphs/ # JSON dependency graphs -└── temp/ # Temporary files -``` - -### SSH Keys - -If you need to clone private repositories, ensure your SSH keys are available: - -```bash -# Verify SSH keys are accessible -ls -la ~/.ssh/ - -# The docker-compose.yml mounts ~/.ssh as read-only +cp docker/env.example .env +# Edit CODEWIKI_REPO in .env, for example: +# CODEWIKI_REPO=/home/me/projects/my-project ``` ---- +Without an override, Compose mounts the CodeWiki checkout itself. The target +is mounted read/write at `/workspace`, which is the container's working +directory. Generated `docs/` and other output therefore appear directly in +the target repository on your host. -## Troubleshooting +Compose uses `.env` for path interpolation. It does not inject the old web +app's `LLM_*` settings into CLI configuration. -### Port Already in Use +## Configure a provider -If port 8000 is already in use: +Configure an API-backed provider once, using the same CLI options as a local +installation. Substitute your endpoint, API key, and model names: ```bash -# Change APP_PORT in .env file -echo "APP_PORT=8001" >> .env - -# Restart services -docker-compose -f docker/docker-compose.yml down -docker-compose -f docker/docker-compose.yml up -d -``` - -### Container Won't Start - -Check logs for errors: - -```bash -docker logs codewiki +docker compose -f docker/docker-compose.yml run --rm codewiki config set \ + --provider openai-compatible \ + --base-url https://api.example.com/v1 \ + --api-key YOUR_API_KEY \ + --main-model YOUR_MODEL \ + --cluster-model YOUR_MODEL ``` -Common issues: -- **Invalid API key**: Verify `LLM_API_KEY` in `.env` -- **Network not found**: Create network with `docker network create codewiki-network` -- **Port conflict**: Change `APP_PORT` in `.env` - -### Health Check Failing - -```bash -# Check if the application is responding -curl http://localhost:8000/ - -# Check container health status -docker inspect codewiki --format='{{.State.Health.Status}}' +Settings persist in the Compose `codewiki-config` volume, mounted at +`/root/.codewiki`. `CODEWIKI_NO_KEYRING=1` selects file-based credential storage +inside that volume. Treat it as private and do not commit credentials. +See [Providers and models](providers.md) for other API providers. -# View health check logs -docker inspect codewiki --format='{{range .State.Health.Log}}{{.Output}}{{end}}' -``` +Claude Code and Codex executables and their subscription authentication are +not bundled in this image. Use a local installation for subscription mode, +or extend the image and provide the corresponding CLI authentication. -### Permission Issues with Volumes - -If you encounter permission issues with mounted volumes: +## Generate documentation ```bash -# On Linux, ensure proper ownership -sudo chown -R $(id -u):$(id -g) output/ - -# Or run container with user mapping -docker-compose -f docker/docker-compose.yml down -# Add to docker-compose.yml under 'codewiki' service: -# user: "${UID}:${GID}" +docker compose -f docker/docker-compose.yml run --rm codewiki generate +docker compose -f docker/docker-compose.yml run --rm codewiki generate --github-pages +docker compose -f docker/docker-compose.yml run --rm codewiki generate --update +docker compose -f docker/docker-compose.yml run --rm codewiki generate --techdocs ``` -### Private Repository Access - -For private repositories: - -1. Ensure SSH keys are properly mounted: - ```yaml - volumes: - - ~/.ssh:/root/.ssh:ro - ``` - -2. Verify key permissions: - ```bash - chmod 600 ~/.ssh/id_rsa - chmod 644 ~/.ssh/id_rsa.pub - ``` - -3. Add GitHub to known_hosts: - ```bash - docker exec -it codewiki ssh-keyscan github.com >> /root/.ssh/known_hosts - ``` - ---- - -## Production Deployment - -### Security Considerations - -1. **Environment Variables**: Never commit `.env` file to version control -2. **API Keys**: Use secrets management in production -3. **Network**: Use isolated Docker networks -4. **Volumes**: Set appropriate permissions on mounted volumes -5. **Updates**: Regularly update base image and dependencies - -### Recommended Production Setup - -```yaml -# Use secrets instead of .env file -services: - codewiki: - secrets: - - llm_api_key - environment: - - LLM_API_KEY_FILE=/run/secrets/llm_api_key - -secrets: - llm_api_key: - external: true -``` +Commands exit when the job finishes. There is no listening HTTP port, health +check, daemon restart policy, or external Docker network to create. For private +repositories, mount a local checkout; Git credentials and SSH keys are not +mounted by default. -### Resource Limits - -Add resource limits in production: - -```yaml -services: - codewiki: - deploy: - resources: - limits: - cpus: '2' - memory: 4G - reservations: - cpus: '1' - memory: 2G -``` - -### Reverse Proxy - -Use nginx or traefik as a reverse proxy: - -```yaml -services: - nginx: - image: nginx:alpine - ports: - - "80:80" - - "443:443" - volumes: - - ./nginx.conf:/etc/nginx/nginx.conf:ro - - ./certs:/etc/nginx/certs:ro -``` - ---- - -## Integration with External Services - -### Using LiteLLM Proxy - -If using a LiteLLM proxy for LLM API management: +The equivalent direct Docker workflow is: ```bash -# In .env file -LLM_BASE_URL=http://litellm:4000/ -LLM_API_KEY=sk-your-proxy-key - -# Add LiteLLM service to docker-compose.yml -services: - litellm: - image: ghcr.io/berriai/litellm:latest - ports: - - "4000:4000" - environment: - - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY} - - OPENAI_API_KEY=${OPENAI_API_KEY} - networks: - - codewiki-network +docker build -f docker/Dockerfile -t codewiki:local . +docker run --rm codewiki:local --version +docker run --rm \ + --mount type=bind,src=/absolute/path/to/project,dst=/workspace \ + --mount type=volume,src=codewiki-cli-config,dst=/root/.codewiki \ + codewiki:local config set --provider openai-compatible \ + --base-url https://api.example.com/v1 --api-key YOUR_API_KEY \ + --main-model YOUR_MODEL --cluster-model YOUR_MODEL +docker run --rm \ + --mount type=bind,src=/absolute/path/to/project,dst=/workspace \ + --mount type=volume,src=codewiki-cli-config,dst=/root/.codewiki \ + codewiki:local generate --github-pages ``` ---- - -## More Information - -- [README](../README.md): features and quick start -- [CLI reference](cli-reference.md): command-line generation without Docker -- [MCP / IDE-driven mode](mcp-ide-mode.md): run inside an AI IDE - ---- - -## Support +Direct Docker uses a separate configuration volume in this example. Reuse +the same volume across configuration and generation commands. -For issues related to Docker deployment: -1. Check logs: `docker logs codewiki` -2. Verify configuration: `docker exec codewiki env | grep -E '(LLM|APP)'` -3. Test connectivity: `docker exec codewiki curl -I http://localhost:8000` -4. Report issues: https://github.com/FSoft-AI4Code/CodeWiki/issues +## Updating and troubleshooting ---- +- Rebuild the image after updating CodeWiki: `docker compose -f docker/docker-compose.yml build`. +- A configuration error usually means the provider has not been configured in + the container's volume. Host keychain credentials are not available there. +- If output is not writable, check ownership of the mounted repository. + Linux containers run as root by default, so generated files may need their + ownership adjusted on the host. +- Stop any old web-app containers before switching to this workflow. The + former browser submission queue and cache are not migrated into CLI state; + keep any documentation you want from the old output mount. +- `docker compose -f docker/docker-compose.yml down` preserves configuration. + Adding `--volumes` deletes the saved settings and credentials. -**Happy documenting with Docker! πŸ³πŸ“š** +See the [CLI reference](cli-reference.md), [MCP guide](mcp-ide-mode.md), and +[Backstage TechDocs guide](backstage-techdocs.md) for supported workflows. diff --git a/index.html b/index.html index 1c7bc0f3..8f2a98d6 100644 --- a/index.html +++ b/index.html @@ -837,7 +837,7 @@
  • Results
  • Demo
  • Installation
  • -
  • Repo Docs
  • +
  • Guides
  • Citation
  • @@ -864,7 +864,7 @@

    Turn source code into a living technical wiki.

    Read the paper

    - CodeWiki documents itself. Browse this repository’s generated wiki β†’ + Read the guides for installation, providers, and workflows β†’

    -
    -
    πŸ“š
    -

    This Repo's Docs

    -

    Documentation for the CodeWiki repository itself β€” generated by CodeWiki

    - - Browse Docs - -
    -
    πŸ“˜

    Guides

    @@ -1327,7 +1318,7 @@

    Changelog

    🐳

    Docker Deployment

    -

    Run the web application in a container

    +

    Run CLI documentation jobs in a container

    Docker Guide @@ -1352,7 +1343,6 @@

    Development Guide

    GitHub Paper Demo - Repo Docs Benchmark

    diff --git a/pyproject.toml b/pyproject.toml index c586911d..72e1452f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -58,7 +58,6 @@ dependencies = [ "PyYAML>=6.0.2", "mermaid-parser-py>=0.0.2", "mermaid-py>=0.8.0", - "fastapi>=0.140.0", "starlette>=1.3.1", "uvicorn>=0.35.0", "python-multipart>=0.0.31", @@ -107,7 +106,7 @@ codewiki = "codewiki.cli.main:cli" [project.urls] Homepage = "https://github.com/FSoft-AI4Code/CodeWiki" -Documentation = "https://fsoft-ai4code.github.io/CodeWiki/docs/index.html" +Documentation = "https://github.com/FSoft-AI4Code/CodeWiki/blob/main/guides/README.md" Repository = "https://github.com/FSoft-AI4Code/CodeWiki" Issues = "https://github.com/FSoft-AI4Code/CodeWiki/issues" @@ -128,7 +127,6 @@ packages = [ "codewiki.src.be.dependency_analyzer.models", "codewiki.src.be.dependency_analyzer.utils", "codewiki.src.be.updater", - "codewiki.src.fe", "codewiki.mcp", "codewiki.mcp.tools" ] diff --git a/requirements.txt b/requirements.txt index ef1503a3..4e3667dd 100644 --- a/requirements.txt +++ b/requirements.txt @@ -29,7 +29,6 @@ decorator==5.2.1 distro==1.9.0 eval_type_backport==0.2.2 executing==2.2.0 -fastapi==0.140.0 fastavro==1.12.0 fastuuid==0.14.0 filelock==4.2.1