Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 33 additions & 5 deletions codewiki/cli/commands/serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import logging
import sys
import time

import click

Expand Down Expand Up @@ -54,18 +55,34 @@ def serve_command(docs_dir, port, host, allow_origins, model, no_log_questions):
fg="yellow",
err=True,
)
index = get_index(docs)
origins = sorted(default_origins(host, port, docs) | {origin_of(o) or o for o in allow_origins})
from rich.console import Console

qa_logger = logging.getLogger("codewiki.src.be.qa")
qa_logger.setLevel(logging.INFO)
click.echo(f"Loading {docs} …")
started = time.monotonic()
# Indexing can take a while (re-reading code changed since the docs): show
# each step the index logs as it starts it.
with Console(stderr=True).status("Reading the docs…") as status:
step = _StatusHandler(status)
qa_logger.addHandler(step)
try:
index = get_index(docs)
status.update("Starting the server…")
origins = sorted(
default_origins(host, port, docs) | {origin_of(o) or o for o in allow_origins}
)
finally:
qa_logger.removeHandler(step)
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(logging.Formatter("[%(asctime)s] %(message)s", "%H:%M:%S"))
qa_logger = logging.getLogger("codewiki.src.be.qa")
qa_logger.addHandler(handler)
qa_logger.setLevel(logging.INFO)

click.secho(f"CodeWiki docs + chat: http://{host}:{port}/", fg="green", bold=True)
click.echo(f" Docs: {docs}")
click.echo(
f" Indexed: {len(index.sections)} doc sections, {len(index.code)} code components"
f" Indexed: {len(index.sections)} doc sections, {len(index.code)} code components "
f"in {time.monotonic() - started:.1f}s"
)
click.echo(f" Freshness: {index.freshness.summary()}")
if index.stale_pages:
Expand All @@ -77,3 +94,14 @@ def serve_command(docs_dir, port, host, allow_origins, model, no_log_questions):
click.echo(f" Chat allowed from: {', '.join(origins)}")
click.echo(" Ctrl+C to stop.")
serve(docs, host, port, allow_origins, model=model, log_questions=not no_log_questions)


class _StatusHandler(logging.Handler):
"""Shows each log message as the spinner's text."""

def __init__(self, status) -> None:
super().__init__(logging.INFO)
self.status = status

def emit(self, record: logging.LogRecord) -> None:
self.status.update(record.getMessage())
6 changes: 5 additions & 1 deletion codewiki/src/be/qa/impact.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,8 +253,12 @@ def _repo_files(index: QAIndex):
and not d.startswith(".")
and os.path.abspath(os.path.join(root, d)) != docs
)
# relpath of the directory, never of the file: Windows resolves a file
# named NUL / CON / ... to \\.\NUL, which relpath rejects ("path is on
# mount '\\.\nul', start on mount 'C:'").
folder = os.path.relpath(root, repo).replace(os.sep, "/")
for name in sorted(files):
yield os.path.relpath(os.path.join(root, name), repo).replace(os.sep, "/")
yield name if folder == "." else f"{folder}/{name}"


def _parameters(source: str) -> set[str]:
Expand Down
3 changes: 3 additions & 0 deletions codewiki/src/be/qa/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,10 +190,12 @@ def __init__(self, docs_dir: str, repo_path: str | None = None) -> None:
self.repo_path = _resolve_repo(
self.docs_dir, repo_path, {n.relative_path for n in graph.values() if n.relative_path}
)
logger.info("Checking what changed since the docs were generated…")
self.freshness: Freshness = detect(
self.docs_dir, self.repo_path, {n.relative_path for n in graph.values()}
)
self._build_code(graph)
logger.info("Indexing doc pages and %d code component(s)…", len(self.code))
self._build_pages()
self._build_index()
self.stamp = self.compute_stamp(self.docs_dir)
Expand Down Expand Up @@ -222,6 +224,7 @@ def _build_code(self, graph: dict[str, Any]) -> None:
if self.repo_path and os.path.isfile(os.path.join(self.repo_path, f))
)
if to_parse and len(to_parse) <= MAX_OVERLAY_FILES:
logger.info("Re-reading %d file(s) changed since the docs…", len(to_parse))
try:
live = _overlay(self.repo_path, to_parse)
replaced |= set(to_parse)
Expand Down
17 changes: 2 additions & 15 deletions codewiki/src/be/qa/retrieve.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from dataclasses import dataclass, field

from codewiki.src.be.qa.bm25 import tokenize
from codewiki.src.be.qa.impact import _repo_files
from codewiki.src.be.qa.index import QAIndex, approx_tokens

STALE_FACTOR = 0.5
Expand All @@ -27,7 +28,6 @@
_NAME_QUERY_RE = re.compile(r"^(?:[\w./-]+::)?[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$")
MAX_PINNED = 5
_CHARS_PER_TOKEN = 3.6
_SKIP_DIRS = {".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build", ".tox"}


@dataclass
Expand Down Expand Up @@ -216,23 +216,10 @@ def grep(self, patterns: list[str], max_files: int = _GREP_MAX_FILES) -> list[Ca
return sorted(found.values(), key=lambda c: c.score, reverse=True)

def _repo_files(self):
repo = self.index.repo_path
docs = os.path.abspath(self.index.docs_dir)
known = sorted({u.file for u in self.index.code.values()})
seen = set(known)
yield from known
for root, dirs, files in os.walk(repo):
dirs[:] = sorted(
d
for d in dirs
if d not in _SKIP_DIRS
and not d.startswith(".")
and os.path.abspath(os.path.join(root, d)) != docs
)
for name in sorted(files):
rel = os.path.relpath(os.path.join(root, name), repo).replace(os.sep, "/")
if rel not in seen:
yield rel
yield from (rel for rel in _repo_files(self.index) if rel not in seen)

def expand(self, cands: list[Candidate], hops: int = 1, limit: int = 30) -> list[Candidate]:
"""Add graph neighbours (calls, callers, page<->component) at a discount."""
Expand Down
34 changes: 34 additions & 0 deletions tests/test_qa_retrieval.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Q&A index, freshness, retrieval and the no-LLM MCP tools."""

import os
import sys
import time

import pytest
Expand Down Expand Up @@ -293,3 +294,36 @@ def spy(self, ids, budget, focus=None):
{"docs_dir": str(docs_dir), "ids": ["pkg/timed.py::TimestampSigner"], "query": "clock"}
)
assert seen["focus"] == "clock"


def test_repo_walk_survives_windows_device_names(docs, monkeypatch):
"""On Windows a stray file named NUL resolves to \\\\.\\nul and relpath raises
"path is on mount '\\\\.\\nul', start on mount 'C:'"; grep and impact walk the
repo for every Ask AI question."""
from codewiki.src.be.qa.impact import _repo_files, find_references

repo, docs_dir = docs
# What `> nul` in Git Bash leaves behind. Windows needs \\?\ to create it
# (a plain path writes to the NUL device) and then fails for real;
# elsewhere relpath's Windows error is simulated.
nul = os.path.join(os.path.abspath(repo), "nul")
if sys.platform == "win32":
nul = "\\\\?\\" + nul
else:
real = os.path.relpath

def windows_relpath(path, start=os.curdir):
if os.path.basename(path).lower() == "nul":
raise ValueError("path is on mount '\\\\.\\nul', start on mount 'C:'")
return real(path, start)

monkeypatch.setattr(os.path, "relpath", windows_relpath)
with open(nul, "w"):
pass
try:
index = QAIndex(str(docs_dir))
assert "nul" in set(_repo_files(index))
assert Retriever(index).grep([r"\bmax_age\b"])
assert find_references(index, "MAX_AGE").all_ids
finally:
os.remove(nul) # pytest's own cleanup cannot delete it on Windows
Loading