Skip to content

Phase 0→27: Complete job-search platform with auth, analysis, and APIs - #1

Merged
Rebell-Leader merged 30 commits into
mainfrom
claude/elegant-knuth-aI7NB
Jun 6, 2026
Merged

Rebell-Leader merged 30 commits into
mainfrom
claude/elegant-knuth-aI7NB

Conversation

@Rebell-Leader

Copy link
Copy Markdown
Owner

Summary

This is a comprehensive rewrite transforming the codebase from a proof-of-concept demo into a production-ready job-search analysis platform. The changes span database schema, authentication, background processing, REST APIs, Telegram integration, and a Chrome extension—organized across 27 development phases.

Key Changes

Database & Persistence

  • Added SQLAlchemy ORM models (db/models.py) with 657 lines covering users, applications, stages, artifacts, projects, CVs, and audit logs
  • Implemented Alembic migrations for schema versioning (13 migration files)
  • Session factory with SQLite default and PostgreSQL support (db/session.py)

Authentication & Security

  • Email/password auth with bcrypt hashing (services/auth.py)
  • TOTP-based 2FA setup and verification (services/totp.py)
  • OAuth 2.0 for Google/GitHub login (services/oauth.py)
  • API token management with bcrypt-hashed storage (services/api_tokens.py)
  • Rate limiting with pluggable backend (services/rate_limit.py)
  • Security headers middleware for FastAPI (api/security.py)

Job Application Tracking

  • Application persistence with status/stage tracking (services/applications.py, services/stages.py)
  • Master CV management with revision history (services/master_cv.py)
  • Project gallery for tailored CV selection (services/projects.py)
  • Tailored CV/cover letter generation with no-fabrication constraints (services/tailoring.py)
  • Constraint checking to verify generated artifacts don't invent facts (services/constraint_check.py)
  • Soft suggestions for constraint violations (services/suggestions.py)

Analysis & Reporting

  • Refactored agent orchestration (agents/orchestrator.py) with concurrent execution
  • Job posting extraction tools (tools/job_tools.py) with JSON fallback to regex
  • Company research tools (tools/company_tools.py) with honest data-source handling
  • Salary/COL estimation tools (tools/salary_tools.py) with "ESTIMATE" prefixes
  • Resume ingestion and ATS keyword matching (tools/resume_tools.py)
  • Per-user analytics (overview, funnel, time-in-stage) (services/analytics.py)
  • Timeline data for charting (services/timeline.py)

Bulk Import & Export

  • CSV + LLM-based bulk import for projects and applications (services/bulk_import.py)
  • PDF export for tailored CVs/cover letters (services/pdf_export.py)
  • Diff utility for revision history (utils/diff.py)

Background Processing & Notifications

  • Celery integration for async analysis (services/background_analysis.py, worker/tasks.py)
  • Pipeline checkpointing for resumable analysis (services/checkpoint.py)
  • Inactivity reminders with configurable thresholds (services/reminders.py)
  • Email delivery via SMTP (services/email.py)
  • Telegram bot integration with account linking (bot/handlers.py, bot/main.py, services/telegram_link.py)
  • Outbound webhooks with HMAC signing (services/webhooks.py)

REST API & Web Services

  • FastAPI app factory (api/main.py)
  • REST endpoints for auth, applications, CV, projects, analysis (api/routes.py)
  • Bearer token authentication dependency (api/auth.py)

Observability

  • Structured logging setup (utils/logging_setup.py)
  • Metrics collection and timing (utils/metrics.py, utils/timing.py)
  • Audit event recording and retrieval (services/audit.py)
  • Worker metrics dumping (worker/metrics_dump.py)

Chrome Extension

  • Manifest v3 extension for one-click job posting analysis
  • Pure JS helpers for extraction and request building (chrome-extension/extract.js)
  • Popup UI and content script integration

Testing & Deployment

  • 27 phase-specific unit test files covering auth, analysis, bulk import, 2FA, webhooks, OAuth, etc.
  • End-to-end

https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd

claude added 30 commits June 6, 2026 09:50
The previous prototype always returned canned "TechCorp Inc." output:
utils/llm.get_completion never actually called the API, and the demo-mode
badge keyed off OPENAI_API_KEY while the client used FEATHERLESS_API_KEY,
so users could see "Production Mode" with 100% fabricated results.

This change makes the foundation real:
- Provider-agnostic LLM client (Anthropic / OpenAI / Featherless), auto-
  detected from whichever API key is present, overridable via LLM_PROVIDER.
  Logical "fast"/"detailed" tiers resolve to per-provider models.
- Real API calls with retries + exponential backoff. No silent fabrication
  on failure — errors surface to the caller.
- Demo mode is driven by the same detection the LLM layer uses, so the UI
  badge can no longer disagree with what's actually happening.
- Removed the fabricated-employee-reviews tool; replaced with an inference
  briefing that labels itself and points users at real sources to check.
- Layoffs/news stubs now return explicit "NOT AVAILABLE" sentinels so the
  downstream LLM can't treat absence as good news.
- Salary/COL heuristics kept but labelled as ESTIMATE end-to-end.
- Orchestrator state schema fixed (job_posting was being smuggled in).
- Thread-safe cache (Streamlit reruns concurrently).
- Added .env.example, demo-mode end-to-end smoke test, dropped unused
  twilio dep, added anthropic.
- Prompt-injection defense (utils/security.py): sanitize untrusted job text
  and company names (strip control chars, neutralize fence spoofing, cap
  length) and wrap them as inert, clearly-delimited data in every prompt that
  embeds attacker-controlled input (job extraction, requirements, company
  stability/culture).
- Pluggable external data (tools/data_sources.py): real company news via
  NEWS_API_KEY (newsapi.org) and optional layoffs via LAYOFFS_DATASET_URL,
  each degrading to an explicit "NOT AVAILABLE" sentinel when unconfigured so
  the model never reads absence as good news.
- Concurrency: company and salary stages now run in a thread pool (real
  wall-clock parallelism for the two LLM-bound calls); progress callbacks fire
  on the main thread to keep Streamlit updates single-threaded.
- Tests: security sanitization/wrapping + news formatting + honest-fallback
  behavior. Full suite (7 tests) green; demo e2e still passes.
- Resume / ATS analysis (tools/resume_tools.py + agents/resume_analyzer.py):
  parse PDF/DOCX/TXT uploads, compute a deterministic keyword-match score
  against the job's required skills (boundary class includes + and # so C
  doesn't falsely match C# / C++, with sentence-period tolerance), flag ATS
  formatting issues (pipe tables, multi-tab columns, ALL-CAPS body lines,
  length extremes), and ask the LLM for a grounded gap commentary. Stage is
  optional — skipped when no resume is uploaded.
- URL ingest (tools/url_ingest.py): generic requests + BeautifulSoup fetcher
  with timeouts, size cap, user-agent, and honest errors when a page is
  JS-rendered or yields too little text. JS-heavy job boards still require a
  headless scraper; we don't pretend otherwise.
- Structured verdict (utils/verdict.py): the report generator now asks the
  model for a <verdict_json> sidecar with verdict / reasons / confidence;
  parsed deterministically, with a phrase-inference fallback (specific-first
  ordering so "Highly Recommended" isn't eaten by "Recommended"). The UI
  renders it as a Green / Yellow / Red badge above the report.
- App updates: resume file_uploader, optional URL field, verdict badge,
  Resume / ATS expander with metric + matched/missing partition + format
  issues + commentary.
- Orchestrator threads resume_text through state; pipeline order is
  job -> (company || salary) -> resume? -> report.
- Tests: 14 new unit tests (ATS scoring incl. C# boundary, format checks,
  verdict parse + fallback + ordering, URL detect + HTML clean, resume stage
  no-op without upload). Full suite 21/21 green.
- Persistence layer (db/): SQLAlchemy 2.0 declarative models for User and
  Application. SQLite by default at ./data/joboffer.db, drops straight in
  Postgres via DATABASE_URL. Schema init is idempotent (create_all); Alembic
  comes later when fields evolve. Application.analysis_json stores the full
  result blob so the historical view doesn't need a fresh LLM call.
- Auth (services/auth.py): bcrypt password hashing, normalized email keying,
  identical error messages for unknown-user vs wrong-password (no
  enumeration leak). Configurable min password length.
- Application tracking (services/applications.py): save_analysis,
  list_applications, get_application, update_status, delete_application.
  Every read/write checks ownership (user_id) — cross-user access raises.
  _serializable strips callables (progress_callback) so the JSON column
  never chokes on a live result dict.
- UI rewrite (app.py): auth gate (sign in / create account), tabbed layout
  (Analyze a posting / My Applications), Save form with status + notes,
  per-row expander with update + delete + saved report viewer. Last result
  persists in session_state so the post-save rerun doesn't wipe the screen.
- Tests: 15 new in tests/test_phase3_units.py covering email normalization,
  duplicate detection, password verification, no-enumeration error parity,
  bcrypt storage, ownership isolation across all CRUD ops, status validation,
  callable stripping. Full suite 36/36 green.
- Deps: sqlalchemy, bcrypt. .gitignore covers data/. .env.example documents
  DATABASE_URL + Phase 1 data-source keys.
- CI (.github/workflows/tests.yml): full unittest suite runs on push and
  pull_request against Python 3.11 and 3.12. Provider keys forcibly blanked
  in the CI env so the demo-mode smoke test exercises the no-key path
  deterministically.
- Real salary benchmarks via Adzuna (tools/data_sources.fetch_salary_benchmark):
  when ADZUNA_APP_ID and ADZUNA_APP_KEY are set, pulls live posting data,
  computes median + p10/p90 + predicted-share, and routes by country (15+
  locales mapped). The salary prompt now leads with Adzuna data as the
  primary signal and demotes the heuristic table to a cross-check. Degrades
  honestly to labelled-ESTIMATE heuristics when unconfigured.
- Telegram bot (bot/): /start, /help, /analyze <url-or-text>. Handlers split
  from the runtime so they're unit-testable without python-telegram-bot
  installed. Long reports are chunked on paragraph boundaries to fit the
  4096-char Telegram limit. python-telegram-bot is an optional extra
  (pip install -e ".[telegram]") so the rest of the project keeps importing
  in environments that don't need the bot.
- Password reset + change-password (services/auth.py + db/models.py
  PasswordResetToken): bcrypt-hashed one-shot tokens with 1-hour expiry,
  raw token never stored. Identical error messages for unknown-email vs
  bad-token vs expired-token (no enumeration leak). Token delivery left
  pluggable — printed to server logs by default; opt-in
  RESET_TOKEN_SURFACE_IN_UI=1 surfaces it in the UI for self-hosted
  single-operator use only.
- UI (app.py): Forgot Password + Use Reset Token tabs in the auth gate,
  Change Password expander in the authenticated sidebar.
- Tests: 23 new in tests/test_phase4_units.py — change-password happy +
  wrong-current + min-length; reset request known-vs-unknown; complete-
  reset happy + one-shot + expired + wrong-token; token-hash-not-raw;
  Adzuna summary math + no-salaries + country routing; Telegram arg
  parsing (url/url+text/text-only), paragraph-aware chunking, verdict
  formatting, error formatting, empty-input help, analyze handler with
  mocked run_analysis. Full suite 59/59 green.
- Cost-of-living dataset (tools/data_sources.fetch_cost_of_living): real COL
  via configurable COL_DATASET_URL, same pluggable pattern as layoffs.
  Salary prompt now treats COL data as primary when available and demotes
  the heuristic index to a cross-check.
- Salary cache-key bug fix: the cache key now includes which data sources
  contributed (adz/col tags). Previously a heuristic-only result could be
  served back to a user who then configured Adzuna/COL — that stale-data
  path is now closed. Regression-tested.
- Alembic migrations (alembic.ini + migrations/): initial schema migration
  for users + applications, plus a follow-up migration adding
  password_reset_tokens. env.py reads the same DATABASE_URL the runtime
  uses (with the same SQLite fallback). render_as_batch=True keeps SQLite
  ALTERs safe. Runtime init_db respects USE_ALEMBIC=1 to skip create_all
  in migration-managed deployments; defaults to create_all so zero-config
  setups still work. Test runs `alembic upgrade head` against a temp
  SQLite and inspects the resulting schema.
- Application export (services/applications.export_applications_csv /
  _json): CSV with pinned column order so user-side schemas stay stable;
  JSON includes the full analysis_json blob for real backups. User-scoped
  in both directions. Surfaced as two Streamlit download_button widgets at
  the top of My Applications.
- Gitignore fix: the broad *token* rule was eating
  migrations/versions/*password_reset_tokens*.py. Added unignore exceptions
  for tracked code paths so the secret-blocking rule keeps protecting
  stray .token files without swallowing legitimate sources.
- 9 new tests (COL formatting + honest fallback, salary cache invalidation
  + cache hit, CSV header + scoping, JSON full backup + datetime
  serialization, Alembic upgrade produces expected tables). Full suite
  68/68 green.
Browser scraper (tools/browser_scraper.py):
- Headless Playwright rendering for resources whose API is paid/unavailable:
  JS-rendered job boards (LinkedIn-class) and Numbeo cost-of-living.
- Rendering (network/browser) split from parsing (pure functions) so parsers
  are unit-testable offline. Numbeo price parser handles both US (1,234.56)
  and EU (1.234,56) number formats.
- Optional [browser] extra; disabled unless BROWSER_SCRAPER_ENABLED=1.
- Wired as automatic fallbacks: url_ingest falls back to browser render when a
  plain GET yields a JS shell; data_sources.fetch_cost_of_living falls back to
  Numbeo scraping when no COL_DATASET_URL match.

Async job queue (worker/, services/analysis_runner.py):
- Celery + Redis ([worker] extra). analysis_runner.submit() enqueues when
  CELERY_BROKER_URL is set, else runs in-process. Interactive Streamlit flow
  stays synchronous for live progress.
- Import-cycle-safe Celery factory: tasks registered via include=, not an
  eager import; module-level app exposed for `celery -A worker.celery_app:app`.

Email (services/email.py, services/notifications.py):
- SMTP password-reset delivery; best-effort (logs + returns False when
  unconfigured so a missing mail server never breaks the reset flow). Pure
  MIME builder for testability. Renders a full link when APP_BASE_URL is set,
  else the raw token. Wired into the forgot-password flow.

Docker:
- Dockerfile (python:3.12-slim, installs .[telegram]) and docker-compose.yml
  bringing up web + worker + redis + postgres; bot behind a profile. App
  container runs `alembic upgrade head` before serving (USE_ALEMBIC=1).
- .dockerignore excludes data/, .env, tests, assets.

Validation under the sandbox host allowlist: external hosts return proxy 403,
so connection code was verified to attempt real requests and degrade
gracefully (Adzuna country routing confirmed in the request URL), and parsing
was verified against real-shaped HTML/JSON fixtures. 85/85 tests green.
Rate limiting (services/rate_limit.py):
- Sliding-window limiter, thread-safe in-memory backend by default; Redis
  backend auto-selected when REDIS_URL (or CELERY_BROKER_URL) is set.
- Pre-wired limiters: login (10/5min, reset on success so legit users aren't
  punished for old typos), register (5/hour), reset-request (5/hour),
  analysis (30/hour, per user_id). All env-tunable via RL_*_MAX / RL_*_WINDOW.
- RateLimitExceeded carries retry_after with a human-readable message.

Telegram bot async-queue integration (bot/handlers.py):
- When a Celery broker is configured, the bot enqueues + polls off the asyncio
  loop (asyncio.to_thread), so other commands stay responsive while a long
  analysis runs in the worker. Falls back to in-thread sync execution when no
  queue is available. Timeout and FAILURE/REVOKED state reporting included.

UI/UX overhaul (the user-facing changes that matter):
- Required-field trap fixed: Company/Title/Location are now optional on the
  form. They auto-populate from extracted_details before Save, so users who
  paste a URL or full description aren't forced to type fields the analyzer
  is about to extract anyway.
- Posting input split into "🔗 From URL" / "📝 Paste text" tabs with clearer
  intent than one big form.
- Auth tabs collapsed 4 → 3 by merging Forgot + Reset into a single
  "Recover password" two-step flow.
- Two-step delete in My Applications — first click arms a confirmation,
  second confirms. Eliminates one-click data loss.
- Search + status filter on My Applications. Friendly empty state for new
  accounts (with concrete next-step instructions instead of a blank page).
- Resume ATS expander upgraded: big colored score banner (green/yellow/red),
  matched skills as green ✓ bullets, missing skills as red ✗ bullets, count
  metrics. The whole point of the resume feature now pops visually.
- Sign-out moved to the bottom of the sidebar so it's not the second-most-
  clickable button on every page.
- Optional Telegram-bot link surfaced in the sidebar when
  TELEGRAM_BOT_USERNAME is set.
- Rate-limit errors render distinctly from auth errors.

Tests:
- 15 new in tests/test_phase7_units.py (limiter core: budget/isolation/
  window-rolling/reset; auth integration: login lock-out, success resets
  counter, register lock-out, reset-request lock-out; analysis quota: per-
  user isolation, None skips; bot routing: queue-when-available, sync-
  fallback, timeout reporting, FAILURE reporting).
- _fresh_db() in phase 3/4/5 tests now also wipes the rate-limit backend so
  global limiters don't leak counters across test classes.
- Full suite 100/100 green.
Data model:
- New ApplicationStage table (db/models.py) — one row per pipeline event
  (applied, recruiter_screen, phone_screen, technical_interview, take_home,
  onsite, offer_received, offer_accepted) plus terminal events (rejected,
  withdrew, ghosted). Each row carries occurred_on (date), free-text notes,
  at_pipeline_stage (for terminal events: where in the funnel did it end),
  and a JSON extra payload for structured per-stage data (offer comp,
  verbatim feedback, rejection reason).
- Application.status remains as a denormalized cache derived from the
  latest stage via services.stages.derive_status_from_stages, so existing
  filters and badges keep working without re-querying every render.
- Alembic migration c067abb9272c adds the table + indexes.

Services:
- services/stages.py: add_stage, list_stages, delete_stage, latest_stage,
  plus a QUICK_ACTIONS list the UI uses for one-click buttons. All ops are
  ownership-checked (cross-user access raises). add_stage auto-syncs
  Application.status; delete_stage recomputes it (and reverts to "saved"
  when no stages remain).
- services/analytics.py: pure-ish dashboard builder. Computes Overview
  (totals + active + in-interview + offers + rejection rate), Funnel (per
  pipeline stage reached, plus stage-over-stage conversion — zero-reach
  stages are skipped so the chart reflects real signal), TimeInStage
  (averages computed from each app's actual chronological events, not
  fixed adjacent pairs, so apps that skip a stage still contribute),
  VerdictOutcome (does Green/Yellow/Red correlate with reached_offer /
  rejected?), RejectionStageDistribution (where in the funnel rejections
  happen), and weekly volume.

UI (app.py):
- New "📊 Analytics" tab between My Applications and the auth gate.
  Empty state for new users; otherwise overview metric cards, funnel +
  conversion table, time-in-stage chart with sample-size caption,
  verdict-outcome dataframe, rejection-stage chart, weekly-volume line.
- Per-application expander gets a "🪜 Pipeline stages" section:
  chronological timeline with delete buttons, QUICK_ACTIONS one-click
  buttons (9 common transitions), and a detailed add-stage form (date +
  notes + at_pipeline_stage).

Tests (tests/test_phase8_units.py — 18 new):
- Stage CRUD: add/list/delete, unknown-kind rejection, cross-user
  isolation on add/list/delete.
- Status sync: applied -> applied, technical -> interviewing,
  offer_received -> offer, rejected -> rejected; latest-by-date not by
  insert order; delete-revert to previous status or "saved".
- Default occurred_on = today.
- Analytics on a 4-app fixture: overview counts incl. rejection_rate,
  funnel counts + conversion rates, time-in-stage per pair with samples,
  verdict outcomes (Highly Recommended -> 100% offer rate), rejection
  stage distribution.
- Empty-state for a brand-new user.
- Cross-user analytics isolation.
- Alembic upgrade head includes application_stages.

Full suite 118/118 green.
Data model:
- MasterCV (one per user; user_id unique). raw_text is the source of truth;
  optional structured projection (Summary/Skills/Experience/Education/
  Certifications) populated on demand by an LLM parse. Tailoring reads
  raw_text directly so a parse step can never drop a fact silently.
- Project (many per user). title/role/tech_stack/summary/highlights[]/url.
  Highlights is JSON so per-bullet metrics can be added without a schema
  change later.
- ApplicationArtifact (versioned per application). kind ∈ {tailored_cv,
  cover_letter}; multiple revisions accumulate so iteration doesn't lose
  history. Newest-first listing.
- Alembic migration 83518f3daa22.

Services:
- services/master_cv.py: get/save/delete, save_master_cv_from_upload (reuses
  the existing PDF/DOCX/TXT parser), parse_master_cv (optional LLM-derived
  structured projection persisted alongside raw_text). save_master_cv keeps
  the previous structured projection when only the text changes; pass an
  explicit empty dict to clear it.
- services/projects.py: create/list/update/delete with ownership checks;
  projects_as_text renderer prepares the gallery for tailoring prompts.
- services/tailoring.py: generate_tailored_cv and generate_cover_letter,
  each wrapping the user's data with utils.security.wrap_untrusted and
  building a prompt that includes NO_FABRICATION_RULES verbatim. The rules
  enumerate exactly what the LLM may do (rephrase/reorder/select/emphasize)
  and what it must not (invent skills, employers, dates, degrees,
  quantitative claims, projects). Adjacent-experience framing is allowed;
  pretending is not. Job context (extracted company/title/required skills
  from the saved analysis) is included so the tailoring is actually
  job-specific. Generations are persisted as ApplicationArtifact rows;
  persist=False supports preview without saving.

UI (app.py):
- New top-level "📝 CV & Projects" tab with Master CV + Project gallery
  sub-tabs. Upload (PDF/DOCX/TXT) or paste/edit; optional "Parse into
  structured sections" button; two-step delete for both master CV and each
  project.
- Per-application expander gets a "🎯 Tailored artifacts" section: gate
  with a helpful hint when no master CV exists, two generate buttons,
  in-place preview of each saved artifact, markdown download, two-step
  delete.

Tests (tests/test_phase9_units.py — 22 new):
- Master CV: save/get/delete, empty rejected, structured-preservation on
  text-only updates (and explicit-clear), one-CV-per-user invariant,
  parse_master_cv (LLM-mocked) round-trip + invalid-JSON failure +
  wrap_untrusted in the prompt.
- Projects: create/list/update/delete, empty-title rejected, ownership
  isolation across read/update/delete, projects_as_text rendering, empty
  gallery sentinel.
- Tailoring (the part that matters): missing-CV guard, NO_FABRICATION_RULES
  text presence in BOTH tailored-CV and cover-letter prompts (asserts each
  critical phrase individually), job context propagation into the prompt
  (company, title, required skills), wrap_untrusted on user-supplied
  content, artifact persistence + newest-first history, full cross-user
  ownership isolation across generate/list/delete, preview-mode (persist=
  False) returns an unpersisted record.
- Alembic upgrade creates master_cvs, projects, application_artifacts.

Full suite 140/140 green.
The Phase 9 no-fabrication rules were a HOPE — words in the prompt asking
the LLM to stay inside the sources. This phase turns that into a deterministic
post-check that runs on every generation and surfaces specifically what (if
anything) might be fabricated.

services/constraint_check.py:
- Extracts skill-shaped tokens, 4-digit years, percentages, and quantitative
  claims ("10M users", "3x growth", "$50M ARR") from any text.
- check_tailored_output compares the tailored output against the union of
  master CV + project gallery + job context (the last one is important so
  echoing the target company / required skill back into the tailored output
  doesn't trip the check). Returns ConstraintCheck with severity in
  {"clean", "review_recommended"} and per-category flags.
- Regex anchors use lookbehind/lookahead instead of \b — \b doesn't fire after
  non-word chars like + or %, which silently dropped "C++", "C#", and "40%"
  from extraction. Trailing sentence punctuation stripped so "Python." matches
  "Python".
- Multi-word phrase matching deliberately removed. It falsely flagged
  routine title text ("Staff ML") because the phrase didn't appear verbatim
  in the master CV even though both component words did. Single-word
  extraction still catches genuine invented skills like "TensorFlow" or
  "Apache Spark" (both components flagged).

services/tailoring.py:
- generate_tailored_cv and generate_cover_letter now run the check
  automatically and persist the result on artifact.meta.constraint_check.
- recheck_artifact re-runs the check against the CURRENT master CV +
  projects. Useful after a user edits their master CV to add a skill that
  was previously flagged — the existing artifact clears without
  regeneration. Ownership-checked.
- COVER_LETTER_TONES tuple (professional, warm, direct, enthusiastic,
  concise) for the UI tone selector.

UI (app.py):
- Each saved artifact shows a ✅/⚠️ badge in its expander header.
- Clean artifacts get a green confirmation; flagged ones get the detector's
  summary, the specific terms / years / percentages, and a one-line caption
  about false positives + the Re-check workflow.
- Per-application cover-letter tone selectbox (persists in session_state).
- Re-check button alongside delete + download.

Tests (tests/test_phase10_units.py — 22 new):
- Token extraction primitives (punctuated skills C++/C#/Node.js, percentages
  including decimals, year extraction, quantitative-claim patterns).
- Stopword filtering (section headers don't trigger flags).
- check_tailored_output across scenarios: clean, invented skill, invented
  year, invented percentage, job-context whitelisting (target company /
  required skills echoed in tailored output do NOT flag), serialization
  round-trip, None handling.
- Tailoring integration: auto-check on clean output (severity=clean,
  total_flags=0), auto-check on fabricated output (TensorFlow + Apache Spark
  flagged), tone propagation into the cover-letter prompt + meta.
- Re-check after master CV update: previously-flagged "tensorflow" clears
  to "clean" without regeneration; meta is persisted.
- Re-check ownership isolation.

End-to-end smoke run confirms all three real scenarios (well-behaved LLM
→ clean; LLM hallucinates TensorFlow/Apache Spark/Kafka/2017/87% → all
caught; user updates master CV honestly → re-check clears all flags).

Full suite 162/162 green.
Closes the loop on Phase 10: the checker no longer just flags problems, it
offers concrete fixes — and every CV change is reversible.

services/suggestions.py (soft suggestions):
- build_suggestions(ConstraintCheck) -> [Suggestion]. Each suggestion carries
  a title, an explanation, and an auto_appliable flag.
- Only skill flags are auto-appliable. Years / percentages / quantitative
  claims are deliberately NOT one-click: appending "2018" or "87%" to the CV
  without a real anchoring event would invite the exact fabrication the
  checker exists to prevent. The UI nudges the user to verify and edit
  manually for those.
- Every skill suggestion's explanation explicitly warns "only do this if
  you genuinely have this experience" — tested.
- apply_skill_addition appends to a dedicated, in-app-managed section
  ("Additional skills (added in-app):") so we never trample the user's
  hand-written Skills line. Case-folded dedup makes re-applying the same
  skill a no-op. The save is tagged reason="added skill: X".

services/master_cv.py (revision history):
- New MasterCVRevision table snapshots the prior content on every
  content-changing save. Pure-metadata calls (re-parse that returns the same
  structured payload, no-op text save) do NOT create a snapshot — verified.
- save_master_cv takes an optional reason tag stored on the snapshot
  (manual edit / parsed / added skill: X / before restore of #N).
- list_revisions returns newest-first.
- restore_revision promotes a revision to the active CV and FIRST snapshots
  the current version under reason="before restore of #N" so the restore
  itself is undoable.
- delete_revision lets users prune history. All three ownership-checked.
- Migration a3b401ffdd58 adds the table + indexes.

UI (app.py):
- Per-artifact constraint-warning block now embeds a "Suggested fixes"
  sub-expander. Skill suggestions get an "Add ✓" button that performs
  apply_skill_addition + recheck_artifact in one click. Non-auto suggestions
  render explanation-only.
- Master CV section gets a "Revision history" expander with reason tag,
  byte count, content preview, two-step Restore, and Delete per row.

Tests (tests/test_phase11_units.py — 21 new):
- Suggestion building: skill flags produce auto-appliable suggestions;
  years/percentages/quant claims do NOT (the whole point); explanations
  contain a "genuinely/actually" warning; empty check yields no suggestions.
- apply_skill_addition: appends to dedicated section; idempotent across
  case differences; multiple additions accumulate under one header;
  rejects empty input; raises when no master CV exists; end-to-end clears
  the constraint flag (checker re-run goes from flagged to clean).
- Revisions: first save creates no snapshot; overwrite snapshots; SAME
  content twice doesn't snapshot (no balloon); reason tag persists;
  newest-first ordering; restore promotes content AND snapshots current
  under "before restore of #N"; restore/delete cross-user blocked;
  apply_skill_addition implicitly creates a revision tagged with the skill.
- Migration adds master_cv_revisions on upgrade head.

Full suite 183/183 green.
services/pdf_export.py: pure-Python markdown -> PDF via fpdf2 (optional [pdf]
extra). Renders the deliberately small markdown subset our tailoring prompts
produce: # / ## / ### / #### / ##### headings, - / * bullets, paragraphs,
horizontal rules. Non-Latin-1 characters (em dash, smart quotes, ellipsis,
bullet glyphs, checkmark/cross emoji) get mapped to plain ASCII so the
built-in Helvetica core font can render them.

UI: each artifact now offers parallel ".md" and ".pdf" download buttons.
Missing-fpdf2 surfaces as a disabled caption rather than a crash.

Hard-won implementation notes (preserved as code comments so the next person
to touch this doesn't have to rediscover them):

  * fpdf2 2.7+ leaves the cursor at the RIGHT margin of the last rendered
    line after multi_cell(0, ...). The next multi_cell(0, ...) then computes
    available width = (page_width - r_margin - x) = 0 and raises "Not enough
    horizontal space to render a single character". We now explicitly
    pdf.set_x(pdf.l_margin) at the top of every line iteration.
  * Mixing pdf.write() (for inline bold) and pdf.multi_cell() leaves the
    cursor in inconsistent states across fpdf2 versions. We dropped inline
    **bold** rendering — strip the markers and render as plain via a single
    multi_cell. Visual loss is minor; headings still render bold and a
    tailored CV's emphasis comes mostly from those.
  * Bullets prefix "- " into the body text and reuse the inline renderer
    rather than splitting into cell() + multi_cell() — the original split
    triggered the same width=0 crash from a different angle.

Tests (tests/test_phase12_pdf.py — 6 new):
- markdown_to_pdf returns bytes starting with the %PDF- magic header.
- Realistic CV (headings + bold + bullets + em-dash + percentages) renders
  without raising and produces >1KB output.
- Unicode em-dash / smart quotes / unicode bullets don't crash.
- Empty input still produces a valid PDF.
- Heading + inline-bold parsing regexes (_HEADING_RE / _BOLD_RE) verified.
- _ascii_safe mapping table verified.
- markdown_to_pdf raises PDFExportError (not silent fail) when fpdf2 is
  unavailable, with a clear install hint.

End-to-end live verification: rendered a realistic 4-section tailored CV
to PDF, extracted via pypdf, confirmed every line lands in the right order
with bullets intact and em-dashes mapped to '-'. 1.6KB output, valid
PDF-1.3 header.

Full suite 189/189 green.
services/bulk_import.py:
- Two ingest paths per kind. CSV path is deterministic (predictable headers,
  parse-then-validate). Free-form path uses the LLM with the same
  no-fabrication discipline as the tailoring prompts: "Do NOT invent any
  field not present in the input; null where unknown" — wrapped in the
  utils.security.wrap_untrusted helper. Tests assert both phrases stay in
  both prompts.
- Always returns previews; nothing is auto-persisted. The UI shows a
  checkboxed preview list and the user picks which entries land in their
  data.
- save_projects: straight persistence of approved previews.
- save_applications materializes stage events matching each imported
  status (interviewing -> applied + phone_screen, offer -> applied +
  offer_received, rejected -> applied + rejected, withdrawn -> applied +
  withdrew). This fixed a real bug caught during the e2e: previously the
  import added an "applied" stage which auto-synced Application.status
  back to "applied", silently downgrading an imported rejected/offer/
  interviewing record. Tested for each status transition.
- Stage occurred_on uses the imported applied_on for both events when we
  don't have a better date — an honest approximation the user can refine,
  never a fabricated independent date.
- _parse_date accepts a small list of common date formats; unparseable
  values silently become None (imports stay best-effort, not fragile).

UI (app.py):
- Project gallery: "📥 Bulk import projects" expander with CSV and
  Free-form (LLM) tabs, preview-with-checkboxes, save / discard buttons.
- My Applications: "📥 Import past applications" expander at the top of
  the tab so a brand-new user can light up analytics from their history
  before having saved anything in-app.

Tests (tests/test_phase13_bulk_import.py — 18 new):
- Project CSV: basic parse with multi-bullet highlights, rejects missing
  title column, skips empty-title rows, empty input.
- Project free-form (LLM-mocked): clean JSON, code-fence stripping,
  non-JSON rejected, non-array rejected, prompt-carries-no-invention
  constraint + wrap_untrusted.
- save_projects: persists all approved previews.
- Application CSV: basic parse with status normalization, rejects missing
  required columns, unknown status falls back to "applied" (don't reject
  the whole row), multiple date formats incl. unparseable -> None.
- Application free-form: prompt carries the no-invention constraint and
  wrap_untrusted; status normalization on parse.
- save_applications: persists with _imported sentinel; status survives
  auto-sync (the bug we fixed); offer + rejected statuses create the
  correct secondary stage; without applied_on, no stages are created.

End-to-end live verification: imported 4 past applications via CSV; their
statuses (interviewing/offer/rejected/applied) survive auto-sync; the
funnel correctly shows applied=4 -> phone_screen=1 -> offer_received=1;
verdict-outcome correlation shows Recommended apps at 33% offer rate vs
Not Recommended at 0% — the kind of signal that justifies the analyzer.

Full suite 209/209 green.
utils/diff.py — thin wrapper around difflib.unified_diff that:
- splits on lines without losing the final newline (the keepends=True dance
  that difflib needs to avoid "missing line endings" warnings)
- returns "" when identical so callers can truthiness-check
- produces output tagged for ``st.code(diff, language="diff")`` so Streamlit
  syntax-highlights +/- lines

services/master_cv.diff_revision_against_current(user_id, revision_id) wraps
the diff for the common UI question "what changed between this old snapshot
and what I have now?" — ownership-checked, raises when there's no active CV.

UI (app.py):
- Per-revision "🔀 Diff against current" expander in the Revision history.
  Empty diff shows a clear "no textual differences" caption; non-empty
  renders via st.code with language=diff for colour-coded +/- output.
- Master CV "⬇️ Master CV .pdf" button next to Parse + Delete, reusing
  services/pdf_export.markdown_to_pdf. Plain-text master CVs render fine
  (the renderer falls through to multi_cell paragraphs); markdown-ish CVs
  get proper headings.
- Per-application "🆚 Compare two artifacts" toggle in My Applications.
  Picks two artifacts of the same kind, shows them side by side with their
  constraint-check badges + tone, and an optional unified diff between
  the two contents. Only shows when ≥2 artifacts exist; needs ≥2 of the
  selected kind to actually render.

Tests (tests/test_phase14_units.py — 10 new):
- unified_diff: empty when identical, has_differences strips trailing
  whitespace, additions/deletions render on +/- lines with correct labels,
  newlines preserved (the difflib gotcha), handles empty inputs in both
  directions.
- diff_revision_against_current: real diff content, empty after restore-to-
  match-current, cross-user blocked, raises when no active master CV exists.
- Master CV PDF: plain (non-markdown) CV renders, pypdf extracts the
  expected text from the bytes (round-trip integration check).

Full suite 219/219 green.
Closes the two-channel loop: events that happen in the web UI are now
push-notified to the bound Telegram chat. Linking is deliberately user-
initiated (web issues a token, bot consumes it) so the bot can't be tricked
into binding to an arbitrary account.

Schema (migration 3ba1c52f7b93):
- telegram_link_tokens: bcrypt-hashed binding tokens with a 15-min TTL,
  one-shot (used_at watermark). Same security discipline as password reset.
- telegram_links: one row per user (UNIQUE user_id), carries chat_id
  (BigInteger so 64-bit Telegram IDs fit), optional chat_username, and a
  notify_on_stage preference toggle.

services/telegram_link.py:
- issue_binding_token(user_id) - generates token + persists its hash
- complete_binding(chat_id, raw_token, chat_username) - bot side; same
  generic error for invalid/expired/used tokens (no token-validity probing)
- get_link / get_user_id_by_chat / unlink / set_notify_on_stage - normal CRUD
- send_to_chat(chat_id, text) - posts directly to Telegram's HTTP API; no
  shared state with the bot's long-running process. No-ops cleanly when
  TELEGRAM_BOT_TOKEN is unset.
- send_to_user(user_id, text) - one-shot lookup + send

services/notifications.notify_stage_added(user_id, app, stage):
- Glanceable message: stage emoji + label + job title + company + date +
  truncated notes (cap 240 chars). Skips silently when no link, when
  notify_on_stage is False, or when send fails. Never raises into the
  caller's UI flow - the user shouldn't lose their stage save because
  Telegram had a hiccup.

Bot handlers (bot/handlers.py + bot/main.py):
- /bind <token>, /unbind, /me - all run via asyncio.to_thread so the DB
  query doesn't block the event loop while other commands come in.
- Help text + registration in main.py.

UI (app.py):
- Sidebar "📲 Link Telegram" expander: unlinked state shows a "Generate
  binding token" button that emits a copy-pasteable `/bind <token>` block
  valid for 15 min; linked state shows @username (when present),
  notify-on-stage toggle that persists immediately, and Disconnect.
- Stage-add code paths (quick-action buttons + detailed form) now call
  notify_stage_added after a successful add_stage. Best-effort: never
  rolls back the stage save, never surfaces an error.

Test-infrastructure fix:
- reset_engine_for_testing now uses StaticPool. Without it, tests that
  hopped threads via asyncio.to_thread (the bot handler tests) saw a
  fresh empty :memory: SQLite database because each new connection
  gets its own. With StaticPool every connection in the test process
  shares one SQLite connection, so the schema persists across threads.
  This was a latent bug waiting to bite anything else multi-threaded.

Tests (tests/test_phase15_units.py - 28 new):
- Binding: issue + complete creates link; invalid/empty/wrong-user/used/
  expired tokens all rejected; raw token never persisted (bcrypt $2 prefix);
  rebind replaces existing link; chat-id lookup; idempotent unlink;
  notify_on_stage toggle incl. error for unlinked user.
- Send: skips when TELEGRAM_BOT_TOKEN unset (no HTTP call); posts to
  api.telegram.org with chat_id+text+parse_mode payload; returns False on
  HTTP error; send_to_user uses linked chat; returns False for unlinked user.
- notify_stage_added: success path includes emoji + label + title + company +
  notes; skipped when notify disabled; skipped when unlinked; long notes
  truncated with ellipsis; survives send_to_user raising an exception
  without bubbling up (the don't-break-the-UI invariant).
- Bot: /bind with valid token, /bind with no args shows usage, /bind with
  bad token says invalid, /unbind when unlinked is polite, /unbind removes
  existing link, /me reports unlinked vs linked account.
- Alembic head creates both new tables.

End-to-end live verification: web issues a 22-char token, bot accepts /bind,
link persists, save_analysis + add_stage triggers a Telegram message
formatted as "🎯 *Offer received* — Staff ML Engineer @ Stripe / _2026-06-01_
/ Verbal offer: $250k base + equity", /unbind cleanly removes the link.

Full suite 247/247 green.
utils/diff.inline_diff_html(before, after):
- Word-level diff rendered as HTML with green ins-style + red strikethrough
  del-style spans for in-place display.
- Tokenises on word/whitespace boundaries (preserves layout); newlines
  become <br> so the rendered diff matches the original line structure.
- HTML metacharacters in user content are escaped before insertion — verified
  by test that a <script>alert(1)</script> in the source survives as
  &lt;script&gt;alert(1)&lt;/script&gt; in the output (no XSS via diff).
- Whitespace tokens are emitted between styled spans rather than inside them,
  so the colored highlight covers actual words and the diff reads cleanly.

services/timeline.py:
- per_application_timeline(user_id, application_id) - chronological stage
  events for one app, ownership-checked (returns [] for cross-user).
- cross_application_swimlane(user_id) - all the user's apps in one dataset,
  one row per application, for the "swimlane" Altair chart.
- TimelinePoint carries (kind, occurred_on, color, pipeline_index,
  application_label, notes). PIPELINE_STAGES index is preserved on the
  point so charts can sort consistently; non-pipeline stages get -1.
- STAGE_COLORS palette (grey -> blue -> purple -> yellow -> green for the
  positive arc, red for rejected, neutral for withdrew/ghosted), tuned to
  read on both light and dark Streamlit themes.
- points_to_records helper for pandas.DataFrame() consumption.

UI (app.py):
- Per-application "📅 Pipeline timeline" Altair chart inside each saved-app
  expander: dots colored by stage kind, connecting line, Y axis sorted by
  PIPELINE_STAGES order, tooltips show kind + date + notes.
- Analytics tab "All applications — stage timeline" swimlane: one row per
  application, shared X axis, height scales with row count. Useful for
  velocity / drop-off patterns across the whole search.
- Master CV "Diff against current" expander gains an Inline / Unified radio
  toggle. Inline mode renders the word-level diff via st.markdown +
  unsafe_allow_html=True. Unified mode keeps the existing st.code(language=
  "diff") for users who prefer the patch view.
- Per-application A/B compare diff expander gets the same Inline / Unified
  toggle.

Tests (tests/test_phase16_units.py - 15 new):
- inline_diff_html: identical inputs emit no styled spans, insertion gets
  green span, deletion gets red strikethrough span, replacement emits both,
  newlines become <br>, HTML metacharacters escaped (XSS guard).
- Timeline: per_application_timeline chronological order, label format,
  color/index mapping incl. -1 for non-pipeline (ghosted), ownership scoping
  returns []; cross_application_swimlane includes all apps, user-scoped,
  empty for a new user; points_to_records shape.

Full suite 262/262 green.
Resumable pipeline (services/checkpoint.py + agents/orchestrator.py):
- When an LLM call fails mid-pipeline, completed stages get persisted to an
  in-process checkpoint keyed by (user_id, posting, manual_inputs, model,
  resume_text). Retrying the same form skips already-done stages and only
  re-runs the failed/missing ones, so a 502 in the salary stage doesn't
  cost the user another job + company LLM call on retry.
- CheckpointStore is thread-safe + process-local. CHECKPOINT_STAGES tuple
  is the canonical order; completed_stages() returns the slice that's done.
- compute_key normalises cosmetic differences (whitespace, empty fields)
  so the user retyping the same content doesn't bust the cache.
- Each agent runs through a checkpoint-aware wrapper in the orchestrator:
  reads from the checkpoint to short-circuit, writes back on success. The
  company+salary parallel stage checkpoints each branch independently —
  if company succeeds and salary fails, only salary re-runs.
- run_analysis takes an optional checkpoint_key. The UI computes the key
  from the current form state, hands it in, and clears the checkpoint on
  successful end-to-end completion. On failure the UI shows which stages
  were saved and tells the user to "Analyze posting again to resume".

Inactivity reminders (services/reminders.py + worker/reminders.py):
- find_stale_applications(user_id, threshold_days, today=...): returns
  open + idle + non-snoozed applications, sorted by days_idle descending.
  Closed apps (rejected / withdrew / ghosted / offer_accepted) and apps
  with a future snooze_reminders_until are skipped.
- send_inactivity_reminders walks every TelegramLink with
  inactive_reminder_days > 0 and sends one summary message per user.
  Setting the threshold to 0 disables the inactivity ping without losing
  per-stage notifications.
- snooze_application / unsnooze_application / set_inactive_threshold —
  all ownership-checked.
- worker/reminders.py is the CLI entry point for cron / systemd-timer /
  k8s CronJob (`python -m worker.reminders [--user N]`). Exits 0 on quiet
  days so the scheduler doesn't alarm.

Schema (migration bee6851b0338):
- Application.snooze_reminders_until (Date, nullable) — set to a future
  date to mute reminders for one application.
- TelegramLink.inactive_reminder_days (Integer, default 7) — per-user
  threshold; 0 disables inactivity reminders.
- batch_alter_table for SQLite compatibility on both ALTERs.

UI (app.py):
- Per-application "🔕 Snooze reminders" selectbox (7/14/30 days) +
  Unsnooze button in the actions column. Snoozed apps show the until-date.
- Sidebar Telegram-link panel grows an "Inactivity reminder threshold
  (days, 0 = off)" number_input that calls set_inactive_threshold.
- Analyze tab: when the checkpoint already has stages for the current
  form state, the progress area shows "♻ Resuming — stages already
  completed in this session: X, Y" before the spinner starts. On error,
  shows what's saved and how to resume.
- Successful end-to-end run clears the checkpoint so a re-submit doesn't
  serve stale data.

ApplicationRecord grew snooze_reminders_until (exposed for the UI).
LinkRecord grew inactive_reminder_days. Both are read-only projections of
the columns above.

Tests (tests/test_phase17_units.py - 24 new):
- Checkpoint keys: same inputs -> same key, different user -> different key,
  cosmetic whitespace normalised, empty manual fields ignored.
- Store: round-trip, completed_stages in canonical order regardless of
  insertion order, key isolation.
- Orchestrator: completed-stage wrapper short-circuits without calling the
  agent, first run writes to checkpoint, end-to-end partial-failure-then-
  resume invokes the failed stage exactly twice (NOT three times — which
  proves job + company weren't redone on resume).
- Reminders: stale detection excludes recent + rejected + snoozed apps,
  threshold=0 disables, snooze/unsnooze round-trip, format_summary content,
  send_inactivity_reminders happy path + user-targeted, set_inactive_
  threshold persists + requires Telegram link, cross-user snooze blocked.
- CLI: main() invokes send_inactivity_reminders, --user flag is propagated.
- Alembic head adds both new columns.

End-to-end live verification:
1) Resumable pipeline — first run fails at salary; checkpoint contains
   job_details + company_analysis. Resume call only runs salary#2 + report.
2) Inactivity reminders — with 4 apps (3-day, 14-day, 25-day, 40-day-but-
   rejected), threshold=7 correctly flags only Stripe (25d) + Beta (14d),
   sends a formatted Telegram summary skipping the closed Globex.

Full suite 286/286 green.
Five-piece observability stack, designed to be useful before any production
deploy without forcing a Datadog / Prometheus dependency.

utils/logging_setup.py - structured JSON logging:
- LOG_FORMAT=json -> one JSON object per log line {ts, level, logger, msg,
  request_id?, ...extra}. Anything else -> a clean human-readable line
  (default for local dev).
- Contextvar-based request_id, set via request_context(rid) ctxmgr. Threads
  through nested calls without arg passing; the JSON formatter picks it up
  via a logging.Filter on the handler.
- configure() is idempotent — Streamlit reruns and tests can call it
  freely without multiplying handlers. Quiets chatty third-party loggers
  (urllib3, httpx, sqlalchemy.engine.Engine) to >= WARNING.

utils/metrics.py - in-process counters + histograms:
- Counter (name, tags) -> int; Histogram observations bounded to 1000
  samples each (FIFO drop) so a hot path doesn't eat memory at the cost of
  approximate quantiles. Thread-safe via RLock.
- snapshot() -> MetricsSnapshot dataclass with per-series min/p50/p95/p99/
  max derived on demand. render_snapshot_text() for human-readable dumps.
- worker/metrics_dump.py is the CLI (`python -m worker.metrics_dump
  [--json]`) for ad-hoc inspection. JSON output pipes to jq cleanly.

utils/timing.timed_block(name, tags=...) - one context manager that emits:
- one INFO log line on success or ERROR on exception (with op + duration_ms
  + tags as `extra=`),
- one histogram observation (duration_ms),
- one counter for total operations,
- one counter for errors (when the block raised),
- and re-raises the underlying exception.

Wired the timing helper into:
- utils/llm.get_completion - tags={provider, model}. So we now know per-
  provider call counts, error counts, and latency distribution.
- agents/orchestrator - tags={stage}. Each pipeline stage is timed
  independently, including the company/salary parallel pair.

services/audit.py + db.models.AuditEvent (migration f7cd19cbca6e):
- AUDIT_KINDS enum: user.register / login.success / login.failure /
  password.change / password.reset.request / password.reset.complete /
  application.delete / telegram.bind / telegram.unbind / artifact.delete.
- record(kind, user_id, details) appends one row. NEVER raises into the
  caller's flow (logs warning on DB failure). Captures the current
  request_id from logging_setup so audit rows can be cross-referenced
  with the log line that recorded the event.
- list_for_user(user_id) for the sidebar viewer; list_recent() for
  system-wide forensics.
- audit_events table has indexes on user_id, kind, created_at — these are
  the realistic query patterns.

Call sites wired:
- services/auth: register_user, authenticate_user (both success + failure
  branches incl. unknown-email failures which record with user_id=None
  and the attempted email in details), change_password,
  request_password_reset, complete_password_reset.
- services/applications.delete_application — audited AFTER commit so a
  failed delete is not recorded as if it happened.
- services/telegram_link.complete_binding + unlink.
- services/tailoring.delete_artifact.

UI:
- app.py: configure_logging() at module load; "📜 My recent activity"
  sidebar expander showing the user's last 20 audit events.
- bot/main.py + worker/reminders.py: replaced ad-hoc logging.basicConfig
  with configure_logging() so JSON / plain mode is consistent across all
  entry points.

Tests (tests/test_phase18_units.py — 28 new):
- JsonFormatter: basic fields, request_id when set, extra= fields,
  unserialisable fallback to repr.
- request_context: explicit + autogenerated id, cleared on exit, log line
  in scope vs out of scope.
- Metrics: counter accumulation, tag separation, histogram quantile
  correctness (1..100 -> p50≈50, p95≈95), empty + populated snapshot
  rendering.
- timed_block: records duration + count on success; records errors counter
  on exception; reraises the underlying exception unchanged.
- Audit: register / login (success and failure incl. unknown-email) /
  password.change / password.reset.request+complete / application.delete /
  telegram.bind+unbind events all recorded. audit.record never raises on
  DB failure. Unknown kind still written (warning logged, not rejected).
  request_id contextvar persisted on audit row.
- Metrics CLI: text mode + JSON mode.
- Migration: audit_events table created.

End-to-end live verification:
1) JSON log emits with request_id contextvar threaded through nested calls.
2) Auth flow records register + login.failure + login.success in correct
   order with correct details payloads.
3) Three llm.request operations (2 ok + 1 failure) produce 3 timing log
   lines, counter llm.request.count = 3, llm.request.errors = 1, and
   separate histograms tagged with the error type.

Full suite 314/314 green.
Queue long analyses to Celery, walk away, come back later — even from a
different session. Persisted (user, task_id) pairs survive container
restarts, so the result waits for the user instead of the user waiting
for it.

Schema (migration cc044d01b2b9):
- BackgroundAnalysis: user_id (FK, indexed) + task_id (unique) + title +
  state (PENDING/STARTED/SUCCESS/FAILURE/REVOKED) + inputs_summary +
  result_json (cached on SUCCESS) + error_message (cached on FAILURE) +
  timestamps. Task_id is the join key against Celery's result backend.
- BACKGROUND_STATES tuple + BACKGROUND_TERMINAL_STATES set exported from
  db.models so callers can stop polling once a row reaches terminal.

services/background_analysis.py:
- submit_background_analysis(user_id, posting, manual_inputs, model,
  resume_text) — enqueues via analysis_runner.enqueue_analysis + persists
  a tracking row. Returns None when no broker is configured so callers
  fall back to the synchronous path cleanly.
- list_for_user (newest first) / get (cross-user blocked) / delete (cross-
  user blocked) — all ownership-scoped.
- refresh_state(user_id, analysis_id) polls Celery via get_async_result
  and CACHES the terminal state. Already-terminal rows short-circuit
  without hitting the broker (tested: poll asserted NOT called on the
  second refresh of a SUCCESS row).
- refresh_all_pending(user_id) — UI auto-refresh entry point. Skips
  already-terminal rows.
- UNAVAILABLE broker response leaves the row state untouched so a
  temporary infrastructure blip doesn't poison the cache.
- cleanup_terminal_older_than(days) — sweep helper for periodic pruning;
  tested.

UI (app.py):
- @st.fragment(run_every="5s") "🛰 Background analyses" card above the
  Analyze form, shown only when async_enabled. Renders a bordered tile
  per pending/recent analysis with badge (⏳ Pending / 🏃 Running / ✅
  Done / ❌ Failed / 🛑 Cancelled), the inputs summary, the task_id
  prefix, and per-row Open / Delete buttons.
- The fragment auto-refreshes the listing on a 5-second cadence WITHOUT
  rerunning the rest of the page — the user's form stays stable while
  background tasks update.
- "Open" on a SUCCESS row hydrates session_state.last_result and
  session_state.last_inputs from the cached result_json, then triggers
  st.rerun() so the existing render_result() path picks it up — the user
  sees the verdict / sections / artifacts identically to a sync run.
- Analyze form gains a "Run in background" checkbox (only shown when
  async_enabled). Checked + submitted -> submit_background_analysis +
  early-exit with a success message pointing to the card above.

Tests (tests/test_phase19_units.py - 17 new):
- Submit returns None when async disabled; persists row with task_id +
  derived title ("ML Engineer @ Stripe") + inputs_summary; returns None
  when enqueue dispatches no task (defensive: no phantom rows).
- list_for_user newest-first, user-scoped; get + delete cross-user
  blocked; delete removes row.
- refresh_state: PENDING -> polls broker; SUCCESS caches result + sets
  completed_at; SECOND refresh of SUCCESS row does NOT poll (terminal
  short-circuit asserted via mock); FAILURE caches error_message;
  UNAVAILABLE leaves state untouched; cross-user raises.
- refresh_all_pending skips terminal rows (only the still-pending task
  gets polled).
- cleanup_terminal_older_than removes old terminals, leaves fresh ones.
- Alembic head creates background_analyses table.

Full suite 331/331 green.
Web-side setup ceremony + login challenge + backup codes + disable, with
audit + rate-limit hooks. RFC-default TOTP (SHA-1, 30s, 6 digits) with ±1
step skew tolerance via pyotp; QR code for authenticator-app onboarding
via the qrcode library.

Schema (migration fa017c8b7014):
- UserTwoFactor: secret (base32) + verified flag + backup_codes (JSON
  list of bcrypt hashes). Unique (user_id) so we can't end up with
  multiple TOTP rows per user. Documented in-line that secret is stored
  unencrypted by design — TOTP is secondary defence and the primary bcrypt
  password hash remains intact under a DB-only compromise.

services/totp.py:
- start_setup(user_id, account_label) -> SetupResult{secret, provisioning_uri}.
  Rotates the secret if called repeatedly before confirmation (no orphan
  setups). Refuses when 2FA is already verified to force an explicit
  disable() before re-setup.
- confirm_setup(user_id, otp) verifies the live OTP, generates 10
  one-shot backup codes, persists bcrypt-hashed CANONICAL forms, returns
  the formatted XXXXX-XXXXX strings ONCE for user display.
- verify_login(user_id, code) — accepts a 6-digit OTP OR a backup code.
  Normalises input (strip spaces/dashes, upper-case) so the user can
  type the code naturally. Backup codes are consumed on use. Failures
  audited individually so brute-force attempts are visible.
- disable(user_id, current_password) — gated by a password re-check via
  the same bcrypt path as the rest of auth.
- is_enabled / pending_setup / remaining_backup_codes for UI state.
- Rate-limited via services.rate_limit (10/5min default). Success resets
  the counter so a legit user typing the wrong code 3 times still has
  budget after they get it right.

Caught a real bug during testing: backup codes were generated as
XXXXX-XXXXX (with dash) and hashed in that form, but verify_login
normalised user input by stripping the dash before bcrypt comparison —
so they NEVER matched. Fix splits canonical (10 alphanumeric upper-case,
hashed and compared against) from display (XXXXX-XXXXX, shown to user
once). Tests now cover lowercase + extra-space input working.

services/auth.AuthedUser grew a two_factor_required flag. authenticate_user
checks totp.is_enabled after the password phase and returns the flag
set if 2FA is on; audit row carries second_factor_pending=True so the
event log shows the partial state. The UI then prompts for OTP before
fully signing in.

services/audit.AUDIT_KINDS extended with user.2fa.{enable,disable,
verify.success,verify.failure,backup_code.used}.

UI (app.py):
- Login flow: when authenticate_user returns two_factor_required, the
  UI stashes pending_2fa_user_id in session_state and renders an OTP
  form instead of the password form. Cancel returns to password entry.
  Successful OTP verify hands off to the normal logged-in state.
- Sidebar "🔐 Two-factor authentication" expander:
  - Disabled state -> "Start 2FA setup" button shows QR code (via
    qrcode + PIL) + manual secret + a confirm-OTP form. Cancel button
    drops the pending secret cleanly.
  - Just-confirmed state -> shows the 10 plaintext backup codes ONCE
    with a clear warning, plus an "I've saved them — hide" button.
  - Enabled state -> shows remaining-backup-code count + password-gated
    disable form.

Tests (tests/test_phase20_units.py — 24 new):
- Setup: start returns base32 secret + otpauth URI with issuer name;
  start is idempotent before confirm (rotates secret); start after
  enable rejected; confirm with valid OTP enables + returns 10 codes
  with the XXXXX-XXXXX format; confirm with bad OTP doesn't enable;
  confirm without setup rejected; confirm twice rejected; secret
  round-trips through the DB.
- Login challenge: valid OTP succeeds; invalid OTP returns False;
  backup code succeeds AND is consumed (second use fails);
  lowercase/whitespace/extra-dash variants all accepted (the bug fix);
  verify with no setup returns False; rate limit kicks in after 10
  attempts; successful verify resets the limiter.
- Disable: requires current password (wrong password leaves 2FA on);
  correct password disables; disabled user can re-enroll.
- Auth integration: login without 2FA returns no challenge; login with
  2FA enabled returns two_factor_required=True with id+email still set
  so the UI can prompt.
- Audit: enable / verify.failure / backup_code.used all recorded with
  the right details (remaining count for backup-code use).
- Alembic head creates user_two_factor table.

Full suite 355/355 green.
Owner clicks "Share", picks an expiry, optionally bundles tailored
artifacts, gets a URL. Anyone holding that URL sees a read-only view
without an account. Owner sees view counts and can revoke.

Schema (migration 24da269ee301):
- ApplicationShare: application_id + user_id (denormalised for owner-
  scoped queries) + opaque token (UNIQUE, 32-byte url-safe) + optional
  expires_at + revoked_at + include_artifacts toggle + view_count +
  last_viewed_at. Token is stored raw (not hashed) because the only
  thing leaking it can grant is exactly the read access the owner
  intentionally created.

services/sharing.py:
- create_share(user_id, application_id, ttl_days=7, include_artifacts=False)
  -> ShareRecord. ttl_days=None and ttl_days=0 both mean "no expiry"
  (a zero-day TTL would be useless and is almost certainly a UI bug).
- list_shares_for_application + revoke — ownership-scoped, audited.
- get_view(token, viewer_ip=None) — PUBLIC read path. Resolves the
  token, validates not-revoked + not-expired, increments view_count,
  records a "share.view" audit row stamped with the OWNER's user_id so
  the owner sees who accessed when. Raises ShareError with distinct
  messages for unknown / revoked / expired so the recipient gets
  actionable feedback.
- PublicView dataclass returns only what the recipient should see —
  no user_id leak.

UI (app.py):
- BEFORE the auth gate: if ?share=<token> is in the query string, render
  a clean read-only page (verdict badge + title + report + optional
  artifacts) and st.stop(). No login required.
- Per-application "🔗 Share read-only link" expander with: a create
  form (expiry select: 7 days / 30 days / Never, include-artifacts
  checkbox), the generated URL shown in a code block, and the list of
  existing shares with per-row status (active / revoked / expired),
  view counts, and a Revoke button. APP_BASE_URL produces absolute
  links; otherwise the relative ?share=... form is shown.

AUDIT_KINDS extended with share.create / share.revoke / share.view.

Tests (tests/test_phase21_units.py — 19 new):
- Create returns active token with expiry; ttl_days=None and =0 both
  -> no expiry; cross-user blocked; list newest-first; list cross-user
  blocked; revoke marks inactive; revoke cross-user blocked.
- get_view returns application data; include_artifacts surfaces tailored
  artifacts; unknown/revoked/expired tokens rejected with distinct
  messages; empty token rejected; view_count + last_viewed_at update on
  each view; share.view audit row recorded with the OWNER's user_id and
  the viewer IP in details (so a leaked link is auditable from the
  owner's side).
- create + revoke audit rows include share_id + ttl_days details.
- Alembic head creates application_shares.

Full suite 374/374 green.
services/api_tokens.py — token issuance/verification:
- Token format: jos_<32-byte url-safe random>. The 4-char head is a
  product-recognisable prefix; the rest is the secret. NEVER stored raw.
- ApiToken table (migration 1a94fd33628a): user_id + name + indexed
  prefix (first 8 chars of raw token) + bcrypt token_hash + optional
  expires_at/revoked_at + last_used_at + created_at.
- Per-request verify is fast: split incoming token, look up by prefix
  (indexed, ~constant time), bcrypt-compare full token to candidates.
  Prefix-collision odds are ~1/1.4e11 so the iteration cost is
  effectively constant.
- issue / list_for_user / revoke ownership-scoped; revoke ownership-
  checked. verify updates last_used_at and records api_token.used audit.
- ApiTokenError raised for missing name; expired/revoked tokens silently
  return None from verify (the API layer maps that to 401).

api/main.py + api/auth.py + api/routes.py — FastAPI app:
- create_app() configures logging, inits DB, mounts the router. Module-
  level `app` so `uvicorn api.main:app` works directly. `/healthz` is
  open (no auth) for liveness probes.
- require_user FastAPI dependency wraps HTTPBearer, calls verify(),
  returns the user_id. Missing/invalid tokens return 401 with a
  WWW-Authenticate: Bearer challenge.

Endpoints under /v1 (all bearer-authenticated except /healthz):
- GET /me — {user_id, email}.
- POST /analyze — runs the full pipeline; optional save=true persists
  it as an Application (status configurable). On pipeline error, 502
  with the underlying message in `detail`.
- GET /applications, GET /applications/{id}, DELETE /applications/{id}.
  Cross-user reads return 404 (not 403) so we don't leak which IDs
  exist — a deliberate choice to make ownership checks indistinguishable
  from non-existence.
- GET /cv + PUT /cv — round-trip the master CV raw_text. Pydantic
  min_length=1 on PUT rejects empty submissions with 422.
- GET /analytics — the full Dashboard payload as JSON.

UI (app.py) sidebar "🔑 API tokens" expander:
- Create form (name + expiry: 30/90/365 days/Never). On submit, the raw
  token is shown ONCE in a code block with a clear "copy it now" warning.
- List of existing tokens shows prefix + name + status (active/revoked/
  expired) + last_used_at. Active tokens have a Revoke button.

AUDIT_KINDS extended with api_token.{create,revoke,used}.

Tests (tests/test_phase22_units.py — 31 new):
- Token service: issue returns prefixed raw token; raw token NOT
  persisted (bcrypt $2 prefix in DB); empty name rejected; ttl=None ->
  no expiry; list newest-first; revoke marks inactive; cross-user
  revoke blocked; verify resolves user; verify rejects unknown prefix,
  missing-prefix string, empty, revoked, expired; verify updates
  last_used_at; verify records api_token.used audit.
- FastAPI via TestClient: unauth -> 401; invalid token -> 401; /me
  returns user; healthz open without auth; /applications scoped to
  caller; another user's token returns []; DELETE happy path + 404
  for nonexistent; cross-user GET /applications/{id} returns 404 (not
  403) per the no-leakage policy; PUT/GET /cv round-trip; PUT /cv
  empty rejected with 422; POST /analyze (mocked pipeline) returns
  result inline; save=true persists with the requested status;
  pipeline error propagated as 502; /analytics returns full Dashboard
  shape.
- Alembic head creates api_tokens.

End-to-end live verification: issue token -> Authorization: Bearer ...
-> /me + /analyze (with save=true, mocked LLM) + /applications +
/cv PUT/GET + /analytics all return 2xx with the expected data. No-auth
and bad-token requests return 401. healthz returns {"ok": true} without
auth.

Full suite 405/405 green.
HMAC-signed POSTs when a subscribed event fires (stage.added,
application.saved, verdict.changed).

Schema (migration 32e5033bc887):
- Webhook: user_id + url + secret (signs deliveries) + events (JSON list)
  + active flag.
- WebhookDelivery: receipt log — webhook_id + event + payload + success +
  status_code + error + attempts. Persisted so the owner can see what
  fired and re-send failures.

services/webhooks.py:
- register/list/set_active/delete/list_deliveries — ownership-scoped,
  audited (webhook.create / webhook.delete).
- sign(secret, body) -> "sha256=<hmac>" so receivers can verify.
- dispatch_event(user_id, event, payload): synchronous, records a
  delivery row per attempt, returns them. Best-effort — a 500 or a
  network error is RECORDED, never raised.
- dispatch_event_background: daemon-thread fire-and-forget so the web
  request that triggered the event doesn't block on receiver latency.
- redeliver(delivery_id): re-POST the same payload, creating a NEW
  delivery row (keeps both the failure and the retry in the log).
- Each POST carries X-JobOffer-Event, X-JobOffer-Delivery (idempotency
  key = delivery row id), and X-JobOffer-Signature headers.

Events fire for NEW activity only — bulk import (historical backfill)
deliberately does NOT dispatch.

UI (app.py): "🪝 Webhooks" sidebar panel (add with URL + event multiselect,
shows the secret once, list with pause/resume/delete, recent-delivery
log with status icons). Stage-add (quick action + detailed form) and the
Save-analysis path fire background dispatches.

AUDIT_KINDS += webhook.create / webhook.delete.

Tests (tests/test_phase23_units.py - 18): CRUD + cross-user blocks +
audit; sign() matches manual HMAC; dispatch posts to subscribed hooks
with correct signature header, skips unsubscribed events + inactive
hooks, records HTTP-error + network-error failures without raising;
redeliver creates a new row + cross-user blocked; payload body shape;
alembic head creates both tables.
Authorization-code flow over Streamlit query params, with provider
configs driven by env vars.

Schema (migration 268857701205):
- OAuthIdentity: links (provider, provider_user_id) -> local user. Pair
  is globally UNIQUE; one user can hold multiple identities (Google AND
  GitHub resolving to the same account by email).

services/oauth.py:
- PROVIDERS registry (Google, GitHub) with authorize/token/userinfo URLs
  + scopes. is_configured / configured_providers gate on env presence.
- build_authorize_url(provider, state) — the UI renders a link to this.
- _exchange_code / _fetch_userinfo — network steps, ISOLATED so the
  resolution logic is unit-testable without a live provider. GitHub
  userinfo falls back to /user/emails when the primary email is hidden.
- resolve_identity(provider, subject, email) — the testable core:
    existing identity      -> login   (audit user.oauth.login)
    email matches a user   -> link    (audit user.oauth.link)
    otherwise              -> register (audit user.oauth.register)
- complete_login orchestrates code -> token -> userinfo -> account and
  wraps any network failure in OAuthError.

services/auth.py:
- create_oauth_user(email): user with an unusable random password hash
  (column is NOT NULL; OAuth users authenticate via the provider). They
  can later set a real password via the reset flow. Idempotent on an
  existing email.
- find_user_by_email(email): case-insensitive lookup for the link step.

UI (app.py): auth gate renders "Sign in with Google/GitHub" link_buttons
for configured providers (CSRF state nonce stashed per render). The
callback (?code=&state=) is consumed before rendering the rest of the
gate: state is verified with secrets.compare_digest, complete_login runs,
session is established. Failures show an error; query params cleared.

AUDIT_KINDS += user.oauth.login / register / link.

Caught a dup-index bug: index=True on the column already creates
ix_oauth_identities_user_id, so the explicit Index() in __table_args__
collided on create_all. Removed the redundant one.

Tests (tests/test_phase24_units.py - 23): config gating; authorize URL
params; resolve_identity for new/existing/email-match/two-providers-one-
account; missing email + missing subject raise; audit events; complete_
login end-to-end (mocked network) + unconfigured + empty-code + network-
failure-wrapped; userinfo normalisation for Google + GitHub (inline +
emails-endpoint fallback); create_oauth_user unusable password +
idempotent; find_user_by_email; alembic head creates oauth_identities.
api/security.py — pure-ASGI SecurityHeadersMiddleware that attaches a
defensive header set to EVERY response, including streamed + error
responses (it hooks http.response.start, so a 401 carries the headers
too). All values env-overridable:
  - Content-Security-Policy: default-src 'none'; frame-ancestors 'none'
    (the API only ever returns JSON, so the strictest CSP is correct)
  - X-Content-Type-Options: nosniff
  - X-Frame-Options: DENY
  - Referrer-Policy: no-referrer (don't leak token-bearing URLs)
  - Cache-Control: no-store (responses can carry personal data)
  - Permissions-Policy: geolocation=(), microphone=(), camera=()
  - Strict-Transport-Security: opt-in via API_ENABLE_HSTS=1 (HSTS on
    plain HTTP is a footgun, so off by default).
Wired into api.main.create_app.

Streamlit can't set CSP / HSTS / Secure-cookie flags itself, so:
- .streamlit/config.toml pins enableXsrfProtection=true + enableCORS=false
  (Streamlit ties XSRF to CORS-off) + disables usage stats.
- deploy/Caddyfile.example + deploy/nginx.conf.example: TLS-terminating
  reverse proxy that adds the web-UI CSP (Streamlit needs
  'unsafe-inline'/'unsafe-eval' for its bundled JS), HSTS, frame denial,
  and upgrades the Streamlit session cookie to Secure; SameSite=Lax.
  Both route /api/* -> FastAPI (127.0.0.1:8000) and / -> Streamlit
  (127.0.0.1:5000) with the websocket upgrade Streamlit requires.

Tests (tests/test_phase25_units.py - 8): default header set + CSP
override + HSTS opt-in + max-age override (unit); headers present on
/healthz and on a 401 error response, HSTS present only when enabled
(integration via TestClient).
Added a migrations-postgres CI job alongside the existing unittest matrix.
It spins up a postgres:16 service container, installs the project +
psycopg[binary], and runs the FULL migration cycle against real Postgres:

    alembic upgrade head
    alembic downgrade base
    alembic upgrade head

then asserts all 15 expected tables exist. SQLite's permissive DDL hides
issues Postgres enforces (real ALTER semantics, FK ordering, strict
types, server-default rendering), so this catches migrations that only
work on SQLite — exactly the gap our existing SQLite-only alembic tests
left open.

Verified the up/down/up chain locally on SQLite first (all 12 migrations
reverse cleanly), so the CI job should be green on first run.

Full suite 454/454 green.
One-click analysis of the job posting on the current tab via the user's
API token. Reads the ALREADY-RENDERED page in the browser, so JS-heavy
boards (LinkedIn / Indeed / Glassdoor) that the server's requests-based
URL ingest can't fetch work here.

chrome-extension/:
- manifest.json — MV3, permissions activeTab + scripting + storage.
- extract.js — PURE helpers (extractJobText heuristic, normalizeWhitespace,
  buildAnalyzeRequest, renderVerdict). No chrome/DOM globals at module
  scope, so it's unit-testable in Node. CommonJS export guarded so the
  popup can also load it via <script>.
- popup.html + popup.js — settings (API base URL + jos_ token in
  chrome.storage.local), "Analyze this page" injects an extraction fn via
  chrome.scripting.executeScript, POSTs to {base}/v1/analyze with the
  bearer token, renders the verdict + report. save:false (use the web app
  to persist).
- README.md — dev-mode install + token-creation steps.
- extract.test.mjs — Node test for the pure helpers.

Tests:
- chrome-extension/extract.test.mjs (9, run via node): whitespace
  normalisation; extractJobText prefers a description container, falls
  back to body, skips too-short containers, survives a broken
  querySelector, handles missing body; buildAnalyzeRequest strips
  trailing slashes + sets the bearer header + save:false body;
  renderVerdict emoji mapping + default.
- tests/test_phase27_extension.py (8): manifest is valid MV3 with the
  right permissions + an existing popup; popup loads extract.js before
  popup.js; the API endpoint + Bearer are wired; chrome.storage +
  chrome.scripting are used; required files present; and it shells out
  to `node extract.test.mjs` (skipped if node is absent) so the JS suite
  runs as part of the Python test run too.
The committed uv.lock was generated at the prototype stage and was missing
~14 of the dependencies added across phases 0-27 (fastapi, pyotp, qrcode,
uvicorn, alembic, bcrypt, anthropic, pypdf, python-docx, …). Replit installs
from uv.lock, so a merge would have crashed `streamlit run app.py` at startup
on `import pyotp` / `import bcrypt`.

Regenerated uv.lock via `uv lock` so it matches pyproject.toml exactly,
including the optional extras (celery/redis/playwright/fpdf2/
python-telegram-bot) and dropping the now-unused twilio. Verified all 40
top-level app.py imports resolve in a clean environment afterwards.

REPLIT_DEPLOYMENT.md documents, grounded in the live Replit docs:
- The lockfile fix (the one strictly-required change to keep Replit working).
- SQLite default is unsafe on Replit Autoscale (stateless/ephemeral/scale-
  to-zero per the docs) — set DATABASE_URL to Replit's built-in Postgres;
  init_db() create_all handles schema on first boot.
- Provider API key needed to leave demo mode.
- The REST API / Celery worker / Telegram bot / reminders are NOT started by
  Replit's single `streamlit run app.py`; they degrade gracefully and need
  separate processes (docker-compose.yml or extra Replit deployments).
- CSP/HSTS hardening needs a reverse proxy not present on vanilla Replit.

Net: merging is safe; the required lockfile fix is in this branch, the rest
are deploy-time Secrets (DATABASE_URL + provider key), not code changes.

Full Python suite 462/462 green; 9 JS helper tests green.
PR #1's CI surfaced a real packaging bug (first time `pip install -e .`
ran — it never executed locally, where deps were installed individually).
All three jobs died at install with:

  error: Multiple top-level packages discovered in a flat-layout:
  ['db','api','bot','agents','worker','deploy','services','migrations',
   'attached_assets']. setuptools will not proceed with this build.

Root cause: pyproject.toml had no build-system / package config, so
setuptools auto-discovery couldn't decide what to package among our many
top-level dirs. This would also have broken Replit's `uv sync` (same
build step), so catching it pre-merge is a win.

Fix: this is an APPLICATION, not an importable library — it's installed
only to pull dependencies; the source is imported from the repo root
(on sys.path in every run context: Streamlit runs from root, the
API/worker/bot launch via `python -m …`, tests prepend the root).
Added an explicit build-system and `[tool.setuptools] py-modules = []`,
which disables flat-layout discovery so the editable build is a no-op
that still installs deps. Verified `pip install -e .` now succeeds
(builds a 2.9KB empty editable wheel) and imports still resolve.

Also:
- Regenerated uv.lock for the pyproject change (deps unchanged).
- Postgres CI healthcheck: `pg_isready -U joboffer -d joboffer_ci`
  (was querying the implicit `joboffer` DB that doesn't exist, spamming
  "database joboffer does not exist" FATALs in the service logs).

Representative test subset green; CI re-run on push will validate the
full matrix + the Postgres migration job.
@Rebell-Leader
Rebell-Leader merged commit f01a7f4 into main Jun 6, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants