Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix: repo-local DB by default, security pin, and misc bug fixes (#32)
Swati Ahuja0d85dc213127
diff --git a/.gitignore b/.gitignoreindex 7bcdd87f2..bb1789512 100644--- a/.gitignore+++ b/.gitignore@@ -1,14 +1,3 @@-# Hosted backend (private, not part of the open-source project)-backend/-hosted_backend_plan/-migrations/--# Outreach / marketing data-repowise_outreach_targets.csv--# IDE/tool caches-.sfdx/-# Python__pycache__/*.py[cod]@@ -21,8 +10,6 @@ dist/downloads/eggs/.eggs/-.claude/-# Python build dirs (only at root, not packages/web/src/lib/)/lib//lib64/parts/@@ -72,15 +59,12 @@ dmypy.json*.swp*.swo*~-.DS_Store-Thumbs.db# Node / Next.jsnode_modules/.next/.nuxt/out/-dist/.npm.eslintcache.parcel-cache@@ -122,51 +106,8 @@ docker-compose.override.yml._*.Spotlight-V100.Trashes+Thumbs.dbehthumbs.db-# repowise API keys (local)-.repowise/.env--# Google service account keys-awesome-gist-*.json--# Local dev scripts and notes-CLAUDE.md-BUILD_STATUS.md-TESTING_GUIDE.md-PLAN.md-run_ingest.py-run_test.ps1-smoke_test.py-provider_config.json-.mcp.json-frontend/-integrations/-providers/--# Private release notes-docs/PYPI_RELEASE.md--# Frontend (separate repo, not part of OSS)-frontend/--# Embedded repos-fastapi/-repowise-hosted-frontend/--# Local dev artifacts-.mcp.json-!plugins/**/.mcp.json-BUILD_STATUS.md-PLAN.md-TESTING_GUIDE.md-provider_config.json-run_ingest.py-run_test.ps1-smoke_test.py-integrations/-providers/-demo_init.py-fastapi/-openclaw/-repowise.zip+# Claude Code+.claude/diff --git a/packages/cli/src/repowise/cli/commands/init_cmd.py b/packages/cli/src/repowise/cli/commands/init_cmd.pyindex c8d165901..96efa6cb8 100644--- a/packages/cli/src/repowise/cli/commands/init_cmd.py+++ b/packages/cli/src/repowise/cli/commands/init_cmd.py@@ -27,7 +27,6 @@ from repowise.cli.helpers import (save_state,)-# ---------------------------------------------------------------------------# Helpers (kept in this file; _resolve_embedder also imported by other cmds)# ---------------------------------------------------------------------------diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd.py b/packages/cli/src/repowise/cli/commands/serve_cmd.pyindex 1209065c3..662491025 100644--- a/packages/cli/src/repowise/cli/commands/serve_cmd.py+++ b/packages/cli/src/repowise/cli/commands/serve_cmd.py@@ -317,13 +317,14 @@ def serve_command(port: int, host: str, workers: int, ui_port: int, no_ui: bool)_setup_embedder()- # Auto-detect local .repowise/wiki.db if REPOWISE_DB_URL is not set.+ # Auto-detect local .repowise/ directory if REPOWISE_DB_URL is not set.# repowise init writes to <repo>/.repowise/wiki.db, so honour it when# the user runs `repowise serve` from the same directory.if not os.environ.get("REPOWISE_DB_URL"):- local_db = Path.cwd() / ".repowise" / "wiki.db"- if local_db.exists():- os.environ["REPOWISE_DB_URL"] = f"sqlite+aiosqlite:///{local_db}"+ local_repowise = Path.cwd() / ".repowise"+ if local_repowise.exists():+ local_db = local_repowise / "wiki.db"+ os.environ["REPOWISE_DB_URL"] = f"sqlite+aiosqlite:///{local_db.as_posix()}"console.print(f"[dim]Using local database: {local_db}[/dim]")frontend_proc: subprocess.Popen | None = Nonediff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.pyindex b72bf8075..68518c31f 100644--- a/packages/cli/src/repowise/cli/helpers.py+++ b/packages/cli/src/repowise/cli/helpers.py@@ -19,7 +19,6 @@ console = Console()err_console = Console(stderr=True)STATE_FILENAME = "state.json"-DB_FILENAME = "wiki.db"REPOWISE_DIR = ".repowise"@@ -69,16 +68,12 @@ def ensure_repowise_dir(repo_path: Path) -> Path:def get_db_url_for_repo(repo_path: Path) -> str:"""Return a database URL for this repo.- If ``REPOWISE_DB_URL`` is set in the environment that URL is used.- Otherwise defaults to the global ``~/.repowise/wiki.db`` so all repos- are visible in one ``repowise serve`` regardless of working directory.+ Prefers ``REPOWISE_DB_URL``, then the legacy ``REPOWISE_DATABASE_URL``.+ Otherwise defaults to the repo-local ``<repo>/.repowise/wiki.db``."""- env_url = os.environ.get("REPOWISE_DB_URL")- if env_url:- return env_url- db_path = Path.home() / REPOWISE_DIR / DB_FILENAME- db_path.parent.mkdir(parents=True, exist_ok=True)- return f"sqlite+aiosqlite:///{db_path}"+ from repowise.core.persistence.database import resolve_db_url++ return resolve_db_url(repo_path)async def _ensure_db_async(repo_path: Path) -> tuple[Any, Any]:@@ -220,8 +215,6 @@ def resolve_provider(3. ``.repowise/config.yaml`` (written by ``repowise init``)4. Auto-detect from API key env vars"""- import os-from repowise.core.providers import get_providerif provider_name is None:@@ -311,8 +304,6 @@ def validate_provider_config(provider_name: str | None = None) -> list[str]:List of warning messages for missing or invalid configuration.Empty list means all required config is present."""- import os-warnings = []def _is_env_var_set(var_name: str) -> bool:diff --git a/packages/core/src/repowise/core/persistence/__init__.py b/packages/core/src/repowise/core/persistence/__init__.pyindex c73538cfe..790afc80e 100644--- a/packages/core/src/repowise/core/persistence/__init__.py+++ b/packages/core/src/repowise/core/persistence/__init__.py@@ -68,9 +68,12 @@ from .database import (async_sessionmaker,create_engine,create_session_factory,+ get_configured_db_url,get_db_url,+ get_repo_db_path,get_session,init_db,+ resolve_db_url,)from .models import (Base,@@ -143,6 +146,7 @@ __all__ = ["delete_decision",# git metadata crud"get_all_git_metadata",+ "get_configured_db_url","get_conversation","get_db_url",# dead code crud@@ -155,6 +159,7 @@ __all__ = ["get_git_metadata_bulk","get_page","get_page_versions",+ "get_repo_db_path","get_repository","get_repository_by_path","get_session",@@ -167,6 +172,7 @@ __all__ = ["list_pages","mark_webhook_processed","recompute_decision_staleness",+ "resolve_db_url","save_dead_code_findings","store_webhook_event","touch_conversation",diff --git a/packages/core/src/repowise/core/persistence/database.py b/packages/core/src/repowise/core/persistence/database.pyindex ce61de687..c29cd50b4 100644--- a/packages/core/src/repowise/core/persistence/database.py+++ b/packages/core/src/repowise/core/persistence/database.py@@ -11,8 +11,10 @@ Call init_db() once at startup to create all tables and the FTS index.from __future__ import annotations+import osfrom collections.abc import AsyncGeneratorfrom contextlib import asynccontextmanager+from pathlib import Pathfrom sqlalchemy.ext.asyncio import (AsyncEngine,@@ -31,19 +33,35 @@ __all__ = ["async_sessionmaker","create_engine","create_session_factory",+ "get_configured_db_url","get_db_url",+ "get_repo_db_path","get_session","init_db",+ "resolve_db_url",]+DB_FILENAME = "wiki.db"+REPOWISE_DIRNAME = ".repowise"+DB_ENV_VARS = ("REPOWISE_DB_URL", "REPOWISE_DATABASE_URL")-def _default_db_url() -> str:- """Global SQLite DB at ~/.repowise/wiki.db — shared across all repos."""- from pathlib import Path- db_path = Path.home() / ".repowise" / "wiki.db"+def get_repo_db_path(repo_path: str | Path) -> Path:+ """Return the repo-local database path ``<repo>/.repowise/wiki.db``."""+ return Path(repo_path).resolve() / REPOWISE_DIRNAME / DB_FILENAME+++def _default_db_url(repo_path: str | Path | None = None) -> str:+ """Return the default SQLite URL for a repo-local or global wiki database.++ Always creates the parent directory to prevent sqlite crashes.+ """+ if repo_path is not None:+ db_path = get_repo_db_path(repo_path)+ else:+ db_path = Path.home() / REPOWISE_DIRNAME / DB_FILENAMEdb_path.parent.mkdir(parents=True, exist_ok=True)- return f"sqlite+aiosqlite:///{db_path}"+ return f"sqlite+aiosqlite:///{db_path.as_posix()}"def get_db_url(raw_url: str | None = None) -> str:@@ -69,6 +87,30 @@ def get_db_url(raw_url: str | None = None) -> str:return url+def get_configured_db_url() -> str | None:+ """Return the configured DB URL from supported env vars, if present."""+ for env_name in DB_ENV_VARS:+ env_url = os.environ.get(env_name)+ if env_url:+ return get_db_url(env_url)+ return None+++def resolve_db_url(repo_path: str | Path | None = None) -> str:+ """Resolve the active DB URL from env vars or the default filesystem path.++ Resolution order:+ 1. ``REPOWISE_DB_URL``+ 2. ``REPOWISE_DATABASE_URL`` (legacy compatibility)+ 3. ``<repo>/.repowise/wiki.db`` when *repo_path* is provided+ 4. ``~/.repowise/wiki.db`` otherwise+ """+ configured = get_configured_db_url()+ if configured is not None:+ return configured+ return _default_db_url(repo_path)++def create_engine(url: str | None = None,*,diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.pyindex 4618fcab9..420599a56 100644--- a/packages/core/src/repowise/core/pipeline/orchestrator.py+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py@@ -14,8 +14,6 @@ Callers:from __future__ import annotations-import asyncio-import loggingimport timefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom dataclasses import dataclass, field@@ -115,7 +113,7 @@ async def run_pipeline(repo_path:Path to an already-cloned repository on disk.commit_depth:- Maximum commits to analyse per file (1–5000). Default 500.+ Maximum commits to analyse per file (1-5000). Default 500.follow_renames:Use ``git log --follow`` to track files across renames.skip_tests:diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.pyindex 3f79e7918..44cd2c8d2 100644--- a/packages/server/src/repowise/server/app.py+++ b/packages/server/src/repowise/server/app.py@@ -12,14 +12,15 @@ import osfrom collections.abc import AsyncGeneratorfrom contextlib import asynccontextmanager-from fastapi import FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse+from fastapi import FastAPI, Requestfrom repowise.core.persistence.database import (create_engine,create_session_factory,init_db,+ resolve_db_url,)from repowise.core.persistence.search import FullTextSearchfrom repowise.core.persistence.vector_store import InMemoryVectorStore@@ -75,7 +76,7 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:Shutdown: dispose engine, stop scheduler, close vector store."""# Database- db_url = os.environ.get("REPOWISE_DB_URL")+ db_url = resolve_db_url()engine = create_engine(db_url)await init_db(engine)session_factory = create_session_factory(engine)diff --git a/packages/server/src/repowise/server/deps.py b/packages/server/src/repowise/server/deps.pyindex 9e0025018..62e1acd27 100644--- a/packages/server/src/repowise/server/deps.py+++ b/packages/server/src/repowise/server/deps.py@@ -12,10 +12,10 @@ from __future__ import annotationsimport osfrom collections.abc import AsyncGenerator-from fastapi import HTTPException, Request, Securityfrom fastapi.security import APIKeyHeaderfrom sqlalchemy.ext.asyncio import AsyncSession+from fastapi import HTTPException, Request, Securityfrom repowise.core.persistence.database import get_session_API_KEY = os.environ.get("REPOWISE_API_KEY")diff --git a/packages/server/src/repowise/server/mcp_server/_server.py b/packages/server/src/repowise/server/mcp_server/_server.pyindex 793240d8d..6fba31c0a 100644--- a/packages/server/src/repowise/server/mcp_server/_server.py+++ b/packages/server/src/repowise/server/mcp_server/_server.py@@ -11,12 +11,19 @@ from typing import Anyfrom mcp.server.fastmcp import FastMCPfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine-from repowise.core.persistence.database import init_db+from repowise.core.persistence.database import (+ get_configured_db_url,+ get_repo_db_path,+ init_db,+ resolve_db_url,+)from repowise.core.persistence.search import FullTextSearchfrom repowise.core.persistence.vector_store import InMemoryVectorStorefrom repowise.core.providers.embedding.base import MockEmbedderfrom repowise.server.mcp_server import _state+_log = __import__("logging").getLogger("repowise.mcp")+def _resolve_embedder():"""Resolve embedder from REPOWISE_EMBEDDER env var or .repowise/config.yaml."""@@ -27,12 +34,12 @@ def _resolve_embedder():cfg_path = Path(_state._repo_path) / ".repowise" / "config.yaml"if cfg_path.exists():- import yaml+ import yaml # type: ignore[import-untyped]cfg = yaml.safe_load(cfg_path.read_text(encoding="utf-8")) or {}name = (cfg.get("embedder") or "").lower()except Exception:- pass+ _log.debug("Failed to read embedder from config.yaml", exc_info=True)if name == "gemini":try:from repowise.core.providers.embedding.gemini import GeminiEmbedder@@ -40,7 +47,7 @@ def _resolve_embedder():dims = int(os.environ.get("REPOWISE_EMBEDDING_DIMS", "768"))return GeminiEmbedder(output_dimensionality=dims)except Exception:- pass+ _log.warning("Failed to initialise Gemini embedder — falling back to mock", exc_info=True)if name == "openai":try:from repowise.core.providers.embedding.openai import OpenAIEmbedder@@ -48,7 +55,7 @@ def _resolve_embedder():model = os.environ.get("REPOWISE_EMBEDDING_MODEL", "text-embedding-3-small")return OpenAIEmbedder(model=model)except Exception:- pass+ _log.warning("Failed to initialise OpenAI embedder — falling back to mock", exc_info=True)return MockEmbedder()@@ -71,9 +78,7 @@ async def _load_vector_stores(repo_path: str | None) -> None:self._db is not None and skip the blocking import entirely."""import asyncio as _asyncio- import logging as _logging- _log = _logging.getLogger("repowise.mcp")try:embedder = _resolve_embedder()vector_store: Any = InMemoryVectorStore(embedder=embedder)@@ -123,31 +128,25 @@ async def _lifespan(server: FastMCP):the server starts accepting tool calls immediately. search_codebase awaits_state._vector_store_ready before querying the vector store."""- import logging as _logging+ configured_db_url = get_configured_db_url()- _log = _logging.getLogger("repowise.mcp")-- db_url = os.environ.get("REPOWISE_DATABASE_URL", "sqlite+aiosqlite:///repowise.db")-- # If a repo path was configured, try .repowise/wiki.db- if _state._repo_path:- from pathlib import Path-- repowise_dir = Path(_state._repo_path) / ".repowise"+ # When repo path is set and no env override, prefer repo-local DB.+ if _state._repo_path and configured_db_url is None:+ db_path = get_repo_db_path(_state._repo_path)+ repowise_dir = db_path.parentif not repowise_dir.exists():_log.warning("No .repowise directory at %s — run 'repowise init' first",_state._repo_path,)- elif not (repowise_dir / "wiki.db").exists():+ repowise_dir.mkdir(parents=True, exist_ok=True)+ elif not db_path.exists():_log.warning("No wiki.db in %s — run 'repowise init' to generate the wiki",repowise_dir,)- if repowise_dir.exists():- db_path = repowise_dir / "wiki.db"- if db_path.exists():- db_url = f"sqlite+aiosqlite:///{db_path.as_posix()}"++ db_url = resolve_db_url(_state._repo_path)connect_args: dict = {}if db_url.startswith("sqlite"):diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.pyindex 2686e9f40..3932734ac 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py@@ -4,8 +4,8 @@ from __future__ import annotationsimport contextlibimport json-import osimport re+from pathlib import Pathfrom typing import Anyfrom sqlalchemy import select@@ -431,7 +431,7 @@ async def _git_archaeology_fallback(# --- Layer 3: Live git log (when local repo exists) ---git_log_results = []local_path = getattr(repository, "local_path", None)- if local_path and os.path.isdir(os.path.join(local_path, ".git")):+ if local_path and (Path(local_path) / ".git").is_dir():git_log_results = await _run_git_log(local_path, file_path, stem)result["git_log"] = git_log_resultsdiff --git a/packages/server/src/repowise/server/routers/chat.py b/packages/server/src/repowise/server/routers/chat.pyindex 0344bdbe5..5e1ee757b 100644--- a/packages/server/src/repowise/server/routers/chat.py+++ b/packages/server/src/repowise/server/routers/chat.py@@ -6,9 +6,9 @@ import jsonimport loggingfrom typing import Any-from fastapi import APIRouter, Depends, HTTPException, Requestfrom starlette.responses import StreamingResponse+from fastapi import APIRouter, Depends, HTTPException, Requestfrom repowise.core.persistence import crudfrom repowise.core.persistence.database import get_sessionfrom repowise.core.providers.llm.base import ChatProvider, ProviderErrordiff --git a/packages/server/src/repowise/server/routers/claude_md.py b/packages/server/src/repowise/server/routers/claude_md.pyindex 342302521..cec3cb69a 100644--- a/packages/server/src/repowise/server/routers/claude_md.py+++ b/packages/server/src/repowise/server/routers/claude_md.py@@ -4,9 +4,9 @@ from __future__ import annotationsfrom pathlib import Path-from fastapi import APIRouter, Depends, HTTPExceptionfrom sqlalchemy.ext.asyncio import AsyncSession+from fastapi import APIRouter, Depends, HTTPExceptionfrom repowise.core.generation.editor_files import ClaudeMdGenerator, EditorFileDataFetcherfrom repowise.core.persistence import crudfrom repowise.server.deps import get_db_session, verify_api_keydiff --git a/packages/server/src/repowise/server/routers/dead_code.py b/packages/server/src/repowise/server/routers/dead_code.pyindex 72d4b3a1f..3db7dc1a6 100644--- a/packages/server/src/repowise/server/routers/dead_code.py+++ b/packages/server/src/repowise/server/routers/dead_code.py@@ -2,9 +2,9 @@from __future__ import annotations-from fastapi import APIRouter, Depends, HTTPException, Queryfrom sqlalchemy.ext.asyncio import AsyncSession+from fastapi import APIRouter, Depends, HTTPException, Queryfrom repowise.core.persistence import crudfrom repowise.server.deps import get_db_session, verify_api_keyfrom repowise.server.schemas import (diff --git a/packages/server/src/repowise/server/routers/decisions.py b/packages/server/src/repowise/server/routers/decisions.pyindex fdfe6e623..2ad0ba5e9 100644--- a/packages/server/src/repowise/server/routers/decisions.py+++ b/packages/server/src/repowise/server/routers/decisions.py@@ -2,9 +2,9 @@from __future__ import annotations-from fastapi import APIRouter, Depends, HTTPException, Queryfrom sqlalchemy.ext.asyncio import AsyncSession+from fastapi import APIRouter, Depends, HTTPException, Queryfrom repowise.core.persistence import crudfrom repowise.server.deps import get_db_session, verify_api_keyfrom repowise.server.schemas import (diff --git a/packages/server/src/repowise/server/routers/git.py b/packages/server/src/repowise/server/routers/git.pyindex f399e6a9a..57e80fe2a 100644--- a/packages/server/src/repowise/server/routers/git.py+++ b/packages/server/src/repowise/server/routers/git.py@@ -4,10 +4,10 @@ from __future__ import annotationsimport json-from fastapi import APIRouter, Depends, HTTPException, Queryfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from fastapi import APIRouter, Depends, HTTPException, Queryfrom repowise.core.persistence import crudfrom repowise.core.persistence.models import GitMetadatafrom repowise.server.deps import get_db_session, verify_api_keydiff --git a/packages/server/src/repowise/server/routers/graph.py b/packages/server/src/repowise/server/routers/graph.pyindex 520b00d34..96ec597d0 100644--- a/packages/server/src/repowise/server/routers/graph.py+++ b/packages/server/src/repowise/server/routers/graph.py@@ -4,10 +4,10 @@ from __future__ import annotationsimport json-from fastapi import APIRouter, Depends, HTTPException, Queryfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from fastapi import APIRouter, Depends, HTTPException, Queryfrom repowise.core.persistence import crudfrom repowise.core.persistence.models import (DeadCodeFinding,diff --git a/packages/server/src/repowise/server/routers/health.py b/packages/server/src/repowise/server/routers/health.pyindex 5fea9e274..84afa330c 100644--- a/packages/server/src/repowise/server/routers/health.py+++ b/packages/server/src/repowise/server/routers/health.py@@ -5,10 +5,10 @@ These endpoints are NOT protected by API key auth.from __future__ import annotations-from fastapi import APIRouter, Requestfrom sqlalchemy import func, selectfrom sqlalchemy.sql import text+from fastapi import APIRouter, Requestfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import GenerationJob, Pagefrom repowise.server import __version__diff --git a/packages/server/src/repowise/server/routers/jobs.py b/packages/server/src/repowise/server/routers/jobs.pyindex 63b1710d2..b8edfbf79 100644--- a/packages/server/src/repowise/server/routers/jobs.py+++ b/packages/server/src/repowise/server/routers/jobs.py@@ -5,11 +5,11 @@ from __future__ import annotationsimport asyncioimport json-from fastapi import APIRouter, Depends, HTTPException, Query, Requestfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSessionfrom starlette.responses import StreamingResponse+from fastapi import APIRouter, Depends, HTTPException, Query, Requestfrom repowise.core.persistence import crudfrom repowise.core.persistence.database import get_sessionfrom repowise.core.persistence.models import GenerationJobdiff --git a/packages/server/src/repowise/server/routers/pages.py b/packages/server/src/repowise/server/routers/pages.pyindex 0094da3c3..23323eca9 100644--- a/packages/server/src/repowise/server/routers/pages.py+++ b/packages/server/src/repowise/server/routers/pages.py@@ -7,9 +7,9 @@ parameter greedily matches the suffix as part of the page_id.from __future__ import annotations-from fastapi import APIRouter, Depends, HTTPException, Queryfrom sqlalchemy.ext.asyncio import AsyncSession+from fastapi import APIRouter, Depends, HTTPException, Queryfrom repowise.core.persistence import crudfrom repowise.server.deps import get_db_session, verify_api_keyfrom repowise.server.schemas import PageResponse, PageVersionResponsediff --git a/packages/server/src/repowise/server/routers/providers.py b/packages/server/src/repowise/server/routers/providers.pyindex df8027a85..9bf4ad11d 100644--- a/packages/server/src/repowise/server/routers/providers.py+++ b/packages/server/src/repowise/server/routers/providers.py@@ -3,7 +3,6 @@from __future__ import annotationsfrom fastapi import APIRouter, Depends, HTTPException-from repowise.server.deps import verify_api_keyfrom repowise.server.provider_config import (list_provider_status,diff --git a/packages/server/src/repowise/server/routers/repos.py b/packages/server/src/repowise/server/routers/repos.pyindex 824c492ba..9788a7ab0 100644--- a/packages/server/src/repowise/server/routers/repos.py+++ b/packages/server/src/repowise/server/routers/repos.py@@ -2,10 +2,10 @@from __future__ import annotations-from fastapi import APIRouter, Depends, HTTPExceptionfrom sqlalchemy import func, selectfrom sqlalchemy.ext.asyncio import AsyncSession+from fastapi import APIRouter, Depends, HTTPExceptionfrom repowise.core.persistence import crudfrom repowise.core.persistence.models import DeadCodeFinding, GraphNode, Page, Repositoryfrom repowise.server.deps import get_db_session, verify_api_keydiff --git a/packages/server/src/repowise/server/routers/search.py b/packages/server/src/repowise/server/routers/search.pyindex dc425375c..ceb436ef8 100644--- a/packages/server/src/repowise/server/routers/search.py+++ b/packages/server/src/repowise/server/routers/search.py@@ -3,7 +3,6 @@from __future__ import annotationsfrom fastapi import APIRouter, Depends, Query-from repowise.server.deps import get_fts, get_vector_store, verify_api_keyfrom repowise.server.schemas import SearchResultResponsediff --git a/packages/server/src/repowise/server/routers/symbols.py b/packages/server/src/repowise/server/routers/symbols.pyindex 97d6d50a4..aef662824 100644--- a/packages/server/src/repowise/server/routers/symbols.py+++ b/packages/server/src/repowise/server/routers/symbols.py@@ -2,10 +2,10 @@from __future__ import annotations-from fastapi import APIRouter, Depends, HTTPException, Queryfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from fastapi import APIRouter, Depends, HTTPException, Queryfrom repowise.core.persistence.models import WikiSymbolfrom repowise.server.deps import get_db_session, verify_api_keyfrom repowise.server.schemas import SymbolResponsediff --git a/packages/server/src/repowise/server/routers/webhooks.py b/packages/server/src/repowise/server/routers/webhooks.pyindex 944f2fc82..2f5f6b290 100644--- a/packages/server/src/repowise/server/routers/webhooks.py+++ b/packages/server/src/repowise/server/routers/webhooks.py@@ -7,9 +7,9 @@ import hmacimport jsonimport os-from fastapi import APIRouter, Depends, HTTPException, Requestfrom sqlalchemy.ext.asyncio import AsyncSession+from fastapi import APIRouter, Depends, HTTPException, Requestfrom repowise.core.persistence import crudfrom repowise.server.deps import get_db_sessionfrom repowise.server.schemas import WebhookResponsediff --git a/packages/web/src/lib/api/client.ts b/packages/web/src/lib/api/client.tsindex aaf9ef5f5..1185f61d6 100644--- a/packages/web/src/lib/api/client.ts+++ b/packages/web/src/lib/api/client.ts@@ -87,9 +87,17 @@ export async function apiPost<T>(path: string,body?: unknown,fetchOptions?: RequestInit,+ params?: Record<string, string | number | boolean | undefined>,): Promise<T> {- const url = `${BASE_URL}${path}`;- const res = await fetch(url, {+ const url = new URL(`${BASE_URL}${path}`, typeof window !== "undefined" ? window.location.href : "http://localhost");+ if (params) {+ for (const [k, v] of Object.entries(params)) {+ if (v !== undefined && v !== null) {+ url.searchParams.set(k, String(v));+ }+ }+ }+ const res = await fetch(url.toString(), {method: "POST",headers: buildHeaders(),body: body !== undefined ? JSON.stringify(body) : undefined,diff --git a/packages/web/src/lib/api/pages.ts b/packages/web/src/lib/api/pages.tsindex 0d305e57f..ba6a6a9e7 100644--- a/packages/web/src/lib/api/pages.ts+++ b/packages/web/src/lib/api/pages.ts@@ -45,5 +45,5 @@ export async function getPageVersions(/** Force-regenerate a page by ID */export async function regeneratePage(pageId: string): Promise<{ job_id: string }> {- return apiPost<{ job_id: string }>(`/api/pages/lookup/regenerate?page_id=${encodeURIComponent(pageId)}`);+ return apiPost<{ job_id: string }>("/api/pages/lookup/regenerate", undefined, undefined, { page_id: pageId });}diff --git a/pyproject.toml b/pyproject.tomlindex ed2c3d0c4..bcebcab0c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -77,9 +77,9 @@ dependencies = ["cryptography>=43,<44",# LLM providers (bundled — no extras needed)"anthropic>=0.40,<1",- "openai>=1.50,<2",+ "openai>=1.50,<3","google-genai>=1.0,<2",- "litellm>=1.50,<2",+ "litellm>=1.83.0,<2",][project.optional-dependencies]@@ -195,7 +195,7 @@ known-first-party = ["repowise"]# mypy — strict type checking# ---------------------------------------------------------------------------[tool.mypy]-python_version = "0.1.30"+python_version = "3.11"warn_unused_configs = trueshow_error_codes = truenamespace_packages = truediff --git a/tests/integration/test_cli.py b/tests/integration/test_cli.pyindex 7f32b1e0f..902dfbd87 100644--- a/tests/integration/test_cli.py+++ b/tests/integration/test_cli.py@@ -59,6 +59,27 @@ class TestInitFullMock:assert "init complete" in result.output+class TestInitDefaultDbLocation:+ def test_creates_repo_local_db_without_env_override(+ self,+ runner,+ tmp_path,+ sample_repo_path,+ monkeypatch,+ ):+ work_repo = tmp_path / "repo"+ shutil.copytree(sample_repo_path, work_repo)+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)+ result = runner.invoke(+ cli,+ ["init", str(work_repo), "--provider", "mock", "--yes"],+ catch_exceptions=False,+ )+ assert result.exit_code == 0, result.output+ assert (work_repo / ".repowise" / "wiki.db").exists()++class TestInitIdempotent:def test_running_init_twice(self, runner, work_repo):args = ["init", str(work_repo), "--provider", "mock", "--yes"]diff --git a/tests/providers/test_mock_provider.py b/tests/providers/test_mock_provider.pyindex 8f13878ab..6ecc45772 100644--- a/tests/providers/test_mock_provider.py+++ b/tests/providers/test_mock_provider.py@@ -7,12 +7,9 @@ access are required to run these tests.from __future__ import annotations-import pytest-from repowise.core.providers.llm.base import BaseProvider, GeneratedResponsefrom repowise.core.providers.llm.mock import MockProvider-# ---------------------------------------------------------------------------# Interface contract# ---------------------------------------------------------------------------diff --git a/tests/providers/test_rate_limiter.py b/tests/providers/test_rate_limiter.pyindex 8486c07ed..61416a164 100644--- a/tests/providers/test_rate_limiter.py+++ b/tests/providers/test_rate_limiter.py@@ -50,14 +50,14 @@ class TestRateLimiterAcquire:limiter = RateLimiter(config)await limiter.acquire(estimated_tokens=500)# One request should now be recorded- assert len(limiter._request_times) == 1 # noqa: SLF001+ assert len(limiter._request_times) == 1async def test_multiple_acquires_within_limits(self) -> None:config = RateLimitConfig(requests_per_minute=100, tokens_per_minute=1_000_000)limiter = RateLimiter(config)for _ in range(10):await limiter.acquire(estimated_tokens=100)- assert len(limiter._request_times) == 10 # noqa: SLF001+ assert len(limiter._request_times) == 10async def test_acquire_respects_rpm_limit(self) -> None:"""Acquiring more than RPM slots should block until window clears."""@@ -71,8 +71,8 @@ class TestRateLimiterAcquire:# Manually expire the window by backdating the timestampsnow = time.monotonic()- limiter._request_times = [now - 61.0, now - 61.0] # noqa: SLF001- limiter._token_records = [(now - 61.0, 1), (now - 61.0, 1)] # noqa: SLF001+ limiter._request_times = [now - 61.0, now - 61.0]+ limiter._token_records = [(now - 61.0, 1), (now - 61.0, 1)]# Third acquire should now succeed immediately (window cleared)await asyncio.wait_for(limiter.acquire(estimated_tokens=1), timeout=1.0)@@ -87,8 +87,8 @@ class TestRateLimiterAcquire:# Manually expire the windownow = time.monotonic()- limiter._request_times = [now - 61.0] # noqa: SLF001- limiter._token_records = [(now - 61.0, 100)] # noqa: SLF001+ limiter._request_times = [now - 61.0]+ limiter._token_records = [(now - 61.0, 100)]# Next acquire should succeedawait asyncio.wait_for(limiter.acquire(estimated_tokens=100), timeout=1.0)@@ -101,13 +101,13 @@ class TestRateLimiterPruning:# Inject old timestamps (> 60s ago)old_time = time.monotonic() - 65.0- limiter._request_times = [old_time, old_time] # noqa: SLF001- limiter._token_records = [(old_time, 500), (old_time, 500)] # noqa: SLF001+ limiter._request_times = [old_time, old_time]+ limiter._token_records = [(old_time, 500), (old_time, 500)]# Acquire should prune stale records and succeedawait limiter.acquire(estimated_tokens=100)# After pruning, only the new request remains- assert len(limiter._request_times) == 1 # noqa: SLF001+ assert len(limiter._request_times) == 1class TestRateLimiterBackoff:diff --git a/tests/unit/cli/test_commands.py b/tests/unit/cli/test_commands.pyindex 532d0987b..b249adbbe 100644--- a/tests/unit/cli/test_commands.py+++ b/tests/unit/cli/test_commands.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport pytestfrom click.testing import CliRunner+from repowise.cli import __version__from repowise.cli.main import cli@@ -23,7 +24,7 @@ class TestCliBasics:result = runner.invoke(cli, ["--version"])assert result.exit_code == 0assert "repowise" in result.output- assert "0.1.2" in result.output+ assert __version__ in result.outputdef test_help(self, runner):result = runner.invoke(cli, ["--help"])diff --git a/tests/unit/cli/test_helpers.py b/tests/unit/cli/test_helpers.pyindex 85f4a5797..1444ac2a1 100644--- a/tests/unit/cli/test_helpers.py+++ b/tests/unit/cli/test_helpers.py@@ -90,10 +90,11 @@ class TestrepowiseDir:class TestDbUrl:- def test_sqlite_url(self, tmp_path):+ def test_defaults_to_repo_local_database(self, tmp_path):url = get_db_url_for_repo(tmp_path)- assert url.startswith("sqlite+aiosqlite:///")- assert "wiki.db" in url+ expected_path = (tmp_path / ".repowise" / "wiki.db").as_posix()+ assert url == f"sqlite+aiosqlite:///{expected_path}"+ assert (tmp_path / ".repowise").exists()# ---------------------------------------------------------------------------diff --git a/tests/unit/server/conftest.py b/tests/unit/server/conftest.pyindex bf9fbab4f..dfe23151a 100644--- a/tests/unit/server/conftest.py+++ b/tests/unit/server/conftest.py@@ -21,10 +21,10 @@ def _create_test_app():"""Create a FastAPI app without the lifespan (we manage state manually)."""from contextlib import asynccontextmanager- from fastapi import FastAPIfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse+ from fastapi import FastAPIfrom repowise.server.routers import (dead_code,git,diff --git a/tests/unit/server/test_mcp.py b/tests/unit/server/test_mcp.pyindex a20c3581a..4b751f27b 100644--- a/tests/unit/server/test_mcp.py+++ b/tests/unit/server/test_mcp.py@@ -1352,3 +1352,77 @@ def test_format_setup_instructions():assert "Cursor" in instructionsassert "Cline" in instructionsassert "repowise" in instructions+++# ---- MCP lifespan DB resolution ----+++async def test_mcp_lifespan_uses_cli_database_env_var(monkeypatch):+ """REPOWISE_DB_URL should be respected by MCP lifespan via resolve_db_url."""+ import repowise.server.mcp_server._server as mcp_server+ from repowise.server.mcp_server import _state++ captured: dict[str, str] = {}++ class DummyEngine:+ @property+ def dialect(self):+ class _D:+ name = "sqlite"+ return _D()++ async def dispose(self) -> None:+ return None++ class DummyFts:+ def __init__(self, engine) -> None:+ self.engine = engine++ async def ensure_index(self) -> None:+ return None++ class DummyVectorStore:+ def __init__(self, *, embedder) -> None:+ self.embedder = embedder++ async def close(self) -> None:+ return None++ async def fake_init_db(engine) -> None:+ return None++ async def fake_load_vector_stores(repo_path: str | None) -> None:+ return None++ def fake_create_async_engine(url: str, connect_args: dict | None = None) -> DummyEngine:+ captured["url"] = url+ return DummyEngine()++ monkeypatch.setenv("REPOWISE_DB_URL", "sqlite+aiosqlite:///tmp/from-cli.db")+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)+ monkeypatch.setattr(mcp_server, "create_async_engine", fake_create_async_engine)+ monkeypatch.setattr(mcp_server, "init_db", fake_init_db)+ monkeypatch.setattr(mcp_server, "FullTextSearch", DummyFts)+ monkeypatch.setattr(mcp_server, "InMemoryVectorStore", DummyVectorStore)+ monkeypatch.setattr(mcp_server, "async_sessionmaker", lambda *args, **kwargs: object())+ monkeypatch.setattr(mcp_server, "_load_vector_stores", fake_load_vector_stores)++ original_repo_path = _state._repo_path+ original_vector_store = _state._vector_store+ original_decision_store = _state._decision_store+ original_ready = _state._vector_store_ready++ _state._repo_path = None+ _state._vector_store = None+ _state._decision_store = None+ _state._vector_store_ready = None++ try:+ async with mcp_server._lifespan(mcp_server.mcp):+ assert captured["url"] == "sqlite+aiosqlite:///tmp/from-cli.db"+ finally:+ _state._repo_path = original_repo_path+ _state._vector_store = original_vector_store+ _state._decision_store = original_decision_store+ _state._vector_store_ready = original_ready