diff --git a/.env.example b/.env.example index 665066c..88ad1f6 100644 --- a/.env.example +++ b/.env.example @@ -1,4 +1,15 @@ # Copy to .env and fill in whichever provider you want to use. +# +# Personal local use: ./scripts/run_local.sh sets PERSONAL_MODE=1 (no +# sign-up/login/billing/quotas; you're the single local owner). An Anthropic +# key also unlocks Claude's server-side web search for live company / salary +# research and open-web job discovery. +# PERSONAL_MODE=1 +# PERSONAL_OWNER_EMAIL=me@personal.local +# WEB_RESEARCH=1 # 0 = never use Claude web search +# ANTHROPIC_REFUSAL_FALLBACK=1 # server-side fallback model on refusals +# WEB_SEARCH_USD_PER_CALL=0.01 # cost ledger: $10 per 1,000 searches + # Auto-detection order: Anthropic -> OpenAI -> Featherless. # Override with LLM_PROVIDER=anthropic|openai|featherless. @@ -12,11 +23,22 @@ # Featherless (OpenAI-compatible, hosts Qwen / DeepSeek) # FEATHERLESS_API_KEY=... +# Model tiers ("Fast" / "Detailed" in the UI). Defaults: Anthropic +# claude-haiku-5-5 / claude-opus-5-5; OpenAI gpt-5-mini / gpt-5. +# Sonnet 5.5 halves Detailed-tier cost vs Opus 5.5 ($2/$10 vs $4/$20 per 1M tokens): +# ANTHROPIC_FAST_MODEL=claude-haiku-5-5 +# ANTHROPIC_DETAILED_MODEL=claude-sonnet-5-5 +# OPENAI_FAST_MODEL=gpt-5-mini +# OPENAI_DETAILED_MODEL=gpt-5 + # Tuning (optional) # LLM_PROVIDER=anthropic -# LLM_TEMPERATURE=0.4 -# LLM_MAX_TOKENS=2000 -# LLM_MAX_RETRIES=3 +# LLM_TEMPERATURE=0.4 # only sent to models that accept it +# LLM_MAX_TOKENS=16000 # thinking/reasoning tokens count toward this +# LLM_MAX_RETRIES=3 # transient errors only (timeouts, 429, 5xx) +# LLM_TIMEOUT_SECONDS=300 +# ANTHROPIC_EFFORT=low # low|medium|high; unset = model default +# OPENAI_REASONING_EFFORT=low # minimal|low|medium|high (gpt-5 / o-series) # Persistence # DATABASE_URL=postgresql://user:pass@localhost:5432/joboffer @@ -36,7 +58,8 @@ # 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) +# Adzuna — real salary benchmarks AND a UK/EU job-discovery source +# (free tier, ~1000 calls/month) # Sign up at https://developer.adzuna.com/ # ADZUNA_APP_ID=... # ADZUNA_APP_KEY=... @@ -125,6 +148,16 @@ # Telegram bot channel (alternative to the Streamlit UI) # TELEGRAM_BOT_TOKEN=... # from @BotFather +# /analyze requires a chat linked to a web account (metered like the web UI). +# Private single-user bots can allow anonymous chats instead: +# TELEGRAM_ALLOW_UNLINKED_ANALYZE=1 + +# Operators allowed to run the System test tab (live integration probes). +# Unset: everyone when billing is off (self-hosted), nobody when it's on. +# ADMIN_EMAILS=you@example.com + +# PDF export embeds the bundled DejaVu Unicode font from assets/fonts/. +# PDF_FONT_DIR=/path/to/dir/with/DejaVuSans.ttf+DejaVuSans-Bold.ttf # 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 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index b7c7b9a..391024f 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -33,11 +33,17 @@ jobs: with: python-version: "3.12" cache: pip - - name: Install deps + type stubs + # Type-check against the locked versions Replit installs (uv sync), not + # whatever pip resolves today: unpinned numpy 2.5 stubs use 3.12-only + # syntax that mypy rejects under python_version = 3.11, and drift like + # that should never be what turns the gate red. + - name: Lockfile matches pyproject run: | - python -m pip install --upgrade pip - pip install -e ".[telegram,worker,dev]" - - run: mypy + python -m pip install --upgrade pip "uv>=0.5" + uv lock --check + - name: Install locked deps + type stubs + run: uv sync --frozen --python python3.12 --extra telegram --extra worker --extra dev + - run: .venv/bin/mypy security: name: bandit + pip-audit @@ -170,6 +176,8 @@ jobs: "webhooks", "webhook_deliveries", "oauth_identities", "email_verification_tokens", "llm_usage", "subscriptions", "usage_events", "waitlist_entries", + "candidate_profiles", "discovered_jobs", "master_cv_revisions", + "password_reset_tokens", "telegram_link_tokens", } missing = required - tables assert not missing, f"missing tables after migrate: {missing}" diff --git a/.gitignore b/.gitignore index 1978989..9825a67 100644 --- a/.gitignore +++ b/.gitignore @@ -73,3 +73,4 @@ credentials.json !tests/**/*token* !services/**/*token* !db/**/*token* +backups/ diff --git a/.python-version b/.python-version new file mode 100644 index 0000000..2c07333 --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.11 diff --git a/CLAUDE.md b/CLAUDE.md index efd5886..90cb14f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -22,13 +22,16 @@ Postgres); a `docker-compose.yml` runs the full multi-service stack. ``` 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 +ui/ New UI modules split out of app.py (discover tab, + search-profile editor); app.py calls render_* funcs +agents/ Analysis pipeline: orchestrator + per-stage agents + orchestrator.py Checkpointed stage sequence: 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), html_extract (shared), - company_research (agentic keyless DuckDuckGo + Browserbase fallback) + company_research (Claude web research; keyless DuckDuckGo fallback), + job_sources (discovery connectors: public ATS + job-board APIs only) services/ Business logic (34 modules) — the bulk of the app auth, totp, oauth, api_tokens, rate_limit, audit (identity/security) applications, stages, analytics, timeline, background_analysis (tracking) @@ -67,7 +70,7 @@ app.py / api/ / bot/ entry points (UI, REST, Telegram) ▼ db/ SQLAlchemy models + session -agents/ (LangGraph pipeline) ─┐ +agents/ (analysis pipeline) ─┐ tools/ (LLM-facing tools) ├─▶ utils/ (LEAF — depends on nothing internal) ─┘ worker/ (Celery) consumes services; runs the same pipeline off-process. @@ -93,6 +96,20 @@ worker/ (Celery) consumes services; runs the same pipeline off-process. intentionally empty (no symbol re-exports) so a submodule is never shadowed by a same-named re-exported value. +### Feature isolation (personal mode) + +- **Core vs side features** are declared once in `utils/features.py`. Side + features (accounts, billing, api_tokens, webhooks, telegram, + notifications, sharing, background, audit_log, rate_limits) are checked + with `feature_enabled("")`. `PERSONAL_MODE=1` turns them all off. +- **What "off" means:** the web app doesn't import their modules (app.py + imports them inside `if not PERSONAL_MODE:`); service-level side effects + (webhook dispatch in stages/applications, billing gates in + `analysis_runner`) are skipped. +- **Enforced by** `PersonalModeIsolationTests` (fresh subprocess, asserts no + side-feature module is loaded). Keep new side-feature imports out of + core modules, or make them lazy. + ### Shared helpers — use these, don't re-roll them - **Config:** `utils/env.env_{str,bool,int,float}` — never `os.getenv(...) == @@ -213,6 +230,21 @@ same canned "TechCorp" text regardless of input) to the current product: ## Production-readiness roadmap (what's left) +> **Personal mode** (`PERSONAL_MODE=1`, default in `scripts/run_local.sh`): +> single local owner (`services/personal`), no auth/billing/quota UI. Search +> profile in `services/profile` (JSON doc, table `candidate_profiles`) feeds +> the report's "Fit for You" + verdict, discovery and triage. Job discovery: +> connectors in `tools/job_sources` (public ATS + job-board APIs only), +> pipeline in `services/discovery` (table `discovered_jobs`). Claude web +> research (`utils/llm.web_research`, server-side web search/fetch) powers +> company + salary research when an Anthropic key is set. +> +> **Superseded in part by `docs/ASSESSMENT.md` (2026-10-19)**: the current +> verified state, remaining paid-launch blockers, and P1 backlog. Some items +> marked ✅ below were not actually true at that point (e.g. 5 +> `use_container_width` sites remain). Local single-user launch: +> `./scripts/run_local.sh` (nothing in the app loads `.env` by itself). + The app is feature-complete and deployed, but several things stand between it and "production-grade for real multi-user traffic." Prioritized: diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md deleted file mode 100644 index ac96cc6..0000000 --- a/DEVELOPMENT.md +++ /dev/null @@ -1,169 +0,0 @@ - -# Development Documentation - -## Current Technical State - -### ✅ Completed Components - -#### Core Architecture -- **Agent System**: Modular agents for job analysis, company research, salary analysis -- **Tool Integration**: Structured tool system ready for API integrations -- **State Management**: Proper state passing between agents via orchestrator -- **Error Handling**: Comprehensive try-catch blocks and fallback mechanisms -- **Caching System**: In-memory caching for performance optimization - -#### User Interface -- **Streamlit App**: Clean, responsive interface with progress tracking -- **Form Validation**: Input validation and required field checking -- **Progress Feedback**: Real-time progress updates with stage information -- **Results Display**: Expandable sections for different analysis components -- **Model Selection**: User can choose between Fast/Detailed analysis modes - -#### Code Quality -- **Modular Design**: Clear separation of concerns across agents, tools, and utilities -- **Environment Variables**: Proper configuration management (no hardcoded secrets) -- **Mock System**: Comprehensive fallback system for demo purposes -- **Logging**: Debug output and error tracking throughout the system - -### 🔄 Mock/Simulated Components - -#### Data Sources (Ready for Real API Integration) -```python -# Current: Mock responses in utils/llm.py -# Future: Real API calls to: -tools/company_tools.py -> Financial APIs (Alpha Vantage, Yahoo Finance) -tools/salary_tools.py -> Salary APIs (Glassdoor, PayScale, Levels.fyi) -agents/company_analyzer.py -> News APIs, Review platforms -``` - -#### Analysis Functions -- **Company Financial Analysis**: Uses simulated financial health metrics -- **Salary Benchmarking**: Basic calculation formulas instead of market data -- **Cost of Living**: Placeholder multipliers rather than real location data -- **Company Culture**: Generated examples instead of real reviews - -### 🛠️ Technical Debt & Improvements Needed - -#### High Priority -1. **Real API Integration**: Replace mock responses with actual external API calls -2. **Database Layer**: Implement user data persistence (PostgreSQL ready in .env) -3. **Authentication System**: User accounts and session management -4. **Error Recovery**: Better error handling for external API failures - -#### Medium Priority -1. **Test Coverage**: Unit tests for agents and tools -2. **API Rate Limiting**: Implement rate limiting and retry mechanisms -3. **Data Validation**: Input sanitization and output validation -4. **Performance**: Optimize LLM calls and caching strategy - -#### Low Priority -1. **Code Documentation**: Add comprehensive docstrings -2. **Type Hints**: Complete type annotation coverage -3. **Code Formatting**: Implement black/pylint standards -4. **CI/CD Pipeline**: Automated testing and deployment - -### 📦 Dependencies & Security - -#### Current Dependencies (pyproject.toml) -```toml -dependencies = [ - "beautifulsoup4>=4.13.3", # Web scraping (for future use) - "langchain>=0.3.19", # LLM framework - "langgraph>=0.3.1", # Agent orchestration - "openai>=1.65.1", # LLM API client - "requests>=2.32.3", # HTTP client - "streamlit>=1.42.2", # Web interface - "twilio>=9.4.6", # SMS notifications (future) -] -``` - -#### Security Checklist -- ✅ No hardcoded API keys or secrets -- ✅ Environment variable usage for configuration -- ✅ Input validation in Streamlit forms -- ✅ Safe JSON parsing with error handling -- ❌ Missing: Input sanitization for LLM prompts -- ❌ Missing: Rate limiting for API calls -- ❌ Missing: User authentication/authorization - -### 🚀 Production Readiness Checklist - -#### MVP Ready Items -- [x] Core functionality working end-to-end -- [x] Clean user interface with good UX -- [x] Error handling and graceful degradation -- [x] Environment configuration system -- [x] Comprehensive documentation (README.md) - -#### Production Prerequisites -- [ ] Real external API integrations -- [ ] User authentication system -- [ ] Database setup and migrations -- [ ] Monitoring and logging system -- [ ] Rate limiting and API quotas -- [ ] Automated testing suite -- [ ] Deployment configuration -- [ ] Security audit and penetration testing - -### 🔌 API Integration Guide - -#### Priority 1: Core Data APIs -```python -# Company Financial Data -ALPHA_VANTAGE_API_KEY = "your_key" # Company financials -POLYGON_IO_API_KEY = "your_key" # Stock data - -# Salary Data -GLASSDOOR_PARTNER_ID = "your_id" # Salary benchmarks -LEVELS_FYI_API_KEY = "your_key" # Tech compensation - -# Cost of Living -NUMBEO_API_KEY = "your_key" # COL data -TELEPORT_API_KEY = "your_key" # City data -``` - -#### Priority 2: Enhanced Features -```python -# Company Intelligence -NEWS_API_KEY = "your_key" # Company news -CRUNCHBASE_API_KEY = "your_key" # Startup data - -# Job Market -LINKEDIN_API_KEY = "your_key" # Professional data -INDEED_PUBLISHER_ID = "your_id" # Job postings -``` - -### 📊 Performance Considerations - -#### Current Bottlenecks -1. **LLM API Calls**: Sequential processing of job → company → salary analysis -2. **No Async Processing**: Everything runs synchronously -3. **Limited Caching**: Only basic in-memory cache - -#### Optimization Opportunities -1. **Parallel Processing**: Run company and salary analysis simultaneously -2. **Smart Caching**: Cache API responses with TTL -3. **Batch Processing**: Group similar requests -4. **Progressive Loading**: Show partial results as they complete - -### 🎯 Next Development Sprint - -#### Week 1: Real API Integration -- [ ] Implement Alpha Vantage for company financials -- [ ] Add Glassdoor API for salary data -- [ ] Create API key management system - -#### Week 2: User System -- [ ] Add user authentication (OAuth/email) -- [ ] Implement application tracking database -- [ ] Create user dashboard - -#### Week 3: Enhanced Features -- [ ] CV tailoring functionality -- [ ] Cover letter generation -- [ ] Interview prep questions - -#### Week 4: Polish & Deploy -- [ ] Comprehensive testing -- [ ] Performance optimization -- [ ] Production deployment on Replit diff --git a/Dockerfile b/Dockerfile index ada49a9..5c8c3b8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,6 @@ # syntax=docker/dockerfile:1 -FROM python:3.12-slim AS base +# trixie ships postgresql-client 17; pg_dump must be >= the server (16). +FROM python:3.12-slim-trixie AS base ENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 \ @@ -7,9 +8,10 @@ ENV PYTHONUNBUFFERED=1 \ WORKDIR /app -# System deps: build tools for any wheels that need them; curl for healthchecks. +# System deps: build tools for any wheels that need them; curl for healthchecks; +# postgresql-client for scripts/backup_db.sh (run by the scheduler service). RUN apt-get update \ - && apt-get install -y --no-install-recommends build-essential curl \ + && apt-get install -y --no-install-recommends build-essential curl postgresql-client \ && rm -rf /var/lib/apt/lists/* # Install Python deps first (better layer caching). Copy only metadata so a @@ -17,7 +19,7 @@ RUN apt-get update \ COPY pyproject.toml ./ # Editable install needs the package dirs to exist at build time. COPY . . -RUN pip install --upgrade pip && pip install ".[telegram]" +RUN pip install --upgrade pip && pip install ".[telegram,worker,billing,research,pdf]" EXPOSE 5000 diff --git a/README.md b/README.md index 78bf596..deff673 100644 --- a/README.md +++ b/README.md @@ -426,32 +426,47 @@ round-trip requires running outside the allowlist (or adding these hosts to it). ## 🛠️ Technology Stack - **Frontend**: Streamlit -- **Backend**: Python with LangChain/LangGraph +- **Backend**: Python; a checkpointed multi-stage LLM pipeline (Anthropic / OpenAI / Featherless) with Claude web research - **AI Models**: Support for multiple LLMs (OpenAI, DeepSeek, Qwen) - **Caching**: In-memory caching system - **Architecture**: Agent-based orchestration pattern ## 🚀 Quick Start -1. **Clone and Setup**: - ```bash - # The project runs on Replit - click "Run" to start - # or manually run: - streamlit run app.py - ``` - -2. **Environment Variables**: - ```bash - # Add your API keys to .env file: - OPENAI_API_KEY=your_openai_key_here - # Add other API keys as you integrate real data sources - ``` - -3. **Usage**: - - Select analysis model (Fast or Detailed) - - Fill in basic job details - - Paste the full job description - - Click "Analyze Job" and wait for results +**Local (single user, SQLite):** + +```bash +uv sync --python 3.11 --extra research --extra pdf # Python 3.11/3.12 (not 3.14) +cp .env.example .env # set ANTHROPIC_API_KEY=... (or OPENAI_API_KEY=...) +./scripts/run_local.sh # http://127.0.0.1:5000 +``` + +`run_local.sh` exports `.env` (nothing in the app reads `.env` by itself), +applies Alembic migrations to `./data/joboffer.db`, binds to localhost only, +and starts in **personal mode**: no sign-up, login, billing or quotas; you're +the single local owner (`PERSONAL_MODE=0` runs the multi-user product). + +**Personal job search, in order:** +1. **📝 CV & Profile → 📄 Master CV**: upload or paste your full CV (the + source of truth every tailored document is checked against). +2. **👤 Search profile**: *Draft from my master CV*, then set target roles, + locations / remote region, salary floor, must-haves, dealbreakers, and a + **company watchlist** (auto-detects their Greenhouse / Lever / Ashby / + SmartRecruiters board). +3. **🔭 Discover**: *Refresh feed* pulls your watchlist + Arbeitnow, Remotive, + RemoteOK, HN "Who is hiring" (and Adzuna with a free key), filters and + ranks against your profile, and has Claude Haiku score fit for you. + *Search the web with Claude* finds postings beyond those sources. +4. **Deep analysis** on the promising ones: live, cited company and salary + research (Claude web search), a "Fit for You" section and a verdict that + respects your dealbreakers and floor, and an ATS match against your CV. +5. Save to **📌 My Applications**, log stages, generate a tailored CV / cover + letter (review the "new facts" check), export PDF; **📊 Analytics** tracks + your funnel. + +**Full stack (Docker Compose):** `docker compose up --build` (web + worker + +Redis + Postgres + scheduler). See `docs/ASSESSMENT.md` for the current +state, known gaps, and the launch checklist. ## 📁 Project Structure diff --git a/agents/company_analyzer.py b/agents/company_analyzer.py index 58ae46e..ad08d00 100644 --- a/agents/company_analyzer.py +++ b/agents/company_analyzer.py @@ -27,7 +27,19 @@ def analyze(state: Dict) -> Dict: ) if not company_name: - state["error"] = "Company analysis failed: company name missing from inputs and extraction." + # Recruiter / agency / stealth postings often don't name the employer. + # That's a property of the posting, not a failure: say so and let the + # rest of the pipeline (salary, resume fit, report) still run. + state["company_analysis"] = { + "stability_analysis": ( + "COMPANY NOT IDENTIFIED: the posting does not name the employer " + "(common for recruiter or agency listings), so no company research " + "was done. Treat stability as unknown and ask the recruiter who " + "the client is before investing time." + ), + } + if progress_callback: + progress_callback("company", 100, "Employer not named in posting; skipped research") return state try: diff --git a/agents/job_analyzer.py b/agents/job_analyzer.py index 1829fec..46253b6 100644 --- a/agents/job_analyzer.py +++ b/agents/job_analyzer.py @@ -10,12 +10,15 @@ def analyze(state: Dict) -> Dict: progress_callback = state.get("progress_callback") try: - # Use manual inputs as the source-of-truth for the basics when provided. - # Still run requirements extraction on the description for skill detail. - if isinstance(manual_inputs, dict) and manual_inputs.get("company_name"): - extracted = dict(manual_inputs) - else: - extracted = extract_job_details(job_posting, model) + # Always extract from the posting, then let any non-empty manual field + # override the extracted value. (Skipping extraction whenever a company + # name was typed used to drop location, seniority, skills and + # responsibilities from the report.) Copy: the extraction is cached. + extracted = dict(extract_job_details(job_posting, model)) + if isinstance(manual_inputs, dict): + for key, value in manual_inputs.items(): + if value.strip() if isinstance(value, str) else value: + extracted[key] = value requirements = analyze_requirements(job_posting, model) state["job_details"] = { diff --git a/agents/orchestrator.py b/agents/orchestrator.py index c164295..f689b66 100644 --- a/agents/orchestrator.py +++ b/agents/orchestrator.py @@ -2,8 +2,6 @@ from concurrent.futures import ThreadPoolExecutor from typing import Callable, Dict, Optional, TypedDict -from langgraph.graph import StateGraph - from agents import ( company_analyzer, job_analyzer, @@ -36,6 +34,7 @@ class JobAnalysisState(TypedDict, total=False): model: Optional[str] progress_callback: Optional[Callable] checkpoint_key: Optional[str] + profile_text: Optional[str] # --------------------------------------------------------------------------- @@ -179,19 +178,23 @@ def _generate_report_with_checkpoint(state: Dict) -> Dict: return state -def create_analysis_graph(): - workflow = StateGraph(JobAnalysisState) - workflow.add_node("analyze_job", _analyze_job_with_checkpoint) - workflow.add_node("analyze_company_and_salary", _analyze_company_and_salary) - workflow.add_node("analyze_resume", _analyze_resume_with_checkpoint) - workflow.add_node("generate_report", _generate_report_with_checkpoint) +# The pipeline is a fixed sequence (company and salary run in parallel inside +# their stage). Each stage takes and returns the shared state and is a no-op +# once an earlier stage set ``error``. (This was a LangGraph StateGraph with +# only linear edges and its own checkpointing: the dependency added ~200 ms +# of import time and no capability.) +_PIPELINE = ( + _analyze_job_with_checkpoint, + _analyze_company_and_salary, + _analyze_resume_with_checkpoint, + _generate_report_with_checkpoint, +) - workflow.add_edge("analyze_job", "analyze_company_and_salary") - workflow.add_edge("analyze_company_and_salary", "analyze_resume") - workflow.add_edge("analyze_resume", "generate_report") - workflow.set_entry_point("analyze_job") - return workflow.compile() +def _run_pipeline(state: Dict) -> Dict: + for stage in _PIPELINE: + state = stage(state) + return state def run_analysis( @@ -201,17 +204,20 @@ def run_analysis( progress_callback: Optional[Callable] = None, resume_text: Optional[str] = None, checkpoint_key: Optional[str] = None, + profile_text: Optional[str] = None, ) -> dict: """Run the analysis pipeline. + ``profile_text`` (the candidate's search profile, see services/profile) + personalises the report: a "Fit for You" section and a verdict that + weighs dealbreakers and the salary floor. + ``checkpoint_key`` opt-in: when present, completed stages are read from (and new completions written to) the in-process checkpoint store. A retry of the same call with the same key only re-runs failed/missing stages. On a successful end-to-end run the caller should clear the checkpoint (the UI does this after rendering the result). """ - graph = create_analysis_graph() - initial_state: JobAnalysisState = { "job_posting": job_posting, "job_details": {}, @@ -226,13 +232,14 @@ def run_analysis( "model": model, "progress_callback": progress_callback, "checkpoint_key": checkpoint_key, + "profile_text": profile_text or "", } if progress_callback: progress_callback("job", 25) try: - return graph.invoke(initial_state) + return _run_pipeline(dict(initial_state)) except Exception as exc: # noqa: BLE001 - surfaced to the caller return { **initial_state, diff --git a/agents/report_generator.py b/agents/report_generator.py index aec5930..5c69635 100644 --- a/agents/report_generator.py +++ b/agents/report_generator.py @@ -2,6 +2,7 @@ from typing import Dict from utils.llm import get_completion +from utils.security import wrap_untrusted from utils.verdict import extract_verdict, strip_verdict_block @@ -27,12 +28,12 @@ def generate(state: Dict) -> Dict: job_details_str = "\n".join( [ - f"- **Company:** {extracted.get('company_name', 'Not specified')}", - f"- **Position:** {extracted.get('job_title', 'Not specified')}", - f"- **Location:** {extracted.get('location', 'Not specified')}", - f"- **Experience Required:** {extracted.get('experience_level', 'Not specified')}", - f"- **Job Type:** {extracted.get('job_type', 'Not specified')}", - f"- **Compensation:** {extracted.get('compensation', 'Not specified')}", + f"- **Company:** {extracted.get('company_name') or 'Not specified'}", + f"- **Position:** {extracted.get('job_title') or 'Not specified'}", + f"- **Location:** {extracted.get('location') or 'Not specified'}", + f"- **Experience Required:** {extracted.get('experience_level') or 'Not specified'}", + f"- **Job Type:** {extracted.get('job_type') or 'Not specified'}", + f"- **Compensation:** {extracted.get('compensation') or 'Not specified'}", ] ) @@ -50,14 +51,38 @@ def generate(state: Dict) -> Dict: {resume_analysis.get('commentary', '')} """ + profile_text = (state.get("profile_text") or "").strip() + profile_section = ( + f""" +## Candidate Profile (what THIS candidate wants; written by them) +{profile_text} +""" + if profile_text else "" + ) + fit_section = ( + """ Then, before section 2, a **Fit for You** section judging the posting + against the Candidate Profile: + role and seniority match; location, remote region and work authorization; + salary vs. their minimum (give the numbers, or say compensation is + unstated); must-haves met or unmet; and end with "Dealbreakers hit:" followed + by the list or "none". +""" + if profile_text else "" + ) + verdict_rule = ( + "- The recommendation is for THIS candidate: a dealbreaker hit, or salary\n" + " clearly below their minimum, caps it at `Consider with Caution` or lower.\n" + if profile_text else "" + ) + prompt = f""" Generate a comprehensive job analysis report from the data below. +{profile_section} +## Job Details (extracted from the posting) +{wrap_untrusted(job_details_str, "job_details")} -## Job Details -{job_details_str} - -## Requirements Analysis -{json.dumps(requirements, indent=2)} +## Requirements Analysis (extracted from the posting) +{wrap_untrusted(json.dumps(requirements, indent=2), "requirements")} ## Company Analysis {json.dumps(company_analysis, indent=2)} @@ -68,7 +93,7 @@ def generate(state: Dict) -> Dict: Structure your markdown report with these sections: 1. **Executive Summary** — position, key findings, headline verdict. -2. **Company Profile** — stability, market position, culture signals. Repeat any +{fit_section}2. **Company Profile** — stability, market position, culture signals. Repeat any data caveats from the inputs (e.g. "layoffs data not available", "salary figures are estimates"). Do NOT pretend you have data you weren't given. 3. **Job Requirements Analysis** — required skills/experience and how @@ -88,7 +113,7 @@ def generate(state: Dict) -> Dict: Rules: -- Do not output `` blocks or markdown code fences around the whole report. +{verdict_rule}- Do not output `` blocks or markdown code fences around the whole report. - Do not fabricate company news, layoffs, or salary benchmarks. - The verdict in the JSON block MUST match the one in the markdown. """ diff --git a/agents/resume_analyzer.py b/agents/resume_analyzer.py index d3780b7..53e047f 100644 --- a/agents/resume_analyzer.py +++ b/agents/resume_analyzer.py @@ -21,13 +21,17 @@ def analyze(state: Dict) -> Dict: job_details = state.get("job_details") or {} requirements = job_details.get("requirements_analysis") or {} + # Score against both lists: the posting's tools ("Terraform", "Datadog") + # used to be ignored whenever any technical skill was extracted. required_skills: list = [] if isinstance(requirements, dict): - required_skills = ( - requirements.get("technical_skills") - or requirements.get("tools_and_technologies") - or [] - ) + seen = set() + for skill in (requirements.get("technical_skills") or []) + ( + requirements.get("tools_and_technologies") or [] + ): + if isinstance(skill, str) and skill.strip().lower() not in seen: + seen.add(skill.strip().lower()) + required_skills.append(skill) try: state["resume_analysis"] = analyze_resume( diff --git a/agents/salary_analyzer.py b/agents/salary_analyzer.py index 237ebdf..42059a4 100644 --- a/agents/salary_analyzer.py +++ b/agents/salary_analyzer.py @@ -30,6 +30,7 @@ def analyze(state: Dict) -> Dict: location=location, experience_level=experience_level, model=model, + posted_compensation=manual.get("compensation") or extracted.get("compensation"), ) state["salary_analysis"] = {"estimated_range": salary_report} if progress_callback: diff --git a/app.py b/app.py index 1718375..b5b528b 100644 --- a/app.py +++ b/app.py @@ -1,9 +1,10 @@ -import os +import html from datetime import date, datetime, timedelta import altair as alt import pandas as pd import streamlit as st +from sqlalchemy.exc import SQLAlchemyError from agents.orchestrator import run_analysis from db.models import APPLICATION_STATUSES, PIPELINE_STAGES @@ -19,22 +20,6 @@ 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, - refresh_all_pending, - submit_background_analysis, -) -from services.background_analysis import ( - delete as delete_background_analysis, -) from services.billing import TierLimitExceeded as BillingTierError from services.bulk_import import ( BulkImportError, @@ -65,11 +50,8 @@ 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.personal import ensure_local_owner from services.projects import ( ProjectError, create_project, @@ -103,59 +85,93 @@ list_artifacts, recheck_artifact, ) -from services.telegram_link import ( - TelegramLinkError, - get_link, - issue_binding_token, - set_notify_on_stage, - unlink, -) 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, -) -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.webhooks import ( - WebhookError, - delete_webhook, - list_webhooks, - register_webhook, -) -from services.webhooks import ( - list_deliveries as list_webhook_deliveries, -) -from services.webhooks import ( - set_active as set_webhook_active, -) +from services.usage import BudgetExceeded from tools.resume_tools import extract_resume_text from tools.url_ingest import fetch_job_posting, is_url +from ui.discover import render_discover_tab +from ui.personal import render_personal_sidebar +from ui.profile import render_profile_editor 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.env import env_bool, env_str +from utils.features import enabled as feature_enabled +from utils.features import personal_mode from utils.logging_setup import configure as configure_logging +# Personal mode (PERSONAL_MODE=1): one local owner, core features only. The +# hosted product's side features (accounts, 2FA, background jobs, webhooks, +# Telegram, notifications) are imported only when they can run; see +# utils/features.py. +PERSONAL_MODE = personal_mode() + +if not PERSONAL_MODE: + from services.auth import ( + AuthError, + authenticate_user, + change_password, + complete_password_reset, + register_user, + request_password_reset, + ) + from services.background_analysis import ( + BackgroundAnalysisError, + refresh_all_pending, + submit_background_analysis, + ) + from services.background_analysis import ( + delete as delete_background_analysis, + ) + 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.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, + ) + 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.webhooks import ( + WebhookError, + delete_webhook, + list_webhooks, + register_webhook, + ) + from services.webhooks import ( + list_deliveries as list_webhook_deliveries, + ) + from services.webhooks import ( + set_active as set_webhook_active, + ) + # Activation: a realistic sample posting new users can analyze in one click, # and a polished static verdict shown to anonymous visitors before signup. SAMPLE_POSTING = """\ @@ -197,7 +213,7 @@ # --------------------------------------------------------------------------- share_token = st.query_params.get("share") -if share_token: +if share_token and feature_enabled("sharing"): from services.sharing import ShareError, get_view st.title("📄 Shared job analysis") @@ -492,8 +508,12 @@ def render_auth() -> None: if "user_id" not in st.session_state: - render_auth() - st.stop() + if PERSONAL_MODE: + # Single local owner: no sign-up, login, 2FA or billing screens. + st.session_state.user_id, st.session_state.user_email = ensure_local_owner() + else: + render_auth() + st.stop() # --------------------------------------------------------------------------- @@ -561,382 +581,391 @@ def _render_verification_gate() -> None: st.error(str(exc)) st.query_params.pop("verify_token", None) -_render_verification_gate() +if not PERSONAL_MODE: + _render_verification_gate() # --------------------------------------------------------------------------- # Authenticated layout # --------------------------------------------------------------------------- -st.sidebar.markdown(f"👤 **{st.session_state.user_email}**") +if PERSONAL_MODE: + render_personal_sidebar(st.session_state.user_id) +else: + st.sidebar.markdown(f"👤 **{st.session_state.user_email}**") -with st.sidebar.expander("💳 Plan & usage"): - from services.billing import ( - BillingError, - create_checkout_session, - create_portal_session, - plan_summary, - ) - _plan = plan_summary(st.session_state.user_id) - if not _plan["billing_enabled"]: - st.caption("Self-hosted deployment — no plan limits.") - else: - st.markdown(f"**{_plan['label']} plan**") - _an_lim = _plan["analyses_limit"] - _ar_lim = _plan["artifacts_limit"] - st.caption( - f"Analyses: {_plan['analyses_used']}" - + (f" / {_an_lim}" if _an_lim >= 0 else " (unlimited)") - + f" · Tailored docs: {_plan['artifacts_used']}" - + (f" / {_ar_lim}" if _ar_lim >= 0 else " (unlimited)") - + f" · per {_plan['window_days']} days" +if not PERSONAL_MODE: + + with st.sidebar.expander("💳 Plan & usage"): + from services.billing import ( + BillingError, + create_checkout_session, + create_portal_session, + plan_summary, ) - if _plan["tier"] == "free": - _up_col1, _up_col2 = st.columns(2) - with _up_col1: - if st.button("Upgrade to Pro", key="upgrade_pro"): - try: - _url = create_checkout_session( - st.session_state.user_id, "pro", - user_email=st.session_state.user_email, - ) - st.session_state["checkout_url"] = _url - except BillingError as exc: - st.error(str(exc)) - with _up_col2: - if st.button("Upgrade to Power", key="upgrade_power"): + _plan = plan_summary(st.session_state.user_id) + if not _plan["billing_enabled"]: + st.caption("Self-hosted deployment — no plan limits.") + else: + st.markdown(f"**{_plan['label']} plan**") + _an_lim = _plan["analyses_limit"] + _ar_lim = _plan["artifacts_limit"] + st.caption( + f"Analyses: {_plan['analyses_used']}" + + (f" / {_an_lim}" if _an_lim >= 0 else " (unlimited)") + + f" · Tailored docs: {_plan['artifacts_used']}" + + (f" / {_ar_lim}" if _ar_lim >= 0 else " (unlimited)") + + f" · per {_plan['window_days']} days" + ) + if _plan["tier"] == "free": + _up_col1, _up_col2 = st.columns(2) + with _up_col1: + if st.button("Upgrade to Pro", key="upgrade_pro"): + try: + _url = create_checkout_session( + st.session_state.user_id, "pro", + user_email=st.session_state.user_email, + ) + st.session_state["checkout_url"] = _url + except BillingError as exc: + st.error(str(exc)) + with _up_col2: + if st.button("Upgrade to Power", key="upgrade_power"): + try: + _url = create_checkout_session( + st.session_state.user_id, "power", + user_email=st.session_state.user_email, + ) + st.session_state["checkout_url"] = _url + except BillingError as exc: + st.error(str(exc)) + if st.session_state.get("checkout_url"): + st.link_button("→ Complete checkout", st.session_state["checkout_url"]) + else: + if st.button("Manage billing", key="billing_portal"): try: - _url = create_checkout_session( - st.session_state.user_id, "power", - user_email=st.session_state.user_email, + st.session_state["portal_url"] = create_portal_session( + st.session_state.user_id ) - st.session_state["checkout_url"] = _url except BillingError as exc: st.error(str(exc)) - if st.session_state.get("checkout_url"): - st.link_button("→ Complete checkout", st.session_state["checkout_url"]) + if st.session_state.get("portal_url"): + st.link_button("→ Open billing portal", st.session_state["portal_url"]) + + with st.sidebar.expander("📜 My recent activity"): + from services.audit import list_for_user as _list_audit + events = _list_audit(st.session_state.user_id, limit=20) + if not events: + st.caption("_No recorded activity yet._") else: - if st.button("Manage billing", key="billing_portal"): + for ev in events: + st.caption( + f"`{ev.created_at.strftime('%Y-%m-%d %H:%M')}` — `{ev.kind}`" + ) + + 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( + "Long-lived bearer tokens for the REST API " + "(`/v1/analyze`, `/v1/applications`, etc.). " + "Shown ONCE on creation — save it somewhere safe." + ) + with st.form("new_api_token_form"): + col_n, col_t = st.columns(2) + with col_n: + api_name = st.text_input("Token name", placeholder="e.g. cli-laptop") + with col_t: + api_ttl = st.selectbox( + "Expiry", ["30 days", "90 days", "365 days", "Never"], + ) + if st.form_submit_button("Create token", type="primary"): try: - st.session_state["portal_url"] = create_portal_session( - st.session_state.user_id + ttl_days = None if api_ttl == "Never" else int(api_ttl.split()[0]) + issued = issue_api_token( + st.session_state.user_id, api_name, ttl_days=ttl_days, ) - except BillingError as exc: + st.session_state["new_api_token_value"] = issued.raw_token + st.rerun() + except ApiTokenError as exc: st.error(str(exc)) - if st.session_state.get("portal_url"): - st.link_button("→ Open billing portal", st.session_state["portal_url"]) - -with st.sidebar.expander("📜 My recent activity"): - from services.audit import list_for_user as _list_audit - events = _list_audit(st.session_state.user_id, limit=20) - if not events: - st.caption("_No recorded activity yet._") - else: - for ev in events: - st.caption( - f"`{ev.created_at.strftime('%Y-%m-%d %H:%M')}` — `{ev.kind}`" - ) -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( - "Long-lived bearer tokens for the REST API " - "(`/v1/analyze`, `/v1/applications`, etc.). " - "Shown ONCE on creation — save it somewhere safe." - ) - with st.form("new_api_token_form"): - col_n, col_t = st.columns(2) - with col_n: - api_name = st.text_input("Token name", placeholder="e.g. cli-laptop") - with col_t: - api_ttl = st.selectbox( - "Expiry", ["30 days", "90 days", "365 days", "Never"], + if st.session_state.get("new_api_token_value"): + st.warning( + "Copy this token NOW. You will not see it again — only the " + "8-char prefix remains in the list below." ) - if st.form_submit_button("Create token", type="primary"): - try: - ttl_days = None if api_ttl == "Never" else int(api_ttl.split()[0]) - issued = issue_api_token( - st.session_state.user_id, api_name, ttl_days=ttl_days, - ) - st.session_state["new_api_token_value"] = issued.raw_token + st.code(st.session_state["new_api_token_value"], language=None) + if st.button("I've copied it"): + st.session_state.pop("new_api_token_value", None) st.rerun() - except ApiTokenError as exc: - st.error(str(exc)) - if st.session_state.get("new_api_token_value"): - st.warning( - "Copy this token NOW. You will not see it again — only the " - "8-char prefix remains in the list below." + tokens = list_api_tokens(st.session_state.user_id) + if tokens: + st.markdown("**Existing tokens**") + for t in tokens: + status = ( + "revoked" if t.revoked_at else + "expired" if t.expires_at and t.expires_at <= datetime.utcnow() else + "active" + ) + cols = st.columns([4, 1]) + with cols[0]: + st.caption( + f"`{t.prefix}…` · **{t.name}** · _{status}_" + + (f" · last used {t.last_used_at.strftime('%Y-%m-%d')}" + if t.last_used_at else "") + ) + with cols[1]: + if status == "active": + if st.button("Revoke", key=f"api_revoke_{t.id}"): + try: + revoke_api_token(st.session_state.user_id, t.id) + st.rerun() + except ApiTokenError as exc: + st.error(str(exc)) + + with st.sidebar.expander("🪝 Webhooks"): + from db.models import WEBHOOK_EVENTS + st.caption( + "POST a signed JSON payload to your URL when events fire. Each " + "request carries an `X-JobOffer-Signature: sha256=…` HMAC header " + "computed with the webhook secret." ) - st.code(st.session_state["new_api_token_value"], language=None) - if st.button("I've copied it"): - st.session_state.pop("new_api_token_value", None) - st.rerun() - - tokens = list_api_tokens(st.session_state.user_id) - if tokens: - st.markdown("**Existing tokens**") - for t in tokens: - status = ( - "revoked" if t.revoked_at else - "expired" if t.expires_at and t.expires_at <= datetime.utcnow() else - "active" + with st.form("new_webhook_form"): + wh_url = st.text_input("Endpoint URL", placeholder="https://example.com/hook") + wh_events = st.multiselect("Events", list(WEBHOOK_EVENTS), default=["stage.added"]) + if st.form_submit_button("Add webhook", type="primary"): + try: + wh = register_webhook(st.session_state.user_id, wh_url, wh_events) + st.success("Webhook created. Secret (verify signatures with this):") + st.code(wh.secret, language=None) + except WebhookError as exc: + st.error(str(exc)) + + hooks = list_webhooks(st.session_state.user_id) + if hooks: + st.markdown("**Configured webhooks**") + for wh in hooks: + state = "active" if wh.active else "paused" + cols = st.columns([4, 1]) + with cols[0]: + st.caption(f"#{wh.id} · _{state}_ · {', '.join(wh.events)}") + st.caption(wh.url) + with cols[1]: + if st.button("Pause" if wh.active else "Resume", key=f"wh_toggle_{wh.id}"): + set_webhook_active(st.session_state.user_id, wh.id, not wh.active) + st.rerun() + if st.button("🗑️", key=f"wh_del_{wh.id}"): + delete_webhook(st.session_state.user_id, wh.id) + st.rerun() + + deliveries = list_webhook_deliveries(st.session_state.user_id, limit=8) + if deliveries: + st.markdown("**Recent deliveries**") + for d in deliveries: + icon = "✅" if d.success else "❌" + code = d.status_code if d.status_code is not None else "—" + st.caption(f"{icon} `{d.event}` → HTTP {code} ({d.attempts} attempt(s))") + + with st.sidebar.expander("🔐 Two-factor authentication"): + if totp_is_enabled(st.session_state.user_id): + remaining = totp_backup_codes_left(st.session_state.user_id) + st.success(f"2FA is **enabled**. {remaining} backup code(s) remaining.") + st.caption( + "To disable, enter your current password and confirm." ) - cols = st.columns([4, 1]) - with cols[0]: - st.caption( - f"`{t.prefix}…` · **{t.name}** · _{status}_" - + (f" · last used {t.last_used_at.strftime('%Y-%m-%d')}" - if t.last_used_at else "") + with st.form("2fa_disable_form"): + cur_pw = st.text_input( + "Current password", type="password", key="2fa_disable_pw", ) - with cols[1]: - if status == "active": - if st.button("Revoke", key=f"api_revoke_{t.id}"): + if st.form_submit_button("Disable 2FA"): + try: + totp_disable(st.session_state.user_id, cur_pw) + st.success("2FA disabled.") + st.rerun() + except TOTPError as exc: + st.error(str(exc)) + else: + # Setup ceremony lives across reruns in session_state. + if not st.session_state.get("totp_setup_secret"): + if st.button("Start 2FA setup"): + try: + setup = totp_start_setup( + st.session_state.user_id, + st.session_state.user_email, + ) + st.session_state.totp_setup_secret = setup.secret + st.session_state.totp_setup_uri = setup.provisioning_uri + st.rerun() + except TOTPError as exc: + st.error(str(exc)) + else: + try: + import io + + import qrcode + + img = qrcode.make(st.session_state.totp_setup_uri) + buf = io.BytesIO() + img.save(buf, format="PNG") + st.image(buf.getvalue(), caption="Scan in your authenticator app") + except ImportError: + pass + # A checkbox, not an expander: this already sits inside the + # sidebar 2FA expander and Streamlit forbids nesting them. + if st.checkbox("Show the secret to enter manually", key="totp_show_secret"): + st.code(st.session_state.totp_setup_secret, language=None) + with st.form("2fa_confirm_form"): + otp = st.text_input("Enter the current 6-digit code") + if st.form_submit_button("Confirm setup", type="primary"): try: - revoke_api_token(st.session_state.user_id, t.id) + result = totp_confirm_setup(st.session_state.user_id, otp) + st.session_state.totp_backup_codes_once = result.backup_codes + st.session_state.pop("totp_setup_secret", None) + st.session_state.pop("totp_setup_uri", None) st.rerun() - except ApiTokenError as exc: + except TOTPError as exc: st.error(str(exc)) - -with st.sidebar.expander("🪝 Webhooks"): - from db.models import WEBHOOK_EVENTS - st.caption( - "POST a signed JSON payload to your URL when events fire. Each " - "request carries an `X-JobOffer-Signature: sha256=…` HMAC header " - "computed with the webhook secret." - ) - with st.form("new_webhook_form"): - wh_url = st.text_input("Endpoint URL", placeholder="https://example.com/hook") - wh_events = st.multiselect("Events", list(WEBHOOK_EVENTS), default=["stage.added"]) - if st.form_submit_button("Add webhook", type="primary"): - try: - wh = register_webhook(st.session_state.user_id, wh_url, wh_events) - st.success("Webhook created. Secret (verify signatures with this):") - st.code(wh.secret, language=None) - except WebhookError as exc: - st.error(str(exc)) - - hooks = list_webhooks(st.session_state.user_id) - if hooks: - st.markdown("**Configured webhooks**") - for wh in hooks: - state = "active" if wh.active else "paused" - cols = st.columns([4, 1]) - with cols[0]: - st.caption(f"#{wh.id} · _{state}_ · {', '.join(wh.events)}") - st.caption(wh.url) - with cols[1]: - if st.button("Pause" if wh.active else "Resume", key=f"wh_toggle_{wh.id}"): - set_webhook_active(st.session_state.user_id, wh.id, not wh.active) + if st.button("Cancel setup", key="2fa_cancel"): + st.session_state.pop("totp_setup_secret", None) + st.session_state.pop("totp_setup_uri", None) st.rerun() - if st.button("🗑️", key=f"wh_del_{wh.id}"): - delete_webhook(st.session_state.user_id, wh.id) + + # One-shot display of freshly-generated backup codes. + if st.session_state.get("totp_backup_codes_once"): + st.success("✅ 2FA enabled!") + st.warning( + "**Save these backup codes now.** Each works once — store " + "them somewhere safe. You will NOT see them again." + ) + for code in st.session_state["totp_backup_codes_once"]: + st.code(code, language=None) + if st.button("I've saved them — hide"): + st.session_state.pop("totp_backup_codes_once", None) st.rerun() - deliveries = list_webhook_deliveries(st.session_state.user_id, limit=8) - if deliveries: - st.markdown("**Recent deliveries**") - for d in deliveries: - icon = "✅" if d.success else "❌" - code = d.status_code if d.status_code is not None else "—" - st.caption(f"{icon} `{d.event}` → HTTP {code} ({d.attempts} attempt(s))") - -with st.sidebar.expander("🔐 Two-factor authentication"): - if totp_is_enabled(st.session_state.user_id): - remaining = totp_backup_codes_left(st.session_state.user_id) - st.success(f"2FA is **enabled**. {remaining} backup code(s) remaining.") - st.caption( - "To disable, enter your current password and confirm." + with st.sidebar.expander("🗄 Privacy & account"): + from services.account_export import export_json + 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( + "⬇️ 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", ) - with st.form("2fa_disable_form"): - cur_pw = st.text_input( - "Current password", type="password", key="2fa_disable_pw", + + 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." ) - if st.form_submit_button("Disable 2FA"): + 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: - totp_disable(st.session_state.user_id, cur_pw) - st.success("2FA disabled.") + 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 TOTPError as exc: + except _AuthError as exc: st.error(str(exc)) - else: - # Setup ceremony lives across reruns in session_state. - if not st.session_state.get("totp_setup_secret"): - if st.button("Start 2FA setup"): + + with st.sidebar.expander("🔒 Change password"): + with st.form("change_pw_form"): + cur_pw = st.text_input("Current password", type="password", key="cur_pw") + new_pw = st.text_input("New password", type="password", key="new_pw", help="Minimum 8 characters.") + if st.form_submit_button("Update password"): try: - setup = totp_start_setup( - st.session_state.user_id, - st.session_state.user_email, - ) - st.session_state.totp_setup_secret = setup.secret - st.session_state.totp_setup_uri = setup.provisioning_uri - st.rerun() - except TOTPError as exc: + change_password(st.session_state.user_id, cur_pw, new_pw) + st.success("Password updated.") + except AuthError as exc: st.error(str(exc)) - else: - try: - import io - - import qrcode - - img = qrcode.make(st.session_state.totp_setup_uri) - buf = io.BytesIO() - img.save(buf, format="PNG") - st.image(buf.getvalue(), caption="Scan in your authenticator app") - except ImportError: - pass - with st.expander("Or enter the secret manually"): - st.code(st.session_state.totp_setup_secret, language=None) - with st.form("2fa_confirm_form"): - otp = st.text_input("Enter the current 6-digit code") - if st.form_submit_button("Confirm setup", type="primary"): - try: - result = totp_confirm_setup(st.session_state.user_id, otp) - st.session_state.totp_backup_codes_once = result.backup_codes - st.session_state.pop("totp_setup_secret", None) - st.session_state.pop("totp_setup_uri", None) - st.rerun() - except TOTPError as exc: - st.error(str(exc)) - if st.button("Cancel setup", key="2fa_cancel"): - st.session_state.pop("totp_setup_secret", None) - st.session_state.pop("totp_setup_uri", None) - st.rerun() - # One-shot display of freshly-generated backup codes. - if st.session_state.get("totp_backup_codes_once"): - st.success("✅ 2FA enabled!") - st.warning( - "**Save these backup codes now.** Each works once — store " - "them somewhere safe. You will NOT see them again." + with st.sidebar.expander("📲 Link Telegram"): + link = get_link(st.session_state.user_id) + if link is None: + st.caption( + "Generate a binding token, then send `/bind ` to the bot. " + "Once linked, you'll get a Telegram ping when any of your saved " + "applications gets a new pipeline stage." ) - for code in st.session_state["totp_backup_codes_once"]: - st.code(code, language=None) - if st.button("I've saved them — hide"): - 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 - from services.auth import 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") - new_pw = st.text_input("New password", type="password", key="new_pw", help="Minimum 8 characters.") - if st.form_submit_button("Update password"): - try: - change_password(st.session_state.user_id, cur_pw, new_pw) - st.success("Password updated.") - except AuthError as exc: - st.error(str(exc)) + if st.button("Generate binding token"): + tok = issue_binding_token(st.session_state.user_id) + st.code(f"/bind {tok}", language=None) + st.caption("Valid for 15 minutes. Paste into the bot.") + else: + username = f"@{link.chat_username}" if link.chat_username else f"chat {link.chat_id}" + st.success(f"Linked to {username}.") + notify_key = f"notify_on_stage_pref_{st.session_state.user_id}" + new_pref = st.toggle( + "Notify on new stage events", + value=link.notify_on_stage, + key=notify_key, + ) + if new_pref != link.notify_on_stage: + try: + set_notify_on_stage(st.session_state.user_id, new_pref) + st.rerun() + except TelegramLinkError as exc: + st.error(str(exc)) -with st.sidebar.expander("📲 Link Telegram"): - link = get_link(st.session_state.user_id) - if link is None: - st.caption( - "Generate a binding token, then send `/bind ` to the bot. " - "Once linked, you'll get a Telegram ping when any of your saved " - "applications gets a new pipeline stage." - ) - if st.button("Generate binding token"): - tok = issue_binding_token(st.session_state.user_id) - st.code(f"/bind {tok}", language=None) - st.caption("Valid for 15 minutes. Paste into the bot.") - else: - username = f"@{link.chat_username}" if link.chat_username else f"chat {link.chat_id}" - st.success(f"Linked to {username}.") - notify_key = f"notify_on_stage_pref_{st.session_state.user_id}" - new_pref = st.toggle( - "Notify on new stage events", - value=link.notify_on_stage, - key=notify_key, - ) - if new_pref != link.notify_on_stage: - try: - set_notify_on_stage(st.session_state.user_id, new_pref) - st.rerun() - except TelegramLinkError as exc: - st.error(str(exc)) + # Inactivity-reminder threshold (0 disables the inactivity ping + # without losing per-stage notifications). + threshold_key = f"inactive_days_{st.session_state.user_id}" + new_threshold = st.number_input( + "Inactivity reminder threshold (days, 0 = off)", + min_value=0, + max_value=180, + value=link.inactive_reminder_days, + step=1, + key=threshold_key, + ) + if int(new_threshold) != link.inactive_reminder_days: + try: + set_inactive_threshold(st.session_state.user_id, int(new_threshold)) + st.rerun() + except PermissionError as exc: + st.error(str(exc)) + st.caption( + "Scheduled job (`python -m worker.reminders`) sends a Telegram " + "summary of applications that haven't moved within this window." + ) - # Inactivity-reminder threshold (0 disables the inactivity ping - # without losing per-stage notifications). - threshold_key = f"inactive_days_{st.session_state.user_id}" - new_threshold = st.number_input( - "Inactivity reminder threshold (days, 0 = off)", - min_value=0, - max_value=180, - value=link.inactive_reminder_days, - step=1, - key=threshold_key, - ) - if int(new_threshold) != link.inactive_reminder_days: - try: - set_inactive_threshold(st.session_state.user_id, int(new_threshold)) + if st.button("Disconnect"): + unlink(st.session_state.user_id) st.rerun() - except PermissionError as exc: - st.error(str(exc)) - st.caption( - "Scheduled job (`python -m worker.reminders`) sends a Telegram " - "summary of applications that haven't moved within this window." - ) - - if st.button("Disconnect"): - unlink(st.session_state.user_id) - st.rerun() -if os.getenv("TELEGRAM_BOT_USERNAME"): - bot_url = f"https://t.me/{os.getenv('TELEGRAM_BOT_USERNAME').lstrip('@')}" +_telegram_bot_username = env_str("TELEGRAM_BOT_USERNAME") +if _telegram_bot_username: + bot_url = f"https://t.me/{_telegram_bot_username.lstrip('@')}" st.sidebar.markdown(f"💬 [Use the Telegram bot]({bot_url})") st.sidebar.title("About") @@ -959,13 +988,25 @@ def _render_verification_gate() -> 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): - for key in ("user_id", "user_email", "last_result", "last_inputs"): - st.session_state.pop(key, None) +if not PERSONAL_MODE and st.sidebar.button("Sign out", use_container_width=True): + # Clear everything: API-token values, billing-portal links, 2FA backup + # codes and import previews would otherwise carry over to the next login + # in this browser tab. + st.session_state.clear() st.rerun() -analyze_tab, applications_tab, analytics_tab, cv_tab, test_tab = st.tabs( - ["🔍 Analyze a posting", "📌 My Applications", "📊 Analytics", "📝 CV & Projects", "🧪 System test"] +_TAB_NAMES = { + "discover": "🔭 Discover", "analyze": "🔍 Analyze a posting", + "applications": "📌 My Applications", "analytics": "📊 Analytics", + "cv": "📝 CV & Profile", "test": "🧪 System test", +} +_tab_order = ( + ["discover", "analyze", "applications", "analytics", "cv", "test"] if PERSONAL_MODE + else ["analyze", "discover", "applications", "analytics", "cv", "test"] +) +_tabs = dict(zip(_tab_order, st.tabs([_TAB_NAMES[k] for k in _tab_order]))) +analyze_tab, applications_tab, analytics_tab, cv_tab, test_tab = ( + _tabs[k] for k in ("analyze", "applications", "analytics", "cv", "test") ) @@ -973,6 +1014,27 @@ def _render_verification_gate() -> None: # Analyze tab # --------------------------------------------------------------------------- +def _is_operator() -> bool: + """Who may run live integration probes: ADMIN_EMAILS when set; otherwise + everyone on a self-hosted deployment (billing off), nobody on a paid one.""" + admins = {e.strip().lower() for e in (env_str("ADMIN_EMAILS") or "").split(",") if e.strip()} + if admins: + return (st.session_state.get("user_email") or "").lower() in admins + from services.billing import billing_enabled + return not billing_enabled() + + +def _render_sections(value) -> None: + """Render a stage output (a dict of markdown sections) as markdown.""" + if isinstance(value, dict) and all(isinstance(v, str) for v in value.values()): + for section in value.values(): + st.markdown(section) + elif isinstance(value, str): + st.markdown(value) + else: + st.write(value) + + def render_result(result: dict) -> None: verdict = result.get("verdict") or {} if verdict: @@ -989,7 +1051,21 @@ def render_result(result: dict) -> None: st.write(f"- {reason}") with st.expander("🎯 Job Analysis", expanded=True): - st.write(result["job_details"]) + extracted = result["job_details"].get("extracted_details") or {} + if isinstance(extracted, dict) and extracted: + for label, key in ( + ("Company", "company_name"), ("Position", "job_title"), + ("Location", "location"), ("Experience", "experience_level"), + ("Type", "job_type"), ("Compensation", "compensation"), + ): + st.markdown(f"**{label}:** {extracted.get(key) or 'Not specified'}") + responsibilities = extracted.get("responsibilities") or [] + if responsibilities: + st.markdown("**Responsibilities**") + for item in responsibilities: + st.markdown(f"- {item}") + else: + st.write(result["job_details"]) requirements = result["job_details"].get("requirements_analysis", {}) tech_skills = requirements.get("technical_skills", []) if isinstance(requirements, dict) else [] if tech_skills: @@ -998,10 +1074,10 @@ def render_result(result: dict) -> None: st.write(f"- {skill}") with st.expander("🏢 Company Research", expanded=True): - st.write(result["company_analysis"]) + _render_sections(result["company_analysis"]) with st.expander("💰 Compensation Analysis", expanded=True): - st.write(result["salary_analysis"]) + _render_sections(result["salary_analysis"]) resume_analysis = result.get("resume_analysis") or {} if resume_analysis: @@ -1031,14 +1107,14 @@ def render_result(result: dict) -> None: st.markdown("**✅ Matched required skills**") if matched: for s in matched: - st.markdown(f"✓ {s}", unsafe_allow_html=True) + st.markdown(f"✓ {html.escape(str(s))}", unsafe_allow_html=True) else: st.caption("_None matched — review the missing list._") with sk_col_g: st.markdown("**❌ Missing required skills**") if missing: for s in missing: - st.markdown(f"✗ {s}", unsafe_allow_html=True) + st.markdown(f"✗ {html.escape(str(s))}", unsafe_allow_html=True) else: st.caption("_All required skills detected._") @@ -1053,6 +1129,22 @@ def render_result(result: dict) -> None: st.markdown(result["final_report"]) +def _needs_migration(render, *args, **kwargs) -> None: + """Run a UI section that depends on newer tables; on an unmigrated + database show how to fix it instead of halting the rest of the page.""" + try: + render(*args, **kwargs) + except SQLAlchemyError as exc: + st.error( + "This section needs a database migration. Run `alembic upgrade head` " + "(see docs/ASSESSMENT.md for the safe procedure on an existing database)." + ) + st.caption(f"Details: {str(exc).splitlines()[0][:200]}") + + +with _tabs["discover"]: + _needs_migration(render_discover_tab, st.session_state.user_id, render_result, personal=PERSONAL_MODE) + with analyze_tab: st.caption( "Paste a job description (or a URL we can fetch), optionally drop in " @@ -1070,7 +1162,7 @@ def _render_background_card(): completed task, we hand it off to ``session_state`` so the main script rerun picks it up and renders it via ``render_result``. """ - if not async_enabled(): + if not (feature_enabled("background") and async_enabled()): return # nothing to show when the queue isn't configured backgrounds = refresh_all_pending(st.session_state.user_id) if not backgrounds: @@ -1170,6 +1262,12 @@ def _render_background_card(): ) st.markdown("**2. Your resume** _(optional — enables ATS match score)_") + _has_master_cv = get_master_cv(st.session_state.user_id) is not None + use_master_cv = st.checkbox( + "Use my master CV for the fit / ATS analysis", + value=_has_master_cv, disabled=not _has_master_cv, + help="Save one in 📝 CV & Profile. An uploaded file below takes precedence.", + ) resume_file = st.file_uploader( "Resume — PDF, DOCX, or TXT", type=["pdf", "docx", "txt", "md"], @@ -1192,7 +1290,7 @@ def _render_background_card(): help="What the posting itself says — leave blank if unspecified.", ) - if async_enabled(): + if (feature_enabled("background") and async_enabled()): run_background = st.checkbox( "Run in background (returns immediately; pick up the result here later)", value=False, @@ -1213,11 +1311,15 @@ def _render_background_card(): st.success(f"Fetched {len(posting_text)} characters from URL.") except ValueError as exc: st.error(str(exc)) - if not posting_text: - st.info( - "💡 The URL couldn't be parsed (JS-rendered or access-denied). " - "Copy the job text and paste it in the **📝 Paste text** tab." - ) + # Never fall back to whatever sits in the Paste tab: it may be + # an older posting (or the sample), which would be analyzed + # and saved under the wrong company without any warning. + posting_text = "" + st.info( + "💡 The URL couldn't be parsed (JS-rendered or access-denied). " + "Copy the job text into the **📝 Paste text** tab, clear the URL " + "field, and analyze again." + ) elif raw_url_input and not is_url(raw_url_input) and len(raw_url_input) > 80: # User pasted job description text into the URL field — route correctly. st.info( @@ -1233,12 +1335,16 @@ def _render_background_card(): st.warning("Resume parsed but contained no extractable text — skipping ATS.") except ValueError as exc: st.error(f"Resume parsing failed: {exc}") + elif use_master_cv: + _cv = get_master_cv(st.session_state.user_id) + resume_text = _cv.raw_text if _cv else "" if not posting_text: - st.warning( - "We need either a fetchable URL or pasted job-description text " - "to start. Add one of those and try again." - ) + if not (raw_url_input and is_url(raw_url_input)): + st.warning( + "We need either a fetchable URL or pasted job-description text " + "to start. Add one of those and try again." + ) else: # Manual fields are now hints, not requirements — extraction fills the gaps. job_data = { @@ -1256,7 +1362,8 @@ def _render_background_card(): from services.rate_limit import RateLimitExceeded from services.usage import BudgetExceeded try: - check_user_quota(st.session_state.user_id) + if not PERSONAL_MODE: + check_user_quota(st.session_state.user_id) except (RateLimitExceeded, BudgetExceeded, TierLimitExceeded) as exc: st.error(str(exc)) st.stop() @@ -1319,9 +1426,11 @@ def update_progress(stage, progress, stage_info=None): # Stable per-(user, inputs) checkpoint key so retrying the same # form short-circuits stages that already completed. + from services.profile import profile_prompt_for + profile_text = profile_prompt_for(st.session_state.user_id) checkpoint_key = compute_checkpoint_key( - posting_text, job_data, selected_model, resume_text, - user_id=st.session_state.user_id, + posting_text, {**job_data, "_profile": profile_text}, selected_model, + resume_text, user_id=st.session_state.user_id, ) ckpt_store = get_checkpoint_store() prior = ckpt_store.completed_stages(checkpoint_key) @@ -1344,6 +1453,7 @@ def update_progress(stage, progress, stage_info=None): progress_callback=update_progress, resume_text=resume_text, checkpoint_key=checkpoint_key, + profile_text=profile_text, ) if result.get("error"): @@ -1379,16 +1489,25 @@ def update_progress(stage, progress, stage_info=None): with st.form("save_application_form"): st.markdown("### Save to applications") + last_inputs = dict(st.session_state.get("last_inputs") or {}) + # Editable here so a posting that doesn't name the employer (or a + # mis-extracted title) can still be saved without re-running. + col_c, col_t = st.columns(2) + with col_c: + save_company = st.text_input("Company", last_inputs.get("company_name") or "") + with col_t: + save_title = st.text_input("Job title", last_inputs.get("job_title") or "") col_s, col_n = st.columns([1, 3]) with col_s: save_status = st.selectbox("Status", APPLICATION_STATUSES, index=0) with col_n: save_notes = st.text_input("Notes (optional)", "") if st.form_submit_button("💾 Save analysis", type="primary"): + last_inputs.update(company_name=save_company.strip(), job_title=save_title.strip()) try: save_analysis( user_id=st.session_state.user_id, - manual_inputs=st.session_state.last_inputs, + manual_inputs=last_inputs, analysis_result=st.session_state.last_result, status=save_status, notes=save_notes or None, @@ -1439,9 +1558,13 @@ def update_progress(stage, progress, stage_info=None): if st.button("Parse with LLM", key="app_free_preview"): with st.spinner("Parsing applications…"): try: - st.session_state["app_import_previews"] = parse_applications_freeform(app_free) - except BulkImportError as exc: + st.session_state["app_import_previews"] = parse_applications_freeform( + app_free, user_id=st.session_state.user_id + ) + except (BulkImportError, BudgetExceeded, BillingTierError) as exc: st.error(str(exc)) + except Exception as exc: # noqa: BLE001 - provider/LLM failure + st.error(f"Parsing failed: {exc}") app_previews = st.session_state.get("app_import_previews") or [] if app_previews: @@ -1704,9 +1827,11 @@ def _matches(rec) -> bool: ) # 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, - ) + if feature_enabled("notifications"): + if feature_enabled("notifications"): + notify_stage_added( + st.session_state.user_id, rec, new_stage, + ) st.rerun() except StageError as exc: st.error(str(exc)) @@ -1773,8 +1898,10 @@ def _matches(rec) -> bool: ) st.success(f"Saved tailored CV #{art.id}.") st.rerun() - except (TailoringError, MasterCVError, BillingTierError) as exc: + except (TailoringError, MasterCVError, BillingTierError, BudgetExceeded) as exc: st.error(str(exc)) + except Exception as exc: # noqa: BLE001 - provider/LLM failure + st.error(f"Generation failed, nothing was saved: {exc}") with art_col2: # Tone preset for cover letters — persists per-application # in session_state so the user's last choice sticks. @@ -1796,8 +1923,10 @@ def _matches(rec) -> bool: ) st.success(f"Saved cover letter #{art.id}.") st.rerun() - except (TailoringError, MasterCVError, BillingTierError) as exc: + except (TailoringError, MasterCVError, BillingTierError, BudgetExceeded) as exc: st.error(str(exc)) + except Exception as exc: # noqa: BLE001 - provider/LLM failure + st.error(f"Generation failed, nothing was saved: {exc}") # List existing artifacts (newest first). arts = list_artifacts(st.session_state.user_id, rec.id) @@ -1988,17 +2117,19 @@ def _matches(rec) -> bool: except PDFExportError as exc: st.caption(f"PDF disabled: {exc}") - # ----- Share links ----- - from services.sharing import ( - 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}"): - base_url = os.getenv("APP_BASE_URL", "").rstrip("/") + # ----- Share links (side feature) ----- + if feature_enabled("sharing") and st.checkbox( + "🔗 Share read-only link", key=f"share_expand_{rec.id}" + ): + from services.sharing import ( + ShareError, + create_share, + list_shares_for_application, + ) + from services.sharing import ( + revoke as revoke_share, + ) + base_url = env_str("APP_BASE_URL", "").rstrip("/") existing_shares = list_shares_for_application( st.session_state.user_id, rec.id, ) @@ -2238,7 +2369,11 @@ def _matches(rec) -> bool: "every application can pull from them." ) - cv_section, proj_section = st.tabs(["📄 Master CV", "🧩 Project gallery"]) + profile_section, cv_section, proj_section = st.tabs( + ["👤 Search profile", "📄 Master CV", "🧩 Project gallery"] + ) + with profile_section: + _needs_migration(render_profile_editor, st.session_state.user_id) # ----- Master CV ---------------------------------------------------------- with cv_section: @@ -2302,8 +2437,10 @@ def _matches(rec) -> bool: structured = parse_master_cv(st.session_state.user_id) st.success("Parsed.") st.json(structured) - except MasterCVError as exc: + except (MasterCVError, BudgetExceeded, BillingTierError) as exc: st.error(str(exc)) + except Exception as exc: # noqa: BLE001 - provider/LLM failure + st.error(f"Parsing failed: {exc}") with pdf_col: try: cv_pdf = markdown_to_pdf( @@ -2462,9 +2599,13 @@ def _matches(rec) -> bool: if st.button("Parse with LLM", key="proj_free_preview"): with st.spinner("Parsing projects…"): try: - st.session_state["proj_import_previews"] = parse_projects_freeform(free_text) - except BulkImportError as exc: + st.session_state["proj_import_previews"] = parse_projects_freeform( + free_text, user_id=st.session_state.user_id + ) + except (BulkImportError, BudgetExceeded, BillingTierError) as exc: st.error(str(exc)) + except Exception as exc: # noqa: BLE001 - provider/LLM failure + st.error(f"Parsing failed: {exc}") previews = st.session_state.get("proj_import_previews") or [] if previews: @@ -2598,109 +2739,112 @@ def _matches(rec) -> bool: # --------------------------------------------------------------------------- with test_tab: - st.header("🧪 System health check") - st.caption( - "Runs a lightweight probe of every configured integration. " - "LLM probes make one tiny real API call (~10 tokens) so actual " - "connectivity is verified. Everything else is connection-level only — " - "no writes, no side-effects." - ) - - run_test_btn = st.button("▶ Run system test", type="primary", key="run_system_test_btn") + if not _is_operator(): + st.info("System checks are available to the operator of this deployment.") + else: + st.header("🧪 System health check") + st.caption( + "Runs a lightweight probe of every configured integration. " + "LLM probes make one tiny real API call (~10 tokens) so actual " + "connectivity is verified. Everything else is connection-level only — " + "no writes, no side-effects." + ) - if run_test_btn: - st.session_state["system_test_results"] = None # clear stale results + run_test_btn = st.button("▶ Run system test", type="primary", key="run_system_test_btn") - if run_test_btn or st.session_state.get("system_test_results") is not None: if run_test_btn: - from services.system_test import run_system_test - with st.spinner("Running probes…"): - results = run_system_test() - st.session_state["system_test_results"] = results - else: - results = st.session_state["system_test_results"] + st.session_state["system_test_results"] = None # clear stale results + + if run_test_btn or st.session_state.get("system_test_results") is not None: + if run_test_btn: + from services.system_test import run_system_test + with st.spinner("Running probes…"): + results = run_system_test() + st.session_state["system_test_results"] = results + else: + results = st.session_state["system_test_results"] - # ── results table ──────────────────────────────────────────────────── - st.subheader("Test results") - all_ok = all(r.ok or r.skipped for r in results) - if all_ok: - st.success("All configured integrations passed ✅") - else: - failures = [r.name for r in results if not r.ok and not r.skipped] - st.error(f"Issues detected with: {', '.join(failures)}") + # ── results table ──────────────────────────────────────────────────── + st.subheader("Test results") + all_ok = all(r.ok or r.skipped for r in results) + if all_ok: + st.success("All configured integrations passed ✅") + else: + failures = [r.name for r in results if not r.ok and not r.skipped] + st.error(f"Issues detected with: {', '.join(failures)}") - for r in results: - cols = st.columns([0.05, 0.35, 0.45, 0.15]) - cols[0].markdown(r.icon) - cols[1].markdown(f"**{r.name}**") - cols[2].markdown(r.message) - cols[3].markdown(r.duration_str if not r.skipped else "_skipped_") + for r in results: + cols = st.columns([0.05, 0.35, 0.45, 0.15]) + cols[0].markdown(r.icon) + cols[1].markdown(f"**{r.name}**") + cols[2].markdown(r.message) + cols[3].markdown(r.duration_str if not r.skipped else "_skipped_") - st.divider() + st.divider() - # ── mock demo analysis display ─────────────────────────────────────── - st.subheader("📋 Demo analysis") - st.caption( - "Pre-baked sample — shows every UI section without spending LLM tokens. " - "This is what a real analysis looks like." - ) + # ── mock demo analysis display ─────────────────────────────────────── + st.subheader("📋 Demo analysis") + st.caption( + "Pre-baked sample — shows every UI section without spending LLM tokens. " + "This is what a real analysis looks like." + ) - from services.system_test import MOCK_ANALYSIS - mock = MOCK_ANALYSIS - details = mock["job_details"]["extracted_details"] - req = mock["job_details"]["requirements_analysis"] - verdict = mock["verdict"] + from services.system_test import MOCK_ANALYSIS + mock = MOCK_ANALYSIS + details = mock["job_details"]["extracted_details"] + req = mock["job_details"]["requirements_analysis"] + verdict = mock["verdict"] - # Verdict banner - confidence = verdict.get("confidence", 0) - decision = verdict.get("decision", "") - verdict_color = {"Apply": "green", "Consider": "orange", "Avoid": "red"}.get(decision, "blue") - st.markdown( - f"**Verdict:** :{verdict_color}[{decision}]  ·  " - f"Confidence **{confidence}/10**" - ) + # Verdict banner + confidence = verdict.get("confidence", 0) + decision = verdict.get("decision", "") + verdict_color = {"Apply": "green", "Consider": "orange", "Avoid": "red"}.get(decision, "blue") + st.markdown( + f"**Verdict:** :{verdict_color}[{decision}]  ·  " + f"Confidence **{confidence}/10**" + ) - reason_cols = st.columns(2) - with reason_cols[0]: - st.markdown("**Why apply**") - for r in verdict.get("reasons", []): - st.markdown(f"- {r}") - with reason_cols[1]: - st.markdown("**Watch-outs**") - for c in verdict.get("cautions", []): - st.markdown(f"- {c}") - - st.divider() - - # Job details - d1, d2 = st.columns(2) - with d1: - st.markdown("**Position**") - st.markdown(f"🏢 {details.get('company_name', '')}") - st.markdown(f"💼 {details.get('job_title', '')}") - st.markdown(f"📍 {details.get('location', '')}") - st.markdown(f"💰 {details.get('compensation', '')}") - with d2: - st.markdown("**Required skills**") - for skill in req.get("technical_skills", []): - st.markdown(f"- {skill}") - - st.divider() - - # Analysis sections (company / salary / report) - for section_key, section_label in [ - ("company_analysis", "Company analysis"), - ("salary_analysis", "Compensation analysis"), - ]: - section = mock.get(section_key, {}) - if section: - st.markdown(f"**{section_label}**") - for _k, v in section.items(): - st.markdown(v) - st.divider() - - st.markdown("**Full report**") - st.markdown(mock.get("final_report", "")) + reason_cols = st.columns(2) + with reason_cols[0]: + st.markdown("**Why apply**") + for r in verdict.get("reasons", []): + st.markdown(f"- {r}") + with reason_cols[1]: + st.markdown("**Watch-outs**") + for c in verdict.get("cautions", []): + st.markdown(f"- {c}") + + st.divider() + + # Job details + d1, d2 = st.columns(2) + with d1: + st.markdown("**Position**") + st.markdown(f"🏢 {details.get('company_name', '')}") + st.markdown(f"💼 {details.get('job_title', '')}") + st.markdown(f"📍 {details.get('location', '')}") + st.markdown(f"💰 {details.get('compensation', '')}") + with d2: + st.markdown("**Required skills**") + for skill in req.get("technical_skills", []): + st.markdown(f"- {skill}") + + st.divider() + + # Analysis sections (company / salary / report) + for section_key, section_label in [ + ("company_analysis", "Company analysis"), + ("salary_analysis", "Compensation analysis"), + ]: + section = mock.get(section_key, {}) + if section: + st.markdown(f"**{section_label}**") + for _k, v in section.items(): + st.markdown(v) + st.divider() + + st.markdown("**Full report**") + st.markdown(mock.get("final_report", "")) - else: - st.info("Click **▶ Run system test** above to probe all configured integrations.") + else: + st.info("Click **▶ Run system test** above to probe all configured integrations.") diff --git a/assets/fonts/DejaVu-LICENSE.txt b/assets/fonts/DejaVu-LICENSE.txt new file mode 100644 index 0000000..b3d93a1 --- /dev/null +++ b/assets/fonts/DejaVu-LICENSE.txt @@ -0,0 +1,78 @@ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Upstream-Name: DejaVu fonts +Upstream-Author: Stepan Roh (original author), + see /usr/share/doc/fonts-dejavu-core/AUTHORS for full list +Source: https://dejavu-fonts.github.io/ + +Files: * +Copyright: Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. + Bitstream Vera is a trademark of Bitstream, Inc. + DejaVu changes are in public domain. +License: bitstream-vera + Permission is hereby granted, free of charge, to any person obtaining a copy + of the fonts accompanying this license ("Fonts") and associated + documentation files (the "Font Software"), to reproduce and distribute the + Font Software, including without limitation the rights to use, copy, merge, + publish, distribute, and/or sell copies of the Font Software, and to permit + persons to whom the Font Software is furnished to do so, subject to the + following conditions: + . + The above copyright and trademark notices and this permission notice shall + be included in all copies of one or more of the Font Software typefaces. + . + The Font Software may be modified, altered, or added to, and in particular + the designs of glyphs or characters in the Fonts may be modified and + additional glyphs or characters may be added to the Fonts, only if the fonts + are renamed to names not containing either the words "Bitstream" or the word + "Vera". + . + This License becomes null and void to the extent applicable to Fonts or Font + Software that has been modified and is distributed under the "Bitstream + Vera" names. + . + The Font Software may be sold as part of a larger software package but no + copy of one or more of the Font Software typefaces may be sold by itself. + . + THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, + TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME + FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING + ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF + THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE + FONT SOFTWARE. + . + Except as contained in this notice, the names of Gnome, the Gnome + Foundation, and Bitstream Inc., shall not be used in advertising or + otherwise to promote the sale, use or other dealings in this Font Software + without prior written authorization from the Gnome Foundation or Bitstream + Inc., respectively. For further information, contact: fonts at gnome dot + org. + +Files: debian/* +Copyright: (C) 2005-2006 Peter Cernak + (C) 2006-2011 Davide Viti + (C) 2011-2013 Christian Perrier + (C) 2013 Fabian Greffrath +License: GPL-2+ + This program is free software; you can redistribute it + and/or modify it under the terms of the GNU General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later + version. + . + This program is distributed in the hope that it will be + useful, but WITHOUT ANY WARRANTY; without even the implied + warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR + PURPOSE. See the GNU General Public License for more + details. + . + You should have received a copy of the GNU General Public + License along with this package; if not, write to the Free + Software Foundation, Inc., 51 Franklin St, Fifth Floor, + Boston, MA 02110-1301 USA + . + On Debian systems, the full text of the GNU General Public + License version 2 can be found in the file + /usr/share/common-licenses/GPL-2'. diff --git a/assets/fonts/DejaVuSans-Bold.ttf b/assets/fonts/DejaVuSans-Bold.ttf new file mode 100644 index 0000000..e43f1e6 Binary files /dev/null and b/assets/fonts/DejaVuSans-Bold.ttf differ diff --git a/assets/fonts/DejaVuSans.ttf b/assets/fonts/DejaVuSans.ttf new file mode 100644 index 0000000..4cb860c Binary files /dev/null and b/assets/fonts/DejaVuSans.ttf differ diff --git a/bot/handlers.py b/bot/handlers.py index 0654733..2cede1a 100644 --- a/bot/handlers.py +++ b/bot/handlers.py @@ -14,20 +14,24 @@ from dataclasses import dataclass from typing import Awaitable, Callable, Optional -from agents.orchestrator import run_analysis from services.analysis_runner import ( async_enabled, + check_user_quota, enqueue_analysis, get_async_result, + run_analysis_sync, ) +from services.billing import TierLimitExceeded +from services.rate_limit import RateLimitExceeded from services.telegram_link import ( TelegramLinkError, complete_binding, get_user_id_by_chat, unlink, ) +from services.usage import BudgetExceeded from tools.url_ingest import fetch_job_posting, is_url -from utils.env import env_float +from utils.env import env_bool, env_float logger = logging.getLogger(__name__) @@ -174,12 +178,32 @@ async def handle_me(reply: Reply, args: str, chat_id: int) -> None: await reply(f"Linked to web account *#{user_id}*.") -async def handle_analyze(reply: Reply, args: str) -> None: +async def handle_analyze(reply: Reply, args: str, chat_id: Optional[int] = None) -> None: parsed = parse_analyze_args(args) if not parsed.url and not parsed.text: await reply("Please include a URL or pasted posting text. " + HELP_TEXT) return + # Linked chats are metered exactly like the web UI / API (request-count + # rate limit + spend budget + tier quota). Unlinked chats are refused by + # default: anyone who finds the bot would otherwise spend the operator's + # LLM key (and trigger server-side URL fetches) without limit — and a + # metered user could escape their quota with /unbind. + # TELEGRAM_ALLOW_UNLINKED_ANALYZE=1 restores anonymous use for private bots. + user_id = await asyncio.to_thread(get_user_id_by_chat, chat_id) if chat_id is not None else None + if user_id is None and not env_bool("TELEGRAM_ALLOW_UNLINKED_ANALYZE"): + await reply( + "Link this chat to your web account first: open Settings → Telegram in " + "the web app, then send `/bind ` here." + ) + return + if user_id is not None: + try: + await asyncio.to_thread(check_user_quota, user_id) + except (RateLimitExceeded, BudgetExceeded, TierLimitExceeded) as exc: + await reply(f"⚠️ {exc}") + return + posting_text = parsed.text if parsed.url: try: @@ -192,7 +216,7 @@ async def handle_analyze(reply: Reply, args: str) -> None: await reply("Analyzing — this can take 30-60 seconds…") try: - result = await _run_analysis_for_bot(posting_text) + result = await _run_analysis_for_bot(posting_text, user_id) except Exception as exc: # noqa: BLE001 - reported to user logger.exception("Telegram analyze failed.") await reply(f"❌ Analysis crashed: {exc}") @@ -213,21 +237,25 @@ async def handle_analyze(reply: Reply, args: str) -> None: _BOT_POLL_TIMEOUT = env_float("BOT_TASK_TIMEOUT", 600.0) -async def _run_analysis_for_bot(posting_text: str) -> dict: +async def _run_analysis_for_bot(posting_text: str, user_id: Optional[int] = None) -> dict: """Pick the best execution path: async queue if available, else inline. Async path: enqueue via Celery, then poll for completion off the event loop so the bot stays responsive to other users while a long analysis - runs in the worker. + runs in the worker. ``user_id`` (when the chat is linked) is threaded + through so LLM usage/cost is attributed to the right account instead of + ledgering with a NULL owner. """ if async_enabled(): - task_id = enqueue_analysis(posting_text, manual_inputs=None, model="fast") + task_id = enqueue_analysis( + posting_text, manual_inputs=None, model="fast", user_id=user_id + ) if task_id is not None: return await _await_task(task_id) - # Inline fallback. run_analysis is sync-blocking; offload it so the asyncio - # loop stays free to handle other commands while we wait. + # Inline fallback. run_analysis_sync is sync-blocking; offload it so the + # asyncio loop stays free to handle other commands while we wait. return await asyncio.to_thread( - run_analysis, posting_text, None, "fast", None, + run_analysis_sync, posting_text, None, "fast", None, None, user_id, ) diff --git a/bot/main.py b/bot/main.py index 35b53ff..f13ae44 100644 --- a/bot/main.py +++ b/bot/main.py @@ -77,7 +77,8 @@ async def _analyze(update: Update, ctx: ContextTypes.DEFAULT_TYPE) -> None: return raw = update.message.text or "" _, _, args = raw.partition(" ") - await handle_analyze(_reply_for(update.message), args=args) + chat_id = update.effective_chat.id if update.effective_chat else None + await handle_analyze(_reply_for(update.message), args=args, chat_id=chat_id) async def _bind(update: Update, ctx: ContextTypes.DEFAULT_TYPE) -> None: if update.message is None or update.effective_chat is None: diff --git a/chrome-extension/extract.js b/chrome-extension/extract.js index fec143d..ab0a323 100644 --- a/chrome-extension/extract.js +++ b/chrome-extension/extract.js @@ -62,6 +62,32 @@ function renderVerdict(result) { return `${emoji} ${label}`; } +// Turn a non-2xx /v1/analyze response into an actionable popup message. +// `detail` is the FastAPI error body's `detail` field (or null/undefined +// when the body wasn't JSON) — the REST API already maps quota/rate-limit +// errors to 402/429 with a human-readable detail string, so surfacing it +// beats a bare status code. +function describeApiError(status, detail) { + const suffix = detail ? ` ${detail}` : ""; + switch (status) { + case 401: + return "Token rejected (401). Check your API token."; + case 402: + return `Plan limit reached (402).${suffix || " Upgrade your plan to keep analyzing."}`; + case 403: + return `Access denied (403).${suffix}`; + case 404: + return `Not found (404).${suffix}`; + case 429: + return `Rate limited (429).${suffix || " Try again shortly."}`; + default: + if (status >= 500) { + return `Server error (${status}). Try again shortly.`; + } + return `API error ${status}.${suffix}`; + } +} + // Export for Node tests; harmless in the browser (module is undefined there, // guarded so the popup can load this file directly via
Senior Platform Engineer" + "
" + ) + text = extract_job_text(html) + self.assertIn("Company: Globex", text) + self.assertIn("Location: Berlin, DE", text) + self.assertIn("Compensation: EUR 85000-105000 per year", text) + self.assertIn("Own our Kubernetes platform.", text) + self.assertNotIn("

", text) + self.assertNotIn("cookies", text) + + def test_longest_content_container_wins(self): + from tools.html_extract import extract_job_text + + html = ( + "

" + "
" + "Build data pipelines in Python. " * 10 + + "
" + ) + self.assertIn("Build data pipelines", extract_job_text(html)) diff --git a/tests/test_phase38_ops_backup.py b/tests/test_phase38_ops_backup.py index 55bbb29..81b1988 100644 --- a/tests/test_phase38_ops_backup.py +++ b/tests/test_phase38_ops_backup.py @@ -104,6 +104,49 @@ def test_runbook_exists_and_covers_drill(self): for needle in ("backup", "restore drill", "migration", "escalation"): self.assertIn(needle, text) + def test_runbook_documents_the_compose_scheduler(self): + text = _RUNBOOK.read_text().lower() + self.assertIn("worker.scheduler", text) + + +class SchedulerWiringTests(unittest.TestCase): + """P2 follow-up: reminders + backups are real but nothing invoked them in + the shipped Docker Compose stack. worker/scheduler.py + the compose + `scheduler` service close that gap — assert both exist and are wired.""" + + def test_compose_defines_scheduler_service(self): + compose = (_ROOT / "docker-compose.yml").read_text() + self.assertIn("scheduler:", compose) + self.assertIn("worker.scheduler", compose) + + def test_scheduler_module_calls_reminders_and_backup(self): + from unittest import mock + + from worker import scheduler + + with mock.patch.object(scheduler, "send_inactivity_reminders", + return_value=3) as reminders, \ + mock.patch.object(scheduler.subprocess, "run") as run: + scheduler._run_reminders() + scheduler._run_backup() + + reminders.assert_called_once_with() + run.assert_called_once() + self.assertIn(str(scheduler._BACKUP_SCRIPT), run.call_args.args[0]) + + def test_scheduler_survives_a_failing_run(self): + from unittest import mock + + from worker import scheduler + + with mock.patch.object(scheduler, "send_inactivity_reminders", + side_effect=RuntimeError("boom")): + scheduler._run_reminders() # must not raise + + with mock.patch.object(scheduler.subprocess, "run", + side_effect=RuntimeError("boom")): + scheduler._run_backup() # must not raise + if __name__ == "__main__": unittest.main() diff --git a/tests/test_phase3_units.py b/tests/test_phase3_units.py index c5b9400..4c02391 100644 --- a/tests/test_phase3_units.py +++ b/tests/test_phase3_units.py @@ -184,3 +184,49 @@ def test_delete_removes_record(self): if __name__ == "__main__": unittest.main() + + +class StatusBecomesStageTests(unittest.TestCase): + """Analytics and reminders read stages, so a status change must log one.""" + + def setUp(self): + from db.session import reset_engine_for_testing + from services.auth import register_user + reset_engine_for_testing("sqlite:///:memory:") + self.user = register_user("stage@example.com", "Sup3rSecret!") + + def _save(self, status="saved"): + from services.applications import save_analysis + return save_analysis( + self.user.id, {"company_name": "Acme", "job_title": "Eng"}, + {"verdict": {"verdict": "Recommended", "light": "green"}}, status=status, + ) + + def test_status_change_records_stage(self): + from services.applications import update_status + from services.stages import list_stages + + app = self._save() + self.assertEqual(list_stages(self.user.id, app.id), []) + updated = update_status(self.user.id, app.id, status="rejected") + self.assertEqual([s.kind for s in list_stages(self.user.id, app.id)], ["rejected"]) + self.assertEqual(updated.status, "rejected") + + def test_saving_as_applied_records_stage_once(self): + from services.applications import update_status + from services.stages import list_stages + + app = self._save(status="applied") + update_status(self.user.id, app.id, status="applied", notes="resent") + self.assertEqual([s.kind for s in list_stages(self.user.id, app.id)], ["applied"]) + + def test_existing_interview_stage_not_duplicated(self): + from services.applications import update_status + from services.stages import add_stage, list_stages + + app = self._save(status="applied") + add_stage(self.user.id, app.id, "technical_interview") + update_status(self.user.id, app.id, status="saved") + update_status(self.user.id, app.id, status="interviewing") + kinds = [s.kind for s in list_stages(self.user.id, app.id)] + self.assertEqual(kinds.count("recruiter_screen"), 0) diff --git a/tests/test_phase41_e2e_journeys.py b/tests/test_phase41_e2e_journeys.py index 686f400..a6600d7 100644 --- a/tests/test_phase41_e2e_journeys.py +++ b/tests/test_phase41_e2e_journeys.py @@ -150,7 +150,9 @@ def setUp(self): def test_clean_tailored_cv(self): from services.tailoring import generate_tailored_cv - clean_cv = "Senior Backend Engineer. Skills: Python, PostgreSQL, AWS at Globex." + # No seniority word: the master CV doesn't claim one ("Senior" here + # would be title inflation and is rightly flagged). + clean_cv = "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") diff --git a/tests/test_phase43_billing.py b/tests/test_phase43_billing.py index daa77a1..fc22f8d 100644 --- a/tests/test_phase43_billing.py +++ b/tests/test_phase43_billing.py @@ -317,3 +317,40 @@ def test_generation_blocked_at_artifact_limit(self): if __name__ == "__main__": unittest.main() + + +class StripeWebhookRealSdkTests(unittest.TestCase): + """Goes through the real stripe.Webhook.construct_event (the dict-based + tests above can't catch an SDK object that lacks ``.get``).""" + + def setUp(self): + self.user = _fresh() + + def test_signed_checkout_event_upgrades_user(self): + try: + import stripe # noqa: F401 + except ImportError: + self.skipTest("stripe not installed") + import hashlib + import hmac + import json + import time + + from services import billing + + secret = "whsec_test_secret" + payload = json.dumps({ + "id": "evt_1", "object": "event", "type": "checkout.session.completed", + "data": {"object": { + "object": "checkout.session", + "metadata": {"user_id": str(self.user.id), "tier": "pro"}, + "customer": "cus_1", "subscription": "sub_1", + }}, + }).encode() + ts = int(time.time()) + sig = hmac.new(secret.encode(), f"{ts}.".encode() + payload, hashlib.sha256).hexdigest() + env = dict(_BILLING_ENV, STRIPE_WEBHOOK_SECRET=secret) + with mock.patch.dict(os.environ, env): + event = billing.verify_webhook(payload, f"t={ts},v1={sig}") + self.assertTrue(billing.handle_webhook_event(event)) + self.assertEqual(billing.get_tier(self.user.id), "pro") diff --git a/tests/test_phase44_ssrf.py b/tests/test_phase44_ssrf.py index effdd6c..80c81c8 100644 --- a/tests/test_phase44_ssrf.py +++ b/tests/test_phase44_ssrf.py @@ -105,3 +105,30 @@ def test_webhook_registration_allows_public_host(self): if __name__ == "__main__": unittest.main() + + +class RedirectSsrfTests(unittest.TestCase): + """A public URL must not be able to bounce the fetcher to an internal host.""" + + def test_redirect_to_metadata_service_is_blocked(self): + import tools.url_ingest as url_ingest + + class _Redirect: + is_redirect = True + headers = {"location": "http://169.254.169.254/latest/meta-data/"} + def close(self): pass + + with mock.patch.object(url_ingest.requests, "get", return_value=_Redirect()) as get, \ + mock.patch("utils.security.socket.getaddrinfo", + return_value=[(None, None, None, None, ("93.184.216.34", 0))]): + with self.assertRaises(ValueError) as ctx: + url_ingest.fetch_job_posting("https://example.com/job/1") + self.assertIn("Redirect blocked", str(ctx.exception)) + self.assertEqual(get.call_count, 1) # never requested the internal hop + self.assertFalse(get.call_args.kwargs["allow_redirects"]) + + def test_cgnat_range_is_private(self): + from utils.security import check_url_allowed + + ok, _ = check_url_allowed("http://100.100.100.200/latest/meta-data") + self.assertFalse(ok) diff --git a/tests/test_phase46_personal_discovery.py b/tests/test_phase46_personal_discovery.py new file mode 100644 index 0000000..573fa24 --- /dev/null +++ b/tests/test_phase46_personal_discovery.py @@ -0,0 +1,553 @@ +"""Personal mode: search profile, job discovery, web research, personalised report.""" + +from __future__ import annotations + +import json +import os +import sys +import unittest +from datetime import datetime, timedelta +from types import SimpleNamespace +from unittest import mock + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + + +def _fresh(): + from db.session import reset_engine_for_testing + from services.auth import register_user + from services.rate_limit import reset_backend_for_testing + from utils.cache import cache + + reset_engine_for_testing("sqlite:///:memory:") + reset_backend_for_testing() + cache.clear() + return register_user("me@example.com", "Sup3rSecret!") + + +class _Resp: + def __init__(self, payload, status=200): + self._payload = payload + self.status_code = status + + def json(self): + return self._payload + + +def _routes(table): + """requests.get stand-in: first URL substring match wins.""" + def get(url, params=None, **_kw): + for fragment, payload in table: + if fragment in url: + return payload if isinstance(payload, _Resp) else _Resp(payload) + return _Resp({}, status=404) + return get + + +# Shapes trimmed from real API responses (2026-10). +GREENHOUSE = {"jobs": [{ + "id": 1, "title": "Senior Backend Engineer", "absolute_url": "https://job-boards.greenhouse.io/acme/jobs/1", + "location": {"name": "Remote, Germany"}, "company_name": "Acme", + "first_published": "2026-10-02T11:31:50-04:00", + "content": "<p>Build <b>Python</b> services on Kubernetes.</p>", + "departments": [{"name": "Engineering"}], +}]} +LEVER = [{ + "id": "abc", "text": "Platform Engineer", "hostedUrl": "https://jobs.lever.co/acme/abc", + "categories": {"location": "Berlin", "team": "Infra", "commitment": "Permanent"}, + "workplaceType": "hybrid", "createdAt": 1791566108174, + "descriptionPlain": "Run our platform.", "lists": [{"text": "You have", "content": "
  • Go
  • "}], + "additionalPlain": "", "salaryRange": {"min": 80000, "max": 100000, "currency": "EUR", "interval": "per-year-salary"}, +}] +ASHBY = {"jobs": [{ + "id": "x1", "title": "Staff Backend Engineer", "location": "Europe", "secondaryLocations": [], + "isRemote": True, "isListed": True, "publishedAt": "2021-04-27T20:13:45.158+00:00", + "jobUrl": "https://jobs.ashbyhq.com/acme/x1", "descriptionPlain": "Evergreen role.", + "compensation": {"compensationTierSummary": "€90K – €120K"}, +}]} +REMOTEOK = [ + {"legal": "API Terms of Service: link back..."}, + {"id": "9", "position": "Backend Engineer", "company": "Sothebyâ\u0080\u0099s", "location": "", + "epoch": 1792350002, "url": "https://remoteOK.com/remote-jobs/9", "description": "

    Python

    ", + "salary_min": 0, "salary_max": 0, "tags": ["python"]}, +] +HN_STORIES = {"hits": [ + {"title": "Ask HN: Who wants to be hired? (October 2026)", "objectID": "2"}, + {"title": "Ask HN: Who is hiring? (October 2026)", "objectID": "1"}, +]} +HN_ITEM = {"children": [ + {"id": 11, "created_at": "2026-10-01T15:02:37Z", + "text": "PAGNOS | Cloud Engineer, AWS Serverless | REMOTE (Germany)

    We build things."}, + {"id": 12, "created_at": "2026-10-01T15:03:00Z", "text": None}, +]} + + +class JobSourceParsingTests(unittest.TestCase): + def setUp(self): + _fresh() + + def test_greenhouse_unescapes_html_content(self): + from tools import job_sources as js + with mock.patch.object(js.requests, "get", side_effect=_routes([("greenhouse.io", GREENHOUSE)])): + [lead] = js.greenhouse("acme") + self.assertEqual(lead.company, "Acme") + self.assertTrue(lead.remote) + self.assertIn("Build Python services", lead.description) + self.assertNotIn("<", lead.description) + + def test_lever_falls_back_to_eu_host_and_reads_salary(self): + from tools import job_sources as js + routes = [("api.eu.lever.co", LEVER), ("api.lever.co", _Resp({}, status=404))] + with mock.patch.object(js.requests, "get", side_effect=_routes(routes)): + [lead] = js.lever("acme", "Acme") + self.assertEqual(lead.title, "Platform Engineer") + self.assertIn("EUR 80000-100000", lead.salary) + self.assertIn("Go", lead.description) + + def test_ashby_compensation_and_remote(self): + from tools import job_sources as js + with mock.patch.object(js.requests, "get", side_effect=_routes([("ashbyhq", ASHBY)])): + [lead] = js.ashby("acme", "Acme") + self.assertTrue(lead.remote) + self.assertEqual(lead.salary, "€90K – €120K") + + def test_remoteok_skips_legal_notice_and_fixes_mojibake(self): + from tools import job_sources as js + with mock.patch.object(js.requests, "get", side_effect=_routes([("remoteok", REMOTEOK)])): + leads = js.remoteok() + self.assertEqual(len(leads), 1) + self.assertEqual(leads[0].company, "Sotheby’s") + + def test_hn_picks_hiring_thread_and_parses_header(self): + from tools import job_sources as js + routes = [("search_by_date", HN_STORIES), ("items/1", HN_ITEM)] + with mock.patch.object(js.requests, "get", side_effect=_routes(routes)): + [lead] = js.hn_whos_hiring() + self.assertEqual(lead.company, "PAGNOS") + self.assertIn("Cloud Engineer", lead.title) + self.assertIn("REMOTE (Germany)", lead.location) + self.assertTrue(lead.remote) + + def test_board_slug_is_validated(self): + from tools import job_sources as js + with self.assertRaises(js.SourceError): + js.greenhouse("../../admin") + + def test_responses_are_cached(self): + from tools import job_sources as js + get = mock.Mock(side_effect=_routes([("greenhouse.io", GREENHOUSE)])) + with mock.patch.object(js.requests, "get", get): + js.greenhouse("acme") + js.greenhouse("acme") + self.assertEqual(get.call_count, 1) + + +class ProfileTests(unittest.TestCase): + def setUp(self): + self.user = _fresh() + + def test_roundtrip_normalizes(self): + from services.profile import CandidateProfile, get_profile, save_profile + save_profile(self.user.id, CandidateProfile( + target_titles=["Backend Engineer", " backend engineer ", ""], + work_modes=["remote", "teleport"], salary_currency="eur", + )) + p = get_profile(self.user.id) + self.assertEqual(p.target_titles, ["Backend Engineer"]) + self.assertEqual(p.work_modes, ["remote"]) + self.assertEqual(p.salary_currency, "EUR") + + def test_watchlist_requires_known_ats(self): + from services.profile import CandidateProfile, ProfileError, save_profile + with self.assertRaises(ProfileError): + save_profile(self.user.id, CandidateProfile( + target_titles=["x"], watchlist=[{"company": "A", "ats": "workday", "slug": "a"}])) + + def test_prompt_text_includes_floor_and_dealbreakers(self): + from services.profile import CandidateProfile, profile_as_prompt + text = profile_as_prompt(CandidateProfile( + target_titles=["SRE"], salary_floor=80000, dealbreakers=["crypto"])) + self.assertIn("80,000 EUR/year", text) + self.assertIn("Dealbreakers: crypto", text) + self.assertEqual(profile_as_prompt(CandidateProfile()), "") + + +def _profile(**kw): + from services.profile import CandidateProfile + base = dict(target_titles=["Senior Backend Engineer"], seniority="Senior", + locations=["Berlin", "Germany"], work_modes=["remote", "hybrid"], + remote_regions="EU", salary_floor=80000, salary_currency="EUR", + search_keywords=["Python", "Kubernetes"]) + base.update(kw) + return CandidateProfile(**base) + + +def _lead(**kw): + from tools.job_sources import JobLead + base = dict(source="remotive", external_id="1", url="https://x.test/1", + title="Backend Engineer", company="Acme", location="Remote", remote=True, + posted_at=datetime.utcnow(), description="Python and Kubernetes") + base.update(kw) + return JobLead(**base) + + +class RankingTests(unittest.TestCase): + def test_title_match_ignores_seniority_and_synonyms(self): + from services.discovery import title_match + self.assertEqual(title_match("Sr. Back-end Developer", ["Senior Backend Engineer"]), 1.0) + self.assertEqual(title_match("Engineering Manager", ["Backend Engineer"]), 0.0) + self.assertEqual(title_match("ML Engineer", ["Machine Learning Engineer"]), 1.0) + + def test_flags_us_only_remote_for_eu_candidate(self): + from services.discovery import score_lead + score_us, flags = score_lead(_lead(location="Remote (US only)"), _profile()) + score_eu, _ = score_lead(_lead(location="Remote, Europe"), _profile()) + self.assertIn("Remote, but restricted to the Americas", flags) + self.assertLess(score_us, score_eu) + + def test_salary_below_floor_and_dealbreaker_flags(self): + from services.discovery import score_lead + _, flags = score_lead(_lead(salary="EUR 50000-60000"), _profile()) + self.assertTrue(any("below your floor" in f for f in flags)) + _, flags = score_lead(_lead(company="CryptoCorp", tags=["crypto"]), _profile(dealbreakers=["crypto"])) + self.assertTrue(any("dealbreaker" in f for f in flags)) + + def test_salary_parsing(self): + from services.discovery import parse_salary_max + self.assertEqual(parse_salary_max("€90K – €120K"), (120000.0, "EUR")) + self.assertEqual(parse_salary_max("$1000 per task"), (None, None)) + self.assertEqual(parse_salary_max("EUR 85,000 - 105,000"), (105000.0, "EUR")) + + def test_prefilter_age_applies_to_aggregators_not_watchlist(self): + from services.discovery import prefilter + old = _lead(posted_at=datetime.utcnow() - timedelta(days=400)) + self.assertFalse(prefilter("remotive:backend", old, _profile())) + self.assertTrue(prefilter("ashby:Acme", old, _profile())) + self.assertFalse(prefilter("remotive:x", _lead(title="Sales Manager"), _profile())) + + +class DiscoveryLifecycleTests(unittest.TestCase): + def setUp(self): + self.user = _fresh() + from services.profile import save_profile + save_profile(self.user.id, _profile()) + + def _refresh(self, leads, **kw): + from services import discovery + report = discovery.RefreshReport(fetched=len(leads)) + with mock.patch.object(discovery, "gather", return_value=([("remotive:x", l) for l in leads], report)): + return discovery.refresh_feed(self.user.id, triage_limit=0, **kw) + + def test_dedupe_and_dismissed_stays_dismissed(self): + from services import discovery + a = _lead(url="https://x.test/1?utm=1") + b = _lead(url="https://x.test/1", source="remoteok") + report = self._refresh([a, b]) + self.assertEqual(report.new, 1) + [job] = discovery.list_feed(self.user.id) + discovery.set_status(self.user.id, job.id, "dismissed") + report = self._refresh([a]) + self.assertEqual((report.new, report.seen_again), (0, 1)) + self.assertEqual(discovery.list_feed(self.user.id), []) + self.assertEqual(discovery.feed_counts(self.user.id)["dismissed"], 1) + + def test_triage_scores_and_orders_feed(self): + from services import discovery + self._refresh([_lead(url="https://x.test/1"), _lead(url="https://x.test/2", title="Backend Engineer II")]) + jobs = discovery.list_feed(self.user.id) + payload = json.dumps([ + {"id": jobs[0].id, "fit": 40, "summary": "meh", "flags": ["German C1 required"]}, + {"id": jobs[1].id, "fit": 90, "summary": "strong", "flags": []}, + {"id": 99999, "fit": 100, "summary": "not in batch"}, + ]) + with mock.patch("utils.llm.is_demo_mode", return_value=False), \ + mock.patch.object(discovery, "get_completion", return_value=payload): + self.assertEqual(discovery.triage(self.user.id), 2) + ordered = discovery.list_feed(self.user.id) + self.assertEqual([j.fit_score for j in ordered], [90, 40]) + self.assertIn("German C1 required", ordered[1].fit_flags) + + def test_track_creates_application(self): + from services import discovery + from services.applications import get_application + self._refresh([_lead(description="x" * 500)]) + [job] = discovery.list_feed(self.user.id) + app_id = discovery.track(self.user.id, job.id) + app = get_application(self.user.id, app_id) + self.assertEqual((app.company_name, app.job_title), ("Acme", "Backend Engineer")) + self.assertEqual(discovery.get_job(self.user.id, job.id).status, "saved") + + def test_refresh_requires_profile(self): + from services import discovery + from services.auth import register_user + other = register_user("other@example.com", "Sup3rSecret!") + with self.assertRaises(discovery.DiscoveryError): + discovery.refresh_feed(other.id) + + +def _block(kind, **kw): + return SimpleNamespace(type=kind, **kw) + + +class WebResearchTests(unittest.TestCase): + def setUp(self): + _fresh() + self.env = mock.patch.dict(os.environ, {"ANTHROPIC_API_KEY": "sk-test"}) + self.env.start() + self.addCleanup(self.env.stop) + + def _client(self, responses): + client = mock.Mock() + client.beta.messages.create.side_effect = responses + return client + + def test_pause_turn_continues_and_collects_sources(self): + from utils import llm + usage = SimpleNamespace(input_tokens=100, output_tokens=50, + server_tool_use=SimpleNamespace(web_search_requests=2)) + paused = SimpleNamespace(stop_reason="pause_turn", usage=usage, content=[ + _block("text", text="Part one.", citations=None), + _block("web_search_tool_result", content=[SimpleNamespace(url="https://a.test", title="A")]), + ]) + done = SimpleNamespace(stop_reason="end_turn", usage=usage, content=[ + _block("text", text="Part two.", citations=[SimpleNamespace(url="https://a.test", title="A"), + SimpleNamespace(url="https://b.test", title="B")]), + ]) + client = self._client([paused, done]) + recorded = [] + with mock.patch("anthropic.Anthropic", return_value=client), \ + mock.patch.object(llm, "_record_usage", side_effect=lambda *a: recorded.append(a)): + text, sources = llm.web_research("Research Acme") + self.assertEqual(text, "Part one.\nPart two.") + self.assertEqual([s["url"] for s in sources], ["https://a.test", "https://b.test"]) + second_call = client.beta.messages.create.call_args_list[1].kwargs + self.assertEqual(second_call["messages"][1]["role"], "assistant") + self.assertEqual(len(recorded), 2) + self.assertAlmostEqual(recorded[0][2]["extra_cost_usd"], 0.02) + first = client.beta.messages.create.call_args_list[0].kwargs + self.assertEqual(first["extra_body"], {"fallbacks": "default"}) + self.assertEqual(first["tools"][0]["type"], "web_search_20260209") + + def test_rejected_fallback_beta_degrades_to_plain_request(self): + from utils import llm + + class _BadRequest(Exception): + status_code = 400 + + client = mock.Mock() + client.beta.messages.create.side_effect = _BadRequest("fallbacks: unknown beta") + client.messages.create.return_value = SimpleNamespace( + stop_reason="end_turn", usage=None, content=[_block("text", text="ok", citations=None)]) + with mock.patch.object(llm, "_fallbacks_rejected", False), \ + mock.patch("anthropic.Anthropic", return_value=client): + text, _ = llm.web_research("x") + self.assertTrue(llm._fallbacks_rejected) + self.assertEqual(text, "ok") + + def test_unavailable_without_anthropic_key(self): + from utils import llm + with mock.patch.dict(os.environ, {"ANTHROPIC_API_KEY": ""}): + with self.assertRaises(llm.WebResearchUnavailable): + llm.web_research("x") + + +class PersonalisedReportTests(unittest.TestCase): + def test_report_prompt_carries_profile_and_fit_section(self): + from agents import report_generator + captured = {} + + def grab(prompt, model=None): + captured["prompt"] = prompt + return "# Report\n\nok" + + state = {"job_details": {"extracted_details": {"company_name": "Acme"}}, + "profile_text": "- Minimum acceptable base salary: 80,000 EUR/year"} + with mock.patch.object(report_generator, "get_completion", side_effect=grab): + report_generator.generate(state) + self.assertIn("80,000 EUR/year", captured["prompt"]) + self.assertIn("Fit for You", captured["prompt"]) + self.assertIn("caps it at `Consider with Caution`", captured["prompt"]) + + with mock.patch.object(report_generator, "get_completion", side_effect=grab): + report_generator.generate({"job_details": {}}) + self.assertNotIn("Fit for You", captured["prompt"]) + + +try: + from streamlit.testing.v1 import AppTest + HAS_APPTEST = True +except Exception: # noqa: BLE001 + HAS_APPTEST = False + + +@unittest.skipUnless(HAS_APPTEST, "streamlit AppTest harness unavailable") +class PersonalModeAppTests(unittest.TestCase): + def setUp(self): + _fresh() + for k in ("ANTHROPIC_API_KEY", "OPENAI_API_KEY", "FEATHERLESS_API_KEY", "LLM_PROVIDER"): + os.environ.pop(k, None) + + def test_renders_without_login_and_discover_first(self): + app_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "app.py")) + with mock.patch.dict(os.environ, {"PERSONAL_MODE": "1"}): + at = AppTest.from_file(app_path, default_timeout=60) + at.run() + self.assertFalse(at.exception, msg=[str(e.value) for e in at.exception]) + self.assertEqual(at.tabs[0].label, "🔭 Discover") + labels = {b.label for b in at.button} + self.assertNotIn("Sign out", labels) + self.assertIn("✨ Draft from my master CV", labels) + self.assertFalse(any("Sign in" in (b.label or "") for b in at.button)) + + +if __name__ == "__main__": + unittest.main() + + +class UnmigratedDatabaseTests(unittest.TestCase): + """The live deploy has lagged migrations before: a database without the + new tables must not break analyses or halt the page.""" + + def setUp(self): + _fresh() + from sqlalchemy import text + + from db.session import get_engine + with get_engine().begin() as conn: + conn.execute(text("DROP TABLE candidate_profiles")) + conn.execute(text("DROP TABLE discovered_jobs")) + + def test_profile_prompt_is_best_effort(self): + from services.profile import profile_prompt_for + self.assertEqual(profile_prompt_for(1), "") + + @unittest.skipUnless(HAS_APPTEST, "streamlit AppTest harness unavailable") + def test_app_still_renders_with_migration_hint(self): + for k in ("ANTHROPIC_API_KEY", "OPENAI_API_KEY", "FEATHERLESS_API_KEY", "LLM_PROVIDER"): + os.environ.pop(k, None) + app_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "app.py")) + with mock.patch.dict(os.environ, {"PERSONAL_MODE": "1"}): + at = AppTest.from_file(app_path, default_timeout=60) + at.run() + self.assertFalse(at.exception, msg=[str(e.value) for e in at.exception]) + self.assertTrue(any("needs a database migration" in e.value for e in at.error)) + # The Analyze tab renders after Discover: its submit button proves the + # script wasn't halted by the missing tables. + self.assertIn("🔍 Analyze posting", [b.label for b in at.button]) + + +_ISOLATION_PROBE = r""" +import os, sys +for k in ("ANTHROPIC_API_KEY", "OPENAI_API_KEY", "FEATHERLESS_API_KEY"): + os.environ.pop(k, None) +os.environ["PERSONAL_MODE"] = "1" +from db.session import reset_engine_for_testing +reset_engine_for_testing("sqlite:///:memory:") +from services.personal import ensure_local_owner +ensure_local_owner() +sys.modules.pop("services.auth", None) # owner creation happens once, on first start +from streamlit.testing.v1 import AppTest +at = AppTest.from_file(sys.argv[1], default_timeout=60) +at.run() +assert not at.exception, [e.value for e in at.exception] +side = [m for m in sys.modules if m.split(".")[0] in ("celery", "stripe", "telegram", "pyotp", "qrcode") + or m in ("services.auth", "services.webhooks", "services.telegram_link", "services.totp", + "services.oauth", "services.background_analysis", "services.sharing", + "services.notifications", "services.api_tokens", "services.email_verify", + "worker.tasks", "worker.celery_app")] +print("SIDE=" + ",".join(sorted(side))) +""" + + +@unittest.skipUnless(HAS_APPTEST, "streamlit AppTest harness unavailable") +class PersonalModeIsolationTests(unittest.TestCase): + def test_side_features_are_not_imported(self): + """Fresh process: personal mode must not import accounts, 2FA, OAuth, + webhooks, Telegram, sharing, notifications, background jobs, billing SDKs.""" + import subprocess + + root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) + out = subprocess.run( + [sys.executable, "-c", _ISOLATION_PROBE, os.path.join(root, "app.py")], + cwd=root, capture_output=True, text=True, timeout=180, + ) + line = next((l for l in out.stdout.splitlines() if l.startswith("SIDE=")), None) + self.assertIsNotNone(line, msg=out.stderr[-2000:]) + self.assertEqual(line, "SIDE=", msg="side-feature modules loaded in personal mode") + + +@unittest.skipUnless(HAS_APPTEST, "streamlit AppTest harness unavailable") +class PersonalJourneyTests(unittest.TestCase): + """Personal mode, end to end: feed → track → stages → tailored CV → PDF.""" + + def setUp(self): + _fresh() + for k in ("ANTHROPIC_API_KEY", "OPENAI_API_KEY", "FEATHERLESS_API_KEY", "LLM_PROVIDER"): + os.environ.pop(k, None) + self.env = mock.patch.dict(os.environ, {"PERSONAL_MODE": "1"}) + self.env.start() + self.addCleanup(self.env.stop) + from services.master_cv import save_master_cv + from services.personal import ensure_local_owner + from services.profile import save_profile + self.uid, _ = ensure_local_owner() + save_master_cv(self.uid, "Alex Kim\nSoftware Engineer at Initech (2019-2024)\n" + "Skills: Python, Django, PostgreSQL\n- Built billing APIs") + save_profile(self.uid, _profile()) + + def _app(self): + app_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "app.py")) + at = AppTest.from_file(app_path, default_timeout=60) + at.run() + self.assertFalse(at.exception, msg=[str(e.value) for e in at.exception]) + return at + + def _button(self, at, key): + return next((b for b in at.button if getattr(b, "key", None) == key), None) + + def test_track_stage_and_tailor_flow(self): + from services import discovery + from services.applications import get_application + from services.stages import list_stages + from services.tailoring import list_artifacts + + report = discovery.RefreshReport() + lead = _lead(company="Globex", title="Backend Engineer", description="Python and Django. " * 30) + with mock.patch.object(discovery, "gather", return_value=([("remotive:x", lead)], report)): + discovery.refresh_feed(self.uid, triage_limit=0) + + at = self._app() + [job] = discovery.list_feed(self.uid) + self._button(at, f"disc_tr_{job.id}").click().run() # 📌 Track + self.assertFalse(at.exception, msg=[str(e.value) for e in at.exception]) + app_id = discovery.get_job(self.uid, job.id).application_id + self.assertIsNotNone(app_id) + + self._button(at, f"qa_{app_id}_applied").click().run() # stage quick-actions + self._button(at, f"qa_{app_id}_technical_interview").click().run() + self.assertFalse(at.exception, msg=[str(e.value) for e in at.exception]) + self.assertEqual([s.kind for s in list_stages(self.uid, app_id)], ["applied", "technical_interview"]) + self.assertEqual(get_application(self.uid, app_id).status, "interviewing") + + # Tailored CV: the generated text claims a skill the CV lacks; the check must flag it. + with mock.patch("services.tailoring.get_completion", + return_value="# Alex Kim\n## Skills\nPython, Django, Kubernetes"): + self._button(at, f"gen_cv_{app_id}").click().run() + self.assertFalse(at.exception, msg=[str(e.value) for e in at.exception]) + [art] = list_artifacts(self.uid, app_id) + self.assertIn("kubernetes", art.meta["constraint_check"]["new_proper_nouns"]) + at.checkbox(key=f"art_expand_{art.id}").check().run() # open the artifact + self.assertFalse(at.exception, msg=[str(e.value) for e in at.exception]) + self.assertTrue(any("Review recommended" in w.value and "kubernetes" in w.value + for w in at.warning)) + # Markdown + PDF downloads rendered for this artifact (PDF built OK). + ids = " ".join(str(d.proto.id) for d in at.get("download_button")) + self.assertIn(f"art_dl_pdf_{art.id}", ids) + self.assertIn(f"art_dl_md_{art.id}", ids) + + with mock.patch("services.tailoring.get_completion", + return_value="Dear Hiring Manager,\n\nI built billing APIs in Python at Initech."): + self._button(at, f"gen_cl_{app_id}").click().run() + self.assertFalse(at.exception, msg=[str(e.value) for e in at.exception]) + kinds = sorted(a.kind for a in list_artifacts(self.uid, app_id)) + self.assertEqual(kinds, ["cover_letter", "tailored_cv"]) diff --git a/tests/test_phase4_units.py b/tests/test_phase4_units.py index db6d03a..bbd9256 100644 --- a/tests/test_phase4_units.py +++ b/tests/test_phase4_units.py @@ -256,7 +256,8 @@ def test_analyze_handler_with_text(self): "job_details": {"extracted_details": {"company_name": "Acme"}}, "final_report": "# Report\n\nShort.", } - with mock.patch.object(handlers, "run_analysis", return_value=fake_result): + with mock.patch.object(handlers, "run_analysis_sync", return_value=fake_result), \ + mock.patch.dict(os.environ, {"TELEGRAM_ALLOW_UNLINKED_ANALYZE": "1"}): _run(handlers.handle_analyze(cap, "Company: Acme\nTitle: Eng")) joined = "\n".join(cap.messages) self.assertIn("Analyzing", joined) diff --git a/tests/test_phase6_units.py b/tests/test_phase6_units.py index 96701c5..e7a3637 100644 --- a/tests/test_phase6_units.py +++ b/tests/test_phase6_units.py @@ -129,7 +129,10 @@ class _Resp: status_code = 200 headers = {"content-type": "text/html"} content = b"tiny" + is_redirect = False def raise_for_status(self): pass + def iter_content(self, chunk_size=1): yield self.content + def close(self): pass with mock.patch.object(url_ingest.requests, "get", return_value=_Resp()), \ mock.patch.object(url_ingest, "_try_browser_fallback", return_value="X" * 500) as fb: @@ -144,7 +147,10 @@ class _Resp: status_code = 200 headers = {"content-type": "text/html"} content = b"tiny" + is_redirect = False def raise_for_status(self): pass + def iter_content(self, chunk_size=1): yield self.content + def close(self): pass with mock.patch.object(url_ingest.requests, "get", return_value=_Resp()), \ mock.patch.object(url_ingest, "_try_browser_fallback", return_value=None): diff --git a/tests/test_phase7_units.py b/tests/test_phase7_units.py index 63391bf..035fcbf 100644 --- a/tests/test_phase7_units.py +++ b/tests/test_phase7_units.py @@ -93,14 +93,32 @@ def setUp(self): os.environ["RL_RESET_MAX"] = "2" os.environ["RL_RESET_WINDOW"] = "60" # Re-import services.rate_limit so the env-driven defaults take effect, - # then rebuild the limiters in services.auth too. - for mod_name in ("services.rate_limit", "services.auth"): + # then rebuild the limiters in services.auth too. Reloading mints new + # exception classes, so anything that already imported the originals + # at module load time (bot/handlers.py, api/routes.py) would hold a + # stale class for the rest of the suite — save + restore in tearDown. + self._saved_modules = { + name: sys.modules.get(name) + for name in ("services.rate_limit", "services.auth") + } + for mod_name in self._saved_modules: sys.modules.pop(mod_name, None) _reset_rate_limit() _fresh_db() from services.auth import register_user # noqa: F401 - re-imports below self._register = register_user + def tearDown(self): + for name in ("RL_LOGIN_MAX", "RL_LOGIN_WINDOW", "RL_REGISTER_MAX", + "RL_REGISTER_WINDOW", "RL_RESET_MAX", "RL_RESET_WINDOW"): + os.environ.pop(name, None) + for name, mod in self._saved_modules.items(): + if mod is not None: + sys.modules[name] = mod + else: + sys.modules.pop(name, None) + _reset_rate_limit() + def test_login_blocks_after_max_failures(self): from services.auth import AuthError, authenticate_user from services.rate_limit import RateLimitExceeded @@ -159,10 +177,30 @@ def setUp(self): os.environ.pop("CELERY_BROKER_URL", None) os.environ["RL_ANALYSIS_MAX"] = "2" os.environ["RL_ANALYSIS_WINDOW"] = "60" - for mod_name in ("services.rate_limit", "services.analysis_runner"): + # Reloading these modules picks up the env vars above, but it also + # mints NEW exception classes (RateLimitExceeded et al.). Anything + # that already imported the originals at module load time (e.g. + # bot/handlers.py, api/routes.py) would then hold a stale class, so + # its `except RateLimitExceeded` stops matching for the rest of the + # suite. Save the pre-reload modules and put them back in tearDown. + self._saved_modules = { + name: sys.modules.get(name) + for name in ("services.rate_limit", "services.analysis_runner") + } + for mod_name in self._saved_modules: sys.modules.pop(mod_name, None) _reset_rate_limit() + def tearDown(self): + os.environ.pop("RL_ANALYSIS_MAX", None) + os.environ.pop("RL_ANALYSIS_WINDOW", None) + for name, mod in self._saved_modules.items(): + if mod is not None: + sys.modules[name] = mod + else: + sys.modules.pop(name, None) + _reset_rate_limit() + def test_quota_blocks_after_max(self): from services.analysis_runner import check_user_quota from services.rate_limit import RateLimitExceeded @@ -193,6 +231,13 @@ def test_quota_none_user_id_skips(self): # --------------------------------------------------------------------------- class BotQueueRoutingTests(unittest.TestCase): + + def setUp(self): + # These cover queue routing, not auth: run them as an opted-in + # private bot (unlinked chats are refused by default). + patcher = mock.patch.dict(os.environ, {"TELEGRAM_ALLOW_UNLINKED_ANALYZE": "1"}) + patcher.start() + self.addCleanup(patcher.stop) def test_bot_uses_queue_when_async_enabled(self): from bot import handlers @@ -232,7 +277,7 @@ async def reply(text): } with mock.patch.object(handlers, "async_enabled", return_value=False), \ - mock.patch.object(handlers, "run_analysis", return_value=fake_result), \ + mock.patch.object(handlers, "run_analysis_sync", return_value=fake_result), \ mock.patch.object(handlers, "enqueue_analysis") as enq: asyncio.run(handlers.handle_analyze(reply, "Company: Acme\nTitle: Eng")) @@ -278,6 +323,81 @@ async def reply(text): msg=f"unexpected reply set: {sent!r}", ) + def test_bot_enforces_quota_for_linked_chat(self): + # A chat linked to a web account must be metered exactly like the + # web UI/API — this used to be a total bypass (chat_id was never + # even threaded into the handler). + from bot import handlers + from services.rate_limit import RateLimitExceeded + + sent = [] + + async def reply(text): + sent.append(text) + + with mock.patch.object(handlers, "get_user_id_by_chat", return_value=7), \ + mock.patch.object(handlers, "check_user_quota", + side_effect=RateLimitExceeded(30)) as quota, \ + mock.patch.object(handlers, "run_analysis_sync") as run_sync, \ + mock.patch.object(handlers, "enqueue_analysis") as enq: + asyncio.run( + handlers.handle_analyze(reply, "Company: Acme\nTitle: Eng", chat_id=123) + ) + + quota.assert_called_once_with(7) + run_sync.assert_not_called() + enq.assert_not_called() + self.assertTrue(any("⚠️" in m for m in sent)) + + def test_bot_refuses_unlinked_chat_by_default(self): + # Anonymous /analyze spent the operator's key without any limit, and + # /unbind let a metered user escape their quota. + from bot import handlers + + sent = [] + + async def reply(text): + sent.append(text) + + env = {k: v for k, v in os.environ.items() if k != "TELEGRAM_ALLOW_UNLINKED_ANALYZE"} + with mock.patch.dict(os.environ, env, clear=True), \ + mock.patch.object(handlers, "get_user_id_by_chat", return_value=None), \ + mock.patch.object(handlers, "run_analysis_sync") as run_sync, \ + mock.patch.object(handlers, "fetch_job_posting") as fetch: + asyncio.run( + handlers.handle_analyze(reply, "https://example.com/job", chat_id=999) + ) + + run_sync.assert_not_called() + fetch.assert_not_called() + self.assertTrue(any("/bind" in m for m in sent)) + + def test_unlinked_chat_allowed_when_opted_in(self): + from bot import handlers + + sent = [] + + async def reply(text): + sent.append(text) + + fake_result = { + "verdict": {"verdict": "Recommended", "light": "green", "reasons": []}, + "job_details": {"extracted_details": {"company_name": "Acme"}}, + "final_report": "# Report\n\nUnlinked.", + } + + with mock.patch.dict(os.environ, {"TELEGRAM_ALLOW_UNLINKED_ANALYZE": "1"}), \ + mock.patch.object(handlers, "get_user_id_by_chat", return_value=None), \ + mock.patch.object(handlers, "check_user_quota") as quota, \ + mock.patch.object(handlers, "async_enabled", return_value=False), \ + mock.patch.object(handlers, "run_analysis_sync", return_value=fake_result): + asyncio.run( + handlers.handle_analyze(reply, "Company: Acme\nTitle: Eng", chat_id=999) + ) + + quota.assert_not_called() + self.assertIn("Unlinked.", "\n".join(sent)) + if __name__ == "__main__": unittest.main() diff --git a/tools/company_research.py b/tools/company_research.py index 1775bc4..d574d14 100644 --- a/tools/company_research.py +++ b/tools/company_research.py @@ -264,10 +264,66 @@ def _format_results(results: List[dict]) -> str: return "\n".join(lines) +_CLAUDE_RESEARCH_PROMPT = """\ +Research the company **{company}** for a job seeker deciding whether to apply +or accept an offer. Use web search (and fetch a page when a snippet isn't +enough). Cover, briefly: + +1. What they do and how they make money; size and locations. +2. Funding stage, latest round / financial results, profitability signals. +3. Layoffs, hiring freezes, restructurings or leadership changes in the last + 18 months (with dates). +4. Employee sentiment: Glassdoor, Kununu (DACH), Blind, Reddit — ratings and + recurring themes if found. +5. Engineering/work culture and remote/hybrid policy. +6. Red flags: lawsuits, regulatory trouble, scam reports, wage complaints. + +Rules: cite every fact inline as a markdown link to its source; write "not +found" where you found nothing rather than guessing; prefer sources from the +last 24 months and give dates. +Start with exactly: "REAL DATA (web research) for {company}:" +""" + + +def claude_company_research(company: str) -> Optional[str]: + """Live, cited company research via Claude's server-side web tools. + Cached per company; None on failure (caller falls back).""" + from utils.cache import cache + from utils.llm import web_research + + key = f"webresearch:company:{company.strip().lower()}" + cached = cache.get(key) + if isinstance(cached, str): + return cached + try: + text, sources = web_research( + _CLAUDE_RESEARCH_PROMPT.format(company=company), max_searches=6, max_fetches=2 + ) + except Exception as exc: # noqa: BLE001 - fall back to keyless search + logger.warning("Claude company research failed for %s: %s", company, exc) + return None + if sources: + text += "\n\nSources:\n" + "\n".join(f"- [{s['title']}]({s['url']})" for s in sources[:12]) + cache.set(key, text) + return text + + 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: + """Web research for a company. Returns a synthesised briefing string, or + None when unavailable (caller uses its sentinel). + + With an Anthropic key: Claude's own web search + fetch (cited, current). + Otherwise: LLM-proposed queries over keyless DuckDuckGo snippets. + """ + if not company: + return None + from utils.llm import web_research_available + + if web_research_available(): + researched = claude_company_research(company) + if researched: + return researched + if not fallback_enabled(): return None queries = build_queries(company, model) diff --git a/tools/company_tools.py b/tools/company_tools.py index a7c0281..2c1bb1a 100644 --- a/tools/company_tools.py +++ b/tools/company_tools.py @@ -15,11 +15,6 @@ import logging -try: - from langchain_core.tools import Tool # langchain >= 0.3 -except ImportError: # pragma: no cover - older langchain layout - 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 from utils.llm import get_completion @@ -125,17 +120,3 @@ def analyze_culture_signals(company_name: str, model: str = "detailed") -> str: response = get_completion(prompt, model) cache.set(cache_key, response) return response - - -company_tools = [ - Tool( - name="analyze_company_stability", - func=analyze_company_stability, - description="Analyzes company stability and growth prospects", - ), - Tool( - name="analyze_culture_signals", - func=analyze_culture_signals, - description="Inferred culture briefing (not real reviews)", - ), -] diff --git a/tools/html_extract.py b/tools/html_extract.py index 003af50..3ad5ce8 100644 --- a/tools/html_extract.py +++ b/tools/html_extract.py @@ -8,8 +8,10 @@ from __future__ import annotations +import html as html_lib +import json import re -from typing import Union +from typing import Any, Iterator, Optional, Union from bs4 import BeautifulSoup @@ -20,8 +22,18 @@ def extract_job_text(html: Union[str, bytes]) -> str: - """Return cleaned posting text from raw HTML (``str`` or ``bytes``).""" + """Return cleaned posting text from raw HTML (``str`` or ``bytes``). + + Prefers schema.org ``JobPosting`` JSON-LD, which Greenhouse, Lever, Ashby, + Workday, SmartRecruiters and LinkedIn guest pages embed for Google Jobs: + it is the complete posting, including salary, independent of page layout. + (It lives in a ``