diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..d6b0810 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,41 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + lint-and-test: + name: lint + tests (Python 3.11) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + + - uses: actions/setup-python@v7 + with: + # The minor version the image actually ships. Local development runs a + # newer one, so this is the only place the two are forced to agree. + python-version: "3.11" + cache: pip + + # Also the check that the documented install still resolves: the pins in + # requirements.txt are open-ended, so this job can go red on an upstream + # release with no code change on our side. + - name: Install dependencies + run: python -m pip install -r requirements-dev.txt + + - name: Lint + run: ruff check . + + - name: Test + run: python -m pytest -q diff --git a/README.md b/README.md index 7cbc597..4f85d20 100644 --- a/README.md +++ b/README.md @@ -742,8 +742,11 @@ pip install -r requirements-dev.txt pytest # whole suite pytest tests/test_summary.py # one file pytest -k reindex # tests whose name matches +ruff check . # lint (rules configured in pyproject.toml) ``` +`.github/workflows/ci.yml` runs `ruff check .` and `pytest` on every push to `main` and on pull requests, on Python 3.11 — the version the Docker image ships, so a newer local interpreter can't hide an incompatibility from production. + | File | Covers | |---|---| | `test_api_logger.py` | Request logging for aiohttp/httpx/httpx2, redaction, body capture, inbound interactions (runs in its own process) | diff --git a/REVIEW.md b/REVIEW.md index 3d449ee..f9f0de6 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -348,12 +348,14 @@ The current 18 patterns in `responses/errors.py` cover common cases. The followi 2. Create `docker-compose.yml` with volume mount for `data/` (vector store persistence) and `.env` passthrough 3. Document in `SETUP.md` -### 6.3 CI/CD Pipeline ⚡ Low - -Add a GitHub Actions workflow: -1. **Lint** — `ruff check .` or `flake8` -2. **Test** — `pytest` (once 6.1 is implemented) -3. **Build** — verify `pip install -r requirements.txt` succeeds -4. Trigger on push to `main` and on PRs -5. Optional: automated Docker image build and push to GHCR +### 6.3 CI/CD Pipeline ⚡ Low ✅ Implemented (1–4; 5 still open) + +`.github/workflows/ci.yml` runs on push to `main` and on pull requests: +`pip install -r requirements-dev.txt` → `ruff check .` → `pytest`, on +**Python 3.11** — the version the Dockerfile ships (local development runs 3.14). + +Rules live in `pyproject.toml` and are deliberately the default `E4,E7,E9,F` set. +Widening it is follow-up work, one ruleset per commit: `I001` currently has 46 +hits, `B` 12, `UP` 10, `SIM` 70, and `E501` at 120 columns 262. Item 5 (build the +image and push it to GHCR) is not implemented. diff --git a/cogs/history_rag.py b/cogs/history_rag.py index 31d133b..d44616b 100644 --- a/cogs/history_rag.py +++ b/cogs/history_rag.py @@ -16,7 +16,7 @@ except ImportError: TTLCache = dict # type: ignore from discord import app_commands -from discord.ext import commands, tasks +from discord.ext import commands from core.discord_text import format_chunk_line, format_message_line, message_content_text, render_search_results from core.local_inference import run_local_model @@ -44,7 +44,6 @@ HISTORY_SQL_TIMEOUT_SECONDS, HISTORY_SQL_TOOL_ENABLED, HISTORY_TIME_DECAY_LAMBDA, - HISTORY_WINDOW_OVERLAP, HISTORY_WINDOW_SIZE, LOCAL_RERANK_DEVICE, LOCAL_RERANK_MODEL, @@ -1864,7 +1863,7 @@ def _regexp(pattern, value): lines = [" | ".join(cols)] if cols else [] for r in rows: lines.append(" | ".join(_sql_cell(v) for v in r)) - if sum(len(l) for l in lines) > _SQL_OUTPUT_CHARS: + if sum(len(line) for line in lines) > _SQL_OUTPUT_CHARS: lines.pop() truncated = True lines.append(f"…saída truncada em {_SQL_OUTPUT_CHARS} caracteres") diff --git a/cogs/log_analyzer.py b/cogs/log_analyzer.py index a1ca4f8..8e3e05d 100644 --- a/cogs/log_analyzer.py +++ b/cogs/log_analyzer.py @@ -89,7 +89,7 @@ def _extract_relevant_lines(text: str, limit: int = MAX_LOG_CONTEXT) -> str: """ lines = text.splitlines(keepends=True) header = lines[:_LOG_HEADER_LINES] - relevant = [l for l in lines[_LOG_HEADER_LINES:] if _LOG_ERROR_PATTERN.search(l)] + relevant = [line for line in lines[_LOG_HEADER_LINES:] if _LOG_ERROR_PATTERN.search(line)] filtered = ( ''.join(header) + '\n[... linhas informativas omitidas — exibindo apenas erros e avisos ...]\n\n' diff --git a/core/conversations.py b/core/conversations.py index 2b9e5fb..38ecf97 100644 --- a/core/conversations.py +++ b/core/conversations.py @@ -355,7 +355,7 @@ def make_turn( if s.get('url') ][:6], 'reply_to': str(reply_to) if reply_to else None, - 'prior_context': [l for l in (prior_context or []) if l][:max(30, CONVERSATIONS_GAP_MESSAGES)], + 'prior_context': [line for line in (prior_context or []) if line][:max(30, CONVERSATIONS_GAP_MESSAGES)], } context_refs = [u for u in (context_images or []) if u][:image_store.MAX_IMAGES_PER_TURN] if context_refs: @@ -470,7 +470,7 @@ def _prior_context_head(lines: list[str], channel_id: str | int | None) -> str: def _prior_context_block(turn: dict) -> str: """Render the channel chatter captured before a turn's question, if any.""" - prior = [l for l in (turn.get('prior_context') or []) if l] + prior = [line for line in (turn.get('prior_context') or []) if line] return _prior_context_head(prior, turn.get('channel_id')) @@ -686,7 +686,7 @@ def build_current_message( inline: list[dict] = [] parts: list[dict] | None = None head = (f"{context_blocks}\n\n" if context_blocks else '') + _prior_context_head( - [l for l in (prior_context or []) if l], channel_id + [line for line in (prior_context or []) if line], channel_id ) text = question tag = author_tag(author, ts, reply_to=reply_to) diff --git a/core/tavily_tools.py b/core/tavily_tools.py index 25e5fa1..9c92da9 100644 --- a/core/tavily_tools.py +++ b/core/tavily_tools.py @@ -1,12 +1,11 @@ """Tavily web search and content extraction tools for the LLM agentic loop.""" -import json import logging from typing import Any from tavily import AsyncTavilyClient -from config import TAVILY_API_KEY, TAVILY_AVAILABLE +from config import TAVILY_API_KEY logger = logging.getLogger(__name__) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..e258f12 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,22 @@ +# Tool configuration only — QuillBot is an application, not a distributable package. +# Tests are configured in pytest.ini; the runtime dependencies in requirements.txt. + +[tool.ruff] +# Matches the Dockerfile base image, which is what production actually runs. +target-version = "py311" +# p99 of the tracked sources sits just under this; E501 is not enforced yet, so +# raising it later stays a separate, reviewable change. +line-length = 120 +extend-exclude = ["data"] + +[tool.ruff.format] +# The whole tree is single-quoted; without this `ruff format` would rewrite it. +quote-style = "single" +# CI runs `ruff check`, not `ruff format --check`: even with the quotes kept, the +# formatter still wants to rewrap 72 files, which belongs in a commit of its own. + +[tool.ruff.lint] +# Deliberately the ruff default set. The wider candidates each found real hits +# (I001 46, B 12, UP 10, SIM 70) that belong in their own commits, and the gate +# has to be green from the first run to be worth having. +select = ["E4", "E7", "E9", "F"] diff --git a/requirements-dev.txt b/requirements-dev.txt index a266747..ac8bcc5 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,2 +1,4 @@ -r requirements.txt pytest>=8.0 +# Pinned exactly: CI and local runs must agree on what a lint error is. +ruff==0.15.12 diff --git a/tests/test_api_logger.py b/tests/test_api_logger.py index 52431bc..c47bd45 100644 --- a/tests/test_api_logger.py +++ b/tests/test_api_logger.py @@ -110,7 +110,9 @@ async def main(): await client.chat.completions.create(model='sdk/model', messages=[{'role': 'user', 'content': 'x'}]) raise AssertionError('non-streaming request should have been rejected') except BadRequestError as e: - assert 'streaming_only' in str(e) + # str(e) only carries the provider's message text on openai>=3 and the whole + # body on 2.x, so the code lives in the logged response body (asserted below). + assert e.status_code == 400 SDK_BODIES.clear() messages = [{'role': 'user', 'content': 'via sdk'}] @@ -161,22 +163,22 @@ async def main(): # registered listener directly — same coroutine the event loop would run. await bot.extra_events['on_interaction'][0](inter) - lines = [json.loads(l) for l in open(os.environ['API_REQUEST_LOG_PATH'])] - for l in lines: - print(json.dumps(l, ensure_ascii=False)) + lines = [json.loads(raw) for raw in open(os.environ['API_REQUEST_LOG_PATH'])] + for rec in lines: + print(json.dumps(rec, ensure_ascii=False)) - aiohttp_lines = [l for l in lines if l['dir'] == 'outbound' and l['url'].startswith(base) and l.get('status') == 200 and 'token' in l['url']] + aiohttp_lines = [rec for rec in lines if rec['dir'] == 'outbound' and rec['url'].startswith(base) and rec.get('status') == 200 and 'token' in rec['url']] assert len(aiohttp_lines) == 1, 'aiohttp success line missing' assert 'supersecret' not in aiohttp_lines[0]['url'] and 'REDACTED' in aiohttp_lines[0]['url'], 'query redaction failed' assert aiohttp_lines[0]['service'] == 'other' and aiohttp_lines[0]['status'] == 200 and 'duration_ms' in aiohttp_lines[0] - hx = [l for l in lines if l['dir'] == 'outbound' and l['method'] == 'POST' and l['url'].endswith('/chat')] + hx = [rec for rec in lines if rec['dir'] == 'outbound' and rec['method'] == 'POST' and rec['url'].endswith('/chat')] assert len(hx) == 1 and hx[0]['status'] == 200, 'httpx success line missing' assert hx[0]['model'] == 'qwen/qwen3.6-plus', 'model extraction failed' assert hx[0]['request_body']['messages'][0]['content'] == 'oi', 'request body capture failed' assert hx[0]['response_body']['usage']['prompt_tokens'] == 42, 'response body capture failed' - sdk = [l for l in lines if l['dir'] == 'outbound' and l['url'].endswith('/v1/chat/completions')] + sdk = [rec for rec in lines if rec['dir'] == 'outbound' and rec['url'].endswith('/v1/chat/completions')] assert len(sdk) == 3, 'OpenAI SDK request not logged' assert sdk[0]['status'] == 400 and sdk[0]['response_body']['error']['code'] == 'streaming_only' assert sdk[1]['status'] == 200 and sdk[1]['request_body']['messages'][0]['content'] == 'via sdk', 'SDK request body capture failed' @@ -198,13 +200,13 @@ async def main(): assert cut.startswith('HEAD') and cut.endswith('TAIL') and 'truncated' in cut assert len(cut) < limit + 100 - errs = [l for l in lines if 'error' in l] + errs = [rec for rec in lines if 'error' in rec] assert len(errs) == 1 and errs[0]['url'].startswith('http://127.0.0.1:1'), 'error path line missing' - meta = [l for l in lines if l['dir'] == 'meta'] + meta = [rec for rec in lines if rec['dir'] == 'meta'] assert meta and meta[0]['event'] == 'api_request_logging_installed' - inbound = [l for l in lines if l['dir'] == 'inbound'] + inbound = [rec for rec in lines if rec['dir'] == 'inbound'] assert len(inbound) == 1 and inbound[0]['command'] == 'ask' and inbound[0]['user_id'] == 123 assert inbound[0]['interaction_type'] == 'application_command' assert inbound[0]['guild_id'] == 456 and inbound[0]['channel_id'] == 789 diff --git a/tests/test_docs_rag.py b/tests/test_docs_rag.py index 1219d0f..12ed7a4 100644 --- a/tests/test_docs_rag.py +++ b/tests/test_docs_rag.py @@ -100,7 +100,7 @@ def test_partial_reindex_keeps_other_sources(): by_source = {} for c in rag.chunks: by_source.setdefault(c['source'], []).append(c['title']) - check('other sources untouched', all(len(by_source[l]) == 2 for l in LABELS if l != 'PaperMC'), by_source) + check('other sources untouched', all(len(by_source[label]) == 2 for label in LABELS if label != 'PaperMC'), by_source) check('reindexed source replaced', sorted(by_source['PaperMC']) == ['new-2000', 'new-2001', 'new-2002'], by_source['PaperMC']) check('matrix rows stay aligned with chunks', _aligned(rag)) check('composite SHA unchanged on partial', rag._last_commit_sha == 'composite-old') diff --git a/tests/test_history_search.py b/tests/test_history_search.py index 8a951cc..3d9e0e8 100644 --- a/tests/test_history_search.py +++ b/tests/test_history_search.py @@ -49,12 +49,12 @@ def chunk(mid, cid, cname, aid, aname, afull, content, ts, chunk_text=None): def build_chunks(): - alice = lambda mid, name, content, ts, cid=GENERAL, cname="general": chunk( - mid, cid, cname, ALICE_ID, name, f"{name} (@alice)", content, ts - ) - bob = lambda mid, content, ts, cid=DEV, cname="dev": chunk( - mid, cid, cname, BOB_ID, "Bob", "Bob (@bob)", content, ts - ) + def alice(mid, name, content, ts, cid=GENERAL, cname="general"): + return chunk(mid, cid, cname, ALICE_ID, name, f"{name} (@alice)", content, ts) + + def bob(mid, content, ts, cid=DEV, cname="dev"): + return chunk(mid, cid, cname, BOB_ID, "Bob", "Bob (@bob)", content, ts) + return [ alice(1, "Alice", "paper lag fix applied", "2025-06-01T10:00:00+00:00"), alice(2, "Alice", "restart after the paper lag fix", "2025-06-01T10:02:00+00:00"), diff --git a/tests/test_history_sql.py b/tests/test_history_sql.py index ab3fa12..012a49a 100644 --- a/tests/test_history_sql.py +++ b/tests/test_history_sql.py @@ -46,12 +46,12 @@ def chunk(mid, gid, cid, cname, aid, aname, afull, content, ts, reply_to=None): def build_chunks(): - alice = lambda mid, content, ts, cid=GENERAL, cname="general", reply=None: chunk( - mid, GID, cid, cname, ALICE_ID, "Alice", "Alice (@alice)", content, ts, reply - ) - bob = lambda mid, content, ts, reply=None: chunk( - mid, GID, DEV, "dev", BOB_ID, "Bob", "Bob (@bob)", content, ts, reply - ) + def alice(mid, content, ts, cid=GENERAL, cname="general", reply=None): + return chunk(mid, GID, cid, cname, ALICE_ID, "Alice", "Alice (@alice)", content, ts, reply) + + def bob(mid, content, ts, reply=None): + return chunk(mid, GID, DEV, "dev", BOB_ID, "Bob", "Bob (@bob)", content, ts, reply) + return [ alice(1, "server lag is terrible today", "2025-06-01T10:00:00+00:00"), alice(2, "restart fixed the server lag", "2025-06-01T10:02:00+00:00", reply="1"), diff --git a/tests/test_mentions.py b/tests/test_mentions.py index 77314c6..ef1286f 100644 --- a/tests/test_mentions.py +++ b/tests/test_mentions.py @@ -59,7 +59,7 @@ def test_limit(): STRIP_CASES = [ # addressing mentions are dropped (f'{BM} como otimizar?', None, 'como otimizar?'), - (f'<@!900000000000000001>, como otimizar?', None, 'como otimizar?'), + ('<@!900000000000000001>, como otimizar?', None, 'como otimizar?'), (f'como otimizar? {BM}', None, 'como otimizar?'), (BM, None, ''), # in-sentence mentions keep their place as @name (the reported bug) diff --git a/tests/test_message_media.py b/tests/test_message_media.py index 6e4bebb..f224925 100644 --- a/tests/test_message_media.py +++ b/tests/test_message_media.py @@ -153,7 +153,9 @@ async def download(url): def test_context_groups_media_first_then_emoji_sheets(): - img = lambda i: SimpleNamespace(id=i, filename=f'{i}.png', content_type='image/png', url='u') + def img(i): + return SimpleNamespace(id=i, filename=f'{i}.png', content_type='image/png', url='u') + messages = [ # newest first fake_message(6, '<:a:111111111111111111>'), fake_message(5, attachments=[img(50)]), diff --git a/tests/test_settings_router.py b/tests/test_settings_router.py index c15e54c..a72b647 100644 --- a/tests/test_settings_router.py +++ b/tests/test_settings_router.py @@ -83,7 +83,10 @@ async def monitors(msg): router.observe('history', observer) router.handle('monitors', monitors, priority=20) router.handle('chat', chat, priority=10) - human = lambda mid, content: NS(id=mid, content=content, author=NS(bot=False)) + + def human(mid, content): + return NS(id=mid, content=content, author=NS(bot=False)) + check('chat claims first', await router.dispatch(human(1, 'para o bot')) == 'chat') check('monitors get the rest', await router.dispatch(human(2, 'outra coisa')) == 'monitors') check('bots are observed but never handled', await router.dispatch(NS(id=3, content='x', author=NS(bot=True))) is None)