Skip to content

Copy of CLAUDE.md from smart_apply_backend

Generated from smart_apply_backend/CLAUDE.md at commit e15126d9. Edit the source file, not this copy.

CLAUDE.md

Explore in graph

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Commands

uv sync                       # install deps + dev group into .venv (add --extra ml for torch/MiniLM)

# Run the API (dev). Interactive docs at http://localhost:8000/docs
uv run uvicorn app.main:app --reload --host 0.0.0.0

# Production entrypoint (downloads MiniLM if missing, single worker, thread caps)
./start.sh

# Tests run with pytest (fixtures in tests/conftest.py). `python -m unittest` finds only
# the unittest-style subset, so don't use it.
uv run pytest                                        # all
uv run pytest tests/test_work_ledger.py              # one module
uv run pytest tests/test_work_ledger.py -k test_name # one test

On Windows the venv interpreter is .venv/Scripts/python. There is no linter or formatter configured.

Dependencies are managed by uv: pyproject.toml + uv.lock (commit both; uv add/uv lock to change them, never pip install). It's an app, not a package (tool.uv.package = false). The ml extra adds torch/transformers/sentence-transformers (CUDA build on Linux, MPS on Apple Silicon, skipped on Intel Macs). The dev group (pytest) installs by default; e2e (playwright) is opt-in via --group e2e. On machines without the ml extra, set RESUME_MATCHING_ENABLED=false.

JWT_SECRET_KEY is required at import time (Settings has no default for it). The rest of the config is in app/config.py and is read from .env.

Architecture

FastAPI + MongoDB (Motor, async). It's a flat package: app/main.py wires one router per app/routers_*.py file (plus auth.py), each with its own URL prefix. Jobs endpoints are split across routers_jobs.py, routers_jobs_bidder.py, and routers_jobs_assign.py (same /jobs prefix); shared helpers live in app/jobs_common.py.

Startup (lifespan in main.py): ensure_indexes creates every index on each boot, so new indexes go in app/database.py. work_ledger.backfill_existing runs a one-time backfill guarded by a marker id. Then the APScheduler daily cron (app/cron.py) starts. Production runs one uvicorn worker, and the Mongo pool and in-process caches assume that.

Roles and hierarchy (UserRole in app/models.py): superadmin → manager → admin → bidder. Users link upward through manager_id / admin_id. A bidder can work under several admins (admin_ids, where admin_id is the first entry, see bidder_admin_id_strings). Shared role gates live in app/authz.py (require_role, require_admin, require_manager, require_bidder, require_superadmin, require_roles_exact). Ownership checks stay inline in each router. CurrentUser (in auth.py) is the auth dependency.

Data model: there's no separate applications collection. Applications are embedded in jobs.applications[], one entry per admin/bidder, with status drawn from ApplicationStatus. Most job queries and indexes target applications.* fields. Bidders can't set final statuses directly. They put a job into request_applied / request_expired, and a manager confirms it. Admin status changes skip jobs in that request queue (admin_status_change_applies).

Applied companies / company filter: the companies an admin has applied to live in the applied_companies collection (app/applied_companies.py), not in users.applied_company_names. That array is legacy, and scripts/migrate_db_perf.py moves and drops it; the user runs that script, the app never migrates on its own. Code that writes jobs.companyName also sets companyName_lc (with_company_lc / company_lc in jobs_common.py). The exclude-applied filter falls back to $toLower for jobs without it, such as rows from the external aggregator.

Work ledger / pay (app/work_ledger.py): it records bidder work events (confirmed/assigned/unassigned/expired) into bidder_daily at the moment they happen, de-duplicated by the unique bidder_counted_jobs index. That's because the retention cleanup deletes old jobs, so pay can't be recomputed from jobs. Weekly pay (bidder_pay_weeks) uses rates from bidder_rates with effective dates, and weeks start on Monday (UTC). Any code path that changes assignment or status needs to call the matching record_* helper. tests/test_work_ledger.py covers this with an in-memory FakeCollection.

Data retention (app/retention.py, app/cron.py, routers_retention.py): every retention period lives in one Mongo doc (app_settings / _id: "retention"), edited by the superadmin at /admin/retention (dashboard page /data-retention). Nothing is hard-coded: RetentionPolicy defaults apply until the superadmin first saves (reads never write), and None means keep forever. The daily cron reads the policy each run, at the configured UTC hour, and skips when disabled. run_cleanup(dry_run=True) counts without deleting (the preview endpoint). Each step fails independently and the summary is saved as last_run. When adding a collection that grows, add a policy field, a step in cron._STEPS, and a row in the frontend's features/retention/utils/retentionCategories.js. The orphan-file sweep only touches the APP_FILE_PREFIXES in tigris.py, and it never deletes a file still referenced by a job or a profile resume. If you add a new place that stores file URLs, add it to _referenced_file_keys.

Storage: Tigris (S3-compatible) through app/tigris.py holds resumes and screenshots. Screenshot URLs are presigned only when building responses (_presign_applications_for_response in jobs_common.py). Raw URLs stay in the DB.

LLM / generation (app/util.py): OpenAI calls do job scraping/extraction, resume and cover-letter generation, and Q&A answers. app/form_answers.py answers whole application forms for Auto Apply (POST /applications/answer-form: a field inventory from the auto-apply browser service in, one cleaned answer per field out); it reuses util.client and _record_usage. Before the LLM call, app/job_details_check.py checks the job's title, company, description and salary against the details the browser service read off the posting page (page_job, first call of a run), fixes them in jobs, and sets details_verified so later profiles skip the check; /applications/scrape and /applications/resume unset it. Its upload files come from POST /applications/files: the best matching profile resume (same pick as POST /applications/resume, via _select_profile_resume) plus a cover letter from util.generate_cover_letter. That endpoint is read only, unlike POST /applications, which tailors a new resume and sets the application to autofilled. Token usage is logged to the api_usage collection with a sync pymongo client (_get_sync_db). PDFs are rendered here too.

Auto Apply (app/auto_apply_*.py, routers_auto_apply.py): admins set a start time and title keywords at /auto-apply/start. An hourly APScheduler job (auto_apply_scheduler.register, called from cron.start_scheduler) runs auto_apply_sync.run_all. For each enabled admin it: 1. finds jobs created after cursor_at whose title matches (auto_apply_filter) 1a. drops jobs from companies the admin applied to or already has queued, and keeps one job per company (app/company_dedup/: normalize strips legal forms/accents/punctuation, match runs RapidFuzz on the keys with guards so ABC Ltd vs ABC Holdings is only POSSIBLE, select.pick_best takes the oldest for now). The rest stay unassigned. Applied companies are compared by applied_companies.name_norm (normalize_company(name), set on every write, read by get_applied_company_norms, which normalizes rows that lack it); scripts/normalize_applied_companies.py backfills it. Each fetch is logged as one auto_apply_dedup_runs document (company_dedup/run_log.py): every fetched job's title, company, outcome (kept/applied/duplicate/not_assigned) and reason, served by GET /auto-apply/dedup-runs[/{id}] to the dashboard's Auto Apply Monitor. Logs live 24 hours (TTL index on ran_at, not the retention policy). 2. assigns the kept ones to the admin themselves (auto_apply_assign.assign_to_self: assignee_id = the admin, with no ledger or payment rows) 3. records them in auto_apply_jobs 4. POSTs every still-queued id to the browser service (auto_apply_dispatch, AUTO_APPLY_URL) with an admin token it mints (AUTO_APPLY_TOKEN_MINUTES)

The service reports back through POST /auto-apply/jobs/{id}/result, and applied/expired results mark the admin's own application. A failed result carries the run's log lines, stored on the row (trimmed to LOG_MAX_LINES) and served by GET /auto-apply/jobs/{id}/log. POST /auto-apply/jobs/{id}/retry puts one failed job back to queued and sends just that id to the service (restoring the row if the service is unreachable). POST /jobs/assign and /jobs/unassign remove a job from the admin's Auto Apply list, and handing the admin's own assignment to a bidder writes no "unassigned" ledger event. POST /applications keeps the existing assignee_id when it rewrites an application. auto_apply_jobs has no retention step yet; GET /auto-apply/jobs drops rows whose job is gone.

Resume matching (app/resumeSelector/): picks the best of an admin's resumes for a job, using spaCy skill extraction, a canonical skill graph, and MiniLM embeddings. registry.py loads models lazily on first use (there's deliberately no warmup at boot, to keep idle RAM low on Railway) and caches a selector per admin, keyed by a hash of the resumes. Call invalidate_admin when an admin's resumes change. When RESUME_MATCHING_ENABLED=false it raises ResumeMatchingUnavailable, and callers fall back to the preferred title or the first resume. The model is looked up in app/resumeSelector/models/ or app/models/.