Skip to content

Copy of CLAUDE.md from aetherion-autoapply

Generated from aetherion-autoapply/CLAUDE.md at commit 89a92b10. Edit the source file, not this copy.

CLAUDE.md

Explore in graph

The Auto Apply browser service: a FastAPI + Playwright service (this repo, src/aetherion_web/) that applies to jobs in a server-side browser for admins. It has no UI of its own. Admins use the dashboard's Auto Apply page (../frontend/src/features/auto-apply/), and ../backend (smart_apply_backend) fills the queue every hour. It talks to smart_apply_backend over HTTP. (It used to be the bidder web app with its own frontend/; that was removed.)

Commands

# from the repo root (browser service, FastAPI + Playwright, :8100; deps managed by uv, locked in uv.lock)
uv sync                                           # create/update .venv from uv.lock
uv add <pkg>                                      # add a dependency (updates pyproject.toml + uv.lock)
uv run python -m aetherion_web                    # serve (reads .env)
uv run python -m aetherion_web --self-test        # can this machine drive Chromium?
uv run python -m unittest discover tests          # stdlib unittest, not pytest
uv run python -m unittest tests.test_api          # one module
uv run ruff check src tests                       # lint (config in pyproject.toml; CI runs it)

docker compose up --build                         # the service, from the repo root

Layout

src/aetherion_web/
  main.py            create_app(): builds the Services container, mounts routes
  config.py          Settings from env / .env
  auth.py            bearer token -> admin (via upstream /auth/me, cached; ALLOWED_ROLES)
  util.py            tiny shared helpers (first_line)
  routes/            HTTP + WS surface, one module per area (health, session, queue, live)
    deps.py          Services container, Svc / Admin dependencies, open_session()
  upstream/          client for smart_apply_backend (client.py) + typed payloads (models.py)
  browser/           one Playwright browser per admin
    events.py        live-view protocol: states, HUMAN_STATES, Subscriber, idle_snapshot
    session.py       BrowserSession lifecycle (begin/stop/close, generation counter)
    manager.py       all sessions and Auto Apply queues, slot cap, idle reaper
    screencast.py, netguard.py, setup.py
  automation/        auto-apply (the "Apply Orchestrator")
    applier.py       run_application: the page loop (read, answer, fill, Next/Submit, review gate)
    context.py       ApplyContext: what a run gets from the session (emitters, token, approval wait, unattended)
    queue.py         JobQueue: the admin's Auto Apply queue (run jobs one by one, report results)
    steps.py         one page: answers -> fill -> read back; bidder edits; upload files; saved record
    answers.py       Answer/Problem, pre-fill validation of LLM answers
    fill/            filler (base.GenericFiller + per-ATS deltas) and verify.py (post-fill read-back)
    navigate.py      find the Next or Submit button
    submit.py        click Submit, collect signals, classify (success/failed/email_verification/unknown)
    extract/         form inventory (shared scan, normalizer, per-ATS deltas)

Where new code goes: - A new browser-service endpoint: a module in routes/ (or the matching one), registered in routes/__init__.py. Get dependencies through Svc/Admin, not globals. Request bodies are Pydantic models next to the route. The dashboard calls it from ../frontend/src/features/auto-apply/api/browserApi.js. - A new smart_apply_backend call: a method on upstream.Upstream. - A new live-view event: browser/events.py (docstring + emitter in session.py) and liveReducer in ../frontend/src/features/auto-apply/live/liveState.js, with a test on each side. - A queue change (ordering, retries, priorities): automation/queue.py and tests/test_queue.py. What gets queued is decided in ../backend/app/auto_apply_*.py. - An ATS-specific fix: extraction follows .claude/rules/ats-extractor-delta.md, filling follows .claude/rules/ats-filler-delta.md. Prefer a shared fix in both.

Architecture

  • Who calls what.
  • smart_apply_backend's hourly sync (app/auto_apply_sync.py) finds matching jobs, assigns them to the admin, and calls POST /queue {job_ids} here with a short-lived admin token it mints (app/auto_apply_dispatch.py). It calls every hour even with nothing new, so the queue always has a fresh token, and it re-sends jobs still queued (which covers a restart here).
  • The dashboard's Auto Apply page reads GET /queue and the live view (/ws) with the admin's own token. Everything else on that page goes to smart_apply_backend.
  • The browser service forwards the admin's bearer token to smart_apply_backend. It never stores tokens on disk (the queue and the running job keep the latest one in memory).
  • Auto-apply's LLM call lives in smart_apply_backend (POST /applications/answer-form: inventory in, one answer per field out). The upload files come from its POST /applications/files: a resume picked from the admin profile's resumes and an LLM cover letter. It doesn't touch the application. This service holds no LLM keys.
  • Results go to POST /auto-apply/jobs/{id}/result {outcome: queued|running|applied|failed|expired, reason, screenshot, log} (Upstream.report_result). A failure carries the job's log (BrowserSession.log_lines(): timestamped _log lines plus the traceback of any error), which the dashboard shows when the admin clicks the Failed tag. A retry from the dashboard arrives as a normal POST /queue with one id. For applied/expired, smart_apply_backend marks the admin's own application. Never call POST /jobs/{id}/apply or PUT /jobs/{id}/application-status from here.
  • Browser service auth (src/aetherion_web/auth.py). It checks the token with GET /auth/me, cached for 60 s, and accepts admins only (ALLOWED_ROLES). The WebSocket can't send headers, so its first message is {"type":"auth","token":...}. Close codes are 4401 and 4403.
  • Starting a job takes a job_id, never a URL. The service loads the job with GET /jobs/{id} using the admin's token.
  • Sessions (browser/session.py, browser/manager.py).
  • There is one BrowserSession per admin and one persistent profile (DATA_DIR/profiles/<user id>), reused across jobs, with a new tab per job. If the profile is locked, a throwaway context is used instead.
  • Everything runs on uvicorn's single event loop. There are no threads.
  • Sessions are in memory, so the service runs as one process.
  • begin() bumps a generation counter, and setup runs under a lock. Only the run_application phase is ever cancelled, because cancelling a launch midway leaks a browser. Check the generation before emitting anything job-specific.
  • MAX_SESSIONS caps open browsers. The reaper closes sessions nobody watches after SESSION_IDLE_SECONDS, except while that admin's queue is working.
  • BrowserSession.run(job, token, unattended=True) starts a job and waits for its (outcome, reason). The completion future resolves however the run ends (finished, error, launch failure, stop, replaced), so the queue never hangs.
  • Live view protocol. JSON events go out (snapshot first, then state, url, log, inventory, answers, phase, human, finished), plus binary JPEG frames from CDP Page.startScreencast (browser/screencast.py, which follows new tabs and popups). Subscriber keeps only the newest frame, so slow clients skip frames. The live view can be scrolled but is otherwise read-only: the mouse wheel sends {"type":"input","kind":"wheel",x,y,dx,dy} (position as 0..1 fractions of the frame), which browser/remote_input.py turns into a CDP mouseWheel on the screencast's page (Screencast.send_input); every other input is dropped. The dashboard side is ../frontend/src/features/auto-apply/live/ (remoteInput.js, LiveView.jsx), enabled only while a job is running. The protocol is defined in browser/events.py. The dashboard mirrors the session in live/liveState.js (a pure reducer, keep it in sync with events.py and session.py).
  • Private-network guard (browser/netguard.py). Unless ALLOW_PRIVATE_NETWORKS=1, every context request to a non-public address is aborted, and service workers are blocked. Keep it on in production. Tests that serve pages from 127.0.0.1 turn it off.
  • Hand-offs and security checks. human events carry a reason from events.HUMAN_STATES: bot_check, needs_input, email_verification, submit_failed, submit_unconfirmed. On a "verify you are human" page, registry.extract_inventory waits up to 20 s, then reports page_state="bot_check". The dashboard's live panel shows the reason. An unattended run never waits on one: it ends and the job is reported failed with the text from applier.FAILURE_REASONS. Add new hand-off reasons to events.HUMAN_STATES, applier.FAILURE_REASONS and the dashboard's features/auto-apply/live/humanReasons.js together (HumanStatesInSyncTest checks). Don't add stealth or captcha-solving code.
  • Auto-apply (automation/applier.run_application(page, ctx)) runs after the screencast starts.
  • Per page, up to MAX_FORM_STEPS: extract the inventory, get answers from answer-form, prefill_validate, fill (fill.select_filler(ats)), postfill_validate. Each page's answers and problems are emitted as answers and saved to DATA_DIR/answers/<job_id>.json (with the submit result).
  • Unattended (ctx.unattended, every job from the queue): nothing waits. "Next" with a flagged answer, an emailed code, a bot check, a rejected or unconfirmed submit, or any other dead end ends the run with outcome None and ctx.failure set (ctx.fail(...)). "Submit" with nothing flagged on any page submits.
  • Attended (a job opened with POST /session/start, only while the queue is idle): "Next": if anything is flagged, wait (needs_input), then click and loop. "Submit": phase review, wait for POST /session/submit unless AUTO_SUBMIT=1 and nothing on any page was flagged. Fields are fixed through POST /session/answers {answers: {ref: value}}, which fills the paused page (steps.apply_edits). The run waits with ctx.wait_for_approval(); Stop or a new job cancels it.
  • Then submit.submit_and_verify. An emailed code (email_verification) is another page.
  • "request_applied"/"request_expired" makes the session emit finished with that outcome; the queue reports applied (with a screenshot) or expired. None is reported failed with the reason. Without a token or upstream (tests) the run only reads the form.
  • Never click a bare "Apply" as submit, and never submit a form with anything flagged. tests/test_orchestrator.py runs the whole loop against a local two-page form with a fake smart_apply.
  • Form extraction (automation/extract/).
  • extract_inventory(page, log) produces the canonical schema (schema.py). It saves to DATA_DIR/inventories/<job_id>.json and goes out as the inventory event (the dashboard joins it with the answers).
  • There is one shared scan (dom_scan.js) and one normalizer, with thin per-ATS deltas for Greenhouse, Lever and Ashby. Follow .claude/rules/ats-extractor-delta.md.
  • tests/test_extract_conformance.py runs every extractor over tests/fixtures/extract/<ats>/. Capture or regenerate fixtures with uv run python -m aetherion_web.automation.extract.capture.
  • Auto Apply queue (automation/queue.py, routes/queue.py). One JobQueue per admin, owned by SessionManager. POST /queue adds ids (ignoring ones already queued or running), keeps the newest token and starts the worker when idle. The worker loads each job, reports running, runs it unattended, and reports the result. The running reply is the last check before applying: when smart_apply answers tracked: false (the job was handed to a bidder or applied by hand meanwhile) or can't be reached, the job is skipped. A run longer than JOB_TIMEOUT_SECONDS (900) is stopped and reported failed. One job's failure (including a failed report) never stops the queue. No free browser slot: the job is reported queued again, stays at the front of the queue, and the worker pauses until the next POST /queue. DELETE /queue (Stop on the dashboard) drops pending jobs and reports the current one queued; ids sent while it stops start a new round afterwards. POST /queue/drop {job_ids} (smart_apply calls it when the admin assigns or unassigns a queued job) forgets those ids and stops the current one if it is among them, reporting nothing for it. The queue is in memory; smart_apply_backend re-sends queued jobs every hour.
  • Config. Settings are env-driven (.env.example, config.Settings). CORS_ORIGINS must include the dashboard's origin. The dashboard finds this service through VITE_BROWSER_API_BASE, and smart_apply_backend through AUTO_APPLY_URL.