From 72cad19a5632cf816ec154463e2a1a4bb0d8c13c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 6 Jun 2026 20:20:08 +0000 Subject: [PATCH 01/24] Add Streamlit render smoke test + reconcile mock verdict schema MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes the test-coverage gap that let the nested-st.expander bug ship through CI and only surface on the live Replit deploy: the 462-test suite exercised every service but never rendered app.py. tests/test_phase28_ui_smoke.py (4 tests): - Renders the real app.py through Streamlit's AppTest harness: * unauthenticated auth gate, * a fully-seeded authenticated account (application + stages + TWO tailored artifacts + master CV with a revision + a share link — the densest nested-UI path, exactly where the nested-expander bug lived), asserting no render-time exception, * the public ?share= view. Uses the StaticPool in-memory SQLite so the ScriptRunner thread shares the seeded DB; demo mode (no provider key) so no network during render. - A static guard that scans app.py for `with st.expander(` nested inside another, verified to flag a true positive and pass the checkbox-inner pattern. Belt-and-suspenders for code paths a single render might miss. services/system_test.py: reconcile MOCK_ANALYSIS["verdict"] to the canonical {verdict, light, reasons, confidence, source} shape used by utils/verdict.py + render_result, so the System Test tab renders the verdict badge identically to a real analysis (it previously used a divergent {decision, confidence, cautions} shape that render_result couldn't read). Full suite 466/466 green. --- services/system_test.py | 8 +- tests/test_phase28_ui_smoke.py | 199 +++++++++++++++++++++++++++++++++ 2 files changed, 206 insertions(+), 1 deletion(-) create mode 100644 tests/test_phase28_ui_smoke.py diff --git a/services/system_test.py b/services/system_test.py index 2f74dec..9b984fe 100644 --- a/services/system_test.py +++ b/services/system_test.py @@ -242,8 +242,14 @@ def run_system_test() -> List[TestResult]: "3. Prepare a system-design example (high-throughput Python service)" ), "verdict": { - "decision": "Apply", + # Canonical verdict shape used everywhere else in the app + # (utils/verdict.py + render_result): verdict / light / reasons / + # confidence. Keeping the mock on the same schema means the System + # Test tab renders the verdict badge identically to a real analysis. + "verdict": "Recommended", + "light": "green", "confidence": 8, + "source": "structured", "reasons": [ "Compensation at / above market", "Well-funded (Series B, 18-month runway)", diff --git a/tests/test_phase28_ui_smoke.py b/tests/test_phase28_ui_smoke.py new file mode 100644 index 0000000..8139e52 --- /dev/null +++ b/tests/test_phase28_ui_smoke.py @@ -0,0 +1,199 @@ +"""Phase 28: Streamlit render smoke test. + +The whole 462-test suite exercises *services* but never rendered ``app.py``, +which is exactly how a nested-``st.expander`` bug (Streamlit raises +"Expanders may not be nested") shipped through CI and only surfaced on the +live Replit deployment. + +This test closes that gap. It seeds a fully-populated account (an application +with stages, multiple tailored artifacts, a master CV with a revision, and a +share link — i.e. the densest nested-UI path) and renders the real ``app.py`` +through Streamlit's ``AppTest`` harness, asserting the script raises no +exception. If anyone reintroduces a nested expander (or any render-time +error in the authenticated UI), this fails in CI instead of in production. + +``AppTest`` executes the script in a ScriptRunner thread, so the DB must be a +StaticPool in-memory SQLite (one shared connection across threads) — which +``reset_engine_for_testing`` already provides. +""" + +from __future__ import annotations + +import os +import sys +import unittest + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +try: + from streamlit.testing.v1 import AppTest + HAS_APPTEST = True +except Exception: # noqa: BLE001 - older/newer streamlit without the harness + HAS_APPTEST = False + +_APP_PATH = os.path.abspath( + os.path.join(os.path.dirname(__file__), "..", "app.py") +) + + +def _fmt_exc(at) -> str: + """Render AppTest exception elements into a readable message.""" + try: + return " | ".join(str(getattr(e, "value", e)) for e in at.exception) or "(none)" + except Exception: # noqa: BLE001 + return str(at.exception) + +def _fresh_db(): + from db.session import reset_engine_for_testing + from services.rate_limit import reset_backend_for_testing + reset_engine_for_testing("sqlite:///:memory:") + reset_backend_for_testing() + + +def _seed_dense_account(): + """Create a user whose My Applications row exercises the full nested UI: + stages (timeline + list), 2 artifacts (A/B compare + per-artifact toggles), + a master CV with a revision (history + diff), and a share link. + Returns the user record. + """ + from datetime import date + + from services.applications import save_analysis + from services.auth import register_user + from services.master_cv import save_master_cv + from services.sharing import create_share + from services.stages import add_stage + from services.tailoring import save_artifact + + user = register_user("smoke@x.com", "longenough") + + # Master CV + a second save so a revision exists. + save_master_cv(user.id, "Jane Doe\nSkills: Python, AWS, PyTorch") + save_master_cv(user.id, "Jane Doe\nSkills: Python, AWS, PyTorch, Docker") + + app_rec = save_analysis( + user.id, + {"company_name": "Acme", "job_title": "ML Engineer", "location": "Berlin"}, + { + "final_report": "# Report\n\nStrong fit.", + "verdict": {"verdict": "Recommended", "light": "green", + "reasons": ["good match"], "confidence": 8, + "source": "structured"}, + "resume_analysis": {"ats_score": 78, "matched_skills": ["Python"], + "missing_skills": ["Kubernetes"], + "format_issues": [], "commentary": "Looks good."}, + "job_details": { + "extracted_details": {"company_name": "Acme", + "job_title": "ML Engineer", + "location": "Berlin"}, + "requirements_analysis": {"technical_skills": ["Python", "AWS"]}, + }, + }, + ) + + add_stage(user.id, app_rec.id, "applied", occurred_on=date(2026, 5, 1)) + add_stage(user.id, app_rec.id, "phone_screen", occurred_on=date(2026, 5, 6)) + + # Two artifacts of the same kind so the A/B compare UI renders. + check = {"severity": "review_recommended", "new_proper_nouns": ["kafka"], + "new_years": [], "new_percentages": [], "new_quantitative_claims": [], + "total_flags": 1} + save_artifact(user.id, app_rec.id, "tailored_cv", "# CV v1\n\n- Python", + meta={"model": "fast", "constraint_check": check}) + save_artifact(user.id, app_rec.id, "tailored_cv", "# CV v2\n\n- Python, AWS", + meta={"model": "fast", "constraint_check": + {"severity": "clean", "new_proper_nouns": [], + "new_years": [], "new_percentages": [], + "new_quantitative_claims": [], "total_flags": 0}}) + + create_share(user.id, app_rec.id, ttl_days=7, include_artifacts=True) + return user + + +@unittest.skipUnless(HAS_APPTEST, "streamlit AppTest harness unavailable") +class AppRenderSmokeTests(unittest.TestCase): + def setUp(self): + # No provider key -> demo mode, so no network during render. + for k in ("ANTHROPIC_API_KEY", "OPENAI_API_KEY", "FEATHERLESS_API_KEY", + "LLM_PROVIDER"): + os.environ.pop(k, None) + _fresh_db() + + def _run_app(self): + at = AppTest.from_file(_APP_PATH, default_timeout=60) + return at + + def test_auth_gate_renders_without_error(self): + """Unauthenticated: the login gate must render cleanly (no user_id).""" + at = self._run_app() + at.run() + self.assertEqual(len(at.exception), 0, msg=_fmt_exc(at)) + + def test_full_authenticated_ui_renders_without_error(self): + """The dense nested-UI path must render without a render-time exception + (this is the path the nested-expander bug lived in).""" + user = _seed_dense_account() + at = self._run_app() + # First run hits the auth gate + st.stop(); then we sign in and re-run + # so session_state exists exactly as the live app would have it. + at.run() + at.session_state["user_id"] = user.id + at.session_state["user_email"] = user.email + at.run() + self.assertEqual( + len(at.exception), 0, + msg="app.py raised during authenticated render: " + _fmt_exc(at), + ) + # Sanity: the app rendered tabs (>=5 top-level; more counting the + # nested st.tabs in the CV + analyze sections). + self.assertGreaterEqual(len(at.tabs), 5) + + def test_share_view_renders_without_error(self): + """The public ?share= view (renders before the auth gate) must work.""" + user = _seed_dense_account() + from services.sharing import list_shares_for_application + from services.applications import list_applications + + app_id = list_applications(user.id)[0].id + token = list_shares_for_application(user.id, app_id)[0].token + + at = self._run_app() + at.query_params["share"] = token + at.run() + self.assertEqual(len(at.exception), 0, msg=_fmt_exc(at)) + + def test_no_nested_expanders_in_source(self): + """Belt-and-suspenders static guard: app.py must not nest expanders. + + AppTest catches it dynamically only on a code path that actually + renders; this static check catches a nested `with st.expander` inside + another `with st.expander` block regardless of runtime path. + """ + src = open(_APP_PATH, encoding="utf-8").read() + depth = 0 + max_depth = 0 + # Track indentation-based nesting of `with st.expander(` blocks. This is + # a heuristic — it flags an expander opened while another is still in + # scope at greater indentation. + expander_stack = [] # list of indentation levels of open expanders + for line in src.splitlines(): + stripped = line.lstrip() + indent = len(line) - len(stripped) + # Pop expanders we've dedented out of. + while expander_stack and indent <= expander_stack[-1]: + expander_stack.pop() + if stripped.startswith("with st.expander("): + if expander_stack: + max_depth = max(max_depth, len(expander_stack) + 1) + expander_stack.append(indent) + depth = max(depth, len(expander_stack)) + self.assertLessEqual( + max_depth, 0, + msg="Found a nested `with st.expander(...)` in app.py — Streamlit " + "forbids nested expanders. Use st.checkbox toggles for the " + "inner level (see the Phase-27 Replit fix).", + ) + + +if __name__ == "__main__": + unittest.main() From 79f193317adbe328b41041667c0c19f147852eb6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 7 Jun 2026 16:58:54 +0000 Subject: [PATCH 02/24] Extend UI smoke test with interaction paths Beyond initial render, exercise the two highest-value callback paths so a broken on-click handler fails in CI, not production: - Analyze form submit in demo mode -> runs the pipeline and renders the result (covers the analyze -> render_result path); asserts last_result is populated with a final_report. - Stage quick-action click -> add_stage + st.rerun + dense re-render; asserts the stage was persisted and no render exception. Added _textarea_by_label / _button_by_label / _button_by_key AppTest helpers. Full suite 468/468 green. --- tests/test_phase28_ui_smoke.py | 79 ++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/tests/test_phase28_ui_smoke.py b/tests/test_phase28_ui_smoke.py index 8139e52..89cf262 100644 --- a/tests/test_phase28_ui_smoke.py +++ b/tests/test_phase28_ui_smoke.py @@ -43,6 +43,27 @@ def _fmt_exc(at) -> str: except Exception: # noqa: BLE001 return str(at.exception) +def _textarea_by_label(at, label): + for ta in at.text_area: + if (ta.label or "") == label: + return ta + return None + + +def _button_by_label(at, label): + for b in at.button: + if (b.label or "") == label: + return b + return None + + +def _button_by_key(at, key): + for b in at.button: + if getattr(b, "key", None) == key: + return b + return None + + def _fresh_db(): from db.session import reset_engine_for_testing from services.rate_limit import reset_backend_for_testing @@ -162,6 +183,64 @@ def test_share_view_renders_without_error(self): at.run() self.assertEqual(len(at.exception), 0, msg=_fmt_exc(at)) + # -- interaction paths (click, don't just render) ---------------------- + + def test_analyze_submit_in_demo_mode_renders_result(self): + """Submitting the analyze form in demo mode must run the pipeline and + render a result without error — covers the analyze -> render_result + callback path, not just initial render.""" + user = _seed_dense_account() + at = self._run_app() + at.run() + at.session_state["user_id"] = user.id + at.session_state["user_email"] = user.email + at.run() + self.assertEqual(len(at.exception), 0, msg=_fmt_exc(at)) + + jd = _textarea_by_label(at, "Job description") + self.assertIsNotNone(jd, "Job description text area not found") + jd.set_value( + "Company: Acme\nTitle: ML Engineer\nLocation: Berlin\n" + "We need Python, AWS and PyTorch experience for a senior role." + ) + submit = _button_by_label(at, "🔍 Analyze posting") + self.assertIsNotNone(submit, "Analyze submit button not found") + submit.click().run() + + self.assertEqual(len(at.exception), 0, msg=_fmt_exc(at)) + # The pipeline result is stashed in session_state and rendered. + try: + last = at.session_state["last_result"] + except (KeyError, AttributeError): + last = None + self.assertIsNotNone(last, "analyze submit did not produce a result") + self.assertTrue(last.get("final_report")) + + def test_stage_quick_action_click_adds_stage(self): + """Clicking a stage quick-action button must add a stage + re-render + the dense application UI without error.""" + from services.applications import list_applications + from services.stages import list_stages + + user = _seed_dense_account() + app_id = list_applications(user.id)[0].id + before = len(list_stages(user.id, app_id)) + + at = self._run_app() + at.run() + at.session_state["user_id"] = user.id + at.session_state["user_email"] = user.email + at.run() + + btn = _button_by_key(at, f"qa_{app_id}_technical_interview") + self.assertIsNotNone(btn, "technical_interview quick-action not found") + btn.click().run() + + self.assertEqual(len(at.exception), 0, msg=_fmt_exc(at)) + after = list_stages(user.id, app_id) + self.assertEqual(len(after), before + 1) + self.assertIn("technical_interview", [s.kind for s in after]) + def test_no_nested_expanders_in_source(self): """Belt-and-suspenders static guard: app.py must not nest expanders. From eca6dd5a5f37a2e5bb5464d8b29af448bd96ed67 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 7 Jun 2026 17:00:52 +0000 Subject: [PATCH 03/24] Add CLAUDE.md: codebase guide + production-readiness roadmap Agent/human onboarding doc covering: what the app is, repo layout, how to run each surface, the conventions that must be followed (demo mode, no-fabrication, ownership scoping, best-effort side-effects, bcrypt-at-rest, migrations + StaticPool testing, no nested expanders), the testing approach, a summary of the ~28 increments shipped, and a prioritized production-readiness roadmap (P0/P1/P2) with the concrete gaps that remain before real multi-user traffic (in-process state vs horizontal scaling, the dated use_container_width deprecation, account lifecycle/GDPR, schema-drift guard, CI quality gates, secrets-at-rest, cost controls, observability shipping, live provider e2e, webhook durability, backups/runbook). --- CLAUDE.md | 196 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 196 insertions(+) create mode 100644 CLAUDE.md diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..97528d3 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,196 @@ +# CLAUDE.md — JobOffer Scanner + +Guide for AI agents (and humans) working in this repo. Read this first. + +## What this is + +An AI-assisted **job-offer analysis platform**. A user pastes a job posting +(or a URL); the system runs a multi-stage LLM pipeline that extracts +requirements, assesses company stability, benchmarks compensation, optionally +scores a resume against the posting (ATS), and emits a structured +Green/Yellow/Red verdict + report. Around that core it tracks applications +through pipeline stages, derives analytics, maintains a master CV + project +gallery, and generates **tailored CVs / cover letters that cannot fabricate** +(a deterministic post-check verifies every generated artifact stays within the +user's real CV facts). + +Three channels: **Streamlit web UI** (`app.py`), a **Telegram bot** (`bot/`), +and a **REST API** (`api/`). Deployed on **Replit** (Streamlit + Replit +Postgres); a `docker-compose.yml` runs the full multi-service stack. + +## Repo layout + +``` +app.py Streamlit web UI (single entry; all tabs + sidebar) +agents/ LangGraph pipeline: orchestrator + per-stage agents + orchestrator.py Checkpoint-aware graph: job -> (company || salary) -> resume? -> report + job_/company_/salary_/resume_analyzer.py, report_generator.py +tools/ LLM-facing tools + ingestion + job_tools, company_tools, salary_tools, resume_tools, data_sources, + url_ingest, browser_scraper (Playwright, optional) +services/ Business logic (28 modules) — the bulk of the app + auth, totp, oauth, api_tokens, rate_limit, audit (identity/security) + applications, stages, analytics, timeline, background_analysis (tracking) + master_cv, projects, tailoring, constraint_check, suggestions, pdf_export (CV/artifacts) + sharing, webhooks, telegram_link, notifications, email, reminders (integrations) + checkpoint, bulk_import, system_test, analysis_runner +db/ SQLAlchemy 2.0 models + session (StaticPool-aware) +api/ FastAPI app: routes, bearer auth, security headers +bot/ Telegram bot: handlers (pure) + main (runtime) +worker/ Celery app + tasks + CLI runners (reminders, metrics_dump) +utils/ llm, config, security, diff, verdict, logging_setup, metrics, timing, cache +migrations/ Alembic (14 revisions, 18 tables) +chrome-extension/ MV3 extension calling the REST API (JS, Node-tested) +deploy/ Caddyfile + nginx reverse-proxy examples (CSP/HSTS) +tests/ 28 files, 468 Python tests + 9 JS (extract.test.mjs) +``` + +## How to run + +```bash +# Web UI (what Replit runs) +streamlit run app.py # :5000 + +# REST API +python -m api.main # :8000 ; /healthz, /v1/* + +# Telegram bot (needs TELEGRAM_BOT_TOKEN + [telegram] extra) +python -m bot.main + +# Celery worker (needs CELERY_BROKER_URL + [worker] extra) +celery -A worker.celery_app:app worker + +# Scheduled reminders (cron / Scheduled Deployment) +python -m worker.reminders + +# Tests +python -m unittest discover -s tests # ~5 min, 468 tests +node chrome-extension/extract.test.mjs # 9 JS tests + +# Migrations +USE_ALEMBIC=1 alembic upgrade head # prod; else create_all on boot +``` + +Config is via env vars / `.env` (see `.env.example`). No key set ⇒ **demo +mode** (sample data, clearly labelled). `DATABASE_URL` unset ⇒ SQLite at +`./data/joboffer.db`. + +## Conventions that matter (follow these) + +- **Demo mode is a first-class state.** `utils/llm.get_completion` returns + bounded sample data when no provider key is set, and **raises** (never + fabricates) when a key is set but the call fails. The UI badge reflects it. +- **No fabrication in generated artifacts.** `services/tailoring` injects + `NO_FABRICATION_RULES` into every prompt AND `services/constraint_check` + deterministically flags any skill/year/percentage/claim in the output that + isn't in the master CV + projects + job context. Keep both halves. +- **Ownership scoping everywhere.** Every service read/write that takes a + `user_id` checks it; cross-user access raises. The REST API returns **404 + (not 403)** for another user's resource so IDs can't be enumerated. +- **Best-effort side-effects never break the main flow.** Notifications + (Telegram/email/webhooks) and audit writes log-and-continue; they must not + raise into the user action that triggered them. Webhooks dispatch on a + daemon thread. +- **Secrets are bcrypt-hashed at rest**: passwords, reset tokens, 2FA backup + codes, API tokens (with an indexed 8-char prefix for fast lookup). TOTP + secrets are stored plaintext by design (documented; envelope-encrypt for + hardened prod). +- **Migrations:** add a model field ⇒ add an Alembic migration. CI runs the + full `up → down → up` on real Postgres. `db.session.reset_engine_for_testing` + uses **StaticPool** so thread-hopping tests (bot handlers, Streamlit + `AppTest`) share one in-memory connection. +- **Streamlit forbids nested `st.expander`.** Inner collapsibles use + `st.checkbox` toggles. `tests/test_phase28_ui_smoke.py` guards this both + dynamically (AppTest render) and statically (source scan). + +## Testing approach + +- Services are unit-tested directly against in-memory SQLite. +- Network is always mocked (LLM, HTTP, SMTP, Telegram). No test hits a real + provider — this is deliberate (the sandbox is egress-restricted; CI is too). +- `tests/test_phase28_ui_smoke.py` renders the real `app.py` via Streamlit + `AppTest` (auth gate, dense authenticated UI, public share view) and clicks + the analyze-submit + a stage quick-action — this is the only layer that + exercises the Streamlit render/callback path, and it exists because a + nested-expander bug once shipped through a fully-green service suite. + +## Recent improvements (high level) + +Built across ~28 increments from a non-functional prototype (it returned the +same canned "TechCorp" text regardless of input) to the current product: + +- **Core made real:** provider-agnostic LLM (Anthropic/OpenAI/Featherless, + incl. GPT-5 / o-series `max_completion_tokens` handling), prompt-injection + hardening, parallel company‖salary stages, resumable pipeline checkpoints. +- **Product:** resume/ATS analysis, URL ingestion, structured verdict, stage + tracking + analytics + timelines, master CV (with revisions + diff), + project gallery, tailored CV/cover-letter generation with the deterministic + no-fabrication check + one-click "add skill to CV" suggestions, PDF export, + bulk import. +- **Platform:** email/password + **OAuth (Google/GitHub)** + **TOTP 2FA**, + rate limiting, audit log, structured JSON logging, in-process metrics + + timing, background analyses (Celery), inactivity reminders, public share + links, webhooks, REST API + bearer tokens, Chrome extension, system-test tab. +- **Ops:** Alembic migrations (Postgres-tested in CI), Docker Compose, + reverse-proxy CSP/HSTS configs, Replit deployment (live). + +## Production-readiness roadmap (what's left) + +The app is feature-complete and deployed, but several things stand between it +and "production-grade for real multi-user traffic." Prioritized: + +### P0 — do before scaling past one instance / real users +1. **State that's in-process won't survive horizontal scaling.** `utils/cache.SimpleCache`, + `services/checkpoint`, `utils/metrics`, and the default rate-limit backend + are per-process. Rate-limit already supports Redis; do the same for the + cache + checkpoint store (or accept single-instance Reserved-VM only). +2. **`use_container_width` is deprecated and past its removal date + (2025-12-31).** 5 call sites in `app.py`. Migrate to `width="stretch"` + before a Streamlit bump breaks the UI. +3. **Account lifecycle gaps:** no email verification on signup, no "delete my + account / export all my data" (GDPR). FK cascades exist, but expose the + action. `RESET_TOKEN_SURFACE_IN_UI` and reset-token logging must be off in + prod. +4. **Schema drift guard.** App boots with `create_all` by default; prod uses + Alembic. Add a CI check (`alembic check` / autogenerate-diff) so models and + migrations can't silently diverge. + +### P1 — hardening + confidence +5. **CI quality gates:** add lint (ruff), type-check (mypy), security scan + (bandit + pip-audit), and a coverage floor. Run the JS tests in CI + (add setup-node). Bump `actions/checkout`/`setup-python` off Node 20. +6. **Secrets at rest:** envelope-encrypt the TOTP secret (KMS-derived key); + consider the same for OAuth-linked emails. +7. **LLM cost controls:** token accounting + per-user budget (today's quota is + a request count, not spend). Cache identical analyses (the cache exists; wire + COL/news/LLM through it consistently). +8. **Observability shipping:** logs are structured JSON and metrics exist, but + nothing exports them. Wire an OTLP/Prometheus exporter or a log drain; + metrics are currently per-process snapshot-only. +9. **Live provider e2e:** every test mocks the LLM. Add a gated, + key-required smoke test (skipped without a key) that does one real + round-trip per provider so model/param regressions (like the GPT-5 + `max_completion_tokens` change) are caught. + +### P2 — robustness + reach +10. **JS-board scraping:** `browser_scraper` (Playwright) exists but isn't + deployed; LinkedIn/Indeed/Glassdoor need it (or the Chrome extension). +11. **Webhook delivery durability:** deliveries are best-effort daemon + threads; move to the Celery queue with retry/backoff for at-least-once. +12. **Backups + runbook:** automated Postgres backups, a restore drill, and a + documented incident/runbook. None exist yet. +13. **Reverse proxy on the real deployment:** the CSP/HSTS configs in `deploy/` + aren't applied on vanilla Replit; a hardened public deploy should sit + behind Caddy/nginx (or an equivalent edge). + +## Gotchas + +- The sandbox/CI is **egress-restricted** — only allowlisted hosts resolve. + Don't write tests that hit real network; mock it. +- `uv.lock` must match `pyproject.toml` — regenerate with `uv lock` after any + dependency change, or Replit's `uv sync` installs the wrong set. +- This is an **application, not a library**: `pyproject.toml` sets + `[tool.setuptools] py-modules = []` so `pip install -e .` only pulls deps; + source is imported from the repo root (on `sys.path` in every run context). +- `fpdf2 >= 2.8` imports `cryptography` eagerly; if a sandbox has broken Rust + bindings, pin to `2.7.x` locally (prod/CI are fine). From dbd532ab8123537d71782ce130cdf0331be5abdf Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 7 Jun 2026 17:04:13 +0000 Subject: [PATCH 04/24] P0.2: migrate deprecated use_container_width -> width="stretch" use_container_width was deprecated with removal scheduled after 2025-12-31 (already past). All 5 call sites in app.py (link_button, sidebar button, two altair_chart, one dataframe) used =True; replaced with width="stretch", the documented successor. The Streamlit AppTest smoke test confirms the UI renders with no deprecation warnings. Also closed an unclosed-file ResourceWarning in the nested-expander static scan. --- app.py | 10 +++++----- tests/test_phase28_ui_smoke.py | 3 ++- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/app.py b/app.py index fb110a3..b9070d1 100644 --- a/app.py +++ b/app.py @@ -270,7 +270,7 @@ def _render_oauth_buttons() -> None: st.session_state.oauth_provider = provider url = build_authorize_url(provider, state) label = {"google": "Google", "github": "GitHub"}.get(provider, provider) - st.link_button(f"Sign in with {label}", url, use_container_width=True) + st.link_button(f"Sign in with {label}", url, width="stretch") st.divider() @@ -693,7 +693,7 @@ def render_auth() -> None: # Sign out lives at the bottom so it isn't the second sidebar click target. st.sidebar.markdown("---") -if st.sidebar.button("Sign out", use_container_width=True): +if st.sidebar.button("Sign out", width="stretch"): for key in ("user_id", "user_email", "last_result", "last_inputs"): st.session_state.pop(key, None) st.rerun() @@ -1381,7 +1381,7 @@ def _matches(rec) -> bool: ) st.altair_chart( (line + dots).properties(height=180), - use_container_width=True, + width="stretch", ) # ----- Pipeline stages ----- @@ -1886,7 +1886,7 @@ def _matches(rec) -> bool: for v in dash.verdict_outcomes ], hide_index=True, - use_container_width=True, + width="stretch", ) st.caption( "Correlation isn't causation — but a consistent gap between " @@ -1952,7 +1952,7 @@ def _matches(rec) -> bool: chart_height = max(180, row_height * len(label_order) + 60) st.altair_chart( (line_per_app + dots_per_app).properties(height=chart_height), - use_container_width=True, + width="stretch", ) diff --git a/tests/test_phase28_ui_smoke.py b/tests/test_phase28_ui_smoke.py index 89cf262..dbfc927 100644 --- a/tests/test_phase28_ui_smoke.py +++ b/tests/test_phase28_ui_smoke.py @@ -248,7 +248,8 @@ def test_no_nested_expanders_in_source(self): renders; this static check catches a nested `with st.expander` inside another `with st.expander` block regardless of runtime path. """ - src = open(_APP_PATH, encoding="utf-8").read() + with open(_APP_PATH, encoding="utf-8") as fh: + src = fh.read() depth = 0 max_depth = 0 # Track indentation-based nesting of `with st.expander(` blocks. This is From c293ccee1cf67a39b6f9efb4436c153d2095f02c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 7 Jun 2026 17:06:44 +0000 Subject: [PATCH 05/24] P0.4: schema-drift guard (models vs migrations) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tests/test_phase29_schema_drift.py applies all migrations to a fresh DB and uses Alembic's compare_metadata to assert there is no SUBSTANTIVE drift (add/remove table or column) between the migrated schema and the SQLAlchemy models. This catches the canonical "added a model field, forgot the migration" case — which create_all (dev/test) would mask but a migrated prod DB would not. Scoped to table/column ops on purpose: the models enforce uniqueness via column unique=True (a unique index) while the hand-written migrations use UniqueConstraint — functionally identical, so the cosmetic index/constraint naming diffs are excluded (documented), as are SQLite reflection artifacts (BigInteger->INTEGER, server defaults, String lengths). Real types/defaults are exercised by the Postgres CI migration job. The guard surfaced those pre-existing cosmetic differences on first run, confirming it works; it now passes clean and will fail CI on a future column/table divergence. --- tests/test_phase29_schema_drift.py | 103 +++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 tests/test_phase29_schema_drift.py diff --git a/tests/test_phase29_schema_drift.py b/tests/test_phase29_schema_drift.py new file mode 100644 index 0000000..e59d58e --- /dev/null +++ b/tests/test_phase29_schema_drift.py @@ -0,0 +1,103 @@ +"""P0.4: schema-drift guard. + +The app boots with ``create_all`` by default but production runs Alembic, so a +model change without a matching migration would silently diverge — `create_all` +dev/test would have the column, the migrated prod DB wouldn't. This test +applies all migrations to a fresh DB and asserts Alembic's autogenerate finds +**no difference** between the migrated schema and the SQLAlchemy models. + +If this fails, you added/changed a model column without a migration: generate +one (`alembic revision --autogenerate -m "..."`), review it, and commit it. +""" + +from __future__ import annotations + +import os +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + + +# We assert on SUBSTANTIVE drift only: a model table/column that has no +# matching migration (or vice-versa). That's the canonical "I added a field +# and forgot the migration" failure the roadmap calls out. +# +# We deliberately do NOT assert on index/constraint/default/type diffs here: +# * The models enforce uniqueness via column `unique=True` (a unique INDEX), +# while the hand-written migrations use `UniqueConstraint` — functionally +# identical (Postgres backs a UNIQUE constraint with a unique index), but +# compare_metadata reports the cosmetic difference. Reconciling would need +# an index-rename migration across SQLite+Postgres for no behavioural gain. +# * SQLite reflection can't round-trip server defaults, BigInteger (-> INTEGER), +# or String lengths, so type/default diffs are false positives here. The +# Postgres CI migration job exercises real types/defaults instead. +_SUBSTANTIVE_OPS = {"add_table", "remove_table", "add_column", "remove_column"} + + +def _op_name(diff): + """Extract the operation name from an Alembic diff entry. + + Entries are either a tuple ``(op, ...)`` or, for modify_*, a list of such + tuples. Returns the op string (first tuple's first element). + """ + if isinstance(diff, list): + return diff[0][0] if diff and isinstance(diff[0], (list, tuple)) else None + if isinstance(diff, (list, tuple)) and diff: + return diff[0] + return None + + +class SchemaDriftTests(unittest.TestCase): + def test_models_match_migrations(self): + from alembic.autogenerate import compare_metadata + from alembic.migration import MigrationContext + from sqlalchemy import create_engine + + from db.models import Base + + with tempfile.TemporaryDirectory() as tmp: + db_path = Path(tmp) / "drift.db" + url = f"sqlite:///{db_path.as_posix()}" + + # Apply every migration to a fresh DB via the project's alembic. + import subprocess + env = dict(os.environ) + env["DATABASE_URL"] = url + result = subprocess.run( + [sys.executable, "-m", "alembic", "upgrade", "head"], + cwd=Path(__file__).resolve().parents[1], + env=env, capture_output=True, text=True, + ) + self.assertEqual( + result.returncode, 0, + msg=f"alembic upgrade failed:\n{result.stdout}\n{result.stderr}", + ) + + engine = create_engine(url) + with engine.connect() as conn: + ctx = MigrationContext.configure(conn) + raw_diffs = compare_metadata(ctx, Base.metadata) + + # Keep only substantive table/column add/remove diffs, excluding + # the alembic bookkeeping table. + diffs = [ + d for d in raw_diffs + if _op_name(d) in _SUBSTANTIVE_OPS and "alembic_version" not in str(d) + ] + self.assertEqual( + diffs, [], + msg=( + "Model/migration table-or-column drift detected — these " + "are in the models but not the migrations (or vice versa):\n" + + "\n".join(f" - {d}" for d in diffs) + + "\n\nGenerate a migration: " + "`alembic revision --autogenerate -m ''`, review it, commit it." + ), + ) + + +if __name__ == "__main__": + unittest.main() From ebf0d20135ca37866370ef6af3768978740fe38d Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 7 Jun 2026 17:16:16 +0000 Subject: [PATCH 06/24] P0.1: Redis-backed cache + checkpoint store (horizontal scaling) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In-process state breaks once you run more than one app instance. Rate limiting already had a Redis backend; this gives the LLM/data-source cache and the analysis checkpoint store the same treatment, behind the same REDIS_URL (or CELERY_BROKER_URL) detection. utils/cache.py: - RedisCache (JSON-serialised values under a "joc:cache:" namespace, TTL via CACHE_TTL_SECONDS) alongside the existing SimpleCache. - build_cache() picks Redis when configured + importable, else in-memory; a failing/absent redis degrades to in-memory (logged, never raised). - Cache ops never raise into callers (a cache hiccup can't break a request). services/checkpoint.py: - RedisCheckpointStore (each key a Redis hash stage->JSON, TTL via CHECKPOINT_TTL_SECONDS) so a retry can land on a different replica and still resume completed stages. Same factory + graceful fallback. Both keep cached/checkpointed values JSON-serialisable (they already are: parsed dicts + report strings). reset_store_for_testing now rebuilds a fresh in-memory store (tests never use Redis). .env.example documents REDIS_URL now backs rate-limit + cache + checkpoints and is REQUIRED for >1 instance. Tests (tests/test_phase30_redis_state.py - 15): factory selection + graceful fallback (no URL / import fails / non-redis URL) for both stores; RedisCache set/get round-trip (dict + str), namespacing, namespaced clear, unserialisable-skip; RedisCheckpointStore set/get/has, canonical-order completed_stages, clear, key isolation — all via an injected fake redis. Full suite 484/484 green. --- .env.example | 7 +- services/checkpoint.py | 97 +++++++++++++- tests/test_phase30_redis_state.py | 216 ++++++++++++++++++++++++++++++ utils/cache.py | 93 ++++++++++++- 4 files changed, 400 insertions(+), 13 deletions(-) create mode 100644 tests/test_phase30_redis_state.py diff --git a/.env.example b/.env.example index a9c9508..e34f48a 100644 --- a/.env.example +++ b/.env.example @@ -73,7 +73,12 @@ # UI / discoverability # TELEGRAM_BOT_USERNAME=YourBot # if set, sidebar shows a link to t.me/... -# REDIS_URL=redis://localhost:6379/1 # distributed rate-limit backend (else in-mem) +# REDIS_URL=redis://localhost:6379/1 # shared backend for rate-limit + cache + +# # analysis checkpoints (REQUIRED for >1 +# # app instance; else each is in-process). +# # CELERY_BROKER_URL is used as a fallback. +# CACHE_TTL_SECONDS=3600 +# CHECKPOINT_TTL_SECONDS=3600 # Telegram bot channel (alternative to the Streamlit UI) # TELEGRAM_BOT_TOKEN=... # from @BotFather diff --git a/services/checkpoint.py b/services/checkpoint.py index 07e8c7f..8747aad 100644 --- a/services/checkpoint.py +++ b/services/checkpoint.py @@ -24,10 +24,14 @@ import hashlib import json +import logging +import os import threading from dataclasses import dataclass, field from typing import Any, Dict, Optional, Tuple +logger = logging.getLogger(__name__) + # What stages of the orchestrator write checkpointable output. Order here # mirrors the LangGraph edges in agents/orchestrator.py and is the order the @@ -103,18 +107,99 @@ def reset(self) -> None: self._data.clear() -# Module-level singleton — same lifecycle as the Python process. Streamlit -# session lifecycle is bigger than the process for ``--server.runOnSave`` -# reloads, but a reload is exactly when we'd WANT to drop the cache anyway. -_store = CheckpointStore() +class RedisCheckpointStore: + """Redis-backed checkpoint store so a retry can land on a different replica + and still resume completed stages. Each key is a Redis hash (stage -> + JSON) with a TTL so abandoned checkpoints self-expire. + """ + + _NS = "joc:ckpt:" + _TTL = int(os.getenv("CHECKPOINT_TTL_SECONDS", "3600")) + + def __init__(self, url: str) -> None: + import redis # lazy + + self._r = redis.from_url(url, decode_responses=True) + + def _k(self, key: str) -> str: + return f"{self._NS}{key}" + + def get(self, key: str) -> CheckpointPayload: + payload = CheckpointPayload() + try: + raw = self._r.hgetall(self._k(key)) + except Exception as exc: # noqa: BLE001 + logger.warning("RedisCheckpointStore get failed: %s", exc) + return payload + for stage, val in (raw or {}).items(): + try: + payload.stages[stage] = json.loads(val) + except (TypeError, ValueError): + continue + return payload + + def has(self, key: str) -> bool: + try: + return bool(self._r.exists(self._k(key))) + except Exception as exc: # noqa: BLE001 + logger.warning("RedisCheckpointStore has failed: %s", exc) + return False + + def set(self, key: str, stage: str, value: Any) -> None: + try: + self._r.hset(self._k(key), stage, json.dumps(value, default=str)) + self._r.expire(self._k(key), self._TTL) + except (TypeError, ValueError): + return # unserialisable — skip + except Exception as exc: # noqa: BLE001 + logger.warning("RedisCheckpointStore set failed: %s", exc) + + def completed_stages(self, key: str) -> Tuple[str, ...]: + try: + present = set(self._r.hkeys(self._k(key)) or []) + except Exception as exc: # noqa: BLE001 + logger.warning("RedisCheckpointStore completed_stages failed: %s", exc) + return () + return tuple(s for s in CHECKPOINT_STAGES if s in present) + + def clear(self, key: str) -> None: + try: + self._r.delete(self._k(key)) + except Exception as exc: # noqa: BLE001 + logger.warning("RedisCheckpointStore clear failed: %s", exc) + + def reset(self) -> None: + try: + for k in self._r.scan_iter(f"{self._NS}*"): + self._r.delete(k) + except Exception as exc: # noqa: BLE001 + logger.warning("RedisCheckpointStore reset failed: %s", exc) + + +def _build_store(): + url = os.getenv("REDIS_URL") or os.getenv("CELERY_BROKER_URL") + if url and url.startswith(("redis://", "rediss://")): + try: + store = RedisCheckpointStore(url) + logger.info("Using Redis checkpoint store.") + return store + except Exception as exc: # noqa: BLE001 - degrade to in-memory + logger.warning("Redis checkpoint store unavailable (%s); in-memory.", exc) + return CheckpointStore() + + +# Module-level singleton — built once at import from the environment. +_store = _build_store() -def get_store() -> CheckpointStore: +def get_store(): return _store def reset_store_for_testing() -> None: - _store.reset() + """Reset to a fresh in-memory store (tests never use Redis).""" + global _store + _store = CheckpointStore() def compute_key( diff --git a/tests/test_phase30_redis_state.py b/tests/test_phase30_redis_state.py new file mode 100644 index 0000000..5ad5b6a --- /dev/null +++ b/tests/test_phase30_redis_state.py @@ -0,0 +1,216 @@ +"""P0.1: Redis-backed cache + checkpoint store (for horizontal scaling). + +Redis isn't available in CI/sandbox, so we inject a small in-memory fake +``redis`` module to exercise the Redis backends, and assert the factory falls +back to the in-process backend when Redis is absent/unconfigured. +""" + +from __future__ import annotations + +import os +import sys +import types +import unittest +from unittest import mock + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + + +# --------------------------------------------------------------------------- +# Minimal fake redis client (decode_responses=True semantics: str in/out) +# --------------------------------------------------------------------------- + +class _FakeRedisClient: + def __init__(self): + self.kv: dict[str, str] = {} + self.hashes: dict[str, dict[str, str]] = {} + + # string ops + def get(self, k): + return self.kv.get(k) + + def set(self, k, v, ex=None): + self.kv[k] = v + + def delete(self, k): + self.kv.pop(k, None) + self.hashes.pop(k, None) + + def scan_iter(self, pattern): + prefix = pattern.rstrip("*") + yield from [k for k in list(self.kv) + list(self.hashes) if k.startswith(prefix)] + + # hash ops + def hgetall(self, k): + return dict(self.hashes.get(k, {})) + + def hset(self, k, field, value): + self.hashes.setdefault(k, {})[field] = value + + def hkeys(self, k): + return list(self.hashes.get(k, {}).keys()) + + def expire(self, k, ttl): + pass + + def exists(self, k): + return 1 if (k in self.kv or k in self.hashes) else 0 + + +def _install_fake_redis(): + """Put a fake ``redis`` module on sys.modules; return the shared client.""" + client = _FakeRedisClient() + fake = types.ModuleType("redis") + fake.from_url = lambda url, decode_responses=True: client # noqa: ARG005 + return fake, client + + +# --------------------------------------------------------------------------- +# Cache +# --------------------------------------------------------------------------- + +class CacheFactoryTests(unittest.TestCase): + def setUp(self): + for k in ("REDIS_URL", "CELERY_BROKER_URL"): + os.environ.pop(k, None) + + def test_defaults_to_in_memory(self): + from utils.cache import SimpleCache, build_cache + + self.assertIsInstance(build_cache(), SimpleCache) + + def test_uses_redis_when_configured(self): + import importlib + cache_mod = importlib.import_module('utils.cache') + + fake, _client = _install_fake_redis() + with mock.patch.dict(os.environ, {"REDIS_URL": "redis://localhost:6379/0"}), \ + mock.patch.dict(sys.modules, {"redis": fake}): + backend = cache_mod.build_cache() + self.assertIsInstance(backend, cache_mod.RedisCache) + + def test_falls_back_when_redis_import_fails(self): + import importlib + cache_mod = importlib.import_module('utils.cache') + + # URL set but no redis module importable -> in-memory. + with mock.patch.dict(os.environ, {"REDIS_URL": "redis://x:6379/0"}), \ + mock.patch.dict(sys.modules, {"redis": None}): + backend = cache_mod.build_cache() + self.assertIsInstance(backend, cache_mod.SimpleCache) + + def test_ignores_non_redis_url(self): + import importlib + cache_mod = importlib.import_module('utils.cache') + + with mock.patch.dict(os.environ, {"CELERY_BROKER_URL": "amqp://x"}): + self.assertIsInstance(cache_mod.build_cache(), cache_mod.SimpleCache) + + +class RedisCacheTests(unittest.TestCase): + def _backend(self): + import importlib + cache_mod = importlib.import_module('utils.cache') + fake, client = _install_fake_redis() + with mock.patch.dict(sys.modules, {"redis": fake}): + return cache_mod.RedisCache("redis://localhost:6379/0"), client + + def test_set_get_roundtrip_dict_and_str(self): + backend, _ = self._backend() + backend.set("k1", {"company_name": "Acme", "skills": ["Python"]}) + backend.set("k2", "a report string") + self.assertEqual(backend.get("k1"), {"company_name": "Acme", "skills": ["Python"]}) + self.assertEqual(backend.get("k2"), "a report string") + + def test_get_missing_returns_none(self): + backend, _ = self._backend() + self.assertIsNone(backend.get("nope")) + + def test_namespaced_keys(self): + backend, client = self._backend() + backend.set("abc", 1) + self.assertTrue(any(k.startswith("joc:cache:") for k in client.kv)) + + def test_clear_only_touches_namespace(self): + backend, client = self._backend() + client.kv["unrelated"] = "x" # not in our namespace + backend.set("k", 1) + backend.clear() + self.assertIn("unrelated", client.kv) + self.assertFalse(any(k.startswith("joc:cache:") for k in client.kv)) + + def test_unserialisable_value_is_skipped_not_raised(self): + backend, _ = self._backend() + backend.set("k", object()) # not JSON-serialisable + # default=str makes most things serialisable; a bare object() becomes + # its repr string rather than raising — assert no exception + a value. + self.assertIsNotNone(backend.get("k")) + + +# --------------------------------------------------------------------------- +# Checkpoint store +# --------------------------------------------------------------------------- + +class CheckpointFactoryTests(unittest.TestCase): + def setUp(self): + for k in ("REDIS_URL", "CELERY_BROKER_URL"): + os.environ.pop(k, None) + + def test_defaults_to_in_memory(self): + import services.checkpoint as ckpt + self.assertIsInstance(ckpt._build_store(), ckpt.CheckpointStore) + + def test_uses_redis_when_configured(self): + import services.checkpoint as ckpt + fake, _ = _install_fake_redis() + with mock.patch.dict(os.environ, {"REDIS_URL": "redis://localhost:6379/0"}), \ + mock.patch.dict(sys.modules, {"redis": fake}): + self.assertIsInstance(ckpt._build_store(), ckpt.RedisCheckpointStore) + + +class RedisCheckpointStoreTests(unittest.TestCase): + def _store(self): + import services.checkpoint as ckpt + fake, client = _install_fake_redis() + with mock.patch.dict(sys.modules, {"redis": fake}): + return ckpt.RedisCheckpointStore("redis://localhost:6379/0"), client + + def test_set_get_and_has(self): + store, _ = self._store() + self.assertFalse(store.has("key")) + store.set("key", "job_details", {"extracted_details": {"company_name": "Acme"}}) + self.assertTrue(store.has("key")) + payload = store.get("key") + self.assertTrue(payload.has("job_details")) + self.assertEqual(payload.get("job_details")["extracted_details"]["company_name"], "Acme") + + def test_completed_stages_in_canonical_order(self): + from services.checkpoint import CHECKPOINT_STAGES + store, _ = self._store() + # Write out of order. + store.set("k", "salary_analysis", {"x": 1}) + store.set("k", "job_details", {"y": 1}) + store.set("k", "company_analysis", {"z": 1}) + done = store.completed_stages("k") + self.assertEqual( + done, + tuple(s for s in CHECKPOINT_STAGES + if s in ("job_details", "company_analysis", "salary_analysis")), + ) + + def test_clear_removes_key(self): + store, _ = self._store() + store.set("k", "job_details", {"a": 1}) + store.clear("k") + self.assertFalse(store.has("k")) + + def test_keys_isolated(self): + store, _ = self._store() + store.set("alice", "job_details", {"co": "a"}) + store.set("bob", "job_details", {"co": "b"}) + self.assertEqual(store.get("alice").get("job_details")["co"], "a") + self.assertEqual(store.get("bob").get("job_details")["co"], "b") + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/cache.py b/utils/cache.py index a63113c..f9128a6 100644 --- a/utils/cache.py +++ b/utils/cache.py @@ -1,19 +1,36 @@ -"""Thread-safe in-memory cache with TTL. +"""TTL cache with a pluggable backend. -Streamlit reruns can execute concurrently across sessions, so the previous -plain-dict cache could race. This is still an in-process cache — Phase 3 -swaps it for Redis. +Default is a thread-safe in-memory cache (fine for a single process). When +``REDIS_URL`` (or ``CELERY_BROKER_URL``) points at Redis AND the ``redis`` +package is installed, a Redis-backed cache is used instead so multiple app +instances share cached LLM/data-source results — required for horizontal +scaling (Streamlit reruns + multiple replicas). + +Cached values MUST be JSON-serialisable (today: parsed dicts and report +strings). The Redis backend JSON-encodes on set and decodes on get; an +unserialisable value is silently skipped rather than raised, so a caching +path can never break the request that produced the value. """ from __future__ import annotations +import json +import logging +import os import threading from datetime import datetime, timedelta from typing import Any, Optional +logger = logging.getLogger(__name__) + +_DEFAULT_TTL = int(os.getenv("CACHE_TTL_SECONDS", "3600")) +_NAMESPACE = "joc:cache:" + class SimpleCache: - def __init__(self, ttl_seconds: int = 3600): + """Thread-safe in-process TTL cache.""" + + def __init__(self, ttl_seconds: int = _DEFAULT_TTL): self._cache: dict[str, tuple[Any, datetime]] = {} self._ttl = timedelta(seconds=ttl_seconds) self._lock = threading.Lock() @@ -38,4 +55,68 @@ def clear(self) -> None: self._cache.clear() -cache = SimpleCache() +class RedisCache: + """Redis-backed TTL cache. JSON-serialises values under a namespace.""" + + def __init__(self, url: str, ttl_seconds: int = _DEFAULT_TTL): + import redis # lazy — only when configured + + self._r = redis.from_url(url, decode_responses=True) + self._ttl = ttl_seconds + + def _k(self, key: str) -> str: + return f"{_NAMESPACE}{key}" + + def get(self, key: str) -> Optional[Any]: + try: + raw = self._r.get(self._k(key)) + except Exception as exc: # noqa: BLE001 - cache must never break callers + logger.warning("RedisCache get failed: %s", exc) + return None + if raw is None: + return None + try: + return json.loads(raw) + except (TypeError, ValueError): + return None + + def set(self, key: str, value: Any) -> None: + try: + payload = json.dumps(value, default=str) + except (TypeError, ValueError): + return # uncacheable value — skip, don't raise + try: + self._r.set(self._k(key), payload, ex=self._ttl) + except Exception as exc: # noqa: BLE001 + logger.warning("RedisCache set failed: %s", exc) + + def clear(self) -> None: + try: + for k in self._r.scan_iter(f"{_NAMESPACE}*"): + self._r.delete(k) + except Exception as exc: # noqa: BLE001 + logger.warning("RedisCache clear failed: %s", exc) + + +def _redis_url() -> Optional[str]: + url = os.getenv("REDIS_URL") or os.getenv("CELERY_BROKER_URL") + if url and url.startswith(("redis://", "rediss://")): + return url + return None + + +def build_cache(): + """Pick the cache backend from the environment.""" + url = _redis_url() + if url: + try: + backend = RedisCache(url) + logger.info("Using Redis cache backend.") + return backend + except Exception as exc: # noqa: BLE001 - degrade to in-memory + logger.warning("Redis cache unavailable (%s); using in-memory.", exc) + return SimpleCache() + + +# Module-level singleton used across tools/*. Built once at import from env. +cache = build_cache() From 461dc7fb8570841ea979c681fd3a4f1db464c0b5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 7 Jun 2026 17:25:39 +0000 Subject: [PATCH 07/24] P0.3 (part 1): account deletion, data export, reset-token safety MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Account self-service + GDPR data portability, plus a prod-safety fix. - services/auth.delete_account(user_id, password): password-gated permanent deletion. Audited BEFORE the row vanishes (audit row's user_id is SET NULL by cascade, so the record + email survive). Deleting the User cascades to every child table. - db/session: enable `PRAGMA foreign_keys=ON` for SQLite connections (via a connect event listener, in both get_engine and reset_engine_for_testing). SQLite ignores ON DELETE CASCADE/SET NULL without it, which would orphan child rows on SQLite while Postgres cascaded — a dev/prod split. Now identical. Verified: deleting a fully-seeded user empties all 11 child tables; another user's data is untouched. - services/account_export.build_export / export_json: one JSON bundle of everything the user owns (account, applications + stages + artifacts + shares, master CV + revisions, projects, API-token + webhook metadata, telegram link). Secrets (password/token hashes, webhook secret, TOTP secret) are excluded — tested. Audited as user.account.export. - app.py "🗄 Privacy & account" sidebar panel: download-all-my-data button + two-step password-gated delete (wipes session on success). - Reset-token prod safety: the `print([auth] reset token ...)` log line is now gated on RESET_TOKEN_SURFACE_IN_UI (same flag as the UI display), so a production deploy never leaks reset tokens to logs. - AUDIT_KINDS += user.account.{delete,export}, user.email.verify.{request,complete}. Tests (tests/test_phase31_account_lifecycle.py - 9): FK pragma on; delete wrong-password rejected; delete cascades all child tables; delete audited + record survives with SET NULL; delete is user-scoped; export bundles every domain; export excludes secrets (incl. the live webhook secret value); export is valid JSON + audited. Full suite 493/493 green. --- app.py | 48 +++++- db/models.py | 4 + db/session.py | 22 ++- services/account_export.py | 135 +++++++++++++++++ services/auth.py | 21 +++ tests/test_phase31_account_lifecycle.py | 192 ++++++++++++++++++++++++ 6 files changed, 419 insertions(+), 3 deletions(-) create mode 100644 services/account_export.py create mode 100644 tests/test_phase31_account_lifecycle.py diff --git a/app.py b/app.py index b9070d1..b093a64 100644 --- a/app.py +++ b/app.py @@ -373,11 +373,13 @@ def render_auth() -> None: if token is not None: # Best-effort email delivery (no-op if SMTP unconfigured). send_password_reset_email(forgot_email, token) - # Self-hosted operator convenience. + # Self-hosted operator convenience — BOTH the UI display + # and the log line are gated on the same opt-in flag so a + # production deploy never leaks reset tokens to stdout/logs. if os.getenv("RESET_TOKEN_SURFACE_IN_UI") == "1": st.code(token, language=None) st.caption("RESET_TOKEN_SURFACE_IN_UI=1 — disable in production.") - print(f"[auth] reset token for {forgot_email}: {token}") + print(f"[auth] reset token for {forgot_email}: {token}") # Always the same notice — never reveal whether the email exists. st.info(_RESET_GENERIC_NOTICE) except RateLimitExceeded as exc: @@ -604,6 +606,48 @@ def render_auth() -> None: st.session_state.pop("totp_backup_codes_once", None) st.rerun() +with st.sidebar.expander("🗄 Privacy & account"): + from services.account_export import export_json + from services.auth import AuthError as _AuthError, delete_account + + st.caption("Download everything we hold about you, or delete your account.") + st.download_button( + "⬇️ Download all my data (JSON)", + data=export_json(st.session_state.user_id), + file_name="my_joboffer_data.json", + mime="application/json", + key="account_export_btn", + ) + + st.markdown("---") + st.markdown("**Danger zone**") + if not st.session_state.get("account_delete_armed"): + if st.button("Delete my account…"): + st.session_state["account_delete_armed"] = True + st.rerun() + else: + st.warning( + "This permanently deletes your account and ALL data (applications, " + "CV, artifacts, tokens). This cannot be undone." + ) + with st.form("delete_account_form"): + del_pw = st.text_input("Confirm current password", type="password") + col_d, col_c = st.columns(2) + do_delete = col_d.form_submit_button("Permanently delete", type="primary") + cancel = col_c.form_submit_button("Cancel") + if cancel: + st.session_state.pop("account_delete_armed", None) + st.rerun() + if do_delete: + try: + delete_account(st.session_state.user_id, del_pw) + # Wipe the session entirely and return to the auth gate. + for key in list(st.session_state.keys()): + st.session_state.pop(key, None) + st.rerun() + except _AuthError as exc: + st.error(str(exc)) + with st.sidebar.expander("🔒 Change password"): with st.form("change_pw_form"): cur_pw = st.text_input("Current password", type="password", key="cur_pw") diff --git a/db/models.py b/db/models.py index ed66a0c..05ce661 100644 --- a/db/models.py +++ b/db/models.py @@ -541,6 +541,10 @@ class ApplicationShare(Base): "user.oauth.login", "user.oauth.register", "user.oauth.link", + "user.account.delete", + "user.account.export", + "user.email.verify.request", + "user.email.verify.complete", ) diff --git a/db/session.py b/db/session.py index d23bc81..bd5b0c7 100644 --- a/db/session.py +++ b/db/session.py @@ -15,12 +15,30 @@ from pathlib import Path from typing import Optional -from sqlalchemy import create_engine +from sqlalchemy import create_engine, event from sqlalchemy.engine import Engine from sqlalchemy.orm import Session, sessionmaker from db.models import Base + +def _enable_sqlite_fk(engine: Engine) -> None: + """Turn on ``PRAGMA foreign_keys`` for SQLite connections. + + SQLite ignores ``ON DELETE CASCADE`` / ``SET NULL`` unless foreign-key + enforcement is enabled per-connection. Without this, account deletion + (which relies on cascade) would orphan child rows on SQLite while working + on Postgres — a dev/prod behaviour split. This makes them identical. + """ + if not str(engine.url).startswith("sqlite"): + return + + @event.listens_for(engine, "connect") + def _set_pragma(dbapi_connection, _record): # noqa: ANN001 + cursor = dbapi_connection.cursor() + cursor.execute("PRAGMA foreign_keys=ON") + cursor.close() + logger = logging.getLogger(__name__) _DEFAULT_SQLITE_PATH = Path(os.getenv("SQLITE_PATH", "./data/joboffer.db")) @@ -46,6 +64,7 @@ def get_engine() -> Engine: # can share the connection. connect_args = {"check_same_thread": False} if url.startswith("sqlite") else {} _engine = create_engine(url, connect_args=connect_args, future=True) + _enable_sqlite_fk(_engine) logger.info("DB engine created for %s", url.split("://", 1)[0]) return _engine @@ -94,6 +113,7 @@ def reset_engine_for_testing(url: str) -> None: poolclass=StaticPool, future=True, ) + _enable_sqlite_fk(_engine) _SessionLocal = sessionmaker(bind=_engine, expire_on_commit=False, future=True) _initialized = False init_db() diff --git a/services/account_export.py b/services/account_export.py new file mode 100644 index 0000000..2864686 --- /dev/null +++ b/services/account_export.py @@ -0,0 +1,135 @@ +"""GDPR-style "export all my data" — a single JSON bundle of everything a +user owns. Secrets (password hash, TOTP secret, token hashes, webhook +secrets) are deliberately excluded — this is the user's *data*, not their +credentials. + +Reuses the existing per-domain list functions so the export stays correct as +those evolve. Returns a JSON string ready for a download button. +""" + +from __future__ import annotations + +import json +from datetime import date, datetime +from typing import Any + +from services.audit import record as _audit + + +def _default(o: Any): + if isinstance(o, (datetime, date)): + return o.isoformat() + return str(o) + + +def build_export(user_id: int) -> dict: + """Assemble the full data bundle for ``user_id`` as a plain dict.""" + from services.api_tokens import list_for_user as list_tokens + from services.applications import list_applications + from services.auth import get_user + from services.master_cv import get_master_cv, list_revisions + from services.projects import list_projects + from services.sharing import list_shares_for_application + from services.stages import list_stages + from services.tailoring import list_artifacts + from services.telegram_link import get_link + from services.webhooks import list_webhooks + + user = get_user(user_id) + bundle: dict = { + "exported_at": datetime.utcnow().isoformat() + "Z", + "account": { + "user_id": user.id if user else user_id, + "email": user.email if user else None, + }, + "applications": [], + "master_cv": None, + "master_cv_revisions": [], + "projects": [], + "api_tokens": [], # metadata only (no secret) + "webhooks": [], # metadata only (no secret) + "telegram_link": None, + } + + for app in list_applications(user_id): + entry = { + "id": app.id, + "company_name": app.company_name, + "job_title": app.job_title, + "location": app.location, + "status": app.status, + "verdict": app.verdict, + "verdict_light": app.verdict_light, + "ats_score": app.ats_score, + "notes": app.notes, + "created_at": app.created_at, + "updated_at": app.updated_at, + "analysis": app.analysis_json, + "stages": [ + {"kind": s.kind, "occurred_on": s.occurred_on, + "notes": s.notes, "at_pipeline_stage": s.at_pipeline_stage} + for s in list_stages(user_id, app.id) + ], + "artifacts": [ + {"id": a.id, "kind": a.kind, "content": a.content, + "created_at": a.created_at, "meta": a.meta} + for a in list_artifacts(user_id, app.id) + ], + "shares": [ + {"id": sh.id, "token": sh.token, "expires_at": sh.expires_at, + "revoked_at": sh.revoked_at, "view_count": sh.view_count, + "include_artifacts": sh.include_artifacts} + for sh in list_shares_for_application(user_id, app.id) + ], + } + bundle["applications"].append(entry) + + cv = get_master_cv(user_id) + if cv is not None: + bundle["master_cv"] = { + "raw_text": cv.raw_text, + "structured": cv.structured, + "updated_at": cv.updated_at, + } + bundle["master_cv_revisions"] = [ + {"id": r.id, "reason": r.reason, "raw_text": r.raw_text, + "created_at": r.created_at} + for r in list_revisions(user_id) + ] + + bundle["projects"] = [ + {"id": p.id, "title": p.title, "role": p.role, "tech_stack": p.tech_stack, + "summary": p.summary, "highlights": p.highlights, "url": p.url} + for p in list_projects(user_id) + ] + + bundle["api_tokens"] = [ + {"id": t.id, "name": t.name, "prefix": t.prefix, + "created_at": t.created_at, "last_used_at": t.last_used_at, + "expires_at": t.expires_at, "revoked_at": t.revoked_at} + for t in list_tokens(user_id) + ] + + bundle["webhooks"] = [ + {"id": w.id, "url": w.url, "events": w.events, "active": w.active, + "created_at": w.created_at} + for w in list_webhooks(user_id) + ] + + link = get_link(user_id) + if link is not None: + bundle["telegram_link"] = { + "chat_id": link.chat_id, + "chat_username": link.chat_username, + "notify_on_stage": link.notify_on_stage, + "inactive_reminder_days": link.inactive_reminder_days, + } + + return bundle + + +def export_json(user_id: int) -> str: + """Return the user's full data bundle as an indented JSON string.""" + bundle = build_export(user_id) + _audit("user.account.export", user_id=user_id) + return json.dumps(bundle, indent=2, default=_default, ensure_ascii=False) diff --git a/services/auth.py b/services/auth.py index 578f225..2cbec77 100644 --- a/services/auth.py +++ b/services/auth.py @@ -159,6 +159,27 @@ def find_user_by_email(email: str) -> Optional[AuthedUser]: return AuthedUser(id=user.id, email=user.email) if user else None +def delete_account(user_id: int, password: str) -> None: + """Permanently delete a user and ALL their data. + + Gated by a current-password re-check. Deleting the ``User`` row cascades + (FK ``ondelete=CASCADE``) to applications, stages, artifacts, master CV + + revisions, projects, shares, webhooks, API tokens, 2FA, OAuth identities, + telegram link, reset tokens, and background analyses. Audit-logged before + deletion (the audit row's user_id is set NULL by its own + ``ondelete=SET NULL`` so the record survives the cascade). + """ + with get_session() as session: + user = session.get(User, user_id) + if user is None or not _verify_password(password, user.password_hash): + raise AuthError("Current password is incorrect.") + email = user.email + # Record the intent BEFORE the row vanishes. + _audit("user.account.delete", user_id=user_id, details={"email": email}) + session.delete(user) + session.commit() + + def get_user(user_id: int) -> Optional[AuthedUser]: with get_session() as session: user = session.get(User, user_id) diff --git a/tests/test_phase31_account_lifecycle.py b/tests/test_phase31_account_lifecycle.py new file mode 100644 index 0000000..39ff8ca --- /dev/null +++ b/tests/test_phase31_account_lifecycle.py @@ -0,0 +1,192 @@ +"""P0.3 (part 1): account deletion + data export + cascade integrity.""" + +from __future__ import annotations + +import json +import os +import sys +import unittest +from unittest import mock + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + + +def _fresh_db(): + from db.session import reset_engine_for_testing + from services.rate_limit import reset_backend_for_testing + reset_engine_for_testing("sqlite:///:memory:") + reset_backend_for_testing() + + +def _seed(user_email="u@x.com"): + """A user with data across many child tables, to test cascade + export.""" + from datetime import date + from services.applications import save_analysis + from services.auth import register_user + from services.api_tokens import issue + from services.master_cv import save_master_cv + from services.projects import create_project + from services.sharing import create_share + from services.stages import add_stage + from services.tailoring import save_artifact + from services.webhooks import register_webhook + + user = register_user(user_email, "longenough") + save_master_cv(user.id, "Jane Doe\nSkills: Python") + save_master_cv(user.id, "Jane Doe\nSkills: Python, AWS") # creates a revision + create_project(user.id, title="recsys", tech_stack="Python") + app = save_analysis( + user.id, + {"company_name": "Acme", "job_title": "Eng", "location": "Berlin"}, + {"final_report": "# r", "verdict": {"verdict": "Recommended", "light": "green"}, + "resume_analysis": {"ats_score": 70}}, + ) + add_stage(user.id, app.id, "applied", occurred_on=date(2026, 5, 1)) + save_artifact(user.id, app.id, "tailored_cv", "# CV", meta={"model": "fast"}) + create_share(user.id, app.id, ttl_days=7) + issue(user.id, "cli") + register_webhook(user.id, "https://x.com/h", ["stage.added"]) + return user, app + + +# --------------------------------------------------------------------------- +# SQLite FK pragma (cascade enforcement) +# --------------------------------------------------------------------------- + +class SqliteForeignKeyTests(unittest.TestCase): + def test_foreign_keys_pragma_enabled(self): + _fresh_db() + from sqlalchemy import text + from db.session import get_session + with get_session() as s: + val = s.execute(text("PRAGMA foreign_keys")).scalar() + self.assertEqual(val, 1) + + +# --------------------------------------------------------------------------- +# Account deletion +# --------------------------------------------------------------------------- + +class DeleteAccountTests(unittest.TestCase): + def setUp(self): + _fresh_db() + self.user, self.app = _seed() + + def test_wrong_password_rejected(self): + from services.auth import AuthError, delete_account + with self.assertRaises(AuthError): + delete_account(self.user.id, "wrongpassword") + # Still there. + from services.auth import get_user + self.assertIsNotNone(get_user(self.user.id)) + + def test_delete_removes_user_and_cascades_children(self): + from sqlalchemy import text + from db.session import get_session + from services.auth import delete_account, get_user + + delete_account(self.user.id, "longenough") + self.assertIsNone(get_user(self.user.id)) + + with get_session() as s: + # Tables that carry user_id directly. + user_scoped = [ + "applications", "application_artifacts", "application_shares", + "master_cvs", "master_cv_revisions", "projects", "api_tokens", + "webhooks", "telegram_links", "background_analyses", + ] + for tbl in user_scoped: + n = s.execute( + text(f"SELECT COUNT(*) FROM {tbl} WHERE user_id = :u"), + {"u": self.user.id}, + ).scalar() + self.assertEqual(n, 0, msg=f"{tbl} not cascaded ({n} rows left)") + # application_stages is app-scoped (no user_id) — the only app was + # the deleted user's, so the table must be empty (cascade from + # applications -> stages). + stages_left = s.execute(text("SELECT COUNT(*) FROM application_stages")).scalar() + self.assertEqual(stages_left, 0, msg="application_stages not cascaded") + + def test_delete_is_audited_and_audit_survives(self): + from services.audit import list_recent + from services.auth import delete_account + + delete_account(self.user.id, "longenough") + # The audit row's user_id is SET NULL by the cascade, but the record + # (with the email in details) survives. + recent = list_recent(limit=50) + match = next( + (e for e in recent + if e.kind == "user.account.delete" + and e.details.get("email") == "u@x.com"), + None, + ) + self.assertIsNotNone(match) + self.assertIsNone(match.user_id) # SET NULL on cascade + + def test_delete_only_affects_target_user(self): + from services.applications import list_applications + from services.auth import delete_account + + other, _ = _seed("other@x.com") + delete_account(self.user.id, "longenough") + # Other user's data is intact. + self.assertEqual(len(list_applications(other.id)), 1) + + +# --------------------------------------------------------------------------- +# Data export +# --------------------------------------------------------------------------- + +class ExportTests(unittest.TestCase): + def setUp(self): + _fresh_db() + self.user, self.app = _seed() + + def test_export_bundles_all_domains(self): + from services.account_export import build_export + + b = build_export(self.user.id) + self.assertEqual(b["account"]["email"], "u@x.com") + self.assertEqual(len(b["applications"]), 1) + app = b["applications"][0] + self.assertEqual(app["company_name"], "Acme") + self.assertEqual(len(app["stages"]), 1) + self.assertEqual(len(app["artifacts"]), 1) + self.assertEqual(len(app["shares"]), 1) + self.assertIsNotNone(b["master_cv"]) + self.assertEqual(len(b["master_cv_revisions"]), 1) + self.assertEqual(len(b["projects"]), 1) + self.assertEqual(len(b["api_tokens"]), 1) + self.assertEqual(len(b["webhooks"]), 1) + + def test_export_excludes_secrets(self): + """The bundle must not leak password hash, token hash, or webhook secret.""" + from services.account_export import export_json + + blob = export_json(self.user.id) + lowered = blob.lower() + self.assertNotIn("password_hash", lowered) + self.assertNotIn("token_hash", lowered) + # Webhook secret value must not appear: fetch it and assert absence. + from services.webhooks import list_webhooks + secret = list_webhooks(self.user.id)[0].secret + self.assertNotIn(secret, blob) + + def test_export_is_valid_json(self): + from services.account_export import export_json + + data = json.loads(export_json(self.user.id)) # must parse + self.assertIn("exported_at", data) + + def test_export_records_audit(self): + from services.account_export import export_json + from services.audit import list_for_user + + export_json(self.user.id) + kinds = {e.kind for e in list_for_user(self.user.id)} + self.assertIn("user.account.export", kinds) + + +if __name__ == "__main__": + unittest.main() From ed73f56420a1865b53bdeffa7271648db2769a17 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 7 Jun 2026 17:36:20 +0000 Subject: [PATCH 08/24] P0.3 (part 2): email verification on signup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Schema (migration 46b9602c99a1): - users.email_verified (Boolean). server_default=true backfills EXISTING rows so no one is locked out; the ORM default is False so new password signups start unverified. - email_verification_tokens: bcrypt-hashed, 24h, one-shot (same shape as password reset). services/email_verify.py: is_verified / start_verification (rate-limited resend, returns None when already verified) / complete_verification (single generic error for unknown-email/wrong/expired/used; idempotent if already verified). Audited request + complete. services/auth.py: - AuthedUser gains email_verified; register/authenticate/get_user/ find_user_by_email all populate it from the DB. - create_oauth_user sets email_verified=True (the provider verified the email) — OAuth users never see the banner. UI (app.py): - Signup triggers start_verification + send_verification_email (best-effort; never blocks signup). - An email-verification gate renders for unverified users: a banner with a "Resend email" button and a token-entry form. Informational by default; set REQUIRE_EMAIL_VERIFICATION=1 to hard-block app usage until verified (off by default so the live deploy / existing users aren't impeded). - A ?verify_token= deep link (from the emailed link) is consumed on load. services/notifications.send_verification_email (full link when APP_BASE_URL set, else the raw token). AUDIT_KINDS already extended in part 1. Tests (tests/test_phase32_email_verify.py - 13): new password user unverified / OAuth user verified; authenticate reports state; start+complete; start returns None when verified; one-shot (used token can't verify another account); wrong/expired/empty token rejected; token hash != raw; resend rate-limited; audit events. Plus a migration test that inserts a legacy user at the pre-feature revision and asserts the upgrade backfills it verified. Schema-drift guard still green (models == migrations). Full suite 506/506. --- app.py | 78 ++++++- db/models.py | 23 +++ .../46b9602c99a1_email_verification.py | 55 +++++ services/auth.py | 26 ++- services/email_verify.py | 110 ++++++++++ services/notifications.py | 16 ++ tests/test_phase32_email_verify.py | 195 ++++++++++++++++++ 7 files changed, 495 insertions(+), 8 deletions(-) create mode 100644 migrations/versions/46b9602c99a1_email_verification.py create mode 100644 services/email_verify.py create mode 100644 tests/test_phase32_email_verify.py diff --git a/app.py b/app.py index b093a64..ab9afd0 100644 --- a/app.py +++ b/app.py @@ -356,7 +356,16 @@ def render_auth() -> None: user = register_user(email, password) st.session_state.user_id = user.id st.session_state.user_email = user.email - st.success("Account created. Signing you in...") + # Kick off email verification (best-effort delivery). + try: + from services.email_verify import start_verification + from services.notifications import send_verification_email + tok = start_verification(user.id) + if tok is not None: + send_verification_email(user.email, tok) + except Exception: # noqa: BLE001 - never block signup + pass + st.success("Account created. Check your email to verify it.") st.rerun() except RateLimitExceeded as exc: st.error(str(exc)) @@ -406,6 +415,73 @@ def render_auth() -> None: st.stop() +# --------------------------------------------------------------------------- +# Email-verification gate / banner +# --------------------------------------------------------------------------- + +def _render_verification_gate() -> None: + """Show a verify-your-email banner for unverified accounts. + + Always informational; when REQUIRE_EMAIL_VERIFICATION=1 it hard-blocks the + app (st.stop) until the user verifies — otherwise it's a dismissible-by- + verifying banner that doesn't impede usage (so the live deploy isn't + broken for existing/unverified users). + """ + from services.email_verify import ( + EmailVerifyError, + complete_verification, + is_verified, + start_verification, + ) + + if is_verified(st.session_state.user_id): + return + + hard_gate = os.getenv("REQUIRE_EMAIL_VERIFICATION") == "1" + box = st.warning if hard_gate else st.info + box( + "📧 Please verify your email" + + (" to use the app." if hard_gate else " — check your inbox for the link.") + ) + col_a, col_b = st.columns([1, 2]) + with col_a: + if st.button("Resend email"): + try: + from services.notifications import send_verification_email + tok = start_verification(st.session_state.user_id) + if tok is not None: + send_verification_email(st.session_state.user_email, tok) + st.success("Verification email sent.") + except (EmailVerifyError, RateLimitExceeded) as exc: + st.error(str(exc)) + with col_b: + with st.form("verify_email_form"): + code = st.text_input("Verification token", key="verify_token_input") + if st.form_submit_button("Verify"): + try: + complete_verification(st.session_state.user_email, code) + st.success("Email verified. Thank you!") + st.rerun() + except EmailVerifyError as exc: + st.error(str(exc)) + if hard_gate: + st.stop() + + +# Consume a ?verify_token= deep link (from the emailed link) before rendering. +_vt = st.query_params.get("verify_token") +if _vt: + from services.email_verify import EmailVerifyError as _EVErr, complete_verification as _cv + try: + _cv(st.session_state.user_email, _vt) + st.success("Email verified. Thank you!") + except _EVErr as exc: + st.error(str(exc)) + st.query_params.pop("verify_token", None) + +_render_verification_gate() + + # --------------------------------------------------------------------------- # Authenticated layout # --------------------------------------------------------------------------- diff --git a/db/models.py b/db/models.py index 05ce661..6ca2bca 100644 --- a/db/models.py +++ b/db/models.py @@ -50,6 +50,10 @@ class User(Base): id: Mapped[int] = mapped_column(Integer, primary_key=True) email: Mapped[str] = mapped_column(String(255), unique=True, nullable=False, index=True) password_hash: Mapped[str] = mapped_column(String(255), nullable=False) + # New password signups start unverified (ORM default False). The migration + # backfills existing rows to True (server_default) so no one is locked out, + # and OAuth-created users are set True explicitly (provider verified email). + email_verified: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) applications: Mapped[list["Application"]] = relationship( @@ -119,6 +123,25 @@ class UserTwoFactor(Base): user: Mapped["User"] = relationship(back_populates="two_factor") +class EmailVerificationToken(Base): + """Short-lived email-verification token (bcrypt-hashed, like reset tokens). + + Created on signup; the user clicks the emailed link / pastes the token to + mark their account ``email_verified``. One-shot via ``used_at``. + """ + + __tablename__ = "email_verification_tokens" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + user_id: Mapped[int] = mapped_column( + ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True + ) + token_hash: Mapped[str] = mapped_column(String(255), nullable=False) + expires_at: Mapped[datetime] = mapped_column(DateTime, nullable=False) + used_at: Mapped[Optional[datetime]] = mapped_column(DateTime) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + + class OAuthIdentity(Base): """Links an external OAuth identity (Google / GitHub) to a local user. diff --git a/migrations/versions/46b9602c99a1_email_verification.py b/migrations/versions/46b9602c99a1_email_verification.py new file mode 100644 index 0000000..4cf7f5d --- /dev/null +++ b/migrations/versions/46b9602c99a1_email_verification.py @@ -0,0 +1,55 @@ +"""add users.email_verified + email_verification_tokens + +Revision ID: 46b9602c99a1 +Revises: 268857701205 +Create Date: 2026-06-07 00:00:00 +""" +from typing import Sequence, Union + +import sqlalchemy as sa +from alembic import op + +revision: str = "46b9602c99a1" +down_revision: Union[str, None] = "268857701205" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + # Add the column with server_default=true so EXISTING rows (which predate + # verification) are treated as verified and nobody is locked out. New rows + # are inserted by the ORM with email_verified=False explicitly. + with op.batch_alter_table("users") as batch: + batch.add_column( + sa.Column( + "email_verified", sa.Boolean(), + nullable=False, server_default=sa.true(), + ) + ) + + op.create_table( + "email_verification_tokens", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column( + "user_id", sa.Integer(), + sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=False, + ), + sa.Column("token_hash", sa.String(255), nullable=False), + sa.Column("expires_at", sa.DateTime(), nullable=False), + sa.Column("used_at", sa.DateTime()), + sa.Column("created_at", sa.DateTime(), nullable=False), + ) + op.create_index( + "ix_email_verification_tokens_user_id", + "email_verification_tokens", ["user_id"], + ) + + +def downgrade() -> None: + op.drop_index( + "ix_email_verification_tokens_user_id", + table_name="email_verification_tokens", + ) + op.drop_table("email_verification_tokens") + with op.batch_alter_table("users") as batch: + batch.drop_column("email_verified") diff --git a/services/auth.py b/services/auth.py index 2cbec77..cd0324e 100644 --- a/services/auth.py +++ b/services/auth.py @@ -50,6 +50,7 @@ class AuthedUser: id: int email: str two_factor_required: bool = False + email_verified: bool = True def _normalize_email(email: str) -> str: @@ -88,7 +89,7 @@ def register_user(email: str, password: str) -> AuthedUser: session.commit() session.refresh(user) _audit("user.register", user_id=user.id, details={"email": email}) - return AuthedUser(id=user.id, email=user.email) + return AuthedUser(id=user.id, email=user.email, email_verified=user.email_verified) def authenticate_user(email: str, password: str) -> AuthedUser: @@ -125,9 +126,10 @@ def authenticate_user(email: str, password: str) -> AuthedUser: ) return AuthedUser( id=user.id, email=user.email, two_factor_required=True, + email_verified=user.email_verified, ) _audit("user.login.success", user_id=user.id, details={"email": email}) - return AuthedUser(id=user.id, email=user.email) + return AuthedUser(id=user.id, email=user.email, email_verified=user.email_verified) def create_oauth_user(email: str) -> AuthedUser: @@ -144,19 +146,29 @@ def create_oauth_user(email: str) -> AuthedUser: with get_session() as session: existing = session.execute(select(User).where(User.email == email)).scalar_one_or_none() if existing is not None: - return AuthedUser(id=existing.id, email=existing.email) - user = User(email=email, password_hash=_hash_password(secrets.token_urlsafe(32))) + return AuthedUser(id=existing.id, email=existing.email, + email_verified=existing.email_verified) + # OAuth users are verified by construction — the provider verified the + # email before returning it to us. + user = User( + email=email, + password_hash=_hash_password(secrets.token_urlsafe(32)), + email_verified=True, + ) session.add(user) session.commit() session.refresh(user) - return AuthedUser(id=user.id, email=user.email) + return AuthedUser(id=user.id, email=user.email, email_verified=True) def find_user_by_email(email: str) -> Optional[AuthedUser]: email = _normalize_email(email) with get_session() as session: user = session.execute(select(User).where(User.email == email)).scalar_one_or_none() - return AuthedUser(id=user.id, email=user.email) if user else None + return ( + AuthedUser(id=user.id, email=user.email, email_verified=user.email_verified) + if user else None + ) def delete_account(user_id: int, password: str) -> None: @@ -185,7 +197,7 @@ def get_user(user_id: int) -> Optional[AuthedUser]: user = session.get(User, user_id) if user is None: return None - return AuthedUser(id=user.id, email=user.email) + return AuthedUser(id=user.id, email=user.email, email_verified=user.email_verified) def change_password(user_id: int, current_password: str, new_password: str) -> None: diff --git a/services/email_verify.py b/services/email_verify.py new file mode 100644 index 0000000..613caae --- /dev/null +++ b/services/email_verify.py @@ -0,0 +1,110 @@ +"""Email verification — bcrypt-hashed, one-shot, expiring tokens. + +Created on signup; the user verifies by pasting the token (or clicking the +emailed link). Same security shape as password reset: only the hash is +stored, a single generic error covers all failure modes, success is one-shot. + +Gating is the caller's choice: ``is_verified`` lets the UI show a banner, and +the app can hard-block usage when ``REQUIRE_EMAIL_VERIFICATION=1``. OAuth +users are created already-verified (the provider verified the email), and +existing pre-feature accounts were backfilled verified by the migration. +""" + +from __future__ import annotations + +import secrets +from datetime import datetime, timedelta +from typing import Optional + +import bcrypt +from sqlalchemy import select + +from db.models import EmailVerificationToken, User +from db.session import get_session +from services.audit import record as _audit +from services.rate_limit import RateLimiter, RateLimitExceeded + +VERIFY_TOKEN_TTL = timedelta(hours=24) +_TOKEN_BYTES = 32 + +# Cap resend spam. +_REQUEST_LIMITER = RateLimiter("email_verify_request", max_attempts=5, window_seconds=3600) + + +class EmailVerifyError(ValueError): + """User-facing failure (invalid/expired/used token).""" + + +def _hash(token: str) -> str: + return bcrypt.hashpw(token.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") + + +def _verify(token: str, hashed: str) -> bool: + try: + return bcrypt.checkpw(token.encode("utf-8"), hashed.encode("utf-8")) + except (ValueError, TypeError): + return False + + +def is_verified(user_id: int) -> bool: + with get_session() as session: + user = session.get(User, user_id) + return bool(user and user.email_verified) + + +def start_verification(user_id: int) -> Optional[str]: + """Issue a verification token for the user. Returns the raw token, or None + if the account is already verified (no-op).""" + decision = _REQUEST_LIMITER.check(str(user_id)) + if not decision.allowed: + raise RateLimitExceeded(decision.retry_after) + + with get_session() as session: + user = session.get(User, user_id) + if user is None: + raise EmailVerifyError("Account not found.") + if user.email_verified: + return None + raw = secrets.token_urlsafe(_TOKEN_BYTES) + session.add( + EmailVerificationToken( + user_id=user_id, + token_hash=_hash(raw), + expires_at=datetime.utcnow() + VERIFY_TOKEN_TTL, + ) + ) + session.commit() + _audit("user.email.verify.request", user_id=user_id) + return raw + + +def complete_verification(email: str, token: str) -> None: + """Consume a verification token and mark the account verified. + + Single generic error for unknown-email / wrong / expired / used token. + """ + generic = EmailVerifyError("Verification link is invalid or expired.") + email = (email or "").strip().lower() + token = (token or "").strip() + if not token: + raise generic + + with get_session() as session: + user = session.execute(select(User).where(User.email == email)).scalar_one_or_none() + if user is None: + raise generic + if user.email_verified: + return # already done — idempotent success + candidates = session.execute( + select(EmailVerificationToken) + .where(EmailVerificationToken.user_id == user.id) + .where(EmailVerificationToken.used_at.is_(None)) + .where(EmailVerificationToken.expires_at > datetime.utcnow()) + ).scalars().all() + match = next((t for t in candidates if _verify(token, t.token_hash)), None) + if match is None: + raise generic + match.used_at = datetime.utcnow() + user.email_verified = True + session.commit() + _audit("user.email.verify.complete", user_id=user.id) diff --git a/services/notifications.py b/services/notifications.py index 4e79976..c1156af 100644 --- a/services/notifications.py +++ b/services/notifications.py @@ -20,6 +20,22 @@ def _reset_link_or_token(token: str) -> str: return f"Reset token: {token}" +def send_verification_email(email: str, token: str) -> bool: + """Email an email-verification token/link. Best-effort (False if no SMTP).""" + base = os.getenv("APP_BASE_URL") + instruction = ( + f"{base.rstrip('/')}/?verify_token={token}" if base + else f"Verification token: {token}" + ) + body = ( + "Welcome to JobOffer Scanner! Confirm your email to finish setting up " + "your account.\n\n" + f"{instruction}\n\n" + "This link expires in 24 hours. If you didn't sign up, ignore this email.\n" + ) + return send_email(email, "Verify your JobOffer Scanner email", body) + + def send_password_reset_email(email: str, token: str) -> bool: """Email a password-reset token/link. Best-effort (False if no SMTP).""" instruction = _reset_link_or_token(token) diff --git a/tests/test_phase32_email_verify.py b/tests/test_phase32_email_verify.py new file mode 100644 index 0000000..67562c3 --- /dev/null +++ b/tests/test_phase32_email_verify.py @@ -0,0 +1,195 @@ +"""P0.3 (part 2): email verification.""" + +from __future__ import annotations + +import os +import subprocess +import sys +import tempfile +import unittest +from datetime import datetime, timedelta +from pathlib import Path + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + + +def _fresh_db(): + from db.session import reset_engine_for_testing + from services.rate_limit import reset_backend_for_testing + reset_engine_for_testing("sqlite:///:memory:") + reset_backend_for_testing() + + +class RegistrationVerificationStateTests(unittest.TestCase): + def setUp(self): + _fresh_db() + + def test_new_password_user_is_unverified(self): + from services.auth import register_user + from services.email_verify import is_verified + + user = register_user("u@x.com", "longenough") + self.assertFalse(user.email_verified) + self.assertFalse(is_verified(user.id)) + + def test_oauth_user_is_verified_on_creation(self): + from services.auth import create_oauth_user + from services.email_verify import is_verified + + user = create_oauth_user("oauth@x.com") + self.assertTrue(user.email_verified) + self.assertTrue(is_verified(user.id)) + + def test_authenticate_reports_verification_state(self): + from services.auth import authenticate_user, register_user + from services.email_verify import complete_verification, start_verification + + register_user("u@x.com", "longenough") + self.assertFalse(authenticate_user("u@x.com", "longenough").email_verified) + # Verify, then a fresh login reflects it. + tok = start_verification(authenticate_user("u@x.com", "longenough").id) + complete_verification("u@x.com", tok) + self.assertTrue(authenticate_user("u@x.com", "longenough").email_verified) + + +class VerificationFlowTests(unittest.TestCase): + def setUp(self): + _fresh_db() + from services.auth import register_user + self.user = register_user("u@x.com", "longenough") + + def test_start_then_complete(self): + from services.email_verify import complete_verification, is_verified, start_verification + + tok = start_verification(self.user.id) + self.assertIsNotNone(tok) + complete_verification("u@x.com", tok) + self.assertTrue(is_verified(self.user.id)) + + def test_start_returns_none_when_already_verified(self): + from services.email_verify import complete_verification, start_verification + + complete_verification("u@x.com", start_verification(self.user.id)) + self.assertIsNone(start_verification(self.user.id)) + + def test_token_is_one_shot(self): + from services.email_verify import ( + EmailVerifyError, complete_verification, start_verification, + ) + + tok = start_verification(self.user.id) + complete_verification("u@x.com", tok) + # Account is now verified -> complete is idempotent (no raise), but the + # token itself is consumed. Verify a *fresh unverified* user can't reuse + # someone else's used token. + from services.auth import register_user + other = register_user("o@x.com", "longenough") # noqa: F841 + with self.assertRaises(EmailVerifyError): + complete_verification("o@x.com", tok) + + def test_wrong_token_rejected(self): + from services.email_verify import EmailVerifyError, complete_verification, start_verification + + start_verification(self.user.id) + with self.assertRaises(EmailVerifyError): + complete_verification("u@x.com", "totally-wrong") + + def test_expired_token_rejected(self): + from sqlalchemy import select + from db.models import EmailVerificationToken + from db.session import get_session + from services.email_verify import ( + EmailVerifyError, complete_verification, start_verification, + ) + + tok = start_verification(self.user.id) + with get_session() as s: + row = s.execute(select(EmailVerificationToken)).scalar_one() + row.expires_at = datetime.utcnow() - timedelta(minutes=1) + s.commit() + with self.assertRaises(EmailVerifyError): + complete_verification("u@x.com", tok) + + def test_empty_token_rejected(self): + from services.email_verify import EmailVerifyError, complete_verification + + with self.assertRaises(EmailVerifyError): + complete_verification("u@x.com", "") + + def test_token_hash_not_raw(self): + from sqlalchemy import select + from db.models import EmailVerificationToken + from db.session import get_session + from services.email_verify import start_verification + + tok = start_verification(self.user.id) + with get_session() as s: + row = s.execute(select(EmailVerificationToken)).scalar_one() + self.assertNotEqual(row.token_hash, tok) + self.assertTrue(row.token_hash.startswith("$2")) + + def test_resend_rate_limited(self): + from services.email_verify import start_verification + from services.rate_limit import RateLimitExceeded + + for _ in range(5): + start_verification(self.user.id) + with self.assertRaises(RateLimitExceeded): + start_verification(self.user.id) + + def test_audit_events_recorded(self): + from services.audit import list_for_user + from services.email_verify import complete_verification, start_verification + + complete_verification("u@x.com", start_verification(self.user.id)) + kinds = {e.kind for e in list_for_user(self.user.id)} + self.assertIn("user.email.verify.request", kinds) + self.assertIn("user.email.verify.complete", kinds) + + +class MigrationTests(unittest.TestCase): + def test_existing_users_backfilled_verified(self): + """The migration must backfill pre-existing rows to verified (so nobody + is locked out), while the table + column exist.""" + from sqlalchemy import create_engine, inspect, text + + project_root = Path(__file__).resolve().parents[1] + with tempfile.TemporaryDirectory() as tmp: + db_path = Path(tmp) / "m.db" + url = f"sqlite:///{db_path.as_posix()}" + env = dict(os.environ) + env["DATABASE_URL"] = url + + # Migrate to just BEFORE email verification, insert a legacy user, + # then migrate up and assert the backfill marked it verified. + def _alembic(*args): + return subprocess.run( + [sys.executable, "-m", "alembic", *args], + cwd=project_root, env=env, capture_output=True, text=True, + ) + + r = _alembic("upgrade", "268857701205") # pre-verification head + self.assertEqual(r.returncode, 0, msg=r.stderr) + + eng = create_engine(url) + with eng.begin() as c: + c.execute(text( + "INSERT INTO users (email, password_hash, created_at) " + "VALUES ('legacy@x.com', 'x', :ts)" + ), {"ts": datetime.utcnow()}) + + r = _alembic("upgrade", "head") + self.assertEqual(r.returncode, 0, msg=r.stderr) + + with eng.connect() as c: + verified = c.execute(text( + "SELECT email_verified FROM users WHERE email='legacy@x.com'" + )).scalar() + self.assertEqual(verified, 1) # backfilled True + + tables = set(inspect(eng).get_table_names()) + self.assertIn("email_verification_tokens", tables) + + +if __name__ == "__main__": + unittest.main() From 5c413e27fe90788a85e33223a1eb1e1c2ac973de Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 7 Jun 2026 17:37:35 +0000 Subject: [PATCH 09/24] docs: mark P0 roadmap items done in CLAUDE.md All four P0 items shipped (Redis-backed cache+checkpoint, width="stretch" migration, account lifecycle: verification+deletion+export, schema-drift guard). P1 is now the top priority. Refreshed module/migration/table/test counts (29 service modules, 15 migrations, 19 tables, 506 Python tests). --- CLAUDE.md | 45 +++++++++++++++++++++++---------------------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 97528d3..fe52abb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -28,21 +28,22 @@ agents/ LangGraph pipeline: orchestrator + per-stage agents tools/ LLM-facing tools + ingestion job_tools, company_tools, salary_tools, resume_tools, data_sources, url_ingest, browser_scraper (Playwright, optional) -services/ Business logic (28 modules) — the bulk of the app +services/ Business logic (29 modules) — the bulk of the app auth, totp, oauth, api_tokens, rate_limit, audit (identity/security) applications, stages, analytics, timeline, background_analysis (tracking) master_cv, projects, tailoring, constraint_check, suggestions, pdf_export (CV/artifacts) sharing, webhooks, telegram_link, notifications, email, reminders (integrations) - checkpoint, bulk_import, system_test, analysis_runner + checkpoint, bulk_import, system_test, analysis_runner, + account_export, email_verify db/ SQLAlchemy 2.0 models + session (StaticPool-aware) api/ FastAPI app: routes, bearer auth, security headers bot/ Telegram bot: handlers (pure) + main (runtime) worker/ Celery app + tasks + CLI runners (reminders, metrics_dump) utils/ llm, config, security, diff, verdict, logging_setup, metrics, timing, cache -migrations/ Alembic (14 revisions, 18 tables) +migrations/ Alembic (15 revisions, 19 tables) chrome-extension/ MV3 extension calling the REST API (JS, Node-tested) deploy/ Caddyfile + nginx reverse-proxy examples (CSP/HSTS) -tests/ 28 files, 468 Python tests + 9 JS (extract.test.mjs) +tests/ 31 files, 506 Python tests + 9 JS (extract.test.mjs) ``` ## How to run @@ -64,7 +65,7 @@ celery -A worker.celery_app:app worker python -m worker.reminders # Tests -python -m unittest discover -s tests # ~5 min, 468 tests +python -m unittest discover -s tests # ~5 min, 506 tests node chrome-extension/extract.test.mjs # 9 JS tests # Migrations @@ -139,23 +140,23 @@ same canned "TechCorp" text regardless of input) to the current product: The app is feature-complete and deployed, but several things stand between it and "production-grade for real multi-user traffic." Prioritized: -### P0 — do before scaling past one instance / real users -1. **State that's in-process won't survive horizontal scaling.** `utils/cache.SimpleCache`, - `services/checkpoint`, `utils/metrics`, and the default rate-limit backend - are per-process. Rate-limit already supports Redis; do the same for the - cache + checkpoint store (or accept single-instance Reserved-VM only). -2. **`use_container_width` is deprecated and past its removal date - (2025-12-31).** 5 call sites in `app.py`. Migrate to `width="stretch"` - before a Streamlit bump breaks the UI. -3. **Account lifecycle gaps:** no email verification on signup, no "delete my - account / export all my data" (GDPR). FK cascades exist, but expose the - action. `RESET_TOKEN_SURFACE_IN_UI` and reset-token logging must be off in - prod. -4. **Schema drift guard.** App boots with `create_all` by default; prod uses - Alembic. Add a CI check (`alembic check` / autogenerate-diff) so models and - migrations can't silently diverge. - -### P1 — hardening + confidence +### P0 — ✅ DONE (all four shipped) +1. ✅ **Horizontal-scaling state.** `utils/cache` and `services/checkpoint` + gained Redis backends behind `REDIS_URL` (same detection + graceful + fallback as rate-limiting). Metrics aggregation across instances is still + per-process — that's folded into P1 "observability shipping". +2. ✅ **`use_container_width` → `width="stretch"`** (all 5 sites); the + AppTest smoke test confirms no deprecation warnings. +3. ✅ **Account lifecycle:** email verification on signup (soft banner; + `REQUIRE_EMAIL_VERIFICATION=1` to hard-gate), `delete_account` + (password-gated, cascades — SQLite FK pragma now ON so cascade matches + Postgres), full data export (`services/account_export`, secrets excluded), + and reset-token logging now gated behind `RESET_TOKEN_SURFACE_IN_UI`. +4. ✅ **Schema-drift guard** (`tests/test_phase29_schema_drift.py`): applies + all migrations and asserts no add/remove table-or-column drift vs the + models. Runs in CI via the unittest job. + +### P1 — hardening + confidence (now the top priority) 5. **CI quality gates:** add lint (ruff), type-check (mypy), security scan (bandit + pip-audit), and a coverage floor. Run the JS tests in CI (add setup-node). Bump `actions/checkout`/`setup-python` off Node 20. From 7a0e3208953a966f8df57e762c8bb4bee93984fb Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 7 Jun 2026 18:55:50 +0000 Subject: [PATCH 10/24] P1: CI quality gates (ruff, mypy, bandit, pip-audit, coverage, JS) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New CI jobs in .github/workflows/tests.yml: - lint: ruff check (E/F/W/I). Config in pyproject ([tool.ruff]); fixed all 39 findings (36 unused imports auto-removed, 3 unused vars) + applied isort ordering across the tree. - typecheck: mypy on the app packages (services/utils/db/tools/agents/api/ bot/worker), ignore_missing_imports + import-untyped disabled (we check OUR code, not third-party signatures). Fixed the 4 genuine errors (email.py None args, url_ingest None.strip guard, analytics/resume_analyzer annotations). Clean across 71 files. - security: bandit -ll (hard gate, currently clean) + pip-audit (ADVISORY/ continue-on-error — transitive-dep CVEs in the base image are outside our control). - js-tests: setup-node + node chrome-extension/extract.test.mjs (the JS suite now runs in CI, not just locally). - test: now runs under coverage with --fail-under=80 on the logic packages (actual ~87%). app.py is excluded from the gate (dense Streamlit UI, only smoke-tested). - FORCE_JAVASCRIPT_ACTIONS_TO_NODE24=true silences the Node-20 action deprecation ahead of the forced cutover. pyproject: [tool.ruff]/[tool.mypy]/[tool.bandit] config + a [project. optional-dependencies] dev extra (ruff/mypy/bandit/pip-audit/coverage/ types-requests). uv.lock regenerated. Also extended the Postgres migration job's expected-tables assertion with email_verification_tokens (added in P0.3). No behaviour change — lint/type fixes are import cleanups + annotations + None-guards. Full suite 506/506 green; ruff/mypy/bandit clean; coverage gate passes. --- .coverage | Bin 0 -> 69632 bytes .github/workflows/tests.yml | 84 +++- agents/__init__.py | 6 +- agents/orchestrator.py | 1 - agents/resume_analyzer.py | 2 +- api/routes.py | 1 - app.py | 123 +++-- db/models.py | 7 +- migrations/env.py | 5 +- pyproject.toml | 39 ++ services/analysis_runner.py | 1 - services/analytics.py | 2 +- services/auth.py | 1 - services/bulk_import.py | 3 +- services/constraint_check.py | 2 +- services/email.py | 8 +- services/rate_limit.py | 2 +- services/reminders.py | 5 +- services/stages.py | 2 +- services/suggestions.py | 3 +- services/system_test.py | 4 +- services/tailoring.py | 5 +- services/timeline.py | 4 - services/totp.py | 3 +- tests/test_phase11_units.py | 2 +- tests/test_phase12_pdf.py | 5 +- tests/test_phase14_units.py | 3 +- tests/test_phase15_units.py | 6 +- tests/test_phase18_units.py | 4 +- tests/test_phase19_units.py | 9 +- tests/test_phase20_units.py | 4 +- tests/test_phase21_units.py | 5 +- tests/test_phase22_units.py | 5 +- tests/test_phase23_units.py | 5 +- tests/test_phase24_units.py | 6 +- tests/test_phase25_units.py | 1 + tests/test_phase28_ui_smoke.py | 2 +- tests/test_phase31_account_lifecycle.py | 6 +- tests/test_phase32_email_verify.py | 16 +- tests/test_phase3_units.py | 3 +- tests/test_phase4_units.py | 6 +- tests/test_phase5_units.py | 2 +- tests/test_phase8_units.py | 2 +- tests/test_phase9_units.py | 10 +- tools/__init__.py | 2 +- tools/company_tools.py | 2 +- tools/resume_tools.py | 4 +- tools/url_ingest.py | 4 +- utils/__init__.py | 2 +- utils/config.py | 2 +- utils/metrics.py | 3 +- uv.lock | 600 +++++++++++++++++++++++- 52 files changed, 890 insertions(+), 144 deletions(-) create mode 100644 .coverage diff --git a/.coverage b/.coverage new file mode 100644 index 0000000000000000000000000000000000000000..03c15c77925ed03ba9fcd21354692ab12461a436 GIT binary patch literal 69632 zcmeHw33wD$+HQ4Kr}wS`0)!Aqnk``o>Fg_HVc)|hAPAjKrxIGyU9r29fDk$@&LiI6 zks1AG&>u0()%l%!eHa`a2^vCY)I08kJ38V_NIG7ZXf%rkvygP^epS6DNV?~?1q@zMmifeyp~VgNCK82FcA zz_v{xj);sDJWylN7MIf&lU7HYTz{1-x34bPxmvZeV8y1@Dp#0lp-ctG(xs{bm5HfV zRnR6?slJ?6>5V0Noz|i^mZ>ZUX^(cLnJ(e_EC_>Mi&ISC@!Xk4Ujir#T?SE9nDhp% z>4@qOeI%Y&aHnRW4_jOT5DBd>GjbZLg>LvFm5DB;O|(%*n_X5c)R!!hEjnS9i6g?p z1rO1Dp0p+%{4XDq8wl`aWqm0`q+?7aob|;ftx9-W=)}u=B9Rm0J^IP+J&P zx!%ZU(`eRP^o&tOAEtGc7P{mIGZ@d2<~e{o|J*=aMO=o8Tu66Xe(dH~5~1DLnjSZOE*%I~c-RB(j@2v@=u=1#~vVJ(b1vq6{550s@ZzhjEiLpfKX zE>xvae_ti-E&OXoiy4?3&US)pzt+G z@JI3BWQjN;CPwhkeY~S^^k|Cp7PI$6I>u?d!FO;S?*5(qhN~rGorJ4J<>e}-l&>-z zTIDJn@MixyqxO)YHE|V9#kdv0(*IU(uMJMyB!H!CrK)bSRHdG*YUc5Cdqp$vqg%;5m8Zs2c*0kxl79} z#A95@Q<6W>jCyVvXsx-@RW_=Bg1~yTttq8&NuDrT5+T5ELm z4S-m0hBWnN6>r1sy;7bp4)YN%j4y!Zq_dq0)Kk7n~RjT4Ra3zv8-KSFF(X zbCr`z$JK}cP!$K2(hOB}T%4Xr-FLYb%M*V>1#rT}YS5OrsykOGelb=bq;HGP)f=tS zT4;;jK&v?0mQ(+AOi%Ulydw3rFbnyeMmh^ouahV zN=iunKk^x}l*}aKl>N$gm8X=Y%1q^aWw_!i#a|V#DxOdrR_s<}Dkyok{Lk_;@(Ovn ze4$(=8Y6;O8yv8IK63>)_P~as zFoE=EQ;Vwd^7Gf#euka2&6y;?3m%&@dVL_;`nm)JJzI;92Q@W5vyK%(+)A#5|HS!N00wW4Y`8+TM5jS z4pu8(;ENc;7ixgr?Hagwv+Gwwb*%HDW~*XEEyl5Y#sObL6~4fB3_h*CW);UB0L`rj zaO@mgMUVF7ouUSNhWk32^H`e*XLD!k+lH;q(XXn7llOz-{QVH+;=ZqXB47Bn@wZ9$ zKv2m&ICgVdNiEwqG}K2u$lC2{K}w&)V8usSX$8xsua3%ES;VQPn!5Mxy)nJ&Zo#FR_ETj|EO|GmMc<9*fB#** zd(b9U zHuqAIg`kmIh+~$Y4O(x+NCxvJ^|C}C`wWYdTi{mo7QFV#vRhw$=On^6!}Y?=_ilU| ztBn@0r)rO09}t9Z;sQ6}*Y@puT4kScLoCFeet!N&2;8s{_^|IQ|Dw+No&dMT+6Elo zY1omGo7PdnX>C0xp0WY7VmIIie_Qx?G-eUyW7+A^>me+6J&xV~S)cXks|QL3PL2+C zvmdftguUiZ4$mj#u+LqGmJ&o0Wdg0|azv^xO zQZg9+&PJG9ZQXpOp7n4>mereJwIGMW&f3;aM!p8ooE+%a1N(foJ zGW{iI|0#j$F|L}fESAq%0iml_>{7kRQpc|L#Qmb-@z$7*`aVJLC#N0n=jF3`QL+M1 znO^YD>F;OZ@_aa-k^fG7|D5A&gg4~dc-%=L*^2SYd&FFK^(a|PM^2PvV zJ$^+%Mkm_JZpMg~bK1)V5z9a(F2le4tjQXgc;Xb+)P6iqaBJXLOb*=0&%tXC*xqAD zs3!IqACshKgMu*|9MxWDyLp){G^(JXIX)cctjpi($Y8^vLN*<* zXN4n^vA&uv$LEm;*&!8^H!BNp*;(Kxk%w<-9$>Bcw{Be&?eBGbEliY7ipqq$nVEQg z#(;D%tmZfBskPXY_U`V;j^-x?Gc(|3dItV#>1ZAMrusXly`!$8@9UutSXPjg4)-kS zc>eA|X(BsBLF&C9IIKf>R_*ZU>gWnPJGXa$S~c&NT+8@}Me~VC*X$3z>UezgeetX` z&Z0DE|K&pXsIm%Eovq#c@vz`*L`Duic}XhV-II!6`}wx9Ui+>aC2X@I*{?Mj*gWvh1gI4)&qLKq(QC2#Se`c>d2%M{bZtM@_*h z@IqnxF-oL{8>Bj6aRSI)3HZ%h??HPrC>|-nD%eWr&{u`M&2`NW<+D(Q@*x4qOMi-r zTnf6WOL5G(wrJBE2a3w+xdqD7F+YeY66p})Z~ z95{uooUH^V;sR#mV?`!X~BWt(ZY94CN6D(Q?fjbxC&i?#Io~(OvrNdd+YhCTw+?3lhG_SU2F-D zQ|Ck4i|6BC?#I9Tt8}4CaP?W~TLYqb5K7Jy%$*Bz&0KJH0ahLhAMM8fv*zh1ZNuHr z6V1bKwhceS%0zQG-8lk<3gk=`o}JV)`l2v12Chsoo$9(iHYW+|?Y~&r;;b6(XQ*St zjRq@me7L)bS@JYiIs97dK=+0I>V~5|ZMI?iQG8J}Aa_P{$e8we$HlHHLv>EIBfWQM z$lR@Q4t!MFRsZVn-kBI`k{HV^; z)C~ti5YP|b1wtDtLo1q$4O^5p{ zrsFlXvWAxo9}rAyb=&)no;HW{^6-$e!Fr`GavEr)PU|$;&$nGwGOrA^)OV$KTnTG8 z7fzW9w_>N_=hT?0;M1>1&c1oRU|~3fZ4ZaSu6*RrpMEY$uU};P4A#bKJbn^{?VSV} z6hC#b@nyU6Mz_8709(~k6?4hi)zxnsHrTtEb|~NW(NWfT879f7j6Yy9^BjT@8f&uif9* z3_D-0uWuZ9vHto~W!FbXuM9uWj`X*jYI0VGFH!<_r_$qE#+Hxl2K(&6{tMk#49s=A zv(*tj*j*iSi8bPC1*jG&I!`xe^?vj`!?c4@7rLnt=KTIcEk{~x_SRkPw))nn!voz7 zoLxdn4gi%L$ZqVq(cgFkkC#EfUKwZTm6~sw)wlLoTVAej>{5=@IlG*lM#mLHbO&|0 zqo;)!aBR+zg7#r4}-zAxTC z+R}3MqOz*&=x~mst2?*7jl5wU2v>;#zCzsjxw-wLs`?Agu8q|;rcKj!(Qv5Rc)t1X z{Zp2UxCBI<_G9F+6OHwT6ZI#KH(YP3I+4*kvo~t+eEqP!waXeasA;hew=(RmsKbt$ zhW!mEm}=^VwHlul2Jq~#&hN4+qFNk(sV5xmyW7)xm4kwZGWHb43*qiwVduLYO+R;B z%&GXctE=j(yx#7k?SE!k42Rp7Ub)e1>}iDmYK*KfoB-{GMCWUtD2wjWwH#o|HgpIR za0onrLuuKn9jy&5U9XIES84{Xcm2L4dhnvNv+KNFdF<>N8`J*o@%GW4*u?^&RJy10 zbK-he*F^)RD82N`k)uano@Qk4J=9}!u*?fJ!ymQn@7K4qNV)xgnBHU5Fm;paqQ0OU z)W_8SrQV@lr!G@3Q@^L4qs~!JQjbypMm?0mQ(M z$N)EG6qJ_of~I*+ytw;r zUhLV!i`~0-_DC|+jy~cD=!KQd9h^+FE(%H#imWX*tn4w z8#eG_{d!)kTgQvFYk9F|4KG%&=EbU2yjZ!C7b{lqqM(2m`T4xa%i~3EE-#kz6Klb; zW&Bl64llB^d6AXHi_A=3WMuFnJ)IY6X}m~H;X+=-#qlCGmKO^a@M8XaUd)@vi@9@oF=q}hR4QJ?#PA|I znisQY^J3O4UPMLlV&+U?fu9@$-2OkB|NrEQ1sQ}GKnx%T5Cez- z!~kLdF@P9A3?K#&1Bihil>zSke>DI9Q7J`{AqEfwhyla^VgNCK7(fgl1`q>?0mJ}e z;3vm`Oc;%2V{ha53_+{lKLv~+6?;2ur{b!@fIWr z|3f`Y6;cZF8u{O_K`5DDK@tkUaf_<|y1sQ|!^Y~sj-0B=$i zjLD*bbZL{;!fgH~^ZxbMcW zKpF6ss@VeN#Tk^7L6|2@zzZp^EI*{t8@S>HTy~(+@!~2%P(dubj2ozILkf(Z^}(dx??lipYcNu`Iqfz7^Sbxb14f{T)dQYnY% zwgjr9UZRYQMPI7dX+3$~95m8Gm(yh?twB?+Hy(mCHwOARsy9u(Nigfp8dD|r)l|T4 z2)baQw(1U5FnS~B4{HM%>uw*++H$RFOs!iJbSW9MW(#f7=&B&S1j!yO@&`*PUuYwO zE23hp?ogSDsWg_jS^?kzV!kVAdrY)JZ!B?D?5#mNs6}s}p`2()sxWA8(pHw}Ihq#* z-EM0uEe8RxFq5bZjty-^MY*5%#RcsL&|uTxc?RCV*mz?9gz1$Os|`#EUCvRxU@4&q zq->_mW@rRJdwv3;4W#YYbk18w)J&-Etpqw~W1!msN7nE@4Qb5{x;Xt(oC80m_QxOe zNfd|}_=z$QXt?C9C0d;hno5hWFV_X#wD5hQriwP{OOHV1Dvl+#O;|IbDFU^kpj$`A z-Pmb@uC>*4@j-?;#5F<(0u9NyA(oleRhsk`&ieg9_YZvMYSHVsRPG68Am`4;zCg_) zXA$&U@QHJXd2cZG`?XSgf^OI$8I6TGMDruC-6_PO2@B2ZDCUD&_fTqAAm6c?73(x#<5bXsmGtG+GO zL~o|K=l_?8evMIYP$%IR{U(tgl8=)+NJ{yk@|VhWN}=Ly#iNQHiW%}&`Tvxc$(P86 zM8B53CVND7w``uYOM*)qq>qSGr3a)*l3S8=$y<^#$!T%3s99VhJ_A1ijSj>BVgNCK z7(fh!z(Ankw1r{H&FW$kQw{x{#;h}GEBF1$HQpuId(m;zkZdkbil;Z=2a*z8LM2*@R%2!= zO|T^c<|PFxM^{3gJq}M|iGkR2!Ti`$hcZIfSMUp)niAT;fRUGDm2AA1&UlLv`Isn_oXCj#;xPbSSPfFhZaYY z#WMWbSR%u9#qCFdKG_! z@BJ-PU~;?MD$kK)vPPLjmMHyR`l{3_T_u%Du1X%4?3T{i(8VLuPs7dBtmExaszShzzto9G~3Bl{^{?w$P zOdB`EOiK(jx13fz&sbs&&5*{0+{FZB>(;Yw50*ebI~w_7|Z?cp%J4C2&vXnI|M5u4Flob^s z)HhVkni(S0H&V@t3=!%ZsIHhH#B3pLHr+m1S{ngzga_*#TnVTA@MNiAIz%K6DWdU{ zrL1WoQsEnSub3Jt6}L~8a>F5x|H5P`ZwlavP#73DS<0RqLPZ@nS<0RiD%R(M*;J@l zpATk}p<;c7maPmG>zgcPD?-Kk_F1#!A^MqLva%49P4YE}+0sz4z7{cC5-Qf$BxZ|4 z#roRBY*DCKU!#~E7An@~k_Ez0Ta%>m`~R6lfLZAHt}Ds2|DTPAYPg?+z(eyvceY#| zPV)IBH~*g_U4v17rcO~BDuMityhJ`oZXjnUKUJPr-Va~Yo2F<}oK@%*$qHQlk^Fb^ zWAZif>9S8`7i1@8dt@=v&!m5Zm4G$>(6k+a5Cez-!~kLdF@P9A4E&QakWm_7Y00(J zcl!e?DRh9v754)hV;)#ZC<(A~?gn`tSjo}_n0t8FuRJ@F-j~!eiUVZK3mvy1nxG9} zqiY4w`;g3nA_Chs(LC1mtWKgP*kwY`gYYQ_0x;~&f!~Ah3Ht+BKkh;J)O&(mxb=S! ze(^p6+c$BZ^=kKn@bP;CtPhTP5PtF9LB#BSS2AHw5P9`m+DqFV>}u$khvt)a5!j)L zGV3h|-$V0xcLiGA@PdB$1-7)E0c>^GlyQ$I?e^x7LTYwD@ zH^z_p)UCm~nSVklg~8SUzxVMHw**_!_=*qP9hsX0%zeFOHU90+Mur5I5asj*#zNM`V;ILlf#=LTxxh4P` JcYNja{{!tB>n{KR literal 0 HcmV?d00001 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 2acdab6..5920b61 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -6,9 +6,71 @@ on: pull_request: branches: [main] +# Opt JS-based actions (checkout, setup-python) into the Node 24 runtime so the +# Node 20 deprecation warnings go away ahead of the forced cutover. +env: + FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true" + jobs: + lint: + name: ruff lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + cache: pip + - run: pip install ruff>=0.6 + - run: ruff check . + + typecheck: + name: mypy + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + cache: pip + - name: Install deps + type stubs + run: | + python -m pip install --upgrade pip + pip install -e ".[telegram,worker,dev]" + - run: mypy + + security: + name: bandit + pip-audit + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + cache: pip + - run: pip install "bandit>=1.7" "pip-audit>=2.7" + # bandit is a hard gate (we keep it clean at medium+high severity). + # Explicit -x (rather than pyproject config) avoids needing bandit[toml]. + - run: bandit -r . -ll -x ./tests,./migrations,./.venv + # pip-audit is ADVISORY: transitive-dep CVEs are often outside our + # control (base-image setuptools/wheel, etc.), so it informs without + # blocking the build. + - name: pip-audit (advisory) + continue-on-error: true + run: pip-audit --progress-spinner off || true + + js-tests: + name: chrome-extension JS tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "22" + - run: node chrome-extension/extract.test.mjs + test: - name: unittest (Python ${{ matrix.python-version }}) + name: unittest + coverage (Python ${{ matrix.python-version }}) runs-on: ubuntu-latest strategy: fail-fast: false @@ -26,13 +88,10 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip - # Telegram extra so the bot-handler tests can run. - pip install -e ".[telegram]" - - - name: Show installed package versions - run: pip freeze | sort + # Telegram extra so the bot-handler tests can run; dev extra for coverage. + pip install -e ".[telegram,dev]" - - name: Run unit tests + - name: Run unit tests under coverage # Strip any provider keys the CI environment may inject so the demo # smoke test exercises the no-key path deterministically. env: @@ -40,7 +99,15 @@ jobs: OPENAI_API_KEY: "" FEATHERLESS_API_KEY: "" LLM_PROVIDER: "" - run: python -m unittest discover -s tests -v + run: coverage run -m unittest discover -s tests + + - name: Enforce coverage floor on the logic packages + # app.py (the dense Streamlit UI) is only smoke-tested, so the gate is + # on the service/logic packages where coverage is meaningful (~87%). + run: | + coverage report \ + --include="services/*,utils/*,db/*,tools/*,agents/*,api/*,bot/*,worker/*" \ + --fail-under=80 migrations-postgres: name: alembic up/down/up on Postgres @@ -101,6 +168,7 @@ jobs: "telegram_links", "audit_events", "background_analyses", "user_two_factor", "application_shares", "api_tokens", "webhooks", "webhook_deliveries", "oauth_identities", + "email_verification_tokens", } missing = required - tables assert not missing, f"missing tables after migrate: {missing}" diff --git a/agents/__init__.py b/agents/__init__.py index b2f0bfd..b427e07 100644 --- a/agents/__init__.py +++ b/agents/__init__.py @@ -1,8 +1,4 @@ -from . import job_analyzer -from . import company_analyzer -from . import salary_analyzer -from . import report_generator -from . import orchestrator +from . import company_analyzer, job_analyzer, orchestrator, report_generator, salary_analyzer __all__ = [ 'job_analyzer', diff --git a/agents/orchestrator.py b/agents/orchestrator.py index b5fd6cd..21666a6 100644 --- a/agents/orchestrator.py +++ b/agents/orchestrator.py @@ -11,7 +11,6 @@ salary_analyzer, ) from services.checkpoint import ( - CHECKPOINT_STAGES, CheckpointPayload, get_store, ) diff --git a/agents/resume_analyzer.py b/agents/resume_analyzer.py index 4517724..d3780b7 100644 --- a/agents/resume_analyzer.py +++ b/agents/resume_analyzer.py @@ -21,7 +21,7 @@ def analyze(state: Dict) -> Dict: job_details = state.get("job_details") or {} requirements = job_details.get("requirements_analysis") or {} - required_skills = [] + required_skills: list = [] if isinstance(requirements, dict): required_skills = ( requirements.get("technical_skills") diff --git a/api/routes.py b/api/routes.py index 36c2e72..d91d345 100644 --- a/api/routes.py +++ b/api/routes.py @@ -35,7 +35,6 @@ from services.auth import get_user from services.master_cv import MasterCVError, get_master_cv, save_master_cv - router = APIRouter(prefix="/v1") diff --git a/app.py b/app.py index ab9afd0..f80e8c0 100644 --- a/app.py +++ b/app.py @@ -19,17 +19,21 @@ save_analysis, update_status, ) +from services.auth import ( + AuthError, + authenticate_user, + change_password, + complete_password_reset, + register_user, + request_password_reset, +) from services.background_analysis import ( BackgroundAnalysisError, - delete as delete_background_analysis, - list_for_user as list_background_analyses, refresh_all_pending, submit_background_analysis, ) -from services.checkpoint import ( - CHECKPOINT_STAGES, - compute_key as compute_checkpoint_key, - get_store as get_checkpoint_store, +from services.background_analysis import ( + delete as delete_background_analysis, ) from services.bulk_import import ( BulkImportError, @@ -40,6 +44,14 @@ save_applications, save_projects, ) +from services.checkpoint import ( + compute_key as compute_checkpoint_key, +) +from services.checkpoint import ( + get_store as get_checkpoint_store, +) +from services.constraint_check import ConstraintCheck +from services.constraint_check import summarize as summarize_check from services.master_cv import ( MasterCVError, delete_master_cv, @@ -52,6 +64,11 @@ save_master_cv, save_master_cv_from_upload, ) +from services.notifications import ( + notify_stage_added, + send_password_reset_email, +) +from services.pdf_export import PDFExportError, markdown_to_pdf from services.projects import ( ProjectError, create_project, @@ -59,6 +76,12 @@ list_projects, update_project, ) +from services.rate_limit import RateLimitExceeded +from services.reminders import ( + set_inactive_threshold, + snooze_application, + unsnooze_application, +) from services.stages import ( QUICK_ACTIONS, StageError, @@ -66,8 +89,6 @@ delete_stage, list_stages, ) -from services.constraint_check import ConstraintCheck, summarize as summarize_check -from services.pdf_export import PDFExportError, markdown_to_pdf from services.suggestions import ( apply_skill_addition, build_suggestions, @@ -81,58 +102,55 @@ list_artifacts, recheck_artifact, ) -from services.auth import ( - AuthError, - authenticate_user, - change_password, - complete_password_reset, - register_user, - request_password_reset, -) -from services.notifications import ( - notify_stage_added, - send_password_reset_email, +from services.telegram_link import ( + TelegramLinkError, + get_link, + issue_binding_token, + set_notify_on_stage, + unlink, ) -from services.webhooks import ( - WebhookError, - delete_webhook, - dispatch_event_background, - list_deliveries as list_webhook_deliveries, - list_webhooks, - register_webhook, - set_active as set_webhook_active, +from services.timeline import ( + STAGE_COLORS, + cross_application_swimlane, + per_application_timeline, + points_to_records, ) from services.totp import ( TOTPError, +) +from services.totp import ( confirm_setup as totp_confirm_setup, +) +from services.totp import ( disable as totp_disable, +) +from services.totp import ( is_enabled as totp_is_enabled, - pending_setup as totp_pending_setup, +) +from services.totp import ( remaining_backup_codes as totp_backup_codes_left, +) +from services.totp import ( start_setup as totp_start_setup, +) +from services.totp import ( verify_login as totp_verify_login, ) -from services.rate_limit import RateLimitExceeded -from services.reminders import ( - set_inactive_threshold, - snooze_application, - unsnooze_application, +from services.webhooks import ( + WebhookError, + delete_webhook, + dispatch_event_background, + list_webhooks, + register_webhook, ) -from services.telegram_link import ( - TelegramLinkError, - get_link, - issue_binding_token, - set_notify_on_stage, - unlink, +from services.webhooks import ( + list_deliveries as list_webhook_deliveries, +) +from services.webhooks import ( + set_active as set_webhook_active, ) from tools.resume_tools import extract_resume_text from tools.url_ingest import fetch_job_posting, is_url -from services.timeline import ( - STAGE_COLORS, - cross_application_swimlane, - per_application_timeline, - points_to_records, -) from utils.config import check_environment_setup, print_environment_status from utils.diff import inline_diff_html, unified_diff from utils.logging_setup import configure as configure_logging @@ -471,7 +489,8 @@ def _render_verification_gate() -> None: # Consume a ?verify_token= deep link (from the emailed link) before rendering. _vt = st.query_params.get("verify_token") if _vt: - from services.email_verify import EmailVerifyError as _EVErr, complete_verification as _cv + from services.email_verify import EmailVerifyError as _EVErr + from services.email_verify import complete_verification as _cv try: _cv(st.session_state.user_email, _vt) st.success("Email verified. Thank you!") @@ -502,8 +521,14 @@ def _render_verification_gate() -> None: with st.sidebar.expander("🔑 API tokens"): from services.api_tokens import ( ApiTokenError, + ) + from services.api_tokens import ( issue as issue_api_token, + ) + from services.api_tokens import ( list_for_user as list_api_tokens, + ) + from services.api_tokens import ( revoke as revoke_api_token, ) st.caption( @@ -643,6 +668,7 @@ def _render_verification_gate() -> None: else: try: import io + import qrcode img = qrcode.make(st.session_state.totp_setup_uri) @@ -684,7 +710,8 @@ def _render_verification_gate() -> None: with st.sidebar.expander("🗄 Privacy & account"): from services.account_export import export_json - from services.auth import AuthError as _AuthError, delete_account + from services.auth import AuthError as _AuthError + from services.auth import delete_account st.caption("Download everything we hold about you, or delete your account.") st.download_button( @@ -1845,6 +1872,8 @@ def _matches(rec) -> bool: ShareError, create_share, list_shares_for_application, + ) + from services.sharing import ( revoke as revoke_share, ) if st.checkbox("🔗 Share read-only link", key=f"share_expand_{rec.id}"): diff --git a/db/models.py b/db/models.py index 6ca2bca..f5e3f67 100644 --- a/db/models.py +++ b/db/models.py @@ -13,17 +13,18 @@ from sqlalchemy import ( JSON, - BigInteger as sa_BigInt, Boolean, - Column, Date, DateTime, ForeignKey, + Index, Integer, String, Text, UniqueConstraint, - Index, +) +from sqlalchemy import ( + BigInteger as sa_BigInt, ) from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship diff --git a/migrations/env.py b/migrations/env.py index 05addf6..edc498e 100644 --- a/migrations/env.py +++ b/migrations/env.py @@ -7,14 +7,15 @@ from __future__ import annotations import os + +# Make ``db.models`` importable when alembic runs from the project root. +import sys from logging.config import fileConfig from pathlib import Path from alembic import context from sqlalchemy import engine_from_config, pool -# Make ``db.models`` importable when alembic runs from the project root. -import sys sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from db.models import Base # noqa: E402 diff --git a/pyproject.toml b/pyproject.toml index 5d14e75..48b828d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,6 +35,14 @@ telegram = ["python-telegram-bot>=21.0"] worker = ["celery>=5.3.0", "redis>=5.0.0"] browser = ["playwright>=1.44.0"] pdf = ["fpdf2>=2.7.0"] +dev = [ + "ruff>=0.6", + "mypy>=1.10", + "bandit>=1.7", + "pip-audit>=2.7", + "coverage>=7.5", + "types-requests", +] # This is an APPLICATION, not an importable library. It's installed (pip # install -e . / uv sync) only to pull the dependencies above — the source is @@ -45,3 +53,34 @@ pdf = ["fpdf2>=2.7.0"] # otherwise errors out on our many top-level dirs (agents/, services/, db/, …). [tool.setuptools] py-modules = [] + +# --- Quality tooling -------------------------------------------------------- + +[tool.ruff] +line-length = 100 +target-version = "py311" +exclude = ["migrations/versions"] # generated-ish; alembic templates + +[tool.ruff.lint] +# F (pyflakes) + E/W (pycodestyle) + I (isort). Pragmatic for an app. +select = ["E", "F", "W", "I"] +ignore = [ + "E501", # line length is handled by the formatter, not enforced hard + "E741", # ambiguous var names (l/I) — a few in chart code +] + +[tool.mypy] +python_version = "3.11" +ignore_missing_imports = true # langchain/openai/celery/etc. ship no stubs +# import-untyped fires for libs that *have* stubs (requests) but aren't +# resolved here; we type-check OUR code, not third-party signatures. +disable_error_code = ["import-untyped"] +warn_unused_ignores = false +check_untyped_defs = false +# Scope: the app packages we actively maintain types for. Tests + migrations +# are intentionally excluded (heavy mocking / generated code). +files = ["services", "utils", "db", "tools", "agents", "api", "bot", "worker"] + +[tool.bandit] +exclude_dirs = ["tests", "migrations", ".venv"] + diff --git a/services/analysis_runner.py b/services/analysis_runner.py index a098f95..868de11 100644 --- a/services/analysis_runner.py +++ b/services/analysis_runner.py @@ -14,7 +14,6 @@ from typing import Callable, Optional from services.rate_limit import ANALYSIS_LIMITER, RateLimitExceeded -from worker.tasks import analyze_payload logger = logging.getLogger(__name__) diff --git a/services/analytics.py b/services/analytics.py index d217fff..5688a83 100644 --- a/services/analytics.py +++ b/services/analytics.py @@ -190,7 +190,7 @@ def compute_funnel(data) -> List[FunnelRow]: ``recruiter_screen`` but two logged ``phone_screen``, phone_screen's conversion is computed against ``applied``, not against 0. """ - counts = Counter() + counts: Counter = Counter() for _, stages in data: kinds = _stage_kinds_seen(stages) for stage in PIPELINE_STAGES: diff --git a/services/auth.py b/services/auth.py index cd0324e..b00ad16 100644 --- a/services/auth.py +++ b/services/auth.py @@ -8,7 +8,6 @@ from __future__ import annotations import logging -import os import re import secrets from dataclasses import dataclass diff --git a/services/bulk_import.py b/services/bulk_import.py index 0a14f19..021eed3 100644 --- a/services/bulk_import.py +++ b/services/bulk_import.py @@ -24,12 +24,11 @@ import io import json import re -from dataclasses import dataclass from datetime import date as date_cls from datetime import datetime from typing import List, Optional -from db.models import ALL_STAGE_KINDS, APPLICATION_STATUSES +from db.models import APPLICATION_STATUSES from services.applications import save_analysis from services.projects import ProjectRecord, create_project from services.stages import add_stage diff --git a/services/constraint_check.py b/services/constraint_check.py index 7da62fd..2e203a8 100644 --- a/services/constraint_check.py +++ b/services/constraint_check.py @@ -21,7 +21,7 @@ import re from dataclasses import dataclass, field -from typing import Iterable, List, Optional, Set +from typing import List, Optional, Set # --------------------------------------------------------------------------- # Token-extraction patterns diff --git a/services/email.py b/services/email.py index f9fe35c..cf3fd3b 100644 --- a/services/email.py +++ b/services/email.py @@ -47,10 +47,12 @@ def send_email(to: str, subject: str, body: str) -> bool: return False msg = build_message(to, subject, body) - host = os.getenv("SMTP_HOST") + # email_configured() above guarantees these are present; the "" defaults + # are only to satisfy the type checker (str, not str | None). + host = os.getenv("SMTP_HOST", "") port = int(os.getenv("SMTP_PORT", "587")) - username = os.getenv("SMTP_USERNAME") - password = os.getenv("SMTP_PASSWORD") + username = os.getenv("SMTP_USERNAME", "") + password = os.getenv("SMTP_PASSWORD", "") use_tls = os.getenv("SMTP_USE_TLS", "1") == "1" try: diff --git a/services/rate_limit.py b/services/rate_limit.py index a866df2..35951e4 100644 --- a/services/rate_limit.py +++ b/services/rate_limit.py @@ -23,7 +23,7 @@ import time from collections import defaultdict, deque from dataclasses import dataclass -from typing import Deque, Dict, Optional +from typing import Deque, Dict logger = logging.getLogger(__name__) diff --git a/services/reminders.py b/services/reminders.py index ad864c9..c9830a4 100644 --- a/services/reminders.py +++ b/services/reminders.py @@ -22,17 +22,16 @@ import logging from dataclasses import dataclass from datetime import date as date_cls -from datetime import datetime, timedelta +from datetime import timedelta from typing import List, Optional -from sqlalchemy import asc, desc, select +from sqlalchemy import asc, select from db.models import ( TERMINAL_NEGATIVE_STAGES, Application, ApplicationStage, TelegramLink, - User, ) from db.session import get_session from services.telegram_link import send_to_chat diff --git a/services/stages.py b/services/stages.py index 6cb1afa..3198c4b 100644 --- a/services/stages.py +++ b/services/stages.py @@ -19,7 +19,7 @@ from datetime import datetime from typing import List, Optional -from sqlalchemy import asc, desc, select +from sqlalchemy import asc, select from db.models import ( ALL_STAGE_KINDS, diff --git a/services/suggestions.py b/services/suggestions.py index 6ba5207..4398dc2 100644 --- a/services/suggestions.py +++ b/services/suggestions.py @@ -15,8 +15,7 @@ import re from dataclasses import dataclass -from datetime import datetime -from typing import List, Optional +from typing import List from services.constraint_check import ConstraintCheck from services.master_cv import MasterCVError, get_master_cv, save_master_cv diff --git a/services/system_test.py b/services/system_test.py index 9b984fe..3be1f1c 100644 --- a/services/system_test.py +++ b/services/system_test.py @@ -13,10 +13,9 @@ import os import smtplib import time -from dataclasses import dataclass, field +from dataclasses import dataclass from typing import List, Optional - # --------------------------------------------------------------------------- # Result container # --------------------------------------------------------------------------- @@ -50,6 +49,7 @@ def _probe_database() -> TestResult: t0 = time.time() try: from sqlalchemy import text as sa_text + from db.session import get_session session = get_session() session.execute(sa_text("SELECT 1")) diff --git a/services/tailoring.py b/services/tailoring.py index d2a926a..6f7386f 100644 --- a/services/tailoring.py +++ b/services/tailoring.py @@ -17,7 +17,7 @@ from datetime import datetime from typing import List, Optional -from sqlalchemy import asc, desc, select +from sqlalchemy import desc, select from db.models import ( ARTIFACT_KINDS, @@ -26,12 +26,11 @@ ) from db.session import get_session from services.constraint_check import ConstraintCheck, check_tailored_output -from services.master_cv import MasterCVError, get_master_cv +from services.master_cv import get_master_cv from services.projects import projects_as_text from utils.llm import get_completion from utils.security import wrap_untrusted - # Canonical cover-letter tone presets surfaced in the UI. COVER_LETTER_TONES = ( "professional", diff --git a/services/timeline.py b/services/timeline.py index 9d782ba..b185488 100644 --- a/services/timeline.py +++ b/services/timeline.py @@ -17,7 +17,6 @@ from __future__ import annotations -from collections import defaultdict from dataclasses import dataclass from datetime import date as date_cls from typing import Dict, List, Optional @@ -25,15 +24,12 @@ from sqlalchemy import asc, select from db.models import ( - ALL_STAGE_KINDS, PIPELINE_STAGES, - TERMINAL_NEGATIVE_STAGES, Application, ApplicationStage, ) from db.session import get_session - # Color hexes chosen to read on both light and dark Streamlit themes. # Pipeline stages: cooler -> warmer as the user advances; terminals stand out. STAGE_COLORS: Dict[str, str] = { diff --git a/services/totp.py b/services/totp.py index edb3783..40ba9d1 100644 --- a/services/totp.py +++ b/services/totp.py @@ -35,8 +35,7 @@ import logging import secrets from dataclasses import dataclass -from datetime import datetime -from typing import List, Optional, Tuple +from typing import Tuple import bcrypt import pyotp diff --git a/tests/test_phase11_units.py b/tests/test_phase11_units.py index e824101..cc5534b 100644 --- a/tests/test_phase11_units.py +++ b/tests/test_phase11_units.py @@ -8,7 +8,6 @@ import tempfile import unittest from pathlib import Path -from unittest import mock sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) @@ -210,6 +209,7 @@ def test_reason_tag_is_recorded(self): def test_revisions_newest_first(self): import time + from services.master_cv import list_revisions, save_master_cv save_master_cv(self.user.id, "v1") diff --git a/tests/test_phase12_pdf.py b/tests/test_phase12_pdf.py index 82c6b5e..5c2ad4b 100644 --- a/tests/test_phase12_pdf.py +++ b/tests/test_phase12_pdf.py @@ -60,7 +60,7 @@ def test_empty_input_renders_blank_pdf(self): self.assertTrue(bytes(out[:5]) == b"%PDF-") def test_heading_and_inline_bold_parsing(self): - from services.pdf_export import _BOLD_RE, _HEADING_RE, _split_inline_bold + from services.pdf_export import _HEADING_RE, _split_inline_bold m = _HEADING_RE.match("### Senior ML Engineer — Acme") self.assertIsNotNone(m) @@ -86,9 +86,10 @@ class PDFExportMissingDepTests(unittest.TestCase): def test_raises_when_fpdf_missing(self): """When fpdf2 isn't installed, markdown_to_pdf must raise a clear PDFExportError instead of silently returning bytes-like junk.""" - import services.pdf_export as mod from unittest import mock + import services.pdf_export as mod + # Force the import inside markdown_to_pdf to fail. real_import = __builtins__["__import__"] if isinstance(__builtins__, dict) else __builtins__.__import__ diff --git a/tests/test_phase14_units.py b/tests/test_phase14_units.py index 7a8b83e..8b14fe3 100644 --- a/tests/test_phase14_units.py +++ b/tests/test_phase14_units.py @@ -171,8 +171,9 @@ def test_plain_text_master_cv_renders(self): out = markdown_to_pdf(plain, title="Master CV") self.assertEqual(bytes(out[:5]), b"%PDF-") # Spot-check that the content survived to the PDF via pypdf extraction. - from pypdf import PdfReader import io + + from pypdf import PdfReader text = PdfReader(io.BytesIO(out)).pages[0].extract_text() for needle in ("Jane Doe", "Python", "Acme"): self.assertIn(needle, text) diff --git a/tests/test_phase15_units.py b/tests/test_phase15_units.py index b7156ca..fe880bc 100644 --- a/tests/test_phase15_units.py +++ b/tests/test_phase15_units.py @@ -82,6 +82,8 @@ def test_bind_token_is_one_shot(self): complete_binding(chat_id=2, raw_token=token) # already used def test_expired_token_rejected(self): + from sqlalchemy import select + from db.models import TelegramLinkBindingToken from db.session import get_session from services.telegram_link import ( @@ -89,7 +91,6 @@ def test_expired_token_rejected(self): complete_binding, issue_binding_token, ) - from sqlalchemy import select token = issue_binding_token(self.user.id) # Manually expire. @@ -101,10 +102,11 @@ def test_expired_token_rejected(self): complete_binding(chat_id=1, raw_token=token) def test_raw_token_is_not_persisted(self): + from sqlalchemy import select + from db.models import TelegramLinkBindingToken from db.session import get_session from services.telegram_link import issue_binding_token - from sqlalchemy import select token = issue_binding_token(self.user.id) with get_session() as s: diff --git a/tests/test_phase18_units.py b/tests/test_phase18_units.py index 7696cca..641367f 100644 --- a/tests/test_phase18_units.py +++ b/tests/test_phase18_units.py @@ -260,8 +260,8 @@ def test_register_creates_audit_event(self): self.assertIn("user.register", kinds) def test_login_success_and_failure_recorded(self): - from services.auth import AuthError, authenticate_user from services.audit import list_for_user + from services.auth import AuthError, authenticate_user with self.assertRaises(AuthError): authenticate_user("u@x.com", "wrongwrongwrong") @@ -272,8 +272,8 @@ def test_login_success_and_failure_recorded(self): self.assertIn("user.login.failure", kinds) def test_login_failure_records_event_even_for_unknown_email(self): - from services.auth import AuthError, authenticate_user from services.audit import list_recent + from services.auth import AuthError, authenticate_user with self.assertRaises(AuthError): authenticate_user("nobody@nowhere.com", "longenough") diff --git a/tests/test_phase19_units.py b/tests/test_phase19_units.py index a44cef3..d66c22c 100644 --- a/tests/test_phase19_units.py +++ b/tests/test_phase19_units.py @@ -81,9 +81,10 @@ def test_submit_returns_none_when_enqueue_returns_none(self): ) def test_list_for_user_returns_newest_first(self): - import services.background_analysis as mod import time + import services.background_analysis as mod + with mock.patch.object(mod, "async_enabled", return_value=True), \ mock.patch.object(mod, "enqueue_analysis", side_effect=["t1", "t2", "t3"]): mod.submit_background_analysis(self.user.id, "p1", {"company_name": "A"}) @@ -223,7 +224,7 @@ def test_refresh_all_pending_skips_terminal_rows(self): # Submit a second row. with mock.patch.object(mod, "async_enabled", return_value=True), \ mock.patch.object(mod, "enqueue_analysis", return_value="task-2"): - second = mod.submit_background_analysis( + mod.submit_background_analysis( self.user.id, "p2", {"company_name": "Acme"}, ) @@ -260,9 +261,9 @@ def test_cleanup_removes_old_terminal_rows(self): with mock.patch.object(mod, "async_enabled", return_value=True), \ mock.patch.object(mod, "enqueue_analysis", side_effect=["old", "fresh"]): - old_rec = mod.submit_background_analysis( + mod.submit_background_analysis( self.user.id, "p", {"company_name": "A"}) - fresh_rec = mod.submit_background_analysis( + mod.submit_background_analysis( self.user.id, "p", {"company_name": "B"}) with get_session() as s: diff --git a/tests/test_phase20_units.py b/tests/test_phase20_units.py index 498de59..0874ac6 100644 --- a/tests/test_phase20_units.py +++ b/tests/test_phase20_units.py @@ -8,7 +8,6 @@ import tempfile import unittest from pathlib import Path -from unittest import mock sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) @@ -109,10 +108,11 @@ def test_confirm_twice_is_rejected(self): def test_secret_persisted_as_base32(self): """Stored secret must be the same one pyotp can generate codes from.""" + from sqlalchemy import select + from db.models import UserTwoFactor from db.session import get_session from services.totp import start_setup - from sqlalchemy import select r = start_setup(self.user.id, "u@x.com") with get_session() as s: diff --git a/tests/test_phase21_units.py b/tests/test_phase21_units.py index c859b41..7a6c343 100644 --- a/tests/test_phase21_units.py +++ b/tests/test_phase21_units.py @@ -142,9 +142,9 @@ def test_get_view_includes_artifacts_when_requested(self): """include_artifacts=True must surface tailored CVs / cover letters.""" from unittest import mock + import services.tailoring as tailoring from services.master_cv import save_master_cv from services.sharing import create_share, get_view - import services.tailoring as tailoring save_master_cv(self.user.id, "Jane Doe\nSkills: Python, AWS") with mock.patch.object(tailoring, "get_completion", return_value="# tailored content"): @@ -171,10 +171,11 @@ def test_get_view_rejects_revoked_token(self): get_view(share.token) def test_get_view_rejects_expired_token(self): + from sqlalchemy import select + from db.models import ApplicationShare from db.session import get_session from services.sharing import ShareError, create_share, get_view - from sqlalchemy import select share = create_share(self.user.id, self.app.id, ttl_days=7) # Manually expire. diff --git a/tests/test_phase22_units.py b/tests/test_phase22_units.py index 4993873..4efa86e 100644 --- a/tests/test_phase22_units.py +++ b/tests/test_phase22_units.py @@ -69,6 +69,7 @@ def test_no_ttl_means_no_expiry(self): def test_list_newest_first(self): import time + from services.api_tokens import issue, list_for_user issue(self.user.id, "a") @@ -125,8 +126,7 @@ def test_verify_rejects_empty(self): self.assertIsNone(verify(" ")) def test_verify_rejects_revoked(self): - from services.api_tokens import revoke, verify - from services.api_tokens import list_for_user + from services.api_tokens import list_for_user, revoke, verify token_id = list_for_user(self.user.id)[0].id revoke(self.user.id, token_id) @@ -174,6 +174,7 @@ def setUp(self): def _client(self): from fastapi.testclient import TestClient + from api.main import create_app return TestClient(create_app()) diff --git a/tests/test_phase23_units.py b/tests/test_phase23_units.py index f974efc..0d37e04 100644 --- a/tests/test_phase23_units.py +++ b/tests/test_phase23_units.py @@ -79,7 +79,10 @@ def test_list_user_scoped(self): def test_set_active_and_delete_cross_user_blocked(self): from services.webhooks import ( - WebhookError, delete_webhook, register_webhook, set_active, + WebhookError, + delete_webhook, + register_webhook, + set_active, ) wh = register_webhook(self.user.id, "https://x.com", ["stage.added"]) diff --git a/tests/test_phase24_units.py b/tests/test_phase24_units.py index 43871f0..a075816 100644 --- a/tests/test_phase24_units.py +++ b/tests/test_phase24_units.py @@ -84,10 +84,11 @@ def setUp(self): _fresh_db() def test_new_identity_creates_user_and_links(self): + from sqlalchemy import select + from db.models import OAuthIdentity, User from db.session import get_session from services.oauth import resolve_identity - from sqlalchemy import select user = resolve_identity("google", "sub-123", "new@example.com") self.assertEqual(user.email, "new@example.com") @@ -107,11 +108,12 @@ def test_existing_identity_logs_in_same_user(self): self.assertEqual(u1.id, u2.id) def test_email_match_links_new_identity_to_existing_user(self): + from sqlalchemy import select + from db.models import OAuthIdentity from db.session import get_session from services.auth import register_user from services.oauth import resolve_identity - from sqlalchemy import select existing = register_user("shared@example.com", "longenough") # OAuth login with a DIFFERENT provider id but the same email links. diff --git a/tests/test_phase25_units.py b/tests/test_phase25_units.py index 178d6b9..87a4fc0 100644 --- a/tests/test_phase25_units.py +++ b/tests/test_phase25_units.py @@ -65,6 +65,7 @@ def setUp(self): def _client(self): from fastapi.testclient import TestClient + from api.main import create_app return TestClient(create_app()) diff --git a/tests/test_phase28_ui_smoke.py b/tests/test_phase28_ui_smoke.py index dbfc927..a4edfdc 100644 --- a/tests/test_phase28_ui_smoke.py +++ b/tests/test_phase28_ui_smoke.py @@ -172,8 +172,8 @@ def test_full_authenticated_ui_renders_without_error(self): def test_share_view_renders_without_error(self): """The public ?share= view (renders before the auth gate) must work.""" user = _seed_dense_account() - from services.sharing import list_shares_for_application from services.applications import list_applications + from services.sharing import list_shares_for_application app_id = list_applications(user.id)[0].id token = list_shares_for_application(user.id, app_id)[0].token diff --git a/tests/test_phase31_account_lifecycle.py b/tests/test_phase31_account_lifecycle.py index 39ff8ca..f0b7566 100644 --- a/tests/test_phase31_account_lifecycle.py +++ b/tests/test_phase31_account_lifecycle.py @@ -6,7 +6,6 @@ import os import sys import unittest -from unittest import mock sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) @@ -21,9 +20,10 @@ def _fresh_db(): def _seed(user_email="u@x.com"): """A user with data across many child tables, to test cascade + export.""" from datetime import date + + from services.api_tokens import issue from services.applications import save_analysis from services.auth import register_user - from services.api_tokens import issue from services.master_cv import save_master_cv from services.projects import create_project from services.sharing import create_share @@ -57,6 +57,7 @@ class SqliteForeignKeyTests(unittest.TestCase): def test_foreign_keys_pragma_enabled(self): _fresh_db() from sqlalchemy import text + from db.session import get_session with get_session() as s: val = s.execute(text("PRAGMA foreign_keys")).scalar() @@ -82,6 +83,7 @@ def test_wrong_password_rejected(self): def test_delete_removes_user_and_cascades_children(self): from sqlalchemy import text + from db.session import get_session from services.auth import delete_account, get_user diff --git a/tests/test_phase32_email_verify.py b/tests/test_phase32_email_verify.py index 67562c3..8a1a771 100644 --- a/tests/test_phase32_email_verify.py +++ b/tests/test_phase32_email_verify.py @@ -74,7 +74,9 @@ def test_start_returns_none_when_already_verified(self): def test_token_is_one_shot(self): from services.email_verify import ( - EmailVerifyError, complete_verification, start_verification, + EmailVerifyError, + complete_verification, + start_verification, ) tok = start_verification(self.user.id) @@ -88,7 +90,11 @@ def test_token_is_one_shot(self): complete_verification("o@x.com", tok) def test_wrong_token_rejected(self): - from services.email_verify import EmailVerifyError, complete_verification, start_verification + from services.email_verify import ( + EmailVerifyError, + complete_verification, + start_verification, + ) start_verification(self.user.id) with self.assertRaises(EmailVerifyError): @@ -96,10 +102,13 @@ def test_wrong_token_rejected(self): def test_expired_token_rejected(self): from sqlalchemy import select + from db.models import EmailVerificationToken from db.session import get_session from services.email_verify import ( - EmailVerifyError, complete_verification, start_verification, + EmailVerifyError, + complete_verification, + start_verification, ) tok = start_verification(self.user.id) @@ -118,6 +127,7 @@ def test_empty_token_rejected(self): def test_token_hash_not_raw(self): from sqlalchemy import select + from db.models import EmailVerificationToken from db.session import get_session from services.email_verify import start_verification diff --git a/tests/test_phase3_units.py b/tests/test_phase3_units.py index 5fcf1b4..c5b9400 100644 --- a/tests/test_phase3_units.py +++ b/tests/test_phase3_units.py @@ -69,10 +69,11 @@ def test_unknown_user_same_error_as_bad_password(self): self.assertEqual(str(ctx_unknown.exception), str(ctx_badpw.exception)) def test_password_not_stored_in_plaintext(self): + from sqlalchemy import select + from db.models import User from db.session import get_session from services.auth import register_user - from sqlalchemy import select register_user("c@x.com", "longenough") with get_session() as s: diff --git a/tests/test_phase4_units.py b/tests/test_phase4_units.py index dcd5881..db6d03a 100644 --- a/tests/test_phase4_units.py +++ b/tests/test_phase4_units.py @@ -85,6 +85,8 @@ def test_reset_token_is_one_shot(self): complete_password_reset("p@x.com", token, "anotherpw") def test_expired_token_rejected(self): + from sqlalchemy import select + from db.models import PasswordResetToken from db.session import get_session from services.auth import ( @@ -92,7 +94,6 @@ def test_expired_token_rejected(self): complete_password_reset, request_password_reset, ) - from sqlalchemy import select token = request_password_reset("p@x.com") # Hand-expire the token. @@ -115,10 +116,11 @@ def test_wrong_token_rejected(self): complete_password_reset("p@x.com", "totally-wrong-token", "brandnewpw") def test_token_hash_not_raw_in_db(self): + from sqlalchemy import select + from db.models import PasswordResetToken from db.session import get_session from services.auth import request_password_reset - from sqlalchemy import select token = request_password_reset("p@x.com") with get_session() as s: diff --git a/tests/test_phase5_units.py b/tests/test_phase5_units.py index 6fe0d58..400d23e 100644 --- a/tests/test_phase5_units.py +++ b/tests/test_phase5_units.py @@ -2,7 +2,6 @@ from __future__ import annotations -import io import json import os import subprocess @@ -174,6 +173,7 @@ class AlembicMigrationTests(unittest.TestCase): def test_upgrade_creates_expected_tables(self): import tempfile + from sqlalchemy import create_engine, inspect project_root = Path(__file__).resolve().parents[1] diff --git a/tests/test_phase8_units.py b/tests/test_phase8_units.py index c77f699..e8b105d 100644 --- a/tests/test_phase8_units.py +++ b/tests/test_phase8_units.py @@ -7,7 +7,7 @@ import sys import tempfile import unittest -from datetime import date, timedelta +from datetime import date from pathlib import Path sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) diff --git a/tests/test_phase9_units.py b/tests/test_phase9_units.py index b4ae6bf..65d1956 100644 --- a/tests/test_phase9_units.py +++ b/tests/test_phase9_units.py @@ -97,10 +97,11 @@ def test_update_does_not_wipe_structured_unless_explicit(self): self.assertEqual(get_master_cv(self.user.id).structured, {}) def test_one_master_cv_per_user(self): + from sqlalchemy import select + from db.models import MasterCV from db.session import get_session from services.master_cv import save_master_cv - from sqlalchemy import select save_master_cv(self.user.id, SAMPLE_CV) save_master_cv(self.user.id, SAMPLE_CV + "\nMore") # overwrites @@ -190,7 +191,11 @@ def test_update_and_delete(self): def test_cross_user_isolation(self): from services.projects import ( - ProjectError, create_project, delete_project, list_projects, update_project, + ProjectError, + create_project, + delete_project, + list_projects, + update_project, ) p = create_project(self.user.id, title="mine") @@ -238,7 +243,6 @@ def test_generate_tailored_cv_requires_master_cv(self): def test_tailored_cv_prompt_contains_constraints(self): """The no-fabrication rules MUST appear verbatim in the generated prompt.""" from services.tailoring import ( - NO_FABRICATION_RULES, build_tailored_cv_prompt, ) diff --git a/tools/__init__.py b/tools/__init__.py index a1e55ca..c880fcd 100644 --- a/tools/__init__.py +++ b/tools/__init__.py @@ -1,5 +1,5 @@ -from .job_tools import job_tools from .company_tools import company_tools +from .job_tools import job_tools from .salary_tools import salary_tools __all__ = [ diff --git a/tools/company_tools.py b/tools/company_tools.py index 89ef309..9bc0f27 100644 --- a/tools/company_tools.py +++ b/tools/company_tools.py @@ -20,10 +20,10 @@ except ImportError: # pragma: no cover - older langchain layout from langchain.tools import Tool +from tools.data_sources import fetch_company_news, fetch_layoffs from utils.cache import cache from utils.llm import get_completion from utils.security import sanitize_untrusted, wrap_untrusted -from tools.data_sources import fetch_company_news, fetch_layoffs logger = logging.getLogger(__name__) diff --git a/tools/resume_tools.py b/tools/resume_tools.py index 346dd3f..0f2b2b7 100644 --- a/tools/resume_tools.py +++ b/tools/resume_tools.py @@ -18,11 +18,11 @@ import io import logging import re -from typing import Dict, Iterable, List, Optional, Tuple +from typing import Dict, Iterable, List, Optional from utils.cache import cache from utils.llm import get_completion -from utils.security import sanitize_untrusted, wrap_untrusted +from utils.security import wrap_untrusted logger = logging.getLogger(__name__) diff --git a/tools/url_ingest.py b/tools/url_ingest.py index 57e89ac..eb73ead 100644 --- a/tools/url_ingest.py +++ b/tools/url_ingest.py @@ -31,7 +31,9 @@ def is_url(text: Optional[str]) -> bool: - return bool(text) and bool(_URL_RE.match(text.strip())) + if not text: + return False + return bool(_URL_RE.match(text.strip())) def fetch_job_posting(url: str) -> str: diff --git a/utils/__init__.py b/utils/__init__.py index 867adf2..d8584ca 100644 --- a/utils/__init__.py +++ b/utils/__init__.py @@ -1,5 +1,5 @@ -from .llm import get_llm_client, get_completion from .cache import SimpleCache, cache +from .llm import get_completion, get_llm_client __all__ = [ 'get_llm_client', diff --git a/utils/config.py b/utils/config.py index 9c5f364..1aa7969 100644 --- a/utils/config.py +++ b/utils/config.py @@ -2,7 +2,7 @@ import os from typing import Dict, List, Union -from utils.llm import get_active_provider, is_demo_mode, TIER_MODELS +from utils.llm import TIER_MODELS, get_active_provider, is_demo_mode def check_environment_setup() -> Dict[str, Union[bool, str, None]]: diff --git a/utils/metrics.py b/utils/metrics.py index 6583c4b..0ee10e1 100644 --- a/utils/metrics.py +++ b/utils/metrics.py @@ -19,8 +19,7 @@ import threading from collections import deque from dataclasses import dataclass -from typing import Deque, Dict, Iterable, List, Optional, Tuple - +from typing import Deque, Dict, List, Optional, Tuple # How many samples each histogram remembers. Bounded so a hot path doesn't # eat memory; older samples drop off in FIFO order. diff --git a/uv.lock b/uv.lock index b2b4562..acfe535 100644 --- a/uv.lock +++ b/uv.lock @@ -2,7 +2,8 @@ version = 1 revision = 3 requires-python = ">=3.11" resolution-markers = [ - "python_full_version >= '3.14'", + "python_full_version >= '3.15'", + "python_full_version == '3.14.*'", "python_full_version >= '3.12.4' and python_full_version < '3.14'", "python_full_version >= '3.12' and python_full_version < '3.12.4'", "python_full_version < '3.12'", @@ -187,6 +188,46 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/46/eb/e7f063ad1fec6b3178a3cd82d1a3c4de82cccf283fc42746168188e1cdd5/anyio-4.8.0-py3-none-any.whl", hash = "sha256:b5011f270ab5eb0abf13385f851315585cc37ef330dd88e27ec3d34d651fd47a", size = 96041, upload-time = "2025-01-05T13:13:07.985Z" }, ] +[[package]] +name = "ast-serialize" +version = "0.5.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/81/9d/09e27731bd5864a9ce04e3244074e674bb8936bf62b45e0357248717adac/ast_serialize-0.5.0.tar.gz", hash = "sha256:5880091bfe6f4f986f22866375c2e884843e7a0b6343ae41aeea659613d879b6", size = 61157, upload-time = "2026-05-17T17:48:29.429Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c0/9a/13dde51ba9e15f8b97957ab7cb0120d0e381524d651c6bd630b9c359227f/ast_serialize-0.5.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:8f5c14f169eb0972c0c21bada5358b23d6047c76583b005234f865b11f1fa00a", size = 1183520, upload-time = "2026-05-17T17:47:30.831Z" }, + { url = "https://files.pythonhosted.org/packages/37/de/5a7f0a9fe68944f536632a5af84676739c7d2582be42deb082634bf3a754/ast_serialize-0.5.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7d1a2de9de5be04652f0ed60738356ef94f66db37924a9499fffe98dc491aa0b", size = 1175779, upload-time = "2026-05-17T17:47:32.551Z" }, + { url = "https://files.pythonhosted.org/packages/9c/81/0bb853e76e4f6e9a1855d569003c59e19ffac45f7079d91505d1bb212f92/ast_serialize-0.5.0-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:be5173fb66f9b49026d9d5a2ff0fc7c7009077107c0eb285b2d60fdf1fe10bd1", size = 1233750, upload-time = "2026-05-17T17:47:34.731Z" }, + { url = "https://files.pythonhosted.org/packages/e5/d3/4cf705beeccc08754d0bbda99aefff26110e209b9a07ac8a6b60eec48531/ast_serialize-0.5.0-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f8015cd071ac1339924ee2b8098c93e00e155f30a16f40ec9816fcf84f4753f6", size = 1235942, upload-time = "2026-05-17T17:47:36.287Z" }, + { url = "https://files.pythonhosted.org/packages/26/c8/ee097e437ea27dd2b8b227865c875492b585650a5802a22d82b304c8201b/ast_serialize-0.5.0-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5499e8797edff2a9186aa313ed382c6b422e798e9332d9953badcee6e69a88f2", size = 1442517, upload-time = "2026-05-17T17:47:38.17Z" }, + { url = "https://files.pythonhosted.org/packages/ff/bd/68063442838f1ba68ec72b5436430bc75b3bb17a1a3c3063f09b0c05ae2b/ast_serialize-0.5.0-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6848f2a093fb5548751a9a09bff8fcd229e2bbeb0e3331f391b6ae6d26cd9903", size = 1254081, upload-time = "2026-05-17T17:47:39.826Z" }, + { url = "https://files.pythonhosted.org/packages/50/e2/1e520793bc6a4e4524a6ab022391e827825eaa0c3811828bfdc6852eca26/ast_serialize-0.5.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:832d4c998e0b091fd60a6d6bceee535483c4d490de9ba85003af835225719261", size = 1259910, upload-time = "2026-05-17T17:47:41.369Z" }, + { url = "https://files.pythonhosted.org/packages/4e/e1/49b60f467979979cfe6913b43948ff25bca971ad0591d181812f163a988e/ast_serialize-0.5.0-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:16db7c62ec0b8efe1d7afd283a388d8f74f2605d56032e5a37747d2de8dba027", size = 1250678, upload-time = "2026-05-17T17:47:43.702Z" }, + { url = "https://files.pythonhosted.org/packages/74/ba/66ab9555de6275677566f6574e5ef6c29cb185ea866f643bc06f8280a8ee/ast_serialize-0.5.0-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:baf5eb061eb5bccade4128ad42da33787d72f6013809cd1b590376ece8b3c937", size = 1301603, upload-time = "2026-05-17T17:47:46.256Z" }, + { url = "https://files.pythonhosted.org/packages/66/42/6aca9b9abc710014b2be9059689e5dd1679339e78f567ffb4d255a9e2050/ast_serialize-0.5.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:104e4a35bd7c124173c41760ef9aaea17ddb3f86c65cb643671d59afbe3ee94c", size = 1410332, upload-time = "2026-05-17T17:47:47.899Z" }, + { url = "https://files.pythonhosted.org/packages/47/68/2f76594432a22581ecf878b5e75a9b8601c24b2241cf0bbeb1e21fcf370c/ast_serialize-0.5.0-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:36be371028fc1675acb38a331bde160dbab7ff907fdf00b67eb6911aa106951b", size = 1509979, upload-time = "2026-05-17T17:47:50.942Z" }, + { url = "https://files.pythonhosted.org/packages/40/ac/a93c9b58292653f6c595752f677a08e608f903b710594909e9231a389b3b/ast_serialize-0.5.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:061ee58bdb52341c8201a6df41182a977736bae3b7ded87ca7176ca25a8a47ab", size = 1505002, upload-time = "2026-05-17T17:47:54.093Z" }, + { url = "https://files.pythonhosted.org/packages/14/2e/b278f68c497ee2f1d1576cbbef8db5281cd4a5f2db040537592ac9c8862e/ast_serialize-0.5.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:b15219e9cdc9f53f6f4cb51c009203507228226148c05c5e8fe451c28b435eb3", size = 1456231, upload-time = "2026-05-17T17:47:56.311Z" }, + { url = "https://files.pythonhosted.org/packages/0b/43/419be1c566a4c504cd8fd60ce2f84e790f295495c0f327cfaeadf3d51012/ast_serialize-0.5.0-cp314-cp314t-win32.whl", hash = "sha256:842d1c004bb466c7df036f95fabef789570541922b10976b12f5592a69cf0b38", size = 1058668, upload-time = "2026-05-17T17:47:58.305Z" }, + { url = "https://files.pythonhosted.org/packages/03/6f/c9d4d549295ed05111aeb8853232d1afd9d0a179fddb01eeffbb3a4a6842/ast_serialize-0.5.0-cp314-cp314t-win_amd64.whl", hash = "sha256:b0c06d760909b095cc466356dfccd05a1c7233a6ca191c020dca2c6a6f16c24c", size = 1101075, upload-time = "2026-05-17T17:48:00.35Z" }, + { url = "https://files.pythonhosted.org/packages/d0/8e/d00c5ab30c58222e07d62956fca86c59d91b9ad32997e633c38b526623a3/ast_serialize-0.5.0-cp314-cp314t-win_arm64.whl", hash = "sha256:787baedb0262cc49e8ce37cc15c00ae818e46a165a3b36f5e21ed174998104cb", size = 1075347, upload-time = "2026-05-17T17:48:01.753Z" }, + { url = "https://files.pythonhosted.org/packages/e0/9e/dc2530acb3a60dc6e46d65abf27d1d9f86721694757906a148d90a6860de/ast_serialize-0.5.0-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:0668aa9459cfa8c9c49ddd2163ebcf43088ba045ef7492af6fe22e0098303101", size = 1191380, upload-time = "2026-05-17T17:48:03.738Z" }, + { url = "https://files.pythonhosted.org/packages/26/0a/bd3d18a582f273d6c843d16bb9e22e9e16365ff7991e92f18f798e9f1224/ast_serialize-0.5.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:bf683d6363edf2b39eed6b6d4fe22d34b6203867a67e27134d9e2a2680c4bc4a", size = 1183879, upload-time = "2026-05-17T17:48:05.463Z" }, + { url = "https://files.pythonhosted.org/packages/40/ae/1f919100f8620887af58fcc381c61a1f218cdf89c6e155f87b213e61010a/ast_serialize-0.5.0-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9cc22cf0c9be65e71cf88fda130af60d61eb4a79370ad4cfe7900d48a4aa2211", size = 1244529, upload-time = "2026-05-17T17:48:07.008Z" }, + { url = "https://files.pythonhosted.org/packages/c6/ca/6376559dcce707cdbc1d0d9a13c8d3baaaa501e949ce0ebdc4230cd881aa/ast_serialize-0.5.0-cp39-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f66173891548c9f2726bf27957b41cabce12fa679dc6da505ddbde4d4b3b31cf", size = 1240560, upload-time = "2026-05-17T17:48:08.46Z" }, + { url = "https://files.pythonhosted.org/packages/35/b2/a620e206b5aeb7efbf2710336df57d457cffbb3991076bbcc1147ef9abd4/ast_serialize-0.5.0-cp39-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e42d729ef2be96a14efbad355093284739e3670ece3e534f82cc8832790911d9", size = 1451172, upload-time = "2026-05-17T17:48:09.922Z" }, + { url = "https://files.pythonhosted.org/packages/fa/e0/4ad5c04c24a40481b2935ce9a0ccdb6023dc8b667167d06ae530cc3512f2/ast_serialize-0.5.0-cp39-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b725026bafa801dbd7310eb13a75f0a2e370e7e51b2cb225f9d21fcfadf919ee", size = 1265072, upload-time = "2026-05-17T17:48:11.469Z" }, + { url = "https://files.pythonhosted.org/packages/b2/71/4d1d479aa56d0101c40e17720c3d6ac2af7269ea0487a80b18e7bfd1a5b7/ast_serialize-0.5.0-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b54f60c1d78767a53b67eaa663f0dfac3afe606aa07f1301572f588b73d64809", size = 1270488, upload-time = "2026-05-17T17:48:13.575Z" }, + { url = "https://files.pythonhosted.org/packages/6d/4f/0de1bbe06f6edef9fde4ed12ca8e7b3ec7e6e2bd4e672c5af487f7957665/ast_serialize-0.5.0-cp39-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:27d51654fc240a1e87e742d353d98eb45b75f62f129086b3596ab53df2ac2a43", size = 1260702, upload-time = "2026-05-17T17:48:15.141Z" }, + { url = "https://files.pythonhosted.org/packages/75/61/e00872439cfdddcc3c1b6cdaa6e5d904ba8e26a18807c67c4e14409d0ca8/ast_serialize-0.5.0-cp39-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:2782c36237c46dd1674542f2109740ea5ea485a169bf1431939ada0434e17934", size = 1311182, upload-time = "2026-05-17T17:48:16.779Z" }, + { url = "https://files.pythonhosted.org/packages/76/8e/699a5b955f7926956c95e9e1d74132acad73c2fe7a426f94da89123c20aa/ast_serialize-0.5.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1943db345233cc7194a470f13afa9c59772c0b123dea0c9414c4d4ca54369759", size = 1421410, upload-time = "2026-05-17T17:48:18.527Z" }, + { url = "https://files.pythonhosted.org/packages/a9/ae/d5b7626874478997adc7a29ab28accf21e596fb590c944290401dfd0b29e/ast_serialize-0.5.0-cp39-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:df1c00022cbbcb064bfaa505aa9c9295362443ce5dacb459d1331d3da353f887", size = 1516587, upload-time = "2026-05-17T17:48:20.133Z" }, + { url = "https://files.pythonhosted.org/packages/0c/ce/b59e02a82d9c4244d64cde502e0b00e83e38816abe19155ceb5437402c7f/ast_serialize-0.5.0-cp39-abi3-musllinux_1_2_i686.whl", hash = "sha256:cae65289fc456fde04af979a2be09302ef5d8ab92ef23e596d6746dc267ada27", size = 1515171, upload-time = "2026-05-17T17:48:21.921Z" }, + { url = "https://files.pythonhosted.org/packages/8b/38/d8d90042747d05aa08d4efcf1c99035a5f670a6bf4c214d31644392afbca/ast_serialize-0.5.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:239a4c354e8d676e9d94631d1d4a64edc6b266f86ff3a5a80aedd344f342c01d", size = 1464668, upload-time = "2026-05-17T17:48:23.544Z" }, + { url = "https://files.pythonhosted.org/packages/dd/51/5b840c4df7334104cecffa28f23904fe81ca89ca223d2450e288de39fd3c/ast_serialize-0.5.0-cp39-abi3-win32.whl", hash = "sha256:143a4ef63285a075871908fda3672dc21864b83a8ec3ee12304aa3e4c5387b9a", size = 1068311, upload-time = "2026-05-17T17:48:25.027Z" }, + { url = "https://files.pythonhosted.org/packages/41/11/ca5672c7d491825bc4cd6702dea106a6b60d928707712ec257c7833ae476/ast_serialize-0.5.0-cp39-abi3-win_amd64.whl", hash = "sha256:cf25572c526add400f26a4750dc6ce0c3bb93fc1f75e7ae0cad4ce4f2cd5c590", size = 1108931, upload-time = "2026-05-17T17:48:26.591Z" }, + { url = "https://files.pythonhosted.org/packages/45/19/cc8bd127d28a43da249aa955cfd164cf8fd534e79e42cea96c4854d72fd0/ast_serialize-0.5.0-cp39-abi3-win_arm64.whl", hash = "sha256:92a31c9c20d25a076edaeec76b128a3535d74a24f340b9a8a7e96c9b86dc9642", size = 1081181, upload-time = "2026-05-17T17:48:28.122Z" }, +] + [[package]] name = "async-timeout" version = "5.0.1" @@ -205,6 +246,21 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/fc/30/d4986a882011f9df997a55e6becd864812ccfcd821d64aac8570ee39f719/attrs-25.1.0-py3-none-any.whl", hash = "sha256:c75a69e28a550a7e93789579c22aa26b0f5b83b75dc4e08fe092980051e1090a", size = 63152, upload-time = "2025-01-25T11:30:10.164Z" }, ] +[[package]] +name = "bandit" +version = "1.9.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "pyyaml" }, + { name = "rich" }, + { name = "stevedore" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/aa/c3/0cb80dfe0f3076e5da7e4c5ad8e57bac6ac357ff4a6406205501cade4965/bandit-1.9.4.tar.gz", hash = "sha256:b589e5de2afe70bd4d53fa0c1da6199f4085af666fde00e8a034f152a52cd628", size = 4242677, upload-time = "2026-02-25T06:44:15.503Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/05/a4/a26d5b25671d27e03afb5401a0be5899d94ff8fab6a698b1ac5be3ec29ef/bandit-1.9.4-py3-none-any.whl", hash = "sha256:f89ffa663767f5a0585ea075f01020207e966a9c0f2b9ef56a57c7963a3f6f8e", size = 134741, upload-time = "2026-02-25T06:44:13.694Z" }, +] + [[package]] name = "bcrypt" version = "5.0.0" @@ -306,6 +362,33 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/10/cb/f2ad4230dc2eb1a74edf38f1a38b9b52277f75bef262d8908e60d957e13c/blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc", size = 8458, upload-time = "2024-11-08T17:25:46.184Z" }, ] +[[package]] +name = "boolean-py" +version = "5.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c4/cf/85379f13b76f3a69bca86b60237978af17d6aa0bc5998978c3b8cf05abb2/boolean_py-5.0.tar.gz", hash = "sha256:60cbc4bad079753721d32649545505362c754e121570ada4658b852a3a318d95", size = 37047, upload-time = "2025-04-03T10:39:49.734Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e5/ca/78d423b324b8d77900030fa59c4aa9054261ef0925631cd2501dd015b7b7/boolean_py-5.0-py3-none-any.whl", hash = "sha256:ef28a70bd43115208441b53a045d1549e2f0ec6e3d08a9d142cbc41c1938e8d9", size = 26577, upload-time = "2025-04-03T10:39:48.449Z" }, +] + +[[package]] +name = "cachecontrol" +version = "0.14.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "msgpack" }, + { name = "requests" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/2d/f6/c972b32d80760fb79d6b9eeb0b3010a46b89c0b23cf6329417ff7886cd22/cachecontrol-0.14.4.tar.gz", hash = "sha256:e6220afafa4c22a47dd0badb319f84475d79108100d04e26e8542ef7d3ab05a1", size = 16150, upload-time = "2025-11-14T04:32:13.138Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/79/c45f2d53efe6ada1110cf6f9fca095e4ff47a0454444aefdde6ac4789179/cachecontrol-0.14.4-py3-none-any.whl", hash = "sha256:b7ac014ff72ee199b5f8af1de29d60239954f223e948196fa3d84adaffc71d2b", size = 22247, upload-time = "2025-11-14T04:32:11.733Z" }, +] + +[package.optional-dependencies] +filecache = [ + { name = "filelock" }, +] + [[package]] name = "cachetools" version = "5.5.2" @@ -495,6 +578,121 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] +[[package]] +name = "coverage" +version = "7.14.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/54/fd/0ab2772530e946e1be1abd0bc09e647ec9b02e88f0867857601fefca8953/coverage-7.14.1.tar.gz", hash = "sha256:30c08f7d90415aa98b3c990385dea2939b0da55f38515e5b369b83655f8523be", size = 920132, upload-time = "2026-05-26T20:41:36.783Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7d/d7/477ad149490e6cb849f28abea1dabb9c823cea72e7500c81b4240ce619c0/coverage-7.14.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:478b5bcd63c2e1357c5c7e16c070690df7b07f676b1c114d7b93e533c664309f", size = 219848, upload-time = "2026-05-26T20:38:38.715Z" }, + { url = "https://files.pythonhosted.org/packages/91/82/a5eb47257c50601bb7b9a9d2857c67b7a3a85ad74180eb2c98bb1fbe0ce5/coverage-7.14.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a24a81f9715ee42ef59a316cc11611c98fe23920f7c81861315c9f3ff4a230f4", size = 220354, upload-time = "2026-05-26T20:38:40.232Z" }, + { url = "https://files.pythonhosted.org/packages/43/8b/78419b5391a5cb706b6544390507e469d83ffc9a8248b02c4011aceb9365/coverage-7.14.1-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:196a13319ad88d6d8ef5ab489ec4f44ddde2143c0c7d5b27786f6c3ffd56a7e1", size = 250771, upload-time = "2026-05-26T20:38:41.782Z" }, + { url = "https://files.pythonhosted.org/packages/77/63/e77aaacd491182210d639636b7a8bba23ffffa9b82aa3762da9431855fa9/coverage-7.14.1-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:3d452fd08b5c72c5167c93e6867b5c08500bd40f2a21e1e854a500550b6cc36f", size = 252683, upload-time = "2026-05-26T20:38:43.305Z" }, + { url = "https://files.pythonhosted.org/packages/65/1c/a022e3cfbec2ac241640003cb3a817e161d9c7f5aa9b49173756cdc03204/coverage-7.14.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:23bf7fa51ac02e07fc7c96849b82946da47ae862dc8f86d183b2a4864fc38129", size = 254791, upload-time = "2026-05-26T20:38:45.361Z" }, + { url = "https://files.pythonhosted.org/packages/61/d6/967e408aca4c1ceb88cb0cc677169110ae7f5995fb5eaf5fb1f5a1bb8f5d/coverage-7.14.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:bcaa50684dcaadfa599ac48f81103c756d791cfd85c97203d2217c593d48b860", size = 256748, upload-time = "2026-05-26T20:38:46.91Z" }, + { url = "https://files.pythonhosted.org/packages/b8/be/869188f7fe28638078ec479331ace6dc5f7b40b7153eb616f47ab79404d8/coverage-7.14.1-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:4ea1c034f95c9b056e856b794630b17f9fa3d57e4800ff1e503d3be0f9c9078c", size = 250907, upload-time = "2026-05-26T20:38:48.493Z" }, + { url = "https://files.pythonhosted.org/packages/07/aa/adb7d3b4278d690e68703abcd76ab1b948242e3668d921711551b78f9ddb/coverage-7.14.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:c7e057326434e441306226fbeb5d1aaf14a2637efe97ba668306635835f32ad7", size = 252483, upload-time = "2026-05-26T20:38:50.074Z" }, + { url = "https://files.pythonhosted.org/packages/43/61/331c74103c62dcb0c4b9b3a0de9a61aca016208b0a90f109592a9f9ecc28/coverage-7.14.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:59baf88468dbc8d63b1887afd92bda52e40bb1561696e5819670601403810cec", size = 250545, upload-time = "2026-05-26T20:38:51.613Z" }, + { url = "https://files.pythonhosted.org/packages/f6/b6/c5dae3c104d89be04828f61810e6b3473825482e4c288cc4ed04553e08ae/coverage-7.14.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:d34d75f892b3ab73ba11cab5442cce7b3e168fd64162b16f0e1e0d09c508edef", size = 254310, upload-time = "2026-05-26T20:38:53.503Z" }, + { url = "https://files.pythonhosted.org/packages/ad/a1/2b9d5863e3b83c01ad8199e3c597802fbb3a9dc90b058885804c20296d31/coverage-7.14.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:3a56abc20a472baf0304c455721bc601477440d28ecfde8a03dde79ede07e0df", size = 250266, upload-time = "2026-05-26T20:38:55.414Z" }, + { url = "https://files.pythonhosted.org/packages/7f/5e/0e511fbdb269359be26fe678a1c3fa1f2aa2a01573cc3f54268c8d6d4797/coverage-7.14.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:6a3cb83d1552c0cd1b4906655b6a33fd4a8473229633a901c6b73bf86914dee9", size = 251174, upload-time = "2026-05-26T20:38:57.141Z" }, + { url = "https://files.pythonhosted.org/packages/85/10/e55307b622b3dd9671cb321824502dc10f93e72f2802b9946159a8edadeb/coverage-7.14.1-cp311-cp311-win32.whl", hash = "sha256:10274a1fbeb8ec5d72966e17bb198a3104257aca4ac09d98667c5f8aca8c8548", size = 222354, upload-time = "2026-05-26T20:38:58.727Z" }, + { url = "https://files.pythonhosted.org/packages/71/cf/107421693cfb71e4f1ca5bf70443f64d4161878068d07a3e51c7ad21d17b/coverage-7.14.1-cp311-cp311-win_amd64.whl", hash = "sha256:87ebdf787d4888e3f3f2d523eadc6e18c6d18c6d0eb173801a189641627fb37e", size = 223290, upload-time = "2026-05-26T20:39:00.413Z" }, + { url = "https://files.pythonhosted.org/packages/b8/1d/3e3644585eb29e9dafefb19555078529a4d7cce12bd21929664eea989277/coverage-7.14.1-cp311-cp311-win_arm64.whl", hash = "sha256:dd34767fa19848d35659ffc0a75314f58c7af3f1cd87ec521e8292a1238398a3", size = 221953, upload-time = "2026-05-26T20:39:02.159Z" }, + { url = "https://files.pythonhosted.org/packages/3d/b7/bdbb725ba02c5b42825b200c940f38b7a54fcad24627b7192f78f8110d76/coverage-7.14.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:a06c76364a9360e33d6d23769aefdf7f66f38e2ffb60ceb1baaa4989d83b695c", size = 220022, upload-time = "2026-05-26T20:39:03.702Z" }, + { url = "https://files.pythonhosted.org/packages/72/81/fdc0898a55c6219223291ec1a1fe89966ef212ce82276aa0899df84b5de0/coverage-7.14.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fad54e871165f6ec2f536063ac74c3104508a12963e64072ba44bd822de52b0c", size = 220379, upload-time = "2026-05-26T20:39:05.381Z" }, + { url = "https://files.pythonhosted.org/packages/de/72/de048c4a25e13bce59ac6a339351c10bdf2515e07459afcdaf04dc3143a2/coverage-7.14.1-cp312-cp312-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:84b535f00655ecafe1d929d1fb00ed5d6fa3051ea643ab2c161a3887b86f294b", size = 251888, upload-time = "2026-05-26T20:39:07.367Z" }, + { url = "https://files.pythonhosted.org/packages/28/30/300c343f68beb9d4cbb64ec81e58c5b6b80b56927f72d2b38654ac26e013/coverage-7.14.1-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:6b6b0853b895fe0e98cbfc580d1ec3393d9302b4b1e96a77b3f5c91fdab899e6", size = 254624, upload-time = "2026-05-26T20:39:09.037Z" }, + { url = "https://files.pythonhosted.org/packages/b1/ed/7b25642496e8170b6bac14adce00537c6e5fa2d586159401a4de3e8b49e6/coverage-7.14.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:442cc9c952b2df400cda54bb04ab87330cf2cd08a8692cbbea36773531eb6f37", size = 255739, upload-time = "2026-05-26T20:39:10.889Z" }, + { url = "https://files.pythonhosted.org/packages/7f/a2/abd210b8c4e29c24e4624916db97bb519097a91034aaeb767f937e7da794/coverage-7.14.1-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:8270544c361ed405a27a060dbc9ed2c124b084d96dfdc2d9a2510482aef981ad", size = 257998, upload-time = "2026-05-26T20:39:12.722Z" }, + { url = "https://files.pythonhosted.org/packages/7f/24/7c50beed3792fe62f6ce0545c6686ce83379719e2c0276179333d97eae92/coverage-7.14.1-cp312-cp312-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:48b283b1dd6372e8de2a7a9a4c4d5dc06f4d4fd209b876f3c88a7a205a0c8f84", size = 252296, upload-time = "2026-05-26T20:39:14.259Z" }, + { url = "https://files.pythonhosted.org/packages/15/05/0f874628ebcbfc77ead559ff210281ef06a97db08481832e7dd39274a135/coverage-7.14.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:5b0c99ba93a07d56f6df340bb79be53202a082b2fdb81bfe6190b741a3470d54", size = 253658, upload-time = "2026-05-26T20:39:15.923Z" }, + { url = "https://files.pythonhosted.org/packages/99/6f/ca6ad067364b337ef997802115e7ecad2abd2248b05471464b0dea02b4d4/coverage-7.14.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:e471bc5769ff073b058cfadb0d736b56ce067c8560eabeb0da88462df98c23e7", size = 251803, upload-time = "2026-05-26T20:39:17.537Z" }, + { url = "https://files.pythonhosted.org/packages/c0/30/b9b4d377cd9f40baf228068f5a81faf8450c6228503011bd499708483a50/coverage-7.14.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:f497a1ea81d4cd7c10ddcaa685135b9aabd291af3d55775a9ddf3cb7a364cdd9", size = 255873, upload-time = "2026-05-26T20:39:19.414Z" }, + { url = "https://files.pythonhosted.org/packages/3c/21/7c721a9e5e6bb88547d30a787aefb97512d3f54c1324c7488d9b3743f7f9/coverage-7.14.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:2222be86d0b54f5dd5a38f45f17f315f737245e857bf0bdedc70734f84a13c02", size = 251372, upload-time = "2026-05-26T20:39:21.169Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8c/f8ae5a2200130e1503cd7661a6cd3b2b7bacef98277fbf3571fb13f8b766/coverage-7.14.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:85e85586565842f6932abebd4c18bcb1074223dc0b3576e7d173ca710622813a", size = 253245, upload-time = "2026-05-26T20:39:23.097Z" }, + { url = "https://files.pythonhosted.org/packages/34/62/70a9024672a5f6910517d9628c52c9afbdd3cf8f46426af52bb148a56fff/coverage-7.14.1-cp312-cp312-win32.whl", hash = "sha256:4a28fd227808366b196a75476dced2eb35b351d6766ba9c858dc93319e87f4f1", size = 222567, upload-time = "2026-05-26T20:39:24.868Z" }, + { url = "https://files.pythonhosted.org/packages/f6/81/8b7cd386839b039ebe1855733b9f9449a8dec5d79564018234f185a7fa70/coverage-7.14.1-cp312-cp312-win_amd64.whl", hash = "sha256:54acdb6674a4661768d7bf7db32dfb9f46ab1d764f8aba6df75ce1a6a088724e", size = 223372, upload-time = "2026-05-26T20:39:26.603Z" }, + { url = "https://files.pythonhosted.org/packages/ae/ba/b44d472022f620d289d95fa830143235c0c36461c6f2437ea8d51e5481ed/coverage-7.14.1-cp312-cp312-win_arm64.whl", hash = "sha256:99cd41ff91afd94896fea3bc002706b6ae4ce95727d06e4a0f39c0a8d8bd8b1a", size = 221989, upload-time = "2026-05-26T20:39:28.242Z" }, + { url = "https://files.pythonhosted.org/packages/8a/9e/5f6d56327c62b185225d145191c607e07515294a0aa6338e58805cd4a5ac/coverage-7.14.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:be9f2c802dcfce3f71298303aa5dad0dce440a76c52f2f60dacd8656dab78793", size = 220044, upload-time = "2026-05-26T20:39:29.902Z" }, + { url = "https://files.pythonhosted.org/packages/75/92/e82aca356744cbbc0f77a0b623e38918c1872361963413a3bab5d0340393/coverage-7.14.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:6223a72fd0e4c7156353ec0f08a5f93623e1d3034d0e2683b9bb8ea674131b1d", size = 220412, upload-time = "2026-05-26T20:39:31.561Z" }, + { url = "https://files.pythonhosted.org/packages/27/c9/385bde0bf7ed0f4bf3a7ee5367060a86b5d218718cfd6fb943c0f836b34f/coverage-7.14.1-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:7279d2110a28cebc738b6459ecda2771735a4c18465fbbd36b3288fe5ed92247", size = 251412, upload-time = "2026-05-26T20:39:33.337Z" }, + { url = "https://files.pythonhosted.org/packages/51/8c/23faf6a2343a0d17f960a4bd56c43bc7eb4cf312f774dd6ceebd82c7d8fc/coverage-7.14.1-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:9eeb3fcbc13ba40dfbdb22d01d196a28e9cef9ed4c29b60061a1e0e823a9929d", size = 254008, upload-time = "2026-05-26T20:39:35.009Z" }, + { url = "https://files.pythonhosted.org/packages/42/06/36f4aa9ca8a815e6036156e80706a67828bb97bd826948244f6996dda957/coverage-7.14.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5f0cfc27c539f07cf5c0a4cfe211d0b6cae039f8f40526dbaa71944e64b50a7b", size = 255241, upload-time = "2026-05-26T20:39:36.71Z" }, + { url = "https://files.pythonhosted.org/packages/ca/79/95266316352f90f6b1c6736bb413302edfde2453fb32422d3911642691b3/coverage-7.14.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:221c70f316241a78e77e607c227cefc8808d4e08f28d99c04f35694690e940be", size = 257373, upload-time = "2026-05-26T20:39:38.412Z" }, + { url = "https://files.pythonhosted.org/packages/e3/9c/58316d1f66c488b5fca8a0eb3e98348807813efa8a0d0833b9021be27488/coverage-7.14.1-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:da028256b04ec30e5e0114b6f76172938c313991f0a2d3d894271315cf5d5e43", size = 251635, upload-time = "2026-05-26T20:39:40.268Z" }, + { url = "https://files.pythonhosted.org/packages/ef/5a/ca2398a568e16fed7bb713e84ba3603a7164fb65779abe645c565ec890d5/coverage-7.14.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:76a085d7005236a767e3426148b2c407e53ad61695c562f8a81da2d373324901", size = 253373, upload-time = "2026-05-26T20:39:42.145Z" }, + { url = "https://files.pythonhosted.org/packages/6e/2c/0396562c32deaebe7be51d865b3a41e9a87d7561acafe1a28f53b07e019a/coverage-7.14.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:b553d04b5e778a8e56d57eb134aff42a92718ecba45e79c4764ecfa40efd92ff", size = 251341, upload-time = "2026-05-26T20:39:43.907Z" }, + { url = "https://files.pythonhosted.org/packages/fd/8f/a94f9221184c9cae1ee115820e3798e48b6b17777a9f19e46fb9a0c8dc74/coverage-7.14.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:46f714d2fb8ae2f4f29f23ada7f1e79b759fff5a70f94a1dac23af204c3ec9e4", size = 255497, upload-time = "2026-05-26T20:39:46.166Z" }, + { url = "https://files.pythonhosted.org/packages/71/69/505d70e47db1eaebcd002c39759707621ef184cd6b1ae084d9f41293f323/coverage-7.14.1-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:1896f5e19ff3f0431c7ce2172adc54890fd97f86b59ced8ca1649145d9ffe35d", size = 251159, upload-time = "2026-05-26T20:39:48.03Z" }, + { url = "https://files.pythonhosted.org/packages/e0/aa/58681c383aa33a9d2ed40a02d7a22fbf780d1fa4d575396365777828198c/coverage-7.14.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:62fd185ef9df3c33d1c8178c5af105f762afbad96038de9a4ae100aa6297ca33", size = 252934, upload-time = "2026-05-26T20:39:49.872Z" }, + { url = "https://files.pythonhosted.org/packages/eb/fd/11c928cd6bdffc7074bb5965c173d9ebf517fb00205e1da524b98d29ef92/coverage-7.14.1-cp313-cp313-win32.whl", hash = "sha256:ab4af6352741a604c431c6072fce5bee33bf0f20dc7a56618d6bf6bb89e9810c", size = 222584, upload-time = "2026-05-26T20:39:51.68Z" }, + { url = "https://files.pythonhosted.org/packages/6f/92/fb416fc26d340dcba19518c418d6048e913186e17243982c5e435e41fa7a/coverage-7.14.1-cp313-cp313-win_amd64.whl", hash = "sha256:7af486dabe8954d03b087f0021540897afe084f04e16ff5579e08cc46f871416", size = 223394, upload-time = "2026-05-26T20:39:53.472Z" }, + { url = "https://files.pythonhosted.org/packages/73/c6/02d56e3867972f77d5036de924643f26c056e848f00452cafb4dbc3c29b4/coverage-7.14.1-cp313-cp313-win_arm64.whl", hash = "sha256:2224f89ffd0c5605ccce1ed7a584da162bc7c55f601ab1c946bc9de31a486b42", size = 222015, upload-time = "2026-05-26T20:39:55.374Z" }, + { url = "https://files.pythonhosted.org/packages/4d/9e/fcc77914050df73f7662fa1f00902774c79c075a8388ab334074574bf77e/coverage-7.14.1-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:de286598cc65d2b489411174b1faec2f5a7775fb3201fd925db2a76b4030f37d", size = 220733, upload-time = "2026-05-26T20:39:57.189Z" }, + { url = "https://files.pythonhosted.org/packages/f7/67/2963cbdaf5cbadec44efa3a1e39eaa1f02df4079585f05387607a221e126/coverage-7.14.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:042c46ded7c288aeb07cf14a28b6c1e10b78fcba40171c3fa1e939377eeef0b5", size = 221086, upload-time = "2026-05-26T20:39:59.019Z" }, + { url = "https://files.pythonhosted.org/packages/c8/c5/8701645574e11881f2f47d8930f98bc48b5d43b25eb5b4430dfc4a2f9f48/coverage-7.14.1-cp313-cp313t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:f4ddbe407477f04c45115d1a4e5bc480f753553b534d338d4c3358b1cdd0ea52", size = 262381, upload-time = "2026-05-26T20:40:00.822Z" }, + { url = "https://files.pythonhosted.org/packages/7c/28/7a64d73598263e0c5abd5084211a8474488d31b3c552ff531c719dfcff62/coverage-7.14.1-cp313-cp313t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:d13e6725992e2d2fd7d81d4f5241952d13740121dfd501da09201be39b2c003a", size = 264458, upload-time = "2026-05-26T20:40:02.506Z" }, + { url = "https://files.pythonhosted.org/packages/fa/d8/4969179db9f7eb4df218e69540adf829d1c835f59452513d065d15446802/coverage-7.14.1-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f747dc8edcfe740130f28f32f3995e955494285717e86ee25af51db2219df08a", size = 266884, upload-time = "2026-05-26T20:40:04.421Z" }, + { url = "https://files.pythonhosted.org/packages/a6/78/a45d5794dbc9bafd97afc96a4377c86c7820d78b6cf51b89bc1d4e919275/coverage-7.14.1-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:ced2f09ef276fd58611a1ef502164ad266d2b75174e5a40cabbdb4033f9f6cf2", size = 268022, upload-time = "2026-05-26T20:40:06.298Z" }, + { url = "https://files.pythonhosted.org/packages/21/cb/4f5e354e9e3e67af96bd4e57113e6db6b22298c7168b13eec408a549903d/coverage-7.14.1-cp313-cp313t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b84800013769a78ccb9ef4659402e26d06867e337b61ec365f77ad008adea80e", size = 261631, upload-time = "2026-05-26T20:40:08.226Z" }, + { url = "https://files.pythonhosted.org/packages/ec/49/eced49af4cb996d5d8b7e94e736175c513e4facd3398507b89892b4326d8/coverage-7.14.1-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:ea8cd6ca0ee9f616aaef3afc6882e32c2cbf18b00d96313ffd76af650574034d", size = 264443, upload-time = "2026-05-26T20:40:10.137Z" }, + { url = "https://files.pythonhosted.org/packages/f1/d8/5603a88a7c5913a6b54f6cb1a8c46f7b39cbb30f27cd3f492908da09b2d7/coverage-7.14.1-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:aa5e304a873fabddc11e484e9b6b738bd38bd7bed17b09aa84eecf5332e8b8bb", size = 262069, upload-time = "2026-05-26T20:40:11.999Z" }, + { url = "https://files.pythonhosted.org/packages/f0/59/2ae3cb79da554a06c8619d6c88ea19dd1e4aed4b834b6a83bb1fa243bdc5/coverage-7.14.1-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:5a1c5215be81035e629d5bc756650634d0bf31991038db7a0eccb90f025ce16d", size = 265780, upload-time = "2026-05-26T20:40:13.858Z" }, + { url = "https://files.pythonhosted.org/packages/af/5f/b130c1dc999031f2648bd25317fbce505ad8d5562079b4ed81e736a84967/coverage-7.14.1-cp313-cp313t-musllinux_1_2_riscv64.whl", hash = "sha256:79058c47dae6788504b5effb319961bcd72d7240551464b91d474bc0ed186d69", size = 260970, upload-time = "2026-05-26T20:40:16.142Z" }, + { url = "https://files.pythonhosted.org/packages/87/d1/ec13ccddeb48ec963bdfa72a11224bac2584bd045ba13beca82f8113e9c7/coverage-7.14.1-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:370c5afae3fa0658e11694a32b24c2778f6bc2d17718121f94ee185e69f26b54", size = 263157, upload-time = "2026-05-26T20:40:18.382Z" }, + { url = "https://files.pythonhosted.org/packages/cf/c2/cd91ead503045161092d3845f7bb95ea2f25131ce96d3e314dd835d91b9c/coverage-7.14.1-cp313-cp313t-win32.whl", hash = "sha256:3758dd0a7f1fa57365ef2e781df0f0731d38b6e3772259d13dae4bd8a958d4b1", size = 223259, upload-time = "2026-05-26T20:40:20.381Z" }, + { url = "https://files.pythonhosted.org/packages/71/9f/1e28d97e6bd2c76b07f38b7c02870f1371255ff6717f54eca578fcbbdd0e/coverage-7.14.1-cp313-cp313t-win_amd64.whl", hash = "sha256:6ff665fb023a77386fe11685190cee1f60a7d635994a30d9b0a061533d470fce", size = 224320, upload-time = "2026-05-26T20:40:22.316Z" }, + { url = "https://files.pythonhosted.org/packages/a9/e0/d936e908f0e1efa55e52b91e01b52f1055cef5e1ab2718493390ed8e2fb8/coverage-7.14.1-cp313-cp313t-win_arm64.whl", hash = "sha256:17a5a241e5997621a956a7f402a7433ef4221e5152809b785bec79e2323799f1", size = 222577, upload-time = "2026-05-26T20:40:24.894Z" }, + { url = "https://files.pythonhosted.org/packages/d6/34/fc2f101b151af3799a101f0550b0454aa008afdc0add677394ec4aa8ea10/coverage-7.14.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d5ed429d0b8edaac649e889b4ffcedb6c80b06629a3f93050e3dddfb99235bee", size = 220091, upload-time = "2026-05-26T20:40:27.249Z" }, + { url = "https://files.pythonhosted.org/packages/3d/a7/1ebae2ab5b961b5c79bb09fe7b3ac99edb190d8be4a8c510b2cf66f46468/coverage-7.14.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:8011224a62280e50dab346960c03cf47aca1a1e09e608c0fb33fd6e0cc8e9500", size = 220421, upload-time = "2026-05-26T20:40:30.084Z" }, + { url = "https://files.pythonhosted.org/packages/5e/90/92aca9cf0acc95123c96cd1eb1f08917897a7f5dee01e15738922971ec31/coverage-7.14.1-cp314-cp314-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:12c42ec1e14f553c4f817e989365982e646e27211f10a0f717855b94a79c8906", size = 251466, upload-time = "2026-05-26T20:40:32.542Z" }, + { url = "https://files.pythonhosted.org/packages/26/2b/78048cbe3b999f6cbf9cc0d90abba6a88a3e0863a8c1c6cbc762f3f8802f/coverage-7.14.1-cp314-cp314-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:06144cd511cf2624873a035c5069cf297144f6e77a73ee3d7a55b605ec5efb42", size = 253973, upload-time = "2026-05-26T20:40:34.473Z" }, + { url = "https://files.pythonhosted.org/packages/8e/21/c2e33b29d1cfde484a19d437afc343c6cd30b08d78cbbf9f5aff14e57b2b/coverage-7.14.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a311d8e1da24be5c1ccf85cbfb06315dbaa1703d5a1eab3f6432c72b837917c8", size = 255318, upload-time = "2026-05-26T20:40:38.154Z" }, + { url = "https://files.pythonhosted.org/packages/8e/ee/aad2f108d63b769121005302f16bf66db8625c88ceaba466942e09a2607e/coverage-7.14.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c79cead5b5bc584d9c71451cb984d0e3a84e0c0937379c8efcbf27c8d661b851", size = 257633, upload-time = "2026-05-26T20:40:40.164Z" }, + { url = "https://files.pythonhosted.org/packages/c2/f8/11a2c29b4fd76d9849f81d0bb812ec0017a9396df3217214e38934a8c837/coverage-7.14.1-cp314-cp314-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:dcbf65f1f66a26cdd88c35cf68fb4729c5d1cd2e88added72420541dfb212034", size = 251488, upload-time = "2026-05-26T20:40:42.631Z" }, + { url = "https://files.pythonhosted.org/packages/c9/b8/9a5820de4b8ac2b71d85e3b5fb49108d7469c665f0e2ad0dd7569023e305/coverage-7.14.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:fd86572566fb40189a8260446158235159bc7a82dfbc87a3b39cf4fb57fcec1c", size = 253329, upload-time = "2026-05-26T20:40:45.208Z" }, + { url = "https://files.pythonhosted.org/packages/6b/ff/f33e4823667e27548e8fd8df44217515303f9808d0ff29817db56f87d990/coverage-7.14.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:7771b601718fdde84832c3a434ca9bbf4ae9adbc49d84198b4110700c3c77c36", size = 251291, upload-time = "2026-05-26T20:40:47.502Z" }, + { url = "https://files.pythonhosted.org/packages/68/9b/489db0ebb209054766b90a9014a45f6d26eb724c02ec21311c3733b5a644/coverage-7.14.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:39b21e212c55af06fa375e3dbf90a8a8e38792f3a910c580066d23563830ddd5", size = 255564, upload-time = "2026-05-26T20:40:49.372Z" }, + { url = "https://files.pythonhosted.org/packages/27/b5/16bc2d4c2409b23c7737edb68c83bc89e345f378050549fe1d75ac7d34d5/coverage-7.14.1-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:f2302660e32562a532b442480121aef8aa61a5bdb20b30bf0adab29f10a5a4b4", size = 251107, upload-time = "2026-05-26T20:40:51.677Z" }, + { url = "https://files.pythonhosted.org/packages/7d/0c/2629997469a00cd069d588a41c9dc887610f2775ae89d250c4791e65272a/coverage-7.14.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:03a6f93c1ec3b7f2e77b5dbcc5573a2c21f12529a5c6bbe0f16f72303cc2fa4d", size = 252764, upload-time = "2026-05-26T20:40:54.267Z" }, + { url = "https://files.pythonhosted.org/packages/d2/ee/f78d63c8f079e0d7211c7e2401fa17e311514534ba61bae03e4b287ce4ab/coverage-7.14.1-cp314-cp314-win32.whl", hash = "sha256:8a3ce026d73290f42f08dafecbd82c193a74df280461fbf97300fec51fd133ee", size = 222837, upload-time = "2026-05-26T20:40:56.496Z" }, + { url = "https://files.pythonhosted.org/packages/dc/b9/be539854f93a70dfbeec69117f33ec70dc42ff0b65b5b07ab8d40d04228e/coverage-7.14.1-cp314-cp314-win_amd64.whl", hash = "sha256:114c95ef29302423b87d159075805f4ab973254a2638a5d7d046c94887cc87d7", size = 223650, upload-time = "2026-05-26T20:40:58.351Z" }, + { url = "https://files.pythonhosted.org/packages/fe/9e/24e2842fef40f35ac82ba3a7719c8023d011bf3bf652d0675316a9d088a1/coverage-7.14.1-cp314-cp314-win_arm64.whl", hash = "sha256:a07891c3f4805442b31b71e84ba3cf29ed1aa9a428284e06deeb4b23e5b46343", size = 222218, upload-time = "2026-05-26T20:41:00.321Z" }, + { url = "https://files.pythonhosted.org/packages/0a/1d/ac0a9df5fe31c1e8bdd658074905fc12844a05c1a7e3fdb8417e97c31e23/coverage-7.14.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:1101a5ebb083aecb625ebb6209d4105b58f647b093cb2dc8122d7b33f743cfe1", size = 220822, upload-time = "2026-05-26T20:41:02.281Z" }, + { url = "https://files.pythonhosted.org/packages/32/cf/f964fd9aff20323f9f1a726c97135f8a76bcd87b92dad141a456a43f3c64/coverage-7.14.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:851b9e1e4e8a4608e77c79714b2e77c0970d2ed7202a05e92ae407817481887b", size = 221084, upload-time = "2026-05-26T20:41:04.593Z" }, + { url = "https://files.pythonhosted.org/packages/d8/5e/7e5ef2aba844de2b80d678619fcf0841b42e3f37f16411226f3fe4c1016f/coverage-7.14.1-cp314-cp314t-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:d5b89cdfb2ee051b71e8c3c70bd81a9eff81100f736a269136fe1a68efe00474", size = 262454, upload-time = "2026-05-26T20:41:06.641Z" }, + { url = "https://files.pythonhosted.org/packages/64/62/75809bded87015cc4935524218a2a8ed8dd1a8498bfed30a2f4f7a4b4d34/coverage-7.14.1-cp314-cp314t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:0177614a0370f227888b4e436a7c55686d6a9f90eb1ade2b624ba685a1686e86", size = 264578, upload-time = "2026-05-26T20:41:08.556Z" }, + { url = "https://files.pythonhosted.org/packages/f3/42/d33392dc14633525012d2d504fa1a33b05538bf535f5c1d64675e5754b78/coverage-7.14.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2d69af5dea2de76fc485a83032a630523f985198b7e25be901ec60181587b01e", size = 266981, upload-time = "2026-05-26T20:41:10.824Z" }, + { url = "https://files.pythonhosted.org/packages/2a/49/0157c4428c2aca7f1e09d5565930586fd5ae36f1655f08b0daa7cf1fcae1/coverage-7.14.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:35ab22d91de736e8966b980dc355cbcdd2c6dbbcfe275f9a2991bc8a91b3df65", size = 268112, upload-time = "2026-05-26T20:41:12.966Z" }, + { url = "https://files.pythonhosted.org/packages/96/26/86b9ce71f4092b1ed325ce1421698081df1286b833400b6836912834d6e0/coverage-7.14.1-cp314-cp314t-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:357d4e32935c36588aaba057d734fa32428c360c9fc2e4442afbf1b646beee6e", size = 261558, upload-time = "2026-05-26T20:41:15Z" }, + { url = "https://files.pythonhosted.org/packages/20/4c/c311210c5472cf5401d8422b0d7812cdd520f24417673afabda6c323faca/coverage-7.14.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:51bd64741cc6fa065abd300ede1afe5a5291ece9c31da8b24884deda48bcc3f8", size = 264447, upload-time = "2026-05-26T20:41:17.369Z" }, + { url = "https://files.pythonhosted.org/packages/fb/71/59513f8710ed3e6b0ac0a050a5b7e977bb9c9e880354863b5d00d8809256/coverage-7.14.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:9132cd363a68a4c3daa7c8704a654b1e39d3360f6f5b8ddd470608a945236c07", size = 262048, upload-time = "2026-05-26T20:41:19.309Z" }, + { url = "https://files.pythonhosted.org/packages/84/8d/bceed32dc494f5bbf50f775cd2e78ca814953942b5ea28d3c1c3ac316f14/coverage-7.14.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:07c6290b1697b862c0478eab545eec949a0d0e4d6d03497f446d706da3b4f2de", size = 265781, upload-time = "2026-05-26T20:41:21.559Z" }, + { url = "https://files.pythonhosted.org/packages/e7/c5/9348fe40dbfd4991aaf78df2c6c3098bfb2cc834d1fd362a64b4efef855a/coverage-7.14.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:5ea0c297e27133853b4d8a3eb799bff5a2dbd9f2f41537a240d337ac9b4df890", size = 260896, upload-time = "2026-05-26T20:41:23.428Z" }, + { url = "https://files.pythonhosted.org/packages/ca/92/1ea0f03929da7cf87206b1fa24f4c8e9c158be0455481af29ec0a1f3503f/coverage-7.14.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:01b7733daad0237daa01ef80fe2dfceffc911e6a17fa7b55d14aa8214eaaaecd", size = 263214, upload-time = "2026-05-26T20:41:25.419Z" }, + { url = "https://files.pythonhosted.org/packages/f6/a9/b2493c054c0e01a643266742ab45e15744e60743f9260cd930c7142b1124/coverage-7.14.1-cp314-cp314t-win32.whl", hash = "sha256:6adc5a36984624a70bf11d7184e20fa0a49aa7c47ffab43804106a1a695ea22e", size = 223624, upload-time = "2026-05-26T20:41:27.795Z" }, + { url = "https://files.pythonhosted.org/packages/fc/bd/3e1e6a57fccd2d7c83fcdf338e93ba98eb85c6e877dd34731ac585375490/coverage-7.14.1-cp314-cp314t-win_amd64.whl", hash = "sha256:ddf799247318f34dbcd2efa8c95a8d0642674e926bb1774cf9b63dfd2a389d1c", size = 224728, upload-time = "2026-05-26T20:41:30.098Z" }, + { url = "https://files.pythonhosted.org/packages/bb/d7/31066cf1d2f0c6c797fce911bcfa01dd35642dc6da992a950256097c5860/coverage-7.14.1-cp314-cp314t-win_arm64.whl", hash = "sha256:145986fe66647eb489f18d9a997567a3fd358584c4b5a808769113abc07466af", size = 222752, upload-time = "2026-05-26T20:41:32.123Z" }, + { url = "https://files.pythonhosted.org/packages/8a/3c/1a983b9a745d7f83d53f057bcc5bf79ba6a2bbc08266b3f0c7d6fe630c9b/coverage-7.14.1-py3-none-any.whl", hash = "sha256:a252f21c27e38347e60111a3266b03827422a7d5525951aceee313aa68bab1d2", size = 211815, upload-time = "2026-05-26T20:41:34.078Z" }, +] + +[[package]] +name = "cyclonedx-python-lib" +version = "11.8.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "license-expression" }, + { name = "packageurl-python" }, + { name = "py-serializable" }, + { name = "sortedcontainers" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/83/45/5ce2515e092656ada3959897681a24a7299f13638d4805de3d1fd9f91342/cyclonedx_python_lib-11.8.0.tar.gz", hash = "sha256:a8935b06dfe53d80efd47b5f6a202eb678cea00f2930e94e3710f2c1510166c9", size = 1422887, upload-time = "2026-06-04T10:38:27.885Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/57/af/333ad82adec8121dae568f7d094a3b08ba485340cf19fe10674f2db14774/cyclonedx_python_lib-11.8.0-py3-none-any.whl", hash = "sha256:a326b575acbb3aa1040986307a4ae282ff27f99ffcbdfdaaf8de10ee85e97f01", size = 523911, upload-time = "2026-06-04T10:38:26.248Z" }, +] + [[package]] name = "defusedxml" version = "0.7.1" @@ -538,6 +736,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e0/82/45359b62a067409bd929ae8a56b8ed13e5a8c8a61194b3c236920999ab83/fastapi-0.136.3-py3-none-any.whl", hash = "sha256:3d2a69bdf04b7e9f3afa292c3bc7a98816bbfafa10bc9b45f3f3700d2f761620", size = 117481, upload-time = "2026-05-23T18:53:16.924Z" }, ] +[[package]] +name = "filelock" +version = "3.29.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1f/f9/f38573ed5844586db374d085911740a501ccfa373b455fc9413f09f85237/filelock-3.29.1.tar.gz", hash = "sha256:d97e6b1b9757569626c58caa07dc4beb1613f4a2938b1e8cc81afca398906c9e", size = 59335, upload-time = "2026-06-03T15:19:04.053Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4c/a0/614c5fe402fd88951df45f4dda2fa3b4e17a99ecd92340771929169b3b95/filelock-3.29.1-py3-none-any.whl", hash = "sha256:85199dfd706869641b72b2e8955d5416a4b2b7dc4b0e8e6d97b4cc1299a6983b", size = 40750, upload-time = "2026-06-03T15:19:02.959Z" }, +] + [[package]] name = "fonttools" version = "4.63.0" @@ -740,7 +947,8 @@ name = "h11" version = "0.16.0" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version >= '3.14'", + "python_full_version >= '3.15'", + "python_full_version == '3.14.*'", ] sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" } wheels = [ @@ -770,7 +978,8 @@ name = "httpcore" version = "1.0.9" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version >= '3.14'", + "python_full_version >= '3.15'", + "python_full_version == '3.14.*'", ] dependencies = [ { name = "certifi", marker = "python_full_version >= '3.14'" }, @@ -896,6 +1105,14 @@ dependencies = [ browser = [ { name = "playwright" }, ] +dev = [ + { name = "bandit" }, + { name = "coverage" }, + { name = "mypy" }, + { name = "pip-audit" }, + { name = "ruff" }, + { name = "types-requests" }, +] pdf = [ { name = "fpdf2" }, ] @@ -912,16 +1129,20 @@ requires-dist = [ { name = "alembic", specifier = ">=1.13.0" }, { name = "altair", specifier = ">=5.5.0" }, { name = "anthropic", specifier = ">=0.40.0" }, + { name = "bandit", marker = "extra == 'dev'", specifier = ">=1.7" }, { name = "bcrypt", specifier = ">=4.1.0" }, { name = "beautifulsoup4", specifier = ">=4.13.3" }, { name = "celery", marker = "extra == 'worker'", specifier = ">=5.3.0" }, + { name = "coverage", marker = "extra == 'dev'", specifier = ">=7.5" }, { name = "fastapi", specifier = ">=0.110.0" }, { name = "fpdf2", specifier = ">=2.8.7" }, { name = "fpdf2", marker = "extra == 'pdf'", specifier = ">=2.7.0" }, { name = "langchain", specifier = ">=0.3.19" }, { name = "langgraph", specifier = ">=0.3.1" }, + { name = "mypy", marker = "extra == 'dev'", specifier = ">=1.10" }, { name = "openai", specifier = ">=1.65.1" }, { name = "pandas", specifier = ">=2.2.3" }, + { name = "pip-audit", marker = "extra == 'dev'", specifier = ">=2.7" }, { name = "playwright", marker = "extra == 'browser'", specifier = ">=1.44.0" }, { name = "psycopg2-binary", specifier = ">=2.9.12" }, { name = "pyotp", specifier = ">=2.9.0" }, @@ -931,11 +1152,13 @@ requires-dist = [ { name = "qrcode", specifier = ">=7.4.0" }, { name = "redis", marker = "extra == 'worker'", specifier = ">=5.0.0" }, { name = "requests", specifier = ">=2.32.3" }, + { name = "ruff", marker = "extra == 'dev'", specifier = ">=0.6" }, { name = "sqlalchemy", specifier = ">=2.0.30" }, { name = "streamlit", specifier = ">=1.42.2" }, + { name = "types-requests", marker = "extra == 'dev'" }, { name = "uvicorn", specifier = ">=0.27.0" }, ] -provides-extras = ["telegram", "worker", "browser", "pdf"] +provides-extras = ["telegram", "worker", "browser", "pdf", "dev"] [[package]] name = "jsonpatch" @@ -1124,6 +1347,91 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ff/68/514ffa62860202a5a0a3acbf5c05017ef9df38d4437d2cb44a3cf93d617b/langsmith-0.3.11-py3-none-any.whl", hash = "sha256:0cca22737ef07d3b038a437c141deda37e00add56022582680188b681bec095e", size = 335265, upload-time = "2025-02-25T04:07:27.153Z" }, ] +[[package]] +name = "librt" +version = "0.11.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/40/08/9e7f6b5d2b5bed6ad055cdd5925f192bb403a51280f86b56554d9d0699a2/librt-0.11.0.tar.gz", hash = "sha256:075dc3ef4458a278e0195cbf6ac9d38808d9b906c5a6c7f7f79c3888276a3fb1", size = 200139, upload-time = "2026-05-10T18:17:25.138Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fe/87/2bf31fe17587b29e3f93ec31421e2b1e1c3e349b8bf6c7c313dbad1d5340/librt-0.11.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:93d95bd45b7d58343d8b90d904450a545144eec19a002511163426f8ab1fae29", size = 141092, upload-time = "2026-05-10T18:15:34.795Z" }, + { url = "https://files.pythonhosted.org/packages/cf/08/5c5bf772920b7ebac6e32bc91a643e0ab3870199c0b542356d3baa83970a/librt-0.11.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4ee278c769a713638cdacd4c0436d72156e75df3ebc0166ab2b9dc43acc386c9", size = 142035, upload-time = "2026-05-10T18:15:36.242Z" }, + { url = "https://files.pythonhosted.org/packages/06/20/662a03d254e5b000d838e8b345d83303ddb768c080fd488e40634c0fa66b/librt-0.11.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f230cb1cbc9faaa616f9a678f530ebcf186e414b6bcbd88b960e4ba1b92428d5", size = 475022, upload-time = "2026-05-10T18:15:37.56Z" }, + { url = "https://files.pythonhosted.org/packages/de/f3/aa81523e45184c6ec23dc7f63263362ec55f80a09d424c012359ecbe7e35/librt-0.11.0-cp311-cp311-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:5d63c855d86938d9de93e265c9bd8c705b51ec494de5738340ee93767a686e4b", size = 467273, upload-time = "2026-05-10T18:15:39.182Z" }, + { url = "https://files.pythonhosted.org/packages/6b/6f/59c74b560ca8853834d5501d589c8a2519f4184f273a085ffd0f37a1cc47/librt-0.11.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:993f028be9e96a08d31df3479ac80d99be374d17f3b78e4796b3fd3c913d4e89", size = 497083, upload-time = "2026-05-10T18:15:40.634Z" }, + { url = "https://files.pythonhosted.org/packages/fe/7b/5aa4d2c9600a719401160bf7055417df0b2a47439b9d88286ce45e56b65f/librt-0.11.0-cp311-cp311-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:258d73a0aa66a055e65b2e4d1b8cdb23b9d132c5bb915d9547d804fcaed116cc", size = 489139, upload-time = "2026-05-10T18:15:41.934Z" }, + { url = "https://files.pythonhosted.org/packages/d6/31/9143803d7da6856a69153785768c4936864430eec0fd9461c3ea527d9922/librt-0.11.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:0827efe7854718f04aaddf6496e96960a956e676fe1d0f04eb41511fd8ad06d5", size = 508442, upload-time = "2026-05-10T18:15:43.206Z" }, + { url = "https://files.pythonhosted.org/packages/2f/5a/bce08184488426bda4ccc2c4964ac048c8f68ae89bd7120082eef4233cfd/librt-0.11.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:7753e57d6e12d019c0d8786f1c09c709f4c3fcc57c3887b24e36e6c06ec938b7", size = 514230, upload-time = "2026-05-10T18:15:44.761Z" }, + { url = "https://files.pythonhosted.org/packages/89/8c/bb5e213d254b7505a0e658da199d8ab719086632ce09eef311ab27976523/librt-0.11.0-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:11bd19822431cc21af9f27374e7ae2e58103c7d98bda823536a6c47f6bb2bb3d", size = 494231, upload-time = "2026-05-10T18:15:46.308Z" }, + { url = "https://files.pythonhosted.org/packages/9d/fb/541cdad5b1ab1300398c74c4c9a497b88e5074c21b1244c8f49731d3a284/librt-0.11.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:22bdf239b219d3993761a148ffa134b19e52e9989c84f845d5d7b71d70a17412", size = 537585, upload-time = "2026-05-10T18:15:47.629Z" }, + { url = "https://files.pythonhosted.org/packages/8f/f2/464bb69295c320cb06bddb4f14a4ec67934ee14b2bffb12b19fb7ab287ba/librt-0.11.0-cp311-cp311-win32.whl", hash = "sha256:46c60b61e308eb535fbd6fa622b1ee1bb2815691c1ad9c98bf7b84952ec3bc8d", size = 100509, upload-time = "2026-05-10T18:15:49.157Z" }, + { url = "https://files.pythonhosted.org/packages/6d/e7/a17ee1788f9e4fbf548c19f4afa07c92089b9e24fef6cb2410863781ef4c/librt-0.11.0-cp311-cp311-win_amd64.whl", hash = "sha256:902e546ff044f579ff1c953ff5fce97b636fe9e3943996b2177710c6ef076f73", size = 118628, upload-time = "2026-05-10T18:15:50.345Z" }, + { url = "https://files.pythonhosted.org/packages/cc/c7/6c766214f9f9903bcfcfbef97d807af8d8f5aa3502d247858ab17582d212/librt-0.11.0-cp311-cp311-win_arm64.whl", hash = "sha256:65ac3bc20f78aa0ee5ae84baa68917f89fef4af63e941084dd019a0d0e749f0c", size = 103122, upload-time = "2026-05-10T18:15:52.068Z" }, + { url = "https://files.pythonhosted.org/packages/8b/d0/07c77e067f0838949b43bd89232c29d72efebb9d2801a9750184eb706b71/librt-0.11.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:b87504f1690a23b9a2cca841191a04f83895d4fc2dd04df91d82b1a04ca2ad46", size = 144147, upload-time = "2026-05-10T18:15:53.227Z" }, + { url = "https://files.pythonhosted.org/packages/7a/24/8493538fa4f62f982686398a5b8f68008138a75086abdea19ade64bf4255/librt-0.11.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:40071fc5fe0ce8daa6de616702314a01e1250711682b0523d6ab8d4525910cb3", size = 143614, upload-time = "2026-05-10T18:15:54.657Z" }, + { url = "https://files.pythonhosted.org/packages/ff/1e/f8bad050810d9171f34a1648ed910e56814c2ba61639f2bd53c6377ae24b/librt-0.11.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:137e79445c896a0ea7b265f52d23954e05b64222ee1af69e2cb34219067cbb67", size = 485538, upload-time = "2026-05-10T18:15:56.117Z" }, + { url = "https://files.pythonhosted.org/packages/c0/fe/3594ebfbaf03084ba4b120c9ba5c3183fd938a48725e9bbe6ff0a5159ad8/librt-0.11.0-cp312-cp312-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:cca6644054e78746d8d4ef238681f9c34ff8b584fe6b988ecebb8db3b15e622a", size = 479623, upload-time = "2026-05-10T18:15:57.544Z" }, + { url = "https://files.pythonhosted.org/packages/b0/da/5d1876984b3746c85dbd219dbfcb73c85f54ee263fd32e5b2a632ec14571/librt-0.11.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d5b0eea49f5562861ee8d757a32ef7d559c1d35be2aaaa1ec28941d74c9ffc8a", size = 513082, upload-time = "2026-05-10T18:15:58.805Z" }, + { url = "https://files.pythonhosted.org/packages/19/6e/55bdf5d5ca00c3e18430690bf2c953d8d3ffd3c337418173d33dec985dc9/librt-0.11.0-cp312-cp312-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0d1029d7e1ae1a7e647ed6fb5df8c4ce2dffefb7a9f5fd1376a4554d96dac09f", size = 508105, upload-time = "2026-05-10T18:16:00.2Z" }, + { url = "https://files.pythonhosted.org/packages/07/10/f1f23a7c595ee90ece4d35c851e5d104b1311a887ed1b4ac4c35bbd13da8/librt-0.11.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:bc3ce6b33c5828d9e80592011a5c584cb2ce86edbc4088405f70da47dc1d1b3b", size = 522268, upload-time = "2026-05-10T18:16:01.708Z" }, + { url = "https://files.pythonhosted.org/packages/b6/02/5720f5697a7f54b78b3aefbe20df3a48cedcff1276618c4aa481177942ed/librt-0.11.0-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:936c5995f3514a42111f20099397d8177c79b4d7e70961e396c6f5a0a3566766", size = 527348, upload-time = "2026-05-10T18:16:03.496Z" }, + { url = "https://files.pythonhosted.org/packages/50/db/b4a47c6f91db4ff76348a0b3dd0cc65e090a078b765a810a62ff9434c3d3/librt-0.11.0-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:9bc0ca6ad9381cbe8e4aa6e5726e4c80c78115a6e9723c599ed1d73e092bc49d", size = 516294, upload-time = "2026-05-10T18:16:05.173Z" }, + { url = "https://files.pythonhosted.org/packages/9e/58/9384b2f4eb1ed1d273d40948a7c5c4b2360213b402ef3be4641c06299f9c/librt-0.11.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:070aa8c26c0a74774317a72df8851facc7f0f012a5b406557ac56992d92e1ec8", size = 553608, upload-time = "2026-05-10T18:16:06.839Z" }, + { url = "https://files.pythonhosted.org/packages/21/7b/5aa8848a7c6a9278c79375146da1812e695754ceec5f005e6043461a7315/librt-0.11.0-cp312-cp312-win32.whl", hash = "sha256:6bf14feb84b05ae945277395451998c89c54d0def4070eb5c08de544930b245a", size = 101879, upload-time = "2026-05-10T18:16:08.103Z" }, + { url = "https://files.pythonhosted.org/packages/37/33/8a745436944947575b584231750a41417de1a38cf6a2e9251d1065651c09/librt-0.11.0-cp312-cp312-win_amd64.whl", hash = "sha256:75672f0bc524ede266287d532d7923dbce94c7514ad07627bac3d0c6d92cc4d9", size = 119831, upload-time = "2026-05-10T18:16:09.174Z" }, + { url = "https://files.pythonhosted.org/packages/59/67/a6739ac96e28b7855808bdb0370e250606104a859750d209e5a0716fe7ab/librt-0.11.0-cp312-cp312-win_arm64.whl", hash = "sha256:2f10cf143e4a9bb0f4f5af568a00df94a2d69ef41c2579584454bb0fe5cc642c", size = 103470, upload-time = "2026-05-10T18:16:10.369Z" }, + { url = "https://files.pythonhosted.org/packages/82/61/e59168d4d0bf2bf90f4f0caf7a001bfc60254c3af4586013b04dc3ef517b/librt-0.11.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:78dc31f7fdfe9c9d0eb0e8f42d139db230e826415bbcabd9f0e9faaaee909894", size = 144119, upload-time = "2026-05-10T18:16:11.771Z" }, + { url = "https://files.pythonhosted.org/packages/61/fd/caa1d60b12f7dd79ccea23054e06eeaebe266a5f52c40a6b651069200ce5/librt-0.11.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:fa475675db22290c3158e1d42326d0f5a65f04f44a0e68c3630a25b53560fb9c", size = 143565, upload-time = "2026-05-10T18:16:13.334Z" }, + { url = "https://files.pythonhosted.org/packages/b8/a9/dc744f5c2b4978d48db970be29f22716d3413d28b14ad99740817315cf2c/librt-0.11.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:621db29691044bdeda22e789e482e1b0f3a985d90e3426c9c6d17606416205ea", size = 485395, upload-time = "2026-05-10T18:16:14.729Z" }, + { url = "https://files.pythonhosted.org/packages/8f/21/7f8e97a1e4dae952a5a95948f6f8507a173bc1e669f54340bba6ca1ca31b/librt-0.11.0-cp313-cp313-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:a9010e2ed5b3a9e158c5fd966b3ab7e834bb3d3aacc8f66c91dd4b57a3799230", size = 479383, upload-time = "2026-05-10T18:16:16.321Z" }, + { url = "https://files.pythonhosted.org/packages/a6/6d/d8ee9c114bebf2c50e29ec2aa940826fccb62a645c3e4c18760987d0e16d/librt-0.11.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7c39513d8b7477a2e1ed8c43fc21c524e8d5a0f8d4e8b7b074dbdbe7820a08e2", size = 513010, upload-time = "2026-05-10T18:16:17.647Z" }, + { url = "https://files.pythonhosted.org/packages/f0/43/0b5708af2bd30a46400e72ba6bdaa8f066f15fb9a688527e34220e8d6c06/librt-0.11.0-cp313-cp313-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:7aef3cf1d5af86e770ab04bfd993dfc4ae8b8c17f66fb77dd4a7d50de7bbb1a3", size = 508433, upload-time = "2026-05-10T18:16:19.309Z" }, + { url = "https://files.pythonhosted.org/packages/4a/50/356187247d09013490481033183b3532b58acf8028bcb34b2b56a375c9b2/librt-0.11.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:557183ddc36babe46b27dd60facbd5adb4492181a5be887587d57cda6e092f21", size = 522595, upload-time = "2026-05-10T18:16:20.642Z" }, + { url = "https://files.pythonhosted.org/packages/40/e7/c6ac4240899c7f3248079d5a9900debe0dadb3fdeaf856684c987105ba47/librt-0.11.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:83d3e1f72bd42f6c5c0b7daec530c3f829bd02db42c70b8ddf0c2d90a2459930", size = 527255, upload-time = "2026-05-10T18:16:22.352Z" }, + { url = "https://files.pythonhosted.org/packages/eb/b5/a81322dbeedeeaf9c1ee6f001734d28a09d8383ac9e6779bc24bbd0743c6/librt-0.11.0-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:4ce1f21fbe589bc1afd7872dece84fb0e1144f794a288e58a10d2c54a55c43be", size = 516847, upload-time = "2026-05-10T18:16:23.627Z" }, + { url = "https://files.pythonhosted.org/packages/ae/66/6e6323787d592b55204a42595ff1102da5115601b53a7e9ddebc889a6da5/librt-0.11.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:970b09f7044ea2b64c9da42fd3d335666518cfd1c6e8a182c95da73d0214b41e", size = 553920, upload-time = "2026-05-10T18:16:25.025Z" }, + { url = "https://files.pythonhosted.org/packages/9c/21/623f8ca230857102066d9ca8c6c1734995908c4d0d1bee7bb2ef0021cb33/librt-0.11.0-cp313-cp313-win32.whl", hash = "sha256:78fddc31cd4d3caa897ad5d31f856b1faadc9474021ad6cb182b9018793e254e", size = 101898, upload-time = "2026-05-10T18:16:26.649Z" }, + { url = "https://files.pythonhosted.org/packages/b3/1d/b4ebd44dd723f768469007515cb92251e0ae286c94c140f374801140fa74/librt-0.11.0-cp313-cp313-win_amd64.whl", hash = "sha256:8ca8aa88751a775870b764e93bad5135385f563cb8dcee399abf034ea4d3cb47", size = 119812, upload-time = "2026-05-10T18:16:27.859Z" }, + { url = "https://files.pythonhosted.org/packages/3b/e4/b2f4ca7965ca373b491cdb4bc25cdb30c1649ca81a8782056a83850292a9/librt-0.11.0-cp313-cp313-win_arm64.whl", hash = "sha256:96f044bb325fd9cf1a723015638c219e9143f0dfbc0ca54c565df2b7fc748b44", size = 103448, upload-time = "2026-05-10T18:16:29.066Z" }, + { url = "https://files.pythonhosted.org/packages/29/eb/dbce197da4e227779e56b5735f2decc3eb36e55a1cdbf1bd65d6639d76c1/librt-0.11.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:4a017a95e5837dc15a8c5661d60e05daa96b90908b1aa6b7acdf443cd25c8ebd", size = 143345, upload-time = "2026-05-10T18:16:30.674Z" }, + { url = "https://files.pythonhosted.org/packages/76/a3/254bebd0c11c8ba684018efb8006ff22e466abce445215cca6c778e7d9de/librt-0.11.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:b1ecbd9819deccc39b7542bf4d2a740d8a620694d39989e58661d3763458f8d4", size = 143131, upload-time = "2026-05-10T18:16:32.037Z" }, + { url = "https://files.pythonhosted.org/packages/f1/3f/f77d6122d21ac7bf6ae8a7dfced1bd2a7ac545d3273ebdcaf8042f6d619f/librt-0.11.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7da327dacd7be8f8ec36547373550744a3cc0e536d54665cd83f8bcd961200e8", size = 477024, upload-time = "2026-05-10T18:16:33.493Z" }, + { url = "https://files.pythonhosted.org/packages/ac/0a/2c996dadebaa7d9bbbd43ef2d4f3e66b6da545f838a41694ef6172cebec8/librt-0.11.0-cp314-cp314-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:0dc56b1f8d06e60db362cc3fdae206681817f86ce4725d34511473487f12a34b", size = 474221, upload-time = "2026-05-10T18:16:34.864Z" }, + { url = "https://files.pythonhosted.org/packages/0a/7e/f5d92af8486b8272c23b3e686b46ff72d89c8169585eb61eef01a2ac7147/librt-0.11.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:05fb8fb2ab90e21c8d12ea240d744ad514da9baf381ebfa70d91d20d21713175", size = 505174, upload-time = "2026-05-10T18:16:36.705Z" }, + { url = "https://files.pythonhosted.org/packages/af/1a/cb0734fe86398eb33193ab753b7326255c74cac5eb09e76b9b16536e7adb/librt-0.11.0-cp314-cp314-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:cae74872be221df4374d10fec61f93ed1513b9546ea84f2c0bf73ab3e9bd0b03", size = 497216, upload-time = "2026-05-10T18:16:38.418Z" }, + { url = "https://files.pythonhosted.org/packages/18/06/094820f91558b66e29943c0ec41c9914f460f48dd51fc503c3101e10842d/librt-0.11.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:32bcc918c0148eb7e3d57385125bac7e5f9e4359d05f07448b09f6f778c2f31c", size = 513921, upload-time = "2026-05-10T18:16:39.848Z" }, + { url = "https://files.pythonhosted.org/packages/0b/c2/00de9018871a282f530cacb457d5ec0428f6ac7e6fedde9aff7468d9fb04/librt-0.11.0-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:f9743fc99135d5f78d2454435615f6dec0473ca507c26ce9d92b10b562a280d3", size = 520850, upload-time = "2026-05-10T18:16:41.471Z" }, + { url = "https://files.pythonhosted.org/packages/51/9d/64631832348fd1834fb3a61b996434edddaaf25a31d03b0a76273159d2cf/librt-0.11.0-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:5ba067f4aadae8fda802d91d2124c90c42195ff32d9161d3549e6d05cfe26f96", size = 504237, upload-time = "2026-05-10T18:16:43.15Z" }, + { url = "https://files.pythonhosted.org/packages/a5/ec/ae5525eb16edc827a044e7bb8777a455ff95d4bca9379e7e6bddd7383647/librt-0.11.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:de3bf945454d032f9e390b85c4072e0a0570bf825421c8be0e71209fa65e1abe", size = 546261, upload-time = "2026-05-10T18:16:44.408Z" }, + { url = "https://files.pythonhosted.org/packages/5a/09/adce371f27ca039411da9659f7430fcc2ba6cd0c7b3e4467a0f091be7fa9/librt-0.11.0-cp314-cp314-win32.whl", hash = "sha256:d2277a05f6dcb9fd13db9566aac4fabd68c3ea1ea46ee5567d4eef8efa495a2f", size = 96965, upload-time = "2026-05-10T18:16:46.039Z" }, + { url = "https://files.pythonhosted.org/packages/d6/ee/8ac720d98548f173c7ce2e632a7ca94673f74cacd5c8162a84af5b35958a/librt-0.11.0-cp314-cp314-win_amd64.whl", hash = "sha256:ab73e8db5e3f564d812c1f5c3a175930a5f9bc96ccb5e3b22a34d7858b401cf7", size = 115151, upload-time = "2026-05-10T18:16:47.133Z" }, + { url = "https://files.pythonhosted.org/packages/94/20/c900cf14efeb09b6bef2b2dff20779f73464b97fd58d1c6bccc379588ae3/librt-0.11.0-cp314-cp314-win_arm64.whl", hash = "sha256:aea3caa317752e3a466fa8af45d91ee0ea8c7fdd96e42b0a8dd9b76a7931eba1", size = 98850, upload-time = "2026-05-10T18:16:48.597Z" }, + { url = "https://files.pythonhosted.org/packages/0c/71/944bfe4b64e12abffcd3c15e1cce07f72f3d55655083786285f4dedeb532/librt-0.11.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:d1b36540d7aaf9b9101b3a6f376c8d8e9f7a9aec93ed05918f2c69d493ffef72", size = 151138, upload-time = "2026-05-10T18:16:49.839Z" }, + { url = "https://files.pythonhosted.org/packages/b6/10/99e64a5c86989357fda078c8143c533389585f6473b7439172dd8f3b3b2d/librt-0.11.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:efbb343ab2ce3540f4ecbe6315d677ed70f37cd9a72b1e58066c918ca83acbaa", size = 151976, upload-time = "2026-05-10T18:16:51.062Z" }, + { url = "https://files.pythonhosted.org/packages/21/31/5072ad880946d83e5ea4147d6d018c78eefce85b77819b19bdd0ee229435/librt-0.11.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:aa0dd688aab3f7914d3e6e5e3554978e0383312fb8e771d84be008a35b9ee548", size = 557927, upload-time = "2026-05-10T18:16:52.632Z" }, + { url = "https://files.pythonhosted.org/packages/5e/8d/70b5fb7cfbab60edbe7381614ab985da58e144fbf465c86d44c95f43cdca/librt-0.11.0-cp314-cp314t-manylinux2014_i686.manylinux_2_17_i686.manylinux_2_28_i686.whl", hash = "sha256:f5fb36b8c6c63fdcbb1d526d94c0d1331610d43f4118cc1beb4efef4f3faacb2", size = 539698, upload-time = "2026-05-10T18:16:53.934Z" }, + { url = "https://files.pythonhosted.org/packages/fa/a3/ba3495a0b3edbd24a4cae0d1d3c64f39a9fc45d06e812101289b50c1a619/librt-0.11.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4a9a237d13addb93715b6fee74023d5ee3469b53fce527626c0e088aa585805f", size = 577162, upload-time = "2026-05-10T18:16:55.589Z" }, + { url = "https://files.pythonhosted.org/packages/f7/db/36e25fb81f99937ff1b96612a1dc9fd66f039cb9cc3aee12c01fac31aab9/librt-0.11.0-cp314-cp314t-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5ddd17bd87b2c56ddd60e546a7984a2e64c4e8eab92fb4cf3830a48ad5469d51", size = 566494, upload-time = "2026-05-10T18:16:56.975Z" }, + { url = "https://files.pythonhosted.org/packages/33/0d/3f622b47f0b013eeb9cf4cc07ae9bfe378d832a4eec998b2b209fe84244d/librt-0.11.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:bd43992b4473d42f12ff9e68326079f0696d9d4e6000e8f39a0238d482ba6ee2", size = 596858, upload-time = "2026-05-10T18:16:58.374Z" }, + { url = "https://files.pythonhosted.org/packages/a9/02/71b90bc93039c46a2000651f6ad60122b114c8f54c4ad306e0e96f5b75ad/librt-0.11.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:f8e3e8056dd674e279741485e2e512d6e9a751c7455809d0114e6ebf8d781085", size = 590318, upload-time = "2026-05-10T18:16:59.676Z" }, + { url = "https://files.pythonhosted.org/packages/04/04/418cb3f75621e2b761fb1ab0f017f4d70a1a72a6e7c74ee4f7e8d198c2f3/librt-0.11.0-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:c1f708d8ae9c56cf38a903c44297243d2ec83fd82b396b977e0144a3e76217e3", size = 575115, upload-time = "2026-05-10T18:17:01.007Z" }, + { url = "https://files.pythonhosted.org/packages/cc/2c/5a2183ac58dd911f26b5d7e7d7d8f1d87fcecdddd99d6c12169a258ff62c/librt-0.11.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:0add982e0e7b9fc14cf4b33789d5f13f66581889b88c2f58099f6ce8f92617bd", size = 617918, upload-time = "2026-05-10T18:17:02.682Z" }, + { url = "https://files.pythonhosted.org/packages/15/1f/dc6771a52592a4451be6effa200cbfc9cec61e4393d3033d81a9d307961d/librt-0.11.0-cp314-cp314t-win32.whl", hash = "sha256:2b481d846ac894c4e8403c5fd0e87c5d11d6499e404b474602508a224ff531c8", size = 103562, upload-time = "2026-05-10T18:17:03.99Z" }, + { url = "https://files.pythonhosted.org/packages/62/4a/7d1415567027286a75ba1093ec4aca11f073e0f559c530cf3e0a757ad55c/librt-0.11.0-cp314-cp314t-win_amd64.whl", hash = "sha256:28edb433edde181112a908c78907af28f964eabc15f4dd16c9d66c834302677c", size = 124327, upload-time = "2026-05-10T18:17:05.465Z" }, + { url = "https://files.pythonhosted.org/packages/ce/62/b40b382fa0c66fee1478073eb8db352a4a6beda4a1adccf1df911d8c289c/librt-0.11.0-cp314-cp314t-win_arm64.whl", hash = "sha256:dee008f20b542e3cd162ba338a7f9ec0f6d23d395f66fe8aeeec3c9d067ea253", size = 102572, upload-time = "2026-05-10T18:17:06.809Z" }, +] + +[[package]] +name = "license-expression" +version = "30.4.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "boolean-py" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/40/71/d89bb0e71b1415453980fd32315f2a037aad9f7f70f695c7cec7035feb13/license_expression-30.4.4.tar.gz", hash = "sha256:73448f0aacd8d0808895bdc4b2c8e01a8d67646e4188f887375398c761f340fd", size = 186402, upload-time = "2025-07-22T11:13:32.17Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/af/40/791891d4c0c4dab4c5e187c17261cedc26285fd41541577f900470a45a4d/license_expression-30.4.4-py3-none-any.whl", hash = "sha256:421788fdcadb41f049d2dc934ce666626265aeccefddd25e162a26f23bcbf8a4", size = 120615, upload-time = "2025-07-22T11:13:31.217Z" }, +] + [[package]] name = "lxml" version = "6.1.1" @@ -1402,6 +1710,66 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/99/b7/b9e70fde2c0f0c9af4cc5277782a89b66d35948ea3369ec9f598358c3ac5/multidict-6.1.0-py3-none-any.whl", hash = "sha256:48e171e52d1c4d33888e529b999e5900356b9ae588c2f09a52dcefb158b27506", size = 10051, upload-time = "2024-09-09T23:49:36.506Z" }, ] +[[package]] +name = "mypy" +version = "2.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "ast-serialize" }, + { name = "librt", marker = "platform_python_implementation != 'PyPy'" }, + { name = "mypy-extensions" }, + { name = "pathspec" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/82/15/cca9d88503549ed6fedeaa1d448cdddd542ee8a490232d732e278036fbf2/mypy-2.1.0.tar.gz", hash = "sha256:81e76ad12c2d804512e9b13240d1588316531bfba07558286078bfbce9613633", size = 3898359, upload-time = "2026-05-11T18:37:36.237Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/a1/639f3024794a2a15899cb90707fe02e044c4412794c39c5769fd3df2e2ef/mypy-2.1.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a683016b16fe2f572dc04c72be7ee0504ac1605a265d0200f5cea695fb788f41", size = 14691685, upload-time = "2026-05-11T18:33:27.973Z" }, + { url = "https://files.pythonhosted.org/packages/3b/08/9a585dea4325f20d8b80dc78623fa50d1fd2173b710f6237afd6ba6ab39b/mypy-2.1.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:1a293c534adb55271fef24a26da04b855540a8c13cc07bc5917b9fd2c394f2ca", size = 13555165, upload-time = "2026-05-11T18:32:16.107Z" }, + { url = "https://files.pythonhosted.org/packages/81/dc/7c42cc9c6cb01e8eb09961f1f738741d3e9c7e9d5c5b30ec69222625cd5f/mypy-2.1.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7406f4d048e71e576f5356d317e5b0a9e666dfd966bd99f9d14ca06e1a341538", size = 13994376, upload-time = "2026-05-11T18:32:39.256Z" }, + { url = "https://files.pythonhosted.org/packages/d4/fa/285946c33bce716e082c11dfeee9ee196eaf1f5042efb3581a31f9f205e4/mypy-2.1.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e0210d626fc8b31ccc90233754c7bc90e1f43205e85d96387f7db1285b55c398", size = 14864618, upload-time = "2026-05-11T18:34:49.765Z" }, + { url = "https://files.pythonhosted.org/packages/2b/83/82397f48af6c27e295d57979ded8490c9829040152cf7571b2f026aeb9a0/mypy-2.1.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:3712c20deed54e814eaaa825603bada8ea1c390670a397c95b98405347acc563", size = 15102063, upload-time = "2026-05-11T18:34:05.855Z" }, + { url = "https://files.pythonhosted.org/packages/40/68/b02dec39057b88eb03dc0aa854732e26e8361f34f9d0e20c7614967d1eba/mypy-2.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:fcaa0e479066e31f7cceb6a3bea39cb22b2ff51a6b2f24f193d19179ba17c389", size = 11060564, upload-time = "2026-05-11T18:35:36.494Z" }, + { url = "https://files.pythonhosted.org/packages/cf/a8/ea3dcbef31f99b634f2ee23bb0321cbc8c1b388b76a861eb849f13c347dc/mypy-2.1.0-cp311-cp311-win_arm64.whl", hash = "sha256:0b1a5260c95aa443083f9ed3592662941951bca3d4ca224a5dc517c38b7cf666", size = 9966983, upload-time = "2026-05-11T18:37:14.139Z" }, + { url = "https://files.pythonhosted.org/packages/95/b1/55861beb5c339b44f9a2ba92df9e2cb1eeb4ae1eee674cdf7772c797778b/mypy-2.1.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:244358bf1c0da7722230bce60683d52e8e9fd030554926f15b747a84efb5b3af", size = 14874381, upload-time = "2026-05-11T18:37:31.784Z" }, + { url = "https://files.pythonhosted.org/packages/0b/b3/b7f770114b7d0ac92d0f76e8d93c2780844a70488a90e91821927850da86/mypy-2.1.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4ec7c57657493c7a75534df2751c8ae2cda383c16ecc55d2106c54476b1b16f6", size = 13665501, upload-time = "2026-05-11T18:34:23.063Z" }, + { url = "https://files.pythonhosted.org/packages/b6/f3/8ae2037967e2126689a0c11d99e2b707134a565191e92c60ca2572aec60a/mypy-2.1.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d8161b6ff4392410023224f0969d17db93e1e154bc3e4ba62598e720723ae211", size = 14045750, upload-time = "2026-05-11T18:31:48.151Z" }, + { url = "https://files.pythonhosted.org/packages/a0/32/615eb5911859e43d054941b0d0a7d06cfa2870eba86529cf385b052b111c/mypy-2.1.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bf03e12003084a67395184d3eb8cbd6a489dc3655b5664b28c210a9e2403ab0b", size = 15061630, upload-time = "2026-05-11T18:37:06.898Z" }, + { url = "https://files.pythonhosted.org/packages/d4/03/4eafbfff8bfab1b87082741eae6e6a624028c984e6708b73bce2a8570c9d/mypy-2.1.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:20509760fd791c51579d573153407d226385ec1f8bcce55d730b354f3336bc22", size = 15288831, upload-time = "2026-05-11T18:31:18.07Z" }, + { url = "https://files.pythonhosted.org/packages/99/ee/919661478e5891a3c96e549c036e467e64563ab85995b10c53c8358e16a3/mypy-2.1.0-cp312-cp312-win_amd64.whl", hash = "sha256:6753d0c1fdd6b1a23b9e4f283ce80b2153b724adcb2653b20b85a8a28ac6436b", size = 11135228, upload-time = "2026-05-11T18:34:31.23Z" }, + { url = "https://files.pythonhosted.org/packages/24/0a/6a12b9782ca0831a553192f351679f4548abc9d19a7cc93bb7feb02084c7/mypy-2.1.0-cp312-cp312-win_arm64.whl", hash = "sha256:98ebb6589bb3b6d0c6f0c459d53ca55b8091fbc13d277c4041c885392e8195e8", size = 10040684, upload-time = "2026-05-11T18:36:48.199Z" }, + { url = "https://files.pythonhosted.org/packages/6e/dd/c7191469c777f07689c032a8f7326e393ea34c92d6d76eb7ce5ba57ea66d/mypy-2.1.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:35aac3bb114e03888f535d5eb51b8bafbb3266586b599da1940f9b1be3ec5bd5", size = 14852174, upload-time = "2026-05-11T18:31:38.929Z" }, + { url = "https://files.pythonhosted.org/packages/55/8c/aed55408879043d72bb9135f4d0d19a02b886dd569631e113e3d2706cb8d/mypy-2.1.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:8de55a8c861f2a49331f807be98d90caeceeef520bde13d43a160207f8af613e", size = 13651542, upload-time = "2026-05-11T18:36:04.636Z" }, + { url = "https://files.pythonhosted.org/packages/3a/8e/f371a824b1f1fa8ea6e3dbb8703d232977d572be2329554a3bc4d960302f/mypy-2.1.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5fdf2941a07434af755837d9880f7d7d25f1dacb1af9dcd4b9b66f2220a3024e", size = 14033929, upload-time = "2026-05-11T18:35:55.742Z" }, + { url = "https://files.pythonhosted.org/packages/94/21/f54be870d6dd53a82c674407e0f8eed7174b05ec78d42e5abd7b42e84fd5/mypy-2.1.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e195b817c13f02352a9c124301f9f30f078405444679b6753c1b96b6eed37285", size = 15039200, upload-time = "2026-05-11T18:33:10.281Z" }, + { url = "https://files.pythonhosted.org/packages/17/99/bf21748626a40ce59fd29a39386ab46afec88b7bd2f0fa6c3a97c995523f/mypy-2.1.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:5431d42af987ebd92ba2f71d45c85ed41d8e6ca9f5fd209a69f68f707d2469e5", size = 15272690, upload-time = "2026-05-11T18:32:07.205Z" }, + { url = "https://files.pythonhosted.org/packages/d6/d7/9e90d2cf47100bea550ed2bc7b0d4de3a62181d84d5e37da0003e8462637/mypy-2.1.0-cp313-cp313-win_amd64.whl", hash = "sha256:767fe8c66dc3e01e19e1737d4c38ebefead16125e1b8e58ad421903b376f5c65", size = 11147435, upload-time = "2026-05-11T18:33:56.477Z" }, + { url = "https://files.pythonhosted.org/packages/ec/46/e5c449e858798e35ffc90946282a27c62a77be743fe17480e4977374eb91/mypy-2.1.0-cp313-cp313-win_arm64.whl", hash = "sha256:ecfe70d43775ab99562ab128ce49854a362044c9f894961f68f898c23cb7429d", size = 10035052, upload-time = "2026-05-11T18:32:30.049Z" }, + { url = "https://files.pythonhosted.org/packages/b0/ca/b279a672e874aedd5498ae25f722dacc8aa86bbffb939b3f97cbb1cf6686/mypy-2.1.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:7354c5a7f69d9345c3d6e69921d57088eea3ddeeb6b20d34c1b3855b02c36ec2", size = 14848422, upload-time = "2026-05-11T18:35:45.984Z" }, + { url = "https://files.pythonhosted.org/packages/27/e6/3efe56c631d959b9b4454e208b0ac4b7f4f58b404c89f8bec7b49efdfc21/mypy-2.1.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:49890d4f76ac9e06ec117f9e09f3174da70a620a0c300953d8595c926e80947f", size = 13677374, upload-time = "2026-05-11T18:36:57.188Z" }, + { url = "https://files.pythonhosted.org/packages/84/7f/8107ea87a44fd1f1b59882442f033c9c3488c127201b1d1d15f1cbd6022e/mypy-2.1.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:761be68e023ef5d94678772396a8af1220030f80837a3afd8d0aef3b419666f4", size = 14055743, upload-time = "2026-05-11T18:35:18.361Z" }, + { url = "https://files.pythonhosted.org/packages/51/4d/b6d34db183133b83761b9199a82d31557cdbb70a380d8c3b3438e11882a3/mypy-2.1.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c90345fc182dc363b891350457ec69c35140858538f38b4540845afcc32b1aef", size = 15020937, upload-time = "2026-05-11T18:34:59.618Z" }, + { url = "https://files.pythonhosted.org/packages/ff/d7/f08360c691d758acb02f45022c34d98b92892f4ea756644e1000d4b9f3d8/mypy-2.1.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:b84802e7b5a6daf1f5e15bc9fcd7ddae77be13981ffab037f1c67bb84d67d135", size = 15253371, upload-time = "2026-05-11T18:36:41.081Z" }, + { url = "https://files.pythonhosted.org/packages/67/1b/09460a13719530a19bce27bd3bc8449e83569dd2ba7faf51c9c3c30c0b61/mypy-2.1.0-cp314-cp314-win_amd64.whl", hash = "sha256:022c771234936ceac541ebaf836fe9e2abeb3f5e09aff21588fe543ff006fe21", size = 11326429, upload-time = "2026-05-11T18:34:13.526Z" }, + { url = "https://files.pythonhosted.org/packages/40/62/75dbf0f82f7b6680340efc614af29dd0b3c17b8a4f1cd09b8bd2fd6bc814/mypy-2.1.0-cp314-cp314-win_arm64.whl", hash = "sha256:498207db725cec88829a6a5c2fc771205fd043719ef98bc49aba8fb9fc4e6d57", size = 10218799, upload-time = "2026-05-11T18:32:23.491Z" }, + { url = "https://files.pythonhosted.org/packages/b2/66/caca04ed7d972fb6eb6dd1ccd6df1de5c38fae8c5b3dc1c4e8e0d85ee6b9/mypy-2.1.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7d5e5cad0efeba72b93cd17490cc0d69c5ac9ca132994fe3fb0314808aeeb83e", size = 15923458, upload-time = "2026-05-11T18:35:28.64Z" }, + { url = "https://files.pythonhosted.org/packages/ed/52/2d90cbe49d014b13ed7ff337930c30bad35893fe38a1e4641e756bb62191/mypy-2.1.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ff715050c127d724fd260a2e666e7747fdd83511c0c47d449d98238970aef780", size = 14757697, upload-time = "2026-05-11T18:36:14.208Z" }, + { url = "https://files.pythonhosted.org/packages/ac/37/d98f4a14e081b238992d0ed96b6d39c7cc0148c9699eb71eaa68629665ea/mypy-2.1.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:82208da9e09414d520e912d3e462d454854bed0810b71540bb016dcbca7308fd", size = 15405638, upload-time = "2026-05-11T18:33:48.249Z" }, + { url = "https://files.pythonhosted.org/packages/a3/c2/15c46613b24a84fad2aea1248bf9619b99c2767ae9071fe224c179a0b7d4/mypy-2.1.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e79ebc1b904b84f0310dff7469655a9c36c7a68bddb37bdd42b67a332df61d08", size = 16215852, upload-time = "2026-05-11T18:32:50.296Z" }, + { url = "https://files.pythonhosted.org/packages/5c/90/9c16a57f482c76d25f6379762b56bbf65c711d8158cf271fb2802cfb0640/mypy-2.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:e583edc957cfb0deb142079162ae826f58449b116c1d442f2d91c69d9fced081", size = 16452695, upload-time = "2026-05-11T18:33:38.182Z" }, + { url = "https://files.pythonhosted.org/packages/0f/4c/215a4eeb63cacc5f17f516691ea7285d11e249802b942476bff15922a314/mypy-2.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:b33b6cd332695bba180d55e717a79d3038e479a2c49cc5eb3d53603409b9a5d7", size = 12866622, upload-time = "2026-05-11T18:34:39.945Z" }, + { url = "https://files.pythonhosted.org/packages/4b/50/1043e1db5f455ffe4c9ab22747cd8ca2bc492b1e4f4e21b130a44ee2b217/mypy-2.1.0-cp314-cp314t-win_arm64.whl", hash = "sha256:4f910fe825376a7b66ef7ca8c98e5a149e8cd64c19ae71d84047a74ee060d4e6", size = 10610798, upload-time = "2026-05-11T18:36:31.444Z" }, + { url = "https://files.pythonhosted.org/packages/0d/2a/13ca1f292f6db1b98ff495ef3467736b331621c5917cad984b7043e7348d/mypy-2.1.0-py3-none-any.whl", hash = "sha256:a663814603a5c563fb87a4f96fb473eeb30d1f5a4885afcf44f9db000a366289", size = 2693302, upload-time = "2026-05-11T18:31:29.246Z" }, +] + +[[package]] +name = "mypy-extensions" +version = "1.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a2/6e/371856a3fb9d31ca8dac321cda606860fa4548858c0cc45d9d1d4ca2628b/mypy_extensions-1.1.0.tar.gz", hash = "sha256:52e68efc3284861e772bbcd66823fde5ae21fd2fdb51c62a211403730b916558", size = 6343, upload-time = "2025-04-22T14:54:24.164Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/79/7b/2c79738432f5c924bef5071f933bcc9efd0473bac3b4aa584a6f7c1c8df8/mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505", size = 4963, upload-time = "2025-04-22T14:54:22.983Z" }, +] + [[package]] name = "narwhals" version = "1.28.0" @@ -1443,7 +1811,8 @@ name = "numpy" version = "2.2.3" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version >= '3.14'", + "python_full_version >= '3.15'", + "python_full_version == '3.14.*'", "python_full_version >= '3.12.4' and python_full_version < '3.14'", "python_full_version >= '3.12' and python_full_version < '3.12.4'", ] @@ -1557,6 +1926,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/27/f1/1d7ec15b20f8ce9300bc850de1e059132b88990e46cd0ccac29cbf11e4f9/orjson-3.10.15-cp313-cp313-win_amd64.whl", hash = "sha256:fd56a26a04f6ba5fb2045b0acc487a63162a958ed837648c5781e1fe3316cfbf", size = 133444, upload-time = "2025-01-18T15:54:42.076Z" }, ] +[[package]] +name = "packageurl-python" +version = "0.17.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/d6/3b5a4e3cfaef7a53869a26ceb034d1ff5e5c27c814ce77260a96d50ab7bb/packageurl_python-0.17.6.tar.gz", hash = "sha256:1252ce3a102372ca6f86eb968e16f9014c4ba511c5c37d95a7f023e2ca6e5c25", size = 50618, upload-time = "2025-11-24T15:20:17.998Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b1/2f/c7277b7615a93f51b5fbc1eacfc1b75e8103370e786fd8ce2abf6e5c04ab/packageurl_python-0.17.6-py3-none-any.whl", hash = "sha256:31a85c2717bc41dd818f3c62908685ff9eebcb68588213745b14a6ee9e7df7c9", size = 36776, upload-time = "2025-11-24T15:20:16.962Z" }, +] + [[package]] name = "packaging" version = "24.2" @@ -1608,6 +1986,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ab/5f/b38085618b950b79d2d9164a711c52b10aefc0ae6833b96f626b7021b2ed/pandas-2.2.3-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:ad5b65698ab28ed8d7f18790a0dc58005c7629f227be9ecc1072aa74c0c1d43a", size = 13098436, upload-time = "2024-09-20T13:09:48.112Z" }, ] +[[package]] +name = "pathspec" +version = "1.1.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5a/82/42f767fc1c1143d6fd36efb827202a2d997a375e160a71eb2888a925aac1/pathspec-1.1.1.tar.gz", hash = "sha256:17db5ecd524104a120e173814c90367a96a98d07c45b2e10c2f3919fff91bf5a", size = 135180, upload-time = "2026-04-27T01:46:08.907Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" }, +] + [[package]] name = "pillow" version = "11.1.0" @@ -1657,6 +2044,70 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/cf/6c/41c21c6c8af92b9fea313aa47c75de49e2f9a467964ee33eb0135d47eb64/pillow-11.1.0-cp313-cp313t-win_arm64.whl", hash = "sha256:67cd427c68926108778a9005f2a04adbd5e67c442ed21d95389fe1d595458756", size = 2377651, upload-time = "2025-01-02T08:12:53.356Z" }, ] +[[package]] +name = "pip" +version = "26.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/91/47e7d486260f618783899587af63ccf7980fb60245c3e63dd4571c6b57ad/pip-26.1.2.tar.gz", hash = "sha256:f49cd134c61cf2fd75e0ce2676db03e4054504a5a4986d00f8299ae632dc4605", size = 1840799, upload-time = "2026-05-31T17:33:58.56Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/95/6b5cb3461ea5673ba0995989746db58eb18b91b54dbf331e72f569540946/pip-26.1.2-py3-none-any.whl", hash = "sha256:382ff9f685ee3bc25864f820aa50505825f10f5458ffff07e30a6d96e5715cab", size = 1813144, upload-time = "2026-05-31T17:33:56.772Z" }, +] + +[[package]] +name = "pip-api" +version = "0.0.34" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pip" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b9/f1/ee85f8c7e82bccf90a3c7aad22863cc6e20057860a1361083cd2adacb92e/pip_api-0.0.34.tar.gz", hash = "sha256:9b75e958f14c5a2614bae415f2adf7eeb54d50a2cfbe7e24fd4826471bac3625", size = 123017, upload-time = "2024-07-09T20:32:30.641Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/91/f7/ebf5003e1065fd00b4cbef53bf0a65c3d3e1b599b676d5383ccb7a8b88ba/pip_api-0.0.34-py3-none-any.whl", hash = "sha256:8b2d7d7c37f2447373aa2cf8b1f60a2f2b27a84e1e9e0294a3f6ef10eb3ba6bb", size = 120369, upload-time = "2024-07-09T20:32:29.099Z" }, +] + +[[package]] +name = "pip-audit" +version = "2.10.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cachecontrol", extra = ["filecache"] }, + { name = "cyclonedx-python-lib" }, + { name = "packaging" }, + { name = "pip-api" }, + { name = "pip-requirements-parser" }, + { name = "platformdirs" }, + { name = "requests" }, + { name = "rich" }, + { name = "tomli" }, + { name = "tomli-w" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bd/89/0e999b413facab81c33d118f3ac3739fd02c0622ccf7c4e82e37cebd8447/pip_audit-2.10.0.tar.gz", hash = "sha256:427ea5bf61d1d06b98b1ae29b7feacc00288a2eced52c9c58ceed5253ef6c2a4", size = 53776, upload-time = "2025-12-01T23:42:40.612Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/be/f3/4888f895c02afa085630a3a3329d1b18b998874642ad4c530e9a4d7851fe/pip_audit-2.10.0-py3-none-any.whl", hash = "sha256:16e02093872fac97580303f0848fa3ad64f7ecf600736ea7835a2b24de49613f", size = 61518, upload-time = "2025-12-01T23:42:39.193Z" }, +] + +[[package]] +name = "pip-requirements-parser" +version = "32.0.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "packaging" }, + { name = "pyparsing" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/5e/2a/63b574101850e7f7b306ddbdb02cb294380d37948140eecd468fae392b54/pip-requirements-parser-32.0.1.tar.gz", hash = "sha256:b4fa3a7a0be38243123cf9d1f3518da10c51bdb165a2b2985566247f9155a7d3", size = 209359, upload-time = "2022-12-21T15:25:22.732Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/d0/d04f1d1e064ac901439699ee097f58688caadea42498ec9c4b4ad2ef84ab/pip_requirements_parser-32.0.1-py3-none-any.whl", hash = "sha256:4659bc2a667783e7a15d190f6fccf8b2486685b6dba4c19c3876314769c57526", size = 35648, upload-time = "2022-12-21T15:25:21.046Z" }, +] + +[[package]] +name = "platformdirs" +version = "4.10.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d7/47/e4501f49c178ae1d9f4a75073fda4204f52647993f075a9db4d14930e0c5/platformdirs-4.10.0.tar.gz", hash = "sha256:31e761a6a0ca04faf7353ea759bdba55652be214725111e5aac52dfa29d4bef7", size = 31224, upload-time = "2026-05-28T03:32:53.587Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/81/e6/cd9575ac904136b3cbf7aa7ee819ef86eedb7274e46f230e94ea4342e729/platformdirs-4.10.0-py3-none-any.whl", hash = "sha256:fb516cdb12eb0d857d0cd85a7c57cea4d060bee4578d6cf5a14dfdf8cbf8784a", size = 22743, upload-time = "2026-05-28T03:32:52.175Z" }, +] + [[package]] name = "playwright" version = "1.60.0" @@ -1827,6 +2278,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/20/be/b732c8418ffa5bcfda002890f5dc4c869fc17db66ff11f53b17cfe44afc0/psycopg2_binary-2.9.12-cp314-cp314-win_amd64.whl", hash = "sha256:f12ae41fcafadb39b2785e64a40f9db05d6de2ac114077457e0e7c597f3af980", size = 2848762, upload-time = "2026-04-20T23:35:46.421Z" }, ] +[[package]] +name = "py-serializable" +version = "2.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "defusedxml" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/73/21/d250cfca8ff30c2e5a7447bc13861541126ce9bd4426cd5d0c9f08b5547d/py_serializable-2.1.0.tar.gz", hash = "sha256:9d5db56154a867a9b897c0163b33a793c804c80cee984116d02d49e4578fc103", size = 52368, upload-time = "2025-07-21T09:56:48.07Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9b/bf/7595e817906a29453ba4d99394e781b6fabe55d21f3c15d240f85dd06bb1/py_serializable-2.1.0-py3-none-any.whl", hash = "sha256:b56d5d686b5a03ba4f4db5e769dc32336e142fc3bd4d68a8c25579ebb0a67304", size = 23045, upload-time = "2025-07-21T09:56:46.848Z" }, +] + [[package]] name = "pyarrow" version = "19.0.1" @@ -1982,6 +2445,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c3/c0/c33c8792c3e50193ef55adb95c1c3c2786fe281123291c2dbf0eaab95a6f/pyotp-2.9.0-py3-none-any.whl", hash = "sha256:81c2e5865b8ac55e825b0358e496e1d9387c811e85bb40e71a3b29b288963612", size = 13376, upload-time = "2023-07-27T23:41:01.685Z" }, ] +[[package]] +name = "pyparsing" +version = "3.3.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f3/91/9c6ee907786a473bf81c5f53cf703ba0957b23ab84c264080fb5a450416f/pyparsing-3.3.2.tar.gz", hash = "sha256:c777f4d763f140633dcb6d8a3eda953bf7a214dc4eff598413c070bcdc117cbc", size = 6851574, upload-time = "2026-01-21T03:57:59.36Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/bd/c038d7cc38edc1aa5bf91ab8068b63d4308c66c4c8bb3cbba7dfbc049f9c/pyparsing-3.3.2-py3-none-any.whl", hash = "sha256:850ba148bd908d7e2411587e247a1e4f0327839c40e2e5e6d05a007ecc69911d", size = 122781, upload-time = "2026-01-21T03:57:55.912Z" }, +] + [[package]] name = "pypdf" version = "6.13.0" @@ -2211,6 +2683,31 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/68/15/6d22d07e063ce5e9bfbd96db9ec2fbb4693591b4503e3a76996639474d02/rpds_py-0.23.1-cp313-cp313t-win_amd64.whl", hash = "sha256:d6f6512a90bd5cd9030a6237f5346f046c6f0e40af98657568fa45695d4de59d", size = 235415, upload-time = "2025-02-21T15:03:12.664Z" }, ] +[[package]] +name = "ruff" +version = "0.15.16" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a6/bd/5f7ec371001337d8fa61701c186ff8b613ecac1651848c5950f4c4d5f2e9/ruff-0.15.16.tar.gz", hash = "sha256:d05e78d38c78caf020b03789e25106c93017db5a0cb6e2819885018c61343b78", size = 4714267, upload-time = "2026-06-04T16:33:09.974Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/42/53ef1c3953f157956db9bf7861e3bc50b9b887ce93300aa48cdba8336fe6/ruff-0.15.16-py3-none-linux_armv6l.whl", hash = "sha256:6ac3c0b3969cc6cf6b158c4e2f8f682acb58e7d700d8a44b65ecdc72d66ab0b2", size = 10709025, upload-time = "2026-06-04T16:32:51.935Z" }, + { url = "https://files.pythonhosted.org/packages/93/9a/a79159346f19134a956607754e57d8d128f7a4c00f4ad2f7514d224c172c/ruff-0.15.16-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:197c207ed75ffba54a0dec23db4aa939a27a3053073e085e0042433cbdc58e4a", size = 11063550, upload-time = "2026-06-04T16:32:42.24Z" }, + { url = "https://files.pythonhosted.org/packages/bc/72/3ce2ac000a5299ec238e01f51397b3b653c93b077d9b1bfe8715bb895f20/ruff-0.15.16-py3-none-macosx_11_0_arm64.whl", hash = "sha256:3a39fec45ab316cc23e7558f23fea4a70403ddb5648ea9a4a3854a16973d0071", size = 10421345, upload-time = "2026-06-04T16:32:37.251Z" }, + { url = "https://files.pythonhosted.org/packages/b0/c2/cc7fad3ec9169373f5b6a18f1917b91080feec40c3f9658334a1d28e2f03/ruff-0.15.16-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ba93191d79003116b95128c9d306e045200fdbd0bccb782b110f3cd1d4abc5cf", size = 10757217, upload-time = "2026-06-04T16:32:54.722Z" }, + { url = "https://files.pythonhosted.org/packages/69/d2/3474009eaa0a65b31fa7152a2fad5e2f050c640ceb1e6b02ee6922e94c82/ruff-0.15.16-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c6ee4b90520630120ef032aa5cc10db483852dff950e78b1d717e2993a61ac8d", size = 10507035, upload-time = "2026-06-04T16:33:05.343Z" }, + { url = "https://files.pythonhosted.org/packages/ca/81/b7ae6ccbd11f0c8dc3d5d67fc4be9b57ff57ca86ba56152021378e1277f2/ruff-0.15.16-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:4e4215bc938bc3c8215c1472c1aa437e310fee20cd427335fec9d7e609563628", size = 11255291, upload-time = "2026-06-04T16:32:49.49Z" }, + { url = "https://files.pythonhosted.org/packages/d9/e1/46e526f1a7cc90857ce6ddf25fbb77eb6568651ac38d71b033af07076dd5/ruff-0.15.16-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7c8d26be963b090f10e29abc8b3e74a2a321f6fa34e02424e30b5af89350ecbb", size = 12124922, upload-time = "2026-06-04T16:33:07.821Z" }, + { url = "https://files.pythonhosted.org/packages/1a/da/5c791b088b596b24d0deb967fa28ae02ad751a140c0b9ea81c5ab915d6c0/ruff-0.15.16-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f198cf4123602a2280ed46c307bcbafe41758d6fee5b456b6b6058ca1514b3b4", size = 11332186, upload-time = "2026-06-04T16:33:02.971Z" }, + { url = "https://files.pythonhosted.org/packages/72/11/5da87abe20047c8962361473923ebb2f62b595250126aadfad8c20649c1e/ruff-0.15.16-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bb27515fa6240fb586ae82b901a59e67d24acff86f2190b433dc542fe0435aeb", size = 11373541, upload-time = "2026-06-04T16:32:47.007Z" }, + { url = "https://files.pythonhosted.org/packages/fe/2a/8554754c23a854ae3fd6b507e36ad61ddb121e298c6d5d617dec94ed0f14/ruff-0.15.16-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:a267c46ba1593fc26b8eecbea050b39d40c0b6bb7781ee11c90a02cd10032951", size = 11353014, upload-time = "2026-06-04T16:32:34.795Z" }, + { url = "https://files.pythonhosted.org/packages/62/25/62ea41529ec89f742ea3fed9cb1059c72877ec7cf9b9e99ac9cf3294d1d9/ruff-0.15.16-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:528c68f39a91498a8d50e91ff5985df3d105782bab49cc378e73ac26bff083e8", size = 10737467, upload-time = "2026-06-04T16:32:26.348Z" }, + { url = "https://files.pythonhosted.org/packages/90/17/334d3ad9de4d40f9dd58fdd09e35ce64553bb501e2f19a839e2fb6be14fc/ruff-0.15.16-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:7ed55c58950df60589a9a7a5d2f8fa5f54ebd287163be805adfe6ee95a9de123", size = 10521910, upload-time = "2026-06-04T16:32:32.54Z" }, + { url = "https://files.pythonhosted.org/packages/4d/bd/3ac7c6ae77a885c1004b3dda2446ea401768d24f851c14b4ad4b24f6639c/ruff-0.15.16-py3-none-musllinux_1_2_i686.whl", hash = "sha256:d482feaf51512b50f9790ceb417a56a61dd1e9d9bf967662b9ed27c01b34f53a", size = 10979190, upload-time = "2026-06-04T16:32:57.492Z" }, + { url = "https://files.pythonhosted.org/packages/33/d7/609546e6a413c3f216fbf2a50c928f97c80939154f6a0503114094a86191/ruff-0.15.16-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:1e15bc8c94513dae2a40cc9ef07c94fdd4ecc9e29dabebeebe170f952322c9e3", size = 11477014, upload-time = "2026-06-04T16:32:44.687Z" }, + { url = "https://files.pythonhosted.org/packages/74/0d/f2cd247ad32633a5c36e97141a2c21b11c6279f7957bc2ff360b1e08fddd/ruff-0.15.16-py3-none-win32.whl", hash = "sha256:580378f7bd4aa25f72e74aa54948a9622f142b1e509521dd10902e886681cc1e", size = 10735541, upload-time = "2026-06-04T16:32:30.145Z" }, + { url = "https://files.pythonhosted.org/packages/8b/9e/02e845ef151b1dee585e55c4739f8e1734ae1d9f1221dff65761c162208b/ruff-0.15.16-py3-none-win_amd64.whl", hash = "sha256:408256017284eddf98fff77b29aa4fb30f586042d535b2d9befc6512f400aaec", size = 11843403, upload-time = "2026-06-04T16:32:39.76Z" }, + { url = "https://files.pythonhosted.org/packages/15/19/016553f86f207450aebebc2b2b5088d086b901cc8186c02ac4284db3bd88/ruff-0.15.16-py3-none-win_arm64.whl", hash = "sha256:8cd61783afb39638a7133ef0d2dfb1e91277593962f81b5a8423eb0b888a6121", size = 11134555, upload-time = "2026-06-04T16:33:00.136Z" }, +] + [[package]] name = "six" version = "1.17.0" @@ -2238,6 +2735,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e9/44/75a9c9421471a6c4805dbf2356f7c181a29c1879239abab1ea2cc8f38b40/sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", size = 10235, upload-time = "2024-02-25T23:20:01.196Z" }, ] +[[package]] +name = "sortedcontainers" +version = "2.4.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e8/c4/ba2f8066cceb6f23394729afe52f3bf7adec04bf9ed2c820b39e19299111/sortedcontainers-2.4.0.tar.gz", hash = "sha256:25caa5a06cc30b6b83d11423433f65d1f9d76c4c6a0c90e3379eaa43b9bfdb88", size = 30594, upload-time = "2021-05-16T22:03:42.897Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/46/9cb0e58b2deb7f82b84065f37f3bffeb12413f947f9388e4cac22c4621ce/sortedcontainers-2.4.0-py2.py3-none-any.whl", hash = "sha256:a163dcaede0f1c021485e957a39245190e74249897e2ae4b2aa38595db237ee0", size = 29575, upload-time = "2021-05-16T22:03:41.177Z" }, +] + [[package]] name = "soupsieve" version = "2.6" @@ -2297,6 +2803,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/1c/54/196d0c1db10af76baa4f64894448505d60d3cdf70ef92cbb35f46a4e4c71/starlette-1.2.1-py3-none-any.whl", hash = "sha256:4de0082d08c8f6764a85a54cf1120d6939507a19905c7768acad2a9f875d2b89", size = 73350, upload-time = "2026-05-31T01:07:50.09Z" }, ] +[[package]] +name = "stevedore" +version = "5.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e9/88/35e4d27d9177d7df76d060e0a18f69c6c5794c96960c94042e20a12c8ba2/stevedore-5.8.0.tar.gz", hash = "sha256:b49867b32ca3016e94100e68dbf26e72aa7b8708d0a3f73c08aeb220370ac715", size = 514710, upload-time = "2026-05-18T09:15:27.731Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f5/ac/19f9941c74add59d17694930ec8105d5eddeee4ce56dd8632b765ca16d6c/stevedore-5.8.0-py3-none-any.whl", hash = "sha256:88eede9e66ca80e34085b9174e2327da2c61ac91f24f70e41c3ad76e4bb4872b", size = 54553, upload-time = "2026-05-18T09:15:25.82Z" }, +] + [[package]] name = "streamlit" version = "1.42.2" @@ -2346,6 +2861,69 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/44/6f/7120676b6d73228c96e17f1f794d8ab046fc910d781c8d151120c3f1569e/toml-0.10.2-py2.py3-none-any.whl", hash = "sha256:806143ae5bfb6a3c6e736a764057db0e6a0e05e338b5630894a5f779cabb4f9b", size = 16588, upload-time = "2020-11-01T01:40:20.672Z" }, ] +[[package]] +name = "tomli" +version = "2.4.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/22/de/48c59722572767841493b26183a0d1cc411d54fd759c5607c4590b6563a6/tomli-2.4.1.tar.gz", hash = "sha256:7c7e1a961a0b2f2472c1ac5b69affa0ae1132c39adcb67aba98568702b9cc23f", size = 17543, upload-time = "2026-03-25T20:22:03.828Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f4/11/db3d5885d8528263d8adc260bb2d28ebf1270b96e98f0e0268d32b8d9900/tomli-2.4.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:f8f0fc26ec2cc2b965b7a3b87cd19c5c6b8c5e5f436b984e85f486d652285c30", size = 154704, upload-time = "2026-03-25T20:21:10.473Z" }, + { url = "https://files.pythonhosted.org/packages/6d/f7/675db52c7e46064a9aa928885a9b20f4124ecb9bc2e1ce74c9106648d202/tomli-2.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:4ab97e64ccda8756376892c53a72bd1f964e519c77236368527f758fbc36a53a", size = 149454, upload-time = "2026-03-25T20:21:12.036Z" }, + { url = "https://files.pythonhosted.org/packages/61/71/81c50943cf953efa35bce7646caab3cf457a7d8c030b27cfb40d7235f9ee/tomli-2.4.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96481a5786729fd470164b47cdb3e0e58062a496f455ee41b4403be77cb5a076", size = 237561, upload-time = "2026-03-25T20:21:13.098Z" }, + { url = "https://files.pythonhosted.org/packages/48/c1/f41d9cb618acccca7df82aaf682f9b49013c9397212cb9f53219e3abac37/tomli-2.4.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5a881ab208c0baf688221f8cecc5401bd291d67e38a1ac884d6736cbcd8247e9", size = 243824, upload-time = "2026-03-25T20:21:14.569Z" }, + { url = "https://files.pythonhosted.org/packages/22/e4/5a816ecdd1f8ca51fb756ef684b90f2780afc52fc67f987e3c61d800a46d/tomli-2.4.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:47149d5bd38761ac8be13a84864bf0b7b70bc051806bc3669ab1cbc56216b23c", size = 242227, upload-time = "2026-03-25T20:21:15.712Z" }, + { url = "https://files.pythonhosted.org/packages/6b/49/2b2a0ef529aa6eec245d25f0c703e020a73955ad7edf73e7f54ddc608aa5/tomli-2.4.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ec9bfaf3ad2df51ace80688143a6a4ebc09a248f6ff781a9945e51937008fcbc", size = 247859, upload-time = "2026-03-25T20:21:17.001Z" }, + { url = "https://files.pythonhosted.org/packages/83/bd/6c1a630eaca337e1e78c5903104f831bda934c426f9231429396ce3c3467/tomli-2.4.1-cp311-cp311-win32.whl", hash = "sha256:ff2983983d34813c1aeb0fa89091e76c3a22889ee83ab27c5eeb45100560c049", size = 97204, upload-time = "2026-03-25T20:21:18.079Z" }, + { url = "https://files.pythonhosted.org/packages/42/59/71461df1a885647e10b6bb7802d0b8e66480c61f3f43079e0dcd315b3954/tomli-2.4.1-cp311-cp311-win_amd64.whl", hash = "sha256:5ee18d9ebdb417e384b58fe414e8d6af9f4e7a0ae761519fb50f721de398dd4e", size = 108084, upload-time = "2026-03-25T20:21:18.978Z" }, + { url = "https://files.pythonhosted.org/packages/b8/83/dceca96142499c069475b790e7913b1044c1a4337e700751f48ed723f883/tomli-2.4.1-cp311-cp311-win_arm64.whl", hash = "sha256:c2541745709bad0264b7d4705ad453b76ccd191e64aa6f0fc66b69a293a45ece", size = 95285, upload-time = "2026-03-25T20:21:20.309Z" }, + { url = "https://files.pythonhosted.org/packages/c1/ba/42f134a3fe2b370f555f44b1d72feebb94debcab01676bf918d0cb70e9aa/tomli-2.4.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c742f741d58a28940ce01d58f0ab2ea3ced8b12402f162f4d534dfe18ba1cd6a", size = 155924, upload-time = "2026-03-25T20:21:21.626Z" }, + { url = "https://files.pythonhosted.org/packages/dc/c7/62d7a17c26487ade21c5422b646110f2162f1fcc95980ef7f63e73c68f14/tomli-2.4.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:7f86fd587c4ed9dd76f318225e7d9b29cfc5a9d43de44e5754db8d1128487085", size = 150018, upload-time = "2026-03-25T20:21:23.002Z" }, + { url = "https://files.pythonhosted.org/packages/5c/05/79d13d7c15f13bdef410bdd49a6485b1c37d28968314eabee452c22a7fda/tomli-2.4.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ff18e6a727ee0ab0388507b89d1bc6a22b138d1e2fa56d1ad494586d61d2eae9", size = 244948, upload-time = "2026-03-25T20:21:24.04Z" }, + { url = "https://files.pythonhosted.org/packages/10/90/d62ce007a1c80d0b2c93e02cab211224756240884751b94ca72df8a875ca/tomli-2.4.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:136443dbd7e1dee43c68ac2694fde36b2849865fa258d39bf822c10e8068eac5", size = 253341, upload-time = "2026-03-25T20:21:25.177Z" }, + { url = "https://files.pythonhosted.org/packages/1a/7e/caf6496d60152ad4ed09282c1885cca4eea150bfd007da84aea07bcc0a3e/tomli-2.4.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:5e262d41726bc187e69af7825504c933b6794dc3fbd5945e41a79bb14c31f585", size = 248159, upload-time = "2026-03-25T20:21:26.364Z" }, + { url = "https://files.pythonhosted.org/packages/99/e7/c6f69c3120de34bbd882c6fba7975f3d7a746e9218e56ab46a1bc4b42552/tomli-2.4.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:5cb41aa38891e073ee49d55fbc7839cfdb2bc0e600add13874d048c94aadddd1", size = 253290, upload-time = "2026-03-25T20:21:27.46Z" }, + { url = "https://files.pythonhosted.org/packages/d6/2f/4a3c322f22c5c66c4b836ec58211641a4067364f5dcdd7b974b4c5da300c/tomli-2.4.1-cp312-cp312-win32.whl", hash = "sha256:da25dc3563bff5965356133435b757a795a17b17d01dbc0f42fb32447ddfd917", size = 98141, upload-time = "2026-03-25T20:21:28.492Z" }, + { url = "https://files.pythonhosted.org/packages/24/22/4daacd05391b92c55759d55eaee21e1dfaea86ce5c571f10083360adf534/tomli-2.4.1-cp312-cp312-win_amd64.whl", hash = "sha256:52c8ef851d9a240f11a88c003eacb03c31fc1c9c4ec64a99a0f922b93874fda9", size = 108847, upload-time = "2026-03-25T20:21:29.386Z" }, + { url = "https://files.pythonhosted.org/packages/68/fd/70e768887666ddd9e9f5d85129e84910f2db2796f9096aa02b721a53098d/tomli-2.4.1-cp312-cp312-win_arm64.whl", hash = "sha256:f758f1b9299d059cc3f6546ae2af89670cb1c4d48ea29c3cacc4fe7de3058257", size = 95088, upload-time = "2026-03-25T20:21:30.677Z" }, + { url = "https://files.pythonhosted.org/packages/07/06/b823a7e818c756d9a7123ba2cda7d07bc2dd32835648d1a7b7b7a05d848d/tomli-2.4.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:36d2bd2ad5fb9eaddba5226aa02c8ec3fa4f192631e347b3ed28186d43be6b54", size = 155866, upload-time = "2026-03-25T20:21:31.65Z" }, + { url = "https://files.pythonhosted.org/packages/14/6f/12645cf7f08e1a20c7eb8c297c6f11d31c1b50f316a7e7e1e1de6e2e7b7e/tomli-2.4.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:eb0dc4e38e6a1fd579e5d50369aa2e10acfc9cace504579b2faabb478e76941a", size = 149887, upload-time = "2026-03-25T20:21:33.028Z" }, + { url = "https://files.pythonhosted.org/packages/5c/e0/90637574e5e7212c09099c67ad349b04ec4d6020324539297b634a0192b0/tomli-2.4.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c7f2c7f2b9ca6bdeef8f0fa897f8e05085923eb091721675170254cbc5b02897", size = 243704, upload-time = "2026-03-25T20:21:34.51Z" }, + { url = "https://files.pythonhosted.org/packages/10/8f/d3ddb16c5a4befdf31a23307f72828686ab2096f068eaf56631e136c1fdd/tomli-2.4.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f3c6818a1a86dd6dca7ddcaaf76947d5ba31aecc28cb1b67009a5877c9a64f3f", size = 251628, upload-time = "2026-03-25T20:21:36.012Z" }, + { url = "https://files.pythonhosted.org/packages/e3/f1/dbeeb9116715abee2485bf0a12d07a8f31af94d71608c171c45f64c0469d/tomli-2.4.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d312ef37c91508b0ab2cee7da26ec0b3ed2f03ce12bd87a588d771ae15dcf82d", size = 247180, upload-time = "2026-03-25T20:21:37.136Z" }, + { url = "https://files.pythonhosted.org/packages/d3/74/16336ffd19ed4da28a70959f92f506233bd7cfc2332b20bdb01591e8b1d1/tomli-2.4.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:51529d40e3ca50046d7606fa99ce3956a617f9b36380da3b7f0dd3dd28e68cb5", size = 251674, upload-time = "2026-03-25T20:21:38.298Z" }, + { url = "https://files.pythonhosted.org/packages/16/f9/229fa3434c590ddf6c0aa9af64d3af4b752540686cace29e6281e3458469/tomli-2.4.1-cp313-cp313-win32.whl", hash = "sha256:2190f2e9dd7508d2a90ded5ed369255980a1bcdd58e52f7fe24b8162bf9fedbd", size = 97976, upload-time = "2026-03-25T20:21:39.316Z" }, + { url = "https://files.pythonhosted.org/packages/6a/1e/71dfd96bcc1c775420cb8befe7a9d35f2e5b1309798f009dca17b7708c1e/tomli-2.4.1-cp313-cp313-win_amd64.whl", hash = "sha256:8d65a2fbf9d2f8352685bc1364177ee3923d6baf5e7f43ea4959d7d8bc326a36", size = 108755, upload-time = "2026-03-25T20:21:40.248Z" }, + { url = "https://files.pythonhosted.org/packages/83/7a/d34f422a021d62420b78f5c538e5b102f62bea616d1d75a13f0a88acb04a/tomli-2.4.1-cp313-cp313-win_arm64.whl", hash = "sha256:4b605484e43cdc43f0954ddae319fb75f04cc10dd80d830540060ee7cd0243cd", size = 95265, upload-time = "2026-03-25T20:21:41.219Z" }, + { url = "https://files.pythonhosted.org/packages/3c/fb/9a5c8d27dbab540869f7c1f8eb0abb3244189ce780ba9cd73f3770662072/tomli-2.4.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:fd0409a3653af6c147209d267a0e4243f0ae46b011aa978b1080359fddc9b6cf", size = 155726, upload-time = "2026-03-25T20:21:42.23Z" }, + { url = "https://files.pythonhosted.org/packages/62/05/d2f816630cc771ad836af54f5001f47a6f611d2d39535364f148b6a92d6b/tomli-2.4.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:a120733b01c45e9a0c34aeef92bf0cf1d56cfe81ed9d47d562f9ed591a9828ac", size = 149859, upload-time = "2026-03-25T20:21:43.386Z" }, + { url = "https://files.pythonhosted.org/packages/ce/48/66341bdb858ad9bd0ceab5a86f90eddab127cf8b046418009f2125630ecb/tomli-2.4.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:559db847dc486944896521f68d8190be1c9e719fced785720d2216fe7022b662", size = 244713, upload-time = "2026-03-25T20:21:44.474Z" }, + { url = "https://files.pythonhosted.org/packages/df/6d/c5fad00d82b3c7a3ab6189bd4b10e60466f22cfe8a08a9394185c8a8111c/tomli-2.4.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:01f520d4f53ef97964a240a035ec2a869fe1a37dde002b57ebc4417a27ccd853", size = 252084, upload-time = "2026-03-25T20:21:45.62Z" }, + { url = "https://files.pythonhosted.org/packages/00/71/3a69e86f3eafe8c7a59d008d245888051005bd657760e96d5fbfb0b740c2/tomli-2.4.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7f94b27a62cfad8496c8d2513e1a222dd446f095fca8987fceef261225538a15", size = 247973, upload-time = "2026-03-25T20:21:46.937Z" }, + { url = "https://files.pythonhosted.org/packages/67/50/361e986652847fec4bd5e4a0208752fbe64689c603c7ae5ea7cb16b1c0ca/tomli-2.4.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:ede3e6487c5ef5d28634ba3f31f989030ad6af71edfb0055cbbd14189ff240ba", size = 256223, upload-time = "2026-03-25T20:21:48.467Z" }, + { url = "https://files.pythonhosted.org/packages/8c/9a/b4173689a9203472e5467217e0154b00e260621caa227b6fa01feab16998/tomli-2.4.1-cp314-cp314-win32.whl", hash = "sha256:3d48a93ee1c9b79c04bb38772ee1b64dcf18ff43085896ea460ca8dec96f35f6", size = 98973, upload-time = "2026-03-25T20:21:49.526Z" }, + { url = "https://files.pythonhosted.org/packages/14/58/640ac93bf230cd27d002462c9af0d837779f8773bc03dee06b5835208214/tomli-2.4.1-cp314-cp314-win_amd64.whl", hash = "sha256:88dceee75c2c63af144e456745e10101eb67361050196b0b6af5d717254dddf7", size = 109082, upload-time = "2026-03-25T20:21:50.506Z" }, + { url = "https://files.pythonhosted.org/packages/d5/2f/702d5e05b227401c1068f0d386d79a589bb12bf64c3d2c72ce0631e3bc49/tomli-2.4.1-cp314-cp314-win_arm64.whl", hash = "sha256:b8c198f8c1805dc42708689ed6864951fd2494f924149d3e4bce7710f8eb5232", size = 96490, upload-time = "2026-03-25T20:21:51.474Z" }, + { url = "https://files.pythonhosted.org/packages/45/4b/b877b05c8ba62927d9865dd980e34a755de541eb65fffba52b4cc495d4d2/tomli-2.4.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:d4d8fe59808a54658fcc0160ecfb1b30f9089906c50b23bcb4c69eddc19ec2b4", size = 164263, upload-time = "2026-03-25T20:21:52.543Z" }, + { url = "https://files.pythonhosted.org/packages/24/79/6ab420d37a270b89f7195dec5448f79400d9e9c1826df982f3f8e97b24fd/tomli-2.4.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7008df2e7655c495dd12d2a4ad038ff878d4ca4b81fccaf82b714e07eae4402c", size = 160736, upload-time = "2026-03-25T20:21:53.674Z" }, + { url = "https://files.pythonhosted.org/packages/02/e0/3630057d8eb170310785723ed5adcdfb7d50cb7e6455f85ba8a3deed642b/tomli-2.4.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1d8591993e228b0c930c4bb0db464bdad97b3289fb981255d6c9a41aedc84b2d", size = 270717, upload-time = "2026-03-25T20:21:55.129Z" }, + { url = "https://files.pythonhosted.org/packages/7a/b4/1613716072e544d1a7891f548d8f9ec6ce2faf42ca65acae01d76ea06bb0/tomli-2.4.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:734e20b57ba95624ecf1841e72b53f6e186355e216e5412de414e3c51e5e3c41", size = 278461, upload-time = "2026-03-25T20:21:56.228Z" }, + { url = "https://files.pythonhosted.org/packages/05/38/30f541baf6a3f6df77b3df16b01ba319221389e2da59427e221ef417ac0c/tomli-2.4.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:8a650c2dbafa08d42e51ba0b62740dae4ecb9338eefa093aa5c78ceb546fcd5c", size = 274855, upload-time = "2026-03-25T20:21:57.653Z" }, + { url = "https://files.pythonhosted.org/packages/77/a3/ec9dd4fd2c38e98de34223b995a3b34813e6bdadf86c75314c928350ed14/tomli-2.4.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:504aa796fe0569bb43171066009ead363de03675276d2d121ac1a4572397870f", size = 283144, upload-time = "2026-03-25T20:21:59.089Z" }, + { url = "https://files.pythonhosted.org/packages/ef/be/605a6261cac79fba2ec0c9827e986e00323a1945700969b8ee0b30d85453/tomli-2.4.1-cp314-cp314t-win32.whl", hash = "sha256:b1d22e6e9387bf4739fbe23bfa80e93f6b0373a7f1b96c6227c32bef95a4d7a8", size = 108683, upload-time = "2026-03-25T20:22:00.214Z" }, + { url = "https://files.pythonhosted.org/packages/12/64/da524626d3b9cc40c168a13da8335fe1c51be12c0a63685cc6db7308daae/tomli-2.4.1-cp314-cp314t-win_amd64.whl", hash = "sha256:2c1c351919aca02858f740c6d33adea0c5deea37f9ecca1cc1ef9e884a619d26", size = 121196, upload-time = "2026-03-25T20:22:01.169Z" }, + { url = "https://files.pythonhosted.org/packages/5a/cd/e80b62269fc78fc36c9af5a6b89c835baa8af28ff5ad28c7028d60860320/tomli-2.4.1-cp314-cp314t-win_arm64.whl", hash = "sha256:eab21f45c7f66c13f2a9e0e1535309cee140182a9cdae1e041d02e47291e8396", size = 100393, upload-time = "2026-03-25T20:22:02.137Z" }, + { url = "https://files.pythonhosted.org/packages/7b/61/cceae43728b7de99d9b847560c262873a1f6c98202171fd5ed62640b494b/tomli-2.4.1-py3-none-any.whl", hash = "sha256:0d85819802132122da43cb86656f8d1f8c6587d54ae7dcaf30e90533028b49fe", size = 14583, upload-time = "2026-03-25T20:22:03.012Z" }, +] + +[[package]] +name = "tomli-w" +version = "1.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/19/75/241269d1da26b624c0d5e110e8149093c759b7a286138f4efd61a60e75fe/tomli_w-1.2.0.tar.gz", hash = "sha256:2dd14fac5a47c27be9cd4c976af5a12d87fb1f0b4512f81d69cce3b35ae25021", size = 7184, upload-time = "2025-01-15T12:07:24.262Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c7/18/c86eb8e0202e32dd3df50d43d7ff9854f8e0603945ff398974c1d91ac1ef/tomli_w-1.2.0-py3-none-any.whl", hash = "sha256:188306098d013b691fcadc011abd66727d3c414c571bb01b1a174ba8c983cf90", size = 6675, upload-time = "2025-01-15T12:07:22.074Z" }, +] + [[package]] name = "tornado" version = "6.4.2" @@ -2376,6 +2954,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d0/30/dc54f88dd4a2b5dc8a0279bdd7270e735851848b762aeb1c1184ed1f6b14/tqdm-4.67.1-py3-none-any.whl", hash = "sha256:26445eca388f82e72884e0d580d5464cd801a3ea01e63e5601bdff9ba6a48de2", size = 78540, upload-time = "2024-11-24T20:12:19.698Z" }, ] +[[package]] +name = "types-requests" +version = "2.33.0.20260518" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e0/01/c5a19253fe1ac159159ddf9a3a07cec8bb5e486ec4d9002ad2821da0e5d2/types_requests-2.33.0.20260518.tar.gz", hash = "sha256:df7bd3bfe0ca8402dfb841e7d9be714bb5578203283d66d7dc4ef69343449a5e", size = 24752, upload-time = "2026-05-18T06:07:37.966Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1c/bc/b139710a3b6018f7fb2b9508b35c8af564e61bf2bf4fa619d088f3e16f85/types_requests-2.33.0.20260518-py3-none-any.whl", hash = "sha256:626d697d1adaaff76e2044dc8c5c051d8f21abc157bdfe204a75558076fe0bf0", size = 21391, upload-time = "2026-05-18T06:07:37.044Z" }, +] + [[package]] name = "typing-extensions" version = "4.15.0" From ca3495d5dd4d3a4d5c3555730bedd5508da0d71a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 7 Jun 2026 19:07:26 +0000 Subject: [PATCH 11/24] P1: agentic web-search fallback + live e2e harness MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fallback so we get REAL company data even with no paid keys. When NEWS_API_KEY is absent but an LLM provider key is set, company-news fetch falls through to a keyless agentic web search instead of an empty sentinel. tools/company_research.py: - ddg_search(query): keyless DuckDuckGo — ddgs/duckduckgo_search library if installed, else the HTML endpoint parsed with BeautifulSoup. [] on any failure. ([research] extra adds ddgs.) - agentic_company_research(company): LLM proposes 3 targeted queries -> DuckDuckGo -> dedup results -> optional deep-fetch of the top URL via a headless agentic browser -> LLM synthesises a briefing under the SAME no-fabrication rule (only use snippet content; label inferences; wrap_untrusted on all fetched text). Returns None in demo mode / when no results, so the caller keeps its sentinel. - deep_fetch(url): Browserbase hosted headless browser (BROWSERBASE_API_KEY + PROJECT_ID, connects Playwright over CDP) -> local Playwright scraper (BROWSER_SCRAPER_ENABLED) -> None. All graceful. - Everything best-effort: a research hiccup never breaks the pipeline. tools/data_sources.fetch_company_news: now tier-1 NewsAPI -> tier-2 agentic fallback (also on NewsAPI failure) -> None. tests/test_e2e_live.py (gated on RUN_E2E=1; 7 tests, skipped by default since CI/sandbox are egress-restricted): real round-trip per configured provider; real keyless DuckDuckGo search; the agentic fallback with news/COL keys removed (the "no keys -> web search for real data" scenario) asserting a real briefing; real URL ingest; optional Browserbase deep-fetch; and a full run_analysis on a real posting asserting a verdict + report. tests/test_phase33_company_research.py (22, always-run, mocked): DDG HTML parsing + limit; library-preferred / HTML-fallback / failure-empty search; query building (LLM JSON, code-fence strip, static fallback); agentic orchestration (demo-disabled, env-disabled, no-results-None, synthesis uses snippets + no-fabrication + untrusted-wrap, URL dedup); deep_fetch backend selection; and the fetch_company_news fallback chain (agentic on missing key, None when both unavailable, NewsAPI-preferred, NewsAPI-failure-falls-through). .env.example documents COMPANY_RESEARCH_FALLBACK / DDG_MAX_RESULTS / BROWSERBASE_*. mypy/ruff clean; full suite 535 (7 e2e skipped) green. --- .env.example | 10 + CLAUDE.md | 29 ++- pyproject.toml | 1 + tests/test_e2e_live.py | 172 ++++++++++++++ tests/test_phase33_company_research.py | 271 +++++++++++++++++++++ tools/company_research.py | 315 +++++++++++++++++++++++++ tools/data_sources.py | 62 +++-- uv.lock | 206 +++++++++++++++- 8 files changed, 1030 insertions(+), 36 deletions(-) create mode 100644 tests/test_e2e_live.py create mode 100644 tests/test_phase33_company_research.py create mode 100644 tools/company_research.py diff --git a/.env.example b/.env.example index e34f48a..33ecc50 100644 --- a/.env.example +++ b/.env.example @@ -26,6 +26,16 @@ # NEWS_API_KEY=... # newsapi.org for real company news # LAYOFFS_DATASET_URL=... # JSON dataset URL with layoff records +# Agentic web-search fallback (keyless): when NEWS_API_KEY is absent but an +# LLM provider key IS set, the company-news fetch falls back to an LLM-directed +# DuckDuckGo search ([research] extra: ddgs) + synthesis. Disable with: +# COMPANY_RESEARCH_FALLBACK=0 +# DDG_MAX_RESULTS=5 +# Optional hosted headless agentic browser for deep-fetching a top result: +# BROWSERBASE_API_KEY=... +# BROWSERBASE_PROJECT_ID=... # both required; falls back to local +# # Playwright when BROWSER_SCRAPER_ENABLED=1 + # Phase 4 — real salary benchmarks via Adzuna (free tier, ~1000 calls/month) # Sign up at https://developer.adzuna.com/ # ADZUNA_APP_ID=... diff --git a/CLAUDE.md b/CLAUDE.md index fe52abb..a890ced 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -27,7 +27,8 @@ agents/ LangGraph pipeline: orchestrator + per-stage agents job_/company_/salary_/resume_analyzer.py, report_generator.py tools/ LLM-facing tools + ingestion job_tools, company_tools, salary_tools, resume_tools, data_sources, - url_ingest, browser_scraper (Playwright, optional) + url_ingest, browser_scraper (Playwright, optional), + company_research (agentic keyless DuckDuckGo + Browserbase fallback) services/ Business logic (29 modules) — the bulk of the app auth, totp, oauth, api_tokens, rate_limit, audit (identity/security) applications, stages, analytics, timeline, background_analysis (tracking) @@ -43,7 +44,8 @@ utils/ llm, config, security, diff, verdict, logging_setup, met migrations/ Alembic (15 revisions, 19 tables) chrome-extension/ MV3 extension calling the REST API (JS, Node-tested) deploy/ Caddyfile + nginx reverse-proxy examples (CSP/HSTS) -tests/ 31 files, 506 Python tests + 9 JS (extract.test.mjs) +tests/ 33 files, 535 Python tests (7 live e2e, skipped + unless RUN_E2E=1) + 9 JS (extract.test.mjs) ``` ## How to run @@ -156,10 +158,10 @@ and "production-grade for real multi-user traffic." Prioritized: all migrations and asserts no add/remove table-or-column drift vs the models. Runs in CI via the unittest job. -### P1 — hardening + confidence (now the top priority) -5. **CI quality gates:** add lint (ruff), type-check (mypy), security scan - (bandit + pip-audit), and a coverage floor. Run the JS tests in CI - (add setup-node). Bump `actions/checkout`/`setup-python` off Node 20. +### P1 — hardening + confidence (in progress) +5. ✅ **CI quality gates:** ruff (lint) + mypy (type) + bandit (hard gate) + + pip-audit (advisory) + coverage floor 80% + JS tests in CI + Node-24 opt-in. + Config in `pyproject.toml`; jobs in `.github/workflows/tests.yml`. 6. **Secrets at rest:** envelope-encrypt the TOTP secret (KMS-derived key); consider the same for OAuth-linked emails. 7. **LLM cost controls:** token accounting + per-user budget (today's quota is @@ -168,10 +170,17 @@ and "production-grade for real multi-user traffic." Prioritized: 8. **Observability shipping:** logs are structured JSON and metrics exist, but nothing exports them. Wire an OTLP/Prometheus exporter or a log drain; metrics are currently per-process snapshot-only. -9. **Live provider e2e:** every test mocks the LLM. Add a gated, - key-required smoke test (skipped without a key) that does one real - round-trip per provider so model/param regressions (like the GPT-5 - `max_completion_tokens` change) are caught. +9. ✅ **Live provider e2e** (`tests/test_e2e_live.py`, `RUN_E2E=1`): real + round-trip per provider, real DuckDuckGo search, the agentic company + fallback with no news/COL keys, URL ingest, optional Browserbase, and a + full real-posting pipeline run. Skipped by default (egress-restricted CI). + +**Agentic fallback (shipped, P1):** when `NEWS_API_KEY` is absent but an LLM +key is set, `tools/company_research.agentic_company_research` does an +LLM-directed **keyless DuckDuckGo** search ([research] extra: ddgs) and +synthesises a briefing under the no-fabrication rule, optionally deep-fetching +a top result via a **headless agentic browser** (Browserbase hosted, or the +local Playwright scraper). Wired into `fetch_company_news` as tier 2. ### P2 — robustness + reach 10. **JS-board scraping:** `browser_scraper` (Playwright) exists but isn't diff --git a/pyproject.toml b/pyproject.toml index 48b828d..f2020ac 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -35,6 +35,7 @@ telegram = ["python-telegram-bot>=21.0"] worker = ["celery>=5.3.0", "redis>=5.0.0"] browser = ["playwright>=1.44.0"] pdf = ["fpdf2>=2.7.0"] +research = ["ddgs>=6.0"] # keyless DuckDuckGo search for the agentic fallback dev = [ "ruff>=0.6", "mypy>=1.10", diff --git a/tests/test_e2e_live.py b/tests/test_e2e_live.py new file mode 100644 index 0000000..80188c2 --- /dev/null +++ b/tests/test_e2e_live.py @@ -0,0 +1,172 @@ +"""Live end-to-end tests — REAL calls to external systems and providers. + +These are OPT-IN and skipped by default (CI and the dev sandbox are +egress-restricted). Enable with: + + RUN_E2E=1 python -m unittest tests.test_e2e_live + +What they exercise (each test self-skips if its prerequisite is missing): + + * A real round-trip to every configured LLM provider. + * A real keyless DuckDuckGo search (the fallback's data source). + * The agentic company-research FALLBACK with NO news/COL keys but WITH an + LLM key — i.e. "no API keys for news/numbeo ⇒ use a web search to fetch at + least some real data about the company". This is the headline fallback the + product promises. + * A real URL ingest. + * Optionally, a Browserbase hosted-headless-browser deep fetch. + * A full pipeline run (analyze a real posting) end-to-end with a real + provider, verifying a verdict + report come back. + +Costs real tokens/time — that's the point. Set RUN_E2E=1 only when you mean it. +""" + +from __future__ import annotations + +import os +import sys +import unittest + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +_RUN = os.getenv("RUN_E2E") == "1" + + +def _has_llm_key() -> bool: + return any(os.getenv(k) for k in + ("ANTHROPIC_API_KEY", "OPENAI_API_KEY", "FEATHERLESS_API_KEY")) + + +@unittest.skipUnless(_RUN, "live e2e disabled (set RUN_E2E=1 to run)") +class LiveProviderTests(unittest.TestCase): + def test_each_configured_provider_round_trips(self): + from utils.llm import _PROVIDER_KEYS, ping_provider + + configured = [p for p, env in _PROVIDER_KEYS.items() if os.getenv(env)] + if not configured: + self.skipTest("no provider API key configured") + for provider in configured: + ok, msg = ping_provider(provider) + self.assertTrue(ok, msg=f"{provider} ping failed: {msg}") + + +@unittest.skipUnless(_RUN, "live e2e disabled (set RUN_E2E=1 to run)") +class LiveSearchTests(unittest.TestCase): + """DuckDuckGo search is keyless — only needs network + RUN_E2E.""" + + def test_ddg_search_returns_results(self): + from tools.company_research import ddg_search + + results = ddg_search("OpenAI company news", max_results=5) + self.assertTrue(results, "DuckDuckGo returned no results") + first = results[0] + self.assertTrue(first.get("title") or first.get("snippet")) + self.assertTrue(first.get("url", "").startswith("http")) + + +@unittest.skipUnless(_RUN, "live e2e disabled (set RUN_E2E=1 to run)") +class LiveFallbackTests(unittest.TestCase): + """The core fallback: no news/COL keys, but an LLM key ⇒ agentic web + research must still produce a real briefing.""" + + def setUp(self): + if not _has_llm_key(): + self.skipTest("agentic fallback needs an LLM provider key") + # Force the no-structured-source scenario for the duration of the test. + self._saved = {k: os.environ.pop(k, None) for k in + ("NEWS_API_KEY", "COL_DATASET_URL", "LAYOFFS_DATASET_URL")} + + def tearDown(self): + for k, v in getattr(self, "_saved", {}).items(): + if v is not None: + os.environ[k] = v + + def test_agentic_company_research_produces_briefing(self): + from tools.company_research import agentic_company_research + + out = agentic_company_research("Stripe", model="fast") + self.assertIsNotNone(out, "agentic research returned None") + self.assertGreater(len(out), 100) + # It should be grounded as web-sourced, not invented. + self.assertIn("web search", out.lower()) + + def test_fetch_company_news_uses_fallback_without_news_key(self): + """With NEWS_API_KEY unset, fetch_company_news must fall through to the + agentic web fallback and return real data (not the None sentinel).""" + from tools.data_sources import fetch_company_news + + out = fetch_company_news("Stripe") + self.assertIsNotNone(out, "no data from the agentic fallback") + self.assertGreater(len(out), 100) + + +@unittest.skipUnless(_RUN, "live e2e disabled (set RUN_E2E=1 to run)") +class LiveUrlIngestTests(unittest.TestCase): + def test_fetch_static_page(self): + from tools.url_ingest import fetch_job_posting + + # A content-rich, stable, JS-free page so the plain fetch yields text. + text = fetch_job_posting("https://en.wikipedia.org/wiki/Software_engineer") + self.assertGreater(len(text), 500) + self.assertIn("software", text.lower()) + + +@unittest.skipUnless(_RUN, "live e2e disabled (set RUN_E2E=1 to run)") +class LiveBrowserbaseTests(unittest.TestCase): + def setUp(self): + if not (os.getenv("BROWSERBASE_API_KEY") and os.getenv("BROWSERBASE_PROJECT_ID")): + self.skipTest("Browserbase not configured") + + def test_browserbase_deep_fetch(self): + from tools.company_research import _browserbase_fetch + + text = _browserbase_fetch("https://example.com") + # Browserbase should render *something*; tolerate small pages. + self.assertTrue(text is None or isinstance(text, str)) + if text is not None: + self.assertGreater(len(text), 0) + + +@unittest.skipUnless(_RUN, "live e2e disabled (set RUN_E2E=1 to run)") +class LiveFullPipelineTests(unittest.TestCase): + """The user-facing headline: analyze a real posting end-to-end with a real + provider and the agentic fallback, and get a verdict + report.""" + + def setUp(self): + if not _has_llm_key(): + self.skipTest("full pipeline e2e needs an LLM provider key") + from db.session import reset_engine_for_testing + reset_engine_for_testing("sqlite:///:memory:") + + def test_analyze_real_posting(self): + from agents.orchestrator import run_analysis + + posting = ( + "Company: Stripe\n" + "Title: Senior Backend Engineer\n" + "Location: Remote, US\n\n" + "We're hiring a senior backend engineer to build payments " + "infrastructure in Python and Go. 5+ years experience with " + "distributed systems, PostgreSQL, and cloud (AWS) required. " + "You'll design APIs, mentor engineers, and own reliability." + ) + result = run_analysis( + posting, + manual_inputs={"company_name": "Stripe", + "job_title": "Senior Backend Engineer", + "location": "Remote, US"}, + model="fast", + ) + self.assertEqual(result.get("error", ""), "", msg=result.get("error")) + self.assertTrue(result.get("final_report")) + self.assertGreater(len(result["final_report"]), 200) + verdict = result.get("verdict") or {} + self.assertIn( + verdict.get("verdict"), + {"Highly Recommended", "Recommended", "Consider with Caution", + "Not Recommended"}, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_phase33_company_research.py b/tests/test_phase33_company_research.py new file mode 100644 index 0000000..43dae4f --- /dev/null +++ b/tests/test_phase33_company_research.py @@ -0,0 +1,271 @@ +"""P1: agentic web-search company-research fallback (mocked; always runs). + +The live version is in tests/test_e2e_live.py (gated on RUN_E2E). Here we mock +DuckDuckGo + the LLM so the fallback logic, chain selection, and graceful +degradation are tested without network. +""" + +from __future__ import annotations + +import os +import sys +import unittest +from unittest import mock + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + + +# --------------------------------------------------------------------------- +# DuckDuckGo HTML parsing (pure) +# --------------------------------------------------------------------------- + +_DDG_HTML = """ + +
+ Acme raises $60M Series B +
Acme Technologies closed a $60M round led by Foo Ventures.
+
+
+ Acme reviews +
Employees praise async culture; some cite fast pace.
+
+ +""" + + +class DdgParseTests(unittest.TestCase): + def test_parse_ddg_html_extracts_results(self): + from tools.company_research import _parse_ddg_html + + out = _parse_ddg_html(_DDG_HTML, limit=5) + self.assertEqual(len(out), 2) + self.assertEqual(out[0]["title"], "Acme raises $60M Series B") + self.assertIn("60M", out[0]["snippet"]) + self.assertTrue(out[0]["url"].startswith("https://news.example")) + + def test_parse_ddg_html_respects_limit(self): + from tools.company_research import _parse_ddg_html + + self.assertEqual(len(_parse_ddg_html(_DDG_HTML, limit=1)), 1) + + def test_parse_empty_html(self): + from tools.company_research import _parse_ddg_html + + self.assertEqual(_parse_ddg_html("", limit=5), []) + + +class DdgSearchTests(unittest.TestCase): + def test_html_fallback_used_when_library_absent(self): + import tools.company_research as cr + + class _Resp: + text = _DDG_HTML + def raise_for_status(self): # noqa: D401 + pass + + with mock.patch.object(cr, "_ddg_via_library", return_value=[]), \ + mock.patch.object(cr.requests, "post", return_value=_Resp()): + results = cr.ddg_search("Acme news") + self.assertEqual(len(results), 2) + + def test_library_results_preferred(self): + import tools.company_research as cr + + lib = [{"title": "t", "snippet": "s", "url": "u"}] + with mock.patch.object(cr, "_ddg_via_library", return_value=lib), \ + mock.patch.object(cr.requests, "post") as post: + results = cr.ddg_search("Acme") + self.assertEqual(results, lib) + post.assert_not_called() # HTML path skipped when library returns data + + def test_search_failure_returns_empty(self): + import tools.company_research as cr + + with mock.patch.object(cr, "_ddg_via_library", return_value=[]), \ + mock.patch.object(cr.requests, "post", side_effect=cr.requests.ConnectionError("x")): + self.assertEqual(cr.ddg_search("Acme"), []) + + def test_empty_query(self): + from tools.company_research import ddg_search + self.assertEqual(ddg_search(""), []) + + +# --------------------------------------------------------------------------- +# Query building +# --------------------------------------------------------------------------- + +class BuildQueriesTests(unittest.TestCase): + def test_llm_queries_parsed(self): + import tools.company_research as cr + + with mock.patch.object(cr, "get_completion", + return_value='["Acme news 2026", "Acme layoffs", "Acme culture"]'): + qs = cr.build_queries("Acme", "fast") + self.assertEqual(qs, ["Acme news 2026", "Acme layoffs", "Acme culture"]) + + def test_llm_code_fence_stripped(self): + import tools.company_research as cr + + with mock.patch.object(cr, "get_completion", + return_value='```json\n["a","b","c"]\n```'): + self.assertEqual(cr.build_queries("Acme"), ["a", "b", "c"]) + + def test_static_fallback_on_bad_json(self): + import tools.company_research as cr + + with mock.patch.object(cr, "get_completion", return_value="not json"): + qs = cr.build_queries("Acme") + self.assertTrue(all("Acme" in q for q in qs)) + self.assertEqual(len(qs), 3) + + +# --------------------------------------------------------------------------- +# Agentic orchestration +# --------------------------------------------------------------------------- + +class AgenticResearchTests(unittest.TestCase): + def test_disabled_in_demo_mode(self): + import tools.company_research as cr + + # No provider -> demo -> fallback disabled -> None. + with mock.patch.object(cr, "get_active_provider", return_value=None): + self.assertIsNone(cr.agentic_company_research("Acme")) + + def test_force_disabled_via_env(self): + import tools.company_research as cr + + with mock.patch.object(cr, "get_active_provider", return_value="openai"), \ + mock.patch.dict(os.environ, {"COMPANY_RESEARCH_FALLBACK": "0"}): + self.assertIsNone(cr.agentic_company_research("Acme")) + + def test_no_results_returns_none(self): + import tools.company_research as cr + + with mock.patch.object(cr, "get_active_provider", return_value="openai"), \ + mock.patch.object(cr, "build_queries", return_value=["q1"]), \ + mock.patch.object(cr, "ddg_search", return_value=[]): + self.assertIsNone(cr.agentic_company_research("Acme")) + + def test_synthesises_briefing_from_results(self): + import tools.company_research as cr + + results = [ + {"title": "Acme raises $60M", "snippet": "Series B", "url": "https://a"}, + {"title": "Acme culture", "snippet": "async", "url": "https://b"}, + ] + captured = {} + + def fake_completion(prompt, model="fast"): + captured["prompt"] = prompt + return "REAL DATA (web search, DuckDuckGo) for Acme:\n- Raised $60M" + + with mock.patch.object(cr, "get_active_provider", return_value="openai"), \ + mock.patch.object(cr, "build_queries", return_value=["q"]), \ + mock.patch.object(cr, "ddg_search", return_value=results), \ + mock.patch.object(cr, "deep_fetch", return_value=None), \ + mock.patch.object(cr, "get_completion", side_effect=fake_completion): + out = cr.agentic_company_research("Acme") + + self.assertIn("REAL DATA (web search", out) + # Snippets + the no-fabrication framing made it into the synthesis prompt. + self.assertIn("Acme raises $60M", captured["prompt"]) + self.assertIn("Do NOT invent", captured["prompt"]) + self.assertIn("<<>>", captured["prompt"]) + + def test_deduplicates_urls_across_queries(self): + import tools.company_research as cr + + dup = [{"title": "t", "snippet": "s", "url": "https://same"}] + seen_prompts = [] + + with mock.patch.object(cr, "get_active_provider", return_value="openai"), \ + mock.patch.object(cr, "build_queries", return_value=["q1", "q2"]), \ + mock.patch.object(cr, "ddg_search", return_value=dup), \ + mock.patch.object(cr, "deep_fetch", return_value=None), \ + mock.patch.object(cr, "get_completion", + side_effect=lambda p, model="fast": seen_prompts.append(p) or "ok"): + cr.agentic_company_research("Acme") + # The same URL from both queries should appear once in the prompt. + self.assertEqual(seen_prompts[-1].count("https://same"), 1) + + +# --------------------------------------------------------------------------- +# deep_fetch backend selection +# --------------------------------------------------------------------------- + +class DeepFetchTests(unittest.TestCase): + def test_none_when_nothing_configured(self): + import tools.company_research as cr + + for k in ("BROWSERBASE_API_KEY", "BROWSERBASE_PROJECT_ID", "BROWSER_SCRAPER_ENABLED"): + os.environ.pop(k, None) + self.assertIsNone(cr.deep_fetch("https://example.com")) + + def test_empty_url(self): + import tools.company_research as cr + self.assertIsNone(cr.deep_fetch("")) + + def test_browserbase_skipped_without_keys(self): + import tools.company_research as cr + + for k in ("BROWSERBASE_API_KEY", "BROWSERBASE_PROJECT_ID"): + os.environ.pop(k, None) + self.assertIsNone(cr._browserbase_fetch("https://example.com")) + + +# --------------------------------------------------------------------------- +# Fallback wiring in fetch_company_news +# --------------------------------------------------------------------------- + +class NewsFallbackChainTests(unittest.TestCase): + def setUp(self): + os.environ.pop("NEWS_API_KEY", None) + + def test_falls_back_to_agentic_when_no_news_key(self): + import tools.data_sources as ds + + with mock.patch("tools.company_research.agentic_company_research", + return_value="REAL DATA (web search) for Acme: ...") as agentic: + out = ds.fetch_company_news("Acme") + agentic.assert_called_once_with("Acme") + self.assertIn("REAL DATA", out) + + def test_returns_none_when_agentic_also_unavailable(self): + import tools.data_sources as ds + + with mock.patch("tools.company_research.agentic_company_research", return_value=None): + self.assertIsNone(ds.fetch_company_news("Acme")) + + def test_newsapi_used_when_key_present(self): + import tools.data_sources as ds + + class _Resp: + status_code = 200 + def raise_for_status(self): pass + def json(self): + return {"status": "ok", "articles": [ + {"title": "Acme news", "source": {"name": "Wire"}, + "publishedAt": "2026-05-01T00:00:00Z"}]} + + with mock.patch.dict(os.environ, {"NEWS_API_KEY": "k"}), \ + mock.patch.object(ds.requests, "get", return_value=_Resp()), \ + mock.patch("tools.company_research.agentic_company_research") as agentic: + out = ds.fetch_company_news("Acme") + self.assertIn("Acme news", out) + agentic.assert_not_called() # tier-1 succeeded, no fallback + + def test_newsapi_failure_falls_through_to_agentic(self): + import tools.data_sources as ds + + with mock.patch.dict(os.environ, {"NEWS_API_KEY": "k"}), \ + mock.patch.object(ds.requests, "get", + side_effect=ds.requests.ConnectionError("down")), \ + mock.patch("tools.company_research.agentic_company_research", + return_value="web fallback") as agentic: + out = ds.fetch_company_news("Acme") + agentic.assert_called_once() + self.assertEqual(out, "web fallback") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/company_research.py b/tools/company_research.py new file mode 100644 index 0000000..4570e93 --- /dev/null +++ b/tools/company_research.py @@ -0,0 +1,315 @@ +"""Agentic web-search fallback for company data. + +When the paid/structured sources aren't configured (no ``NEWS_API_KEY`` for +news, no ``COL_DATASET_URL`` for cost-of-living), we still want *some* real, +current signal about the company rather than an empty sentinel. This module +provides a keyless, agentic fallback: + + 1. The LLM proposes a few targeted search queries for the company. + 2. We run them against **DuckDuckGo** (no API key) — via the ``ddgs`` library + if installed, else DuckDuckGo's HTML endpoint parsed with BeautifulSoup. + 3. Optionally a top result is deep-fetched with a **headless agentic + browser** — Browserbase (hosted, ``BROWSERBASE_API_KEY``) or the local + Playwright scraper (``BROWSER_SCRAPER_ENABLED``) — for JS-heavy pages. + 4. The LLM synthesises the snippets into a briefing, under the same + no-fabrication rule as the rest of the app (use only what the snippets + say; label inferences). + +Everything degrades gracefully: no LLM key (demo mode) ⇒ skip entirely; no +search results ⇒ return ``None`` so the caller falls back to its sentinel. +Network/parse failures are swallowed and logged, never raised — a research +hiccup must never break the analysis pipeline. + +Tunables (env): + COMPANY_RESEARCH_FALLBACK "0" to disable the whole fallback (default on) + DDG_MAX_RESULTS results per query (default 5) + BROWSERBASE_API_KEY enable hosted agentic-browser deep fetch + BROWSERBASE_PROJECT_ID required with the key +""" + +from __future__ import annotations + +import json +import logging +import os +import re +from typing import List, Optional + +import requests + +from utils.llm import get_active_provider, get_completion +from utils.security import wrap_untrusted + +logger = logging.getLogger(__name__) + +_DDG_HTML = "https://html.duckduckgo.com/html/" +_HTTP_TIMEOUT = float(os.getenv("RESEARCH_HTTP_TIMEOUT", "10")) +_USER_AGENT = ( + "Mozilla/5.0 (compatible; JobOfferScannerBot/0.2; +https://example.invalid/bot)" +) + + +def fallback_enabled() -> bool: + """The agentic fallback needs an LLM (for queries + synthesis); it's off in + demo mode and can be force-disabled.""" + if os.getenv("COMPANY_RESEARCH_FALLBACK", "1") != "1": + return False + return get_active_provider() is not None + + +# --------------------------------------------------------------------------- +# DuckDuckGo search (keyless) +# --------------------------------------------------------------------------- + +def ddg_search(query: str, max_results: Optional[int] = None) -> List[dict]: + """Return ``[{title, snippet, url}, …]`` for a query. Best-effort: [] on any + failure. Prefers the ``ddgs``/``duckduckgo_search`` library, falls back to + the HTML endpoint.""" + if not query: + return [] + limit = max_results or int(os.getenv("DDG_MAX_RESULTS", "5")) + + lib_results = _ddg_via_library(query, limit) + if lib_results: + return lib_results + return _ddg_via_html(query, limit) + + +def _load_ddgs(): + """Return the DDGS class from whichever package is installed, or None.""" + try: + from ddgs import DDGS # newer package name + return DDGS + except ImportError: + pass + try: + from duckduckgo_search import DDGS # older name + return DDGS + except ImportError: + return None + + +def _ddg_via_library(query: str, limit: int) -> List[dict]: + ddgs_cls = _load_ddgs() + if ddgs_cls is None: + return [] + try: + out: List[dict] = [] + with ddgs_cls() as ddgs: + for r in ddgs.text(query, max_results=limit): + out.append({ + "title": r.get("title", ""), + "snippet": r.get("body", "") or r.get("snippet", ""), + "url": r.get("href", "") or r.get("url", ""), + }) + return out + except Exception as exc: # noqa: BLE001 - degrade to HTML / empty + logger.warning("ddgs library search failed: %s", exc) + return [] + + +def _ddg_via_html(query: str, limit: int) -> List[dict]: + try: + resp = requests.post( + _DDG_HTML, + data={"q": query}, + headers={"User-Agent": _USER_AGENT}, + timeout=_HTTP_TIMEOUT, + ) + resp.raise_for_status() + return _parse_ddg_html(resp.text, limit) + except Exception as exc: # noqa: BLE001 + logger.warning("DuckDuckGo HTML search failed for %r: %s", query, exc) + return [] + + +def _parse_ddg_html(html: str, limit: int) -> List[dict]: + """Parse DuckDuckGo's HTML results page (pure).""" + from bs4 import BeautifulSoup + + soup = BeautifulSoup(html, "html.parser") + out: List[dict] = [] + for result in soup.select(".result")[: limit * 2]: + a = result.select_one(".result__a") + if a is None: + continue + snippet_el = result.select_one(".result__snippet") + out.append({ + "title": a.get_text(strip=True), + "snippet": snippet_el.get_text(strip=True) if snippet_el else "", + "url": a.get("href", ""), + }) + if len(out) >= limit: + break + return out + + +# --------------------------------------------------------------------------- +# Headless agentic browser deep-fetch (optional) +# --------------------------------------------------------------------------- + +def deep_fetch(url: str) -> Optional[str]: + """Fetch a URL's text via the best available browser backend, or None. + + Order: Browserbase (hosted, no local chromium) → local Playwright scraper + → plain requests is intentionally NOT used here (the caller already has the + DDG snippet; deep-fetch is only worth a real browser). + """ + if not url: + return None + bb = _browserbase_fetch(url) + if bb: + return bb + return _playwright_fetch(url) + + +def _browserbase_fetch(url: str) -> Optional[str]: + """Render ``url`` via Browserbase's hosted headless browser (agentic-capable). + + Connects Playwright to a Browserbase session over CDP. Requires + BROWSERBASE_API_KEY + BROWSERBASE_PROJECT_ID and the playwright package. + Returns cleaned text or None. + """ + api_key = os.getenv("BROWSERBASE_API_KEY") + project_id = os.getenv("BROWSERBASE_PROJECT_ID") + if not api_key or not project_id: + return None + try: + from playwright.sync_api import sync_playwright + except ImportError: + logger.info("Browserbase configured but playwright not installed.") + return None + try: + # Create a session, then connect Playwright to its CDP endpoint. + sess = requests.post( + "https://api.browserbase.com/v1/sessions", + headers={"X-BB-API-Key": api_key, "Content-Type": "application/json"}, + json={"projectId": project_id}, + timeout=_HTTP_TIMEOUT, + ) + sess.raise_for_status() + connect_url = sess.json().get("connectUrl") + if not connect_url: + return None + with sync_playwright() as p: + browser = p.chromium.connect_over_cdp(connect_url) + try: + page = browser.contexts[0].pages[0] if browser.contexts else browser.new_page() + page.goto(url, timeout=30000, wait_until="domcontentloaded") + html = page.content() + finally: + browser.close() + from tools.browser_scraper import _parse_job_html # reuse cleaner + return _parse_job_html(html) + except Exception as exc: # noqa: BLE001 + logger.warning("Browserbase deep-fetch failed for %s: %s", url, exc) + return None + + +def _playwright_fetch(url: str) -> Optional[str]: + try: + from tools.browser_scraper import browser_enabled, scrape_job_posting + except ImportError: + return None + if not browser_enabled(): + return None + try: + return scrape_job_posting(url) + except Exception as exc: # noqa: BLE001 + logger.warning("Playwright deep-fetch failed for %s: %s", url, exc) + return None + + +# --------------------------------------------------------------------------- +# Agentic orchestration +# --------------------------------------------------------------------------- + +_FALLBACK_QUERIES = [ + "{company} company news", + "{company} layoffs OR funding OR revenue", + "{company} glassdoor reviews culture", +] + + +def build_queries(company: str, model: str = "fast") -> List[str]: + """LLM-proposed search queries for the company; static fallback on failure.""" + static = [q.format(company=company) for q in _FALLBACK_QUERIES] + if not company: + return static + prompt = ( + "Propose 3 concise web-search queries to research this company for a " + "job seeker: stability/news, layoffs/financials, and culture. Return a " + "STRICT JSON array of 3 strings, nothing else.\n\n" + f"Company: {wrap_untrusted(company, 'company_name')}" + ) + try: + raw = get_completion(prompt, model).strip() + raw = re.sub(r"^```(?:json)?\s*|\s*```$", "", raw) + queries = json.loads(raw) + cleaned = [str(q).strip() for q in queries if str(q).strip()][:3] + return cleaned or static + except Exception as exc: # noqa: BLE001 - static queries are fine + logger.info("Query generation failed (%s); using static queries.", exc) + return static + + +def _format_results(results: List[dict]) -> str: + lines = [] + for r in results[:10]: + title = (r.get("title") or "").strip() + snippet = (r.get("snippet") or "").strip() + url = (r.get("url") or "").strip() + if title or snippet: + lines.append(f"- {title}\n {snippet}\n ({url})") + return "\n".join(lines) + + +def agentic_company_research(company: str, model: str = "fast") -> Optional[str]: + """Keyless agentic web research for a company. Returns a synthesised + briefing string, or None when unavailable (caller uses its sentinel).""" + if not fallback_enabled() or not company: + return None + + queries = build_queries(company, model) + results: List[dict] = [] + seen_urls = set() + for q in queries: + for r in ddg_search(q): + u = r.get("url") + if u and u in seen_urls: + continue + seen_urls.add(u) + results.append(r) + + if not results: + return None + + # Optional deep dive on the top result (only if a browser backend exists). + deep = deep_fetch(results[0].get("url", "")) + deep_block = ( + f"\n\nTop-result page content:\n{wrap_untrusted(deep[:4000], 'page')}" + if deep else "" + ) + + prompt = f"""\ +You are researching **{company}** for a job seeker using ONLY the web-search +results below. Do NOT invent facts not present in these snippets. Where the +snippets are thin, say so rather than guessing. + +Search results: +{wrap_untrusted(_format_results(results), 'search_results')}{deep_block} + +Produce a concise markdown briefing: +1. Recent news / signals (only what the snippets support) +2. Stability indicators (funding, layoffs, growth — only if mentioned) +3. Culture signals (only if mentioned; label as "Inference:" otherwise) +4. What the candidate should verify themselves + +Start with: "REAL DATA (web search, DuckDuckGo) for {company}:". +Do not output blocks or wrap the whole report in a code fence. +""" + try: + return get_completion(prompt, model) + except Exception as exc: # noqa: BLE001 + logger.warning("Company research synthesis failed: %s", exc) + return None diff --git a/tools/data_sources.py b/tools/data_sources.py index 3ee69ee..cef522b 100644 --- a/tools/data_sources.py +++ b/tools/data_sources.py @@ -45,30 +45,50 @@ def _format_news(articles: list, company_name: str, limit: int = 5) -> str: def fetch_company_news(company_name: str) -> Optional[str]: - """Fetch recent company news, or None if unavailable.""" + """Fetch recent company news. + + Tier 1: NewsAPI when ``NEWS_API_KEY`` is set. Tier 2: a keyless agentic + DuckDuckGo web-search fallback (when an LLM provider is configured). + Returns None only when neither yields anything — the caller then uses its + explicit "NOT AVAILABLE" sentinel. + """ api_key = os.getenv("NEWS_API_KEY") - if not api_key or not company_name: + if api_key and company_name: + try: + resp = requests.get( + _NEWS_ENDPOINT, + params={ + "q": f'"{company_name}"', + "sortBy": "publishedAt", + "language": "en", + "pageSize": 10, + "apiKey": api_key, + }, + timeout=_HTTP_TIMEOUT, + ) + resp.raise_for_status() + data = resp.json() + if data.get("status") == "ok": + return _format_news(data.get("articles", []), company_name) + logger.warning("newsapi returned status=%s", data.get("status")) + except Exception as exc: # noqa: BLE001 - fall through to agentic tier + logger.warning("Company news fetch failed for %s: %s", company_name, exc) + + # Tier 2: keyless agentic web-search fallback. + return _agentic_news_fallback(company_name) + + +def _agentic_news_fallback(company_name: str) -> Optional[str]: + if not company_name: return None try: - resp = requests.get( - _NEWS_ENDPOINT, - params={ - "q": f'"{company_name}"', - "sortBy": "publishedAt", - "language": "en", - "pageSize": 10, - "apiKey": api_key, - }, - timeout=_HTTP_TIMEOUT, - ) - resp.raise_for_status() - data = resp.json() - if data.get("status") != "ok": - logger.warning("newsapi returned status=%s", data.get("status")) - return None - return _format_news(data.get("articles", []), company_name) - except Exception as exc: # noqa: BLE001 - degrade to fallback sentinel - logger.warning("Company news fetch failed for %s: %s", company_name, exc) + from tools.company_research import agentic_company_research + except ImportError: + return None + try: + return agentic_company_research(company_name) + except Exception as exc: # noqa: BLE001 - never break the pipeline + logger.warning("Agentic company research failed for %s: %s", company_name, exc) return None diff --git a/uv.lock b/uv.lock index acfe535..a1d84ab 100644 --- a/uv.lock +++ b/uv.lock @@ -4,7 +4,8 @@ requires-python = ">=3.11" resolution-markers = [ "python_full_version >= '3.15'", "python_full_version == '3.14.*'", - "python_full_version >= '3.12.4' and python_full_version < '3.14'", + "python_full_version == '3.13.*'", + "python_full_version >= '3.12.4' and python_full_version < '3.13'", "python_full_version >= '3.12' and python_full_version < '3.12.4'", "python_full_version < '3.12'", ] @@ -371,6 +372,79 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e5/ca/78d423b324b8d77900030fa59c4aa9054261ef0925631cd2501dd015b7b7/boolean_py-5.0-py3-none-any.whl", hash = "sha256:ef28a70bd43115208441b53a045d1549e2f0ec6e3d08a9d142cbc41c1938e8d9", size = 26577, upload-time = "2025-04-03T10:39:48.449Z" }, ] +[[package]] +name = "brotli" +version = "1.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f7/16/c92ca344d646e71a43b8bb353f0a6490d7f6e06210f8554c8f874e454285/brotli-1.2.0.tar.gz", hash = "sha256:e310f77e41941c13340a95976fe66a8a95b01e783d430eeaf7a2f87e0a57dd0a", size = 7388632, upload-time = "2025-11-05T18:39:42.86Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7a/ef/f285668811a9e1ddb47a18cb0b437d5fc2760d537a2fe8a57875ad6f8448/brotli-1.2.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:15b33fe93cedc4caaff8a0bd1eb7e3dab1c61bb22a0bf5bdfdfd97cd7da79744", size = 863110, upload-time = "2025-11-05T18:38:12.978Z" }, + { url = "https://files.pythonhosted.org/packages/50/62/a3b77593587010c789a9d6eaa527c79e0848b7b860402cc64bc0bc28a86c/brotli-1.2.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:898be2be399c221d2671d29eed26b6b2713a02c2119168ed914e7d00ceadb56f", size = 445438, upload-time = "2025-11-05T18:38:14.208Z" }, + { url = "https://files.pythonhosted.org/packages/cd/e1/7fadd47f40ce5549dc44493877db40292277db373da5053aff181656e16e/brotli-1.2.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:350c8348f0e76fff0a0fd6c26755d2653863279d086d3aa2c290a6a7251135dd", size = 1534420, upload-time = "2025-11-05T18:38:15.111Z" }, + { url = "https://files.pythonhosted.org/packages/12/8b/1ed2f64054a5a008a4ccd2f271dbba7a5fb1a3067a99f5ceadedd4c1d5a7/brotli-1.2.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:2e1ad3fda65ae0d93fec742a128d72e145c9c7a99ee2fcd667785d99eb25a7fe", size = 1632619, upload-time = "2025-11-05T18:38:16.094Z" }, + { url = "https://files.pythonhosted.org/packages/89/5a/7071a621eb2d052d64efd5da2ef55ecdac7c3b0c6e4f9d519e9c66d987ef/brotli-1.2.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:40d918bce2b427a0c4ba189df7a006ac0c7277c180aee4617d99e9ccaaf59e6a", size = 1426014, upload-time = "2025-11-05T18:38:17.177Z" }, + { url = "https://files.pythonhosted.org/packages/26/6d/0971a8ea435af5156acaaccec1a505f981c9c80227633851f2810abd252a/brotli-1.2.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:2a7f1d03727130fc875448b65b127a9ec5d06d19d0148e7554384229706f9d1b", size = 1489661, upload-time = "2025-11-05T18:38:18.41Z" }, + { url = "https://files.pythonhosted.org/packages/f3/75/c1baca8b4ec6c96a03ef8230fab2a785e35297632f402ebb1e78a1e39116/brotli-1.2.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:9c79f57faa25d97900bfb119480806d783fba83cd09ee0b33c17623935b05fa3", size = 1599150, upload-time = "2025-11-05T18:38:19.792Z" }, + { url = "https://files.pythonhosted.org/packages/0d/1a/23fcfee1c324fd48a63d7ebf4bac3a4115bdb1b00e600f80f727d850b1ae/brotli-1.2.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:844a8ceb8483fefafc412f85c14f2aae2fb69567bf2a0de53cdb88b73e7c43ae", size = 1493505, upload-time = "2025-11-05T18:38:20.913Z" }, + { url = "https://files.pythonhosted.org/packages/36/e5/12904bbd36afeef53d45a84881a4810ae8810ad7e328a971ebbfd760a0b3/brotli-1.2.0-cp311-cp311-win32.whl", hash = "sha256:aa47441fa3026543513139cb8926a92a8e305ee9c71a6209ef7a97d91640ea03", size = 334451, upload-time = "2025-11-05T18:38:21.94Z" }, + { url = "https://files.pythonhosted.org/packages/02/8b/ecb5761b989629a4758c394b9301607a5880de61ee2ee5fe104b87149ebc/brotli-1.2.0-cp311-cp311-win_amd64.whl", hash = "sha256:022426c9e99fd65d9475dce5c195526f04bb8be8907607e27e747893f6ee3e24", size = 369035, upload-time = "2025-11-05T18:38:22.941Z" }, + { url = "https://files.pythonhosted.org/packages/11/ee/b0a11ab2315c69bb9b45a2aaed022499c9c24a205c3a49c3513b541a7967/brotli-1.2.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:35d382625778834a7f3061b15423919aa03e4f5da34ac8e02c074e4b75ab4f84", size = 861543, upload-time = "2025-11-05T18:38:24.183Z" }, + { url = "https://files.pythonhosted.org/packages/e1/2f/29c1459513cd35828e25531ebfcbf3e92a5e49f560b1777a9af7203eb46e/brotli-1.2.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:7a61c06b334bd99bc5ae84f1eeb36bfe01400264b3c352f968c6e30a10f9d08b", size = 444288, upload-time = "2025-11-05T18:38:25.139Z" }, + { url = "https://files.pythonhosted.org/packages/3d/6f/feba03130d5fceadfa3a1bb102cb14650798c848b1df2a808356f939bb16/brotli-1.2.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:acec55bb7c90f1dfc476126f9711a8e81c9af7fb617409a9ee2953115343f08d", size = 1528071, upload-time = "2025-11-05T18:38:26.081Z" }, + { url = "https://files.pythonhosted.org/packages/2b/38/f3abb554eee089bd15471057ba85f47e53a44a462cfce265d9bf7088eb09/brotli-1.2.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:260d3692396e1895c5034f204f0db022c056f9e2ac841593a4cf9426e2a3faca", size = 1626913, upload-time = "2025-11-05T18:38:27.284Z" }, + { url = "https://files.pythonhosted.org/packages/03/a7/03aa61fbc3c5cbf99b44d158665f9b0dd3d8059be16c460208d9e385c837/brotli-1.2.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:072e7624b1fc4d601036ab3f4f27942ef772887e876beff0301d261210bca97f", size = 1419762, upload-time = "2025-11-05T18:38:28.295Z" }, + { url = "https://files.pythonhosted.org/packages/21/1b/0374a89ee27d152a5069c356c96b93afd1b94eae83f1e004b57eb6ce2f10/brotli-1.2.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:adedc4a67e15327dfdd04884873c6d5a01d3e3b6f61406f99b1ed4865a2f6d28", size = 1484494, upload-time = "2025-11-05T18:38:29.29Z" }, + { url = "https://files.pythonhosted.org/packages/cf/57/69d4fe84a67aef4f524dcd075c6eee868d7850e85bf01d778a857d8dbe0a/brotli-1.2.0-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:7a47ce5c2288702e09dc22a44d0ee6152f2c7eda97b3c8482d826a1f3cfc7da7", size = 1593302, upload-time = "2025-11-05T18:38:30.639Z" }, + { url = "https://files.pythonhosted.org/packages/d5/3b/39e13ce78a8e9a621c5df3aeb5fd181fcc8caba8c48a194cd629771f6828/brotli-1.2.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:af43b8711a8264bb4e7d6d9a6d004c3a2019c04c01127a868709ec29962b6036", size = 1487913, upload-time = "2025-11-05T18:38:31.618Z" }, + { url = "https://files.pythonhosted.org/packages/62/28/4d00cb9bd76a6357a66fcd54b4b6d70288385584063f4b07884c1e7286ac/brotli-1.2.0-cp312-cp312-win32.whl", hash = "sha256:e99befa0b48f3cd293dafeacdd0d191804d105d279e0b387a32054c1180f3161", size = 334362, upload-time = "2025-11-05T18:38:32.939Z" }, + { url = "https://files.pythonhosted.org/packages/1c/4e/bc1dcac9498859d5e353c9b153627a3752868a9d5f05ce8dedd81a2354ab/brotli-1.2.0-cp312-cp312-win_amd64.whl", hash = "sha256:b35c13ce241abdd44cb8ca70683f20c0c079728a36a996297adb5334adfc1c44", size = 369115, upload-time = "2025-11-05T18:38:33.765Z" }, + { url = "https://files.pythonhosted.org/packages/6c/d4/4ad5432ac98c73096159d9ce7ffeb82d151c2ac84adcc6168e476bb54674/brotli-1.2.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:9e5825ba2c9998375530504578fd4d5d1059d09621a02065d1b6bfc41a8e05ab", size = 861523, upload-time = "2025-11-05T18:38:34.67Z" }, + { url = "https://files.pythonhosted.org/packages/91/9f/9cc5bd03ee68a85dc4bc89114f7067c056a3c14b3d95f171918c088bf88d/brotli-1.2.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0cf8c3b8ba93d496b2fae778039e2f5ecc7cff99df84df337ca31d8f2252896c", size = 444289, upload-time = "2025-11-05T18:38:35.6Z" }, + { url = "https://files.pythonhosted.org/packages/2e/b6/fe84227c56a865d16a6614e2c4722864b380cb14b13f3e6bef441e73a85a/brotli-1.2.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c8565e3cdc1808b1a34714b553b262c5de5fbda202285782173ec137fd13709f", size = 1528076, upload-time = "2025-11-05T18:38:36.639Z" }, + { url = "https://files.pythonhosted.org/packages/55/de/de4ae0aaca06c790371cf6e7ee93a024f6b4bb0568727da8c3de112e726c/brotli-1.2.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:26e8d3ecb0ee458a9804f47f21b74845cc823fd1bb19f02272be70774f56e2a6", size = 1626880, upload-time = "2025-11-05T18:38:37.623Z" }, + { url = "https://files.pythonhosted.org/packages/5f/16/a1b22cbea436642e071adcaf8d4b350a2ad02f5e0ad0da879a1be16188a0/brotli-1.2.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:67a91c5187e1eec76a61625c77a6c8c785650f5b576ca732bd33ef58b0dff49c", size = 1419737, upload-time = "2025-11-05T18:38:38.729Z" }, + { url = "https://files.pythonhosted.org/packages/46/63/c968a97cbb3bdbf7f974ef5a6ab467a2879b82afbc5ffb65b8acbb744f95/brotli-1.2.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4ecdb3b6dc36e6d6e14d3a1bdc6c1057c8cbf80db04031d566eb6080ce283a48", size = 1484440, upload-time = "2025-11-05T18:38:39.916Z" }, + { url = "https://files.pythonhosted.org/packages/06/9d/102c67ea5c9fc171f423e8399e585dabea29b5bc79b05572891e70013cdd/brotli-1.2.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:3e1b35d56856f3ed326b140d3c6d9db91740f22e14b06e840fe4bb1923439a18", size = 1593313, upload-time = "2025-11-05T18:38:41.24Z" }, + { url = "https://files.pythonhosted.org/packages/9e/4a/9526d14fa6b87bc827ba1755a8440e214ff90de03095cacd78a64abe2b7d/brotli-1.2.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:54a50a9dad16b32136b2241ddea9e4df159b41247b2ce6aac0b3276a66a8f1e5", size = 1487945, upload-time = "2025-11-05T18:38:42.277Z" }, + { url = "https://files.pythonhosted.org/packages/5b/e8/3fe1ffed70cbef83c5236166acaed7bb9c766509b157854c80e2f766b38c/brotli-1.2.0-cp313-cp313-win32.whl", hash = "sha256:1b1d6a4efedd53671c793be6dd760fcf2107da3a52331ad9ea429edf0902f27a", size = 334368, upload-time = "2025-11-05T18:38:43.345Z" }, + { url = "https://files.pythonhosted.org/packages/ff/91/e739587be970a113b37b821eae8097aac5a48e5f0eca438c22e4c7dd8648/brotli-1.2.0-cp313-cp313-win_amd64.whl", hash = "sha256:b63daa43d82f0cdabf98dee215b375b4058cce72871fd07934f179885aad16e8", size = 369116, upload-time = "2025-11-05T18:38:44.609Z" }, + { url = "https://files.pythonhosted.org/packages/17/e1/298c2ddf786bb7347a1cd71d63a347a79e5712a7c0cba9e3c3458ebd976f/brotli-1.2.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:6c12dad5cd04530323e723787ff762bac749a7b256a5bece32b2243dd5c27b21", size = 863080, upload-time = "2025-11-05T18:38:45.503Z" }, + { url = "https://files.pythonhosted.org/packages/84/0c/aac98e286ba66868b2b3b50338ffbd85a35c7122e9531a73a37a29763d38/brotli-1.2.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:3219bd9e69868e57183316ee19c84e03e8f8b5a1d1f2667e1aa8c2f91cb061ac", size = 445453, upload-time = "2025-11-05T18:38:46.433Z" }, + { url = "https://files.pythonhosted.org/packages/ec/f1/0ca1f3f99ae300372635ab3fe2f7a79fa335fee3d874fa7f9e68575e0e62/brotli-1.2.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:963a08f3bebd8b75ac57661045402da15991468a621f014be54e50f53a58d19e", size = 1528168, upload-time = "2025-11-05T18:38:47.371Z" }, + { url = "https://files.pythonhosted.org/packages/d6/a6/2ebfc8f766d46df8d3e65b880a2e220732395e6d7dc312c1e1244b0f074a/brotli-1.2.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9322b9f8656782414b37e6af884146869d46ab85158201d82bab9abbcb971dc7", size = 1627098, upload-time = "2025-11-05T18:38:48.385Z" }, + { url = "https://files.pythonhosted.org/packages/f3/2f/0976d5b097ff8a22163b10617f76b2557f15f0f39d6a0fe1f02b1a53e92b/brotli-1.2.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:cf9cba6f5b78a2071ec6fb1e7bd39acf35071d90a81231d67e92d637776a6a63", size = 1419861, upload-time = "2025-11-05T18:38:49.372Z" }, + { url = "https://files.pythonhosted.org/packages/9c/97/d76df7176a2ce7616ff94c1fb72d307c9a30d2189fe877f3dd99af00ea5a/brotli-1.2.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7547369c4392b47d30a3467fe8c3330b4f2e0f7730e45e3103d7d636678a808b", size = 1484594, upload-time = "2025-11-05T18:38:50.655Z" }, + { url = "https://files.pythonhosted.org/packages/d3/93/14cf0b1216f43df5609f5b272050b0abd219e0b54ea80b47cef9867b45e7/brotli-1.2.0-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:fc1530af5c3c275b8524f2e24841cbe2599d74462455e9bae5109e9ff42e9361", size = 1593455, upload-time = "2025-11-05T18:38:51.624Z" }, + { url = "https://files.pythonhosted.org/packages/b3/73/3183c9e41ca755713bdf2cc1d0810df742c09484e2e1ddd693bee53877c1/brotli-1.2.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:d2d085ded05278d1c7f65560aae97b3160aeb2ea2c0b3e26204856beccb60888", size = 1488164, upload-time = "2025-11-05T18:38:53.079Z" }, + { url = "https://files.pythonhosted.org/packages/64/6a/0c78d8f3a582859236482fd9fa86a65a60328a00983006bcf6d83b7b2253/brotli-1.2.0-cp314-cp314-win32.whl", hash = "sha256:832c115a020e463c2f67664560449a7bea26b0c1fdd690352addad6d0a08714d", size = 339280, upload-time = "2025-11-05T18:38:54.02Z" }, + { url = "https://files.pythonhosted.org/packages/f5/10/56978295c14794b2c12007b07f3e41ba26acda9257457d7085b0bb3bb90c/brotli-1.2.0-cp314-cp314-win_amd64.whl", hash = "sha256:e7c0af964e0b4e3412a0ebf341ea26ec767fa0b4cf81abb5e897c9338b5ad6a3", size = 375639, upload-time = "2025-11-05T18:38:55.67Z" }, +] + +[[package]] +name = "brotlicffi" +version = "1.2.0.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8a/b6/017dc5f852ed9b8735af77774509271acbf1de02d238377667145fcee01d/brotlicffi-1.2.0.1.tar.gz", hash = "sha256:c20d5c596278307ad06414a6d95a892377ea274a5c6b790c2548c009385d621c", size = 478156, upload-time = "2026-03-05T19:54:11.547Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/f9/dfa56316837fa798eac19358351e974de8e1e2ca9475af4cb90293cd6576/brotlicffi-1.2.0.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:2c85e65913cf2b79c57a3fdd05b98d9731d9255dc0cb696b09376cc091b9cddd", size = 433046, upload-time = "2026-03-05T19:53:46.209Z" }, + { url = "https://files.pythonhosted.org/packages/4a/f5/f8f492158c76b0d940388801f04f747028971ad5774287bded5f1e53f08d/brotlicffi-1.2.0.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:535f2d05d0273408abc13fc0eebb467afac17b0ad85090c8913690d40207dac5", size = 1541126, upload-time = "2026-03-05T19:53:48.248Z" }, + { url = "https://files.pythonhosted.org/packages/3b/e1/ff87af10ac419600c63e9287a0649c673673ae6b4f2bcf48e96cb2f89f60/brotlicffi-1.2.0.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ce17eb798ca59ecec67a9bb3fd7a4304e120d1cd02953ce522d959b9a84d58ac", size = 1541983, upload-time = "2026-03-05T19:53:50.317Z" }, + { url = "https://files.pythonhosted.org/packages/47/c0/80ecd9bd45776109fab14040e478bf63e456967c9ddee2353d8330ed8de1/brotlicffi-1.2.0.1-cp314-cp314t-win32.whl", hash = "sha256:3c9544f83cb715d95d7eab3af4adbbef8b2093ad6382288a83b3a25feb1a57ec", size = 349047, upload-time = "2026-03-05T19:53:52.215Z" }, + { url = "https://files.pythonhosted.org/packages/ab/98/13e5b250236a281b6cd9e92a01ee1ae231029fa78faee932ef3766e1cb24/brotlicffi-1.2.0.1-cp314-cp314t-win_amd64.whl", hash = "sha256:625f8115d32ae9c0740d01ea51518437c3fbaa3e78d41cb18459f6f7ac326000", size = 385652, upload-time = "2026-03-05T19:53:53.892Z" }, + { url = "https://files.pythonhosted.org/packages/9a/9f/b98dcd4af47994cee97aebac866996a006a2e5fc1fd1e2b82a8ad95cf09c/brotlicffi-1.2.0.1-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:91ba5f0ccc040f6ff8f7efaf839f797723d03ed46acb8ae9408f99ffd2572cf4", size = 432608, upload-time = "2026-03-05T19:53:56.736Z" }, + { url = "https://files.pythonhosted.org/packages/b1/7a/ac4ee56595a061e3718a6d1ea7e921f4df156894acffb28ed88a1fd52022/brotlicffi-1.2.0.1-cp38-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:be9a670c6811af30a4bd42d7116dc5895d3b41beaa8ed8a89050447a0181f5ce", size = 1534257, upload-time = "2026-03-05T19:53:58.667Z" }, + { url = "https://files.pythonhosted.org/packages/99/39/e7410db7f6f56de57744ea52a115084ceb2735f4d44973f349bb92136586/brotlicffi-1.2.0.1-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6f3314a3476f59e5443f9f72a6dff16edc0c3463c9b318feaef04ae3e4683f5a", size = 1536838, upload-time = "2026-03-05T19:54:00.705Z" }, + { url = "https://files.pythonhosted.org/packages/a6/75/6e7977d1935fc3fbb201cbd619be8f2c7aea25d40a096967132854b34708/brotlicffi-1.2.0.1-cp38-abi3-win32.whl", hash = "sha256:82ea52e2b5d3145b6c406ebd3efb0d55db718b7ad996bd70c62cec0439de1187", size = 343337, upload-time = "2026-03-05T19:54:02.446Z" }, + { url = "https://files.pythonhosted.org/packages/d8/ef/e7e485ce5e4ba3843a0a92feb767c7b6098fd6e65ce752918074d175ae71/brotlicffi-1.2.0.1-cp38-abi3-win_amd64.whl", hash = "sha256:da2e82a08e7778b8bc539d27ca03cdd684113e81394bfaaad8d0dfc6a17ddede", size = 379026, upload-time = "2026-03-05T19:54:04.322Z" }, + { url = "https://files.pythonhosted.org/packages/7f/53/6262c2256513e6f530d81642477cb19367270922063eaa2d7b781d8c723d/brotlicffi-1.2.0.1-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:e015af99584c6db1490a69a210c765953e473e63adc2d891ac3062a737c9e851", size = 402265, upload-time = "2026-03-05T19:54:05.858Z" }, + { url = "https://files.pythonhosted.org/packages/1f/d9/d5340b43cf5fbe7fe5a083d237e5338cc1caa73bea523be1c5e452c26290/brotlicffi-1.2.0.1-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:37cb587d32bf7168e2218c455e22e409ad1f3157c6c71945879a311f3e6b6abf", size = 406710, upload-time = "2026-03-05T19:54:07.272Z" }, + { url = "https://files.pythonhosted.org/packages/a3/82/dbced4c1e0792efdf23fd90ff6d2a320c64ff4dfef7aacc85c04fde9ddd2/brotlicffi-1.2.0.1-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9d6ba65dd528892b4d9960beba2ae011a753620bcfc66cf6fa3cee18d7b0baa4", size = 402787, upload-time = "2026-03-05T19:54:08.73Z" }, + { url = "https://files.pythonhosted.org/packages/ef/6f/534205ba7590c9a8716a614f270c5c2ec419b5b7079b3f9cd31b7b5580de/brotlicffi-1.2.0.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:f2a5575653b0672638ba039b82fda56854934d7a6a24d4b8b5033f73ab43cbc1", size = 375108, upload-time = "2026-03-05T19:54:10.079Z" }, +] + [[package]] name = "cachecontrol" version = "0.14.4" @@ -693,6 +767,22 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/57/af/333ad82adec8121dae568f7d094a3b08ba485340cf19fe10674f2db14774/cyclonedx_python_lib-11.8.0-py3-none-any.whl", hash = "sha256:a326b575acbb3aa1040986307a4ae282ff27f99ffcbdfdaaf8de10ee85e97f01", size = 523911, upload-time = "2026-06-04T10:38:26.248Z" }, ] +[[package]] +name = "ddgs" +version = "9.14.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "fake-useragent" }, + { name = "httpx", extra = ["brotli", "http2", "socks"] }, + { name = "lxml" }, + { name = "primp" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/77/24/9d29eeb7dd4852c27c3673adcaf30c4dc55ced76b303c1fbb792ce7cae52/ddgs-9.14.4.tar.gz", hash = "sha256:f7b118a2b709a9e9c04a1dca6e96b98c25d4dfaca1a4b0a244d74454fcca48ef", size = 59742, upload-time = "2026-05-15T06:53:45.946Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e8/5f/32de4d99220eb559b7b1cd1c529a1856efa8097f7a3e10b6c207aa95e36c/ddgs-9.14.4-py3-none-any.whl", hash = "sha256:acb084c34bf1110c974caf7e5e5a2c1973beb4bd9e170bfd191fe5ed2d2b2d6c", size = 70638, upload-time = "2026-05-15T06:53:44.761Z" }, +] + [[package]] name = "defusedxml" version = "0.7.1" @@ -720,6 +810,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a7/5f/ed01f9a3cdffbd5a008556fc7b2a08ddb1cc6ace7effa7340604b1d16699/docstring_parser-0.18.0-py3-none-any.whl", hash = "sha256:b3fcbed555c47d8479be0796ef7e19c2670d428d72e96da63f3a40122860374b", size = 22484, upload-time = "2026-04-14T04:09:18.638Z" }, ] +[[package]] +name = "fake-useragent" +version = "2.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/41/43/948d10bf42735709edb5ae51e23297d034086f17fc7279fef385a7acb473/fake_useragent-2.2.0.tar.gz", hash = "sha256:4e6ab6571e40cc086d788523cf9e018f618d07f9050f822ff409a4dfe17c16b2", size = 158898, upload-time = "2025-04-14T15:32:19.238Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/37/b3ea9cd5558ff4cb51957caca2193981c6b0ff30bd0d2630ac62505d99d0/fake_useragent-2.2.0-py3-none-any.whl", hash = "sha256:67f35ca4d847b0d298187443aaf020413746e56acd985a611908c73dba2daa24", size = 161695, upload-time = "2025-04-14T15:32:17.732Z" }, +] + [[package]] name = "fastapi" version = "0.136.3" @@ -933,7 +1032,8 @@ name = "h11" version = "0.14.0" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version >= '3.12.4' and python_full_version < '3.14'", + "python_full_version == '3.13.*'", + "python_full_version >= '3.12.4' and python_full_version < '3.13'", "python_full_version >= '3.12' and python_full_version < '3.12.4'", "python_full_version < '3.12'", ] @@ -955,12 +1055,35 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, ] +[[package]] +name = "h2" +version = "4.3.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "hpack" }, + { name = "hyperframe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/1d/17/afa56379f94ad0fe8defd37d6eb3f89a25404ffc71d4d848893d270325fc/h2-4.3.0.tar.gz", hash = "sha256:6c59efe4323fa18b47a632221a1888bd7fde6249819beda254aeca909f221bf1", size = 2152026, upload-time = "2025-08-23T18:12:19.778Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/b2/119f6e6dcbd96f9069ce9a2665e0146588dc9f88f29549711853645e736a/h2-4.3.0-py3-none-any.whl", hash = "sha256:c438f029a25f7945c69e0ccf0fb951dc3f73a5f6412981daee861431b70e2bdd", size = 61779, upload-time = "2025-08-23T18:12:17.779Z" }, +] + +[[package]] +name = "hpack" +version = "4.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2c/48/71de9ed269fdae9c8057e5a4c0aa7402e8bb16f2c6e90b3aa53327b113f8/hpack-4.1.0.tar.gz", hash = "sha256:ec5eca154f7056aa06f196a557655c5b009b382873ac8d1e66e79e87535f1dca", size = 51276, upload-time = "2025-01-22T21:44:58.347Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/07/c6/80c95b1b2b94682a72cbdbfb85b81ae2daffa4291fbfa1b1464502ede10d/hpack-4.1.0-py3-none-any.whl", hash = "sha256:157ac792668d995c657d93111f46b4535ed114f0c9c8d672271bbec7eae1b496", size = 34357, upload-time = "2025-01-22T21:44:56.92Z" }, +] + [[package]] name = "httpcore" version = "1.0.7" source = { registry = "https://pypi.org/simple" } resolution-markers = [ - "python_full_version >= '3.12.4' and python_full_version < '3.14'", + "python_full_version == '3.13.*'", + "python_full_version >= '3.12.4' and python_full_version < '3.13'", "python_full_version >= '3.12' and python_full_version < '3.12.4'", "python_full_version < '3.12'", ] @@ -1006,6 +1129,27 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, ] +[package.optional-dependencies] +brotli = [ + { name = "brotli", marker = "platform_python_implementation == 'CPython'" }, + { name = "brotlicffi", marker = "platform_python_implementation != 'CPython'" }, +] +http2 = [ + { name = "h2" }, +] +socks = [ + { name = "socksio" }, +] + +[[package]] +name = "hyperframe" +version = "6.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/02/e7/94f8232d4a74cc99514c13a9f995811485a6903d48e5d952771ef6322e30/hyperframe-6.1.0.tar.gz", hash = "sha256:f630908a00854a7adeabd6382b43923a4c4cd4b821fcb527e6ab9e15382a3b08", size = 26566, upload-time = "2025-01-22T21:41:49.302Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/48/30/47d0bf6072f7252e6521f3447ccfa40b421b6824517f82854703d0f5a98b/hyperframe-6.1.0-py3-none-any.whl", hash = "sha256:b03380493a519fce58ea5af42e4a42317bf9bd425596f7a0835ffce80f1a42e5", size = 13007, upload-time = "2025-01-22T21:41:47.295Z" }, +] + [[package]] name = "idna" version = "3.10" @@ -1116,6 +1260,9 @@ dev = [ pdf = [ { name = "fpdf2" }, ] +research = [ + { name = "ddgs" }, +] telegram = [ { name = "python-telegram-bot" }, ] @@ -1134,6 +1281,7 @@ requires-dist = [ { name = "beautifulsoup4", specifier = ">=4.13.3" }, { name = "celery", marker = "extra == 'worker'", specifier = ">=5.3.0" }, { name = "coverage", marker = "extra == 'dev'", specifier = ">=7.5" }, + { name = "ddgs", marker = "extra == 'research'", specifier = ">=6.0" }, { name = "fastapi", specifier = ">=0.110.0" }, { name = "fpdf2", specifier = ">=2.8.7" }, { name = "fpdf2", marker = "extra == 'pdf'", specifier = ">=2.7.0" }, @@ -1158,7 +1306,7 @@ requires-dist = [ { name = "types-requests", marker = "extra == 'dev'" }, { name = "uvicorn", specifier = ">=0.27.0" }, ] -provides-extras = ["telegram", "worker", "browser", "pdf", "dev"] +provides-extras = ["telegram", "worker", "browser", "pdf", "research", "dev"] [[package]] name = "jsonpatch" @@ -1813,7 +1961,8 @@ source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.15'", "python_full_version == '3.14.*'", - "python_full_version >= '3.12.4' and python_full_version < '3.14'", + "python_full_version == '3.13.*'", + "python_full_version >= '3.12.4' and python_full_version < '3.13'", "python_full_version >= '3.12' and python_full_version < '3.12.4'", ] sdist = { url = "https://files.pythonhosted.org/packages/fb/90/8956572f5c4ae52201fdec7ba2044b2c882832dcec7d5d0922c9e9acf2de/numpy-2.2.3.tar.gz", hash = "sha256:dbdc15f0c81611925f382dfa97b3bd0bc2c1ce19d4fe50482cb0ddc12ba30020", size = 20262700, upload-time = "2025-02-13T17:17:41.558Z" } @@ -2127,6 +2276,44 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/80/c8/210f282d278e4709cdd71b12a31af45a30a22ab3207b387e29b37e478713/playwright-1.60.0-py3-none-win_arm64.whl", hash = "sha256:6e4f6700a4c2250efff8e690a81d66e3855754fb587b6b87cf5c784014f91537", size = 34037981, upload-time = "2026-05-18T12:00:57.584Z" }, ] +[[package]] +name = "primp" +version = "1.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cc/4b/7efa54f38da7de8df6b70dfed173bb41a52b740b144e4be24c1172db4209/primp-1.3.1.tar.gz", hash = "sha256:b04a5941bf9c876d011c5defaf5a25be093d56e7270b8da52c9788b9df2a829a", size = 1360029, upload-time = "2026-05-23T17:39:25.568Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7f/80/c4885a783a7493e396d89a592ba19fce63ef6bd6ad47230924a884a30ec0/primp-1.3.1-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:27b87e6370045a0c65c0e4dfdfacbfe637387d05673ce8ddcce400263f7c27f0", size = 5123967, upload-time = "2026-05-23T17:39:08.586Z" }, + { url = "https://files.pythonhosted.org/packages/58/c1/c965cc23f96a364803d44b4331f33e4465bb6f269add37e39d0ad77ffe33/primp-1.3.1-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:27a8804eb9a3f641f379ee2b443591428cf85c898816e93d04d3e7b6f229ebcb", size = 4743059, upload-time = "2026-05-23T17:39:15.536Z" }, + { url = "https://files.pythonhosted.org/packages/9c/99/f4248d8d833d43fd8ba78208f2f4bf7fba7d3aec8c516090a95d18d6f550/primp-1.3.1-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:862974796552a51af8e276bb19c5d5e189168ab8bad216aef7ce3726a8d3b1dd", size = 5100121, upload-time = "2026-05-23T17:39:04.64Z" }, + { url = "https://files.pythonhosted.org/packages/9b/ad/519e32e0184763e1a76c9321fdeac0bb9b30bf85746f12058feec0cc4a27/primp-1.3.1-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:ceb24198994799706f4020a00173ba9c1b491aa9805b1e014d87946677bc3c5d", size = 4738042, upload-time = "2026-05-23T17:39:35.967Z" }, + { url = "https://files.pythonhosted.org/packages/dc/7b/723cb40694b47ec79a142ed8492835c0ecae9fef7acbed014f04b018d1de/primp-1.3.1-cp310-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b3298b8afcf0a88ba6622bfc18e78aeb11afbb7d5afa4774f24acf7491f54a2d", size = 5001773, upload-time = "2026-05-23T17:39:03.01Z" }, + { url = "https://files.pythonhosted.org/packages/52/b8/80a2e3bdab1c51d738b82ea210a5ab93986b443c561e792e42cae296ec10/primp-1.3.1-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6b8d38c5a6d0a863274cbcae9678f265fcdcead3c20d12d152244e88f5f2186b", size = 5334228, upload-time = "2026-05-23T17:39:24.214Z" }, + { url = "https://files.pythonhosted.org/packages/19/70/c95b8054c7d1fe2d84226ec60a5f48ce6c95a08b7c8b1702d7742082f444/primp-1.3.1-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:96f831c78ddb5900873f51e294bf9bbb4bbfdac3a2f39ce4023f8c558d299332", size = 5157269, upload-time = "2026-05-23T17:38:48.142Z" }, + { url = "https://files.pythonhosted.org/packages/34/bb/9b66986b7ecf2eff987134cd94bde533142e3085d6f67531f1a369ceaaae/primp-1.3.1-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:329d0c320841f65b39d80801d8bae126732b84ec1094ca17b14fda0bda1b20ff", size = 5347438, upload-time = "2026-05-23T17:39:17.405Z" }, + { url = "https://files.pythonhosted.org/packages/aa/29/5d127748d06f3c6a3367f3c4974e45b98cda61cd28ea79ef91ad3fe9e093/primp-1.3.1-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:6c3c67670c38a03e9e8da45b212243d35afc8efa018317c46ecdce47f05329d1", size = 5264862, upload-time = "2026-05-23T17:39:20.625Z" }, + { url = "https://files.pythonhosted.org/packages/16/f3/1aac229425cac142c48418e2de9f70597161ea936543b5e3c9e7476e1921/primp-1.3.1-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:9409a31028a8c62a609d389554ad4f5339aad075130300cd443beef0336d7179", size = 4969889, upload-time = "2026-05-23T17:39:22.412Z" }, + { url = "https://files.pythonhosted.org/packages/38/86/a94d6e6166139c76ae42eb941328679309ca85139e8753d639657a24474c/primp-1.3.1-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:88ca36c2bd1b7c64b96ad07ca367d2d111ac8e9670549be5f232da8bf795d21e", size = 5082679, upload-time = "2026-05-23T17:39:28.411Z" }, + { url = "https://files.pythonhosted.org/packages/cf/61/21d297db575ed660c6aaf35c9014c1874ace45d6dcb79d1a4d3d2608bffb/primp-1.3.1-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:74d13800b501aa003fb05c263d38f8d61656c83a60b2951046c0fc412bc73976", size = 5605392, upload-time = "2026-05-23T17:39:38.007Z" }, + { url = "https://files.pythonhosted.org/packages/36/d6/9262a7ebb1d980a2db0cd505bb902bb3e66acd8a1cb763a4c2921f2f6a5b/primp-1.3.1-cp310-abi3-win32.whl", hash = "sha256:09ada1752629fe89d7b128beeb59cb641f404af462e24177ba36aed1cf322299", size = 4270373, upload-time = "2026-05-23T17:38:44.98Z" }, + { url = "https://files.pythonhosted.org/packages/8f/68/f0c6a60fadff0c185aef232b951a6fa4bbb64511facc48d34734db14f16f/primp-1.3.1-cp310-abi3-win_amd64.whl", hash = "sha256:c0d1e294466cd5ec7ef173eedf8df25cbdc050138d40447a906e92b8553e7765", size = 4661498, upload-time = "2026-05-23T17:39:32.213Z" }, + { url = "https://files.pythonhosted.org/packages/7f/1d/232a52abc77384ac66b9c1741691dec3659b1207bb6c5e55c1e9b59d22f1/primp-1.3.1-cp310-abi3-win_arm64.whl", hash = "sha256:43304cb41cbb46f361de49faf1cbdba57f969f628c9297239c7ed8ef0cac420f", size = 4624481, upload-time = "2026-05-23T17:38:42.724Z" }, + { url = "https://files.pythonhosted.org/packages/e5/0b/34333b26c533c3122b936dad829f0a6e04f32065d39673c92b157d97aa16/primp-1.3.1-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:72249a4540d0a8965f36eb9a86cd16801d1c7e8dac2f0b0fa23a0a5a03402d36", size = 5116098, upload-time = "2026-05-23T17:38:55.219Z" }, + { url = "https://files.pythonhosted.org/packages/7a/56/7fe14708adf9a5cb5d6a15ad840a3de036cebfaf20692a5bc3b72e188a73/primp-1.3.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:db4e2eaa5707e47899eeba6026f420f9b0108a28c08d63f1826d0cab8d50f06f", size = 4736300, upload-time = "2026-05-23T17:38:51.792Z" }, + { url = "https://files.pythonhosted.org/packages/31/cb/521a8c18e8808a75450b6e91dc62cc1149c0178b7d4a8697d3f9b73fa385/primp-1.3.1-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d62e7609c98b4bc99c9cecc47f16f332fb8fe1a023002176267b0043dedad0c7", size = 5093823, upload-time = "2026-05-23T17:38:50.059Z" }, + { url = "https://files.pythonhosted.org/packages/57/84/90f776fe46aeb0e3b86df72c674c0651326dd6a61846dd86bddbabe903ac/primp-1.3.1-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:3d692e912c2b25271163ba7719df0afdb733a7e7c3073c9094e9001882463543", size = 4734511, upload-time = "2026-05-23T17:39:34.166Z" }, + { url = "https://files.pythonhosted.org/packages/19/79/d9bfbc0df0394f18a98b512a65f4bcf3dd7d17bd871937127e1ce4549172/primp-1.3.1-cp314-cp314t-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0c08693517dc160a12c0f9e2565c5319173cef738893a303ff2fb28ecccbd84d", size = 4999315, upload-time = "2026-05-23T17:39:12.061Z" }, + { url = "https://files.pythonhosted.org/packages/bb/d8/5a986957ee1874d08567d7749668cd78a063048d47d6e46a874742b7fed1/primp-1.3.1-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d134ebfa31adc619e4e48289fe3e7eebc8310141560e6a6a04269cc94893d9ab", size = 5329375, upload-time = "2026-05-23T17:39:30.307Z" }, + { url = "https://files.pythonhosted.org/packages/5c/1d/321cac9902cc3992174ed530719141a0da2e426f54f8a90b7b971571d104/primp-1.3.1-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:48e27e7c0e015a6de495cf79c0c8d599ba5f69d091af31572bec2de020522d9c", size = 5140921, upload-time = "2026-05-23T17:38:53.528Z" }, + { url = "https://files.pythonhosted.org/packages/a6/19/ccbe6b67e0e91beb5c9d5cf804354225d5a3a7a9adf84fee3d6acc53febd/primp-1.3.1-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5c3d682df08c1b1f37b1f66b21fd173baebcfcb52490830b12292d8fe89b2147", size = 5344288, upload-time = "2026-05-23T17:39:18.965Z" }, + { url = "https://files.pythonhosted.org/packages/ff/e5/a735751bd11558163e83e0961fc866e4f94634df9eb24937c5f59624e393/primp-1.3.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:fabaac4280df0802377d34b869949d617a0ecf22ca7fd5f9bded3f5c981031f1", size = 5262909, upload-time = "2026-05-23T17:39:00.789Z" }, + { url = "https://files.pythonhosted.org/packages/09/8e/4e3d4520e2e751f2de825dbe2cb43f837d33a5528adc44255f9770ea125a/primp-1.3.1-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:f510e5881e0a4c4b9e7dbc03722c316d58454388b88000a0e7bf18a4b36d601e", size = 4964809, upload-time = "2026-05-23T17:38:59.023Z" }, + { url = "https://files.pythonhosted.org/packages/8f/b5/e7b7495687d07df693325a12c497a9e5185d5001b7b216f32019fa7437a0/primp-1.3.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:0504de2901c97903a9c369856a4b186dc90a782d8320652c142b066e697d5a1a", size = 5083654, upload-time = "2026-05-23T17:39:06.598Z" }, + { url = "https://files.pythonhosted.org/packages/f2/f9/e4652e93beb14a16cc4218cfb1ccc18eaca8ee7d93b517d614a135928ec9/primp-1.3.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:6c3b24e302d95d327e873834b9423823b9c8af2abf5e0bbf57a03f3354cfe528", size = 5594738, upload-time = "2026-05-23T17:39:27.001Z" }, + { url = "https://files.pythonhosted.org/packages/e2/49/e8c8a7bc6b741ab6f15896022eee4f906d04d7ccd15aeeb515dd04bbeb6d/primp-1.3.1-cp314-cp314t-win32.whl", hash = "sha256:4346dcef805279028bf4a54bb87dd43d0920130e25b5790689f5c96c9ba0d9e5", size = 4262615, upload-time = "2026-05-23T17:39:13.88Z" }, + { url = "https://files.pythonhosted.org/packages/a9/84/7ae4a257dec6dff329d4a8d9051d907316095c27ffc8d1ea15c359e6eeb5/primp-1.3.1-cp314-cp314t-win_amd64.whl", hash = "sha256:6c55f152a73b6d6af8ac37bdb648d8bbfd7e656f9ef40d87feb3c0d81cee930a", size = 4660584, upload-time = "2026-05-23T17:39:10.081Z" }, + { url = "https://files.pythonhosted.org/packages/99/20/10e0d96bfaeef1f0cd339ccf9bb8feb4bf798fde93198f7a96c73441080a/primp-1.3.1-cp314-cp314t-win_arm64.whl", hash = "sha256:46a529d74583d6ceba52e15bf4c678fcf24e6d669c1ce935262d5490d1b25801", size = 4623226, upload-time = "2026-05-23T17:38:57.256Z" }, +] + [[package]] name = "prompt-toolkit" version = "3.0.52" @@ -2735,6 +2922,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e9/44/75a9c9421471a6c4805dbf2356f7c181a29c1879239abab1ea2cc8f38b40/sniffio-1.3.1-py3-none-any.whl", hash = "sha256:2f6da418d1f1e0fddd844478f41680e794e6051915791a034ff65e5f100525a2", size = 10235, upload-time = "2024-02-25T23:20:01.196Z" }, ] +[[package]] +name = "socksio" +version = "1.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f8/5c/48a7d9495be3d1c651198fd99dbb6ce190e2274d0f28b9051307bdec6b85/socksio-1.0.0.tar.gz", hash = "sha256:f88beb3da5b5c38b9890469de67d0cb0f9d494b78b106ca1845f96c10b91c4ac", size = 19055, upload-time = "2020-04-17T15:50:34.664Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/37/c3/6eeb6034408dac0fa653d126c9204ade96b819c936e136c5e8a6897eee9c/socksio-1.0.0-py3-none-any.whl", hash = "sha256:95dc1f15f9b34e8d7b16f06d74b8ccf48f609af32ab33c608d08761c5dcbb1f3", size = 12763, upload-time = "2020-04-17T15:50:31.878Z" }, +] + [[package]] name = "sortedcontainers" version = "2.4.0" From daaee4d79bd41a84e1430c1c240d05329fa52e5f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 7 Jun 2026 19:33:54 +0000 Subject: [PATCH 12/24] P1 #6: envelope-encrypt the TOTP secret at rest Add utils/crypto (Fernet, key derived from SECRETS_ENCRYPTION_KEY) and wire it into services/totp: the TOTP secret is stored as enc:v1: when a key is configured, transparently decrypted on read, and passed through as plaintext when unkeyed (dev/demo). Legacy plaintext rows are re-encrypted opportunistically on the next successful verify. - utils/crypto.py: encrypt/decrypt/is_encrypted/encryption_enabled with a transparent prefix scheme; decrypt of a prefixed value with no/wrong key raises DecryptionError (never leaks gibberish into a verify). - db/models.py: widen user_two_factor.secret 64->255 for the ciphertext. - migration 5d2f8a1c4e7b: column widen (up/down/up verified). - .env.example: document SECRETS_ENCRYPTION_KEY + rotation caveat. - pyproject: add cryptography>=41 explicitly; uv.lock regenerated. - tests: 9 new (crypto primitives + TOTP integration incl. lazy re-encrypt). https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd --- .env.example | 8 + CLAUDE.md | 8 +- db/models.py | 15 +- .../versions/5d2f8a1c4e7b_totp_widen_col.py | 43 +++++ pyproject.toml | 1 + services/totp.py | 24 ++- tests/test_phase34_crypto_at_rest.py | 151 ++++++++++++++++ utils/crypto.py | 119 +++++++++++++ uv.lock | 168 +++++++++++++----- 9 files changed, 484 insertions(+), 53 deletions(-) create mode 100644 migrations/versions/5d2f8a1c4e7b_totp_widen_col.py create mode 100644 tests/test_phase34_crypto_at_rest.py create mode 100644 utils/crypto.py diff --git a/.env.example b/.env.example index 33ecc50..e08c8ba 100644 --- a/.env.example +++ b/.env.example @@ -93,6 +93,14 @@ # Telegram bot channel (alternative to the Streamlit UI) # TELEGRAM_BOT_TOKEN=... # from @BotFather +# Secrets at rest — envelope-encrypt the TOTP 2FA secret (and any future +# sensitive low-volume fields). Set to any string/passphrase; a Fernet key is +# derived from it (SHA-256). When UNSET, secrets are stored plaintext (dev/demo) +# and legacy rows are re-encrypted lazily once a key is configured. In prod, +# source this from a KMS-decrypted data key at boot. Rotating the key without +# re-encrypting existing rows will break 2FA verification for those users. +# SECRETS_ENCRYPTION_KEY=change-me-to-a-long-random-string + # Password reset — self-hosted convenience flag. # Set to 1 ONLY in single-user/self-hosted deployments to display reset # tokens directly in the UI. Leave UNSET in multi-tenant production. diff --git a/CLAUDE.md b/CLAUDE.md index a890ced..505615a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -162,8 +162,12 @@ and "production-grade for real multi-user traffic." Prioritized: 5. ✅ **CI quality gates:** ruff (lint) + mypy (type) + bandit (hard gate) + pip-audit (advisory) + coverage floor 80% + JS tests in CI + Node-24 opt-in. Config in `pyproject.toml`; jobs in `.github/workflows/tests.yml`. -6. **Secrets at rest:** envelope-encrypt the TOTP secret (KMS-derived key); - consider the same for OAuth-linked emails. +6. ✅ **Secrets at rest:** the TOTP secret is envelope-encrypted via + `utils/crypto` (Fernet, key derived from `SECRETS_ENCRYPTION_KEY`) — stored + as `enc:v1:…`, transparently decrypted on read, pass-through plaintext when + unkeyed (dev/demo), and legacy plaintext rows re-encrypt opportunistically + on the next successful verify. Column widened 64→255 (migration + `5d2f8a1c4e7b`). Same primitive is reusable for OAuth-linked emails. 7. **LLM cost controls:** token accounting + per-user budget (today's quota is a request count, not spend). Cache identical analyses (the cache exists; wire COL/news/LLM through it consistently). diff --git a/db/models.py b/db/models.py index f5e3f67..157b597 100644 --- a/db/models.py +++ b/db/models.py @@ -93,11 +93,14 @@ class User(Base): class UserTwoFactor(Base): """TOTP-based second factor for one user. - ``secret`` is the base32 TOTP shared secret. It is stored unencrypted - here — for production-grade key protection, layer in an envelope- - encryption step using a KMS-derived key. TOTP is secondary defence; - the primary protection against credential stuffing is the bcrypt - password hash, which remains intact under a DB-only compromise. + ``secret`` is the base32 TOTP shared secret. It is envelope-encrypted at + rest (``utils.crypto``, ``enc:v1:…``) whenever ``SECRETS_ENCRYPTION_KEY`` + is configured; without a key it is stored plaintext (dev/demo) and any + legacy plaintext row is re-encrypted opportunistically on the next + successful verify. The wider column accommodates the Fernet ciphertext. + TOTP is secondary defence; the primary protection against credential + stuffing is the bcrypt password hash, which remains intact under a + DB-only compromise. ``backup_codes`` is the list of bcrypt-hashed one-time recovery codes the user can use instead of an OTP. Used codes are removed from the @@ -113,7 +116,7 @@ class UserTwoFactor(Base): ForeignKey("users.id", ondelete="CASCADE"), nullable=False, unique=True, index=True, ) - secret: Mapped[str] = mapped_column(String(64), nullable=False) + secret: Mapped[str] = mapped_column(String(255), nullable=False) verified: Mapped[bool] = mapped_column(default=False, nullable=False) backup_codes: Mapped[Optional[list]] = mapped_column(JSON) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) diff --git a/migrations/versions/5d2f8a1c4e7b_totp_widen_col.py b/migrations/versions/5d2f8a1c4e7b_totp_widen_col.py new file mode 100644 index 0000000..41aec6d --- /dev/null +++ b/migrations/versions/5d2f8a1c4e7b_totp_widen_col.py @@ -0,0 +1,43 @@ +"""widen user_two_factor.secret for envelope-encrypted ciphertext + +Revision ID: 5d2f8a1c4e7b +Revises: 46b9602c99a1 +Create Date: 2026-06-07 00:00:00 + +The TOTP secret is now envelope-encrypted at rest (utils.crypto, "enc:v1:…") +when SECRETS_ENCRYPTION_KEY is set. The Fernet ciphertext is far longer than +the 32-char base32 plaintext, so the column is widened 64 -> 255. Existing +plaintext values still fit and are re-encrypted lazily by the app. +""" +from typing import Sequence, Union + +import sqlalchemy as sa +from alembic import op + +revision: str = "5d2f8a1c4e7b" +down_revision: Union[str, None] = "46b9602c99a1" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + with op.batch_alter_table("user_two_factor") as batch: + batch.alter_column( + "secret", + existing_type=sa.String(64), + type_=sa.String(255), + existing_nullable=False, + ) + + +def downgrade() -> None: + # Note: if any encrypted secret exceeds 64 chars this would truncate; the + # downgrade is only safe before encryption is enabled (i.e. in a rollback + # of this migration prior to keying). Kept symmetric for the up→down→up CI. + with op.batch_alter_table("user_two_factor") as batch: + batch.alter_column( + "secret", + existing_type=sa.String(255), + type_=sa.String(64), + existing_nullable=False, + ) diff --git a/pyproject.toml b/pyproject.toml index f2020ac..4d08a49 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -13,6 +13,7 @@ dependencies = [ "anthropic>=0.40.0", "bcrypt>=4.1.0", "beautifulsoup4>=4.13.3", + "cryptography>=41.0.0", "fastapi>=0.110.0", "fpdf2>=2.8.7", "langchain>=0.3.19", diff --git a/services/totp.py b/services/totp.py index 40ba9d1..9c90c3d 100644 --- a/services/totp.py +++ b/services/totp.py @@ -45,6 +45,7 @@ from db.session import get_session from services.audit import record as _audit from services.rate_limit import RateLimiter, RateLimitExceeded +from utils import crypto logger = logging.getLogger(__name__) @@ -108,12 +109,13 @@ def pending_setup(user_id: int) -> bool: def start_setup(user_id: int, account_label: str) -> SetupResult: """Generate a fresh TOTP secret + provisioning URI. Idempotent.""" secret = pyotp.random_base32() + stored = crypto.encrypt(secret) # envelope-encrypted at rest when keyed with get_session() as session: row = session.execute( select(UserTwoFactor).where(UserTwoFactor.user_id == user_id) ).scalar_one_or_none() if row is None: - row = UserTwoFactor(user_id=user_id, secret=secret, verified=False) + row = UserTwoFactor(user_id=user_id, secret=stored, verified=False) session.add(row) else: # Unverified pending setup -> replace the secret. A verified row @@ -123,7 +125,7 @@ def start_setup(user_id: int, account_label: str) -> SetupResult: raise TOTPError( "2FA is already enabled. Disable it first if you want a fresh setup." ) - row.secret = secret + row.secret = stored session.commit() issuer = "JobOffer Scanner" uri = pyotp.totp.TOTP(secret).provisioning_uri(name=account_label, issuer_name=issuer) @@ -187,6 +189,11 @@ def verify_login(user_id: int, code: str) -> bool: return False if _verify_totp(row.secret, code): + # Opportunistically migrate a legacy plaintext secret to ciphertext + # now that we've proven the key works against it. + if crypto.encryption_enabled() and not crypto.is_encrypted(row.secret): + row.secret = crypto.encrypt(crypto.decrypt(row.secret)) + session.commit() _VERIFY_LIMITER.reset(str(user_id)) _audit("user.2fa.verify.success", user_id=user_id) return True @@ -248,10 +255,19 @@ def _normalize_code(code: str) -> str: def _verify_totp(secret: str, code: str) -> bool: - """RFC-default TOTP verify with ±1-step (~30s) skew tolerance.""" + """RFC-default TOTP verify with ±1-step (~30s) skew tolerance. + + ``secret`` is the stored value, which may be envelope-encrypted + (``enc:v1:…``) or legacy plaintext; ``crypto.decrypt`` handles both. + """ if not code.isdigit() or len(code) != 6: return False - return pyotp.TOTP(secret).verify(code, valid_window=1) + try: + plain = crypto.decrypt(secret) + except crypto.DecryptionError: + logger.error("TOTP secret could not be decrypted; check SECRETS_ENCRYPTION_KEY.") + return False + return pyotp.TOTP(plain).verify(code, valid_window=1) def _generate_canonical_backup_code() -> str: diff --git a/tests/test_phase34_crypto_at_rest.py b/tests/test_phase34_crypto_at_rest.py new file mode 100644 index 0000000..4bf9fc6 --- /dev/null +++ b/tests/test_phase34_crypto_at_rest.py @@ -0,0 +1,151 @@ +"""P1 #6: envelope-encryption of secrets at rest (utils.crypto + TOTP wiring). + +Covers the crypto primitives (round-trip, prefix scheme, transparent +pass-through when unkeyed, decrypt-failure policy) and the integration with +the TOTP service: the stored secret is ciphertext when keyed, login still +verifies, and a legacy plaintext secret is re-encrypted on first verify. +""" + +from __future__ import annotations + +import os +import sys +import unittest +from unittest import mock + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +import pyotp # noqa: E402 + +from db.session import get_session, reset_engine_for_testing # noqa: E402 +from utils import crypto # noqa: E402 + +_KEY = "test-secrets-encryption-key-please-ignore" + + +class CryptoUnitTests(unittest.TestCase): + def setUp(self): + crypto.reset_cache_for_testing() + + def tearDown(self): + crypto.reset_cache_for_testing() + + def test_passthrough_when_unkeyed(self): + with mock.patch.dict(os.environ, {}, clear=False): + os.environ.pop("SECRETS_ENCRYPTION_KEY", None) + crypto.reset_cache_for_testing() + self.assertFalse(crypto.encryption_enabled()) + self.assertEqual(crypto.encrypt("ABC123"), "ABC123") + self.assertEqual(crypto.decrypt("ABC123"), "ABC123") + + def test_round_trip_when_keyed(self): + with mock.patch.dict(os.environ, {"SECRETS_ENCRYPTION_KEY": _KEY}): + crypto.reset_cache_for_testing() + self.assertTrue(crypto.encryption_enabled()) + token = crypto.encrypt("JBSWY3DPEHPK3PXP") + self.assertTrue(token.startswith("enc:v1:")) + self.assertNotIn("JBSWY3DPEHPK3PXP", token) + self.assertTrue(crypto.is_encrypted(token)) + self.assertEqual(crypto.decrypt(token), "JBSWY3DPEHPK3PXP") + + def test_encrypt_is_idempotent(self): + with mock.patch.dict(os.environ, {"SECRETS_ENCRYPTION_KEY": _KEY}): + crypto.reset_cache_for_testing() + once = crypto.encrypt("secret") + twice = crypto.encrypt(once) + self.assertEqual(once, twice) + + def test_legacy_plaintext_decrypts_transparently_when_keyed(self): + with mock.patch.dict(os.environ, {"SECRETS_ENCRYPTION_KEY": _KEY}): + crypto.reset_cache_for_testing() + # A value without the prefix is treated as legacy plaintext. + self.assertEqual(crypto.decrypt("legacy-plain"), "legacy-plain") + + def test_decrypt_prefixed_without_key_raises(self): + with mock.patch.dict(os.environ, {"SECRETS_ENCRYPTION_KEY": _KEY}): + crypto.reset_cache_for_testing() + token = crypto.encrypt("secret") + os.environ.pop("SECRETS_ENCRYPTION_KEY", None) + crypto.reset_cache_for_testing() + with self.assertRaises(crypto.DecryptionError): + crypto.decrypt(token) + + def test_decrypt_wrong_key_raises(self): + with mock.patch.dict(os.environ, {"SECRETS_ENCRYPTION_KEY": _KEY}): + crypto.reset_cache_for_testing() + token = crypto.encrypt("secret") + with mock.patch.dict(os.environ, {"SECRETS_ENCRYPTION_KEY": "a-different-key"}): + crypto.reset_cache_for_testing() + with self.assertRaises(crypto.DecryptionError): + crypto.decrypt(token) + + +class TotpEncryptionIntegrationTests(unittest.TestCase): + def setUp(self): + reset_engine_for_testing("sqlite:///:memory:") + crypto.reset_cache_for_testing() + # Create a user to attach 2FA to. + from services import auth + self.user = auth.register_user("enc@example.com", "Sup3rSecret!") + + def tearDown(self): + crypto.reset_cache_for_testing() + + def _enable_2fa(self): + from services import totp + setup = totp.start_setup(self.user.id, "enc@example.com") + code = pyotp.TOTP(setup.secret).now() + totp.confirm_setup(self.user.id, code) + return setup.secret + + def test_secret_stored_encrypted_when_keyed(self): + from sqlalchemy import select + + from db.models import UserTwoFactor + with mock.patch.dict(os.environ, {"SECRETS_ENCRYPTION_KEY": _KEY}): + crypto.reset_cache_for_testing() + plain_secret = self._enable_2fa() + with get_session() as session: + row = session.execute( + select(UserTwoFactor).where(UserTwoFactor.user_id == self.user.id) + ).scalar_one() + self.assertTrue(row.secret.startswith("enc:v1:")) + self.assertNotIn(plain_secret, row.secret) + + def test_login_verifies_against_encrypted_secret(self): + from services import totp + with mock.patch.dict(os.environ, {"SECRETS_ENCRYPTION_KEY": _KEY}): + crypto.reset_cache_for_testing() + plain_secret = self._enable_2fa() + code = pyotp.TOTP(plain_secret).now() + self.assertTrue(totp.verify_login(self.user.id, code)) + + def test_legacy_plaintext_secret_reencrypted_on_verify(self): + from sqlalchemy import select + + from db.models import UserTwoFactor + from services import totp + + # Enable WITHOUT a key -> plaintext at rest (legacy state). + plain_secret = self._enable_2fa() + with get_session() as session: + row = session.execute( + select(UserTwoFactor).where(UserTwoFactor.user_id == self.user.id) + ).scalar_one() + self.assertFalse(row.secret.startswith("enc:v1:")) + + # Now a key appears; a successful verify should migrate it to ciphertext. + with mock.patch.dict(os.environ, {"SECRETS_ENCRYPTION_KEY": _KEY}): + crypto.reset_cache_for_testing() + code = pyotp.TOTP(plain_secret).now() + self.assertTrue(totp.verify_login(self.user.id, code)) + with get_session() as session: + row = session.execute( + select(UserTwoFactor).where(UserTwoFactor.user_id == self.user.id) + ).scalar_one() + self.assertTrue(row.secret.startswith("enc:v1:")) + self.assertEqual(crypto.decrypt(row.secret), plain_secret) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/crypto.py b/utils/crypto.py new file mode 100644 index 0000000..cd1da18 --- /dev/null +++ b/utils/crypto.py @@ -0,0 +1,119 @@ +"""Envelope encryption for secrets at rest (Fernet / AES-128-CBC + HMAC). + +The TOTP shared secret (and, optionally, other low-volume sensitive fields) +is encrypted at rest with a key derived from the ``SECRETS_ENCRYPTION_KEY`` +environment variable. The model is intentionally simple and transparent: + + * ``encrypt(plaintext)`` returns ``"enc:v1:"`` when a key is + configured, else the plaintext unchanged. + * ``decrypt(value)`` reverses it: values carrying the ``enc:v1:`` prefix are + decrypted; anything else (legacy plaintext) is returned as-is. + +This dual behaviour makes adoption a no-op migration: existing plaintext rows +keep working and are re-encrypted lazily the next time the app writes them. +When no key is set (dev / demo), encryption is a transparent pass-through so +nothing breaks — the value is simply stored in the clear, exactly as before. + +Key handling: ``SECRETS_ENCRYPTION_KEY`` may be **any** string (a passphrase, +a generated token, a base64 Fernet key). We derive a stable 32-byte Fernet +key from it with SHA-256, so operators don't have to produce a precisely +formatted key. For real KMS integration, set ``SECRETS_ENCRYPTION_KEY`` from +a KMS-decrypted data key at boot — the derivation here is the last mile. + +Failure policy: a decrypt failure (wrong/rotated key, corrupt value) raises +``DecryptionError`` — we must NOT silently treat a ciphertext as plaintext, +which would leak gibberish into a TOTP verify. Encryption never raises for the +caller's data; if the backend is somehow unavailable it falls back to +pass-through and logs once. +""" + +from __future__ import annotations + +import base64 +import hashlib +import logging +import os +from functools import lru_cache +from typing import Optional + +logger = logging.getLogger(__name__) + +_PREFIX = "enc:v1:" +_KEY_ENV = "SECRETS_ENCRYPTION_KEY" + + +class DecryptionError(ValueError): + """An ``enc:v1:`` value could not be decrypted (wrong key / corruption).""" + + +def _derive_fernet_key(passphrase: str) -> bytes: + """Derive a urlsafe-base64 32-byte Fernet key from an arbitrary string.""" + digest = hashlib.sha256(passphrase.encode("utf-8")).digest() + return base64.urlsafe_b64encode(digest) + + +@lru_cache(maxsize=1) +def _get_fernet(): + """Return a cached Fernet instance, or None when encryption is unconfigured + or the backend is unavailable.""" + passphrase = os.getenv(_KEY_ENV) + if not passphrase: + return None + try: + from cryptography.fernet import Fernet + except ImportError: + logger.warning( + "%s is set but the 'cryptography' package is unavailable; " + "secrets will be stored in plaintext.", _KEY_ENV + ) + return None + return Fernet(_derive_fernet_key(passphrase)) + + +def reset_cache_for_testing() -> None: + """Drop the cached Fernet so a test can flip ``SECRETS_ENCRYPTION_KEY``.""" + _get_fernet.cache_clear() + + +def encryption_enabled() -> bool: + """Whether a usable encryption backend is configured.""" + return _get_fernet() is not None + + +def is_encrypted(value: Optional[str]) -> bool: + """Whether ``value`` is an envelope ciphertext produced by ``encrypt``.""" + return value is not None and value.startswith(_PREFIX) + + +def encrypt(plaintext: str) -> str: + """Encrypt ``plaintext`` to an ``enc:v1:`` token, or pass through unchanged + when encryption is unconfigured. Already-encrypted input is returned as-is + (idempotent).""" + if plaintext is None: + return plaintext + if is_encrypted(plaintext): + return plaintext + fernet = _get_fernet() + if fernet is None: + return plaintext + token = fernet.encrypt(plaintext.encode("utf-8")).decode("ascii") + return f"{_PREFIX}{token}" + + +def decrypt(value: str) -> str: + """Decrypt an ``enc:v1:`` value; return non-prefixed (legacy plaintext) + values unchanged. Raises ``DecryptionError`` if a prefixed value can't be + decrypted.""" + if not is_encrypted(value): + return value + fernet = _get_fernet() + if fernet is None: + raise DecryptionError( + f"value is encrypted but {_KEY_ENV} is not configured" + ) + token = value[len(_PREFIX):] + try: + from cryptography.fernet import InvalidToken + return fernet.decrypt(token.encode("ascii")).decode("utf-8") + except InvalidToken as exc: + raise DecryptionError("could not decrypt value (wrong or rotated key)") from exc diff --git a/uv.lock b/uv.lock index a1d84ab..d3f648d 100644 --- a/uv.lock +++ b/uv.lock @@ -503,47 +503,72 @@ wheels = [ [[package]] name = "cffi" -version = "1.17.1" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pycparser" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/fc/97/c783634659c2920c3fc70419e3af40972dbaf758daa229a7d6ea6135c90d/cffi-1.17.1.tar.gz", hash = "sha256:1c39c6016c32bc48dd54561950ebd6836e1670f2ae46128f67cf49e789c52824", size = 516621, upload-time = "2024-09-04T20:45:21.852Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/6b/f4/927e3a8899e52a27fa57a48607ff7dc91a9ebe97399b357b85a0c7892e00/cffi-1.17.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a45e3c6913c5b87b3ff120dcdc03f6131fa0065027d0ed7ee6190736a74cd401", size = 182264, upload-time = "2024-09-04T20:43:51.124Z" }, - { url = "https://files.pythonhosted.org/packages/6c/f5/6c3a8efe5f503175aaddcbea6ad0d2c96dad6f5abb205750d1b3df44ef29/cffi-1.17.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:30c5e0cb5ae493c04c8b42916e52ca38079f1b235c2f8ae5f4527b963c401caf", size = 178651, upload-time = "2024-09-04T20:43:52.872Z" }, - { url = "https://files.pythonhosted.org/packages/94/dd/a3f0118e688d1b1a57553da23b16bdade96d2f9bcda4d32e7d2838047ff7/cffi-1.17.1-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f75c7ab1f9e4aca5414ed4d8e5c0e303a34f4421f8a0d47a4d019ceff0ab6af4", size = 445259, upload-time = "2024-09-04T20:43:56.123Z" }, - { url = "https://files.pythonhosted.org/packages/2e/ea/70ce63780f096e16ce8588efe039d3c4f91deb1dc01e9c73a287939c79a6/cffi-1.17.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a1ed2dd2972641495a3ec98445e09766f077aee98a1c896dcb4ad0d303628e41", size = 469200, upload-time = "2024-09-04T20:43:57.891Z" }, - { url = "https://files.pythonhosted.org/packages/1c/a0/a4fa9f4f781bda074c3ddd57a572b060fa0df7655d2a4247bbe277200146/cffi-1.17.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:46bf43160c1a35f7ec506d254e5c890f3c03648a4dbac12d624e4490a7046cd1", size = 477235, upload-time = "2024-09-04T20:44:00.18Z" }, - { url = "https://files.pythonhosted.org/packages/62/12/ce8710b5b8affbcdd5c6e367217c242524ad17a02fe5beec3ee339f69f85/cffi-1.17.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a24ed04c8ffd54b0729c07cee15a81d964e6fee0e3d4d342a27b020d22959dc6", size = 459721, upload-time = "2024-09-04T20:44:01.585Z" }, - { url = "https://files.pythonhosted.org/packages/ff/6b/d45873c5e0242196f042d555526f92aa9e0c32355a1be1ff8c27f077fd37/cffi-1.17.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:610faea79c43e44c71e1ec53a554553fa22321b65fae24889706c0a84d4ad86d", size = 467242, upload-time = "2024-09-04T20:44:03.467Z" }, - { url = "https://files.pythonhosted.org/packages/1a/52/d9a0e523a572fbccf2955f5abe883cfa8bcc570d7faeee06336fbd50c9fc/cffi-1.17.1-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:a9b15d491f3ad5d692e11f6b71f7857e7835eb677955c00cc0aefcd0669adaf6", size = 477999, upload-time = "2024-09-04T20:44:05.023Z" }, - { url = "https://files.pythonhosted.org/packages/44/74/f2a2460684a1a2d00ca799ad880d54652841a780c4c97b87754f660c7603/cffi-1.17.1-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:de2ea4b5833625383e464549fec1bc395c1bdeeb5f25c4a3a82b5a8c756ec22f", size = 454242, upload-time = "2024-09-04T20:44:06.444Z" }, - { url = "https://files.pythonhosted.org/packages/f8/4a/34599cac7dfcd888ff54e801afe06a19c17787dfd94495ab0c8d35fe99fb/cffi-1.17.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:fc48c783f9c87e60831201f2cce7f3b2e4846bf4d8728eabe54d60700b318a0b", size = 478604, upload-time = "2024-09-04T20:44:08.206Z" }, - { url = "https://files.pythonhosted.org/packages/34/33/e1b8a1ba29025adbdcda5fb3a36f94c03d771c1b7b12f726ff7fef2ebe36/cffi-1.17.1-cp311-cp311-win32.whl", hash = "sha256:85a950a4ac9c359340d5963966e3e0a94a676bd6245a4b55bc43949eee26a655", size = 171727, upload-time = "2024-09-04T20:44:09.481Z" }, - { url = "https://files.pythonhosted.org/packages/3d/97/50228be003bb2802627d28ec0627837ac0bf35c90cf769812056f235b2d1/cffi-1.17.1-cp311-cp311-win_amd64.whl", hash = "sha256:caaf0640ef5f5517f49bc275eca1406b0ffa6aa184892812030f04c2abf589a0", size = 181400, upload-time = "2024-09-04T20:44:10.873Z" }, - { url = "https://files.pythonhosted.org/packages/5a/84/e94227139ee5fb4d600a7a4927f322e1d4aea6fdc50bd3fca8493caba23f/cffi-1.17.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:805b4371bf7197c329fcb3ead37e710d1bca9da5d583f5073b799d5c5bd1eee4", size = 183178, upload-time = "2024-09-04T20:44:12.232Z" }, - { url = "https://files.pythonhosted.org/packages/da/ee/fb72c2b48656111c4ef27f0f91da355e130a923473bf5ee75c5643d00cca/cffi-1.17.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:733e99bc2df47476e3848417c5a4540522f234dfd4ef3ab7fafdf555b082ec0c", size = 178840, upload-time = "2024-09-04T20:44:13.739Z" }, - { url = "https://files.pythonhosted.org/packages/cc/b6/db007700f67d151abadf508cbfd6a1884f57eab90b1bb985c4c8c02b0f28/cffi-1.17.1-cp312-cp312-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1257bdabf294dceb59f5e70c64a3e2f462c30c7ad68092d01bbbfb1c16b1ba36", size = 454803, upload-time = "2024-09-04T20:44:15.231Z" }, - { url = "https://files.pythonhosted.org/packages/1a/df/f8d151540d8c200eb1c6fba8cd0dfd40904f1b0682ea705c36e6c2e97ab3/cffi-1.17.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:da95af8214998d77a98cc14e3a3bd00aa191526343078b530ceb0bd710fb48a5", size = 478850, upload-time = "2024-09-04T20:44:17.188Z" }, - { url = "https://files.pythonhosted.org/packages/28/c0/b31116332a547fd2677ae5b78a2ef662dfc8023d67f41b2a83f7c2aa78b1/cffi-1.17.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d63afe322132c194cf832bfec0dc69a99fb9bb6bbd550f161a49e9e855cc78ff", size = 485729, upload-time = "2024-09-04T20:44:18.688Z" }, - { url = "https://files.pythonhosted.org/packages/91/2b/9a1ddfa5c7f13cab007a2c9cc295b70fbbda7cb10a286aa6810338e60ea1/cffi-1.17.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f79fc4fc25f1c8698ff97788206bb3c2598949bfe0fef03d299eb1b5356ada99", size = 471256, upload-time = "2024-09-04T20:44:20.248Z" }, - { url = "https://files.pythonhosted.org/packages/b2/d5/da47df7004cb17e4955df6a43d14b3b4ae77737dff8bf7f8f333196717bf/cffi-1.17.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b62ce867176a75d03a665bad002af8e6d54644fad99a3c70905c543130e39d93", size = 479424, upload-time = "2024-09-04T20:44:21.673Z" }, - { url = "https://files.pythonhosted.org/packages/0b/ac/2a28bcf513e93a219c8a4e8e125534f4f6db03e3179ba1c45e949b76212c/cffi-1.17.1-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:386c8bf53c502fff58903061338ce4f4950cbdcb23e2902d86c0f722b786bbe3", size = 484568, upload-time = "2024-09-04T20:44:23.245Z" }, - { url = "https://files.pythonhosted.org/packages/d4/38/ca8a4f639065f14ae0f1d9751e70447a261f1a30fa7547a828ae08142465/cffi-1.17.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:4ceb10419a9adf4460ea14cfd6bc43d08701f0835e979bf821052f1805850fe8", size = 488736, upload-time = "2024-09-04T20:44:24.757Z" }, - { url = "https://files.pythonhosted.org/packages/86/c5/28b2d6f799ec0bdecf44dced2ec5ed43e0eb63097b0f58c293583b406582/cffi-1.17.1-cp312-cp312-win32.whl", hash = "sha256:a08d7e755f8ed21095a310a693525137cfe756ce62d066e53f502a83dc550f65", size = 172448, upload-time = "2024-09-04T20:44:26.208Z" }, - { url = "https://files.pythonhosted.org/packages/50/b9/db34c4755a7bd1cb2d1603ac3863f22bcecbd1ba29e5ee841a4bc510b294/cffi-1.17.1-cp312-cp312-win_amd64.whl", hash = "sha256:51392eae71afec0d0c8fb1a53b204dbb3bcabcb3c9b807eedf3e1e6ccf2de903", size = 181976, upload-time = "2024-09-04T20:44:27.578Z" }, - { url = "https://files.pythonhosted.org/packages/8d/f8/dd6c246b148639254dad4d6803eb6a54e8c85c6e11ec9df2cffa87571dbe/cffi-1.17.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:f3a2b4222ce6b60e2e8b337bb9596923045681d71e5a082783484d845390938e", size = 182989, upload-time = "2024-09-04T20:44:28.956Z" }, - { url = "https://files.pythonhosted.org/packages/8b/f1/672d303ddf17c24fc83afd712316fda78dc6fce1cd53011b839483e1ecc8/cffi-1.17.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0984a4925a435b1da406122d4d7968dd861c1385afe3b45ba82b750f229811e2", size = 178802, upload-time = "2024-09-04T20:44:30.289Z" }, - { url = "https://files.pythonhosted.org/packages/0e/2d/eab2e858a91fdff70533cab61dcff4a1f55ec60425832ddfdc9cd36bc8af/cffi-1.17.1-cp313-cp313-manylinux_2_12_i686.manylinux2010_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d01b12eeeb4427d3110de311e1774046ad344f5b1a7403101878976ecd7a10f3", size = 454792, upload-time = "2024-09-04T20:44:32.01Z" }, - { url = "https://files.pythonhosted.org/packages/75/b2/fbaec7c4455c604e29388d55599b99ebcc250a60050610fadde58932b7ee/cffi-1.17.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:706510fe141c86a69c8ddc029c7910003a17353970cff3b904ff0686a5927683", size = 478893, upload-time = "2024-09-04T20:44:33.606Z" }, - { url = "https://files.pythonhosted.org/packages/4f/b7/6e4a2162178bf1935c336d4da8a9352cccab4d3a5d7914065490f08c0690/cffi-1.17.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:de55b766c7aa2e2a3092c51e0483d700341182f08e67c63630d5b6f200bb28e5", size = 485810, upload-time = "2024-09-04T20:44:35.191Z" }, - { url = "https://files.pythonhosted.org/packages/c7/8a/1d0e4a9c26e54746dc08c2c6c037889124d4f59dffd853a659fa545f1b40/cffi-1.17.1-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:c59d6e989d07460165cc5ad3c61f9fd8f1b4796eacbd81cee78957842b834af4", size = 471200, upload-time = "2024-09-04T20:44:36.743Z" }, - { url = "https://files.pythonhosted.org/packages/26/9f/1aab65a6c0db35f43c4d1b4f580e8df53914310afc10ae0397d29d697af4/cffi-1.17.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dd398dbc6773384a17fe0d3e7eeb8d1a21c2200473ee6806bb5e6a8e62bb73dd", size = 479447, upload-time = "2024-09-04T20:44:38.492Z" }, - { url = "https://files.pythonhosted.org/packages/5f/e4/fb8b3dd8dc0e98edf1135ff067ae070bb32ef9d509d6cb0f538cd6f7483f/cffi-1.17.1-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:3edc8d958eb099c634dace3c7e16560ae474aa3803a5df240542b305d14e14ed", size = 484358, upload-time = "2024-09-04T20:44:40.046Z" }, - { url = "https://files.pythonhosted.org/packages/f1/47/d7145bf2dc04684935d57d67dff9d6d795b2ba2796806bb109864be3a151/cffi-1.17.1-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:72e72408cad3d5419375fc87d289076ee319835bdfa2caad331e377589aebba9", size = 488469, upload-time = "2024-09-04T20:44:41.616Z" }, - { url = "https://files.pythonhosted.org/packages/bf/ee/f94057fa6426481d663b88637a9a10e859e492c73d0384514a17d78ee205/cffi-1.17.1-cp313-cp313-win32.whl", hash = "sha256:e03eab0a8677fa80d646b5ddece1cbeaf556c313dcfac435ba11f107ba117b5d", size = 172475, upload-time = "2024-09-04T20:44:43.733Z" }, - { url = "https://files.pythonhosted.org/packages/7c/fc/6a8cb64e5f0324877d503c854da15d76c1e50eb722e320b15345c4d0c6de/cffi-1.17.1-cp313-cp313-win_amd64.whl", hash = "sha256:f6a16c31041f09ead72d69f583767292f750d24913dadacf5756b966aacb3f1a", size = 182009, upload-time = "2024-09-04T20:44:45.309Z" }, +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pycparser", marker = "implementation_name != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/eb/56/b1ba7935a17738ae8453301356628e8147c79dbb825bcbc73dc7401f9846/cffi-2.0.0.tar.gz", hash = "sha256:44d1b5909021139fe36001ae048dbdde8214afa20200eda0f64c068cac5d5529", size = 523588, upload-time = "2025-09-08T23:24:04.541Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/4a/3dfd5f7850cbf0d06dc84ba9aa00db766b52ca38d8b86e3a38314d52498c/cffi-2.0.0-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:b4c854ef3adc177950a8dfc81a86f5115d2abd545751a304c5bcf2c2c7283cfe", size = 184344, upload-time = "2025-09-08T23:22:26.456Z" }, + { url = "https://files.pythonhosted.org/packages/4f/8b/f0e4c441227ba756aafbe78f117485b25bb26b1c059d01f137fa6d14896b/cffi-2.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:2de9a304e27f7596cd03d16f1b7c72219bd944e99cc52b84d0145aefb07cbd3c", size = 180560, upload-time = "2025-09-08T23:22:28.197Z" }, + { url = "https://files.pythonhosted.org/packages/b1/b7/1200d354378ef52ec227395d95c2576330fd22a869f7a70e88e1447eb234/cffi-2.0.0-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:baf5215e0ab74c16e2dd324e8ec067ef59e41125d3eade2b863d294fd5035c92", size = 209613, upload-time = "2025-09-08T23:22:29.475Z" }, + { url = "https://files.pythonhosted.org/packages/b8/56/6033f5e86e8cc9bb629f0077ba71679508bdf54a9a5e112a3c0b91870332/cffi-2.0.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:730cacb21e1bdff3ce90babf007d0a0917cc3e6492f336c2f0134101e0944f93", size = 216476, upload-time = "2025-09-08T23:22:31.063Z" }, + { url = "https://files.pythonhosted.org/packages/dc/7f/55fecd70f7ece178db2f26128ec41430d8720f2d12ca97bf8f0a628207d5/cffi-2.0.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:6824f87845e3396029f3820c206e459ccc91760e8fa24422f8b0c3d1731cbec5", size = 203374, upload-time = "2025-09-08T23:22:32.507Z" }, + { url = "https://files.pythonhosted.org/packages/84/ef/a7b77c8bdc0f77adc3b46888f1ad54be8f3b7821697a7b89126e829e676a/cffi-2.0.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:9de40a7b0323d889cf8d23d1ef214f565ab154443c42737dfe52ff82cf857664", size = 202597, upload-time = "2025-09-08T23:22:34.132Z" }, + { url = "https://files.pythonhosted.org/packages/d7/91/500d892b2bf36529a75b77958edfcd5ad8e2ce4064ce2ecfeab2125d72d1/cffi-2.0.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8941aaadaf67246224cee8c3803777eed332a19d909b47e29c9842ef1e79ac26", size = 215574, upload-time = "2025-09-08T23:22:35.443Z" }, + { url = "https://files.pythonhosted.org/packages/44/64/58f6255b62b101093d5df22dcb752596066c7e89dd725e0afaed242a61be/cffi-2.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:a05d0c237b3349096d3981b727493e22147f934b20f6f125a3eba8f994bec4a9", size = 218971, upload-time = "2025-09-08T23:22:36.805Z" }, + { url = "https://files.pythonhosted.org/packages/ab/49/fa72cebe2fd8a55fbe14956f9970fe8eb1ac59e5df042f603ef7c8ba0adc/cffi-2.0.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:94698a9c5f91f9d138526b48fe26a199609544591f859c870d477351dc7b2414", size = 211972, upload-time = "2025-09-08T23:22:38.436Z" }, + { url = "https://files.pythonhosted.org/packages/0b/28/dd0967a76aab36731b6ebfe64dec4e981aff7e0608f60c2d46b46982607d/cffi-2.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:5fed36fccc0612a53f1d4d9a816b50a36702c28a2aa880cb8a122b3466638743", size = 217078, upload-time = "2025-09-08T23:22:39.776Z" }, + { url = "https://files.pythonhosted.org/packages/2b/c0/015b25184413d7ab0a410775fdb4a50fca20f5589b5dab1dbbfa3baad8ce/cffi-2.0.0-cp311-cp311-win32.whl", hash = "sha256:c649e3a33450ec82378822b3dad03cc228b8f5963c0c12fc3b1e0ab940f768a5", size = 172076, upload-time = "2025-09-08T23:22:40.95Z" }, + { url = "https://files.pythonhosted.org/packages/ae/8f/dc5531155e7070361eb1b7e4c1a9d896d0cb21c49f807a6c03fd63fc877e/cffi-2.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:66f011380d0e49ed280c789fbd08ff0d40968ee7b665575489afa95c98196ab5", size = 182820, upload-time = "2025-09-08T23:22:42.463Z" }, + { url = "https://files.pythonhosted.org/packages/95/5c/1b493356429f9aecfd56bc171285a4c4ac8697f76e9bbbbb105e537853a1/cffi-2.0.0-cp311-cp311-win_arm64.whl", hash = "sha256:c6638687455baf640e37344fe26d37c404db8b80d037c3d29f58fe8d1c3b194d", size = 177635, upload-time = "2025-09-08T23:22:43.623Z" }, + { url = "https://files.pythonhosted.org/packages/ea/47/4f61023ea636104d4f16ab488e268b93008c3d0bb76893b1b31db1f96802/cffi-2.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6d02d6655b0e54f54c4ef0b94eb6be0607b70853c45ce98bd278dc7de718be5d", size = 185271, upload-time = "2025-09-08T23:22:44.795Z" }, + { url = "https://files.pythonhosted.org/packages/df/a2/781b623f57358e360d62cdd7a8c681f074a71d445418a776eef0aadb4ab4/cffi-2.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8eca2a813c1cb7ad4fb74d368c2ffbbb4789d377ee5bb8df98373c2cc0dee76c", size = 181048, upload-time = "2025-09-08T23:22:45.938Z" }, + { url = "https://files.pythonhosted.org/packages/ff/df/a4f0fbd47331ceeba3d37c2e51e9dfc9722498becbeec2bd8bc856c9538a/cffi-2.0.0-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:21d1152871b019407d8ac3985f6775c079416c282e431a4da6afe7aefd2bccbe", size = 212529, upload-time = "2025-09-08T23:22:47.349Z" }, + { url = "https://files.pythonhosted.org/packages/d5/72/12b5f8d3865bf0f87cf1404d8c374e7487dcf097a1c91c436e72e6badd83/cffi-2.0.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b21e08af67b8a103c71a250401c78d5e0893beff75e28c53c98f4de42f774062", size = 220097, upload-time = "2025-09-08T23:22:48.677Z" }, + { url = "https://files.pythonhosted.org/packages/c2/95/7a135d52a50dfa7c882ab0ac17e8dc11cec9d55d2c18dda414c051c5e69e/cffi-2.0.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:1e3a615586f05fc4065a8b22b8152f0c1b00cdbc60596d187c2a74f9e3036e4e", size = 207983, upload-time = "2025-09-08T23:22:50.06Z" }, + { url = "https://files.pythonhosted.org/packages/3a/c8/15cb9ada8895957ea171c62dc78ff3e99159ee7adb13c0123c001a2546c1/cffi-2.0.0-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:81afed14892743bbe14dacb9e36d9e0e504cd204e0b165062c488942b9718037", size = 206519, upload-time = "2025-09-08T23:22:51.364Z" }, + { url = "https://files.pythonhosted.org/packages/78/2d/7fa73dfa841b5ac06c7b8855cfc18622132e365f5b81d02230333ff26e9e/cffi-2.0.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3e17ed538242334bf70832644a32a7aae3d83b57567f9fd60a26257e992b79ba", size = 219572, upload-time = "2025-09-08T23:22:52.902Z" }, + { url = "https://files.pythonhosted.org/packages/07/e0/267e57e387b4ca276b90f0434ff88b2c2241ad72b16d31836adddfd6031b/cffi-2.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3925dd22fa2b7699ed2617149842d2e6adde22b262fcbfada50e3d195e4b3a94", size = 222963, upload-time = "2025-09-08T23:22:54.518Z" }, + { url = "https://files.pythonhosted.org/packages/b6/75/1f2747525e06f53efbd878f4d03bac5b859cbc11c633d0fb81432d98a795/cffi-2.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:2c8f814d84194c9ea681642fd164267891702542f028a15fc97d4674b6206187", size = 221361, upload-time = "2025-09-08T23:22:55.867Z" }, + { url = "https://files.pythonhosted.org/packages/7b/2b/2b6435f76bfeb6bbf055596976da087377ede68df465419d192acf00c437/cffi-2.0.0-cp312-cp312-win32.whl", hash = "sha256:da902562c3e9c550df360bfa53c035b2f241fed6d9aef119048073680ace4a18", size = 172932, upload-time = "2025-09-08T23:22:57.188Z" }, + { url = "https://files.pythonhosted.org/packages/f8/ed/13bd4418627013bec4ed6e54283b1959cf6db888048c7cf4b4c3b5b36002/cffi-2.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:da68248800ad6320861f129cd9c1bf96ca849a2771a59e0344e88681905916f5", size = 183557, upload-time = "2025-09-08T23:22:58.351Z" }, + { url = "https://files.pythonhosted.org/packages/95/31/9f7f93ad2f8eff1dbc1c3656d7ca5bfd8fb52c9d786b4dcf19b2d02217fa/cffi-2.0.0-cp312-cp312-win_arm64.whl", hash = "sha256:4671d9dd5ec934cb9a73e7ee9676f9362aba54f7f34910956b84d727b0d73fb6", size = 177762, upload-time = "2025-09-08T23:22:59.668Z" }, + { url = "https://files.pythonhosted.org/packages/4b/8d/a0a47a0c9e413a658623d014e91e74a50cdd2c423f7ccfd44086ef767f90/cffi-2.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:00bdf7acc5f795150faa6957054fbbca2439db2f775ce831222b66f192f03beb", size = 185230, upload-time = "2025-09-08T23:23:00.879Z" }, + { url = "https://files.pythonhosted.org/packages/4a/d2/a6c0296814556c68ee32009d9c2ad4f85f2707cdecfd7727951ec228005d/cffi-2.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:45d5e886156860dc35862657e1494b9bae8dfa63bf56796f2fb56e1679fc0bca", size = 181043, upload-time = "2025-09-08T23:23:02.231Z" }, + { url = "https://files.pythonhosted.org/packages/b0/1e/d22cc63332bd59b06481ceaac49d6c507598642e2230f201649058a7e704/cffi-2.0.0-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:07b271772c100085dd28b74fa0cd81c8fb1a3ba18b21e03d7c27f3436a10606b", size = 212446, upload-time = "2025-09-08T23:23:03.472Z" }, + { url = "https://files.pythonhosted.org/packages/a9/f5/a2c23eb03b61a0b8747f211eb716446c826ad66818ddc7810cc2cc19b3f2/cffi-2.0.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d48a880098c96020b02d5a1f7d9251308510ce8858940e6fa99ece33f610838b", size = 220101, upload-time = "2025-09-08T23:23:04.792Z" }, + { url = "https://files.pythonhosted.org/packages/f2/7f/e6647792fc5850d634695bc0e6ab4111ae88e89981d35ac269956605feba/cffi-2.0.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:f93fd8e5c8c0a4aa1f424d6173f14a892044054871c771f8566e4008eaa359d2", size = 207948, upload-time = "2025-09-08T23:23:06.127Z" }, + { url = "https://files.pythonhosted.org/packages/cb/1e/a5a1bd6f1fb30f22573f76533de12a00bf274abcdc55c8edab639078abb6/cffi-2.0.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:dd4f05f54a52fb558f1ba9f528228066954fee3ebe629fc1660d874d040ae5a3", size = 206422, upload-time = "2025-09-08T23:23:07.753Z" }, + { url = "https://files.pythonhosted.org/packages/98/df/0a1755e750013a2081e863e7cd37e0cdd02664372c754e5560099eb7aa44/cffi-2.0.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c8d3b5532fc71b7a77c09192b4a5a200ea992702734a2e9279a37f2478236f26", size = 219499, upload-time = "2025-09-08T23:23:09.648Z" }, + { url = "https://files.pythonhosted.org/packages/50/e1/a969e687fcf9ea58e6e2a928ad5e2dd88cc12f6f0ab477e9971f2309b57c/cffi-2.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d9b29c1f0ae438d5ee9acb31cadee00a58c46cc9c0b2f9038c6b0b3470877a8c", size = 222928, upload-time = "2025-09-08T23:23:10.928Z" }, + { url = "https://files.pythonhosted.org/packages/36/54/0362578dd2c9e557a28ac77698ed67323ed5b9775ca9d3fe73fe191bb5d8/cffi-2.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6d50360be4546678fc1b79ffe7a66265e28667840010348dd69a314145807a1b", size = 221302, upload-time = "2025-09-08T23:23:12.42Z" }, + { url = "https://files.pythonhosted.org/packages/eb/6d/bf9bda840d5f1dfdbf0feca87fbdb64a918a69bca42cfa0ba7b137c48cb8/cffi-2.0.0-cp313-cp313-win32.whl", hash = "sha256:74a03b9698e198d47562765773b4a8309919089150a0bb17d829ad7b44b60d27", size = 172909, upload-time = "2025-09-08T23:23:14.32Z" }, + { url = "https://files.pythonhosted.org/packages/37/18/6519e1ee6f5a1e579e04b9ddb6f1676c17368a7aba48299c3759bbc3c8b3/cffi-2.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:19f705ada2530c1167abacb171925dd886168931e0a7b78f5bffcae5c6b5be75", size = 183402, upload-time = "2025-09-08T23:23:15.535Z" }, + { url = "https://files.pythonhosted.org/packages/cb/0e/02ceeec9a7d6ee63bb596121c2c8e9b3a9e150936f4fbef6ca1943e6137c/cffi-2.0.0-cp313-cp313-win_arm64.whl", hash = "sha256:256f80b80ca3853f90c21b23ee78cd008713787b1b1e93eae9f3d6a7134abd91", size = 177780, upload-time = "2025-09-08T23:23:16.761Z" }, + { url = "https://files.pythonhosted.org/packages/92/c4/3ce07396253a83250ee98564f8d7e9789fab8e58858f35d07a9a2c78de9f/cffi-2.0.0-cp314-cp314-macosx_10_13_x86_64.whl", hash = "sha256:fc33c5141b55ed366cfaad382df24fe7dcbc686de5be719b207bb248e3053dc5", size = 185320, upload-time = "2025-09-08T23:23:18.087Z" }, + { url = "https://files.pythonhosted.org/packages/59/dd/27e9fa567a23931c838c6b02d0764611c62290062a6d4e8ff7863daf9730/cffi-2.0.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c654de545946e0db659b3400168c9ad31b5d29593291482c43e3564effbcee13", size = 181487, upload-time = "2025-09-08T23:23:19.622Z" }, + { url = "https://files.pythonhosted.org/packages/d6/43/0e822876f87ea8a4ef95442c3d766a06a51fc5298823f884ef87aaad168c/cffi-2.0.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:24b6f81f1983e6df8db3adc38562c83f7d4a0c36162885ec7f7b77c7dcbec97b", size = 220049, upload-time = "2025-09-08T23:23:20.853Z" }, + { url = "https://files.pythonhosted.org/packages/b4/89/76799151d9c2d2d1ead63c2429da9ea9d7aac304603de0c6e8764e6e8e70/cffi-2.0.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:12873ca6cb9b0f0d3a0da705d6086fe911591737a59f28b7936bdfed27c0d47c", size = 207793, upload-time = "2025-09-08T23:23:22.08Z" }, + { url = "https://files.pythonhosted.org/packages/bb/dd/3465b14bb9e24ee24cb88c9e3730f6de63111fffe513492bf8c808a3547e/cffi-2.0.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:d9b97165e8aed9272a6bb17c01e3cc5871a594a446ebedc996e2397a1c1ea8ef", size = 206300, upload-time = "2025-09-08T23:23:23.314Z" }, + { url = "https://files.pythonhosted.org/packages/47/d9/d83e293854571c877a92da46fdec39158f8d7e68da75bf73581225d28e90/cffi-2.0.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:afb8db5439b81cf9c9d0c80404b60c3cc9c3add93e114dcae767f1477cb53775", size = 219244, upload-time = "2025-09-08T23:23:24.541Z" }, + { url = "https://files.pythonhosted.org/packages/2b/0f/1f177e3683aead2bb00f7679a16451d302c436b5cbf2505f0ea8146ef59e/cffi-2.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:737fe7d37e1a1bffe70bd5754ea763a62a066dc5913ca57e957824b72a85e205", size = 222828, upload-time = "2025-09-08T23:23:26.143Z" }, + { url = "https://files.pythonhosted.org/packages/c6/0f/cafacebd4b040e3119dcb32fed8bdef8dfe94da653155f9d0b9dc660166e/cffi-2.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:38100abb9d1b1435bc4cc340bb4489635dc2f0da7456590877030c9b3d40b0c1", size = 220926, upload-time = "2025-09-08T23:23:27.873Z" }, + { url = "https://files.pythonhosted.org/packages/3e/aa/df335faa45b395396fcbc03de2dfcab242cd61a9900e914fe682a59170b1/cffi-2.0.0-cp314-cp314-win32.whl", hash = "sha256:087067fa8953339c723661eda6b54bc98c5625757ea62e95eb4898ad5e776e9f", size = 175328, upload-time = "2025-09-08T23:23:44.61Z" }, + { url = "https://files.pythonhosted.org/packages/bb/92/882c2d30831744296ce713f0feb4c1cd30f346ef747b530b5318715cc367/cffi-2.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:203a48d1fb583fc7d78a4c6655692963b860a417c0528492a6bc21f1aaefab25", size = 185650, upload-time = "2025-09-08T23:23:45.848Z" }, + { url = "https://files.pythonhosted.org/packages/9f/2c/98ece204b9d35a7366b5b2c6539c350313ca13932143e79dc133ba757104/cffi-2.0.0-cp314-cp314-win_arm64.whl", hash = "sha256:dbd5c7a25a7cb98f5ca55d258b103a2054f859a46ae11aaf23134f9cc0d356ad", size = 180687, upload-time = "2025-09-08T23:23:47.105Z" }, + { url = "https://files.pythonhosted.org/packages/3e/61/c768e4d548bfa607abcda77423448df8c471f25dbe64fb2ef6d555eae006/cffi-2.0.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:9a67fc9e8eb39039280526379fb3a70023d77caec1852002b4da7e8b270c4dd9", size = 188773, upload-time = "2025-09-08T23:23:29.347Z" }, + { url = "https://files.pythonhosted.org/packages/2c/ea/5f76bce7cf6fcd0ab1a1058b5af899bfbef198bea4d5686da88471ea0336/cffi-2.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7a66c7204d8869299919db4d5069a82f1561581af12b11b3c9f48c584eb8743d", size = 185013, upload-time = "2025-09-08T23:23:30.63Z" }, + { url = "https://files.pythonhosted.org/packages/be/b4/c56878d0d1755cf9caa54ba71e5d049479c52f9e4afc230f06822162ab2f/cffi-2.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:7cc09976e8b56f8cebd752f7113ad07752461f48a58cbba644139015ac24954c", size = 221593, upload-time = "2025-09-08T23:23:31.91Z" }, + { url = "https://files.pythonhosted.org/packages/e0/0d/eb704606dfe8033e7128df5e90fee946bbcb64a04fcdaa97321309004000/cffi-2.0.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:92b68146a71df78564e4ef48af17551a5ddd142e5190cdf2c5624d0c3ff5b2e8", size = 209354, upload-time = "2025-09-08T23:23:33.214Z" }, + { url = "https://files.pythonhosted.org/packages/d8/19/3c435d727b368ca475fb8742ab97c9cb13a0de600ce86f62eab7fa3eea60/cffi-2.0.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:b1e74d11748e7e98e2f426ab176d4ed720a64412b6a15054378afdb71e0f37dc", size = 208480, upload-time = "2025-09-08T23:23:34.495Z" }, + { url = "https://files.pythonhosted.org/packages/d0/44/681604464ed9541673e486521497406fadcc15b5217c3e326b061696899a/cffi-2.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:28a3a209b96630bca57cce802da70c266eb08c6e97e5afd61a75611ee6c64592", size = 221584, upload-time = "2025-09-08T23:23:36.096Z" }, + { url = "https://files.pythonhosted.org/packages/25/8e/342a504ff018a2825d395d44d63a767dd8ebc927ebda557fecdaca3ac33a/cffi-2.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:7553fb2090d71822f02c629afe6042c299edf91ba1bf94951165613553984512", size = 224443, upload-time = "2025-09-08T23:23:37.328Z" }, + { url = "https://files.pythonhosted.org/packages/e1/5e/b666bacbbc60fbf415ba9988324a132c9a7a0448a9a8f125074671c0f2c3/cffi-2.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:6c6c373cfc5c83a975506110d17457138c8c63016b563cc9ed6e056a82f13ce4", size = 223437, upload-time = "2025-09-08T23:23:38.945Z" }, + { url = "https://files.pythonhosted.org/packages/a0/1d/ec1a60bd1a10daa292d3cd6bb0b359a81607154fb8165f3ec95fe003b85c/cffi-2.0.0-cp314-cp314t-win32.whl", hash = "sha256:1fc9ea04857caf665289b7a75923f2c6ed559b8298a1b8c49e59f7dd95c8481e", size = 180487, upload-time = "2025-09-08T23:23:40.423Z" }, + { url = "https://files.pythonhosted.org/packages/bf/41/4c1168c74fac325c0c8156f04b6749c8b6a8f405bbf91413ba088359f60d/cffi-2.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:d68b6cef7827e8641e8ef16f4494edda8b36104d79773a334beaa1e3521430f6", size = 191726, upload-time = "2025-09-08T23:23:41.742Z" }, + { url = "https://files.pythonhosted.org/packages/ae/3a/dbeec9d1ee0844c679f6bb5d6ad4e9f198b1224f4e7a32825f47f6192b0c/cffi-2.0.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0a1527a803f0a659de1af2e1fd700213caba79377e27e4693648c2923da066f9", size = 184195, upload-time = "2025-09-08T23:23:43.004Z" }, ] [[package]] @@ -751,6 +776,65 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8a/3c/1a983b9a745d7f83d53f057bcc5bf79ba6a2bbc08266b3f0c7d6fe630c9b/coverage-7.14.1-py3-none-any.whl", hash = "sha256:a252f21c27e38347e60111a3266b03827422a7d5525951aceee313aa68bab1d2", size = 211815, upload-time = "2026-05-26T20:41:34.078Z" }, ] +[[package]] +name = "cryptography" +version = "48.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi", marker = "platform_python_implementation != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9f/a9/db8f313fdcd85d767d4973515e1db101f9c71f95fced83233de224673757/cryptography-48.0.0.tar.gz", hash = "sha256:5c3932f4436d1cccb036cb0eaef46e6e2db91035166f1ad6505c3c9d5a635920", size = 832984, upload-time = "2026-05-04T22:59:38.133Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/3d/01f6dd9190170a5a241e0e98c2d04be3664a9e6f5b9b872cde63aff1c3dd/cryptography-48.0.0-cp311-abi3-macosx_10_9_universal2.whl", hash = "sha256:0c558d2cdffd8f4bbb30fc7134c74d2ca9a476f830bb053074498fbc86f41ed6", size = 8001587, upload-time = "2026-05-04T22:57:36.803Z" }, + { url = "https://files.pythonhosted.org/packages/b2/6e/e90527eef33f309beb811cf7c982c3aeffcce8e3edb178baa4ca3ae4a6fa/cryptography-48.0.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f5333311663ea94f75dd408665686aaf426563556bb5283554a3539177e03b8c", size = 4690433, upload-time = "2026-05-04T22:57:40.373Z" }, + { url = "https://files.pythonhosted.org/packages/90/04/673510ed51ddff56575f306cf1617d80411ee76831ccd3097599140efdfe/cryptography-48.0.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7995ef305d7165c3f11ae07f2517e5a4f1d5c18da1376a0a9ed496336b69e5f3", size = 4710620, upload-time = "2026-05-04T22:57:42.935Z" }, + { url = "https://files.pythonhosted.org/packages/14/d5/e9c4ef932c8d800490c34d8bd589d64a31d5890e27ec9e9ad532be893294/cryptography-48.0.0-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:40ba1f85eaa6959837b1d51c9767e230e14612eea4ef110ee8854ada22da1bf5", size = 4696283, upload-time = "2026-05-04T22:57:45.294Z" }, + { url = "https://files.pythonhosted.org/packages/0c/29/174b9dfb60b12d59ecfc6cfa04bc88c21b42a54f01b8aae09bb6e51e4c7f/cryptography-48.0.0-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:369a6348999f94bbd53435c894377b20ab95f25a9065c283570e70150d8abc3c", size = 5296573, upload-time = "2026-05-04T22:57:47.933Z" }, + { url = "https://files.pythonhosted.org/packages/95/38/0d29a6fd7d0d1373f0c0c88a04ba20e359b257753ac497564cd660fc1d55/cryptography-48.0.0-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:a0e692c683f4df67815a2d258b324e66f4738bd7a96a218c826dce4f4bd05d8f", size = 4743677, upload-time = "2026-05-04T22:57:50.067Z" }, + { url = "https://files.pythonhosted.org/packages/30/be/eef653013d5c63b6a490529e0316f9ac14a37602965d4903efed1399f32b/cryptography-48.0.0-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:18349bbc56f4743c8b12dc32e2bccb2cf83ee8b69a3bba74ef8ae857e26b3d25", size = 4330808, upload-time = "2026-05-04T22:57:52.301Z" }, + { url = "https://files.pythonhosted.org/packages/84/9e/500463e87abb7a0a0f9f256ec21123ecde0a7b5541a15e840ea54551fd81/cryptography-48.0.0-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:7e8eac43dfca5c4cccc6dad9a80504436fca53bb9bc3100a2386d730fbe6b602", size = 4695941, upload-time = "2026-05-04T22:57:54.603Z" }, + { url = "https://files.pythonhosted.org/packages/e3/dc/7303087450c2ec9e7fbb750e17c2abfbc658f23cbd0e54009509b7cc4091/cryptography-48.0.0-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:9ccdac7d40688ecb5a3b4a604b8a88c8002e3442d6c60aead1db2a89a041560c", size = 5252579, upload-time = "2026-05-04T22:57:57.207Z" }, + { url = "https://files.pythonhosted.org/packages/d0/c0/7101d3b7215edcdc90c45da544961fd8ed2d6448f77577460fa75a8443f7/cryptography-48.0.0-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:bd72e68b06bb1e96913f97dd4901119bc17f39d4586a5adf2d3e47bc2b9d58b5", size = 4743326, upload-time = "2026-05-04T22:57:59.535Z" }, + { url = "https://files.pythonhosted.org/packages/ac/d8/5b833bad13016f562ab9d063d68199a4bd121d18458e439515601d3357ec/cryptography-48.0.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:59baa2cb386c4f0b9905bd6eb4c2a79a69a128408fd31d32ca4d7102d4156321", size = 4826672, upload-time = "2026-05-04T22:58:01.996Z" }, + { url = "https://files.pythonhosted.org/packages/98/e1/7074eb8bf3c135558c73fc2bcf0f5633f912e6fb87e868a55c454080ef09/cryptography-48.0.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9249e3cd978541d665967ac2cb2787fd6a62bddf1e75b3e347a594d7dacf4f74", size = 4972574, upload-time = "2026-05-04T22:58:03.968Z" }, + { url = "https://files.pythonhosted.org/packages/04/70/e5a1b41d325f797f39427aa44ef8baf0be500065ab6d8e10369d850d4a4f/cryptography-48.0.0-cp311-abi3-win32.whl", hash = "sha256:9c459db21422be75e2809370b829a87eb37f74cd785fc4aa9ea1e5f43b47cda4", size = 3294868, upload-time = "2026-05-04T22:58:06.467Z" }, + { url = "https://files.pythonhosted.org/packages/f4/ac/8ac51b4a5fc5932eb7ee5c517ba7dc8cd834f0048962b6b352f00f41ebf9/cryptography-48.0.0-cp311-abi3-win_amd64.whl", hash = "sha256:5b012212e08b8dd5edc78ef54da83dd9892fd9105323b3993eff6bea65dc21d7", size = 3817107, upload-time = "2026-05-04T22:58:08.845Z" }, + { url = "https://files.pythonhosted.org/packages/6b/84/70e3feea9feea87fd7cbe77efb2712ae1e3e6edf10749dc6e95f4e60e455/cryptography-48.0.0-cp314-cp314t-macosx_10_9_universal2.whl", hash = "sha256:3cb07a3ed6431663cd321ea8a000a1314c74211f823e4177fefa2255e057d1ec", size = 7986556, upload-time = "2026-05-04T22:58:11.172Z" }, + { url = "https://files.pythonhosted.org/packages/89/6e/18e07a618bb5442ba10cf4df16e99c071365528aa570dfcb8c02e25a303b/cryptography-48.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:8c7378637d7d88016fa6791c159f698b3d3eed28ebf844ac36b9dc04a14dae18", size = 4684776, upload-time = "2026-05-04T22:58:13.712Z" }, + { url = "https://files.pythonhosted.org/packages/be/6a/4ea3b4c6c6759794d5ee2103c304a5076dc4b19ae1f9fe47dba439e159e9/cryptography-48.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:cc90c0b39b2e3c65ef52c804b72e3c58f8a04ab2a1871272798e5f9572c17d20", size = 4698121, upload-time = "2026-05-04T22:58:16.448Z" }, + { url = "https://files.pythonhosted.org/packages/2f/59/6ff6ad6cae03bb887da2a5860b2c9805f8dac969ef01ce563336c49bd1d1/cryptography-48.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:76341972e1eff8b4bea859f09c0d3e64b96ce931b084f9b9b7db8ef364c30eff", size = 4690042, upload-time = "2026-05-04T22:58:18.544Z" }, + { url = "https://files.pythonhosted.org/packages/ca/b4/fc334ed8cfd705aca282fe4d8f5ae64a8e0f74932e9feecb344610cf6e4d/cryptography-48.0.0-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:55b7718303bf06a5753dcdccf2f3945cf18ad7bffde41b61226e4db31ab89a9c", size = 5282526, upload-time = "2026-05-04T22:58:20.75Z" }, + { url = "https://files.pythonhosted.org/packages/11/08/9f8c5386cc4cd90d8255c7cdd0f5baf459a08502a09de30dc51f553d38dc/cryptography-48.0.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:a64697c641c7b1b2178e573cbc31c7c6684cd56883a478d75143dbb7118036db", size = 4733116, upload-time = "2026-05-04T22:58:23.627Z" }, + { url = "https://files.pythonhosted.org/packages/b8/77/99307d7574045699f8805aa500fa0fb83422d115b5400a064ddd306d7750/cryptography-48.0.0-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:561215ea3879cb1cbbf272867e2efda62476f240fb58c64de6b393ae19246741", size = 4316030, upload-time = "2026-05-04T22:58:25.581Z" }, + { url = "https://files.pythonhosted.org/packages/fd/36/a608b98337af3cb2aff4818e406649d30572b7031918b04c87d979495348/cryptography-48.0.0-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:ad64688338ed4bc1a6618076ba75fd7194a5f1797ac60b47afe926285adb3166", size = 4689640, upload-time = "2026-05-04T22:58:27.747Z" }, + { url = "https://files.pythonhosted.org/packages/dd/a6/825010a291b4438aecc1f568bc428189fc1175515223632477c07dc0a6df/cryptography-48.0.0-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:906cbf0670286c6e0044156bc7d4af9cbb0ef6db9f73e52c3ec56ba6bdde5336", size = 5237657, upload-time = "2026-05-04T22:58:29.848Z" }, + { url = "https://files.pythonhosted.org/packages/b9/09/4e76a09b4caa29aad535ddc806f5d4c5d01885bd978bd984fbc6ca032cae/cryptography-48.0.0-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:ea8990436d914540a40ab24b6a77c0969695ed52f4a4874c5137ccf7045a7057", size = 4732362, upload-time = "2026-05-04T22:58:32.009Z" }, + { url = "https://files.pythonhosted.org/packages/18/78/444fa04a77d0cb95f417dda20d450e13c56ba8e5220fc892a1658f44f882/cryptography-48.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:c18684a7f0cc9a3cb60328f496b8e3372def7c5d2df39ac267878b05565aaaae", size = 4819580, upload-time = "2026-05-04T22:58:34.254Z" }, + { url = "https://files.pythonhosted.org/packages/38/85/ea67067c70a1fd4be2c63d35eeed82658023021affccc7b17705f8527dd2/cryptography-48.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:9be5aafa5736574f8f15f262adc81b2a9869e2cfe9014d52a44633905b40d52c", size = 4963283, upload-time = "2026-05-04T22:58:36.376Z" }, + { url = "https://files.pythonhosted.org/packages/75/54/cc6d0f3deac3e81c7f847e8a189a12b6cdd65059b43dad25d4316abd849a/cryptography-48.0.0-cp314-cp314t-win32.whl", hash = "sha256:c17dfe85494deaeddc5ce251aebd1d60bbe6afc8b62071bb0b469431a000124f", size = 3270954, upload-time = "2026-05-04T22:58:38.791Z" }, + { url = "https://files.pythonhosted.org/packages/49/67/cc947e288c0758a4e5473d1dcb743037ab7785541265a969240b8885441a/cryptography-48.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:27241b1dc9962e056062a8eef1991d02c3a24569c95975bd2322a8a52c6e5e12", size = 3797313, upload-time = "2026-05-04T22:58:40.746Z" }, + { url = "https://files.pythonhosted.org/packages/f2/63/61d4a4e1c6b6bab6ce1e213cd36a24c415d90e76d78c5eb8577c5541d2e8/cryptography-48.0.0-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:58d00498e8933e4a194f3076aee1b4a97dfec1a6da444535755822fe5d8b0b86", size = 7983482, upload-time = "2026-05-04T22:58:43.769Z" }, + { url = "https://files.pythonhosted.org/packages/d5/ac/f5b5995b87770c693e2596559ffafe195b4033a57f14a82268a2842953f3/cryptography-48.0.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:614d0949f4790582d2cc25553abd09dd723025f0c0e7c67376a1d77196743d6e", size = 4683266, upload-time = "2026-05-04T22:58:46.064Z" }, + { url = "https://files.pythonhosted.org/packages/ec/c6/8b14f67e18338fbc4adb76f66c001f5c3610b3e2d1837f268f47a347dbbb/cryptography-48.0.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7ce4bfae76319a532a2dc68f82cc32f5676ee792a983187dac07183690e5c66f", size = 4696228, upload-time = "2026-05-04T22:58:48.22Z" }, + { url = "https://files.pythonhosted.org/packages/ea/73/f808fbae9514bd91b47875b003f13e284c8c6bdfd904b7944e803937eec1/cryptography-48.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:2eb992bbd4661238c5a397594c83f5b4dc2bc5b848c365c8f991b6780efcc5c7", size = 4689097, upload-time = "2026-05-04T22:58:50.9Z" }, + { url = "https://files.pythonhosted.org/packages/93/01/d86632d7d28db8ae83221995752eeb6639ffb374c2d22955648cf8d52797/cryptography-48.0.0-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:22a5cb272895dce158b2cacdfdc3debd299019659f42947dbdac6f32d68fe832", size = 5283582, upload-time = "2026-05-04T22:58:53.017Z" }, + { url = "https://files.pythonhosted.org/packages/02/e1/50edc7a50334807cc4791fc4a0ce7468b4a1416d9138eab358bfc9a3d70b/cryptography-48.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:2b4d59804e8408e2fea7d1fbaf218e5ec984325221db76e6a241a9abd6cdd95c", size = 4730479, upload-time = "2026-05-04T22:58:55.611Z" }, + { url = "https://files.pythonhosted.org/packages/6f/af/99a582b1b1641ff5911ac559beb45097cf79efd4ead4657f578ef1af2d47/cryptography-48.0.0-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:984a20b0f62a26f48a3396c72e4bc34c66e356d356bf370053066b3b6d54634a", size = 4326481, upload-time = "2026-05-04T22:58:57.607Z" }, + { url = "https://files.pythonhosted.org/packages/90/ee/89aa26a06ef0a7d7611788ffd571a7c50e368cc6a4d5eef8b4884e866edb/cryptography-48.0.0-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:5a5ed8fde7a1d09376ca0b40e68cd59c69fe23b1f9768bd5824f54681626032a", size = 4688713, upload-time = "2026-05-04T22:59:00.077Z" }, + { url = "https://files.pythonhosted.org/packages/70/ba/bcb1b0bb7a33d4c7c0c4d4c7874b4a62ae4f56113a5f4baefa362dfb1f0f/cryptography-48.0.0-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:8cd666227ef7af430aa5914a9910e0ddd703e75f039cef0825cd0da71b6b711a", size = 5238165, upload-time = "2026-05-04T22:59:02.317Z" }, + { url = "https://files.pythonhosted.org/packages/c9/70/ca4003b1ce5ca3dc3186ada51908c8a9b9ff7d5cab83cc0d43ee14ec144f/cryptography-48.0.0-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:9071196d81abc88b3516ac8cdfad32e2b66dd4a5393a8e68a961e9161ddc6239", size = 4729947, upload-time = "2026-05-04T22:59:05.255Z" }, + { url = "https://files.pythonhosted.org/packages/44/a0/4ec7cf774207905aef1a8d11c3750d5a1db805eb380ee4e16df317870128/cryptography-48.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1e2d54c8be6152856a36f0882ab231e70f8ec7f14e93cf87db8a2ed056bf160c", size = 4822059, upload-time = "2026-05-04T22:59:07.802Z" }, + { url = "https://files.pythonhosted.org/packages/1e/75/a2e55f99c16fcac7b5d6c1eb19ad8e00799854d6be5ca845f9259eae1681/cryptography-48.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:a5da777e32ffed6f85a7b2b3f7c5cbc88c146bfcd0a1d7baf5fcc6c52ee35dd4", size = 4960575, upload-time = "2026-05-04T22:59:09.851Z" }, + { url = "https://files.pythonhosted.org/packages/b8/23/6e6f32143ab5d8b36ca848a502c4bcd477ae75b9e1677e3530d669062578/cryptography-48.0.0-cp39-abi3-win32.whl", hash = "sha256:77a2ccbbe917f6710e05ba9adaa25fb5075620bf3ea6fb751997875aff4ae4bd", size = 3279117, upload-time = "2026-05-04T22:59:12.019Z" }, + { url = "https://files.pythonhosted.org/packages/9d/9a/0fea98a70cf1749d41d738836f6349d97945f7c89433a259a6c2642eefeb/cryptography-48.0.0-cp39-abi3-win_amd64.whl", hash = "sha256:16cd65b9330583e4619939b3a3843eec1e6e789744bb01e7c7e2e62e33c239c8", size = 3792100, upload-time = "2026-05-04T22:59:14.884Z" }, + { url = "https://files.pythonhosted.org/packages/be/d2/024b5e06be9d44cb021fb0e1a03d34d63989cf56a0fe62f3dfbab695b9b4/cryptography-48.0.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:84cf79f0dc8b36ac5da873481716e87aef31fcfa0444f9e1d8b4b2cece142855", size = 3950391, upload-time = "2026-05-04T22:59:17.415Z" }, + { url = "https://files.pythonhosted.org/packages/bc/17/3861e17c56fa0fd37491a14a8673fdb77c57fc5693cafe745ea8b06dba75/cryptography-48.0.0-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:fdfef35d751d510fcef5252703621574364fec16418c4a1e5e1055248401054b", size = 4637126, upload-time = "2026-05-04T22:59:20.197Z" }, + { url = "https://files.pythonhosted.org/packages/f0/0a/7e226dbff530f21480727eb764973a7bff2b912f8e15cd4f129e71b56d1d/cryptography-48.0.0-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:0890f502ddf7d9c6426129c3f49f5c0a39278ed7cd6322c8755ffca6ee675a13", size = 4667270, upload-time = "2026-05-04T22:59:22.647Z" }, + { url = "https://files.pythonhosted.org/packages/3b/f2/5a72274ca9f1b2a8b44a662ee0bf1b435909deb473d6f97bcd035bcdbc71/cryptography-48.0.0-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:ecde28a596bead48b0cfd2a1b4416c3d43074c2d785e3a398d7ec1fc4d0f7fbb", size = 4636797, upload-time = "2026-05-04T22:59:24.912Z" }, + { url = "https://files.pythonhosted.org/packages/b4/e1/48cedb2fe63626e91ded1edad159e2a4fb8b6906c4425eb7749673077ce7/cryptography-48.0.0-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:4defde8685ae324a9eb9d818717e93b4638ef67070ac9bc15b8ca85f63048355", size = 4666800, upload-time = "2026-05-04T22:59:27.474Z" }, + { url = "https://files.pythonhosted.org/packages/a2/ca/7e8365deec19afb2b2c7be7c1c0aa8f99633b54e90c570999acda93260fc/cryptography-48.0.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:db63bf618e5dea46c07de12e900fe1cdd2541e6dc9dbae772a70b7d4d4765f6a", size = 3739536, upload-time = "2026-05-04T22:59:29.61Z" }, +] + [[package]] name = "cyclonedx-python-lib" version = "11.8.0" @@ -1228,6 +1312,7 @@ dependencies = [ { name = "anthropic" }, { name = "bcrypt" }, { name = "beautifulsoup4" }, + { name = "cryptography" }, { name = "fastapi" }, { name = "fpdf2" }, { name = "langchain" }, @@ -1281,6 +1366,7 @@ requires-dist = [ { name = "beautifulsoup4", specifier = ">=4.13.3" }, { name = "celery", marker = "extra == 'worker'", specifier = ">=5.3.0" }, { name = "coverage", marker = "extra == 'dev'", specifier = ">=7.5" }, + { name = "cryptography", specifier = ">=41.0.0" }, { name = "ddgs", marker = "extra == 'research'", specifier = ">=6.0" }, { name = "fastapi", specifier = ">=0.110.0" }, { name = "fpdf2", specifier = ">=2.8.7" }, From f3bd01f82e25da0e55e7207e2534f50e3e5f1a63 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 7 Jun 2026 19:50:24 +0000 Subject: [PATCH 13/24] =?UTF-8?q?P1=20#7:=20LLM=20cost=20controls=20?= =?UTF-8?q?=E2=80=94=20token=20accounting,=20budgets,=20completion=20cache?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the request-count-only quota with real spend accounting: - services/usage.py: ledger every real completion's tokens + estimated USD cost (env-overridable pricing via LLM_PRICING_JSON), attributed to a user through a contextvars scope (account(user_id)). spend_usd() sums a rolling window; check_budget() enforces LLM_BUDGET_USD and raises BudgetExceeded. - db/models.py + migration 7c1a9e3b5f02: new llm_usage table (cost in integer micro-USD; nullable owner for unattributed calls). - utils/llm.py: providers now return (text, usage); get_completion ledgers usage best-effort and supports an opt-in identical-completion cache (LLM_CACHE_COMPLETIONS=1) that serves free hits with no re-charge. - analysis_runner.check_user_quota: also enforces the spend budget; user_id threaded through run_analysis_sync/enqueue/submit + worker task + background_analysis so async runs attribute too. - orchestrator: re-apply the accounting scope inside the company/salary thread pool (contextvars don't cross threads). - app.py: wrap the sync run in account(user_id). - CI: assert llm_usage present on Postgres. .env.example documents the knobs. - tests: 15 new (pricing, ledger, attribution, budget gate, llm wiring+cache). https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd --- .env.example | 12 + .github/workflows/tests.yml | 2 +- CLAUDE.md | 11 +- agents/orchestrator.py | 8 +- app.py | 4 +- db/models.py | 35 +++ .../versions/7c1a9e3b5f02_llm_usage_ledger.py | 45 ++++ services/analysis_runner.py | 45 +++- services/background_analysis.py | 1 + services/usage.py | 223 ++++++++++++++++++ tests/test_phase35_llm_cost_controls.py | 221 +++++++++++++++++ utils/llm.py | 94 +++++++- worker/tasks.py | 21 +- 13 files changed, 688 insertions(+), 34 deletions(-) create mode 100644 migrations/versions/7c1a9e3b5f02_llm_usage_ledger.py create mode 100644 services/usage.py create mode 100644 tests/test_phase35_llm_cost_controls.py diff --git a/.env.example b/.env.example index e08c8ba..121fac3 100644 --- a/.env.example +++ b/.env.example @@ -81,6 +81,18 @@ # RL_ANALYSIS_MAX=30 # RL_ANALYSIS_WINDOW=3600 +# LLM cost controls (services/usage). Token usage of every real provider call +# is ledgered (table llm_usage) with an estimated USD cost. Set a per-user +# spend cap over a rolling window; 0/unset disables budgeting (count-based +# RL_ANALYSIS_* still applies). +# LLM_BUDGET_USD=0 +# LLM_BUDGET_WINDOW_SECONDS=2592000 # default 30 days +# Override the estimated price table (USD per 1k tokens) wholesale: +# LLM_PRICING_JSON={"gpt-4o-mini": [0.00015, 0.0006], "claude-sonnet-4-6": [0.003, 0.015]} +# Cache identical completions (same provider/model/params/prompt) for free +# reuse — off by default; valuable for repeated/identical analyses. +# LLM_CACHE_COMPLETIONS=1 + # UI / discoverability # TELEGRAM_BOT_USERNAME=YourBot # if set, sidebar shows a link to t.me/... # REDIS_URL=redis://localhost:6379/1 # shared backend for rate-limit + cache + diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 5920b61..d93d1bc 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -168,7 +168,7 @@ jobs: "telegram_links", "audit_events", "background_analyses", "user_two_factor", "application_shares", "api_tokens", "webhooks", "webhook_deliveries", "oauth_identities", - "email_verification_tokens", + "email_verification_tokens", "llm_usage", } missing = required - tables assert not missing, f"missing tables after migrate: {missing}" diff --git a/CLAUDE.md b/CLAUDE.md index 505615a..1db1b7b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -168,9 +168,14 @@ and "production-grade for real multi-user traffic." Prioritized: unkeyed (dev/demo), and legacy plaintext rows re-encrypt opportunistically on the next successful verify. Column widened 64→255 (migration `5d2f8a1c4e7b`). Same primitive is reusable for OAuth-linked emails. -7. **LLM cost controls:** token accounting + per-user budget (today's quota is - a request count, not spend). Cache identical analyses (the cache exists; wire - COL/news/LLM through it consistently). +7. ✅ **LLM cost controls:** `services/usage` ledgers every real completion's + tokens + estimated USD cost (`llm_usage` table, migration `7c1a9e3b5f02`), + attributed to a user via a `contextvars` scope (`usage.account(user_id)`, + re-applied across the company‖salary thread pool). `check_user_quota` now + enforces a rolling-window spend budget (`LLM_BUDGET_USD`) on top of the + request-count limiter. Pricing table is env-overridable (`LLM_PRICING_JSON`). + Opt-in identical-completion cache (`LLM_CACHE_COMPLETIONS=1`) returns free + hits with no token/cost re-charge. 8. **Observability shipping:** logs are structured JSON and metrics exist, but nothing exports them. Wire an OTLP/Prometheus exporter or a log drain; metrics are currently per-process snapshot-only. diff --git a/agents/orchestrator.py b/agents/orchestrator.py index 21666a6..4f8f619 100644 --- a/agents/orchestrator.py +++ b/agents/orchestrator.py @@ -95,8 +95,14 @@ def _analyze_company_and_salary(state: Dict) -> Dict: worker_state = dict(state) worker_state["progress_callback"] = None + # Re-open the usage-accounting scope inside each worker thread so LLM calls + # there are still attributed to the user — contextvars don't propagate into + # ThreadPoolExecutor threads, so we capture the value here and re-apply it. + from services.usage import account, current_user + _acct_user = current_user() + def _run(stage_name, fn, s): - with timed_block("pipeline.stage", tags={"stage": stage_name}): + with account(_acct_user), timed_block("pipeline.stage", tags={"stage": stage_name}): return fn(s) with ThreadPoolExecutor(max_workers=2) as pool: diff --git a/app.py b/app.py index f80e8c0..5abca42 100644 --- a/app.py +++ b/app.py @@ -1188,7 +1188,9 @@ def update_progress(stage, progress, stage_info=None): "re-run." ) - with st.spinner("Analyzing job posting..."): + from services.usage import account as _account_usage + with st.spinner("Analyzing job posting..."), \ + _account_usage(st.session_state.user_id): result = run_analysis( posting_text, job_data, diff --git a/db/models.py b/db/models.py index 157b597..ae4ae19 100644 --- a/db/models.py +++ b/db/models.py @@ -686,3 +686,38 @@ class BackgroundAnalysis(Base): error_message: Mapped[Optional[str]] = mapped_column(Text) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime) + + +# --------------------------------------------------------------------------- +# LLM usage ledger — per-call token accounting for cost controls + budgets +# --------------------------------------------------------------------------- + + +class LlmUsage(Base): + """One LLM completion's token usage + estimated cost. + + Rows are written best-effort after each real provider call (demo-mode + calls record nothing). ``user_id`` is nullable: calls made outside an + attributed request (e.g. a CLI/maintenance path) are still ledgered for + global accounting with a NULL owner. Cost is stored as integer + micro-USD (millionths of a dollar) to keep it exact in the DB; the + pricing table that produces it lives in ``services/usage`` and is + env-overridable. ``services/usage.check_budget`` sums ``cost_micro_usd`` + over a rolling window to enforce ``LLM_BUDGET_USD``. + """ + + __tablename__ = "llm_usage" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + user_id: Mapped[Optional[int]] = mapped_column( + ForeignKey("users.id", ondelete="CASCADE"), nullable=True, index=True + ) + provider: Mapped[str] = mapped_column(String(32), nullable=False) + model: Mapped[str] = mapped_column(String(128), nullable=False) + prompt_tokens: Mapped[int] = mapped_column(Integer, nullable=False, default=0) + completion_tokens: Mapped[int] = mapped_column(Integer, nullable=False, default=0) + total_tokens: Mapped[int] = mapped_column(Integer, nullable=False, default=0) + cost_micro_usd: Mapped[int] = mapped_column(sa_BigInt, nullable=False, default=0) + created_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.utcnow, nullable=False, index=True + ) diff --git a/migrations/versions/7c1a9e3b5f02_llm_usage_ledger.py b/migrations/versions/7c1a9e3b5f02_llm_usage_ledger.py new file mode 100644 index 0000000..b37ce3b --- /dev/null +++ b/migrations/versions/7c1a9e3b5f02_llm_usage_ledger.py @@ -0,0 +1,45 @@ +"""add llm_usage ledger for token accounting + budgets + +Revision ID: 7c1a9e3b5f02 +Revises: 5d2f8a1c4e7b +Create Date: 2026-06-07 00:00:00 + +Per-call LLM token usage + estimated cost (integer micro-USD), attributed to a +user when available. services/usage sums cost over a rolling window to enforce +LLM_BUDGET_USD. +""" +from typing import Sequence, Union + +import sqlalchemy as sa +from alembic import op + +revision: str = "7c1a9e3b5f02" +down_revision: Union[str, None] = "5d2f8a1c4e7b" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + op.create_table( + "llm_usage", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column( + "user_id", sa.Integer(), + sa.ForeignKey("users.id", ondelete="CASCADE"), nullable=True, + ), + sa.Column("provider", sa.String(32), nullable=False), + sa.Column("model", sa.String(128), nullable=False), + sa.Column("prompt_tokens", sa.Integer(), nullable=False, server_default="0"), + sa.Column("completion_tokens", sa.Integer(), nullable=False, server_default="0"), + sa.Column("total_tokens", sa.Integer(), nullable=False, server_default="0"), + sa.Column("cost_micro_usd", sa.BigInteger(), nullable=False, server_default="0"), + sa.Column("created_at", sa.DateTime(), nullable=False), + ) + op.create_index("ix_llm_usage_user_id", "llm_usage", ["user_id"]) + op.create_index("ix_llm_usage_created_at", "llm_usage", ["created_at"]) + + +def downgrade() -> None: + op.drop_index("ix_llm_usage_created_at", table_name="llm_usage") + op.drop_index("ix_llm_usage_user_id", table_name="llm_usage") + op.drop_table("llm_usage") diff --git a/services/analysis_runner.py b/services/analysis_runner.py index 868de11..3faac6c 100644 --- a/services/analysis_runner.py +++ b/services/analysis_runner.py @@ -19,12 +19,23 @@ def check_user_quota(user_id: Optional[int]) -> None: - """Enforce the per-user analysis quota. ``None`` skips (bot/anon flow).""" + """Enforce per-user limits before an analysis runs. ``None`` skips (bot/anon). + + Two gates: a request-count rate limit (cheap brake on bursts) and, when + ``LLM_BUDGET_USD`` is configured, a token-spend budget over a rolling + window (``services/usage``). Either being exceeded blocks the run before + any tokens are spent. + """ if user_id is None: return decision = ANALYSIS_LIMITER.check(str(user_id)) if not decision.allowed: raise RateLimitExceeded(decision.retry_after) + # Spend budget (no-op unless LLM_BUDGET_USD is set). Lazy import keeps the + # rate-limit-only callers free of the DB-backed usage module. + from services.usage import check_budget + + check_budget(user_id) def async_enabled() -> bool: @@ -42,17 +53,24 @@ def run_analysis_sync( model: str = "detailed", resume_text: Optional[str] = None, progress_callback: Optional[Callable] = None, + user_id: Optional[int] = None, ) -> dict: - """Run analysis in-process. Used by the interactive Streamlit flow.""" + """Run analysis in-process. Used by the interactive Streamlit flow. + + ``user_id`` (when given) opens a usage-accounting scope so every LLM call + in the pipeline is attributed to that user for cost controls. + """ from agents.orchestrator import run_analysis + from services.usage import account - return run_analysis( - job_posting, - manual_inputs=manual_inputs, - model=model, - progress_callback=progress_callback, - resume_text=resume_text, - ) + with account(user_id): + return run_analysis( + job_posting, + manual_inputs=manual_inputs, + model=model, + progress_callback=progress_callback, + resume_text=resume_text, + ) def enqueue_analysis( @@ -60,6 +78,7 @@ def enqueue_analysis( manual_inputs: Optional[dict] = None, model: str = "detailed", resume_text: Optional[str] = None, + user_id: Optional[int] = None, ) -> Optional[str]: """Dispatch to the Celery worker. Returns a task id, or None if async is off.""" if not async_enabled(): @@ -71,6 +90,7 @@ def enqueue_analysis( manual_inputs=manual_inputs, model=model, resume_text=resume_text, + user_id=user_id, ) return async_result.id @@ -91,11 +111,14 @@ def submit( manual_inputs: Optional[dict] = None, model: str = "detailed", resume_text: Optional[str] = None, + user_id: Optional[int] = None, ) -> dict: """Enqueue if a worker is available (returns {'task_id': ...}), else run synchronously (returns the full result dict).""" - task_id = enqueue_analysis(job_posting, manual_inputs, model, resume_text) + task_id = enqueue_analysis(job_posting, manual_inputs, model, resume_text, user_id=user_id) if task_id is not None: return {"task_id": task_id, "mode": "async"} - result = run_analysis_sync(job_posting, manual_inputs, model, resume_text) + result = run_analysis_sync( + job_posting, manual_inputs, model, resume_text, user_id=user_id + ) return {"result": result, "mode": "sync"} diff --git a/services/background_analysis.py b/services/background_analysis.py index 1cfcab6..6e86f46 100644 --- a/services/background_analysis.py +++ b/services/background_analysis.py @@ -90,6 +90,7 @@ def submit_background_analysis( manual_inputs=manual_inputs, model=model, resume_text=resume_text, + user_id=user_id, ) if task_id is None: return None diff --git a/services/usage.py b/services/usage.py new file mode 100644 index 0000000..d214000 --- /dev/null +++ b/services/usage.py @@ -0,0 +1,223 @@ +"""LLM cost controls: per-call token accounting + per-user spend budgets. + +The previous quota was a *request count* (``services/rate_limit`` ANALYSIS +limiter) — it can't tell a one-line extraction from a 50-stage report. This +module ledgers the actual token usage of every real provider call and turns it +into an estimated dollar cost, so an operator can cap spend per user. + +How attribution works +--------------------- +Threading a ``user_id`` through every agent and tool would be invasive, so we +use a ``contextvars`` scope instead. The request boundary opens an accounting +scope:: + + with usage.account(user_id): + run_analysis(...) # every get_completion inside is attributed + +``utils.llm.get_completion`` calls :func:`record_completion` after each real +call; it reads the current user from the scope (or takes an explicit +``user_id``). Calls made with no scope are still ledgered with a NULL owner for +global accounting. + +Cost model +---------- +Pricing is a per-model ``(input_per_1k, output_per_1k)`` table in USD, +overridable wholesale via the ``LLM_PRICING_JSON`` env var. Unknown models fall +back to ``_DEFAULT_RATE``. Figures are *estimates* for budgeting, not billing — +providers are the source of truth for actual charges. + +Budget +------ +``LLM_BUDGET_USD`` (default 0 = disabled) caps a user's spend over a rolling +``LLM_BUDGET_WINDOW_SECONDS`` window (default 30 days). :func:`check_budget` +raises :class:`BudgetExceeded` when the cap is hit; the analysis entry point +calls it before doing any work. + +Everything here is best-effort for the *write* path: a ledger failure logs and +continues — accounting must never break the user's analysis. +""" + +from __future__ import annotations + +import contextlib +import json +import logging +import os +from contextvars import ContextVar +from datetime import datetime, timedelta +from typing import Dict, Iterator, Optional, Tuple + +from sqlalchemy import func, select + +import utils.metrics as metrics +from db.models import LlmUsage +from db.session import get_session + +logger = logging.getLogger(__name__) + +# Estimated USD per 1,000 tokens, (input, output). Approximate list prices; +# override the whole table with LLM_PRICING_JSON='{"model": [in, out], ...}'. +_DEFAULT_PRICING: Dict[str, Tuple[float, float]] = { + # Anthropic + "claude-haiku-4-5-20251001": (0.001, 0.005), + "claude-sonnet-4-6": (0.003, 0.015), + # OpenAI + "gpt-4o-mini": (0.00015, 0.0006), + "gpt-4o": (0.0025, 0.01), + "gpt-5": (0.00125, 0.01), + # Featherless / open models are flat-rate hosted; treat as ~free per-token. + "Qwen/Qwen3-32B": (0.0, 0.0), + "deepseek-ai/DeepSeek-R1-0528": (0.0, 0.0), +} +# Fallback for any model not in the table (input, output) per 1k tokens. +_DEFAULT_RATE: Tuple[float, float] = (0.001, 0.003) + +# contextvar holding the user_id the current LLM calls should be attributed to. +_current_user: ContextVar[Optional[int]] = ContextVar("usage_current_user", default=None) + + +class BudgetExceeded(Exception): + """Raised when a user has spent their configured LLM budget for the window.""" + + def __init__(self, spent_usd: float, budget_usd: float): + self.spent_usd = spent_usd + self.budget_usd = budget_usd + super().__init__( + f"LLM budget reached: ${spent_usd:.2f} of ${budget_usd:.2f} used " + "for this period. Try again later or contact the operator." + ) + + +# --------------------------------------------------------------------------- +# Attribution scope +# --------------------------------------------------------------------------- + +@contextlib.contextmanager +def account(user_id: Optional[int]) -> Iterator[None]: + """Attribute LLM calls made in this scope to ``user_id`` (None = unattributed).""" + token = _current_user.set(user_id) + try: + yield + finally: + _current_user.reset(token) + + +def current_user() -> Optional[int]: + return _current_user.get() + + +# --------------------------------------------------------------------------- +# Pricing +# --------------------------------------------------------------------------- + +def _pricing_table() -> Dict[str, Tuple[float, float]]: + raw = os.getenv("LLM_PRICING_JSON") + if not raw: + return _DEFAULT_PRICING + try: + parsed = json.loads(raw) + return {str(k): (float(v[0]), float(v[1])) for k, v in parsed.items()} + except Exception as exc: # noqa: BLE001 - bad override shouldn't break accounting + logger.warning("Ignoring invalid LLM_PRICING_JSON (%s); using defaults.", exc) + return _DEFAULT_PRICING + + +def estimate_cost_usd(model: str, prompt_tokens: int, completion_tokens: int) -> float: + """Estimated USD cost for a call, from the pricing table (per-1k rates).""" + in_rate, out_rate = _pricing_table().get(model, _DEFAULT_RATE) + return (prompt_tokens / 1000.0) * in_rate + (completion_tokens / 1000.0) * out_rate + + +# --------------------------------------------------------------------------- +# Recording +# --------------------------------------------------------------------------- + +def record_completion( + provider: str, + model: str, + usage: Optional[dict], + *, + user_id: Optional[int] = None, +) -> None: + """Ledger one real completion's token usage + estimated cost. Best-effort. + + ``usage`` is the provider's usage dict (``prompt_tokens`` / + ``completion_tokens`` / ``total_tokens``); ``None`` (provider didn't report + usage) records nothing but bumps a counter so the gap is visible. + """ + if usage is None: + metrics.increment("llm.completions_without_usage", tags={"provider": provider}) + return + + prompt = int(usage.get("prompt_tokens") or 0) + completion = int(usage.get("completion_tokens") or 0) + total = int(usage.get("total_tokens") or (prompt + completion)) + cost = estimate_cost_usd(model, prompt, completion) + cost_micro = int(round(cost * 1_000_000)) + uid = user_id if user_id is not None else current_user() + + tags = {"provider": provider, "model": model} + metrics.increment("llm.prompt_tokens", prompt, tags=tags) + metrics.increment("llm.completion_tokens", completion, tags=tags) + metrics.increment("llm.cost_micro_usd", cost_micro, tags=tags) + + try: + with get_session() as session: + session.add(LlmUsage( + user_id=uid, + provider=provider, + model=model, + prompt_tokens=prompt, + completion_tokens=completion, + total_tokens=total, + cost_micro_usd=cost_micro, + )) + session.commit() + except Exception as exc: # noqa: BLE001 - accounting must never break the call + logger.warning("Failed to ledger LLM usage: %s", exc) + + +# --------------------------------------------------------------------------- +# Budget +# --------------------------------------------------------------------------- + +def _budget_usd() -> float: + try: + return float(os.getenv("LLM_BUDGET_USD", "0") or 0) + except ValueError: + return 0.0 + + +def _budget_window_seconds() -> int: + try: + return int(os.getenv("LLM_BUDGET_WINDOW_SECONDS", str(30 * 24 * 3600))) + except ValueError: + return 30 * 24 * 3600 + + +def spend_usd(user_id: int, window_seconds: Optional[int] = None) -> float: + """Total estimated USD spend for a user over the rolling window.""" + window = window_seconds if window_seconds is not None else _budget_window_seconds() + cutoff = datetime.utcnow() - timedelta(seconds=window) + with get_session() as session: + total_micro = session.execute( + select(func.coalesce(func.sum(LlmUsage.cost_micro_usd), 0)).where( + LlmUsage.user_id == user_id, + LlmUsage.created_at >= cutoff, + ) + ).scalar_one() + return (total_micro or 0) / 1_000_000.0 + + +def check_budget(user_id: Optional[int]) -> None: + """Raise :class:`BudgetExceeded` if the user is at/over their LLM budget. + + No-ops when budgeting is disabled (``LLM_BUDGET_USD`` unset/0) or there's + no user to attribute to (bot/anon flow). + """ + budget = _budget_usd() + if budget <= 0 or user_id is None: + return + spent = spend_usd(user_id) + if spent >= budget: + raise BudgetExceeded(spent, budget) diff --git a/tests/test_phase35_llm_cost_controls.py b/tests/test_phase35_llm_cost_controls.py new file mode 100644 index 0000000..9366255 --- /dev/null +++ b/tests/test_phase35_llm_cost_controls.py @@ -0,0 +1,221 @@ +"""P1 #7: LLM cost controls — token accounting, budgets, completion cache. + +Covers services/usage (pricing, ledger record, spend sum, budget gate + +attribution scope), the utils/llm wiring (usage recorded from a provider's +usage object; opt-in completion cache returns free hits), and the budget +enforcement in analysis_runner.check_user_quota. +""" + +from __future__ import annotations + +import os +import sys +import unittest +from unittest import mock + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +from db.session import reset_engine_for_testing # noqa: E402 + + +class PricingTests(unittest.TestCase): + def test_known_model_priced(self): + from services import usage + # gpt-4o-mini: (0.00015, 0.0006) per 1k. + cost = usage.estimate_cost_usd("gpt-4o-mini", 1000, 1000) + self.assertAlmostEqual(cost, 0.00015 + 0.0006, places=6) + + def test_unknown_model_uses_default_rate(self): + from services import usage + cost = usage.estimate_cost_usd("some-unlisted-model", 1000, 0) + self.assertAlmostEqual(cost, usage._DEFAULT_RATE[0], places=6) + + def test_pricing_override_via_env(self): + from services import usage + with mock.patch.dict(os.environ, {"LLM_PRICING_JSON": '{"m": [1.0, 2.0]}'}): + cost = usage.estimate_cost_usd("m", 1000, 1000) + self.assertAlmostEqual(cost, 3.0, places=6) + + def test_bad_pricing_override_falls_back(self): + from services import usage + with mock.patch.dict(os.environ, {"LLM_PRICING_JSON": "not json"}): + # Falls back to defaults; known model still priced. + cost = usage.estimate_cost_usd("gpt-4o-mini", 1000, 0) + self.assertAlmostEqual(cost, 0.00015, places=6) + + +class LedgerTests(unittest.TestCase): + def setUp(self): + reset_engine_for_testing("sqlite:///:memory:") + from services import auth + self.user = auth.register_user("usage@example.com", "Sup3rSecret!") + + def test_record_and_spend(self): + from services import usage + usage.record_completion( + "openai", "gpt-4o-mini", + {"prompt_tokens": 1000, "completion_tokens": 1000, "total_tokens": 2000}, + user_id=self.user.id, + ) + spent = usage.spend_usd(self.user.id) + self.assertAlmostEqual(spent, 0.00075, places=6) + + def test_record_none_usage_is_noop_row(self): + from services import usage + usage.record_completion("openai", "gpt-4o-mini", None, user_id=self.user.id) + self.assertEqual(usage.spend_usd(self.user.id), 0.0) + + def test_attribution_via_scope(self): + from services import usage + with usage.account(self.user.id): + self.assertEqual(usage.current_user(), self.user.id) + usage.record_completion( + "openai", "gpt-4o", + {"prompt_tokens": 1000, "completion_tokens": 0}, + ) + self.assertGreater(usage.spend_usd(self.user.id), 0.0) + # Scope restored on exit. + self.assertIsNone(usage.current_user()) + + def test_unattributed_records_with_null_owner(self): + from sqlalchemy import func, select + + from db.models import LlmUsage + from db.session import get_session + from services import usage + usage.record_completion( + "openai", "gpt-4o-mini", + {"prompt_tokens": 10, "completion_tokens": 10}, + ) # no user_id, no scope + with get_session() as session: + n = session.execute( + select(func.count()).select_from(LlmUsage).where(LlmUsage.user_id.is_(None)) + ).scalar_one() + self.assertEqual(n, 1) + + +class BudgetTests(unittest.TestCase): + def setUp(self): + reset_engine_for_testing("sqlite:///:memory:") + from services import auth + self.user = auth.register_user("budget@example.com", "Sup3rSecret!") + + def test_no_budget_configured_is_noop(self): + from services import usage + os.environ.pop("LLM_BUDGET_USD", None) + usage.check_budget(self.user.id) # should not raise + + def test_under_budget_passes(self): + from services import usage + usage.record_completion( + "openai", "gpt-4o-mini", + {"prompt_tokens": 1000, "completion_tokens": 0}, user_id=self.user.id, + ) + with mock.patch.dict(os.environ, {"LLM_BUDGET_USD": "1.00"}): + usage.check_budget(self.user.id) # 0.00015 << 1.00 + + def test_over_budget_raises(self): + from services import usage + # Spend ~$3 with the override price. + with mock.patch.dict(os.environ, {"LLM_PRICING_JSON": '{"m": [1.0, 2.0]}'}): + usage.record_completion( + "openai", "m", + {"prompt_tokens": 1000, "completion_tokens": 1000}, user_id=self.user.id, + ) + with mock.patch.dict(os.environ, {"LLM_BUDGET_USD": "1.00"}): + with self.assertRaises(usage.BudgetExceeded): + usage.check_budget(self.user.id) + + def test_none_user_skips_budget(self): + from services import usage + with mock.patch.dict(os.environ, {"LLM_BUDGET_USD": "0.01"}): + usage.check_budget(None) # anon/bot — never raises + + def test_check_user_quota_enforces_budget(self): + from services import analysis_runner, usage + from services.rate_limit import reset_backend_for_testing + reset_backend_for_testing() + with mock.patch.dict(os.environ, {"LLM_PRICING_JSON": '{"m": [1.0, 2.0]}'}): + usage.record_completion( + "openai", "m", + {"prompt_tokens": 1000, "completion_tokens": 1000}, user_id=self.user.id, + ) + with mock.patch.dict(os.environ, {"LLM_BUDGET_USD": "1.00"}): + with self.assertRaises(usage.BudgetExceeded): + analysis_runner.check_user_quota(self.user.id) + + +class LlmWiringTests(unittest.TestCase): + """utils/llm records usage from a provider's usage object, and the opt-in + completion cache returns free hits without a second provider call.""" + + def setUp(self): + reset_engine_for_testing("sqlite:///:memory:") + + def test_usage_recorded_from_openai_response(self): + import utils.llm as llm + from services import usage + + class _Usage: + prompt_tokens = 100 + completion_tokens = 50 + total_tokens = 150 + + class _Msg: + content = "hello" + + class _Choice: + message = _Msg() + + class _Resp: + choices = [_Choice()] + usage = _Usage() + + with mock.patch.dict(os.environ, {"OPENAI_API_KEY": "k", "LLM_PROVIDER": "openai"}), \ + mock.patch("openai.OpenAI") as Client: + Client.return_value.chat.completions.create.return_value = _Resp() + with usage.account(None): + out = llm.get_completion("hi", model="fast") + self.assertEqual(out, "hello") + # Recorded one row with the reported tokens. + from sqlalchemy import select + + from db.models import LlmUsage + from db.session import get_session + with get_session() as session: + rows = session.execute(select(LlmUsage)).scalars().all() + self.assertEqual(len(rows), 1) + self.assertEqual(rows[0].prompt_tokens, 100) + self.assertEqual(rows[0].completion_tokens, 50) + + def test_completion_cache_hit_skips_second_call(self): + import utils.llm as llm + + class _Msg: + content = "cached-answer" + + class _Choice: + message = _Msg() + + class _Resp: + choices = [_Choice()] + usage = None + + from utils.cache import cache + cache.clear() + with mock.patch.dict(os.environ, { + "OPENAI_API_KEY": "k", "LLM_PROVIDER": "openai", + "LLM_CACHE_COMPLETIONS": "1", + }), mock.patch("openai.OpenAI") as Client: + create = Client.return_value.chat.completions.create + create.return_value = _Resp() + first = llm.get_completion("same prompt", model="fast") + second = llm.get_completion("same prompt", model="fast") + self.assertEqual(first, "cached-answer") + self.assertEqual(second, "cached-answer") + # Second call served from cache -> provider invoked exactly once. + self.assertEqual(create.call_count, 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/llm.py b/utils/llm.py index ea84ad6..36497f8 100644 --- a/utils/llm.py +++ b/utils/llm.py @@ -59,6 +59,48 @@ _MAX_RETRIES = int(os.getenv("LLM_MAX_RETRIES", "3")) +def _record_usage(provider: str, model: str, usage: Optional[dict]) -> None: + """Ledger token usage for a completed call. Never raises into the caller.""" + try: + from services import usage as usage_service + + usage_service.record_completion(provider, model, usage) + except Exception as exc: # noqa: BLE001 - accounting is best-effort + print(f"[llm] usage accounting skipped: {exc}") + + +def _completion_cache_key( + provider: str, model: str, system: str, temperature: float, max_tokens: int, prompt: str +) -> Optional[str]: + """A stable cache key for an identical call, or None when caching is off.""" + if os.getenv("LLM_CACHE_COMPLETIONS", "0") != "1": + return None + import hashlib + + payload = f"{provider}|{model}|{temperature}|{max_tokens}|{system}|{prompt}" + digest = hashlib.sha256(payload.encode("utf-8")).hexdigest() + return f"llm:completion:{digest}" + + +def _cache_get(key: str) -> Optional[str]: + try: + from utils.cache import cache + + value = cache.get(key) + return value if isinstance(value, str) else None + except Exception: # noqa: BLE001 - cache must never break the call + return None + + +def _cache_set(key: str, value: str) -> None: + try: + from utils.cache import cache + + cache.set(key, value) + except Exception: # noqa: BLE001 + pass + + def get_active_provider() -> Optional[str]: """Return the active provider name, or ``None`` if no key is configured. @@ -135,6 +177,18 @@ def get_completion( resolved_model = resolve_model(provider, model) system_prompt = system or _DEFAULT_SYSTEM_PROMPT + # Opt-in completion cache: identical (provider, model, system, params, + # prompt) calls return the cached text for free — no tokens, no cost, no + # ledger entry. Off by default (LLM_CACHE_COMPLETIONS=1 to enable) since + # most prompts are unique; valuable for repeated/identical analyses. + cache_key = _completion_cache_key( + provider, resolved_model, system_prompt, temperature, max_tokens, prompt + ) + if cache_key is not None: + cached = _cache_get(cache_key) + if cached is not None: + return cached + # Local import keeps utils/timing -> utils/metrics -> utils/llm cycle-free # for the (uncommon) callers that import the LLM client transitively. from utils.timing import timed_block @@ -147,15 +201,19 @@ def get_completion( tags={"provider": provider, "model": resolved_model}, ): if provider == "anthropic": - text = _complete_anthropic( + text, usage = _complete_anthropic( prompt, resolved_model, system_prompt, temperature, max_tokens ) else: # openai or featherless share the OpenAI-compatible client - text = _complete_openai_compatible( + text, usage = _complete_openai_compatible( provider, prompt, resolved_model, system_prompt, temperature, max_tokens, ) - return _strip_reasoning_tokens(text) + _record_usage(provider, resolved_model, usage) + result = _strip_reasoning_tokens(text) + if cache_key is not None: + _cache_set(cache_key, result) + return result except Exception as exc: # noqa: BLE001 - retried/surfaced below last_error = exc print(f"[llm] {provider} call failed (attempt {attempt}/{_MAX_RETRIES}): {exc}") @@ -182,7 +240,7 @@ def get_completion( # package being absent never breaks the active path). # --------------------------------------------------------------------------- -def _complete_anthropic(prompt, model, system, temperature, max_tokens) -> str: +def _complete_anthropic(prompt, model, system, temperature, max_tokens): from anthropic import Anthropic # lazy import # The SDK reads ANTHROPIC_API_KEY and (optionally) ANTHROPIC_BASE_URL itself. @@ -195,7 +253,13 @@ def _complete_anthropic(prompt, model, system, temperature, max_tokens) -> str: messages=[{"role": "user", "content": prompt}], ) parts = [block.text for block in resp.content if getattr(block, "type", None) == "text"] - return "".join(parts).strip() + usage = None + u = getattr(resp, "usage", None) + if u is not None: + inp = getattr(u, "input_tokens", 0) or 0 + out = getattr(u, "output_tokens", 0) or 0 + usage = {"prompt_tokens": inp, "completion_tokens": out, "total_tokens": inp + out} + return "".join(parts).strip(), usage def _is_new_style_openai_model(model: str) -> bool: @@ -210,7 +274,7 @@ def _is_new_style_openai_model(model: str) -> bool: def _complete_openai_compatible( provider, prompt, model, system, temperature, max_tokens -) -> str: +): from openai import OpenAI # lazy import if provider == "featherless": @@ -242,7 +306,17 @@ def _complete_openai_compatible( {"role": "user", "content": prompt}, ], ) - return (resp.choices[0].message.content or "").strip() + usage = None + u = getattr(resp, "usage", None) + if u is not None: + prompt_toks = getattr(u, "prompt_tokens", 0) or 0 + completion_toks = getattr(u, "completion_tokens", 0) or 0 + usage = { + "prompt_tokens": prompt_toks, + "completion_tokens": completion_toks, + "total_tokens": getattr(u, "total_tokens", 0) or (prompt_toks + completion_toks), + } + return (resp.choices[0].message.content or "").strip(), usage def _strip_reasoning_tokens(text: str) -> str: @@ -371,9 +445,11 @@ def ping_provider(provider: str) -> tuple[bool, str]: prompt = "Reply with exactly one word: OK" try: if provider == "anthropic": - text = _complete_anthropic(prompt, model, _DEFAULT_SYSTEM_PROMPT, 0.0, 10) + text, _ = _complete_anthropic(prompt, model, _DEFAULT_SYSTEM_PROMPT, 0.0, 10) else: - text = _complete_openai_compatible(provider, prompt, model, _DEFAULT_SYSTEM_PROMPT, 0.0, 10) + text, _ = _complete_openai_compatible( + provider, prompt, model, _DEFAULT_SYSTEM_PROMPT, 0.0, 10 + ) return True, repr(text.strip()[:40]) except Exception as exc: # noqa: BLE001 return False, str(exc) diff --git a/worker/tasks.py b/worker/tasks.py index bbcaf6e..40ef084 100644 --- a/worker/tasks.py +++ b/worker/tasks.py @@ -20,19 +20,24 @@ def analyze_payload( manual_inputs: Optional[dict] = None, model: str = "detailed", resume_text: Optional[str] = None, + user_id: Optional[int] = None, ) -> dict: """Run the analysis pipeline (no progress callback — async has no live UI). Strips any non-serializable bits before returning so the result can cross - the Celery result backend as JSON. + the Celery result backend as JSON. ``user_id`` opens a usage-accounting + scope so LLM spend in the worker is attributed to the requesting user. """ - result = run_analysis( - job_posting, - manual_inputs=manual_inputs, - model=model, - progress_callback=None, - resume_text=resume_text, - ) + from services.usage import account + + with account(user_id): + result = run_analysis( + job_posting, + manual_inputs=manual_inputs, + model=model, + progress_callback=None, + resume_text=resume_text, + ) result.pop("progress_callback", None) return result From ff7675b7ebcffc9873842521a0896d8b97d74441 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 7 Jun 2026 20:03:14 +0000 Subject: [PATCH 14/24] =?UTF-8?q?P1=20#8:=20observability=20shipping=20?= =?UTF-8?q?=E2=80=94=20Prometheus=20exposition=20+=20/metrics=20endpoint?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The in-process metrics registry can now be exported, not just snapshotted: - utils/metrics.render_prometheus(): Prometheus text exposition (v0.0.4) with name/label sanitisation; counters -> counter, histograms -> summary (quantiles + _sum + _count) plus _min/_max gauges. - api/main.py: GET /metrics serves it, gated by METRICS_ENABLED (404 when off) and an optional METRICS_TOKEN bearer (401 without). Per-process is exactly Prometheus's scrape-and-aggregate model. - worker/metrics_dump.py: --prometheus output + --push to a Pushgateway (METRICS_PUSHGATEWAY_URL) as a cron stop-gap when no scraper is available. - .env.example documents the knobs; tests: 12 new (render format, endpoint gating, pushgateway helper). https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd --- .env.example | 10 +++ CLAUDE.md | 10 ++- api/main.py | 26 +++++- tests/test_phase36_observability.py | 128 ++++++++++++++++++++++++++++ utils/metrics.py | 71 +++++++++++++++ worker/metrics_dump.py | 67 ++++++++++++--- 6 files changed, 296 insertions(+), 16 deletions(-) create mode 100644 tests/test_phase36_observability.py diff --git a/.env.example b/.env.example index 121fac3..82e5871 100644 --- a/.env.example +++ b/.env.example @@ -102,6 +102,16 @@ # CACHE_TTL_SECONDS=3600 # CHECKPOINT_TTL_SECONDS=3600 +# Observability — expose this process's metrics for Prometheus. +# The REST API serves GET /metrics in Prometheus text format when enabled. +# Off by default (returns 404); set a token on any public deployment so the +# metrics aren't world-readable (Prometheus sends Authorization: Bearer ). +# METRICS_ENABLED=1 +# METRICS_TOKEN=change-me +# Stop-gap push path (cron): `python -m worker.metrics_dump --push` +# METRICS_PUSHGATEWAY_URL=http://pushgateway:9091 +# METRICS_JOB=joboffer_scanner + # Telegram bot channel (alternative to the Streamlit UI) # TELEGRAM_BOT_TOKEN=... # from @BotFather diff --git a/CLAUDE.md b/CLAUDE.md index 1db1b7b..64960bc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -176,9 +176,13 @@ and "production-grade for real multi-user traffic." Prioritized: request-count limiter. Pricing table is env-overridable (`LLM_PRICING_JSON`). Opt-in identical-completion cache (`LLM_CACHE_COMPLETIONS=1`) returns free hits with no token/cost re-charge. -8. **Observability shipping:** logs are structured JSON and metrics exist, but - nothing exports them. Wire an OTLP/Prometheus exporter or a log drain; - metrics are currently per-process snapshot-only. +8. ✅ **Observability shipping:** `utils/metrics.render_prometheus` emits the + in-process registry in Prometheus text format; the REST API serves it at + `GET /metrics` (gated by `METRICS_ENABLED`, optional `METRICS_TOKEN` bearer). + Per-process is Prometheus's model — it scrapes each instance and aggregates + server-side. `worker/metrics_dump --prometheus|--push` adds a Pushgateway + stop-gap for cron-only deploys. Logs are already structured JSON (stdout + drain). 9. ✅ **Live provider e2e** (`tests/test_e2e_live.py`, `RUN_E2E=1`): real round-trip per provider, real DuckDuckGo search, the agentic company fallback with no news/COL keys, URL ingest, optional Browserbase, and a diff --git a/api/main.py b/api/main.py index 11a163d..3137360 100644 --- a/api/main.py +++ b/api/main.py @@ -14,8 +14,10 @@ from __future__ import annotations import logging +import os +from typing import Optional -from fastapi import FastAPI +from fastapi import FastAPI, Header, HTTPException, Response, status from api.routes import router from api.security import add_security_headers @@ -24,6 +26,9 @@ logger = logging.getLogger(__name__) +# Prometheus exposition content type (text format v0.0.4). +_PROM_CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8" + def create_app() -> FastAPI: configure_logging() @@ -40,6 +45,25 @@ def create_app() -> FastAPI: def healthz(): return {"ok": True} + @app.get("/metrics") + def metrics(authorization: Optional[str] = Header(default=None)): + """Prometheus scrape endpoint for THIS process's metrics. + + Off by default (returns 404) — set ``METRICS_ENABLED=1`` to expose it. + On a public deployment also set ``METRICS_TOKEN`` and have Prometheus + send ``Authorization: Bearer `` so the metrics aren't world + readable. Metrics are per-process; Prometheus aggregates across scraped + instances. + """ + if os.getenv("METRICS_ENABLED") != "1": + raise HTTPException(status_code=status.HTTP_404_NOT_FOUND) + token = os.getenv("METRICS_TOKEN") + if token and authorization != f"Bearer {token}": + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED) + from utils.metrics import render_prometheus + + return Response(content=render_prometheus(), media_type=_PROM_CONTENT_TYPE) + return app diff --git a/tests/test_phase36_observability.py b/tests/test_phase36_observability.py new file mode 100644 index 0000000..a83447c --- /dev/null +++ b/tests/test_phase36_observability.py @@ -0,0 +1,128 @@ +"""P1 #8: observability shipping — Prometheus exposition + /metrics endpoint. + +Covers utils/metrics.render_prometheus (format, name/label sanitisation, +counters + histogram summary), the gated API /metrics endpoint (404 when off, +401 without the token, 200 with it), and the metrics_dump Pushgateway helper. +""" + +from __future__ import annotations + +import os +import sys +import unittest +from unittest import mock + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + + +class PrometheusRenderTests(unittest.TestCase): + def setUp(self): + import utils.metrics as metrics + metrics.reset_for_testing() + + def test_counter_rendered_with_type_and_labels(self): + import utils.metrics as metrics + metrics.increment("llm.requests", 3, tags={"provider": "openai"}) + out = metrics.render_prometheus() + # Name sanitised: dot -> underscore. + self.assertIn("# TYPE llm_requests counter", out) + self.assertIn('llm_requests{provider="openai"} 3', out) + + def test_histogram_rendered_as_summary(self): + import utils.metrics as metrics + for v in (10.0, 20.0, 30.0): + metrics.observe("llm.latency", v, tags={"provider": "openai"}) + out = metrics.render_prometheus() + self.assertIn("# TYPE llm_latency summary", out) + self.assertIn('quantile="0.5"', out) + self.assertIn('llm_latency_count{provider="openai"} 3', out) + self.assertIn('llm_latency_sum{provider="openai"} 60.0', out) + self.assertIn("# TYPE llm_latency_min gauge", out) + self.assertIn("# TYPE llm_latency_max gauge", out) + + def test_label_value_escaping(self): + import utils.metrics as metrics + metrics.increment("x", 1, tags={"model": 'a"b\\c'}) + out = metrics.render_prometheus() + self.assertIn(r'model="a\"b\\c"', out) + + def test_type_declared_once_per_name(self): + import utils.metrics as metrics + metrics.increment("hits", 1, tags={"a": "1"}) + metrics.increment("hits", 1, tags={"a": "2"}) + out = metrics.render_prometheus() + self.assertEqual(out.count("# TYPE hits counter"), 1) + + def test_empty_registry_renders_cleanly(self): + import utils.metrics as metrics + self.assertEqual(metrics.render_prometheus().strip(), "") + + +class MetricsEndpointTests(unittest.TestCase): + def setUp(self): + from fastapi.testclient import TestClient + + import utils.metrics as metrics + from api.main import create_app + metrics.reset_for_testing() + metrics.increment("llm.requests", 1, tags={"provider": "openai"}) + self.client = TestClient(create_app()) + + def test_404_when_disabled(self): + os.environ.pop("METRICS_ENABLED", None) + self.assertEqual(self.client.get("/metrics").status_code, 404) + + def test_200_when_enabled_no_token(self): + with mock.patch.dict(os.environ, {"METRICS_ENABLED": "1"}): + os.environ.pop("METRICS_TOKEN", None) + resp = self.client.get("/metrics") + self.assertEqual(resp.status_code, 200) + self.assertIn("llm_requests", resp.text) + self.assertIn("text/plain", resp.headers["content-type"]) + + def test_401_without_token(self): + with mock.patch.dict(os.environ, {"METRICS_ENABLED": "1", "METRICS_TOKEN": "sek"}): + resp = self.client.get("/metrics") + self.assertEqual(resp.status_code, 401) + + def test_200_with_token(self): + with mock.patch.dict(os.environ, {"METRICS_ENABLED": "1", "METRICS_TOKEN": "sek"}): + resp = self.client.get("/metrics", headers={"Authorization": "Bearer sek"}) + self.assertEqual(resp.status_code, 200) + self.assertIn("llm_requests", resp.text) + + +class PushgatewayTests(unittest.TestCase): + def test_push_posts_to_job_endpoint(self): + from worker import metrics_dump + + captured = {} + + class _Resp: + def raise_for_status(self): + pass + + def fake_post(url, data=None, headers=None, timeout=None): + captured["url"] = url + captured["data"] = data + return _Resp() + + with mock.patch("requests.post", side_effect=fake_post): + ok = metrics_dump.push_to_gateway("metric 1\n", "http://gw:9091/", "myjob") + self.assertTrue(ok) + self.assertEqual(captured["url"], "http://gw:9091/metrics/job/myjob") + + def test_push_failure_returns_false(self): + from worker import metrics_dump + + with mock.patch("requests.post", side_effect=RuntimeError("down")): + self.assertFalse(metrics_dump.push_to_gateway("x", "http://gw", "j")) + + def test_push_cli_requires_url(self): + from worker import metrics_dump + os.environ.pop("METRICS_PUSHGATEWAY_URL", None) + self.assertEqual(metrics_dump.main(["--push"]), 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/metrics.py b/utils/metrics.py index 0ee10e1..d9f9025 100644 --- a/utils/metrics.py +++ b/utils/metrics.py @@ -16,6 +16,7 @@ from __future__ import annotations +import re import threading from collections import deque from dataclasses import dataclass @@ -192,3 +193,73 @@ def render_snapshot_text(snap: Optional[MetricsSnapshot] = None) -> str: if not lines: lines.append("(no metrics recorded yet)") return "\n".join(lines) + + +# --------------------------------------------------------------------------- +# Prometheus exposition format +# --------------------------------------------------------------------------- +# +# Lets a Prometheus server scrape ``GET /metrics`` (api/main.py) or a cron job +# push to a Pushgateway (worker/metrics_dump --push). The registry is per +# process, which is exactly Prometheus's model: it scrapes each instance and +# aggregates server-side — so multi-instance metrics "ship" without us building +# cross-process aggregation. Counters map to ``counter``; histograms map to a +# ``summary`` (quantiles + _sum + _count) plus _min/_max gauges. + +_NAME_RE = re.compile(r"[^a-zA-Z0-9_:]") + + +def _prom_name(name: str) -> str: + """Sanitise a metric name to the Prometheus charset ([a-zA-Z0-9_:]).""" + cleaned = _NAME_RE.sub("_", name) + # A name must start with a letter, underscore, or colon. + if cleaned and cleaned[0].isdigit(): + cleaned = "_" + cleaned + return cleaned or "_" + + +def _prom_label_value(value: str) -> str: + return value.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + + +def _prom_labels(tags: Tuple[Tuple[str, str], ...], extra: Tuple[Tuple[str, str], ...] = ()) -> str: + pairs = list(tags) + list(extra) + if not pairs: + return "" + inner = ",".join(f'{_prom_name(k)}="{_prom_label_value(v)}"' for k, v in pairs) + return "{" + inner + "}" + + +def render_prometheus(snap: Optional[MetricsSnapshot] = None) -> str: + """Render the snapshot in Prometheus text exposition format (v0.0.4).""" + snap = snap or snapshot() + lines: List[str] = [] + + # Counters — declare TYPE once per metric name. + counters_by_name: Dict[str, List[CounterSnapshot]] = {} + for c in snap.counters: + counters_by_name.setdefault(_prom_name(c.name), []).append(c) + for name, cgroup in counters_by_name.items(): + lines.append(f"# TYPE {name} counter") + for c in cgroup: + lines.append(f"{name}{_prom_labels(c.tags)} {c.value}") + + # Histograms -> summary (quantiles + _sum + _count) plus _min/_max gauges. + hists_by_name: Dict[str, List[HistogramSnapshot]] = {} + for h in snap.histograms: + hists_by_name.setdefault(_prom_name(h.name), []).append(h) + for name, hgroup in hists_by_name.items(): + lines.append(f"# TYPE {name} summary") + for h in hgroup: + for q, val in (("0.5", h.p50), ("0.95", h.p95), ("0.99", h.p99)): + lines.append(f"{name}{_prom_labels(h.tags, (('quantile', q),))} {val}") + lines.append(f"{name}_sum{_prom_labels(h.tags)} {h.sum}") + lines.append(f"{name}_count{_prom_labels(h.tags)} {h.count}") + lines.append(f"# TYPE {name}_min gauge") + for h in hgroup: + lines.append(f"{name}_min{_prom_labels(h.tags)} {h.min}") + lines.append(f"# TYPE {name}_max gauge") + for h in hgroup: + lines.append(f"{name}_max{_prom_labels(h.tags)} {h.max}") + + return "\n".join(lines) + "\n" diff --git a/worker/metrics_dump.py b/worker/metrics_dump.py index 5af6a3a..70b2e3d 100644 --- a/worker/metrics_dump.py +++ b/worker/metrics_dump.py @@ -1,36 +1,79 @@ -"""CLI: dump the current in-process metrics snapshot. +"""CLI: dump or ship the current in-process metrics snapshot. -Run from the same process that's serving traffic (the metrics registry is -in-memory and per-process, so this only sees what's been recorded in *this* -container):: +The metrics registry is in-memory and per-process, so this only sees what's +been recorded in *this* container. Use it for ad-hoc inspection, or schedule +``--push`` to a Prometheus Pushgateway as a stop-gap until a scraper hits the +API's ``/metrics`` endpoint directly. - python -m worker.metrics_dump # text format - python -m worker.metrics_dump --json # JSON for piping to jq - -Useful for ad-hoc inspection during development and for scheduling a -periodic dump into your log pipeline until you have a real metrics backend. + python -m worker.metrics_dump # human-readable text + python -m worker.metrics_dump --json # JSON for piping to jq + python -m worker.metrics_dump --prometheus # Prometheus exposition text + python -m worker.metrics_dump --push # POST to a Pushgateway + # (METRICS_PUSHGATEWAY_URL) """ from __future__ import annotations import argparse import json +import logging +import os import sys from dataclasses import asdict -from utils.metrics import render_snapshot_text, snapshot +from utils.metrics import render_prometheus, render_snapshot_text, snapshot + +logger = logging.getLogger(__name__) + + +def push_to_gateway(text: str, url: str, job: str) -> bool: + """POST Prometheus text to a Pushgateway. Best-effort; returns success.""" + import requests + + endpoint = f"{url.rstrip('/')}/metrics/job/{job}" + try: + resp = requests.post( + endpoint, data=text.encode("utf-8"), + headers={"Content-Type": "text/plain"}, timeout=10, + ) + resp.raise_for_status() + return True + except Exception as exc: # noqa: BLE001 - shipping must not crash the cron + logger.warning("Pushgateway push to %s failed: %s", endpoint, exc) + return False def main(argv: list[str] | None = None) -> int: - parser = argparse.ArgumentParser(description="Dump the current metrics snapshot.") + parser = argparse.ArgumentParser(description="Dump or ship the metrics snapshot.") parser.add_argument( "--json", action="store_true", help="Emit a JSON-serialisable dict instead of the human-readable view.", ) + parser.add_argument( + "--prometheus", action="store_true", + help="Emit Prometheus text exposition format.", + ) + parser.add_argument( + "--push", action="store_true", + help="POST the Prometheus text to METRICS_PUSHGATEWAY_URL.", + ) args = parser.parse_args(argv) snap = snapshot() - if args.json: + + if args.push: + url = os.getenv("METRICS_PUSHGATEWAY_URL") + if not url: + print("METRICS_PUSHGATEWAY_URL is not set.", file=sys.stderr) + return 2 + job = os.getenv("METRICS_JOB", "joboffer_scanner") + ok = push_to_gateway(render_prometheus(snap), url, job) + print("pushed" if ok else "push failed", file=sys.stderr) + return 0 if ok else 1 + + if args.prometheus: + print(render_prometheus(snap), end="") + elif args.json: payload = { "counters": [asdict(c) for c in snap.counters], "histograms": [asdict(h) for h in snap.histograms], From baa841e30639c06449b9f32dfb0774bbf447843f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 8 Jun 2026 06:30:01 +0000 Subject: [PATCH 15/24] P2 #11: durable webhook delivery via Celery with retry/backoff Move outbound webhooks off the best-effort daemon thread onto the queue for at-least-once delivery: - services/webhooks.py: split delivery into _create_delivery (pending row) + attempt_delivery(delivery_id) (re-runnable single POST that rebuilds the signed body from the stored row). dispatch_event_durable enqueues a Celery task per matching webhook when a broker is configured, else degrades to the existing daemon thread. retry_delay_for/_max_attempts drive the schedule (WEBHOOK_MAX_ATTEMPTS / WEBHOOK_RETRY_BACKOFF). - worker/tasks.py: deliver_webhook_task (bind=True) attempts a delivery and self.retry()s with exponential backoff until the attempt budget is spent. - app.py: webhook dispatch sites now call dispatch_event_durable. - dispatch_event (sync) + redeliver unchanged; existing tests stay green. - tests: 13 new (backoff schedule, attempt record success/failure/missing, durable enqueue per matching hook, broker-down fallback). https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd --- .env.example | 7 + CLAUDE.md | 8 +- app.py | 8 +- services/webhooks.py | 121 +++++++++++++++-- tests/test_phase37_webhook_durability.py | 164 +++++++++++++++++++++++ worker/tasks.py | 29 +++- 6 files changed, 316 insertions(+), 21 deletions(-) create mode 100644 tests/test_phase37_webhook_durability.py diff --git a/.env.example b/.env.example index 82e5871..5524cf9 100644 --- a/.env.example +++ b/.env.example @@ -57,6 +57,13 @@ # CELERY_BROKER_URL=redis://localhost:6379/0 # CELERY_RESULT_BACKEND=redis://localhost:6379/0 +# Webhook delivery durability — with a Celery broker, deliveries run as a +# retrying task (at-least-once) instead of a best-effort daemon thread. +# WEBHOOK_ASYNC=1 # 0 to force the inline/thread path +# WEBHOOK_MAX_ATTEMPTS=5 # total tries (initial + retries) +# WEBHOOK_RETRY_BACKOFF=10 # base seconds; backoff = base * 2**retry +# WEBHOOK_TIMEOUT=8 # per-POST timeout (seconds) + # Browser scraper (optional — needs the [browser] extra: playwright). # Enables headless rendering for JS job boards + Numbeo COL where APIs are # paid/unavailable. Heavy; opt in explicitly. Then: `playwright install chromium`. diff --git a/CLAUDE.md b/CLAUDE.md index 64960bc..f7a86f5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -198,8 +198,12 @@ local Playwright scraper). Wired into `fetch_company_news` as tier 2. ### P2 — robustness + reach 10. **JS-board scraping:** `browser_scraper` (Playwright) exists but isn't deployed; LinkedIn/Indeed/Glassdoor need it (or the Chrome extension). -11. **Webhook delivery durability:** deliveries are best-effort daemon - threads; move to the Celery queue with retry/backoff for at-least-once. +11. ✅ **Webhook delivery durability:** `dispatch_event_durable` enqueues a + per-delivery Celery task (`worker.tasks.deliver_webhook_task`) that retries + with exponential backoff (`WEBHOOK_MAX_ATTEMPTS`/`WEBHOOK_RETRY_BACKOFF`) + for at-least-once delivery; degrades to the daemon-thread path when no + broker. `attempt_delivery(delivery_id)` is the re-runnable single-attempt + unit (rebuilds the signed body from the stored row). 12. **Backups + runbook:** automated Postgres backups, a restore drill, and a documented incident/runbook. None exist yet. 13. **Reverse proxy on the real deployment:** the CSP/HSTS configs in `deploy/` diff --git a/app.py b/app.py index 5abca42..68a07dd 100644 --- a/app.py +++ b/app.py @@ -139,7 +139,7 @@ from services.webhooks import ( WebhookError, delete_webhook, - dispatch_event_background, + dispatch_event_durable, list_webhooks, register_webhook, ) @@ -1247,7 +1247,7 @@ def update_progress(stage, progress, stage_info=None): status=save_status, notes=save_notes or None, ) - dispatch_event_background( + dispatch_event_durable( st.session_state.user_id, "application.saved", { "application_id": saved_rec.id, @@ -1569,7 +1569,7 @@ def _matches(rec) -> bool: notify_stage_added( st.session_state.user_id, rec, new_stage, ) - dispatch_event_background( + dispatch_event_durable( st.session_state.user_id, "stage.added", { "application_id": rec.id, @@ -1619,7 +1619,7 @@ def _matches(rec) -> bool: notify_stage_added( st.session_state.user_id, rec, new_stage, ) - dispatch_event_background( + dispatch_event_durable( st.session_state.user_id, "stage.added", { "application_id": rec.id, diff --git a/services/webhooks.py b/services/webhooks.py index c90d7c1..6e93a1d 100644 --- a/services/webhooks.py +++ b/services/webhooks.py @@ -8,10 +8,13 @@ webhook's secret. Receivers verify by recomputing the HMAC. Delivery model: ``dispatch_event`` is synchronous + testable (records a -``WebhookDelivery`` row per attempt). ``dispatch_event_background`` runs it in -a daemon thread so the web request that triggered the event doesn't block on -the receiver's latency. Both are best-effort — a failing webhook NEVER breaks -the user action that triggered it. +``WebhookDelivery`` row per attempt). ``dispatch_event_durable`` is the +production entry point — when a Celery broker is configured it enqueues a +per-(webhook,event) task that retries with exponential backoff for +at-least-once delivery; without a broker it degrades to a fire-and-forget +daemon thread (``dispatch_event_background``). Both are best-effort from the +caller's view — a failing webhook NEVER breaks the user action that triggered +it. Events fire for NEW activity going forward. Historical backfill (bulk import) deliberately does NOT dispatch — you don't want "you were rejected" webhooks @@ -24,6 +27,7 @@ import hmac import json import logging +import os import secrets import threading from dataclasses import dataclass @@ -39,7 +43,28 @@ logger = logging.getLogger(__name__) -_DELIVERY_TIMEOUT = float(__import__("os").getenv("WEBHOOK_TIMEOUT", "8")) +_DELIVERY_TIMEOUT = float(os.getenv("WEBHOOK_TIMEOUT", "8")) + + +def _max_attempts() -> int: + """Total delivery attempts before giving up (initial + retries).""" + try: + return max(1, int(os.getenv("WEBHOOK_MAX_ATTEMPTS", "5"))) + except ValueError: + return 5 + + +def _retry_backoff_base() -> float: + """Base seconds for exponential retry backoff (base * 2**retry_index).""" + try: + return float(os.getenv("WEBHOOK_RETRY_BACKOFF", "10")) + except ValueError: + return 10.0 + + +def retry_delay_for(retry_index: int) -> float: + """Exponential backoff for a given retry number (0-based), capped at 1h.""" + return min(3600.0, _retry_backoff_base() * (2 ** max(0, retry_index))) class WebhookError(ValueError): @@ -200,12 +225,51 @@ def _run(): threading.Thread(target=_run, daemon=True).start() -def _deliver(hook: WebhookRecord, event: str, payload: dict) -> DeliveryRecord: - """POST one event to one webhook and record the result.""" - body_dict = {"event": event, "data": payload, "sent_at": datetime.utcnow().isoformat()} - body = json.dumps(body_dict, default=str, ensure_ascii=False).encode("utf-8") +def _celery_delivery_enabled() -> bool: + """True when a Celery broker is available for durable webhook delivery.""" + if os.getenv("WEBHOOK_ASYNC", "1") != "1": + return False + try: + from worker.celery_app import get_celery_app + + return get_celery_app() is not None + except Exception: # noqa: BLE001 - any import/celery issue => sync fallback + return False - # Create the delivery row first so we have an id for the idempotency header. + +def dispatch_event_durable(user_id: int, event: str, payload: dict) -> None: + """Production dispatch entry point. + + With a Celery broker: create a pending delivery row per matching webhook + and enqueue a task that retries with exponential backoff (at-least-once). + Without a broker: degrade to the fire-and-forget daemon thread. Never + raises into the caller. + """ + if not _celery_delivery_enabled(): + dispatch_event_background(user_id, event, payload) + return + try: + from worker.tasks import deliver_webhook_task + + with get_session() as session: + hooks = session.execute( + select(Webhook) + .where(Webhook.user_id == user_id) + .where(Webhook.active.is_(True)) + ).scalars().all() + targets = [_to_record(h) for h in hooks if event in (h.events or [])] + + for hook in targets: + delivery_id = _create_delivery(hook, event, payload) + deliver_webhook_task.delay(delivery_id) + except Exception as exc: # noqa: BLE001 - fall back, never surface + logger.warning("Durable webhook enqueue failed (%s); using thread.", exc) + dispatch_event_background(user_id, event, payload) + + +def _create_delivery(hook: WebhookRecord, event: str, payload: dict) -> int: + """Persist a pending (attempts=0) delivery row and return its id.""" + body_dict = {"event": event, "data": payload, "sent_at": datetime.utcnow().isoformat()} with get_session() as session: row = WebhookDelivery( webhook_id=hook.id, user_id=hook.user_id, event=event, @@ -214,20 +278,41 @@ def _deliver(hook: WebhookRecord, event: str, payload: dict) -> DeliveryRecord: session.add(row) session.commit() session.refresh(row) - delivery_id = row.id + return row.id + + +def attempt_delivery(delivery_id: int) -> bool: + """POST one (existing) delivery row to its webhook; record + return success. + + Idempotent to re-run: each call is one attempt and increments ``attempts``. + Re-builds the signed body from the stored payload so retries are byte-stable. + Returns True on a 2xx, False otherwise (caller decides whether to retry). + """ + with get_session() as session: + row = session.get(WebhookDelivery, delivery_id) + if row is None: + return False + hook = session.get(Webhook, row.webhook_id) + if hook is None: + return False + body_dict = dict(row.payload or {}) + url, secret = hook.url, hook.secret + event = row.event + + body = json.dumps(body_dict, default=str, ensure_ascii=False).encode("utf-8") status_code: Optional[int] = None error: Optional[str] = None success = False try: resp = requests.post( - hook.url, + url, data=body, headers={ "Content-Type": "application/json", "X-JobOffer-Event": event, "X-JobOffer-Delivery": str(delivery_id), - "X-JobOffer-Signature": sign(hook.secret, body), + "X-JobOffer-Signature": sign(secret, body), }, timeout=_DELIVERY_TIMEOUT, ) @@ -245,7 +330,15 @@ def _deliver(hook: WebhookRecord, event: str, payload: dict) -> DeliveryRecord: row.status_code = status_code row.error = error session.commit() - return _to_delivery(row) + return success + + +def _deliver(hook: WebhookRecord, event: str, payload: dict) -> DeliveryRecord: + """Create a delivery row and POST it once (synchronous, single attempt).""" + delivery_id = _create_delivery(hook, event, payload) + attempt_delivery(delivery_id) + with get_session() as session: + return _to_delivery(session.get(WebhookDelivery, delivery_id)) def redeliver(user_id: int, delivery_id: int) -> DeliveryRecord: diff --git a/tests/test_phase37_webhook_durability.py b/tests/test_phase37_webhook_durability.py new file mode 100644 index 0000000..33d3eb4 --- /dev/null +++ b/tests/test_phase37_webhook_durability.py @@ -0,0 +1,164 @@ +"""P2 #11: durable webhook delivery via the Celery queue with retry/backoff. + +The synchronous dispatch_event path is covered in test_phase23_units; here we +test the durable layer: attempt_delivery against an existing row, the pending +row creation, the backoff schedule, and that dispatch_event_durable enqueues a +retrying task per matching webhook (and skips unsubscribed/inactive ones). +Celery itself is mocked — no broker in the sandbox. +""" + +from __future__ import annotations + +import os +import sys +import unittest +from unittest import mock + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +from db.session import reset_engine_for_testing # noqa: E402 + + +class _OkResp: + status_code = 200 + text = "ok" + + +class _ErrResp: + status_code = 500 + text = "boom" + + +class BackoffTests(unittest.TestCase): + def test_exponential_backoff(self): + from services import webhooks + with mock.patch.dict(os.environ, {"WEBHOOK_RETRY_BACKOFF": "10"}): + self.assertEqual(webhooks.retry_delay_for(0), 10) + self.assertEqual(webhooks.retry_delay_for(1), 20) + self.assertEqual(webhooks.retry_delay_for(2), 40) + + def test_backoff_capped_at_one_hour(self): + from services import webhooks + with mock.patch.dict(os.environ, {"WEBHOOK_RETRY_BACKOFF": "10"}): + self.assertEqual(webhooks.retry_delay_for(20), 3600) + + def test_max_attempts_default(self): + from services import webhooks + os.environ.pop("WEBHOOK_MAX_ATTEMPTS", None) + self.assertEqual(webhooks._max_attempts(), 5) + + +class AttemptDeliveryTests(unittest.TestCase): + def setUp(self): + reset_engine_for_testing("sqlite:///:memory:") + from services import auth, webhooks + self.user = auth.register_user("wh@example.com", "Sup3rSecret!") + self.hook = webhooks.register_webhook( + self.user.id, "https://example.test/hook", ["stage.added"] + ) + + def test_attempt_records_success(self): + from services import webhooks + delivery_id = webhooks._create_delivery(self.hook, "stage.added", {"x": 1}) + with mock.patch.object(webhooks.requests, "post", return_value=_OkResp()): + ok = webhooks.attempt_delivery(delivery_id) + self.assertTrue(ok) + rec = webhooks.list_deliveries(self.user.id)[0] + self.assertTrue(rec.success) + self.assertEqual(rec.attempts, 1) + self.assertEqual(rec.status_code, 200) + + def test_attempt_records_failure_without_raising(self): + from services import webhooks + delivery_id = webhooks._create_delivery(self.hook, "stage.added", {"x": 1}) + with mock.patch.object(webhooks.requests, "post", return_value=_ErrResp()): + ok = webhooks.attempt_delivery(delivery_id) + self.assertFalse(ok) + rec = webhooks.list_deliveries(self.user.id)[0] + self.assertFalse(rec.success) + self.assertEqual(rec.attempts, 1) + self.assertIn("HTTP 500", rec.error) + + def test_repeated_attempts_increment_count(self): + from services import webhooks + delivery_id = webhooks._create_delivery(self.hook, "stage.added", {"x": 1}) + with mock.patch.object(webhooks.requests, "post", return_value=_ErrResp()): + webhooks.attempt_delivery(delivery_id) + webhooks.attempt_delivery(delivery_id) + rec = webhooks.list_deliveries(self.user.id)[0] + self.assertEqual(rec.attempts, 2) + + def test_attempt_missing_row_is_false(self): + from services import webhooks + self.assertFalse(webhooks.attempt_delivery(999999)) + + def test_create_delivery_is_pending(self): + from services import webhooks + delivery_id = webhooks._create_delivery(self.hook, "stage.added", {"x": 1}) + rec = webhooks.list_deliveries(self.user.id)[0] + self.assertEqual(rec.id, delivery_id) + self.assertFalse(rec.success) + self.assertEqual(rec.attempts, 0) + + +class DurableDispatchTests(unittest.TestCase): + def setUp(self): + reset_engine_for_testing("sqlite:///:memory:") + from services import auth, webhooks + self.user = auth.register_user("wh2@example.com", "Sup3rSecret!") + self.active = webhooks.register_webhook( + self.user.id, "https://example.test/a", ["stage.added"] + ) + self.other_event = webhooks.register_webhook( + self.user.id, "https://example.test/b", ["application.saved"] + ) + + def test_enqueues_task_per_matching_hook(self): + from services import webhooks + fake_task = mock.Mock() + with mock.patch.object(webhooks, "_celery_delivery_enabled", return_value=True), \ + mock.patch("worker.tasks.deliver_webhook_task", fake_task): + webhooks.dispatch_event_durable(self.user.id, "stage.added", {"x": 1}) + # Only the hook subscribed to stage.added is enqueued. + self.assertEqual(fake_task.delay.call_count, 1) + # A pending row was created for it. + recs = webhooks.list_deliveries(self.user.id) + self.assertEqual(len(recs), 1) + self.assertEqual(recs[0].attempts, 0) + + def test_falls_back_to_thread_without_celery(self): + from services import webhooks + with mock.patch.object(webhooks, "_celery_delivery_enabled", return_value=False), \ + mock.patch.object(webhooks, "dispatch_event_background") as bg: + webhooks.dispatch_event_durable(self.user.id, "stage.added", {"x": 1}) + bg.assert_called_once_with(self.user.id, "stage.added", {"x": 1}) + + def test_enqueue_failure_falls_back(self): + from services import webhooks + with mock.patch.object(webhooks, "_celery_delivery_enabled", return_value=True), \ + mock.patch("worker.tasks.deliver_webhook_task") as task, \ + mock.patch.object(webhooks, "dispatch_event_background") as bg: + task.delay.side_effect = RuntimeError("broker down") + webhooks.dispatch_event_durable(self.user.id, "stage.added", {"x": 1}) + bg.assert_called_once() + + +class TaskBodyTests(unittest.TestCase): + def setUp(self): + reset_engine_for_testing("sqlite:///:memory:") + from services import auth, webhooks + self.user = auth.register_user("wh3@example.com", "Sup3rSecret!") + self.hook = webhooks.register_webhook( + self.user.id, "https://example.test/hook", ["stage.added"] + ) + + def test_deliver_webhook_wrapper_calls_attempt(self): + from services import webhooks + from worker.tasks import _deliver_webhook + delivery_id = webhooks._create_delivery(self.hook, "stage.added", {"x": 1}) + with mock.patch.object(webhooks.requests, "post", return_value=_OkResp()): + self.assertTrue(_deliver_webhook(delivery_id)) + + +if __name__ == "__main__": + unittest.main() diff --git a/worker/tasks.py b/worker/tasks.py index 40ef084..8f617ca 100644 --- a/worker/tasks.py +++ b/worker/tasks.py @@ -42,7 +42,14 @@ def analyze_payload( return result -# Register as a Celery task only when async is configured/available. +def _deliver_webhook(delivery_id: int) -> bool: + """Plain function body for the webhook-delivery task (testable directly).""" + from services.webhooks import attempt_delivery + + return attempt_delivery(delivery_id) + + +# Register as Celery tasks only when async is configured/available. # Import the already-built app (no factory call here) to avoid an import cycle. try: from worker.celery_app import app as _celery @@ -51,5 +58,25 @@ def analyze_payload( if _celery is not None: analyze_task = _celery.task(name="worker.tasks.analyze_task")(analyze_payload) + + @_celery.task(bind=True, name="worker.tasks.deliver_webhook_task") + def deliver_webhook_task(self, delivery_id: int): + """Durable webhook delivery: one POST attempt; retry with backoff. + + Retries until the row's attempt budget (``WEBHOOK_MAX_ATTEMPTS``) is + exhausted, with exponential backoff between tries — at-least-once + delivery rather than the best-effort daemon thread. + """ + from services.webhooks import _max_attempts, retry_delay_for + + ok = _deliver_webhook(delivery_id) + if ok: + return True + # self.request.retries is 0 on the first run, 1 on the first retry, ... + if self.request.retries + 1 >= _max_attempts(): + logger.warning("Webhook delivery %s exhausted retries.", delivery_id) + return False + raise self.retry(countdown=retry_delay_for(self.request.retries)) else: # pragma: no cover - exercised only without a broker analyze_task = None + deliver_webhook_task = None From 2626b56f426088fa3ee0daa5b0e8d90d823e7f45 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 8 Jun 2026 06:32:31 +0000 Subject: [PATCH 16/24] P2 #12: Postgres backups, restore drill, and operations runbook MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - scripts/backup_db.sh: pg_dump custom-format archive with retention pruning and an optional offsite upload hook (BACKUP_UPLOAD_CMD); strict mode, refuses non-Postgres URLs, warns on suspiciously small dumps. - scripts/restore_db.sh: pg_restore --clean --if-exists, confirmation-gated (type "restore", or --force for automated drills), masks the target password. - deploy/RUNBOOK.md: service map, backup schedule (cron/Replit), monthly restore drill, migration safety, common incidents, secrets rotation, and a data-loss escalation checklist. - tests/test_phase38_ops_backup.py: 12 tests guarding script syntax, strict mode, the early-exit guards (no URL / sqlite / missing dump), and runbook coverage — no DB required. https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd --- CLAUDE.md | 7 +- deploy/RUNBOOK.md | 187 +++++++++++++++++++++++++++++++ scripts/backup_db.sh | 77 +++++++++++++ scripts/restore_db.sh | 79 +++++++++++++ tests/test_phase38_ops_backup.py | 109 ++++++++++++++++++ 5 files changed, 457 insertions(+), 2 deletions(-) create mode 100644 deploy/RUNBOOK.md create mode 100755 scripts/backup_db.sh create mode 100755 scripts/restore_db.sh create mode 100644 tests/test_phase38_ops_backup.py diff --git a/CLAUDE.md b/CLAUDE.md index f7a86f5..e70577f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -204,8 +204,11 @@ local Playwright scraper). Wired into `fetch_company_news` as tier 2. for at-least-once delivery; degrades to the daemon-thread path when no broker. `attempt_delivery(delivery_id)` is the re-runnable single-attempt unit (rebuilds the signed body from the stored row). -12. **Backups + runbook:** automated Postgres backups, a restore drill, and a - documented incident/runbook. None exist yet. +12. ✅ **Backups + runbook:** `scripts/backup_db.sh` (pg_dump custom format, + retention pruning, optional offsite upload hook) + `scripts/restore_db.sh` + (confirmation-gated `pg_restore --clean`), documented in `deploy/RUNBOOK.md` + (backup schedule, monthly restore drill, incidents, escalation). Scripts + are syntax/guard-tested in `tests/test_phase38_ops_backup.py`. 13. **Reverse proxy on the real deployment:** the CSP/HSTS configs in `deploy/` aren't applied on vanilla Replit; a hardened public deploy should sit behind Caddy/nginx (or an equivalent edge). diff --git a/deploy/RUNBOOK.md b/deploy/RUNBOOK.md new file mode 100644 index 0000000..8f337c2 --- /dev/null +++ b/deploy/RUNBOOK.md @@ -0,0 +1,187 @@ +# Operations Runbook — JobOffer Scanner + +Practical procedures for running the deployed app: backups, restore drills, +health checks, common incidents, and routine maintenance. Keep this current — +a runbook nobody trusts is worse than none. + +> Scope: the Postgres-backed production deployment (Replit or Docker Compose). +> In dev/demo (SQLite, no keys) most of this is N/A — the "database" is the +> file `./data/joboffer.db`; copy it to back up. + +--- + +## 1. Service map + +| Component | How it runs | Health | +|------------------|----------------------------------------------|--------| +| Web UI | `streamlit run app.py` (:5000) | page loads, auth gate renders | +| REST API | `python -m api.main` (:8000) | `GET /healthz` → `{"ok": true}` | +| Worker (opt.) | `celery -A worker.celery_app:app worker` | tasks leave `PENDING` | +| Reminders (cron) | `python -m worker.reminders` | exits 0 | +| Postgres | managed / compose `postgres` service | `pg_isready` | +| Redis (opt.) | managed / compose `redis` service | `redis-cli ping` → PONG | + +Metrics (if `METRICS_ENABLED=1`): `GET /metrics` on the API (Prometheus text; +send `Authorization: Bearer $METRICS_TOKEN` when a token is set). Logs are +structured JSON on stdout when `LOG_FORMAT=json`. + +--- + +## 2. Backups + +### What & why +`scripts/backup_db.sh` writes a `pg_dump` **custom-format** archive (`-Fc`) — +compressed and restorable selectively/in parallel with `pg_restore`. The full +analysis blobs live in `Application.analysis_json`, so a DB backup is a +complete, self-contained snapshot (no separate object store to reconcile). + +### Run it +```bash +DATABASE_URL=postgresql://user:pass@host:5432/joboffer \ + BACKUP_DIR=/var/backups/joboffer \ + BACKUP_RETENTION_DAYS=14 \ + ./scripts/backup_db.sh +``` + +Offsite copy (recommended) — set an upload command; the dump path is appended: +```bash +BACKUP_UPLOAD_CMD="aws s3 cp" ... # → aws s3 cp s3://… (set dest in cmd) +BACKUP_UPLOAD_CMD="rclone copyto remote:joc/" ... +``` + +### Schedule +- **Docker Compose / VM:** cron, e.g. nightly at 03:17 UTC: + ```cron + 17 3 * * * cd /srv/joboffer && DATABASE_URL=… ./scripts/backup_db.sh >> /var/log/joc-backup.log 2>&1 + ``` +- **Replit:** a Scheduled Deployment running the same command. +- Keep ≥14 days local; rely on the offsite bucket's lifecycle for long-term. + +### Verify (don't trust an unread backup) +- The script warns if a dump is < 1 KB (usually an empty/failed export). +- Confirm a recent file exists and is growing run-over-run: + ```bash + ls -lh "$BACKUP_DIR"/joboffer-*.dump | tail -3 + ``` +- Actually exercise it monthly via the **restore drill** below — an untested + backup is a hypothesis, not a backup. + +--- + +## 3. Restore + +### Restore drill (do this monthly; never first-time-in-prod) +Restore the latest dump into a **scratch** database and sanity-check it: +```bash +# 1. Make an empty scratch DB. +createdb joboffer_restore_test + +# 2. Restore into it (no prod credentials here!). +DATABASE_URL=postgresql://user:pass@host:5432/joboffer_restore_test \ + ./scripts/restore_db.sh --force backups/joboffer-.dump + +# 3. Smoke-check row counts. +psql "$DATABASE_URL" -c "SELECT count(*) FROM users;" +psql "$DATABASE_URL" -c "SELECT count(*) FROM applications;" + +# 4. Point a throwaway app instance at it and confirm login + an app loads. + +# 5. Drop the scratch DB. +dropdb joboffer_restore_test +``` +Record the date + result somewhere durable. If the drill fails, treat it as a +SEV-2 until backups are proven again. + +### Real restore (recovery) +1. **Stop writers** (web + worker) so nothing races the restore. +2. Restore into the target (interactive confirm unless `--force`): + ```bash + DATABASE_URL=postgresql://user:pass@host:5432/joboffer \ + ./scripts/restore_db.sh backups/joboffer-.dump + ``` + The script masks the password and asks you to type `restore` to proceed. +3. Bring the schema to head if the dump predates a migration: + ```bash + USE_ALEMBIC=1 alembic upgrade head + ``` +4. Restart web + worker; verify `GET /healthz` and a login. + +> `restore_db.sh` uses `--clean --if-exists`, so it drops and recreates objects +> in the target. **The target is overwritten** — double-check `DATABASE_URL` +> points where you intend. + +--- + +## 4. Migrations + +- Production runs Alembic: `USE_ALEMBIC=1 alembic upgrade head` at deploy time. +- Always **back up before** applying a migration in prod. +- CI runs the full `up → down → up` on real Postgres and a schema-drift guard + (`tests/test_phase29_schema_drift.py`); a red bar there means a model changed + without a migration. +- Rollback one step: `alembic downgrade -1` (review the migration's + `downgrade()` first — some are intentionally one-way). + +--- + +## 5. Common incidents + +**API/UI 5xx or won't boot** +- Check logs for a stack trace. Most boot failures are config: missing/invalid + `DATABASE_URL`, or a provider key set but unreachable. +- `GET /healthz` isolates API-vs-DB: if it 500s, the DB connection is the + suspect (`pg_isready`, credentials, connection limit). + +**"Demo mode" unexpectedly in prod** +- No provider key is resolving. Confirm `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` + / `FEATHERLESS_API_KEY` (or `LLM_PROVIDER`) is set in the runtime env, not + just `.env.example`. + +**Analyses rejected with a budget error** +- A user hit `LLM_BUDGET_USD`. Inspect spend: `SELECT user_id, sum(cost_micro_usd)/1e6 + FROM llm_usage WHERE created_at > now() - interval '30 days' GROUP BY 1;` + Raise the budget or wait out the window. + +**Webhooks not arriving** +- Deliveries are durable when a Celery broker is set: check the worker is up + and `webhook_deliveries` rows (`success`, `attempts`, `error`). Without a + broker they're best-effort daemon threads (no retry). Owners can re-send a + failed delivery from the UI. + +**Background analyses stuck `PENDING`** +- Worker down or broker unreachable. Check the `worker` process and + `CELERY_BROKER_URL`. Without a broker, analysis runs inline (no async). + +**Rate-limit / lockout complaints** +- Tunables: `RL_LOGIN_*`, `RL_ANALYSIS_*`. In multi-instance deployments these + only coordinate when `REDIS_URL` is set; otherwise each instance counts + independently. + +--- + +## 6. Routine maintenance + +- **Secrets rotation:** rotating `SECRETS_ENCRYPTION_KEY` invalidates existing + encrypted TOTP secrets — those users must re-enrol 2FA. Rotate only with a + re-encryption plan. App/API bearer tokens and webhook secrets can be rotated + per-record from the UI/API. +- **TLS / headers:** terminate TLS and apply CSP/HSTS at the edge — see + `deploy/Caddyfile.example` / `deploy/nginx.conf.example`. The API also sets + defensive headers itself (`api/security.py`); enable HSTS there only behind + TLS (`API_ENABLE_HSTS=1`). +- **Dependency hygiene:** `uv.lock` must match `pyproject.toml` (`uv lock` + after any change). CI runs `pip-audit` (advisory) — review findings. +- **Capacity:** metrics expose LLM latency/cost and pipeline timings; watch + `llm.request` p95 and per-window `llm_usage` spend. + +--- + +## 7. Escalation checklist (data-loss event) + +1. Stop writers immediately (prevent further divergence). +2. Identify the last-known-good dump (`ls -lt "$BACKUP_DIR"`). +3. Run the **restore drill** against a scratch DB to confirm the dump is good + BEFORE touching prod. +4. Restore to prod (§3), `alembic upgrade head`, restart, verify. +5. Write a short post-incident note: trigger, blast radius, recovery time, + follow-ups. diff --git a/scripts/backup_db.sh b/scripts/backup_db.sh new file mode 100755 index 0000000..f1a0ccc --- /dev/null +++ b/scripts/backup_db.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# +# backup_db.sh — take a compressed, restorable Postgres backup. +# +# Produces a pg_dump custom-format archive (-Fc), which pg_restore can load +# selectively and in parallel. Designed to run from cron / a Scheduled +# Deployment. Best-effort uploads and retention pruning are built in. +# +# Usage: +# DATABASE_URL=postgresql://user:pass@host:5432/db ./scripts/backup_db.sh +# +# Environment: +# DATABASE_URL Postgres connection string (required). A +# "+driver" suffix (e.g. postgresql+psycopg) is +# stripped automatically. +# BACKUP_DIR Where to write dumps (default ./backups). +# BACKUP_RETENTION_DAYS Delete local dumps older than this (default 14). +# BACKUP_UPLOAD_CMD Optional command run per new dump for offsite +# copy; the dump path is appended as the last arg. +# e.g. BACKUP_UPLOAD_CMD="aws s3 cp" or +# BACKUP_UPLOAD_CMD="rclone copyto remote:joc/" +# +# Exit codes: 0 ok, 1 misconfig, 2 dump failed. +set -euo pipefail + +if [[ -z "${DATABASE_URL:-}" ]]; then + echo "ERROR: DATABASE_URL is not set." >&2 + exit 1 +fi + +# pg_dump doesn't understand SQLAlchemy's "+driver" suffix. +CONN="${DATABASE_URL/postgresql+psycopg2/postgresql}" +CONN="${CONN/postgresql+psycopg/postgresql}" + +if [[ "$CONN" != postgres* ]]; then + echo "ERROR: backups require a Postgres DATABASE_URL (got: ${CONN%%:*}...)." >&2 + echo " SQLite is just a file — copy ./data/joboffer.db instead." >&2 + exit 1 +fi + +BACKUP_DIR="${BACKUP_DIR:-./backups}" +RETENTION_DAYS="${BACKUP_RETENTION_DAYS:-14}" +mkdir -p "$BACKUP_DIR" + +TIMESTAMP="$(date -u +%Y%m%dT%H%M%SZ)" +OUTFILE="${BACKUP_DIR}/joboffer-${TIMESTAMP}.dump" + +echo "[backup] dumping to ${OUTFILE} ..." +if ! pg_dump --format=custom --no-owner --no-privileges --file="$OUTFILE" "$CONN"; then + echo "ERROR: pg_dump failed." >&2 + rm -f "$OUTFILE" + exit 2 +fi + +SIZE="$(wc -c < "$OUTFILE" | tr -d ' ')" +echo "[backup] wrote ${OUTFILE} (${SIZE} bytes)" + +# A dump under ~1KB almost certainly means an empty/failed export — flag it. +if [[ "$SIZE" -lt 1024 ]]; then + echo "WARNING: backup is suspiciously small (${SIZE} bytes)." >&2 +fi + +if [[ -n "${BACKUP_UPLOAD_CMD:-}" ]]; then + echo "[backup] uploading via: ${BACKUP_UPLOAD_CMD} ${OUTFILE}" + # shellcheck disable=SC2086 # intentional word-split of the command + if ${BACKUP_UPLOAD_CMD} "$OUTFILE"; then + echo "[backup] upload ok" + else + echo "WARNING: upload command failed (local copy retained)." >&2 + fi +fi + +# Prune old local dumps (offsite copies are governed by their own lifecycle). +echo "[backup] pruning local dumps older than ${RETENTION_DAYS} day(s) ..." +find "$BACKUP_DIR" -name 'joboffer-*.dump' -type f -mtime "+${RETENTION_DAYS}" -print -delete || true + +echo "[backup] done." diff --git a/scripts/restore_db.sh b/scripts/restore_db.sh new file mode 100755 index 0000000..2cba256 --- /dev/null +++ b/scripts/restore_db.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +# +# restore_db.sh — restore a pg_dump custom-format archive into a database. +# +# DESTRUCTIVE: with --clean (the default) this drops and recreates objects in +# the target database before loading. Always restore into a scratch/staging DB +# first when validating a backup (the "restore drill" in deploy/RUNBOOK.md). +# +# Usage: +# DATABASE_URL=postgresql://user:pass@host:5432/db \ +# ./scripts/restore_db.sh backups/joboffer-20260608T010203Z.dump +# +# # Skip the interactive confirmation (for automated drills): +# ./scripts/restore_db.sh --force +# +# Environment: +# DATABASE_URL Target Postgres connection string (required). The target is +# what gets overwritten — point it at staging, not prod, +# unless you mean it. +# +# Exit codes: 0 ok, 1 misconfig/usage, 2 aborted, 3 restore failed. +set -euo pipefail + +FORCE=0 +DUMP="" +for arg in "$@"; do + case "$arg" in + --force) FORCE=1 ;; + -*) echo "ERROR: unknown flag: $arg" >&2; exit 1 ;; + *) DUMP="$arg" ;; + esac +done + +if [[ -z "$DUMP" ]]; then + echo "Usage: $0 [--force] " >&2 + exit 1 +fi +if [[ ! -f "$DUMP" ]]; then + echo "ERROR: dump file not found: $DUMP" >&2 + exit 1 +fi +if [[ -z "${DATABASE_URL:-}" ]]; then + echo "ERROR: DATABASE_URL (the RESTORE TARGET) is not set." >&2 + exit 1 +fi + +CONN="${DATABASE_URL/postgresql+psycopg2/postgresql}" +CONN="${CONN/postgresql+psycopg/postgresql}" +if [[ "$CONN" != postgres* ]]; then + echo "ERROR: restore target must be a Postgres DATABASE_URL." >&2 + exit 1 +fi + +# Show the target host/db (without the password) so the operator can confirm. +SAFE_TARGET="$(printf '%s' "$CONN" | sed -E 's#(://[^:/@]+):[^@]*@#\1:***@#')" + +if [[ "$FORCE" -ne 1 ]]; then + echo "About to restore:" + echo " dump: $DUMP" + echo " target: $SAFE_TARGET" + echo "This will DROP and recreate objects in the target database." + read -r -p "Type 'restore' to proceed: " CONFIRM + if [[ "$CONFIRM" != "restore" ]]; then + echo "Aborted." >&2 + exit 2 + fi +fi + +echo "[restore] loading ${DUMP} into ${SAFE_TARGET} ..." +# --clean --if-exists makes the restore idempotent; --no-owner avoids needing +# the original role names. Errors during DROP of not-yet-existing objects are +# tolerated by --if-exists; a real failure still exits non-zero via pipefail. +if ! pg_restore --clean --if-exists --no-owner --no-privileges \ + --dbname="$CONN" "$DUMP"; then + echo "ERROR: pg_restore reported errors." >&2 + exit 3 +fi + +echo "[restore] done. Verify with: deploy/RUNBOOK.md -> 'Restore drill'." diff --git a/tests/test_phase38_ops_backup.py b/tests/test_phase38_ops_backup.py new file mode 100644 index 0000000..55bbb29 --- /dev/null +++ b/tests/test_phase38_ops_backup.py @@ -0,0 +1,109 @@ +"""P2 #12: backup/restore ops scripts + runbook. + +No Postgres in CI, so we don't actually dump/restore here — we guard the +scripts' shape: they parse (`bash -n`), use strict mode, refuse to run without +DATABASE_URL, reject non-Postgres targets, and the restore script is +destructive-by-default but gated by a confirmation. Also assert the runbook +documents the drill. +""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +_ROOT = Path(__file__).resolve().parents[1] +_BACKUP = _ROOT / "scripts" / "backup_db.sh" +_RESTORE = _ROOT / "scripts" / "restore_db.sh" +_RUNBOOK = _ROOT / "deploy" / "RUNBOOK.md" + +_BASH = shutil.which("bash") + + +@unittest.skipUnless(_BASH, "bash not available") +class ScriptSyntaxTests(unittest.TestCase): + def test_backup_parses(self): + self.assertEqual(subprocess.run([_BASH, "-n", str(_BACKUP)]).returncode, 0) + + def test_restore_parses(self): + self.assertEqual(subprocess.run([_BASH, "-n", str(_RESTORE)]).returncode, 0) + + +class ScriptContentTests(unittest.TestCase): + def setUp(self): + self.backup = _BACKUP.read_text() + self.restore = _RESTORE.read_text() + + def test_strict_mode(self): + for src in (self.backup, self.restore): + self.assertIn("set -euo pipefail", src) + + def test_backup_requires_database_url(self): + self.assertIn("DATABASE_URL", self.backup) + self.assertIn("custom", self.backup) # pg_dump custom format + + def test_backup_rejects_non_postgres(self): + self.assertIn("postgres", self.backup) + + def test_restore_is_gated_by_confirmation(self): + # Destructive: must require an explicit confirmation unless --force. + self.assertIn("--force", self.restore) + self.assertIn("restore", self.restore) + self.assertIn("--clean", self.restore) + + def test_scripts_are_executable(self): + for p in (_BACKUP, _RESTORE): + self.assertTrue(os.access(p, os.X_OK), f"{p} should be executable") + + +@unittest.skipUnless(_BASH, "bash not available") +class BackupGuardBehaviourTests(unittest.TestCase): + """Exercise the early-exit guards without needing a database.""" + + def _run(self, script, args, env): + full_env = {**os.environ, **env} + return subprocess.run( + [_BASH, str(script), *args], + env=full_env, capture_output=True, text=True, + ) + + def test_backup_without_url_exits_1(self): + env = dict(os.environ) + env.pop("DATABASE_URL", None) + r = subprocess.run( + [_BASH, str(_BACKUP)], + env={k: v for k, v in env.items()}, capture_output=True, text=True, + ) + self.assertEqual(r.returncode, 1) + self.assertIn("DATABASE_URL", r.stderr) + + def test_backup_rejects_sqlite_url(self): + r = self._run(_BACKUP, [], {"DATABASE_URL": "sqlite:///./data/joboffer.db"}) + self.assertEqual(r.returncode, 1) + + def test_restore_requires_dump_arg(self): + r = self._run(_RESTORE, [], {"DATABASE_URL": "postgresql://u:p@h/db"}) + self.assertEqual(r.returncode, 1) + self.assertIn("Usage", r.stderr) + + def test_restore_missing_file_exits_1(self): + r = self._run(_RESTORE, ["/no/such/file.dump"], + {"DATABASE_URL": "postgresql://u:p@h/db"}) + self.assertEqual(r.returncode, 1) + + +class RunbookTests(unittest.TestCase): + def test_runbook_exists_and_covers_drill(self): + text = _RUNBOOK.read_text().lower() + for needle in ("backup", "restore drill", "migration", "escalation"): + self.assertIn(needle, text) + + +if __name__ == "__main__": + unittest.main() From 0f698d443c3eac8c2e708951f92ddcc068518741 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 8 Jun 2026 06:44:32 +0000 Subject: [PATCH 17/24] P2 #10 + #13: JS-board ingestion via hosted browser; edge deploy guide MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #10 JS-board scraping: - tools/url_ingest.py: is_js_board() routes LinkedIn/Indeed/Glassdoor/ ZipRecruiter straight to a headless browser (skips the doomed plain GET so we don't ingest a consent wall). _try_browser_fallback now tries the local Playwright scraper THEN a hosted Browserbase session (tools.company_research. deep_fetch) — no local chromium, so JS boards work on a vanilla deploy. browser_ingest_available() reports either backend. Honest paste-hint error when none is configured. #13 Reverse-proxy edge: - deploy/README.md: edge topology (TLS + CSP/HSTS + Secure cookies for the Streamlit UI, pass-through for the self-hardening API), how to apply the Caddy/nginx examples, the Replit/Cloudflare note, and the /metrics privacy note. - tests: phase39 (JS-board detection, routing, local/hosted fallback ordering) + phase40 (proxy configs carry the required hardening directives). https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd --- CLAUDE.md | 22 +++-- deploy/README.md | 71 ++++++++++++++++ tests/test_phase39_js_board_ingest.py | 118 ++++++++++++++++++++++++++ tests/test_phase40_edge_proxy.py | 73 ++++++++++++++++ tools/url_ingest.py | 86 ++++++++++++++++--- 5 files changed, 349 insertions(+), 21 deletions(-) create mode 100644 deploy/README.md create mode 100644 tests/test_phase39_js_board_ingest.py create mode 100644 tests/test_phase40_edge_proxy.py diff --git a/CLAUDE.md b/CLAUDE.md index e70577f..256b4d3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -43,7 +43,9 @@ worker/ Celery app + tasks + CLI runners (reminders, metrics_dum utils/ llm, config, security, diff, verdict, logging_setup, metrics, timing, cache migrations/ Alembic (15 revisions, 19 tables) chrome-extension/ MV3 extension calling the REST API (JS, Node-tested) -deploy/ Caddyfile + nginx reverse-proxy examples (CSP/HSTS) +deploy/ Caddy/nginx reverse-proxy examples (CSP/HSTS) + + README (edge topology) + RUNBOOK (backups/incidents) +scripts/ backup_db.sh / restore_db.sh (Postgres ops) tests/ 33 files, 535 Python tests (7 live e2e, skipped unless RUN_E2E=1) + 9 JS (extract.test.mjs) ``` @@ -195,9 +197,13 @@ synthesises a briefing under the no-fabrication rule, optionally deep-fetching a top result via a **headless agentic browser** (Browserbase hosted, or the local Playwright scraper). Wired into `fetch_company_news` as tier 2. -### P2 — robustness + reach -10. **JS-board scraping:** `browser_scraper` (Playwright) exists but isn't - deployed; LinkedIn/Indeed/Glassdoor need it (or the Chrome extension). +### P2 — ✅ DONE (all four shipped) +10. ✅ **JS-board scraping:** `url_ingest` now routes known JS boards + (LinkedIn/Indeed/Glassdoor/ZipRecruiter via `is_js_board`) and any + too-thin plain fetch through a headless browser — the local Playwright + scraper OR a **hosted Browserbase** session (`deep_fetch`, no local + chromium, so it works on a vanilla deploy). Honest paste-hint error when no + backend is configured. The Chrome extension remains the auth'd-board path. 11. ✅ **Webhook delivery durability:** `dispatch_event_durable` enqueues a per-delivery Celery task (`worker.tasks.deliver_webhook_task`) that retries with exponential backoff (`WEBHOOK_MAX_ATTEMPTS`/`WEBHOOK_RETRY_BACKOFF`) @@ -209,9 +215,11 @@ local Playwright scraper). Wired into `fetch_company_news` as tier 2. (confirmation-gated `pg_restore --clean`), documented in `deploy/RUNBOOK.md` (backup schedule, monthly restore drill, incidents, escalation). Scripts are syntax/guard-tested in `tests/test_phase38_ops_backup.py`. -13. **Reverse proxy on the real deployment:** the CSP/HSTS configs in `deploy/` - aren't applied on vanilla Replit; a hardened public deploy should sit - behind Caddy/nginx (or an equivalent edge). +13. ✅ **Reverse proxy on the real deployment:** `deploy/README.md` documents + the edge topology (TLS + CSP/HSTS + Secure cookies for the Streamlit UI, + pass-through for the self-hardening API) and how to apply the Caddy/nginx + examples or an equivalent edge (Cloudflare) on Replit. The header set is + guarded by `tests/test_phase40_edge_proxy.py`. ## Gotchas diff --git a/deploy/README.md b/deploy/README.md new file mode 100644 index 0000000..53ba259 --- /dev/null +++ b/deploy/README.md @@ -0,0 +1,71 @@ +# Deployment & Edge Hardening + +How to put JobOffer Scanner behind a TLS-terminating reverse proxy that applies +CSP/HSTS and Secure cookies to the **web UI** (Streamlit cannot set these +itself), while passing the **REST API** through to FastAPI (which sets its own +strict JSON headers via `api/security.py`). + +## Topology + +``` + ┌──────────────────────────── edge (Caddy / nginx) ─────────────┐ + client ──▶│ TLS, CSP/HSTS, Secure cookies, gzip │ + │ /api/* ─▶ FastAPI 127.0.0.1:8000 (own security headers) │ + │ /* ─▶ Streamlit 127.0.0.1:5000 (UI; needs ws upgrade) │ + └───────────────────────────────────────────────────────────────┘ +``` + +Why an edge at all: Streamlit can't emit CSP/HSTS or mark its session cookie +`Secure`, so a public deployment needs a proxy to harden the browser surface. +The API already hardens itself, so the proxy just forwards `/api/*`. + +## Caddy (auto-TLS, simplest) + +```bash +# Edit the domain + upstream ports first. +cp deploy/Caddyfile.example /etc/caddy/Caddyfile +caddy run --config /etc/caddy/Caddyfile +``` +Caddy provisions and renews certificates automatically — that's what makes the +Secure cookie + HSTS meaningful. + +## nginx (TLS via certbot) + +```bash +cp deploy/nginx.conf.example /etc/nginx/sites-available/joboffer +ln -s /etc/nginx/sites-available/joboffer /etc/nginx/sites-enabled/ +certbot --nginx -d yourdomain.com # obtain certs, edit paths in the conf +nginx -t && systemctl reload nginx +``` +The `map $http_upgrade` block + `Upgrade`/`Connection` headers are **required** +— without them Streamlit's websocket silently fails to connect. + +## Backends + +Run these bound to localhost (the proxy is the only public listener): + +```bash +streamlit run app.py --server.address 127.0.0.1 --server.port 5000 +python -m api.main # API_HOST=127.0.0.1 API_PORT=8000 +``` + +When the API itself sits behind TLS you may also enable its built-in HSTS: +`API_ENABLE_HSTS=1` (footgun on plain HTTP — only behind TLS). + +## Replit / PaaS note + +Vanilla Replit serves Streamlit directly without these headers. For a hardened +public deployment, front it with Caddy/nginx (above) or an edge like Cloudflare +that applies the same CSP/HSTS/cookie policy. The `deploy/*.example` files are +the source of truth for the header set. + +## Metrics endpoint + +If you scrape `GET /metrics` (see `METRICS_ENABLED`), keep it private: bind the +API to localhost and either don't expose `/metrics` through the proxy or set +`METRICS_TOKEN` and have Prometheus send `Authorization: Bearer `. + +## See also + +- `deploy/RUNBOOK.md` — backups, restore drills, incidents, escalation. +- `docker-compose.yml` — the full multi-service stack for local/self-host. diff --git a/tests/test_phase39_js_board_ingest.py b/tests/test_phase39_js_board_ingest.py new file mode 100644 index 0000000..d0579b4 --- /dev/null +++ b/tests/test_phase39_js_board_ingest.py @@ -0,0 +1,118 @@ +"""P2 #10: JS-board ingestion via a headless browser (local or hosted). + +Known JS boards route straight to a browser; the browser fallback now also +uses the hosted Browserbase path (no local chromium), so ingestion works on a +vanilla deploy. Network/browser are mocked. +""" + +from __future__ import annotations + +import os +import sys +import unittest +from unittest import mock + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + + +class JsBoardDetectionTests(unittest.TestCase): + def test_known_boards_detected(self): + from tools.url_ingest import is_js_board + for url in ( + "https://www.linkedin.com/jobs/view/123", + "https://uk.indeed.com/viewjob?jk=abc", + "https://www.glassdoor.com/job-listing/x", + "https://www.ziprecruiter.com/jobs/x", + ): + self.assertTrue(is_js_board(url), url) + + def test_static_site_not_a_board(self): + from tools.url_ingest import is_js_board + self.assertFalse(is_js_board("https://example.com/careers/123")) + self.assertFalse(is_js_board("https://boards.greenhouse.io/acme/jobs/1")) + + +class BrowserAvailabilityTests(unittest.TestCase): + def test_local_flag_enables(self): + from tools.url_ingest import browser_ingest_available + with mock.patch.dict(os.environ, {"BROWSER_SCRAPER_ENABLED": "1"}): + self.assertTrue(browser_ingest_available()) + + def test_browserbase_keys_enable(self): + from tools.url_ingest import browser_ingest_available + with mock.patch.dict(os.environ, { + "BROWSERBASE_API_KEY": "k", "BROWSERBASE_PROJECT_ID": "p", + }): + self.assertTrue(browser_ingest_available()) + + def test_disabled_by_default(self): + from tools.url_ingest import browser_ingest_available + for k in ("BROWSER_SCRAPER_ENABLED", "BROWSERBASE_API_KEY", "BROWSERBASE_PROJECT_ID"): + os.environ.pop(k, None) + self.assertFalse(browser_ingest_available()) + + +class JsBoardRoutingTests(unittest.TestCase): + def test_js_board_uses_browser_and_skips_plain_get(self): + import tools.url_ingest as url_ingest + with mock.patch.object(url_ingest, "_try_browser_fallback", + return_value="J" * 500) as fb, \ + mock.patch.object(url_ingest.requests, "get") as get: + out = url_ingest.fetch_job_posting("https://www.linkedin.com/jobs/view/1") + self.assertEqual(out, "J" * 500) + fb.assert_called_once() + get.assert_not_called() # never wasted a plain GET on a JS board + + def test_js_board_without_browser_raises_targeted_error(self): + import tools.url_ingest as url_ingest + with mock.patch.object(url_ingest, "_try_browser_fallback", return_value=None): + with self.assertRaises(ValueError) as ctx: + url_ingest.fetch_job_posting("https://www.indeed.com/viewjob?jk=1") + self.assertIn("headless browser", str(ctx.exception)) + + def test_js_board_short_browser_text_raises(self): + import tools.url_ingest as url_ingest + with mock.patch.object(url_ingest, "_try_browser_fallback", return_value="too short"): + with self.assertRaises(ValueError): + url_ingest.fetch_job_posting("https://www.glassdoor.com/job/1") + + +class BrowserFallbackOrderingTests(unittest.TestCase): + def test_hosted_used_when_local_disabled(self): + import tools.url_ingest as url_ingest + # Local scraper disabled -> falls through to hosted deep_fetch. + with mock.patch("tools.browser_scraper.browser_enabled", return_value=False), \ + mock.patch("tools.company_research.deep_fetch", return_value="HOSTED" * 50) as deep: + out = url_ingest._try_browser_fallback("https://www.linkedin.com/jobs/1") + self.assertTrue(out.startswith("HOSTED")) + deep.assert_called_once() + + def test_local_preferred_when_enabled(self): + import tools.url_ingest as url_ingest + with mock.patch("tools.browser_scraper.browser_enabled", return_value=True), \ + mock.patch("tools.browser_scraper.scrape_job_posting", + return_value="LOCAL" * 50) as local, \ + mock.patch("tools.company_research.deep_fetch") as deep: + out = url_ingest._try_browser_fallback("https://www.linkedin.com/jobs/1") + self.assertTrue(out.startswith("LOCAL")) + local.assert_called_once() + deep.assert_not_called() # local succeeded; hosted not attempted + + def test_local_failure_falls_through_to_hosted(self): + import tools.url_ingest as url_ingest + with mock.patch("tools.browser_scraper.browser_enabled", return_value=True), \ + mock.patch("tools.browser_scraper.scrape_job_posting", + side_effect=ValueError("login wall")), \ + mock.patch("tools.company_research.deep_fetch", return_value="HOSTED" * 50): + out = url_ingest._try_browser_fallback("https://www.linkedin.com/jobs/1") + self.assertTrue(out.startswith("HOSTED")) + + def test_none_when_nothing_configured(self): + import tools.url_ingest as url_ingest + with mock.patch("tools.browser_scraper.browser_enabled", return_value=False), \ + mock.patch("tools.company_research.deep_fetch", return_value=None): + self.assertIsNone(url_ingest._try_browser_fallback("https://www.linkedin.com/jobs/1")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_phase40_edge_proxy.py b/tests/test_phase40_edge_proxy.py new file mode 100644 index 0000000..1eafd14 --- /dev/null +++ b/tests/test_phase40_edge_proxy.py @@ -0,0 +1,73 @@ +"""P2 #13: reverse-proxy edge configs ship the hardening directives. + +The Caddy/nginx examples are the source of truth for the web-UI security +headers Streamlit can't set itself. Guard that they don't silently lose a +directive, and that the deploy guide documents the topology. +""" + +from __future__ import annotations + +import os +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + +_DEPLOY = Path(__file__).resolve().parents[1] / "deploy" +_CADDY = _DEPLOY / "Caddyfile.example" +_NGINX = _DEPLOY / "nginx.conf.example" +_README = _DEPLOY / "README.md" + +# Header directives every public edge must carry for the web UI. +_REQUIRED = [ + "Content-Security-Policy", + "Strict-Transport-Security", + "X-Content-Type-Options", + "X-Frame-Options", + "frame-ancestors 'none'", +] + + +class CaddyConfigTests(unittest.TestCase): + def setUp(self): + self.text = _CADDY.read_text() + + def test_has_required_headers(self): + for d in _REQUIRED: + self.assertIn(d, self.text, f"Caddyfile missing {d!r}") + + def test_routes_api_and_ui(self): + self.assertIn("127.0.0.1:8000", self.text) # API + self.assertIn("127.0.0.1:5000", self.text) # Streamlit UI + + def test_secure_cookie_upgrade(self): + self.assertIn("Secure", self.text) + + +class NginxConfigTests(unittest.TestCase): + def setUp(self): + self.text = _NGINX.read_text() + + def test_has_required_headers(self): + for d in _REQUIRED: + self.assertIn(d, self.text, f"nginx conf missing {d!r}") + + def test_websocket_upgrade_wired(self): + # Streamlit silently fails without the upgrade plumbing. + self.assertIn("$connection_upgrade", self.text) + self.assertIn("proxy_set_header Upgrade", self.text) + + def test_redirects_http_to_https(self): + self.assertIn("return 301 https://", self.text) + + +class DeployReadmeTests(unittest.TestCase): + def test_documents_topology_and_proxies(self): + text = _README.read_text().lower() + for needle in ("caddy", "nginx", "streamlit", "reverse proxy", "replit"): + self.assertIn(needle, text) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/url_ingest.py b/tools/url_ingest.py index eb73ead..442ef56 100644 --- a/tools/url_ingest.py +++ b/tools/url_ingest.py @@ -1,12 +1,19 @@ """Optional job-URL ingestion. -Fetches a URL and returns cleaned posting text. This is a best-effort generic -scraper — LinkedIn / Indeed / Glassdoor often require auth or render with JS -and will fail; we degrade honestly (raise a clear error) rather than silently -substitute empty text. - -A site-specific scraper (Playwright/Selenium for JS-heavy pages) is the next -upgrade if URL ingest becomes a primary entry point. +Fetches a URL and returns cleaned posting text. For static pages a plain +``requests`` GET + HTML clean is enough. JS-heavy boards (LinkedIn / Indeed / +Glassdoor) return only a shell to ``requests``, so we route those — and any +page whose plain fetch comes back too thin — to a **headless browser**: + + 1. The local Playwright scraper (``BROWSER_SCRAPER_ENABLED=1``; needs + ``playwright install chromium``), or + 2. A **hosted** headless browser (Browserbase, ``BROWSERBASE_API_KEY`` + + ``BROWSERBASE_PROJECT_ID``) — no local chromium, so this works on a + vanilla deploy. Reuses ``tools.company_research.deep_fetch``. + +When no browser backend is configured we degrade honestly (raise a clear, +actionable error naming the board and the paste alternative) rather than +silently substituting empty/consent-wall text. """ from __future__ import annotations @@ -29,6 +36,15 @@ _URL_RE = re.compile(r"^https?://", re.IGNORECASE) +# Boards that render postings with JS — a plain GET returns a shell (or a +# consent wall), so we go straight to a real browser for these. +_JS_BOARD_HOSTS = ( + "linkedin.com", + "indeed.", # indeed.com, indeed.co.uk, … + "glassdoor.", + "ziprecruiter.com", +) + def is_url(text: Optional[str]) -> bool: if not text: @@ -36,6 +52,19 @@ def is_url(text: Optional[str]) -> bool: return bool(_URL_RE.match(text.strip())) +def is_js_board(url: str) -> bool: + """True for known JS-rendered boards that won't yield to a plain fetch.""" + low = (url or "").lower() + return any(host in low for host in _JS_BOARD_HOSTS) + + +def browser_ingest_available() -> bool: + """Whether any headless-browser backend is configured (local or hosted).""" + if os.getenv("BROWSER_SCRAPER_ENABLED") == "1": + return True + return bool(os.getenv("BROWSERBASE_API_KEY") and os.getenv("BROWSERBASE_PROJECT_ID")) + + def fetch_job_posting(url: str) -> str: """Fetch a URL and return cleaned, plain-text job posting content. @@ -45,6 +74,19 @@ def fetch_job_posting(url: str) -> str: if not is_url(url): raise ValueError("URL must start with http:// or https://") + # Known JS boards never yield to a plain GET — go straight to a browser so + # we don't ingest a consent wall's boilerplate as if it were the posting. + if is_js_board(url): + browser_text = _try_browser_fallback(url) + if browser_text and len(browser_text) >= 200: + return browser_text + raise ValueError( + f"{url} is a JS-rendered board (LinkedIn / Indeed / Glassdoor) that " + "needs a headless browser. Configure one (BROWSER_SCRAPER_ENABLED=1 " + "with chromium, or BROWSERBASE_API_KEY + BROWSERBASE_PROJECT_ID), or " + "paste the job description text instead." + ) + try: resp = requests.get( url, @@ -80,18 +122,34 @@ def fetch_job_posting(url: str) -> str: def _try_browser_fallback(url: str) -> Optional[str]: - """Attempt a headless-browser render; return None if unavailable/failed.""" + """Render ``url`` via the best available headless browser, or None. + + Order: the local Playwright scraper (if explicitly enabled) → a hosted + Browserbase session (if configured). Both are optional; any failure + degrades to None so the caller can surface the paste hint. + """ + # 1. Local Playwright scraper (heavy; opt-in via BROWSER_SCRAPER_ENABLED). try: from tools.browser_scraper import browser_enabled, scrape_job_posting + + if browser_enabled(): + try: + return scrape_job_posting(url) + except Exception as exc: # noqa: BLE001 - try the hosted path next + logger.warning("Local browser fallback failed for %s: %s", url, exc) except ImportError: - return None - if not browser_enabled(): - return None + pass + + # 2. Hosted headless browser (Browserbase) — no local chromium required. try: - return scrape_job_posting(url) + from tools.company_research import deep_fetch + + text = deep_fetch(url) + if text: + return text except Exception as exc: # noqa: BLE001 - fall through to the paste hint - logger.warning("Browser fallback failed for %s: %s", url, exc) - return None + logger.warning("Hosted browser fallback failed for %s: %s", url, exc) + return None def _clean_html(body: bytes) -> str: From c783245ce2a27a530dec2bbb5f80aea2e5bed87e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 8 Jun 2026 07:54:36 +0000 Subject: [PATCH 18/24] =?UTF-8?q?fix(security):=20close=20review=20finding?= =?UTF-8?q?s=20=E2=80=94=20OAuth=20takeover,=20API=20cost=20bypass,=20fabr?= =?UTF-8?q?ication-check=20holes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review fixes (from the holistic technical pass): - CRITICAL: OAuth auto-link now requires a provider-verified email (services/oauth.py). _fetch_userinfo carries email_verified (Google OIDC claim; GitHub only a VERIFIED primary from /user/emails — the unverified emails[0] fallback is gone). resolve_identity refuses to auto-link an unverified email to a pre-existing local account (audited user.oauth.link_refused), closing the account-takeover vector. create_oauth_user records the real verification status. - HIGH: REST /v1/analyze enforces the same cost controls as the web/worker paths (api/routes.py) — check_user_quota first (429/402 on RateLimitExceeded/BudgetExceeded) and run through run_analysis_sync(user_id=) so LLM spend is attributed, not ledgered as NULL. - HIGH: no-fabrication check catches lowercase skills (services/constraint_check.py) via a known-skill lexicon scanned case-insensitively on both sides — fixes both the lowercase-fabrication false negative and the lowercase-source false positive. Year regex broadened to 1900-2099 (pre-1950 dates no longer slip). - MEDIUM: Streamlit analyze flow catches BudgetExceeded (app.py) instead of rendering a raw traceback. - MEDIUM: analyze_requirements raises on non-JSON when a provider key is set (tools/job_tools.py) instead of returning an empty 'successful' analysis; empty skeleton kept only for demo mode. Tests: OAuth verified/unverified link paths + userinfo shape; API 429/402; lowercase fabrication caught + lowercase source not flagged + pre-1950 year; job_tools raise-vs-demo. Full suite green (624), bandit clean. https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd --- api/routes.py | 21 +++++++++- app.py | 6 ++- db/models.py | 1 + services/auth.py | 11 ++--- services/constraint_check.py | 35 +++++++++++++++- services/oauth.py | 80 ++++++++++++++++++++++++++++-------- tests/test_phase10_units.py | 27 ++++++++++++ tests/test_phase22_units.py | 32 +++++++++++++-- tests/test_phase24_units.py | 69 ++++++++++++++++++++++++++----- tests/test_phase2_units.py | 29 +++++++++++++ tools/job_tools.py | 11 ++++- 11 files changed, 280 insertions(+), 42 deletions(-) diff --git a/api/routes.py b/api/routes.py index d91d345..5a704d7 100644 --- a/api/routes.py +++ b/api/routes.py @@ -22,8 +22,8 @@ from fastapi import APIRouter, Depends, HTTPException, status from pydantic import BaseModel, Field -from agents.orchestrator import run_analysis from api.auth import require_user +from services.analysis_runner import check_user_quota, run_analysis_sync from services.analytics import compute_dashboard from services.applications import ( ApplicationError, @@ -34,6 +34,8 @@ ) from services.auth import get_user from services.master_cv import MasterCVError, get_master_cv, save_master_cv +from services.rate_limit import RateLimitExceeded +from services.usage import BudgetExceeded router = APIRouter(prefix="/v1") @@ -125,11 +127,26 @@ def post_analyze( "location": body.location or "", "compensation": body.compensation or "", } - result = run_analysis( + + # Enforce the same cost controls as the web/worker paths BEFORE any tokens + # are spent: request-count rate limit + rolling spend budget. Map to the + # conventional HTTP statuses (429 too-many, 402 payment-required). + try: + check_user_quota(user_id) + except RateLimitExceeded as exc: + raise HTTPException(status_code=429, detail=str(exc)) from exc + except BudgetExceeded as exc: + raise HTTPException(status_code=402, detail=str(exc)) from exc + + # run_analysis_sync opens the usage-accounting scope so this run's LLM + # tokens/cost are attributed to the caller (the direct run_analysis call + # would ledger them with a NULL owner and skip the budget). + result = run_analysis_sync( body.job_posting, manual_inputs=manual, model=body.model, resume_text=body.resume_text, + user_id=user_id, ) if result.get("error"): diff --git a/app.py b/app.py index 68a07dd..a886ec2 100644 --- a/app.py +++ b/app.py @@ -1111,12 +1111,14 @@ def _render_background_card(): } selected_model = "detailed" if "Detailed" in model_choice else "fast" - # Quota check — runs BEFORE the LLM does any work. + # Quota check — runs BEFORE the LLM does any work. Covers both the + # request-count rate limit and the rolling spend budget. from services.analysis_runner import check_user_quota from services.rate_limit import RateLimitExceeded + from services.usage import BudgetExceeded try: check_user_quota(st.session_state.user_id) - except RateLimitExceeded as exc: + except (RateLimitExceeded, BudgetExceeded) as exc: st.error(str(exc)) st.stop() diff --git a/db/models.py b/db/models.py index ae4ae19..9f4821a 100644 --- a/db/models.py +++ b/db/models.py @@ -568,6 +568,7 @@ class ApplicationShare(Base): "user.oauth.login", "user.oauth.register", "user.oauth.link", + "user.oauth.link_refused", "user.account.delete", "user.account.export", "user.email.verify.request", diff --git a/services/auth.py b/services/auth.py index b00ad16..c69d968 100644 --- a/services/auth.py +++ b/services/auth.py @@ -131,7 +131,7 @@ def authenticate_user(email: str, password: str) -> AuthedUser: return AuthedUser(id=user.id, email=user.email, email_verified=user.email_verified) -def create_oauth_user(email: str) -> AuthedUser: +def create_oauth_user(email: str, email_verified: bool = True) -> AuthedUser: """Create a user for an OAuth sign-up with an unusable random password. OAuth users authenticate via the external provider, never via password — @@ -147,17 +147,18 @@ def create_oauth_user(email: str) -> AuthedUser: if existing is not None: return AuthedUser(id=existing.id, email=existing.email, email_verified=existing.email_verified) - # OAuth users are verified by construction — the provider verified the - # email before returning it to us. + # New OAuth account. Trust the provider's email-verification status + # (the caller passes it through from the OIDC/verified-primary claim); + # default True for backward compatibility with non-OAuth callers. user = User( email=email, password_hash=_hash_password(secrets.token_urlsafe(32)), - email_verified=True, + email_verified=email_verified, ) session.add(user) session.commit() session.refresh(user) - return AuthedUser(id=user.id, email=user.email, email_verified=True) + return AuthedUser(id=user.id, email=user.email, email_verified=email_verified) def find_user_by_email(email: str) -> Optional[AuthedUser]: diff --git a/services/constraint_check.py b/services/constraint_check.py index 2e203a8..4e874ae 100644 --- a/services/constraint_check.py +++ b/services/constraint_check.py @@ -42,7 +42,10 @@ _TOKEN_RE = re.compile( r"(? Set[str]: for part in norm.split(): if part not in COMMON_WORDS and len(part) >= 2: out.add(part) + # Catch known skills written in lowercase (the capitalization gate above + # misses them). Word-boundaried so "java" doesn't match "javascript" etc. + low = text.casefold() + for skill in _SKILL_LEXICON: + if re.search(rf"(? str: return token +def _as_bool(value) -> bool: + """Coerce a provider claim (bool or "true"/"1"/"yes") to a real bool.""" + return value is True or str(value).strip().lower() in {"true", "1", "yes"} + + def _fetch_userinfo(cfg: ProviderConfig, access_token: str) -> dict: - """Fetch the user's profile; normalise to {provider_user_id, email}.""" + """Fetch the user's profile; normalise to {provider_user_id, email, + email_verified}. + + ``email_verified`` reflects whether the PROVIDER asserts the address is + verified — Google's OIDC ``email_verified`` claim, or (GitHub) a verified + primary from ``/user/emails``. It gates auto-linking to a pre-existing + local account (see ``resolve_identity``), so an attacker can't take over an + account by pointing an unverified provider email at it. + """ resp = requests.get( cfg.userinfo_url, headers={"Authorization": f"Bearer {access_token}", "Accept": "application/json"}, @@ -166,17 +179,33 @@ def _fetch_userinfo(cfg: ProviderConfig, access_token: str) -> dict: info = resp.json() if cfg.name == "google": - return {"provider_user_id": str(info.get("sub")), "email": info.get("email")} + return { + "provider_user_id": str(info.get("sub")), + "email": info.get("email"), + "email_verified": _as_bool(info.get("email_verified")), + } if cfg.name == "github": - email = info.get("email") - if not email: - # GitHub may hide the primary email from /user; fetch /user/emails. - email = _github_primary_email(access_token) - return {"provider_user_id": str(info.get("id")), "email": email} - return {"provider_user_id": str(info.get("id") or info.get("sub")), "email": info.get("email")} - - -def _github_primary_email(access_token: str) -> Optional[str]: + # GitHub's /user.email carries no verified flag, so always consult + # /user/emails for a VERIFIED primary. Only that path is trusted as + # verified; the public profile email is accepted but unverified. + verified = _github_verified_primary_email(access_token) + if verified: + return {"provider_user_id": str(info.get("id")), "email": verified, + "email_verified": True} + return {"provider_user_id": str(info.get("id")), "email": info.get("email"), + "email_verified": False} + return {"provider_user_id": str(info.get("id") or info.get("sub")), + "email": info.get("email"), + "email_verified": _as_bool(info.get("email_verified"))} + + +def _github_verified_primary_email(access_token: str) -> Optional[str]: + """Return the user's VERIFIED primary GitHub email, or None. + + Deliberately returns None (rather than an unverified fallback) when no + verified primary exists — an unverified address must not be treated as + proof of ownership. + """ try: resp = requests.get( "https://api.github.com/user/emails", @@ -185,11 +214,10 @@ def _github_primary_email(access_token: str) -> Optional[str]: ) resp.raise_for_status() emails = resp.json() - primary = next( + return next( (e["email"] for e in emails if e.get("primary") and e.get("verified")), None, ) - return primary or (emails[0]["email"] if emails else None) except Exception as exc: # noqa: BLE001 logger.warning("GitHub email fetch failed: %s", exc) return None @@ -201,13 +229,19 @@ def _github_primary_email(access_token: str) -> Optional[str]: def resolve_identity( provider: str, provider_user_id: str, email: Optional[str], + email_verified: bool = False, ) -> AuthedUser: """Map an external identity to a local account, linking/creating as needed. Resolution order: 1. Existing OAuthIdentity row -> that user (audit: oauth.login). - 2. Email matches an existing user -> link a new identity (oauth.link). - 3. Otherwise -> create a new user + identity (oauth.register). + 2. Email matches an existing user -> link a new identity (oauth.link), + but ONLY if the provider asserts the email is verified. Auto-linking + on an UNVERIFIED email is an account-takeover vector (an attacker sets + their provider email to the victim's address), so we refuse it and + tell the user to link from settings after a password login. + 3. Otherwise -> create a new user + identity (oauth.register), recording + the provider's verification status on the new account. """ if not provider_user_id: raise OAuthError("Provider did not return a stable user id.") @@ -234,11 +268,20 @@ def resolve_identity( existing = find_user_by_email(email) if existing is not None: + if not email_verified: + _audit("user.oauth.link_refused", user_id=existing.id, + details={"provider": provider, "reason": "unverified_email"}) + raise OAuthError( + "An account already exists for this email. For your security we " + f"won't link {provider} to it from an unverified email. Sign in " + "with your password, then link the provider from account settings " + "(or verify the email with the provider first)." + ) _link_identity(existing.id, provider, provider_user_id, email) _audit("user.oauth.link", user_id=existing.id, details={"provider": provider}) return existing - created = create_oauth_user(email) + created = create_oauth_user(email, email_verified=email_verified) _link_identity(created.id, provider, provider_user_id, email) _audit("user.oauth.register", user_id=created.id, details={"provider": provider}) return created @@ -271,4 +314,7 @@ def complete_login(provider: str, code: str) -> AuthedUser: raise except Exception as exc: # noqa: BLE001 raise OAuthError(f"{cfg.label} sign-in failed: {exc}") from exc - return resolve_identity(provider, info["provider_user_id"], info.get("email")) + return resolve_identity( + provider, info["provider_user_id"], info.get("email"), + email_verified=bool(info.get("email_verified")), + ) diff --git a/tests/test_phase10_units.py b/tests/test_phase10_units.py index ac67046..7eeaeeb 100644 --- a/tests/test_phase10_units.py +++ b/tests/test_phase10_units.py @@ -109,6 +109,33 @@ def test_flags_invented_skill(self): self.assertFalse(check.is_clean) self.assertIn("tensorflow", check.new_proper_nouns) + def test_flags_invented_skill_written_lowercase(self): + # Regression guard: a fabricated skill in lowercase must still be + # flagged (the capitalization heuristic alone would miss it). + from services.constraint_check import check_tailored_output + + tailored = "Built services with python and a bit of tensorflow." + check = check_tailored_output(MASTER_CV, PROJECTS, tailored, JOB_CONTEXT) + self.assertFalse(check.is_clean) + self.assertIn("tensorflow", check.new_proper_nouns) + + def test_lowercase_source_skill_not_a_false_positive(self): + # A skill listed lowercase in the master CV must not be flagged when the + # tailored output capitalizes it. + from services.constraint_check import check_tailored_output + + master = "Skills: python, kubernetes, aws." + tailored = "Deployed on Kubernetes and AWS using Python." + check = check_tailored_output(master, "", tailored, "") + self.assertNotIn("kubernetes", check.new_proper_nouns) + self.assertNotIn("python", check.new_proper_nouns) + + def test_flags_pre_1950_year(self): + from services.constraint_check import check_tailored_output + + check = check_tailored_output(MASTER_CV, PROJECTS, "Graduated 1949.", JOB_CONTEXT) + self.assertIn("1949", check.new_years) + def test_flags_invented_year(self): from services.constraint_check import check_tailored_output diff --git a/tests/test_phase22_units.py b/tests/test_phase22_units.py index 4efa86e..b838e20 100644 --- a/tests/test_phase22_units.py +++ b/tests/test_phase22_units.py @@ -318,7 +318,7 @@ def test_post_analyze_returns_result(self): "salary_analysis": {"y": 2}, "resume_analysis": {}, } - with mock.patch.object(routes_mod, "run_analysis", return_value=fake_result): + with mock.patch.object(routes_mod, "run_analysis_sync", return_value=fake_result): client = self._client() r = client.post( "/v1/analyze", @@ -348,7 +348,7 @@ def test_post_analyze_with_save_persists(self): }, "company_analysis": {}, "salary_analysis": {}, "resume_analysis": {}, } - with mock.patch.object(routes_mod, "run_analysis", return_value=fake_result): + with mock.patch.object(routes_mod, "run_analysis_sync", return_value=fake_result): client = self._client() r = client.post( "/v1/analyze", @@ -369,7 +369,7 @@ def test_post_analyze_with_save_persists(self): def test_post_analyze_propagates_pipeline_error(self): import api.routes as routes_mod - with mock.patch.object(routes_mod, "run_analysis", + with mock.patch.object(routes_mod, "run_analysis_sync", return_value={"error": "LLM hung up"}): client = self._client() r = client.post( @@ -379,6 +379,32 @@ def test_post_analyze_propagates_pipeline_error(self): self.assertEqual(r.status_code, 502) self.assertIn("LLM hung up", r.json()["detail"]) + def test_post_analyze_rate_limited_returns_429(self): + import api.routes as routes_mod + from services.rate_limit import RateLimitExceeded + + with mock.patch.object(routes_mod, "check_user_quota", + side_effect=RateLimitExceeded(42.0)), \ + mock.patch.object(routes_mod, "run_analysis_sync") as run: + client = self._client() + r = client.post("/v1/analyze", headers=self._auth(), + json={"job_posting": "hello"}) + self.assertEqual(r.status_code, 429) + run.assert_not_called() # blocked before any pipeline work + + def test_post_analyze_over_budget_returns_402(self): + import api.routes as routes_mod + from services.usage import BudgetExceeded + + with mock.patch.object(routes_mod, "check_user_quota", + side_effect=BudgetExceeded(5.0, 1.0)), \ + mock.patch.object(routes_mod, "run_analysis_sync") as run: + client = self._client() + r = client.post("/v1/analyze", headers=self._auth(), + json={"job_posting": "hello"}) + self.assertEqual(r.status_code, 402) + run.assert_not_called() + def test_analytics_endpoint_returns_full_shape(self): client = self._client() r = client.get("/v1/analytics", headers=self._auth()) diff --git a/tests/test_phase24_units.py b/tests/test_phase24_units.py index a075816..e2fe9a7 100644 --- a/tests/test_phase24_units.py +++ b/tests/test_phase24_units.py @@ -116,8 +116,9 @@ def test_email_match_links_new_identity_to_existing_user(self): from services.oauth import resolve_identity existing = register_user("shared@example.com", "longenough") - # OAuth login with a DIFFERENT provider id but the same email links. - resolved = resolve_identity("github", "gh-999", "shared@example.com") + # OAuth login with a DIFFERENT provider id but the same VERIFIED email links. + resolved = resolve_identity("github", "gh-999", "shared@example.com", + email_verified=True) self.assertEqual(resolved.id, existing.id) with get_session() as s: idents = s.execute( @@ -126,11 +127,22 @@ def test_email_match_links_new_identity_to_existing_user(self): self.assertEqual(len(idents), 1) self.assertEqual(idents[0].provider, "github") + def test_unverified_email_refuses_link_to_existing_account(self): + # Account-takeover guard: an unverified provider email must NOT auto-link + # to a pre-existing local account. + from services.auth import register_user + from services.oauth import OAuthError, resolve_identity + + register_user("victim@example.com", "longenough") + with self.assertRaises(OAuthError): + resolve_identity("github", "attacker-1", "victim@example.com", + email_verified=False) + def test_two_providers_same_email_resolve_same_account(self): from services.oauth import resolve_identity - g = resolve_identity("google", "g-1", "same@example.com") - h = resolve_identity("github", "h-1", "same@example.com") + g = resolve_identity("google", "g-1", "same@example.com", email_verified=True) + h = resolve_identity("github", "h-1", "same@example.com", email_verified=True) self.assertEqual(g.id, h.id) def test_missing_email_for_new_identity_raises(self): @@ -212,31 +224,50 @@ def test_google_userinfo_shape(self): with mock.patch.object(mod.requests, "get") as get: get.return_value = mock.Mock( status_code=200, - json=lambda: {"sub": "12345", "email": "g@x.com"}, + json=lambda: {"sub": "12345", "email": "g@x.com", "email_verified": True}, raise_for_status=lambda: None, ) info = mod._fetch_userinfo(cfg, "tok") - self.assertEqual(info, {"provider_user_id": "12345", "email": "g@x.com"}) + self.assertEqual(info, {"provider_user_id": "12345", "email": "g@x.com", + "email_verified": True}) - def test_github_userinfo_with_inline_email(self): + def test_google_unverified_email_marked_unverified(self): import services.oauth as mod - cfg = mod.PROVIDERS["github"] + cfg = mod.PROVIDERS["google"] with mock.patch.object(mod.requests, "get") as get: + get.return_value = mock.Mock( + status_code=200, + json=lambda: {"sub": "1", "email": "g@x.com", "email_verified": False}, + raise_for_status=lambda: None, + ) + info = mod._fetch_userinfo(cfg, "tok") + self.assertFalse(info["email_verified"]) + + def test_github_inline_email_is_unverified(self): + import services.oauth as mod + + cfg = mod.PROVIDERS["github"] + # No verified primary -> the public profile email is accepted but + # marked unverified (GitHub /user.email carries no verified flag). + with mock.patch.object(mod.requests, "get") as get, \ + mock.patch.object(mod, "_github_verified_primary_email", return_value=None): get.return_value = mock.Mock( status_code=200, json=lambda: {"id": 777, "email": "gh@x.com"}, raise_for_status=lambda: None, ) info = mod._fetch_userinfo(cfg, "tok") - self.assertEqual(info, {"provider_user_id": "777", "email": "gh@x.com"}) + self.assertEqual(info, {"provider_user_id": "777", "email": "gh@x.com", + "email_verified": False}) - def test_github_falls_back_to_emails_endpoint(self): + def test_github_verified_primary_is_trusted(self): import services.oauth as mod cfg = mod.PROVIDERS["github"] with mock.patch.object(mod.requests, "get") as get, \ - mock.patch.object(mod, "_github_primary_email", return_value="primary@x.com"): + mock.patch.object(mod, "_github_verified_primary_email", + return_value="primary@x.com"): get.return_value = mock.Mock( status_code=200, json=lambda: {"id": 5, "email": None}, @@ -244,6 +275,22 @@ def test_github_falls_back_to_emails_endpoint(self): ) info = mod._fetch_userinfo(cfg, "tok") self.assertEqual(info["email"], "primary@x.com") + self.assertTrue(info["email_verified"]) + + def test_github_verified_primary_filters_unverified(self): + import services.oauth as mod + + # _github_verified_primary_email returns ONLY a verified primary. + with mock.patch.object(mod.requests, "get") as get: + get.return_value = mock.Mock( + status_code=200, + json=lambda: [ + {"email": "unverified@x.com", "primary": True, "verified": False}, + {"email": "other@x.com", "primary": False, "verified": True}, + ], + raise_for_status=lambda: None, + ) + self.assertIsNone(mod._github_verified_primary_email("tok")) # --------------------------------------------------------------------------- diff --git a/tests/test_phase2_units.py b/tests/test_phase2_units.py index 3355332..43ec60e 100644 --- a/tests/test_phase2_units.py +++ b/tests/test_phase2_units.py @@ -9,6 +9,35 @@ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) +class AnalyzeRequirementsFailureTests(unittest.TestCase): + """analyze_requirements must surface a provider failure (non-JSON) when a + key is set, rather than returning an empty 'successful' analysis.""" + + def setUp(self): + from utils.cache import cache + cache.clear() + + def test_raises_on_non_json_when_keyed(self): + import importlib + from unittest import mock + + jt = importlib.import_module("tools.job_tools") # pkg shadows the submodule name + with mock.patch.object(jt, "get_completion", return_value="not json at all"), \ + mock.patch.object(jt, "is_demo_mode", return_value=False): + with self.assertRaises(ValueError): + jt.analyze_requirements("Some posting", model="fast") + + def test_empty_skeleton_only_in_demo(self): + import importlib + from unittest import mock + + jt = importlib.import_module("tools.job_tools") + with mock.patch.object(jt, "get_completion", return_value="not json"), \ + mock.patch.object(jt, "is_demo_mode", return_value=True): + out = jt.analyze_requirements("Some posting", model="fast") + self.assertEqual(out["technical_skills"], []) + + class AtsKeywordMatchTests(unittest.TestCase): def test_score_and_partition(self): from tools.resume_tools import ats_keyword_match diff --git a/tools/job_tools.py b/tools/job_tools.py index c485f80..ff7278c 100644 --- a/tools/job_tools.py +++ b/tools/job_tools.py @@ -17,7 +17,7 @@ from langchain.tools import Tool from utils.cache import cache -from utils.llm import get_completion +from utils.llm import get_completion, is_demo_mode from utils.security import wrap_untrusted logger = logging.getLogger(__name__) @@ -148,6 +148,15 @@ def analyze_requirements(job_posting: str, model: str = "detailed") -> dict: try: parsed = json.loads(response) except json.JSONDecodeError as exc: + # With a real provider key set, non-JSON is a genuine call failure — + # surface it rather than returning an empty analysis that looks + # successful (the "raise, never fabricate" convention). The empty + # skeleton is only a defensive path for demo mode (which returns valid + # JSON anyway, so this is belt-and-suspenders). + if not is_demo_mode(): + raise ValueError( + f"Requirements analysis returned non-JSON from the provider: {exc}" + ) from exc logger.warning("LLM returned non-JSON for requirements (%s); using empty fallback.", exc) parsed = { "technical_skills": [], From 88c9e7c55d7f7f04adfdd0dec92ba3e9a838f30e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 8 Jun 2026 08:07:24 +0000 Subject: [PATCH 19/24] test(e2e): add use-case journey layer (real services + orchestrator, mocked LLM) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes the structural gap between shallow UI-render smoke and skipped live-network e2e: full user journeys with mocked LLM/network but the REAL services, DB, and orchestrator graph, driven through real entry points. - tests/e2e_helpers.py: mock_llm() runs the real pipeline on the NON-demo path (sets a provider key so usage accounting/model resolution/caching execute) while stubbing the provider call with stage-appropriate output (reuses the demo sample generator for guaranteed-valid stage shapes); disables optional network fetchers so nothing egresses. Plus fresh_db()/make_user()/ issue_api_token() factories (fresh_db also resets the rate-limit + checkpoint singletons for inter-journey isolation). - tests/test_phase41_e2e_journeys.py: 7 journeys — 1. real graph runs every stage → verdict+report, and threaded company‖salary usage is attributed to the user (guards the contextvars re-application); 2. API token → POST /v1/analyze (real graph) + save → GET the application; 4. over-budget user refused at the API (402) before any pipeline work; 6. master CV + project → tailored CV: constraint-check clean, and a fabricated skill/percentage is flagged; 7. enable TOTP → password auth signals 2FA → OTP gate accept/reject + one-shot backup code; 8. no news/COL keys + mocked DuckDuckGo → agentic fallback briefing. Full suite green (631). https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd --- tests/e2e_helpers.py | 101 +++++++++++++ tests/test_phase41_e2e_journeys.py | 232 +++++++++++++++++++++++++++++ 2 files changed, 333 insertions(+) create mode 100644 tests/e2e_helpers.py create mode 100644 tests/test_phase41_e2e_journeys.py diff --git a/tests/e2e_helpers.py b/tests/e2e_helpers.py new file mode 100644 index 0000000..a885202 --- /dev/null +++ b/tests/e2e_helpers.py @@ -0,0 +1,101 @@ +"""Shared helpers for use-case (user-journey) e2e tests. + +NOT a test module (no ``test`` prefix → unittest won't collect it). The suite +runs under ``unittest`` (not pytest), so this is a plain importable module of +context managers + factories rather than pytest fixtures. + +The headline piece is :func:`mock_llm`: it makes the REAL analysis pipeline run +end-to-end without a provider, by setting a provider key (so the code takes the +non-demo path — usage accounting, model resolution, caching all execute) and +stubbing the provider call to return **stage-appropriate** structured output. +We reuse ``utils.llm.generate_sample_response`` for the body because it already +emits valid, stage-shaped JSON/markdown for every pipeline stage (it's what +demo mode runs on), so the shapes are guaranteed to match what the agents +expect — while the surrounding real code (which demo mode skips) still runs. + +Optional external fetchers (news/COL/salary/agentic search) are disabled via +env so nothing touches the network; individual tests can re-enable + mock a +specific one (e.g. the agentic fallback journey). +""" + +from __future__ import annotations + +import contextlib +import os +from typing import Callable, Iterator, Optional +from unittest import mock + +# Env that gates optional network fetchers — cleared inside mock_llm so the +# pipeline relies solely on the stubbed LLM and never egresses. +_NETWORK_ENV = ( + "NEWS_API_KEY", "LAYOFFS_DATASET_URL", "COL_DATASET_URL", + "ADZUNA_APP_ID", "ADZUNA_APP_KEY", +) + +_STUB_USAGE = {"prompt_tokens": 50, "completion_tokens": 50, "total_tokens": 100} + + +def fresh_db() -> None: + """Reset to a clean in-memory SQLite DB (StaticPool, shared across threads). + + Also clears the process-wide rate-limit + checkpoint singletons so journeys + don't leak counters into each other (registering the same email across + classes would otherwise trip the register limiter).""" + from db.session import reset_engine_for_testing + from services.rate_limit import reset_backend_for_testing + reset_engine_for_testing("sqlite:///:memory:") + reset_backend_for_testing() + try: + from services.checkpoint import reset_store_for_testing + reset_store_for_testing() + except Exception: # noqa: BLE001 - checkpoint reset is best-effort + pass + + +def make_user(email: str = "journey@example.com", password: str = "Sup3rSecret!"): + """Register and return an AuthedUser.""" + from services.auth import register_user + return register_user(email, password) + + +def issue_api_token(user_id: int, label: str = "e2e") -> str: + from services.api_tokens import issue + return issue(user_id, label, ttl_days=30).raw_token + + +@contextlib.contextmanager +def mock_llm(handler: Optional[Callable[[str], str]] = None) -> Iterator[None]: + """Run the real pipeline with a stubbed LLM provider (no network, no key). + + ``handler(prompt) -> text`` lets a test override the response; by default we + delegate to the demo sample generator, which returns valid stage-shaped + output for every pipeline prompt. A non-demo provider key is set so usage + accounting and the non-demo code paths actually execute. + """ + import utils.llm as llm + + def _text(prompt: str) -> str: + if handler is not None: + out = handler(prompt) + if out is not None: + return out + return llm.generate_sample_response(prompt) + + def _openai(provider, prompt, model, system, temperature, max_tokens): + return _text(prompt), dict(_STUB_USAGE) + + def _anthropic(prompt, model, system, temperature, max_tokens): + return _text(prompt), dict(_STUB_USAGE) + + env = {"OPENAI_API_KEY": "sk-e2e-test", "LLM_PROVIDER": "openai", + # Disable the agentic web fallback so the company stage never egresses. + "COMPANY_RESEARCH_FALLBACK": "0"} + with mock.patch.dict(os.environ, env): + for k in _NETWORK_ENV: + os.environ.pop(k, None) + with mock.patch.object(llm, "_complete_openai_compatible", _openai), \ + mock.patch.object(llm, "_complete_anthropic", _anthropic): + # The completion cache would mask per-call stubbing across tests. + from utils.cache import cache + cache.clear() + yield diff --git a/tests/test_phase41_e2e_journeys.py b/tests/test_phase41_e2e_journeys.py new file mode 100644 index 0000000..f2e7338 --- /dev/null +++ b/tests/test_phase41_e2e_journeys.py @@ -0,0 +1,232 @@ +"""Use-case (user-journey) e2e tests. + +The middle layer that was missing: full journeys with mocked LLM/network but +REAL services + DB + orchestrator, driven through the real entry points +(orchestrator, REST API, services). These exercise the seams the unit suite +structurally can't reach — the real multi-agent graph, the API analyze body, +threaded usage attribution, and the cost-control gates — with no network. + +See ``tests/e2e_helpers.py`` for ``mock_llm`` (stubs the provider call with +stage-appropriate output while taking the real, non-demo code path). +""" + +from __future__ import annotations + +import os +import sys +import unittest + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) +sys.path.insert(0, os.path.dirname(__file__)) # for e2e_helpers (tests/ not a package) + +import e2e_helpers as e2e # noqa: E402 + +_VALID_VERDICTS = { + "Highly Recommended", "Recommended", "Consider with Caution", "Not Recommended", +} + +_POSTING = ( + "Company: Acme\nTitle: Senior Backend Engineer\nLocation: Berlin, Germany\n\n" + "We need a backend engineer with Python, PostgreSQL and AWS. 5+ years." +) +_MANUAL = {"company_name": "Acme", "job_title": "Senior Backend Engineer", + "location": "Berlin, Germany", "compensation": "EUR 90k"} + + +class FullPipelineJourney(unittest.TestCase): + """Journey 1: the real orchestrator graph runs every stage with a stubbed + LLM and produces a verdict + report; usage is attributed to the user.""" + + def setUp(self): + e2e.fresh_db() + self.user = e2e.make_user() + + def test_real_graph_runs_and_attributes_usage(self): + from services.analysis_runner import run_analysis_sync + from services.usage import spend_usd + + with e2e.mock_llm(): + result = run_analysis_sync( + _POSTING, manual_inputs=_MANUAL, model="fast", user_id=self.user.id, + ) + + self.assertEqual(result.get("error", ""), "", msg=result.get("error")) + # All four stages populated. + self.assertTrue(result.get("job_details")) + self.assertTrue(result.get("company_analysis")) + self.assertTrue(result.get("salary_analysis")) + self.assertTrue(result.get("final_report")) + self.assertIn((result.get("verdict") or {}).get("verdict"), _VALID_VERDICTS) + # Threaded company‖salary attribution: spend was ledgered to THIS user + # (the contextvars re-application across the stage thread pool works). + self.assertGreater(spend_usd(self.user.id), 0.0) + + +class ApiAnalyzeSaveFetchJourney(unittest.TestCase): + """Journey 2: API token → POST /v1/analyze (real graph) with save → GET the + persisted application back.""" + + def setUp(self): + e2e.fresh_db() + self.user = e2e.make_user() + self.token = e2e.issue_api_token(self.user.id) + + def _client(self): + from fastapi.testclient import TestClient + + from api.main import create_app + return TestClient(create_app()) + + def test_analyze_then_fetch(self): + client = self._client() + headers = {"Authorization": f"Bearer {self.token}"} + with e2e.mock_llm(): + r = client.post("/v1/analyze", headers=headers, json={ + "job_posting": _POSTING, "company_name": "Acme", + "job_title": "Senior Backend Engineer", "location": "Berlin", + "save": True, "save_status": "applied", + }) + self.assertEqual(r.status_code, 200, msg=r.text) + saved_id = r.json()["saved_application_id"] + self.assertIsNotNone(saved_id) + + got = client.get(f"/v1/applications/{saved_id}", headers=headers) + self.assertEqual(got.status_code, 200) + self.assertEqual(got.json()["status"], "applied") + + +class BudgetBlockJourney(unittest.TestCase): + """Journey 4: a user already over their LLM budget is refused at the API + BEFORE any pipeline work (402), with spend attribution intact.""" + + def setUp(self): + e2e.fresh_db() + self.user = e2e.make_user() + self.token = e2e.issue_api_token(self.user.id) + + def test_over_budget_blocks_before_pipeline(self): + from unittest import mock + + from fastapi.testclient import TestClient + + import api.routes as routes + from api.main import create_app + from services import usage + + # Pre-load spend over a $1 budget using an overridden price. + with mock.patch.dict(os.environ, {"LLM_PRICING_JSON": '{"m": [1.0, 2.0]}'}): + usage.record_completion("openai", "m", + {"prompt_tokens": 1000, "completion_tokens": 1000}, + user_id=self.user.id) + + client = TestClient(create_app()) + headers = {"Authorization": f"Bearer {self.token}"} + with mock.patch.dict(os.environ, {"LLM_BUDGET_USD": "1.00"}), \ + mock.patch.object(routes, "run_analysis_sync") as run: + r = client.post("/v1/analyze", headers=headers, + json={"job_posting": _POSTING}) + self.assertEqual(r.status_code, 402) + run.assert_not_called() + + +class TailoredCvConstraintJourney(unittest.TestCase): + """Journey 6: master CV + project → tailored CV → constraint check is clean; + and the negative case where a fabricated skill is flagged.""" + + def setUp(self): + e2e.fresh_db() + self.user = e2e.make_user() + from services.applications import save_analysis + from services.master_cv import save_master_cv + from services.projects import create_project + save_master_cv(self.user.id, + "Skills: Python, PostgreSQL, AWS.\nExperience: Backend at Globex.") + create_project(self.user.id, title="Payments API", role="lead", + tech_stack="Python, PostgreSQL", summary="Built a payments API", + highlights=["Scaled to 1M requests"]) + self.app = save_analysis(self.user.id, _MANUAL, + {"verdict": {"verdict": "Recommended", "light": "green"}}) + + def test_clean_tailored_cv(self): + from services.tailoring import generate_tailored_cv + + clean_cv = "Senior Backend Engineer. Skills: Python, PostgreSQL, AWS at Globex." + with e2e.mock_llm(handler=lambda prompt: clean_cv): + art = generate_tailored_cv(self.user.id, self.app.id, model="fast") + self.assertEqual(art.meta["constraint_check"]["severity"], "clean") + + def test_fabricated_skill_is_flagged(self): + from services.tailoring import generate_tailored_cv + + # Injects "Kubernetes" + "Rust" — neither is in the CV/projects/job. + fabricated = "Skills: Python, Kubernetes, Rust. Reduced latency by 80%." + with e2e.mock_llm(handler=lambda prompt: fabricated): + art = generate_tailored_cv(self.user.id, self.app.id, model="fast") + check = art.meta["constraint_check"] + self.assertEqual(check["severity"], "review_recommended") + self.assertIn("kubernetes", check["new_proper_nouns"]) + self.assertIn("rust", check["new_proper_nouns"]) + self.assertIn("80%", check["new_percentages"]) + + +class TwoFactorLoginJourney(unittest.TestCase): + """Journey 7: enable TOTP → authenticate signals 2FA required → OTP gate + accepts a valid code and rejects a wrong one; a backup code is one-shot.""" + + def setUp(self): + e2e.fresh_db() + self.user = e2e.make_user(email="2fa@example.com") + + def test_login_gate(self): + import pyotp + + from services import totp + from services.auth import authenticate_user + + setup = totp.start_setup(self.user.id, "2fa@example.com") + confirm = totp.confirm_setup(self.user.id, pyotp.TOTP(setup.secret).now()) + + # Password auth now signals the second factor is required. + authed = authenticate_user("2fa@example.com", "Sup3rSecret!") + self.assertTrue(authed.two_factor_required) + + # Wrong OTP rejected; correct OTP accepted. + self.assertFalse(totp.verify_login(self.user.id, "000000")) + self.assertTrue(totp.verify_login(self.user.id, pyotp.TOTP(setup.secret).now())) + + # A backup code works once, then is consumed. + code = confirm.backup_codes[0] + self.assertTrue(totp.verify_login(self.user.id, code)) + self.assertFalse(totp.verify_login(self.user.id, code)) + + +class AgenticFallbackJourney(unittest.TestCase): + """Journey 8: no news/COL keys, but a provider key + mocked DuckDuckGo → + the agentic fallback synthesises a briefing that reaches company analysis.""" + + def setUp(self): + e2e.fresh_db() + self.user = e2e.make_user() + + def test_fallback_briefing_used(self): + from unittest import mock + + from tools.data_sources import fetch_company_news + + ddg_results = [ + {"title": "Acme raises $60M Series B", "snippet": "Led by Foo Ventures.", + "url": "https://news.example/acme"}, + ] + # Provider key set (via mock_llm) but re-enable the fallback and mock DDG. + with e2e.mock_llm(), \ + mock.patch.dict(os.environ, {"COMPANY_RESEARCH_FALLBACK": "1"}), \ + mock.patch("tools.company_research.ddg_search", return_value=ddg_results), \ + mock.patch("tools.company_research.deep_fetch", return_value=None): + out = fetch_company_news("Acme") + self.assertIsNotNone(out) + # Synthesised by the (stubbed) LLM from the search snippets. + self.assertGreater(len(out), 50) + + +if __name__ == "__main__": + unittest.main() From d31e4c159f6b975fa9fa09eadfb7f920be10d4a0 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 8 Jun 2026 08:23:34 +0000 Subject: [PATCH 20/24] refactor: webhooks fire from the service layer; orchestrator surfaces both errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cleanups from the review: - Webhook dispatch for stage.added / application.saved moved from app.py into services/stages.add_stage and services/applications.save_analysis, so the webhooks now fire from EVERY entry point (REST API, bot, UI) instead of only the Streamlit handler — a real delivery gap, not just a test seam. dispatch_event_durable gains a cheap _has_active_subscriber() pre-check that skips the thread/queue (and, in tests, the shared-connection race) entirely when nobody is listening. - agents/orchestrator: surface BOTH company‖salary errors (the second was dropped) and convert an unexpected stage raise into an error result so one branch crashing can't lose the other branch's checkpoint. Adds a module logger. - utils/llm: replace the three print() calls (incl. the per-attempt failure log) with structured logger calls so they reach the JSON drain. - tests: journey 5 (add_stage → webhook delivery recorded) + orchestrator both-errors-surface. CLAUDE.md conventions updated (TOTP encryption, OAuth verified-link rule, service-layer webhook dispatch). Full suite green (633), ruff/mypy/bandit clean. https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd --- CLAUDE.md | 18 ++++++--- agents/orchestrator.py | 25 ++++++++---- app.py | 36 ++--------------- services/applications.py | 17 +++++++- services/stages.py | 19 ++++++++- services/webhooks.py | 22 ++++++++++ tests/test_phase41_e2e_journeys.py | 64 ++++++++++++++++++++++++++++++ utils/llm.py | 11 +++-- 8 files changed, 162 insertions(+), 50 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 256b4d3..82272a7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -94,12 +94,20 @@ mode** (sample data, clearly labelled). `DATABASE_URL` unset ⇒ SQLite at (not 403)** for another user's resource so IDs can't be enumerated. - **Best-effort side-effects never break the main flow.** Notifications (Telegram/email/webhooks) and audit writes log-and-continue; they must not - raise into the user action that triggered them. Webhooks dispatch on a - daemon thread. + raise into the user action that triggered them. The `stage.added` / + `application.saved` webhooks dispatch from the **service layer** + (`services/stages`, `services/applications`) so every entry point (UI, API, + bot) fires them; `dispatch_event_durable` skips work entirely when no active + subscriber exists, else enqueues a retrying Celery task (or a daemon thread + without a broker). - **Secrets are bcrypt-hashed at rest**: passwords, reset tokens, 2FA backup - codes, API tokens (with an indexed 8-char prefix for fast lookup). TOTP - secrets are stored plaintext by design (documented; envelope-encrypt for - hardened prod). + codes, API tokens (with an indexed 8-char prefix for fast lookup). The TOTP + secret is envelope-encrypted (`utils/crypto`, `enc:v1:…`) when + `SECRETS_ENCRYPTION_KEY` is set, else plaintext (dev/demo). +- **OAuth auto-link requires a provider-VERIFIED email.** `services/oauth` + only links an external identity to a pre-existing local account when the + provider asserts the email is verified (Google OIDC claim / GitHub verified + primary) — otherwise it refuses (anti-account-takeover). - **Migrations:** add a model field ⇒ add an Alembic migration. CI runs the full `up → down → up` on real Postgres. `db.session.reset_engine_for_testing` uses **StaticPool** so thread-hopping tests (bot handlers, Streamlit diff --git a/agents/orchestrator.py b/agents/orchestrator.py index 4f8f619..c164295 100644 --- a/agents/orchestrator.py +++ b/agents/orchestrator.py @@ -1,3 +1,4 @@ +import logging from concurrent.futures import ThreadPoolExecutor from typing import Callable, Dict, Optional, TypedDict @@ -16,6 +17,8 @@ ) from utils.timing import timed_block +logger = logging.getLogger(__name__) + class JobAnalysisState(TypedDict, total=False): """State threaded through the analysis pipeline.""" @@ -111,14 +114,20 @@ def _run(stage_name, fn, s): futures["company"] = pool.submit(_run, "company", company_analyzer.analyze, dict(worker_state)) if not salary_done: futures["salary"] = pool.submit(_run, "salary", salary_analyzer.analyze, dict(worker_state)) - results = {name: f.result() for name, f in futures.items()} - - # Surface the first error from either branch — but persist whichever - # half succeeded so a retry doesn't redo it. - error = next( - (r.get("error") for r in results.values() if r.get("error")), - "", - ) + # Capture each branch's outcome, converting an unexpected raise into an + # error result so one branch crashing can't lose the other's checkpoint. + results = {} + for name, f in futures.items(): + try: + results[name] = f.result() + except Exception as exc: # noqa: BLE001 - surfaced via state["error"] + logger.warning("Stage %s raised: %s", name, exc) + results[name] = {"error": f"{name} stage failed: {exc}"} + + # Surface BOTH branch errors (don't silently drop the second), but persist + # whichever half succeeded so a retry doesn't redo it. + branch_errors = [r.get("error") for r in results.values() if r.get("error")] + error = "; ".join(branch_errors) if "company" in results and not results["company"].get("error"): state["company_analysis"] = results["company"].get("company_analysis", {}) diff --git a/app.py b/app.py index a886ec2..9e43ad8 100644 --- a/app.py +++ b/app.py @@ -139,7 +139,6 @@ from services.webhooks import ( WebhookError, delete_webhook, - dispatch_event_durable, list_webhooks, register_webhook, ) @@ -1242,23 +1241,14 @@ def update_progress(stage, progress, stage_info=None): save_notes = st.text_input("Notes (optional)", "") if st.form_submit_button("💾 Save analysis", type="primary"): try: - saved_rec = save_analysis( + save_analysis( user_id=st.session_state.user_id, manual_inputs=st.session_state.last_inputs, analysis_result=st.session_state.last_result, status=save_status, notes=save_notes or None, ) - dispatch_event_durable( - st.session_state.user_id, "application.saved", - { - "application_id": saved_rec.id, - "company_name": saved_rec.company_name, - "job_title": saved_rec.job_title, - "verdict": saved_rec.verdict, - "status": saved_rec.status, - }, - ) + # The application.saved webhook now fires inside save_analysis. st.success("Saved to My Applications.") except ApplicationError as exc: st.error(str(exc)) @@ -1568,19 +1558,10 @@ def _matches(rec) -> bool: st.session_state.user_id, rec.id, kind=kind, ) # Best-effort Telegram notification — never raises. + # (The stage.added webhook fires inside add_stage.) notify_stage_added( st.session_state.user_id, rec, new_stage, ) - dispatch_event_durable( - st.session_state.user_id, "stage.added", - { - "application_id": rec.id, - "company_name": rec.company_name, - "job_title": rec.job_title, - "stage": kind, - "occurred_on": new_stage.occurred_on.isoformat(), - }, - ) st.rerun() except StageError as exc: st.error(str(exc)) @@ -1621,16 +1602,7 @@ def _matches(rec) -> bool: notify_stage_added( st.session_state.user_id, rec, new_stage, ) - dispatch_event_durable( - st.session_state.user_id, "stage.added", - { - "application_id": rec.id, - "company_name": rec.company_name, - "job_title": rec.job_title, - "stage": new_stage.kind, - "occurred_on": new_stage.occurred_on.isoformat(), - }, - ) + # stage.added webhook fires inside add_stage. st.success("Stage added.") st.rerun() except StageError as exc: diff --git a/services/applications.py b/services/applications.py index c1f20bf..fda6401 100644 --- a/services/applications.py +++ b/services/applications.py @@ -94,7 +94,22 @@ def save_analysis( session.add(app) session.commit() session.refresh(app) - return _to_record(app) + record = _to_record(app) + + # Fire the webhook from the service so the API save-on-analyze path delivers + # it too (it previously fired only from the Streamlit save handler). + # Best-effort: dispatch_event_durable never raises into the caller. + from services.webhooks import dispatch_event_durable + dispatch_event_durable( + user_id, "application.saved", + { + "application_id": record.id, + "company_name": record.company_name, + "job_title": record.job_title, + "verdict": record.verdict, + }, + ) + return record def list_applications(user_id: int) -> List[ApplicationRecord]: diff --git a/services/stages.py b/services/stages.py index 3198c4b..3e47152 100644 --- a/services/stages.py +++ b/services/stages.py @@ -137,7 +137,24 @@ def add_stage( app.status = new_status session.commit() session.refresh(stage) - return _to_record(stage) + record = _to_record(stage) + company_name, job_title = app.company_name, app.job_title + + # Fire the webhook from the SERVICE so every entry point (UI, API, bot) + # delivers it — it previously lived only in the Streamlit handler. + # Best-effort: dispatch_event_durable never raises into the caller. + from services.webhooks import dispatch_event_durable + dispatch_event_durable( + user_id, "stage.added", + { + "application_id": application_id, + "company_name": company_name, + "job_title": job_title, + "stage": record.kind, + "occurred_on": record.occurred_on.isoformat(), + }, + ) + return record def list_stages(user_id: int, application_id: int) -> List[StageRecord]: diff --git a/services/webhooks.py b/services/webhooks.py index 6e93a1d..98ef853 100644 --- a/services/webhooks.py +++ b/services/webhooks.py @@ -237,6 +237,26 @@ def _celery_delivery_enabled() -> bool: return False +def _has_active_subscriber(user_id: int, event: str) -> bool: + """Whether the user has any active webhook subscribed to ``event``. + + A cheap pre-check so we don't spawn a delivery thread / enqueue a task (or, + in tests, race the in-memory connection) when nobody is listening — the + common case. Best-effort: a query failure returns False (skip dispatch). + """ + try: + with get_session() as session: + hooks = session.execute( + select(Webhook) + .where(Webhook.user_id == user_id) + .where(Webhook.active.is_(True)) + ).scalars().all() + return any(event in (h.events or []) for h in hooks) + except Exception as exc: # noqa: BLE001 - never raise into the caller + logger.warning("Webhook subscriber check failed: %s", exc) + return False + + def dispatch_event_durable(user_id: int, event: str, payload: dict) -> None: """Production dispatch entry point. @@ -245,6 +265,8 @@ def dispatch_event_durable(user_id: int, event: str, payload: dict) -> None: Without a broker: degrade to the fire-and-forget daemon thread. Never raises into the caller. """ + if not _has_active_subscriber(user_id, event): + return # nobody listening — skip the thread/queue entirely if not _celery_delivery_enabled(): dispatch_event_background(user_id, event, payload) return diff --git a/tests/test_phase41_e2e_journeys.py b/tests/test_phase41_e2e_journeys.py index f2e7338..686f400 100644 --- a/tests/test_phase41_e2e_journeys.py +++ b/tests/test_phase41_e2e_journeys.py @@ -200,6 +200,43 @@ def test_login_gate(self): self.assertFalse(totp.verify_login(self.user.id, code)) +class StageWebhookJourney(unittest.TestCase): + """Journey 5: a registered stage.added webhook fires when a stage is added + through the SERVICE (now entry-point-agnostic, not UI-only).""" + + def setUp(self): + e2e.fresh_db() + self.user = e2e.make_user() + from services.applications import save_analysis + self.app = save_analysis(self.user.id, _MANUAL, + {"verdict": {"verdict": "Recommended", "light": "green"}}) + + def test_add_stage_delivers_webhook(self): + from unittest import mock + + from services import webhooks + from services.stages import add_stage + from services.webhooks import list_deliveries, register_webhook + + register_webhook(self.user.id, "https://example.test/hook", ["stage.added"]) + + class _Ok: + status_code = 200 + text = "ok" + + # Run the (normally daemon-thread) dispatch inline for a deterministic + # assertion, and stub the outbound POST. + with mock.patch.object(webhooks, "dispatch_event_background", + side_effect=lambda u, e, p: webhooks.dispatch_event(u, e, p)), \ + mock.patch.object(webhooks.requests, "post", return_value=_Ok()): + add_stage(self.user.id, self.app.id, kind="applied") + + deliveries = list_deliveries(self.user.id) + self.assertEqual(len(deliveries), 1) + self.assertTrue(deliveries[0].success) + self.assertEqual(deliveries[0].event, "stage.added") + + class AgenticFallbackJourney(unittest.TestCase): """Journey 8: no news/COL keys, but a provider key + mocked DuckDuckGo → the agentic fallback synthesises a briefing that reaches company analysis.""" @@ -228,5 +265,32 @@ def test_fallback_briefing_used(self): self.assertGreater(len(out), 50) +class OrchestratorErrorSurfacingJourney(unittest.TestCase): + """Both parallel-stage errors are surfaced (the second isn't dropped), and a + branch that raises is converted to an error rather than losing the other's + checkpoint.""" + + def setUp(self): + e2e.fresh_db() + + def test_both_branch_errors_surface(self): + from unittest import mock + + from agents import orchestrator + + # company returns an error result; salary RAISES — both must reach the + # final error (and the raise must not crash the run). + with mock.patch.object(orchestrator.company_analyzer, "analyze", + return_value={"error": "company boom"}), \ + mock.patch.object(orchestrator.salary_analyzer, "analyze", + side_effect=RuntimeError("salary kaboom")): + result = orchestrator.run_analysis( + _POSTING, manual_inputs=_MANUAL, model="fast", + ) + err = result.get("error", "") + self.assertIn("company boom", err) + self.assertIn("kaboom", err) + + if __name__ == "__main__": unittest.main() diff --git a/utils/llm.py b/utils/llm.py index 36497f8..44caf76 100644 --- a/utils/llm.py +++ b/utils/llm.py @@ -15,11 +15,14 @@ from __future__ import annotations +import logging import os import re import time from typing import Optional +logger = logging.getLogger(__name__) + # --------------------------------------------------------------------------- # Provider configuration # --------------------------------------------------------------------------- @@ -66,7 +69,7 @@ def _record_usage(provider: str, model: str, usage: Optional[dict]) -> None: usage_service.record_completion(provider, model, usage) except Exception as exc: # noqa: BLE001 - accounting is best-effort - print(f"[llm] usage accounting skipped: {exc}") + logger.warning("usage accounting skipped: %s", exc) def _completion_cache_key( @@ -171,7 +174,7 @@ def get_completion( provider = get_active_provider() if provider is None: - print("[llm] Demo mode (no provider key set) — returning sample data.") + logger.info("Demo mode (no provider key set) — returning sample data.") return generate_sample_response(prompt) resolved_model = resolve_model(provider, model) @@ -216,7 +219,9 @@ def get_completion( return result except Exception as exc: # noqa: BLE001 - retried/surfaced below last_error = exc - print(f"[llm] {provider} call failed (attempt {attempt}/{_MAX_RETRIES}): {exc}") + logger.warning( + "%s call failed (attempt %d/%d): %s", provider, attempt, _MAX_RETRIES, exc + ) if attempt < _MAX_RETRIES: time.sleep(2 ** (attempt - 1)) # 1s, 2s, 4s ... From 9ff823c2a12db465ec93bde5d174119d79f05c97 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 8 Jun 2026 09:31:26 +0000 Subject: [PATCH 21/24] refactor: central typed config layer + shared ownership helper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two maintainability cleanups from the review. Config (utils/env.py): - Typed env accessors env_str/env_bool/env_int/env_float with one place for parsing semantics. env_bool now accepts 1/true/yes/on (any case) — the old `== "1"` foot-gun where true/yes silently read as false is gone; bad numeric/bool values warn and fall back instead of crashing. - Every read is recorded; utils.config.log_effective_config() logs the resolved NON-default config at startup (api/main, app.py) so a typo'd override becomes visible instead of silently using the default. Secrets are not read through this, so only tuning knobs are surfaced (never keys). - Migrated ~36 inline os.getenv parses across services/utils/tools/api/worker/ bot/db to the helpers (12 boolean flags + 24 numeric limits/timeouts/budgets). Ownership (services/_ownership.py): - require_owned(session, Model, id, user_id, exc, msg) centralises the fetch-by-pk + "missing OR cross-user -> raise" check behind the 404-not-403 rule. Migrated all 28 raise-style call sites across 11 services to it, so a future site can't forget the user_id comparison. timeline's return-[] read is left as-is. Tests: utils.env parsing + effective-config (test_phase42); existing cross-user suites continue to guard the migrated ownership sites. mypy clean (76 files), ruff/bandit clean, full suite green (644). https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd --- api/main.py | 9 ++- api/security.py | 4 +- app.py | 9 ++- bot/handlers.py | 6 +- db/session.py | 3 +- services/_ownership.py | 38 +++++++++++ services/api_tokens.py | 5 +- services/applications.py | 13 ++-- services/background_analysis.py | 13 ++-- services/checkpoint.py | 4 +- services/email.py | 6 +- services/master_cv.py | 13 ++-- services/oauth.py | 3 +- services/projects.py | 9 +-- services/rate_limit.py | 7 +- services/reminders.py | 9 +-- services/sharing.py | 13 ++-- services/stages.py | 13 ++-- services/tailoring.py | 21 ++---- services/telegram_link.py | 3 +- services/usage.py | 14 ++-- services/webhooks.py | 29 +++----- tests/test_phase42_config.py | 112 +++++++++++++++++++++++++++++++ tools/browser_scraper.py | 7 +- tools/company_research.py | 7 +- tools/data_sources.py | 4 +- tools/url_ingest.py | 8 ++- utils/cache.py | 4 +- utils/config.py | 20 ++++++ utils/env.py | 113 ++++++++++++++++++++++++++++++++ utils/llm.py | 10 +-- worker/celery_app.py | 4 +- 32 files changed, 391 insertions(+), 142 deletions(-) create mode 100644 services/_ownership.py create mode 100644 tests/test_phase42_config.py create mode 100644 utils/env.py diff --git a/api/main.py b/api/main.py index 3137360..6a20828 100644 --- a/api/main.py +++ b/api/main.py @@ -22,6 +22,7 @@ from api.routes import router from api.security import add_security_headers from db.session import init_db +from utils.env import env_bool, env_int from utils.logging_setup import configure as configure_logging logger = logging.getLogger(__name__) @@ -32,6 +33,8 @@ def create_app() -> FastAPI: configure_logging() + from utils.config import log_effective_config + log_effective_config() init_db() app = FastAPI( title="JobOffer Scanner API", @@ -55,7 +58,7 @@ def metrics(authorization: Optional[str] = Header(default=None)): readable. Metrics are per-process; Prometheus aggregates across scraped instances. """ - if os.getenv("METRICS_ENABLED") != "1": + if not env_bool("METRICS_ENABLED"): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND) token = os.getenv("METRICS_TOKEN") if token and authorization != f"Bearer {token}": @@ -82,8 +85,8 @@ def main() -> None: uvicorn.run( "api.main:app", host=os.getenv("API_HOST", "127.0.0.1"), - port=int(os.getenv("API_PORT", "8000")), - reload=os.getenv("API_RELOAD") == "1", + port=env_int("API_PORT", 8000), + reload=env_bool("API_RELOAD"), ) diff --git a/api/security.py b/api/security.py index e620b21..d7dfb49 100644 --- a/api/security.py +++ b/api/security.py @@ -28,13 +28,15 @@ from starlette.types import ASGIApp, Message, Receive, Scope, Send +from utils.env import env_bool + def _csp() -> str: return os.getenv("API_CSP", "default-src 'none'; frame-ancestors 'none'") def _hsts_value() -> str | None: - if os.getenv("API_ENABLE_HSTS") != "1": + if not env_bool("API_ENABLE_HSTS"): return None max_age = os.getenv("API_HSTS_MAX_AGE", "63072000") return f"max-age={max_age}; includeSubDomains" diff --git a/app.py b/app.py index 9e43ad8..837677a 100644 --- a/app.py +++ b/app.py @@ -152,6 +152,7 @@ from tools.url_ingest import fetch_job_posting, is_url from utils.config import check_environment_setup, print_environment_status from utils.diff import inline_diff_html, unified_diff +from utils.env import env_bool from utils.logging_setup import configure as configure_logging # Page config @@ -159,6 +160,10 @@ configure_logging() print_environment_status() +if not st.session_state.get("_config_logged"): + from utils.config import log_effective_config + log_effective_config() + st.session_state["_config_logged"] = True init_db() @@ -402,7 +407,7 @@ def render_auth() -> None: # Self-hosted operator convenience — BOTH the UI display # and the log line are gated on the same opt-in flag so a # production deploy never leaks reset tokens to stdout/logs. - if os.getenv("RESET_TOKEN_SURFACE_IN_UI") == "1": + if env_bool("RESET_TOKEN_SURFACE_IN_UI"): st.code(token, language=None) st.caption("RESET_TOKEN_SURFACE_IN_UI=1 — disable in production.") print(f"[auth] reset token for {forgot_email}: {token}") @@ -454,7 +459,7 @@ def _render_verification_gate() -> None: if is_verified(st.session_state.user_id): return - hard_gate = os.getenv("REQUIRE_EMAIL_VERIFICATION") == "1" + hard_gate = env_bool("REQUIRE_EMAIL_VERIFICATION") box = st.warning if hard_gate else st.info box( "📧 Please verify your email" diff --git a/bot/handlers.py b/bot/handlers.py index d494651..0654733 100644 --- a/bot/handlers.py +++ b/bot/handlers.py @@ -10,7 +10,6 @@ import asyncio import logging -import os import time from dataclasses import dataclass from typing import Awaitable, Callable, Optional @@ -28,6 +27,7 @@ unlink, ) from tools.url_ingest import fetch_job_posting, is_url +from utils.env import env_float logger = logging.getLogger(__name__) @@ -209,8 +209,8 @@ async def handle_analyze(reply: Reply, args: str) -> None: # --------------------------------------------------------------------------- # Bot-level poll cadence + timeout for queued tasks. -_BOT_POLL_INTERVAL = float(os.getenv("BOT_TASK_POLL_INTERVAL", "2.0")) -_BOT_POLL_TIMEOUT = float(os.getenv("BOT_TASK_TIMEOUT", "600")) +_BOT_POLL_INTERVAL = env_float("BOT_TASK_POLL_INTERVAL", 2.0) +_BOT_POLL_TIMEOUT = env_float("BOT_TASK_TIMEOUT", 600.0) async def _run_analysis_for_bot(posting_text: str) -> dict: diff --git a/db/session.py b/db/session.py index bd5b0c7..6b06d18 100644 --- a/db/session.py +++ b/db/session.py @@ -20,6 +20,7 @@ from sqlalchemy.orm import Session, sessionmaker from db.models import Base +from utils.env import env_bool def _enable_sqlite_fk(engine: Engine) -> None: @@ -80,7 +81,7 @@ def init_db() -> None: global _initialized if _initialized: return - if os.getenv("USE_ALEMBIC") == "1": + if env_bool("USE_ALEMBIC"): logger.info("USE_ALEMBIC=1 — skipping create_all; run `alembic upgrade head`.") else: Base.metadata.create_all(get_engine()) diff --git a/services/_ownership.py b/services/_ownership.py new file mode 100644 index 0000000..9d8991d --- /dev/null +++ b/services/_ownership.py @@ -0,0 +1,38 @@ +"""Shared ownership-scoping helper. + +Every owned read/write fetches a row by primary key and refuses it when it's +missing OR belongs to another user — the security-critical check behind the +"return 404, not 403" anti-enumeration rule. Centralising it here means a future +call site can't silently forget the ``user_id`` comparison, and the policy lives +in exactly one place. + +Usage:: + + app = require_owned(session, Application, application_id, user_id, + ApplicationError, "Application not found.") + +Raises ``exc(message)`` (the caller's service-specific error) on a missing or +cross-user row; returns the owned object otherwise. +""" + +from __future__ import annotations + +from typing import Type, TypeVar + +from sqlalchemy.orm import Session + +T = TypeVar("T") + + +def require_owned( + session: Session, + model: Type[T], + obj_id: object, + user_id: int, + exc: Type[Exception], + message: str, +) -> T: + obj = session.get(model, obj_id) + if obj is None or getattr(obj, "user_id", None) != user_id: + raise exc(message) + return obj diff --git a/services/api_tokens.py b/services/api_tokens.py index 01df632..aa255ea 100644 --- a/services/api_tokens.py +++ b/services/api_tokens.py @@ -31,6 +31,7 @@ from db.models import ApiToken from db.session import get_session +from services._ownership import require_owned from services.audit import record as _audit logger = logging.getLogger(__name__) @@ -147,9 +148,7 @@ def list_for_user(user_id: int) -> List[ApiTokenRecord]: def revoke(user_id: int, token_id: int) -> None: with get_session() as session: - row = session.get(ApiToken, token_id) - if row is None or row.user_id != user_id: - raise ApiTokenError("Token not found.") + row = require_owned(session, ApiToken, token_id, user_id, ApiTokenError, "Token not found.") if row.revoked_at is None: row.revoked_at = datetime.utcnow() session.commit() diff --git a/services/applications.py b/services/applications.py index fda6401..6c38a93 100644 --- a/services/applications.py +++ b/services/applications.py @@ -18,6 +18,7 @@ from db.models import APPLICATION_STATUSES, Application from db.session import get_session +from services._ownership import require_owned class ApplicationError(ValueError): @@ -124,9 +125,7 @@ def list_applications(user_id: int) -> List[ApplicationRecord]: def get_application(user_id: int, application_id: int) -> ApplicationRecord: with get_session() as session: - app = session.get(Application, application_id) - if app is None or app.user_id != user_id: - raise ApplicationError("Application not found.") + app = require_owned(session, Application, application_id, user_id, ApplicationError, "Application not found.") return _to_record(app) @@ -139,9 +138,7 @@ def update_status( if status is not None and status not in APPLICATION_STATUSES: raise ApplicationError(f"Unknown status {status!r}.") with get_session() as session: - app = session.get(Application, application_id) - if app is None or app.user_id != user_id: - raise ApplicationError("Application not found.") + app = require_owned(session, Application, application_id, user_id, ApplicationError, "Application not found.") if status is not None: app.status = status if notes is not None: @@ -153,9 +150,7 @@ def update_status( def delete_application(user_id: int, application_id: int) -> None: with get_session() as session: - app = session.get(Application, application_id) - if app is None or app.user_id != user_id: - raise ApplicationError("Application not found.") + app = require_owned(session, Application, application_id, user_id, ApplicationError, "Application not found.") session.delete(app) session.commit() # Audit AFTER commit so a failed delete isn't recorded as if it happened. diff --git a/services/background_analysis.py b/services/background_analysis.py index 6e86f46..5927db7 100644 --- a/services/background_analysis.py +++ b/services/background_analysis.py @@ -21,6 +21,7 @@ from db.models import BACKGROUND_TERMINAL_STATES, BackgroundAnalysis from db.session import get_session +from services._ownership import require_owned from services.analysis_runner import ( async_enabled, enqueue_analysis, @@ -147,9 +148,7 @@ def list_for_user(user_id: int) -> List[BackgroundAnalysisRecord]: def get(user_id: int, analysis_id: int) -> BackgroundAnalysisRecord: with get_session() as session: - row = session.get(BackgroundAnalysis, analysis_id) - if row is None or row.user_id != user_id: - raise BackgroundAnalysisError("Background analysis not found.") + row = require_owned(session, BackgroundAnalysis, analysis_id, user_id, BackgroundAnalysisError, "Background analysis not found.") return _to_record(row) @@ -166,9 +165,7 @@ def refresh_state(user_id: int, analysis_id: int) -> BackgroundAnalysisRecord: pure reads. """ with get_session() as session: - row = session.get(BackgroundAnalysis, analysis_id) - if row is None or row.user_id != user_id: - raise BackgroundAnalysisError("Background analysis not found.") + row = require_owned(session, BackgroundAnalysis, analysis_id, user_id, BackgroundAnalysisError, "Background analysis not found.") if row.state in BACKGROUND_TERMINAL_STATES: return _to_record(row) @@ -225,9 +222,7 @@ def _stringify_error(payload: Any) -> str: def delete(user_id: int, analysis_id: int) -> None: with get_session() as session: - row = session.get(BackgroundAnalysis, analysis_id) - if row is None or row.user_id != user_id: - raise BackgroundAnalysisError("Background analysis not found.") + row = require_owned(session, BackgroundAnalysis, analysis_id, user_id, BackgroundAnalysisError, "Background analysis not found.") session.delete(row) session.commit() diff --git a/services/checkpoint.py b/services/checkpoint.py index 8747aad..70511cd 100644 --- a/services/checkpoint.py +++ b/services/checkpoint.py @@ -30,6 +30,8 @@ from dataclasses import dataclass, field from typing import Any, Dict, Optional, Tuple +from utils.env import env_int + logger = logging.getLogger(__name__) @@ -114,7 +116,7 @@ class RedisCheckpointStore: """ _NS = "joc:ckpt:" - _TTL = int(os.getenv("CHECKPOINT_TTL_SECONDS", "3600")) + _TTL = env_int("CHECKPOINT_TTL_SECONDS", 3600) def __init__(self, url: str) -> None: import redis # lazy diff --git a/services/email.py b/services/email.py index cf3fd3b..1af0593 100644 --- a/services/email.py +++ b/services/email.py @@ -20,6 +20,8 @@ from email.message import EmailMessage from typing import Optional +from utils.env import env_bool, env_int + logger = logging.getLogger(__name__) @@ -50,10 +52,10 @@ def send_email(to: str, subject: str, body: str) -> bool: # email_configured() above guarantees these are present; the "" defaults # are only to satisfy the type checker (str, not str | None). host = os.getenv("SMTP_HOST", "") - port = int(os.getenv("SMTP_PORT", "587")) + port = env_int("SMTP_PORT", 587) username = os.getenv("SMTP_USERNAME", "") password = os.getenv("SMTP_PASSWORD", "") - use_tls = os.getenv("SMTP_USE_TLS", "1") == "1" + use_tls = env_bool("SMTP_USE_TLS", True) try: with smtplib.SMTP(host, port, timeout=15) as server: diff --git a/services/master_cv.py b/services/master_cv.py index 13b8abb..85c1610 100644 --- a/services/master_cv.py +++ b/services/master_cv.py @@ -18,6 +18,7 @@ from db.models import MasterCV, MasterCVRevision from db.session import get_session +from services._ownership import require_owned from tools.resume_tools import extract_resume_text # PDF/DOCX/TXT parser from utils.llm import get_completion from utils.security import wrap_untrusted @@ -154,9 +155,7 @@ def restore_revision(user_id: int, revision_id: int) -> MasterCVRecord: reversible), then writes the revision's content as the current master CV. """ with get_session() as session: - rev = session.get(MasterCVRevision, revision_id) - if rev is None or rev.user_id != user_id: - raise MasterCVError("Revision not found.") + rev = require_owned(session, MasterCVRevision, revision_id, user_id, MasterCVError, "Revision not found.") cv = session.execute( select(MasterCV).where(MasterCV.user_id == user_id) ).scalar_one_or_none() @@ -181,9 +180,7 @@ def restore_revision(user_id: int, revision_id: int) -> MasterCVRecord: def delete_revision(user_id: int, revision_id: int) -> None: with get_session() as session: - rev = session.get(MasterCVRevision, revision_id) - if rev is None or rev.user_id != user_id: - raise MasterCVError("Revision not found.") + rev = require_owned(session, MasterCVRevision, revision_id, user_id, MasterCVError, "Revision not found.") session.delete(rev) session.commit() @@ -198,9 +195,7 @@ def diff_revision_against_current(user_id: int, revision_id: int) -> str: from utils.diff import unified_diff # local import — keeps the module light with get_session() as session: - rev = session.get(MasterCVRevision, revision_id) - if rev is None or rev.user_id != user_id: - raise MasterCVError("Revision not found.") + rev = require_owned(session, MasterCVRevision, revision_id, user_id, MasterCVError, "Revision not found.") cv = session.execute( select(MasterCV).where(MasterCV.user_id == user_id) ).scalar_one_or_none() diff --git a/services/oauth.py b/services/oauth.py index a645396..072ff7c 100644 --- a/services/oauth.py +++ b/services/oauth.py @@ -38,10 +38,11 @@ from db.session import get_session from services.audit import record as _audit from services.auth import AuthedUser, create_oauth_user, find_user_by_email +from utils.env import env_float logger = logging.getLogger(__name__) -_HTTP_TIMEOUT = float(os.getenv("OAUTH_HTTP_TIMEOUT", "10")) +_HTTP_TIMEOUT = env_float("OAUTH_HTTP_TIMEOUT", 10.0) class OAuthError(ValueError): diff --git a/services/projects.py b/services/projects.py index 2eaf135..a4cceee 100644 --- a/services/projects.py +++ b/services/projects.py @@ -16,6 +16,7 @@ from db.models import Project from db.session import get_session +from services._ownership import require_owned class ProjectError(ValueError): @@ -114,9 +115,7 @@ def update_project( fields["highlights"] = _coerce_highlights(fields["highlights"]) with get_session() as session: - p = session.get(Project, project_id) - if p is None or p.user_id != user_id: - raise ProjectError("Project not found.") + p = require_owned(session, Project, project_id, user_id, ProjectError, "Project not found.") for k, v in fields.items(): if hasattr(p, k): # Normalize empty-string strings to None for nullable columns. @@ -130,9 +129,7 @@ def update_project( def delete_project(user_id: int, project_id: int) -> None: with get_session() as session: - p = session.get(Project, project_id) - if p is None or p.user_id != user_id: - raise ProjectError("Project not found.") + p = require_owned(session, Project, project_id, user_id, ProjectError, "Project not found.") session.delete(p) session.commit() diff --git a/services/rate_limit.py b/services/rate_limit.py index 35951e4..ee86d1e 100644 --- a/services/rate_limit.py +++ b/services/rate_limit.py @@ -135,12 +135,7 @@ def reset(self, identifier: str) -> None: # Defaults tuned for "hostile but not DoS" — generous enough for forgetful # users, strict enough that credential-stuffing or runaway costs get blocked. -def _env_int(name: str, default: int) -> int: - try: - return int(os.getenv(name, str(default))) - except ValueError: - return default - +from utils.env import env_int as _env_int # noqa: E402 LOGIN_LIMITER = RateLimiter( "login", diff --git a/services/reminders.py b/services/reminders.py index c9830a4..fa94767 100644 --- a/services/reminders.py +++ b/services/reminders.py @@ -34,6 +34,7 @@ TelegramLink, ) from db.session import get_session +from services._ownership import require_owned from services.telegram_link import send_to_chat logger = logging.getLogger(__name__) @@ -179,18 +180,14 @@ def snooze_application( user_id: int, application_id: int, until: date_cls, ) -> None: with get_session() as session: - app = session.get(Application, application_id) - if app is None or app.user_id != user_id: - raise PermissionError("Application not found.") + app = require_owned(session, Application, application_id, user_id, PermissionError, "Application not found.") app.snooze_reminders_until = until session.commit() def unsnooze_application(user_id: int, application_id: int) -> None: with get_session() as session: - app = session.get(Application, application_id) - if app is None or app.user_id != user_id: - raise PermissionError("Application not found.") + app = require_owned(session, Application, application_id, user_id, PermissionError, "Application not found.") app.snooze_reminders_until = None session.commit() diff --git a/services/sharing.py b/services/sharing.py index 025648f..71e2845 100644 --- a/services/sharing.py +++ b/services/sharing.py @@ -30,6 +30,7 @@ from db.models import Application, ApplicationShare from db.session import get_session +from services._ownership import require_owned from services.audit import record as _audit @@ -95,9 +96,7 @@ def create_share( to rotate. """ with get_session() as session: - app = session.get(Application, application_id) - if app is None or app.user_id != user_id: - raise ShareError("Application not found.") + require_owned(session, Application, application_id, user_id, ShareError, "Application not found.") expires_at = None if ttl_days and ttl_days > 0: expires_at = datetime.utcnow() + timedelta(days=ttl_days) @@ -129,9 +128,7 @@ def list_shares_for_application( user_id: int, application_id: int, ) -> List[ShareRecord]: with get_session() as session: - app = session.get(Application, application_id) - if app is None or app.user_id != user_id: - raise ShareError("Application not found.") + require_owned(session, Application, application_id, user_id, ShareError, "Application not found.") rows = session.execute( select(ApplicationShare) .where(ApplicationShare.application_id == application_id) @@ -142,9 +139,7 @@ def list_shares_for_application( def revoke(user_id: int, share_id: int) -> None: with get_session() as session: - share = session.get(ApplicationShare, share_id) - if share is None or share.user_id != user_id: - raise ShareError("Share not found.") + share = require_owned(session, ApplicationShare, share_id, user_id, ShareError, "Share not found.") if share.revoked_at is None: share.revoked_at = datetime.utcnow() session.commit() diff --git a/services/stages.py b/services/stages.py index 3e47152..9a00cc0 100644 --- a/services/stages.py +++ b/services/stages.py @@ -29,6 +29,7 @@ ApplicationStage, ) from db.session import get_session +from services._ownership import require_owned class StageError(ValueError): @@ -118,9 +119,7 @@ def add_stage( occurred_on = occurred_on or date_cls.today() with get_session() as session: - app = session.get(Application, application_id) - if app is None or app.user_id != user_id: - raise StageError("Application not found.") + app = require_owned(session, Application, application_id, user_id, StageError, "Application not found.") stage = ApplicationStage( application_id=application_id, kind=kind, @@ -159,9 +158,7 @@ def add_stage( def list_stages(user_id: int, application_id: int) -> List[StageRecord]: with get_session() as session: - app = session.get(Application, application_id) - if app is None or app.user_id != user_id: - raise StageError("Application not found.") + require_owned(session, Application, application_id, user_id, StageError, "Application not found.") rows = session.execute( select(ApplicationStage) .where(ApplicationStage.application_id == application_id) @@ -175,9 +172,7 @@ def delete_stage(user_id: int, stage_id: int) -> None: stage = session.get(ApplicationStage, stage_id) if stage is None: raise StageError("Stage not found.") - app = session.get(Application, stage.application_id) - if app is None or app.user_id != user_id: - raise StageError("Stage not found.") + app = require_owned(session, Application, stage.application_id, user_id, StageError, "Stage not found.") session.delete(stage) session.flush() # Re-derive status from the remaining stages. diff --git a/services/tailoring.py b/services/tailoring.py index 6f7386f..1706600 100644 --- a/services/tailoring.py +++ b/services/tailoring.py @@ -25,6 +25,7 @@ ApplicationArtifact, ) from db.session import get_session +from services._ownership import require_owned from services.constraint_check import ConstraintCheck, check_tailored_output from services.master_cv import get_master_cv from services.projects import projects_as_text @@ -99,9 +100,7 @@ def _to_record(a: ApplicationArtifact) -> ArtifactRecord: def _application_for(user_id: int, application_id: int) -> Application: with get_session() as session: - app = session.get(Application, application_id) - if app is None or app.user_id != user_id: - raise TailoringError("Application not found.") + app = require_owned(session, Application, application_id, user_id, TailoringError, "Application not found.") return app @@ -226,9 +225,7 @@ def recheck_artifact(user_id: int, artifact_id: int) -> ConstraintCheck: The new result is persisted on the artifact's ``meta.constraint_check``. """ with get_session() as session: - artifact = session.get(ApplicationArtifact, artifact_id) - if artifact is None or artifact.user_id != user_id: - raise TailoringError("Artifact not found.") + artifact = require_owned(session, ApplicationArtifact, artifact_id, user_id, TailoringError, "Artifact not found.") cv = get_master_cv(user_id) cv_raw = cv.raw_text if cv else "" projects_text = projects_as_text(user_id) @@ -369,9 +366,7 @@ def save_artifact( if kind not in ARTIFACT_KINDS: raise TailoringError(f"Unknown artifact kind {kind!r}.") with get_session() as session: - app = session.get(Application, application_id) - if app is None or app.user_id != user_id: - raise TailoringError("Application not found.") + require_owned(session, Application, application_id, user_id, TailoringError, "Application not found.") a = ApplicationArtifact( application_id=application_id, user_id=user_id, @@ -391,9 +386,7 @@ def list_artifacts( kind: Optional[str] = None, ) -> List[ArtifactRecord]: with get_session() as session: - app = session.get(Application, application_id) - if app is None or app.user_id != user_id: - raise TailoringError("Application not found.") + require_owned(session, Application, application_id, user_id, TailoringError, "Application not found.") q = select(ApplicationArtifact).where( ApplicationArtifact.application_id == application_id ).order_by(desc(ApplicationArtifact.created_at)) @@ -405,9 +398,7 @@ def list_artifacts( def delete_artifact(user_id: int, artifact_id: int) -> None: with get_session() as session: - a = session.get(ApplicationArtifact, artifact_id) - if a is None or a.user_id != user_id: - raise TailoringError("Artifact not found.") + a = require_owned(session, ApplicationArtifact, artifact_id, user_id, TailoringError, "Artifact not found.") session.delete(a) session.commit() from services.audit import record as _audit diff --git a/services/telegram_link.py b/services/telegram_link.py index 5079a52..3d8dee3 100644 --- a/services/telegram_link.py +++ b/services/telegram_link.py @@ -34,6 +34,7 @@ from db.models import TelegramLink, TelegramLinkBindingToken from db.session import get_session +from utils.env import env_float logger = logging.getLogger(__name__) @@ -42,7 +43,7 @@ BINDING_TOKEN_TTL = timedelta(minutes=15) _BINDING_TOKEN_BYTES = 16 -_TELEGRAM_HTTP_TIMEOUT = float(os.getenv("TELEGRAM_HTTP_TIMEOUT", "8")) +_TELEGRAM_HTTP_TIMEOUT = env_float("TELEGRAM_HTTP_TIMEOUT", 8.0) _TELEGRAM_BASE = "https://api.telegram.org" diff --git a/services/usage.py b/services/usage.py index d214000..f6c76f5 100644 --- a/services/usage.py +++ b/services/usage.py @@ -42,7 +42,6 @@ import contextlib import json import logging -import os from contextvars import ContextVar from datetime import datetime, timedelta from typing import Dict, Iterator, Optional, Tuple @@ -52,6 +51,7 @@ import utils.metrics as metrics from db.models import LlmUsage from db.session import get_session +from utils.env import env_float, env_int, env_str logger = logging.getLogger(__name__) @@ -111,7 +111,7 @@ def current_user() -> Optional[int]: # --------------------------------------------------------------------------- def _pricing_table() -> Dict[str, Tuple[float, float]]: - raw = os.getenv("LLM_PRICING_JSON") + raw = env_str("LLM_PRICING_JSON") if not raw: return _DEFAULT_PRICING try: @@ -182,17 +182,11 @@ def record_completion( # --------------------------------------------------------------------------- def _budget_usd() -> float: - try: - return float(os.getenv("LLM_BUDGET_USD", "0") or 0) - except ValueError: - return 0.0 + return env_float("LLM_BUDGET_USD", 0.0) def _budget_window_seconds() -> int: - try: - return int(os.getenv("LLM_BUDGET_WINDOW_SECONDS", str(30 * 24 * 3600))) - except ValueError: - return 30 * 24 * 3600 + return env_int("LLM_BUDGET_WINDOW_SECONDS", 30 * 24 * 3600) def spend_usd(user_id: int, window_seconds: Optional[int] = None) -> float: diff --git a/services/webhooks.py b/services/webhooks.py index 98ef853..5cd73d1 100644 --- a/services/webhooks.py +++ b/services/webhooks.py @@ -27,7 +27,6 @@ import hmac import json import logging -import os import secrets import threading from dataclasses import dataclass @@ -39,27 +38,23 @@ from db.models import WEBHOOK_EVENTS, Webhook, WebhookDelivery from db.session import get_session +from services._ownership import require_owned from services.audit import record as _audit +from utils.env import env_bool, env_float, env_int logger = logging.getLogger(__name__) -_DELIVERY_TIMEOUT = float(os.getenv("WEBHOOK_TIMEOUT", "8")) +_DELIVERY_TIMEOUT = env_float("WEBHOOK_TIMEOUT", 8.0) def _max_attempts() -> int: """Total delivery attempts before giving up (initial + retries).""" - try: - return max(1, int(os.getenv("WEBHOOK_MAX_ATTEMPTS", "5"))) - except ValueError: - return 5 + return max(1, env_int("WEBHOOK_MAX_ATTEMPTS", 5)) def _retry_backoff_base() -> float: """Base seconds for exponential retry backoff (base * 2**retry_index).""" - try: - return float(os.getenv("WEBHOOK_RETRY_BACKOFF", "10")) - except ValueError: - return 10.0 + return env_float("WEBHOOK_RETRY_BACKOFF", 10.0) def retry_delay_for(retry_index: int) -> float: @@ -149,18 +144,14 @@ def list_webhooks(user_id: int) -> List[WebhookRecord]: def set_active(user_id: int, webhook_id: int, active: bool) -> None: with get_session() as session: - wh = session.get(Webhook, webhook_id) - if wh is None or wh.user_id != user_id: - raise WebhookError("Webhook not found.") + wh = require_owned(session, Webhook, webhook_id, user_id, WebhookError, "Webhook not found.") wh.active = bool(active) session.commit() def delete_webhook(user_id: int, webhook_id: int) -> None: with get_session() as session: - wh = session.get(Webhook, webhook_id) - if wh is None or wh.user_id != user_id: - raise WebhookError("Webhook not found.") + wh = require_owned(session, Webhook, webhook_id, user_id, WebhookError, "Webhook not found.") session.delete(wh) session.commit() _audit("webhook.delete", user_id=user_id, details={"webhook_id": webhook_id}) @@ -227,7 +218,7 @@ def _run(): def _celery_delivery_enabled() -> bool: """True when a Celery broker is available for durable webhook delivery.""" - if os.getenv("WEBHOOK_ASYNC", "1") != "1": + if not env_bool("WEBHOOK_ASYNC", True): return False try: from worker.celery_app import get_celery_app @@ -366,9 +357,7 @@ def _deliver(hook: WebhookRecord, event: str, payload: dict) -> DeliveryRecord: def redeliver(user_id: int, delivery_id: int) -> DeliveryRecord: """Retry a previous delivery (re-POSTs the SAME payload to its webhook).""" with get_session() as session: - row = session.get(WebhookDelivery, delivery_id) - if row is None or row.user_id != user_id: - raise WebhookError("Delivery not found.") + row = require_owned(session, WebhookDelivery, delivery_id, user_id, WebhookError, "Delivery not found.") hook = session.get(Webhook, row.webhook_id) if hook is None: raise WebhookError("Webhook no longer exists.") diff --git a/tests/test_phase42_config.py b/tests/test_phase42_config.py new file mode 100644 index 0000000..7e2e6b6 --- /dev/null +++ b/tests/test_phase42_config.py @@ -0,0 +1,112 @@ +"""P3 cleanup: typed env helpers + effective-config logging (utils.env). + +Guards the shared parsing semantics — notably env_bool accepting true/yes/on +(the old == "1" foot-gun) — and the effective_config record used by +utils.config.log_effective_config. +""" + +from __future__ import annotations + +import os +import sys +import unittest +from unittest import mock + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + + +class EnvBoolTests(unittest.TestCase): + def setUp(self): + from utils import env + env.reset_for_testing() + + def test_truthy_spellings(self): + from utils.env import env_bool + for val in ("1", "true", "TRUE", "Yes", "on", " on "): + with mock.patch.dict(os.environ, {"X": val}): + self.assertTrue(env_bool("X"), val) + + def test_falsy_spellings(self): + from utils.env import env_bool + for val in ("0", "false", "no", "off", ""): + with mock.patch.dict(os.environ, {"X": val}): + self.assertFalse(env_bool("X", default=True) if val == "" else env_bool("X")) + + def test_unset_uses_default(self): + from utils.env import env_bool + os.environ.pop("MISSING", None) + self.assertTrue(env_bool("MISSING", default=True)) + self.assertFalse(env_bool("MISSING", default=False)) + + def test_unrecognised_warns_and_uses_default(self): + from utils.env import env_bool + with mock.patch.dict(os.environ, {"X": "maybe"}): + self.assertTrue(env_bool("X", default=True)) + self.assertFalse(env_bool("X", default=False)) + + +class EnvNumericTests(unittest.TestCase): + def test_int_parses_and_defaults(self): + from utils.env import env_int + with mock.patch.dict(os.environ, {"N": "42"}): + self.assertEqual(env_int("N", 7), 42) + with mock.patch.dict(os.environ, {"N": "notint"}): + self.assertEqual(env_int("N", 7), 7) + os.environ.pop("N", None) + self.assertEqual(env_int("N", 7), 7) + + def test_empty_string_is_default(self): + from utils.env import env_float, env_int + with mock.patch.dict(os.environ, {"N": "", "F": ""}): + self.assertEqual(env_int("N", 5), 5) + self.assertEqual(env_float("F", 1.5), 1.5) + + def test_float_parses(self): + from utils.env import env_float + with mock.patch.dict(os.environ, {"F": "2.5"}): + self.assertEqual(env_float("F", 1.0), 2.5) + + +class EffectiveConfigTests(unittest.TestCase): + def setUp(self): + from utils import env + env.reset_for_testing() + + def test_records_only_overrides_by_default(self): + from utils.env import effective_config, env_bool, env_int + os.environ.pop("UNSET_FLAG", None) + env_bool("UNSET_FLAG", default=False) # default, not recorded as override + with mock.patch.dict(os.environ, {"SET_N": "9"}): + env_int("SET_N", 1) + cfg = effective_config() + self.assertIn("SET_N", cfg) + self.assertEqual(cfg["SET_N"], 9) + self.assertNotIn("UNSET_FLAG", cfg) + + def test_log_effective_config_returns_overrides(self): + from utils.config import log_effective_config + from utils.env import env_bool, reset_for_testing + reset_for_testing() + with mock.patch.dict(os.environ, {"FEATURE_X": "true"}): + env_bool("FEATURE_X") + logged = log_effective_config() + self.assertEqual(logged.get("FEATURE_X"), True) + + +class MigratedCallSiteTests(unittest.TestCase): + """A couple of real call sites now honour true/yes (not just "1").""" + + def test_browser_enabled_accepts_true(self): + from tools.browser_scraper import browser_enabled + with mock.patch.dict(os.environ, {"BROWSER_SCRAPER_ENABLED": "true"}): + self.assertTrue(browser_enabled()) + + def test_company_fallback_disabled_by_false(self): + import tools.company_research as cr + with mock.patch.object(cr, "get_active_provider", return_value="openai"), \ + mock.patch.dict(os.environ, {"COMPANY_RESEARCH_FALLBACK": "false"}): + self.assertFalse(cr.fallback_enabled()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/browser_scraper.py b/tools/browser_scraper.py index 281abf7..c5932c2 100644 --- a/tools/browser_scraper.py +++ b/tools/browser_scraper.py @@ -23,15 +23,16 @@ from __future__ import annotations import logging -import os import re from typing import Dict, Optional from bs4 import BeautifulSoup +from utils.env import env_bool, env_int + logger = logging.getLogger(__name__) -_RENDER_TIMEOUT_MS = int(os.getenv("BROWSER_RENDER_TIMEOUT_MS", "30000")) +_RENDER_TIMEOUT_MS = env_int("BROWSER_RENDER_TIMEOUT_MS", 30000) _USER_AGENT = ( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/124.0 Safari/537.36" @@ -39,7 +40,7 @@ def browser_enabled() -> bool: - return os.getenv("BROWSER_SCRAPER_ENABLED") == "1" + return env_bool("BROWSER_SCRAPER_ENABLED") # --------------------------------------------------------------------------- diff --git a/tools/company_research.py b/tools/company_research.py index 4570e93..fe60c43 100644 --- a/tools/company_research.py +++ b/tools/company_research.py @@ -37,13 +37,14 @@ import requests +from utils.env import env_bool, env_float, env_int from utils.llm import get_active_provider, get_completion from utils.security import wrap_untrusted logger = logging.getLogger(__name__) _DDG_HTML = "https://html.duckduckgo.com/html/" -_HTTP_TIMEOUT = float(os.getenv("RESEARCH_HTTP_TIMEOUT", "10")) +_HTTP_TIMEOUT = env_float("RESEARCH_HTTP_TIMEOUT", 10.0) _USER_AGENT = ( "Mozilla/5.0 (compatible; JobOfferScannerBot/0.2; +https://example.invalid/bot)" ) @@ -52,7 +53,7 @@ def fallback_enabled() -> bool: """The agentic fallback needs an LLM (for queries + synthesis); it's off in demo mode and can be force-disabled.""" - if os.getenv("COMPANY_RESEARCH_FALLBACK", "1") != "1": + if not env_bool("COMPANY_RESEARCH_FALLBACK", True): return False return get_active_provider() is not None @@ -67,7 +68,7 @@ def ddg_search(query: str, max_results: Optional[int] = None) -> List[dict]: the HTML endpoint.""" if not query: return [] - limit = max_results or int(os.getenv("DDG_MAX_RESULTS", "5")) + limit = max_results or env_int("DDG_MAX_RESULTS", 5) lib_results = _ddg_via_library(query, limit) if lib_results: diff --git a/tools/data_sources.py b/tools/data_sources.py index cef522b..969a665 100644 --- a/tools/data_sources.py +++ b/tools/data_sources.py @@ -19,9 +19,11 @@ import requests +from utils.env import env_float + logger = logging.getLogger(__name__) -_HTTP_TIMEOUT = float(os.getenv("DATA_SOURCE_TIMEOUT", "10")) +_HTTP_TIMEOUT = env_float("DATA_SOURCE_TIMEOUT", 10.0) _NEWS_ENDPOINT = "https://newsapi.org/v2/everything" _ADZUNA_ENDPOINT = "https://api.adzuna.com/v1/api/jobs/{country}/search/1" diff --git a/tools/url_ingest.py b/tools/url_ingest.py index 442ef56..875c2dc 100644 --- a/tools/url_ingest.py +++ b/tools/url_ingest.py @@ -26,13 +26,15 @@ import requests from bs4 import BeautifulSoup +from utils.env import env_bool, env_float, env_int + logger = logging.getLogger(__name__) _USER_AGENT = ( "Mozilla/5.0 (compatible; JobOfferScannerBot/0.2; +https://example.invalid/bot)" ) -_HTTP_TIMEOUT = float(os.getenv("URL_INGEST_TIMEOUT", "15")) -_MAX_BYTES = int(os.getenv("URL_INGEST_MAX_BYTES", "1500000")) # ~1.5 MB +_HTTP_TIMEOUT = env_float("URL_INGEST_TIMEOUT", 15.0) +_MAX_BYTES = env_int("URL_INGEST_MAX_BYTES", 1_500_000) # ~1.5 MB _URL_RE = re.compile(r"^https?://", re.IGNORECASE) @@ -60,7 +62,7 @@ def is_js_board(url: str) -> bool: def browser_ingest_available() -> bool: """Whether any headless-browser backend is configured (local or hosted).""" - if os.getenv("BROWSER_SCRAPER_ENABLED") == "1": + if env_bool("BROWSER_SCRAPER_ENABLED"): return True return bool(os.getenv("BROWSERBASE_API_KEY") and os.getenv("BROWSERBASE_PROJECT_ID")) diff --git a/utils/cache.py b/utils/cache.py index f9128a6..0b4548d 100644 --- a/utils/cache.py +++ b/utils/cache.py @@ -21,9 +21,11 @@ from datetime import datetime, timedelta from typing import Any, Optional +from utils.env import env_int + logger = logging.getLogger(__name__) -_DEFAULT_TTL = int(os.getenv("CACHE_TTL_SECONDS", "3600")) +_DEFAULT_TTL = env_int("CACHE_TTL_SECONDS", 3600) _NAMESPACE = "joc:cache:" diff --git a/utils/config.py b/utils/config.py index 1aa7969..d147399 100644 --- a/utils/config.py +++ b/utils/config.py @@ -1,9 +1,13 @@ +import logging import os from typing import Dict, List, Union +from utils.env import effective_config from utils.llm import TIER_MODELS, get_active_provider, is_demo_mode +logger = logging.getLogger(__name__) + def check_environment_setup() -> Dict[str, Union[bool, str, None]]: """Check environment/configuration status. @@ -21,6 +25,22 @@ def check_environment_setup() -> Dict[str, Union[bool, str, None]]: } +def log_effective_config() -> Dict[str, object]: + """Log the resolved, NON-default configuration (from utils.env reads). + + Call once at process startup (api/main, app.py, worker). Makes a typo'd or + unexpected override visible — secrets aren't read through utils.env, so this + only surfaces tuning knobs (limits, timeouts, budgets, feature flags), never + keys. Returns the dict it logged (handy for tests/admin views). + """ + cfg = effective_config() + if cfg: + logger.info("Effective config (non-default): %s", cfg) + else: + logger.info("Effective config: all defaults (no env overrides read yet).") + return cfg + + def get_missing_configs() -> List[str]: """List configuration items missing for full production operation.""" missing = [] diff --git a/utils/env.py b/utils/env.py new file mode 100644 index 0000000..e45961b --- /dev/null +++ b/utils/env.py @@ -0,0 +1,113 @@ +"""Typed environment-variable accessors + a record of what was actually read. + +One place for env-parsing semantics so: + + * Defaults aren't duplicated per call site (and can't silently diverge). + * Boolean parsing isn't the fragile ``== "1"`` check — ``true`` / ``yes`` / + ``on`` (any case) now work too, and an unrecognised value warns instead of + silently reading as false. + * Every read is recorded, so :func:`effective_config` / + ``utils.config.log_effective_config`` can show the operator the resolved, + NON-default configuration at startup — turning a typo'd var (which would + otherwise silently fall back to its default) into something visible. + +Values are read live from ``os.environ`` on every call (never cached), so tests +that flip a var with ``mock.patch.dict`` still take effect. The recording is a +best-effort side-table; it only reflects vars read so far (module-level reads +happen at import, function-level reads on first call). +""" + +from __future__ import annotations + +import logging +import os +import threading +from typing import Dict, Optional, Tuple + +logger = logging.getLogger(__name__) + +_TRUE = {"1", "true", "yes", "on"} +_FALSE = {"0", "false", "no", "off", ""} + +_lock = threading.Lock() +# name -> (resolved_value, default, overridden_by_env) +_seen: Dict[str, Tuple[object, object, bool]] = {} + + +def _record(name: str, value: object, default: object, overridden: bool) -> None: + with _lock: + _seen[name] = (value, default, overridden) + + +def env_str(name: str, default: Optional[str] = None) -> Optional[str]: + raw = os.getenv(name) + value = raw if raw is not None else default + _record(name, value, default, raw is not None) + return value + + +def env_bool(name: str, default: bool = False) -> bool: + raw = os.getenv(name) + if raw is None: + _record(name, default, default, False) + return default + s = raw.strip().lower() + if s in _TRUE: + value = True + elif s in _FALSE: + value = False + else: + logger.warning( + "env %s=%r is not a recognised boolean (use 1/0/true/false); using %s.", + name, raw, default, + ) + value = default + _record(name, value, default, True) + return value + + +def env_int(name: str, default: int) -> int: + raw = os.getenv(name) + if raw is None or raw.strip() == "": + _record(name, default, default, False) + return default + try: + value = int(raw) + except ValueError: + logger.warning("env %s=%r is not an int; using %s.", name, raw, default) + value = default + _record(name, value, default, value != default or raw.strip() != str(default)) + return value + + +def env_float(name: str, default: float) -> float: + raw = os.getenv(name) + if raw is None or raw.strip() == "": + _record(name, default, default, False) + return default + try: + value = float(raw) + except ValueError: + logger.warning("env %s=%r is not a number; using %s.", name, raw, default) + value = default + _record(name, value, default, True) + return value + + +def effective_config(include_defaults: bool = False) -> Dict[str, object]: + """Return the env reads recorded so far. + + By default only the vars whose value was overridden by the environment + (i.e. differ from the in-code default in origin) are returned. + """ + with _lock: + return { + name: value + for name, (value, _default, overridden) in sorted(_seen.items()) + if include_defaults or overridden + } + + +def reset_for_testing() -> None: + with _lock: + _seen.clear() diff --git a/utils/llm.py b/utils/llm.py index 44caf76..fcabee3 100644 --- a/utils/llm.py +++ b/utils/llm.py @@ -21,6 +21,8 @@ import time from typing import Optional +from utils.env import env_bool, env_float, env_int + logger = logging.getLogger(__name__) # --------------------------------------------------------------------------- @@ -57,9 +59,9 @@ _FEATHERLESS_BASE_URL = "https://api.featherless.ai/v1" -DEFAULT_TEMPERATURE = float(os.getenv("LLM_TEMPERATURE", "0.4")) -DEFAULT_MAX_TOKENS = int(os.getenv("LLM_MAX_TOKENS", "2000")) -_MAX_RETRIES = int(os.getenv("LLM_MAX_RETRIES", "3")) +DEFAULT_TEMPERATURE = env_float("LLM_TEMPERATURE", 0.4) +DEFAULT_MAX_TOKENS = env_int("LLM_MAX_TOKENS", 2000) +_MAX_RETRIES = env_int("LLM_MAX_RETRIES", 3) def _record_usage(provider: str, model: str, usage: Optional[dict]) -> None: @@ -76,7 +78,7 @@ def _completion_cache_key( provider: str, model: str, system: str, temperature: float, max_tokens: int, prompt: str ) -> Optional[str]: """A stable cache key for an identical call, or None when caching is off.""" - if os.getenv("LLM_CACHE_COMPLETIONS", "0") != "1": + if not env_bool("LLM_CACHE_COMPLETIONS", False): return None import hashlib diff --git a/worker/celery_app.py b/worker/celery_app.py index 6797298..f56f444 100644 --- a/worker/celery_app.py +++ b/worker/celery_app.py @@ -20,6 +20,8 @@ from functools import lru_cache from typing import Optional +from utils.env import env_int + logger = logging.getLogger(__name__) @@ -55,7 +57,7 @@ def get_celery_app(): result_serializer="json", accept_content=["json"], task_track_started=True, - task_time_limit=int(os.getenv("CELERY_TASK_TIME_LIMIT", "600")), + task_time_limit=env_int("CELERY_TASK_TIME_LIMIT", 600), worker_max_tasks_per_child=50, ) return celery From 628229a2b2458c10a97a1d1abfed797663f241d5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 8 Jun 2026 09:50:21 +0000 Subject: [PATCH 22/24] =?UTF-8?q?refactor:=20invert=20utils.llm=E2=86=92se?= =?UTF-8?q?rvices.usage=20coupling;=20type=20the=20provider=20funcs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Final review cleanups. Layering inversion (observer pattern): - utils.llm no longer imports the services layer. It exposes register_usage_recorder() and notifies registered recorders after each real completion, so it's a true leaf (verified: no `import services` in utils/). - services.usage registers record_completion on import; services/__init__ imports services.usage so the wiring runs early (every entry point imports a service). Recording behaviour is unchanged — usage is still ledgered for all real completions and attributed via the account() scope. Type coverage: - Annotated _complete_anthropic / _complete_openai_compatible (params + Tuple[str, UsageDict] return). With annotations present, mypy now type-checks their bodies (the getattr-heavy SDK-response handling most prone to provider drift) even under check_untyped_defs=false. Tests: observer wiring (utils.llm imports no services; importing services registers the recorder; registration is idempotent). mypy clean (76 files), ruff/bandit clean, full suite green (647). https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd --- services/__init__.py | 10 ++++++ services/usage.py | 8 +++++ tests/test_phase35_llm_cost_controls.py | 28 +++++++++++++++++ utils/llm.py | 42 +++++++++++++++++++------ 4 files changed, 78 insertions(+), 10 deletions(-) diff --git a/services/__init__.py b/services/__init__.py index e69de29..ace5162 100644 --- a/services/__init__.py +++ b/services/__init__.py @@ -0,0 +1,10 @@ +"""Business-logic services. + +Importing this package wires up the LLM usage ledger: ``services.usage`` +registers its recorder with ``utils.llm`` (observer pattern) so token +accounting works without ``utils.llm`` importing the services layer. Every +entry point imports some service, so this runs early enough to capture all +real completions. +""" + +from services import usage as _usage # noqa: F401 (import for its side effect) diff --git a/services/usage.py b/services/usage.py index f6c76f5..f7a9c0b 100644 --- a/services/usage.py +++ b/services/usage.py @@ -215,3 +215,11 @@ def check_budget(user_id: Optional[int]) -> None: spent = spend_usd(user_id) if spent >= budget: raise BudgetExceeded(spent, budget) + + +# Register the ledger with the LLM client (observer pattern). This keeps +# utils.llm a leaf — it notifies recorders rather than importing this module. +# Importing services.usage (guaranteed early via services/__init__) wires it up. +from utils.llm import register_usage_recorder # noqa: E402 + +register_usage_recorder(record_completion) diff --git a/tests/test_phase35_llm_cost_controls.py b/tests/test_phase35_llm_cost_controls.py index 9366255..83be3d0 100644 --- a/tests/test_phase35_llm_cost_controls.py +++ b/tests/test_phase35_llm_cost_controls.py @@ -217,5 +217,33 @@ class _Resp: self.assertEqual(create.call_count, 1) +class UsageObserverWiringTests(unittest.TestCase): + """The ledger is wired into utils.llm via an observer, so utils.llm stays a + leaf (no upward import of the services layer).""" + + def test_utils_llm_does_not_import_services(self): + import pathlib + src = pathlib.Path(__file__).resolve().parents[1] / "utils" / "llm.py" + text = src.read_text() + self.assertNotIn("import services", text) + self.assertNotIn("from services", text) + + def test_importing_services_registers_recorder(self): + import importlib + + import utils.llm as llm + from services import usage + # services package import (above) wires the recorder. + self.assertIn(usage.record_completion, llm._usage_recorders) + importlib.import_module("services") # idempotent — no duplicate + + def test_register_is_idempotent(self): + import utils.llm as llm + from services import usage + before = llm._usage_recorders.count(usage.record_completion) + llm.register_usage_recorder(usage.record_completion) + self.assertEqual(llm._usage_recorders.count(usage.record_completion), before) + + if __name__ == "__main__": unittest.main() diff --git a/utils/llm.py b/utils/llm.py index fcabee3..dd25daa 100644 --- a/utils/llm.py +++ b/utils/llm.py @@ -19,12 +19,28 @@ import os import re import time -from typing import Optional +from typing import Callable, List, Optional, Tuple from utils.env import env_bool, env_float, env_int logger = logging.getLogger(__name__) +# Usage type passed to observers: provider's token-usage dict, or None. +UsageDict = Optional[dict] +UsageRecorder = Callable[[str, str, UsageDict], None] + +# Observers notified after each REAL completion. ``services.usage`` registers +# its ledger here (observer pattern) so this module stays a leaf — utils.llm +# must never import the services layer. Registration is idempotent and happens +# when ``services.usage`` is imported (guaranteed early via services/__init__). +_usage_recorders: List[UsageRecorder] = [] + + +def register_usage_recorder(fn: UsageRecorder) -> None: + """Register a callback invoked as ``fn(provider, model, usage)`` per call.""" + if fn not in _usage_recorders: + _usage_recorders.append(fn) + # --------------------------------------------------------------------------- # Provider configuration # --------------------------------------------------------------------------- @@ -65,13 +81,16 @@ def _record_usage(provider: str, model: str, usage: Optional[dict]) -> None: - """Ledger token usage for a completed call. Never raises into the caller.""" - try: - from services import usage as usage_service + """Notify registered usage observers about a completed call. - usage_service.record_completion(provider, model, usage) - except Exception as exc: # noqa: BLE001 - accounting is best-effort - logger.warning("usage accounting skipped: %s", exc) + Best-effort: an observer failure is logged and never raised into the + caller. No-op when nothing is registered. + """ + for recorder in _usage_recorders: + try: + recorder(provider, model, usage) + except Exception as exc: # noqa: BLE001 - accounting is best-effort + logger.warning("usage accounting skipped: %s", exc) def _completion_cache_key( @@ -247,7 +266,9 @@ def get_completion( # package being absent never breaks the active path). # --------------------------------------------------------------------------- -def _complete_anthropic(prompt, model, system, temperature, max_tokens): +def _complete_anthropic( + prompt: str, model: str, system: str, temperature: float, max_tokens: int, +) -> Tuple[str, UsageDict]: from anthropic import Anthropic # lazy import # The SDK reads ANTHROPIC_API_KEY and (optionally) ANTHROPIC_BASE_URL itself. @@ -280,8 +301,9 @@ def _is_new_style_openai_model(model: str) -> bool: def _complete_openai_compatible( - provider, prompt, model, system, temperature, max_tokens -): + provider: str, prompt: str, model: str, system: str, + temperature: float, max_tokens: int, +) -> Tuple[str, UsageDict]: from openai import OpenAI # lazy import if provider == "featherless": From 36544e225eac65a217748add34ae4974f13878e5 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 9 Jun 2026 08:35:25 +0000 Subject: [PATCH 23/24] refactor: de-duplicate helpers, drop dead shims, tidy imports; document architecture MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Acceptance-review cleanups (two read-only audits: layering CLEAN, no violations). De-duplication: - utils/text.strip_code_fence: single fenced-JSON stripper; replaces three copies (tools/job_tools, services/bulk_import, tools/company_research). - tools/html_extract.extract_job_text: single posting HTML->text cleaner; url_ingest._clean_html and browser_scraper._parse_job_html now delegate. - services/system_test: last `== "1"` / int(os.getenv) straggler migrated to utils.env (env_bool/env_int) — env parsing is now fully centralised. Dead code / import clarity: - Removed dead shims utils/llm.get_llm_client() and the generate_mock_response alias (no callers). - utils/__init__.py and tools/__init__.py no longer re-export symbols (get_llm_client, cache, the *_tools lists) — that re-export shadowed the same-named submodules; consumers already use full submodule paths. Reverted the importlib workaround in test_phase2 now that the shadow is gone. - Replaced three dynamic __import__() calls in app.py with top-level imports (datetime, PIPELINE_STAGES). Docs: - CLAUDE.md: new "Architecture & layering" section (one-directional flow, utils=leaf + observer rule, the two accepted seams, full-submodule-path rule) + "Shared helpers" guidelines; refreshed stale counts (31 services, 17 migrations / 20 tables, 43 test files / 647 tests) and marked P1 done. ruff/mypy (78 files)/bandit clean, full suite green (647). https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd --- CLAUDE.md | 71 +++++++++++++++++++++++++++++++++----- app.py | 10 +++--- services/bulk_import.py | 7 ++-- services/system_test.py | 6 ++-- tests/test_phase2_units.py | 6 ++-- tools/__init__.py | 14 ++++---- tools/browser_scraper.py | 13 ++----- tools/company_research.py | 5 ++- tools/html_extract.py | 35 +++++++++++++++++++ tools/job_tools.py | 18 ++-------- tools/url_ingest.py | 17 ++------- utils/__init__.py | 14 ++++---- utils/llm.py | 14 -------- utils/text.py | 26 ++++++++++++++ 14 files changed, 157 insertions(+), 99 deletions(-) create mode 100644 tools/html_extract.py create mode 100644 utils/text.py diff --git a/CLAUDE.md b/CLAUDE.md index 82272a7..89487d3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -27,29 +27,82 @@ agents/ LangGraph pipeline: orchestrator + per-stage agents job_/company_/salary_/resume_analyzer.py, report_generator.py tools/ LLM-facing tools + ingestion job_tools, company_tools, salary_tools, resume_tools, data_sources, - url_ingest, browser_scraper (Playwright, optional), + url_ingest, browser_scraper (Playwright, optional), html_extract (shared), company_research (agentic keyless DuckDuckGo + Browserbase fallback) -services/ Business logic (29 modules) — the bulk of the app +services/ Business logic (31 modules) — the bulk of the app auth, totp, oauth, api_tokens, rate_limit, audit (identity/security) applications, stages, analytics, timeline, background_analysis (tracking) master_cv, projects, tailoring, constraint_check, suggestions, pdf_export (CV/artifacts) sharing, webhooks, telegram_link, notifications, email, reminders (integrations) - checkpoint, bulk_import, system_test, analysis_runner, - account_export, email_verify + checkpoint, bulk_import, system_test, analysis_runner, usage (LLM cost), + account_export, email_verify, _ownership (require_owned helper) db/ SQLAlchemy 2.0 models + session (StaticPool-aware) api/ FastAPI app: routes, bearer auth, security headers bot/ Telegram bot: handlers (pure) + main (runtime) worker/ Celery app + tasks + CLI runners (reminders, metrics_dump) -utils/ llm, config, security, diff, verdict, logging_setup, metrics, timing, cache -migrations/ Alembic (15 revisions, 19 tables) +utils/ LEAF layer: llm, config, env, crypto, security, diff, + verdict, text, logging_setup, metrics, timing, cache +migrations/ Alembic (17 revisions, 20 tables) chrome-extension/ MV3 extension calling the REST API (JS, Node-tested) deploy/ Caddy/nginx reverse-proxy examples (CSP/HSTS) + README (edge topology) + RUNBOOK (backups/incidents) scripts/ backup_db.sh / restore_db.sh (Postgres ops) -tests/ 33 files, 535 Python tests (7 live e2e, skipped +tests/ 43 files, 647 Python tests (7 live e2e, skipped unless RUN_E2E=1) + 9 JS (extract.test.mjs) ``` +## Architecture & layering (keep this clean) + +Strict one-directional dependency flow — never import upward: + +``` +app.py / api/ / bot/ entry points (UI, REST, Telegram) + │ + ▼ + services/ business logic (owns the DB, side-effects, policy) + │ + ▼ + db/ SQLAlchemy models + session + +agents/ (LangGraph pipeline) ─┐ +tools/ (LLM-facing tools) ├─▶ utils/ (LEAF — depends on nothing internal) + ─┘ +worker/ (Celery) consumes services; runs the same pipeline off-process. +``` + +- **`utils/` is a LEAF.** It must NOT import from `services/agents/tools/api/ + bot/worker`. When a leaf needs a higher-layer behaviour (e.g. the LLM client + notifying the usage ledger), use an **observer**: `utils/llm` exposes + `register_usage_recorder`; `services/usage` registers `record_completion` + into it on import (wired via `services/__init__`). Don't reach back up. +- **`db/` is below services** — it may import `utils.env` (config) but nothing + else internal. No business logic lives in `db/` or `utils/`. +- **`tools/` and `agents/` depend DOWN on `utils/` only** — the one accepted + exception is `agents/orchestrator` importing `services.checkpoint` (resume + persistence) + `services.usage` (per-thread attribution). Provider/transport + code lives only in `utils/llm`; a service calling `get_completion` to run a + domain prompt is correct (business orchestration), not a layer break. +- **`services ↔ worker` is the one accepted bidirectional seam** (producer in + services, consumer in worker). The `services → worker` direction is ALWAYS a + lazy in-function import to avoid an import-time cycle; keep it that way. +- **Import full submodule paths** — `from utils.cache import cache`, not + `from utils import cache`. The `utils/` and `tools/` `__init__.py` are + intentionally empty (no symbol re-exports) so a submodule is never shadowed + by a same-named re-exported value. + +### Shared helpers — use these, don't re-roll them + +- **Config:** `utils/env.env_{str,bool,int,float}` — never `os.getenv(...) == + "1"` (env_bool accepts `1/true/yes/on`) or ad-hoc `int(os.getenv(...))`. + Reads are recorded; `utils/config.log_effective_config()` logs non-default + config at startup (don't read secrets through this). +- **Ownership:** `services/_ownership.require_owned(session, Model, id, + user_id, exc, msg)` for every owned fetch — don't inline the + `is None or .user_id != user_id` check. +- **LLM-output text:** `utils/text.strip_code_fence` (fenced JSON) and + `tools/html_extract.extract_job_text` (posting HTML → text) are the single + implementations — reuse them. + ## How to run ```bash @@ -69,7 +122,7 @@ celery -A worker.celery_app:app worker python -m worker.reminders # Tests -python -m unittest discover -s tests # ~5 min, 506 tests +python -m unittest discover -s tests # ~6 min, 647 tests (7 e2e skipped) node chrome-extension/extract.test.mjs # 9 JS tests # Migrations @@ -168,7 +221,7 @@ and "production-grade for real multi-user traffic." Prioritized: all migrations and asserts no add/remove table-or-column drift vs the models. Runs in CI via the unittest job. -### P1 — hardening + confidence (in progress) +### P1 — ✅ DONE (hardening + confidence) 5. ✅ **CI quality gates:** ruff (lint) + mypy (type) + bandit (hard gate) + pip-audit (advisory) + coverage floor 80% + JS tests in CI + Node-24 opt-in. Config in `pyproject.toml`; jobs in `.github/workflows/tests.yml`. diff --git a/app.py b/app.py index 837677a..a1632de 100644 --- a/app.py +++ b/app.py @@ -1,12 +1,12 @@ import os -from datetime import date, timedelta +from datetime import date, datetime, timedelta import altair as alt import pandas as pd import streamlit as st from agents.orchestrator import run_analysis -from db.models import APPLICATION_STATUSES +from db.models import APPLICATION_STATUSES, PIPELINE_STAGES from db.session import init_db from services.analysis_runner import async_enabled from services.analytics import compute_dashboard @@ -575,7 +575,7 @@ def _render_verification_gate() -> None: for t in tokens: status = ( "revoked" if t.revoked_at else - "expired" if t.expires_at and t.expires_at <= __import__("datetime").datetime.utcnow() else + "expired" if t.expires_at and t.expires_at <= datetime.utcnow() else "active" ) cols = st.columns([4, 1]) @@ -1583,7 +1583,7 @@ def _matches(rec) -> bool: at_pipeline = st.selectbox( "If terminal (rejected/withdrew/ghosted): at which pipeline stage?", ["(none)"] + list( - __import__("db.models", fromlist=["PIPELINE_STAGES"]).PIPELINE_STAGES + PIPELINE_STAGES ), key=f"stage_at_{rec.id}", ) @@ -1899,7 +1899,7 @@ def _matches(rec) -> bool: status = "active" if s.revoked_at: status = "revoked" - elif s.expires_at and s.expires_at <= __import__("datetime").datetime.utcnow(): + elif s.expires_at and s.expires_at <= datetime.utcnow(): status = "expired" col_info, col_act = st.columns([4, 1]) with col_info: diff --git a/services/bulk_import.py b/services/bulk_import.py index 021eed3..68afc7d 100644 --- a/services/bulk_import.py +++ b/services/bulk_import.py @@ -34,6 +34,7 @@ from services.stages import add_stage from utils.llm import get_completion from utils.security import wrap_untrusted +from utils.text import strip_code_fence class BulkImportError(ValueError): @@ -346,11 +347,7 @@ def save_applications(user_id: int, previews: List[dict]) -> List[int]: def _strict_json_list(text: str): """Parse a JSON array from an LLM response, stripping any code fences.""" - text = (text or "").strip() - if text.startswith("```"): - # Drop leading ```json or ``` and trailing ``` - text = re.sub(r"^```(?:json)?\s*", "", text) - text = re.sub(r"\s*```\s*$", "", text) + text = strip_code_fence(text) try: parsed = json.loads(text) except json.JSONDecodeError as exc: diff --git a/services/system_test.py b/services/system_test.py index 3be1f1c..4392c57 100644 --- a/services/system_test.py +++ b/services/system_test.py @@ -16,6 +16,8 @@ from dataclasses import dataclass from typing import List, Optional +from utils.env import env_bool, env_int + # --------------------------------------------------------------------------- # Result container # --------------------------------------------------------------------------- @@ -83,10 +85,10 @@ def _probe_email() -> TestResult: if not email_configured(): return TestResult("Email (SMTP)", ok=False, message="Not configured", skipped=True) host = os.getenv("SMTP_HOST", "") - port = int(os.getenv("SMTP_PORT", "587")) + port = env_int("SMTP_PORT", 587) username = os.getenv("SMTP_USERNAME", "") password = os.getenv("SMTP_PASSWORD", "") - use_tls = os.getenv("SMTP_USE_TLS", "1") == "1" + use_tls = env_bool("SMTP_USE_TLS", True) t0 = time.time() try: with smtplib.SMTP(host, port, timeout=8) as server: diff --git a/tests/test_phase2_units.py b/tests/test_phase2_units.py index 43ec60e..a6f8b1f 100644 --- a/tests/test_phase2_units.py +++ b/tests/test_phase2_units.py @@ -18,20 +18,18 @@ def setUp(self): cache.clear() def test_raises_on_non_json_when_keyed(self): - import importlib from unittest import mock - jt = importlib.import_module("tools.job_tools") # pkg shadows the submodule name + import tools.job_tools as jt with mock.patch.object(jt, "get_completion", return_value="not json at all"), \ mock.patch.object(jt, "is_demo_mode", return_value=False): with self.assertRaises(ValueError): jt.analyze_requirements("Some posting", model="fast") def test_empty_skeleton_only_in_demo(self): - import importlib from unittest import mock - jt = importlib.import_module("tools.job_tools") + import tools.job_tools as jt with mock.patch.object(jt, "get_completion", return_value="not json"), \ mock.patch.object(jt, "is_demo_mode", return_value=True): out = jt.analyze_requirements("Some posting", model="fast") diff --git a/tools/__init__.py b/tools/__init__.py index c880fcd..1475f54 100644 --- a/tools/__init__.py +++ b/tools/__init__.py @@ -1,9 +1,7 @@ -from .company_tools import company_tools -from .job_tools import job_tools -from .salary_tools import salary_tools +"""LLM-facing tools + ingestion. -__all__ = [ - 'job_tools', - 'company_tools', - 'salary_tools' -] +Import submodules by their full path — ``from tools.job_tools import +extract_job_details`` — rather than re-exporting the ``*_tools`` Tool lists +here, which would shadow the same-named submodules (``from tools import +job_tools`` resolving to the list instead of the module). +""" diff --git a/tools/browser_scraper.py b/tools/browser_scraper.py index c5932c2..db5a187 100644 --- a/tools/browser_scraper.py +++ b/tools/browser_scraper.py @@ -106,17 +106,8 @@ def scrape_job_posting(url: str) -> str: def _parse_job_html(html: str) -> str: """Extract plain-text posting content from rendered HTML (pure).""" - soup = BeautifulSoup(html, "html.parser") - for tag in soup(["script", "style", "noscript", "header", "footer", "nav", "svg"]): - tag.decompose() - - candidates = soup.find_all( - ["article", "main", "section", "div"], - attrs={"class": re.compile(r"(job|posting|description|content|details)", re.I)}, - ) - root = candidates[0] if candidates else soup - text = root.get_text(separator="\n", strip=True) - return re.sub(r"\n{3,}", "\n\n", text) + from tools.html_extract import extract_job_text + return extract_job_text(html) # --------------------------------------------------------------------------- diff --git a/tools/company_research.py b/tools/company_research.py index fe60c43..1775bc4 100644 --- a/tools/company_research.py +++ b/tools/company_research.py @@ -32,7 +32,6 @@ import json import logging import os -import re from typing import List, Optional import requests @@ -40,6 +39,7 @@ from utils.env import env_bool, env_float, env_int from utils.llm import get_active_provider, get_completion from utils.security import wrap_untrusted +from utils.text import strip_code_fence logger = logging.getLogger(__name__) @@ -244,8 +244,7 @@ def build_queries(company: str, model: str = "fast") -> List[str]: f"Company: {wrap_untrusted(company, 'company_name')}" ) try: - raw = get_completion(prompt, model).strip() - raw = re.sub(r"^```(?:json)?\s*|\s*```$", "", raw) + raw = strip_code_fence(get_completion(prompt, model)) queries = json.loads(raw) cleaned = [str(q).strip() for q in queries if str(q).strip()][:3] return cleaned or static diff --git a/tools/html_extract.py b/tools/html_extract.py new file mode 100644 index 0000000..003af50 --- /dev/null +++ b/tools/html_extract.py @@ -0,0 +1,35 @@ +"""Shared HTML → plain-text extraction for job postings. + +Both the plain-fetch path (``tools.url_ingest``) and the headless-browser path +(``tools.browser_scraper``) need to turn posting HTML into clean text the same +way: drop chrome (script/style/nav/…), prefer a job-description-shaped +container, then collapse whitespace. This is that single implementation. +""" + +from __future__ import annotations + +import re +from typing import Union + +from bs4 import BeautifulSoup + +# Chrome elements that never carry posting content. +_STRIP_TAGS = ("script", "style", "noscript", "header", "footer", "nav", "svg") +# Container classes that usually wrap the posting body. +_CONTENT_CLASS_RE = re.compile(r"(job|posting|description|content|details)", re.I) + + +def extract_job_text(html: Union[str, bytes]) -> str: + """Return cleaned posting text from raw HTML (``str`` or ``bytes``).""" + soup = BeautifulSoup(html, "html.parser") + for tag in soup(list(_STRIP_TAGS)): + tag.decompose() + + candidates = soup.find_all( + ["article", "main", "section", "div"], + attrs={"class": _CONTENT_CLASS_RE}, + ) + root = candidates[0] if candidates else soup + text = root.get_text(separator="\n", strip=True) + # Collapse runs of blank lines. + return re.sub(r"\n{3,}", "\n\n", text) diff --git a/tools/job_tools.py b/tools/job_tools.py index ff7278c..45797a6 100644 --- a/tools/job_tools.py +++ b/tools/job_tools.py @@ -19,23 +19,11 @@ from utils.cache import cache from utils.llm import get_completion, is_demo_mode from utils.security import wrap_untrusted +from utils.text import strip_code_fence logger = logging.getLogger(__name__) -def _strip_code_fence(text: str) -> str: - text = text.strip() - if text.startswith("```"): - # ```json ... ``` or ``` ... ``` - body = text.split("```", 2) - if len(body) >= 2: - inner = body[1] - if inner.startswith("json"): - inner = inner[4:] - return inner.strip().rstrip("`").strip() - return text - - def _regex_extract(job_posting: str) -> Dict[str, Any]: """Last-ditch extraction when the LLM returns unparseable JSON.""" lines = job_posting.splitlines() @@ -97,7 +85,7 @@ def extract_job_details(job_posting: str, model: str = "detailed") -> dict: - Return ONLY JSON. No prose, no markdown fences. """ response = get_completion(prompt, model) - response = _strip_code_fence(response) + response = strip_code_fence(response) try: parsed = json.loads(response) @@ -144,7 +132,7 @@ def analyze_requirements(job_posting: str, model: str = "detailed") -> dict: - Only include items actually present in the posting. Do not invent. - Return ONLY JSON. No prose, no markdown fences. """ - response = _strip_code_fence(get_completion(prompt, model)) + response = strip_code_fence(get_completion(prompt, model)) try: parsed = json.loads(response) except json.JSONDecodeError as exc: diff --git a/tools/url_ingest.py b/tools/url_ingest.py index 875c2dc..86bb477 100644 --- a/tools/url_ingest.py +++ b/tools/url_ingest.py @@ -24,7 +24,6 @@ from typing import Optional import requests -from bs4 import BeautifulSoup from utils.env import env_bool, env_float, env_int @@ -155,17 +154,5 @@ def _try_browser_fallback(url: str) -> Optional[str]: def _clean_html(body: bytes) -> str: - soup = BeautifulSoup(body, "html.parser") - for tag in soup(["script", "style", "noscript", "header", "footer", "nav"]): - tag.decompose() - - # Prefer a likely job-description container if present. - candidates = soup.find_all( - ["article", "main", "section", "div"], - attrs={"class": re.compile(r"(job|posting|description|content)", re.I)}, - ) - root = candidates[0] if candidates else soup - - text = root.get_text(separator="\n", strip=True) - # Collapse runs of blank lines. - return re.sub(r"\n{3,}", "\n\n", text) + from tools.html_extract import extract_job_text + return extract_job_text(body) diff --git a/utils/__init__.py b/utils/__init__.py index d8584ca..1bfbcb5 100644 --- a/utils/__init__.py +++ b/utils/__init__.py @@ -1,9 +1,7 @@ -from .cache import SimpleCache, cache -from .llm import get_completion, get_llm_client +"""Leaf-layer utilities (no imports from services/agents/tools/api/bot/worker). -__all__ = [ - 'get_llm_client', - 'get_completion', - 'SimpleCache', - 'cache' -] +Import submodules by their full path — ``from utils.cache import cache``, +``from utils.llm import get_completion`` — rather than re-exporting symbols +here, which would shadow the same-named submodules (e.g. ``from utils import +cache`` resolving to the value instead of the module). +""" diff --git a/utils/llm.py b/utils/llm.py index dd25daa..fdbf439 100644 --- a/utils/llm.py +++ b/utils/llm.py @@ -456,10 +456,6 @@ def generate_sample_response(prompt: str) -> str: ) -# Backwards-compatibility alias for any callers/tests referencing the old name. -generate_mock_response = generate_sample_response - - def ping_provider(provider: str) -> tuple[bool, str]: """Make a minimal real API call to verify a provider is reachable. @@ -482,13 +478,3 @@ def ping_provider(provider: str) -> tuple[bool, str]: return True, repr(text.strip()[:40]) except Exception as exc: # noqa: BLE001 return False, str(exc) - - -def get_llm_client(): - """Deprecated: kept for backwards compatibility. - - The provider client is now created per-request inside ``get_completion`` so - that provider/model selection is resolved at call time. Returns None in - demo mode. - """ - return None diff --git a/utils/text.py b/utils/text.py new file mode 100644 index 0000000..a2c23d2 --- /dev/null +++ b/utils/text.py @@ -0,0 +1,26 @@ +"""Small text-processing helpers shared across LLM-output handling. + +Leaf utilities (only ``re``); safe to import from tools/ and services/. +""" + +from __future__ import annotations + +import re + +_FENCE_OPEN = re.compile(r"^```[a-zA-Z0-9_-]*\s*") +_FENCE_CLOSE = re.compile(r"\s*```$") + + +def strip_code_fence(text: str) -> str: + """Strip a leading ```` ```json ```` / ```` ``` ```` fence and trailing ```` ``` ````. + + Returns the inner content stripped of surrounding whitespace. A string with + no fence is returned trimmed. This is the single implementation used by the + job/bulk-import/company-research parsers (which previously each rolled their + own). + """ + s = (text or "").strip() + if s.startswith("```"): + s = _FENCE_OPEN.sub("", s) + s = _FENCE_CLOSE.sub("", s) + return s.strip() From 59268593712967f2c165ea123a27835f9b2ef9e1 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 9 Jun 2026 09:08:55 +0000 Subject: [PATCH 24/24] ci(mypy): pin mypy to 1.x + fix the strict-mypy type errors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI's mypy job is unpinned (mypy>=1.10) and had drifted to mypy 2.1.0, which is materially stricter (third-party stub-shape changes) and surfaced 44 errors — both pre-existing third-party-typing noise and the two functions newly brought under checking by recent annotations. - Pin dev mypy to >=1.10,<2 so the type gate is reproducible (a CI linter must not float to "latest"). uv.lock regenerated (2.1.0 -> 1.20.2). - Fix the genuine type issues so the code is clean under strict mypy too: * utils/llm: getattr(block, "text", "") over the Anthropic content union. * services/webhooks: None-guard the just-created delivery row in attempt_delivery / _deliver (latent None-deref). * services/rate_limit: float() the redis zrange score before arithmetic. * services/checkpoint: str() the redis hgetall key for the dict index. * tools/data_sources: string-valued request params (no mixed int/str). * tools/{job,company,salary}_tools: type: ignore the langchain.tools fallback (langchain 1.x dropped the attribute; langchain_core path is primary). * bot/main: guard Optional update.message / effective_chat and adapt reply_markdown (returns Message) to the handlers' Reply contract. ruff/mypy (78 files)/bandit clean; full suite green (647). https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd --- bot/main.py | 40 ++++++++++---- pyproject.toml | 5 +- services/checkpoint.py | 2 +- services/rate_limit.py | 2 +- services/webhooks.py | 7 ++- tools/company_tools.py | 2 +- tools/data_sources.py | 6 +- tools/job_tools.py | 2 +- tools/salary_tools.py | 2 +- utils/llm.py | 6 +- uv.lock | 121 ++++++++++++++--------------------------- 11 files changed, 92 insertions(+), 103 deletions(-) diff --git a/bot/main.py b/bot/main.py index 50f5825..35b53ff 100644 --- a/bot/main.py +++ b/bot/main.py @@ -53,41 +53,59 @@ def main() -> int: from utils.logging_setup import configure as configure_logging configure_logging() + def _reply_for(message): + """Adapt Telegram's ``reply_markdown`` (returns a Message) to the + handlers' ``Reply = Callable[[str], Awaitable[None]]`` contract.""" + async def _reply(text: str) -> None: + await message.reply_markdown(text) + return _reply + async def _start(update: Update, _ctx: ContextTypes.DEFAULT_TYPE) -> None: - await handle_start(update.message.reply_markdown, _args="") + if update.message is None: + return + await handle_start(_reply_for(update.message), _args="") async def _help(update: Update, _ctx: ContextTypes.DEFAULT_TYPE) -> None: - await handle_help(update.message.reply_markdown, _args="") + if update.message is None: + return + await handle_help(_reply_for(update.message), _args="") async def _analyze(update: Update, ctx: ContextTypes.DEFAULT_TYPE) -> None: - # ctx.args is everything after the command, split on spaces; we want - # the original text after `/analyze ` to preserve newlines, so use - # message.text and strip the command + first space. - raw = (update.message.text or "") + # We want the original text after `/analyze ` to preserve newlines, so + # use message.text and strip the command + first space. + if update.message is None: + return + raw = update.message.text or "" _, _, args = raw.partition(" ") - await handle_analyze(update.message.reply_markdown, args=args) + await handle_analyze(_reply_for(update.message), args=args) async def _bind(update: Update, ctx: ContextTypes.DEFAULT_TYPE) -> None: - raw = (update.message.text or "") + if update.message is None or update.effective_chat is None: + return + raw = update.message.text or "" _, _, args = raw.partition(" ") chat = update.effective_chat await handle_bind( - update.message.reply_markdown, + _reply_for(update.message), args=args, chat_id=chat.id, chat_username=chat.username, ) async def _unbind(update: Update, ctx: ContextTypes.DEFAULT_TYPE) -> None: + if update.message is None or update.effective_chat is None: + return await handle_unbind( - update.message.reply_markdown, + _reply_for(update.message), args="", chat_id=update.effective_chat.id, ) async def _me(update: Update, ctx: ContextTypes.DEFAULT_TYPE) -> None: + if update.message is None or update.effective_chat is None: + return await handle_me( - update.message.reply_markdown, + _reply_for(update.message), args="", chat_id=update.effective_chat.id, ) diff --git a/pyproject.toml b/pyproject.toml index 4d08a49..c0f9d5f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -39,7 +39,10 @@ pdf = ["fpdf2>=2.7.0"] research = ["ddgs>=6.0"] # keyless DuckDuckGo search for the agentic fallback dev = [ "ruff>=0.6", - "mypy>=1.10", + # Pin to the 1.x line: CI gates must use a reproducible type-checker, and + # mypy 2.x is materially stricter (third-party stub shape changes). Bump + # deliberately, re-running the whole `mypy` pass, not via unpinned drift. + "mypy>=1.10,<2", "bandit>=1.7", "pip-audit>=2.7", "coverage>=7.5", diff --git a/services/checkpoint.py b/services/checkpoint.py index 70511cd..8e0c32d 100644 --- a/services/checkpoint.py +++ b/services/checkpoint.py @@ -135,7 +135,7 @@ def get(self, key: str) -> CheckpointPayload: return payload for stage, val in (raw or {}).items(): try: - payload.stages[stage] = json.loads(val) + payload.stages[str(stage)] = json.loads(val) except (TypeError, ValueError): continue return payload diff --git a/services/rate_limit.py b/services/rate_limit.py index ee86d1e..45be52a 100644 --- a/services/rate_limit.py +++ b/services/rate_limit.py @@ -80,7 +80,7 @@ def record_and_check(self, key: str, max_events: int, window: float) -> RateLimi # Roll back the add we just made so a denied attempt doesn't count. self._redis.zpopmax(key, 1) oldest = self._redis.zrange(key, 0, 0, withscores=True) - retry_after = max(0.0, (oldest[0][1] + window - now)) if oldest else window + retry_after = max(0.0, (float(oldest[0][1]) + window - now)) if oldest else window return RateLimitDecision(allowed=False, retry_after=retry_after) return RateLimitDecision(allowed=True, retry_after=0.0) diff --git a/services/webhooks.py b/services/webhooks.py index 5cd73d1..09c2a43 100644 --- a/services/webhooks.py +++ b/services/webhooks.py @@ -338,6 +338,8 @@ def attempt_delivery(delivery_id: int) -> bool: with get_session() as session: row = session.get(WebhookDelivery, delivery_id) + if row is None: # pragma: no cover - row was just created above + return success row.attempts += 1 row.success = success row.status_code = status_code @@ -351,7 +353,10 @@ def _deliver(hook: WebhookRecord, event: str, payload: dict) -> DeliveryRecord: delivery_id = _create_delivery(hook, event, payload) attempt_delivery(delivery_id) with get_session() as session: - return _to_delivery(session.get(WebhookDelivery, delivery_id)) + row = session.get(WebhookDelivery, delivery_id) + if row is None: # pragma: no cover - row was just created above + raise WebhookError("Delivery row missing after creation.") + return _to_delivery(row) def redeliver(user_id: int, delivery_id: int) -> DeliveryRecord: diff --git a/tools/company_tools.py b/tools/company_tools.py index 9bc0f27..a7c0281 100644 --- a/tools/company_tools.py +++ b/tools/company_tools.py @@ -18,7 +18,7 @@ try: from langchain_core.tools import Tool # langchain >= 0.3 except ImportError: # pragma: no cover - older langchain layout - from langchain.tools import Tool + from langchain.tools import Tool # type: ignore[attr-defined,no-redef] from tools.data_sources import fetch_company_news, fetch_layoffs from utils.cache import cache diff --git a/tools/data_sources.py b/tools/data_sources.py index 969a665..f348ff9 100644 --- a/tools/data_sources.py +++ b/tools/data_sources.py @@ -63,8 +63,8 @@ def fetch_company_news(company_name: str) -> Optional[str]: "q": f'"{company_name}"', "sortBy": "publishedAt", "language": "en", - "pageSize": 10, - "apiKey": api_key, + "pageSize": "10", + "apiKey": api_key or "", }, timeout=_HTTP_TIMEOUT, ) @@ -265,7 +265,7 @@ def fetch_salary_benchmark( "app_id": app_id, "app_key": app_key, "what": job_title, - "results_per_page": 50, + "results_per_page": "50", "content-type": "application/json", } if location: diff --git a/tools/job_tools.py b/tools/job_tools.py index 45797a6..bdebe5d 100644 --- a/tools/job_tools.py +++ b/tools/job_tools.py @@ -14,7 +14,7 @@ try: from langchain_core.tools import Tool # langchain >= 0.3 except ImportError: # pragma: no cover - older langchain layout - from langchain.tools import Tool + from langchain.tools import Tool # type: ignore[attr-defined,no-redef] from utils.cache import cache from utils.llm import get_completion, is_demo_mode diff --git a/tools/salary_tools.py b/tools/salary_tools.py index a988c48..2fcab9f 100644 --- a/tools/salary_tools.py +++ b/tools/salary_tools.py @@ -18,7 +18,7 @@ try: from langchain_core.tools import Tool # langchain >= 0.3 except ImportError: # pragma: no cover - older langchain layout - from langchain.tools import Tool + from langchain.tools import Tool # type: ignore[attr-defined,no-redef] from tools.data_sources import fetch_cost_of_living, fetch_salary_benchmark from utils.cache import cache diff --git a/utils/llm.py b/utils/llm.py index fdbf439..6085d67 100644 --- a/utils/llm.py +++ b/utils/llm.py @@ -280,7 +280,11 @@ def _complete_anthropic( system=system, messages=[{"role": "user", "content": prompt}], ) - parts = [block.text for block in resp.content if getattr(block, "type", None) == "text"] + parts = [ + getattr(block, "text", "") + for block in resp.content + if getattr(block, "type", None) == "text" + ] usage = None u = getattr(resp, "usage", None) if u is not None: diff --git a/uv.lock b/uv.lock index d3f648d..c506cf3 100644 --- a/uv.lock +++ b/uv.lock @@ -189,46 +189,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/46/eb/e7f063ad1fec6b3178a3cd82d1a3c4de82cccf283fc42746168188e1cdd5/anyio-4.8.0-py3-none-any.whl", hash = "sha256:b5011f270ab5eb0abf13385f851315585cc37ef330dd88e27ec3d34d651fd47a", size = 96041, upload-time = "2025-01-05T13:13:07.985Z" }, ] -[[package]] -name = "ast-serialize" -version = "0.5.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/81/9d/09e27731bd5864a9ce04e3244074e674bb8936bf62b45e0357248717adac/ast_serialize-0.5.0.tar.gz", hash = "sha256:5880091bfe6f4f986f22866375c2e884843e7a0b6343ae41aeea659613d879b6", size = 61157, upload-time = "2026-05-17T17:48:29.429Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/c0/9a/13dde51ba9e15f8b97957ab7cb0120d0e381524d651c6bd630b9c359227f/ast_serialize-0.5.0-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:8f5c14f169eb0972c0c21bada5358b23d6047c76583b005234f865b11f1fa00a", size = 1183520, upload-time = "2026-05-17T17:47:30.831Z" }, - { url = "https://files.pythonhosted.org/packages/37/de/5a7f0a9fe68944f536632a5af84676739c7d2582be42deb082634bf3a754/ast_serialize-0.5.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:7d1a2de9de5be04652f0ed60738356ef94f66db37924a9499fffe98dc491aa0b", size = 1175779, upload-time = "2026-05-17T17:47:32.551Z" }, - { url = "https://files.pythonhosted.org/packages/9c/81/0bb853e76e4f6e9a1855d569003c59e19ffac45f7079d91505d1bb212f92/ast_serialize-0.5.0-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:be5173fb66f9b49026d9d5a2ff0fc7c7009077107c0eb285b2d60fdf1fe10bd1", size = 1233750, upload-time = "2026-05-17T17:47:34.731Z" }, - { url = "https://files.pythonhosted.org/packages/e5/d3/4cf705beeccc08754d0bbda99aefff26110e209b9a07ac8a6b60eec48531/ast_serialize-0.5.0-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f8015cd071ac1339924ee2b8098c93e00e155f30a16f40ec9816fcf84f4753f6", size = 1235942, upload-time = "2026-05-17T17:47:36.287Z" }, - { url = "https://files.pythonhosted.org/packages/26/c8/ee097e437ea27dd2b8b227865c875492b585650a5802a22d82b304c8201b/ast_serialize-0.5.0-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:5499e8797edff2a9186aa313ed382c6b422e798e9332d9953badcee6e69a88f2", size = 1442517, upload-time = "2026-05-17T17:47:38.17Z" }, - { url = "https://files.pythonhosted.org/packages/ff/bd/68063442838f1ba68ec72b5436430bc75b3bb17a1a3c3063f09b0c05ae2b/ast_serialize-0.5.0-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6848f2a093fb5548751a9a09bff8fcd229e2bbeb0e3331f391b6ae6d26cd9903", size = 1254081, upload-time = "2026-05-17T17:47:39.826Z" }, - { url = "https://files.pythonhosted.org/packages/50/e2/1e520793bc6a4e4524a6ab022391e827825eaa0c3811828bfdc6852eca26/ast_serialize-0.5.0-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:832d4c998e0b091fd60a6d6bceee535483c4d490de9ba85003af835225719261", size = 1259910, upload-time = "2026-05-17T17:47:41.369Z" }, - { url = "https://files.pythonhosted.org/packages/4e/e1/49b60f467979979cfe6913b43948ff25bca971ad0591d181812f163a988e/ast_serialize-0.5.0-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:16db7c62ec0b8efe1d7afd283a388d8f74f2605d56032e5a37747d2de8dba027", size = 1250678, upload-time = "2026-05-17T17:47:43.702Z" }, - { url = "https://files.pythonhosted.org/packages/74/ba/66ab9555de6275677566f6574e5ef6c29cb185ea866f643bc06f8280a8ee/ast_serialize-0.5.0-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:baf5eb061eb5bccade4128ad42da33787d72f6013809cd1b590376ece8b3c937", size = 1301603, upload-time = "2026-05-17T17:47:46.256Z" }, - { url = "https://files.pythonhosted.org/packages/66/42/6aca9b9abc710014b2be9059689e5dd1679339e78f567ffb4d255a9e2050/ast_serialize-0.5.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:104e4a35bd7c124173c41760ef9aaea17ddb3f86c65cb643671d59afbe3ee94c", size = 1410332, upload-time = "2026-05-17T17:47:47.899Z" }, - { url = "https://files.pythonhosted.org/packages/47/68/2f76594432a22581ecf878b5e75a9b8601c24b2241cf0bbeb1e21fcf370c/ast_serialize-0.5.0-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:36be371028fc1675acb38a331bde160dbab7ff907fdf00b67eb6911aa106951b", size = 1509979, upload-time = "2026-05-17T17:47:50.942Z" }, - { url = "https://files.pythonhosted.org/packages/40/ac/a93c9b58292653f6c595752f677a08e608f903b710594909e9231a389b3b/ast_serialize-0.5.0-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:061ee58bdb52341c8201a6df41182a977736bae3b7ded87ca7176ca25a8a47ab", size = 1505002, upload-time = "2026-05-17T17:47:54.093Z" }, - { url = "https://files.pythonhosted.org/packages/14/2e/b278f68c497ee2f1d1576cbbef8db5281cd4a5f2db040537592ac9c8862e/ast_serialize-0.5.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:b15219e9cdc9f53f6f4cb51c009203507228226148c05c5e8fe451c28b435eb3", size = 1456231, upload-time = "2026-05-17T17:47:56.311Z" }, - { url = "https://files.pythonhosted.org/packages/0b/43/419be1c566a4c504cd8fd60ce2f84e790f295495c0f327cfaeadf3d51012/ast_serialize-0.5.0-cp314-cp314t-win32.whl", hash = "sha256:842d1c004bb466c7df036f95fabef789570541922b10976b12f5592a69cf0b38", size = 1058668, upload-time = "2026-05-17T17:47:58.305Z" }, - { url = "https://files.pythonhosted.org/packages/03/6f/c9d4d549295ed05111aeb8853232d1afd9d0a179fddb01eeffbb3a4a6842/ast_serialize-0.5.0-cp314-cp314t-win_amd64.whl", hash = "sha256:b0c06d760909b095cc466356dfccd05a1c7233a6ca191c020dca2c6a6f16c24c", size = 1101075, upload-time = "2026-05-17T17:48:00.35Z" }, - { url = "https://files.pythonhosted.org/packages/d0/8e/d00c5ab30c58222e07d62956fca86c59d91b9ad32997e633c38b526623a3/ast_serialize-0.5.0-cp314-cp314t-win_arm64.whl", hash = "sha256:787baedb0262cc49e8ce37cc15c00ae818e46a165a3b36f5e21ed174998104cb", size = 1075347, upload-time = "2026-05-17T17:48:01.753Z" }, - { url = "https://files.pythonhosted.org/packages/e0/9e/dc2530acb3a60dc6e46d65abf27d1d9f86721694757906a148d90a6860de/ast_serialize-0.5.0-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:0668aa9459cfa8c9c49ddd2163ebcf43088ba045ef7492af6fe22e0098303101", size = 1191380, upload-time = "2026-05-17T17:48:03.738Z" }, - { url = "https://files.pythonhosted.org/packages/26/0a/bd3d18a582f273d6c843d16bb9e22e9e16365ff7991e92f18f798e9f1224/ast_serialize-0.5.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:bf683d6363edf2b39eed6b6d4fe22d34b6203867a67e27134d9e2a2680c4bc4a", size = 1183879, upload-time = "2026-05-17T17:48:05.463Z" }, - { url = "https://files.pythonhosted.org/packages/40/ae/1f919100f8620887af58fcc381c61a1f218cdf89c6e155f87b213e61010a/ast_serialize-0.5.0-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9cc22cf0c9be65e71cf88fda130af60d61eb4a79370ad4cfe7900d48a4aa2211", size = 1244529, upload-time = "2026-05-17T17:48:07.008Z" }, - { url = "https://files.pythonhosted.org/packages/c6/ca/6376559dcce707cdbc1d0d9a13c8d3baaaa501e949ce0ebdc4230cd881aa/ast_serialize-0.5.0-cp39-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f66173891548c9f2726bf27957b41cabce12fa679dc6da505ddbde4d4b3b31cf", size = 1240560, upload-time = "2026-05-17T17:48:08.46Z" }, - { url = "https://files.pythonhosted.org/packages/35/b2/a620e206b5aeb7efbf2710336df57d457cffbb3991076bbcc1147ef9abd4/ast_serialize-0.5.0-cp39-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e42d729ef2be96a14efbad355093284739e3670ece3e534f82cc8832790911d9", size = 1451172, upload-time = "2026-05-17T17:48:09.922Z" }, - { url = "https://files.pythonhosted.org/packages/fa/e0/4ad5c04c24a40481b2935ce9a0ccdb6023dc8b667167d06ae530cc3512f2/ast_serialize-0.5.0-cp39-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b725026bafa801dbd7310eb13a75f0a2e370e7e51b2cb225f9d21fcfadf919ee", size = 1265072, upload-time = "2026-05-17T17:48:11.469Z" }, - { url = "https://files.pythonhosted.org/packages/b2/71/4d1d479aa56d0101c40e17720c3d6ac2af7269ea0487a80b18e7bfd1a5b7/ast_serialize-0.5.0-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b54f60c1d78767a53b67eaa663f0dfac3afe606aa07f1301572f588b73d64809", size = 1270488, upload-time = "2026-05-17T17:48:13.575Z" }, - { url = "https://files.pythonhosted.org/packages/6d/4f/0de1bbe06f6edef9fde4ed12ca8e7b3ec7e6e2bd4e672c5af487f7957665/ast_serialize-0.5.0-cp39-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:27d51654fc240a1e87e742d353d98eb45b75f62f129086b3596ab53df2ac2a43", size = 1260702, upload-time = "2026-05-17T17:48:15.141Z" }, - { url = "https://files.pythonhosted.org/packages/75/61/e00872439cfdddcc3c1b6cdaa6e5d904ba8e26a18807c67c4e14409d0ca8/ast_serialize-0.5.0-cp39-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:2782c36237c46dd1674542f2109740ea5ea485a169bf1431939ada0434e17934", size = 1311182, upload-time = "2026-05-17T17:48:16.779Z" }, - { url = "https://files.pythonhosted.org/packages/76/8e/699a5b955f7926956c95e9e1d74132acad73c2fe7a426f94da89123c20aa/ast_serialize-0.5.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1943db345233cc7194a470f13afa9c59772c0b123dea0c9414c4d4ca54369759", size = 1421410, upload-time = "2026-05-17T17:48:18.527Z" }, - { url = "https://files.pythonhosted.org/packages/a9/ae/d5b7626874478997adc7a29ab28accf21e596fb590c944290401dfd0b29e/ast_serialize-0.5.0-cp39-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:df1c00022cbbcb064bfaa505aa9c9295362443ce5dacb459d1331d3da353f887", size = 1516587, upload-time = "2026-05-17T17:48:20.133Z" }, - { url = "https://files.pythonhosted.org/packages/0c/ce/b59e02a82d9c4244d64cde502e0b00e83e38816abe19155ceb5437402c7f/ast_serialize-0.5.0-cp39-abi3-musllinux_1_2_i686.whl", hash = "sha256:cae65289fc456fde04af979a2be09302ef5d8ab92ef23e596d6746dc267ada27", size = 1515171, upload-time = "2026-05-17T17:48:21.921Z" }, - { url = "https://files.pythonhosted.org/packages/8b/38/d8d90042747d05aa08d4efcf1c99035a5f670a6bf4c214d31644392afbca/ast_serialize-0.5.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:239a4c354e8d676e9d94631d1d4a64edc6b266f86ff3a5a80aedd344f342c01d", size = 1464668, upload-time = "2026-05-17T17:48:23.544Z" }, - { url = "https://files.pythonhosted.org/packages/dd/51/5b840c4df7334104cecffa28f23904fe81ca89ca223d2450e288de39fd3c/ast_serialize-0.5.0-cp39-abi3-win32.whl", hash = "sha256:143a4ef63285a075871908fda3672dc21864b83a8ec3ee12304aa3e4c5387b9a", size = 1068311, upload-time = "2026-05-17T17:48:25.027Z" }, - { url = "https://files.pythonhosted.org/packages/41/11/ca5672c7d491825bc4cd6702dea106a6b60d928707712ec257c7833ae476/ast_serialize-0.5.0-cp39-abi3-win_amd64.whl", hash = "sha256:cf25572c526add400f26a4750dc6ce0c3bb93fc1f75e7ae0cad4ce4f2cd5c590", size = 1108931, upload-time = "2026-05-17T17:48:26.591Z" }, - { url = "https://files.pythonhosted.org/packages/45/19/cc8bd127d28a43da249aa955cfd164cf8fd534e79e42cea96c4854d72fd0/ast_serialize-0.5.0-cp39-abi3-win_arm64.whl", hash = "sha256:92a31c9c20d25a076edaeec76b128a3535d74a24f340b9a8a7e96c9b86dc9642", size = 1081181, upload-time = "2026-05-17T17:48:28.122Z" }, -] - [[package]] name = "async-timeout" version = "5.0.1" @@ -1373,7 +1333,7 @@ requires-dist = [ { name = "fpdf2", marker = "extra == 'pdf'", specifier = ">=2.7.0" }, { name = "langchain", specifier = ">=0.3.19" }, { name = "langgraph", specifier = ">=0.3.1" }, - { name = "mypy", marker = "extra == 'dev'", specifier = ">=1.10" }, + { name = "mypy", marker = "extra == 'dev'", specifier = ">=1.10,<2" }, { name = "openai", specifier = ">=1.65.1" }, { name = "pandas", specifier = ">=2.2.3" }, { name = "pip-audit", marker = "extra == 'dev'", specifier = ">=2.7" }, @@ -1946,53 +1906,52 @@ wheels = [ [[package]] name = "mypy" -version = "2.1.0" +version = "1.20.2" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "ast-serialize" }, { name = "librt", marker = "platform_python_implementation != 'PyPy'" }, { name = "mypy-extensions" }, { name = "pathspec" }, { name = "typing-extensions" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/82/15/cca9d88503549ed6fedeaa1d448cdddd542ee8a490232d732e278036fbf2/mypy-2.1.0.tar.gz", hash = "sha256:81e76ad12c2d804512e9b13240d1588316531bfba07558286078bfbce9613633", size = 3898359, upload-time = "2026-05-11T18:37:36.237Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/0a/a1/639f3024794a2a15899cb90707fe02e044c4412794c39c5769fd3df2e2ef/mypy-2.1.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a683016b16fe2f572dc04c72be7ee0504ac1605a265d0200f5cea695fb788f41", size = 14691685, upload-time = "2026-05-11T18:33:27.973Z" }, - { url = "https://files.pythonhosted.org/packages/3b/08/9a585dea4325f20d8b80dc78623fa50d1fd2173b710f6237afd6ba6ab39b/mypy-2.1.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:1a293c534adb55271fef24a26da04b855540a8c13cc07bc5917b9fd2c394f2ca", size = 13555165, upload-time = "2026-05-11T18:32:16.107Z" }, - { url = "https://files.pythonhosted.org/packages/81/dc/7c42cc9c6cb01e8eb09961f1f738741d3e9c7e9d5c5b30ec69222625cd5f/mypy-2.1.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7406f4d048e71e576f5356d317e5b0a9e666dfd966bd99f9d14ca06e1a341538", size = 13994376, upload-time = "2026-05-11T18:32:39.256Z" }, - { url = "https://files.pythonhosted.org/packages/d4/fa/285946c33bce716e082c11dfeee9ee196eaf1f5042efb3581a31f9f205e4/mypy-2.1.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e0210d626fc8b31ccc90233754c7bc90e1f43205e85d96387f7db1285b55c398", size = 14864618, upload-time = "2026-05-11T18:34:49.765Z" }, - { url = "https://files.pythonhosted.org/packages/2b/83/82397f48af6c27e295d57979ded8490c9829040152cf7571b2f026aeb9a0/mypy-2.1.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:3712c20deed54e814eaaa825603bada8ea1c390670a397c95b98405347acc563", size = 15102063, upload-time = "2026-05-11T18:34:05.855Z" }, - { url = "https://files.pythonhosted.org/packages/40/68/b02dec39057b88eb03dc0aa854732e26e8361f34f9d0e20c7614967d1eba/mypy-2.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:fcaa0e479066e31f7cceb6a3bea39cb22b2ff51a6b2f24f193d19179ba17c389", size = 11060564, upload-time = "2026-05-11T18:35:36.494Z" }, - { url = "https://files.pythonhosted.org/packages/cf/a8/ea3dcbef31f99b634f2ee23bb0321cbc8c1b388b76a861eb849f13c347dc/mypy-2.1.0-cp311-cp311-win_arm64.whl", hash = "sha256:0b1a5260c95aa443083f9ed3592662941951bca3d4ca224a5dc517c38b7cf666", size = 9966983, upload-time = "2026-05-11T18:37:14.139Z" }, - { url = "https://files.pythonhosted.org/packages/95/b1/55861beb5c339b44f9a2ba92df9e2cb1eeb4ae1eee674cdf7772c797778b/mypy-2.1.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:244358bf1c0da7722230bce60683d52e8e9fd030554926f15b747a84efb5b3af", size = 14874381, upload-time = "2026-05-11T18:37:31.784Z" }, - { url = "https://files.pythonhosted.org/packages/0b/b3/b7f770114b7d0ac92d0f76e8d93c2780844a70488a90e91821927850da86/mypy-2.1.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4ec7c57657493c7a75534df2751c8ae2cda383c16ecc55d2106c54476b1b16f6", size = 13665501, upload-time = "2026-05-11T18:34:23.063Z" }, - { url = "https://files.pythonhosted.org/packages/b6/f3/8ae2037967e2126689a0c11d99e2b707134a565191e92c60ca2572aec60a/mypy-2.1.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d8161b6ff4392410023224f0969d17db93e1e154bc3e4ba62598e720723ae211", size = 14045750, upload-time = "2026-05-11T18:31:48.151Z" }, - { url = "https://files.pythonhosted.org/packages/a0/32/615eb5911859e43d054941b0d0a7d06cfa2870eba86529cf385b052b111c/mypy-2.1.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bf03e12003084a67395184d3eb8cbd6a489dc3655b5664b28c210a9e2403ab0b", size = 15061630, upload-time = "2026-05-11T18:37:06.898Z" }, - { url = "https://files.pythonhosted.org/packages/d4/03/4eafbfff8bfab1b87082741eae6e6a624028c984e6708b73bce2a8570c9d/mypy-2.1.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:20509760fd791c51579d573153407d226385ec1f8bcce55d730b354f3336bc22", size = 15288831, upload-time = "2026-05-11T18:31:18.07Z" }, - { url = "https://files.pythonhosted.org/packages/99/ee/919661478e5891a3c96e549c036e467e64563ab85995b10c53c8358e16a3/mypy-2.1.0-cp312-cp312-win_amd64.whl", hash = "sha256:6753d0c1fdd6b1a23b9e4f283ce80b2153b724adcb2653b20b85a8a28ac6436b", size = 11135228, upload-time = "2026-05-11T18:34:31.23Z" }, - { url = "https://files.pythonhosted.org/packages/24/0a/6a12b9782ca0831a553192f351679f4548abc9d19a7cc93bb7feb02084c7/mypy-2.1.0-cp312-cp312-win_arm64.whl", hash = "sha256:98ebb6589bb3b6d0c6f0c459d53ca55b8091fbc13d277c4041c885392e8195e8", size = 10040684, upload-time = "2026-05-11T18:36:48.199Z" }, - { url = "https://files.pythonhosted.org/packages/6e/dd/c7191469c777f07689c032a8f7326e393ea34c92d6d76eb7ce5ba57ea66d/mypy-2.1.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:35aac3bb114e03888f535d5eb51b8bafbb3266586b599da1940f9b1be3ec5bd5", size = 14852174, upload-time = "2026-05-11T18:31:38.929Z" }, - { url = "https://files.pythonhosted.org/packages/55/8c/aed55408879043d72bb9135f4d0d19a02b886dd569631e113e3d2706cb8d/mypy-2.1.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:8de55a8c861f2a49331f807be98d90caeceeef520bde13d43a160207f8af613e", size = 13651542, upload-time = "2026-05-11T18:36:04.636Z" }, - { url = "https://files.pythonhosted.org/packages/3a/8e/f371a824b1f1fa8ea6e3dbb8703d232977d572be2329554a3bc4d960302f/mypy-2.1.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5fdf2941a07434af755837d9880f7d7d25f1dacb1af9dcd4b9b66f2220a3024e", size = 14033929, upload-time = "2026-05-11T18:35:55.742Z" }, - { url = "https://files.pythonhosted.org/packages/94/21/f54be870d6dd53a82c674407e0f8eed7174b05ec78d42e5abd7b42e84fd5/mypy-2.1.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e195b817c13f02352a9c124301f9f30f078405444679b6753c1b96b6eed37285", size = 15039200, upload-time = "2026-05-11T18:33:10.281Z" }, - { url = "https://files.pythonhosted.org/packages/17/99/bf21748626a40ce59fd29a39386ab46afec88b7bd2f0fa6c3a97c995523f/mypy-2.1.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:5431d42af987ebd92ba2f71d45c85ed41d8e6ca9f5fd209a69f68f707d2469e5", size = 15272690, upload-time = "2026-05-11T18:32:07.205Z" }, - { url = "https://files.pythonhosted.org/packages/d6/d7/9e90d2cf47100bea550ed2bc7b0d4de3a62181d84d5e37da0003e8462637/mypy-2.1.0-cp313-cp313-win_amd64.whl", hash = "sha256:767fe8c66dc3e01e19e1737d4c38ebefead16125e1b8e58ad421903b376f5c65", size = 11147435, upload-time = "2026-05-11T18:33:56.477Z" }, - { url = "https://files.pythonhosted.org/packages/ec/46/e5c449e858798e35ffc90946282a27c62a77be743fe17480e4977374eb91/mypy-2.1.0-cp313-cp313-win_arm64.whl", hash = "sha256:ecfe70d43775ab99562ab128ce49854a362044c9f894961f68f898c23cb7429d", size = 10035052, upload-time = "2026-05-11T18:32:30.049Z" }, - { url = "https://files.pythonhosted.org/packages/b0/ca/b279a672e874aedd5498ae25f722dacc8aa86bbffb939b3f97cbb1cf6686/mypy-2.1.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:7354c5a7f69d9345c3d6e69921d57088eea3ddeeb6b20d34c1b3855b02c36ec2", size = 14848422, upload-time = "2026-05-11T18:35:45.984Z" }, - { url = "https://files.pythonhosted.org/packages/27/e6/3efe56c631d959b9b4454e208b0ac4b7f4f58b404c89f8bec7b49efdfc21/mypy-2.1.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:49890d4f76ac9e06ec117f9e09f3174da70a620a0c300953d8595c926e80947f", size = 13677374, upload-time = "2026-05-11T18:36:57.188Z" }, - { url = "https://files.pythonhosted.org/packages/84/7f/8107ea87a44fd1f1b59882442f033c9c3488c127201b1d1d15f1cbd6022e/mypy-2.1.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:761be68e023ef5d94678772396a8af1220030f80837a3afd8d0aef3b419666f4", size = 14055743, upload-time = "2026-05-11T18:35:18.361Z" }, - { url = "https://files.pythonhosted.org/packages/51/4d/b6d34db183133b83761b9199a82d31557cdbb70a380d8c3b3438e11882a3/mypy-2.1.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c90345fc182dc363b891350457ec69c35140858538f38b4540845afcc32b1aef", size = 15020937, upload-time = "2026-05-11T18:34:59.618Z" }, - { url = "https://files.pythonhosted.org/packages/ff/d7/f08360c691d758acb02f45022c34d98b92892f4ea756644e1000d4b9f3d8/mypy-2.1.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:b84802e7b5a6daf1f5e15bc9fcd7ddae77be13981ffab037f1c67bb84d67d135", size = 15253371, upload-time = "2026-05-11T18:36:41.081Z" }, - { url = "https://files.pythonhosted.org/packages/67/1b/09460a13719530a19bce27bd3bc8449e83569dd2ba7faf51c9c3c30c0b61/mypy-2.1.0-cp314-cp314-win_amd64.whl", hash = "sha256:022c771234936ceac541ebaf836fe9e2abeb3f5e09aff21588fe543ff006fe21", size = 11326429, upload-time = "2026-05-11T18:34:13.526Z" }, - { url = "https://files.pythonhosted.org/packages/40/62/75dbf0f82f7b6680340efc614af29dd0b3c17b8a4f1cd09b8bd2fd6bc814/mypy-2.1.0-cp314-cp314-win_arm64.whl", hash = "sha256:498207db725cec88829a6a5c2fc771205fd043719ef98bc49aba8fb9fc4e6d57", size = 10218799, upload-time = "2026-05-11T18:32:23.491Z" }, - { url = "https://files.pythonhosted.org/packages/b2/66/caca04ed7d972fb6eb6dd1ccd6df1de5c38fae8c5b3dc1c4e8e0d85ee6b9/mypy-2.1.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7d5e5cad0efeba72b93cd17490cc0d69c5ac9ca132994fe3fb0314808aeeb83e", size = 15923458, upload-time = "2026-05-11T18:35:28.64Z" }, - { url = "https://files.pythonhosted.org/packages/ed/52/2d90cbe49d014b13ed7ff337930c30bad35893fe38a1e4641e756bb62191/mypy-2.1.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ff715050c127d724fd260a2e666e7747fdd83511c0c47d449d98238970aef780", size = 14757697, upload-time = "2026-05-11T18:36:14.208Z" }, - { url = "https://files.pythonhosted.org/packages/ac/37/d98f4a14e081b238992d0ed96b6d39c7cc0148c9699eb71eaa68629665ea/mypy-2.1.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:82208da9e09414d520e912d3e462d454854bed0810b71540bb016dcbca7308fd", size = 15405638, upload-time = "2026-05-11T18:33:48.249Z" }, - { url = "https://files.pythonhosted.org/packages/a3/c2/15c46613b24a84fad2aea1248bf9619b99c2767ae9071fe224c179a0b7d4/mypy-2.1.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e79ebc1b904b84f0310dff7469655a9c36c7a68bddb37bdd42b67a332df61d08", size = 16215852, upload-time = "2026-05-11T18:32:50.296Z" }, - { url = "https://files.pythonhosted.org/packages/5c/90/9c16a57f482c76d25f6379762b56bbf65c711d8158cf271fb2802cfb0640/mypy-2.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:e583edc957cfb0deb142079162ae826f58449b116c1d442f2d91c69d9fced081", size = 16452695, upload-time = "2026-05-11T18:33:38.182Z" }, - { url = "https://files.pythonhosted.org/packages/0f/4c/215a4eeb63cacc5f17f516691ea7285d11e249802b942476bff15922a314/mypy-2.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:b33b6cd332695bba180d55e717a79d3038e479a2c49cc5eb3d53603409b9a5d7", size = 12866622, upload-time = "2026-05-11T18:34:39.945Z" }, - { url = "https://files.pythonhosted.org/packages/4b/50/1043e1db5f455ffe4c9ab22747cd8ca2bc492b1e4f4e21b130a44ee2b217/mypy-2.1.0-cp314-cp314t-win_arm64.whl", hash = "sha256:4f910fe825376a7b66ef7ca8c98e5a149e8cd64c19ae71d84047a74ee060d4e6", size = 10610798, upload-time = "2026-05-11T18:36:31.444Z" }, - { url = "https://files.pythonhosted.org/packages/0d/2a/13ca1f292f6db1b98ff495ef3467736b331621c5917cad984b7043e7348d/mypy-2.1.0-py3-none-any.whl", hash = "sha256:a663814603a5c563fb87a4f96fb473eeb30d1f5a4885afcf44f9db000a366289", size = 2693302, upload-time = "2026-05-11T18:31:29.246Z" }, +sdist = { url = "https://files.pythonhosted.org/packages/04/af/e3d4b3e9ec91a0ff9aabfdb38692952acf49bbb899c2e4c29acb3a6da3ae/mypy-1.20.2.tar.gz", hash = "sha256:e8222c26daaafd9e8626dec58ae36029f82585890589576f769a650dd20fd665", size = 3817349, upload-time = "2026-04-21T17:12:28.473Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1f/4d/9ebeae211caccbdaddde7ed5e31dfcf57faac66be9b11deb1dc6526c8078/mypy-1.20.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4077797a273e56e8843d001e9dfe4ba10e33323d6ade647ff260e5cd97d9758c", size = 14371307, upload-time = "2026-04-21T17:08:56.442Z" }, + { url = "https://files.pythonhosted.org/packages/95/d7/93473d34b61f04fac1aecc01368485c89c5c4af7a4b9a0cab5d77d04b63f/mypy-1.20.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:cdecf62abcc4292500d7858aeae87a1f8f1150f4c4dd08fb0b336ee79b2a6df3", size = 13258917, upload-time = "2026-04-21T17:05:50.978Z" }, + { url = "https://files.pythonhosted.org/packages/e2/30/3dd903e8bafb7b5f7bf87fcd58f8382086dea2aa19f0a7b357f21f63071b/mypy-1.20.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c566c3a88b6ece59b3d70f65bedef17304f48eb52ff040a6a18214e1917b3254", size = 13700516, upload-time = "2026-04-21T17:11:33.161Z" }, + { url = "https://files.pythonhosted.org/packages/07/05/c61a140aba4c729ac7bc99ae26fc627c78a6e08f5b9dd319244ea71a3d7e/mypy-1.20.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0deb80d062b2479f2c87ae568f89845afc71d11bc41b04179e58165fd9f31e98", size = 14562889, upload-time = "2026-04-21T17:05:27.674Z" }, + { url = "https://files.pythonhosted.org/packages/fd/87/da78243742ffa8a36d98c3010f0d829f93d5da4e6786f1a1a6f2ad616502/mypy-1.20.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:bba9ad231e92a3e424b3e56b65aa17704993425bba97e302c832f9466bb85bac", size = 14803844, upload-time = "2026-04-21T17:10:06.2Z" }, + { url = "https://files.pythonhosted.org/packages/37/52/10a1ddf91b40f843943a3c6db51e2df59c9e237f29d355e95eaab427461f/mypy-1.20.2-cp311-cp311-win_amd64.whl", hash = "sha256:baf593f2765fa3a6b1ef95807dbaa3d25b594f6a52adcc506a6b9cb115e1be67", size = 10846300, upload-time = "2026-04-21T17:12:23.886Z" }, + { url = "https://files.pythonhosted.org/packages/20/02/f9a4415b664c53bd34d6709be59da303abcae986dc4ac847b402edb6fa1e/mypy-1.20.2-cp311-cp311-win_arm64.whl", hash = "sha256:20175a1c0f49863946ec20b7f63255768058ac4f07d2b9ded6a6b46cfb5a9100", size = 9779498, upload-time = "2026-04-21T17:09:23.695Z" }, + { url = "https://files.pythonhosted.org/packages/71/4e/7560e4528db9e9b147e4c0f22660466bf30a0a1fe3d63d1b9d3b0fd354ee/mypy-1.20.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4dbfcf869f6b0517f70cf0030ba6ea1d6645e132337a7d5204a18d8d5636c02b", size = 14539393, upload-time = "2026-04-21T17:07:12.52Z" }, + { url = "https://files.pythonhosted.org/packages/32/d9/34a5efed8124f5a9234f55ac6a4ced4201e2c5b81e1109c49ad23190ec8c/mypy-1.20.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:4b6481b228d072315b053210b01ac320e1be243dc17f9e5887ef167f23f5fae4", size = 13361642, upload-time = "2026-04-21T17:06:53.742Z" }, + { url = "https://files.pythonhosted.org/packages/d1/14/eb377acf78c03c92d566a1510cda8137348215b5335085ef662ab82ecd3a/mypy-1.20.2-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:34397cdced6b90b836e38182076049fdb41424322e0b0728c946b0939ebdf9f6", size = 13740347, upload-time = "2026-04-21T17:12:04.73Z" }, + { url = "https://files.pythonhosted.org/packages/b9/94/7e4634a32b641aa1c112422eed1bbece61ee16205f674190e8b536f884de/mypy-1.20.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a5da6976f20cae27059ea8d0c86e7cef3de720e04c4bb9ee18e3690fdb792066", size = 14734042, upload-time = "2026-04-21T17:07:43.16Z" }, + { url = "https://files.pythonhosted.org/packages/7a/f3/f7e62395cb7f434541b4491a01149a4439e28ace4c0c632bbf5431e92d1f/mypy-1.20.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:56908d7e08318d39f85b1f0c6cfd47b0cac1a130da677630dac0de3e0623e102", size = 14964958, upload-time = "2026-04-21T17:11:00.665Z" }, + { url = "https://files.pythonhosted.org/packages/3e/0d/47e3c3a0ec2a876e35aeac365df3cac7776c36bbd4ed18cc521e1b9d255b/mypy-1.20.2-cp312-cp312-win_amd64.whl", hash = "sha256:d52ad8d78522da1d308789df651ee5379088e77c76cb1994858d40a426b343b9", size = 10911340, upload-time = "2026-04-21T17:10:49.179Z" }, + { url = "https://files.pythonhosted.org/packages/d6/b2/6c852d72e0ea8b01f49da817fb52539993cde327e7d010e0103dc12d0dac/mypy-1.20.2-cp312-cp312-win_arm64.whl", hash = "sha256:785b08db19c9f214dc37d65f7c165d19a30fcecb48abfa30f31b01b5acaabb58", size = 9833947, upload-time = "2026-04-21T17:09:05.267Z" }, + { url = "https://files.pythonhosted.org/packages/5b/c4/b93812d3a192c9bcf5df405bd2f30277cd0e48106a14d1023c7f6ed6e39b/mypy-1.20.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:edfbfca868cdd6bd8d974a60f8a3682f5565d3f5c99b327640cedd24c4264026", size = 14524670, upload-time = "2026-04-21T17:10:30.737Z" }, + { url = "https://files.pythonhosted.org/packages/f3/47/42c122501bff18eaf1e8f457f5c017933452d8acdc52918a9f59f6812955/mypy-1.20.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:e2877a02380adfcdbc69071a0f74d6e9dbbf593c0dc9d174e1f223ffd5281943", size = 13336218, upload-time = "2026-04-21T17:08:44.069Z" }, + { url = "https://files.pythonhosted.org/packages/92/8f/75bbc92f41725fbd585fb17b440b1119b576105df1013622983e18640a93/mypy-1.20.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7488448de6007cd5177c6cea0517ac33b4c0f5ee9b5e9f2be51ce75511a85517", size = 13724906, upload-time = "2026-04-21T17:08:01.02Z" }, + { url = "https://files.pythonhosted.org/packages/a1/32/4c49da27a606167391ff0c39aa955707a00edc500572e562f7c36c08a71f/mypy-1.20.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bb9c2fa06887e21d6a3a868762acb82aec34e2c6fd0174064f27c93ede68ad15", size = 14726046, upload-time = "2026-04-21T17:11:22.354Z" }, + { url = "https://files.pythonhosted.org/packages/7f/fc/4e354a1bd70216359deb0c9c54847ee6b32ef78dfb09f5131ff99b494078/mypy-1.20.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:9d56a78b646f2e3daa865bc70cd5ec5a46c50045801ca8ff17a0c43abc97e3ee", size = 14955587, upload-time = "2026-04-21T17:12:16.033Z" }, + { url = "https://files.pythonhosted.org/packages/62/b2/c0f2056e9eb8f08c62cafd9715e4584b89132bdc832fcf85d27d07b5f3e5/mypy-1.20.2-cp313-cp313-win_amd64.whl", hash = "sha256:2a4102b03bb7481d9a91a6da8d174740c9c8c4401024684b9ca3b7cc5e49852f", size = 10922681, upload-time = "2026-04-21T17:06:35.842Z" }, + { url = "https://files.pythonhosted.org/packages/e5/14/065e333721f05de8ef683d0aa804c23026bcc287446b61cac657b902ccac/mypy-1.20.2-cp313-cp313-win_arm64.whl", hash = "sha256:a95a9248b0c6fd933a442c03c3b113c3b61320086b88e2c444676d3fd1ca3330", size = 9830560, upload-time = "2026-04-21T17:07:51.023Z" }, + { url = "https://files.pythonhosted.org/packages/ae/d1/b4ec96b0ecc620a4443570c6e95c867903428cfcde4206518eafdd5880c3/mypy-1.20.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:419413398fe250aae057fd2fe50166b61077083c9b82754c341cf4fd73038f30", size = 14524561, upload-time = "2026-04-21T17:06:27.325Z" }, + { url = "https://files.pythonhosted.org/packages/3a/63/d2c2ff4fa66bc49477d32dfa26e8a167ba803ea6a69c5efb416036909d30/mypy-1.20.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e73c07f23009962885c197ccb9b41356a30cc0e5a1d0c2ea8fd8fb1362d7f924", size = 13363883, upload-time = "2026-04-21T17:11:11.239Z" }, + { url = "https://files.pythonhosted.org/packages/2a/56/983916806bf4eddeaaa2c9230903c3669c6718552a921154e1c5182c701f/mypy-1.20.2-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0c64e5973df366b747646fc98da921f9d6eba9716d57d1db94a83c026a08e0fb", size = 13742945, upload-time = "2026-04-21T17:08:34.181Z" }, + { url = "https://files.pythonhosted.org/packages/19/65/0cd9285ab010ee8214c83d67c6b49417c40d86ce46f1aa109457b5a9b8d7/mypy-1.20.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5a65aa591af023864fd08a97da9974e919452cfe19cb146c8a5dc692626445dc", size = 14706163, upload-time = "2026-04-21T17:05:15.51Z" }, + { url = "https://files.pythonhosted.org/packages/94/97/48ff3b297cafcc94d185243a9190836fb1b01c1b0918fff64e941e973cc9/mypy-1.20.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:4fef51b01e638974a6e69885687e9bd40c8d1e09a6cd291cca0619625cf1f558", size = 14938677, upload-time = "2026-04-21T17:05:39.562Z" }, + { url = "https://files.pythonhosted.org/packages/fd/a1/1b4233d255bdd0b38a1f284feeb1c143ca508c19184964e22f8d837ec851/mypy-1.20.2-cp314-cp314-win_amd64.whl", hash = "sha256:913485a03f1bcf5d279409a9d2b9ed565c151f61c09f29991e5faa14033da4c8", size = 11089322, upload-time = "2026-04-21T17:06:44.29Z" }, + { url = "https://files.pythonhosted.org/packages/78/c2/ce7ee2ba36aeb954ba50f18fa25d9c1188578654b97d02a66a15b6f09531/mypy-1.20.2-cp314-cp314-win_arm64.whl", hash = "sha256:c3bae4f855d965b5453784300c12ffc63a548304ac7f99e55d4dc7c898673aa3", size = 10017775, upload-time = "2026-04-21T17:07:20.732Z" }, + { url = "https://files.pythonhosted.org/packages/4e/a1/9d93a7d0b5859af0ead82b4888b46df6c8797e1bc5e1e262a08518c6d48e/mypy-1.20.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:2de3dcea53babc1c3237a19002bc3d228ce1833278f093b8d619e06e7cc79609", size = 15549002, upload-time = "2026-04-21T17:08:23.107Z" }, + { url = "https://files.pythonhosted.org/packages/00/d2/09a6a10ee1bf0008f6c144d9676f2ca6a12512151b4e0ad0ff6c4fac5337/mypy-1.20.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:52b176444e2e5054dfcbcb8c75b0b719865c96247b37407184bbfca5c353f2c2", size = 14401942, upload-time = "2026-04-21T17:07:31.837Z" }, + { url = "https://files.pythonhosted.org/packages/57/da/9594b75c3c019e805250bed3583bdf4443ff9e6ef08f97e39ae308cb06f2/mypy-1.20.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:688c3312e5dadb573a2c69c82af3a298d43ecf9e6d264e0f95df960b5f6ac19c", size = 15041649, upload-time = "2026-04-21T17:09:34.653Z" }, + { url = "https://files.pythonhosted.org/packages/97/77/f75a65c278e6e8eba2071f7f5a90481891053ecc39878cc444634d892abe/mypy-1.20.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:29752dbbf8cc53f89f6ac096d363314333045c257c9c75cbd189ca2de0455744", size = 15864588, upload-time = "2026-04-21T17:11:44.936Z" }, + { url = "https://files.pythonhosted.org/packages/d7/46/1a4e1c66e96c1a3246ddf5403d122ac9b0a8d2b7e65730b9d6533ba7a6d3/mypy-1.20.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:803203d2b6ea644982c644895c2f78b28d0e208bba7b27d9b921e0ec5eb207c6", size = 16093956, upload-time = "2026-04-21T17:10:17.683Z" }, + { url = "https://files.pythonhosted.org/packages/5a/2c/78a8851264dec38cd736ca5b8bc9380674df0dd0be7792f538916157716c/mypy-1.20.2-cp314-cp314t-win_amd64.whl", hash = "sha256:9bcb8aa397ff0093c824182fd76a935a9ba7ad097fcbef80ae89bf6c1731d8ec", size = 12568661, upload-time = "2026-04-21T17:11:54.473Z" }, + { url = "https://files.pythonhosted.org/packages/83/01/cd7318aa03493322ce275a0e14f4f52b8896335e4e79d4fb8153a7ad2b77/mypy-1.20.2-cp314-cp314t-win_arm64.whl", hash = "sha256:e061b58443f1736f8a37c48978d7ab581636d6ab03e3d4f99e3fa90463bb9382", size = 10389240, upload-time = "2026-04-21T17:09:42.719Z" }, + { url = "https://files.pythonhosted.org/packages/28/9a/f23c163e25b11074188251b0b5a0342625fc1cdb6af604757174fa9acc9b/mypy-1.20.2-py3-none-any.whl", hash = "sha256:a94c5a76ab46c5e6257c7972b6c8cff0574201ca7dc05647e33e795d78680563", size = 2637314, upload-time = "2026-04-21T17:05:54.5Z" }, ] [[package]]