Skip to content

Production-readiness (P0–P2) + security review remediation + architecture cleanup - #2

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

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

Conversation

@Rebell-Leader

@Rebell-Leader Rebell-Leader commented Jun 9, 2026 •

Copy link
Copy Markdown
Owner

Summary

Takes the app from "feature-complete + deployed" to "production-grade for multi-user traffic." Three arcs: the production-readiness roadmap (P0→P2), a holistic technical review with all findings fixed, and an architecture/quality cleanup.

24 commits · 112 files · suite green throughout (647 tests, 7 live-e2e skipped) · ruff + mypy (pinned 1.x) + bandit all clean.

Note: the monetization layer (billing/tiers/Stripe, landing page, SSRF guard, launch docs) landed on the branch after this PR merged — it's in follow-up PR #3, not here. This description reflects what this PR actually merged.

Production-readiness roadmap (all ✅)

P0 — Redis-backed cache/checkpoint (horizontal scaling), width="stretch" migration, account lifecycle (email verification, password-gated delete with cascade, GDPR export), schema-drift guard.

P1 — CI quality gates (ruff/mypy/bandit/pip-audit/coverage≥80%/JS); TOTP secret envelope-encrypted at rest (utils/crypto, Fernet); LLM cost controls (per-call token+USD ledger, contextvars attribution, rolling spend budget, opt-in completion cache); observability (GET /metrics Prometheus exposition + Pushgateway); gated live-provider e2e; agentic company fallback (keyless DuckDuckGo + Browserbase + no-fabrication synthesis).

P2 — durable webhook delivery (Celery retry/backoff, at-least-once); Postgres backups + restore drill + RUNBOOK; JS-board ingestion via hosted Browserbase; reverse-proxy edge guide.

Security review remediation

  • 🔴 OAuth account-takeover — auto-link now requires a provider-verified email; unverified link refused.
  • 🟠 REST /v1/analyze bypassed cost controls — now enforces quota+budget (429/402) and attributes LLM spend.
  • 🟠 No-fabrication check missed lowercase skills — case-insensitive skill lexicon both sides; year regex widened.
  • 🟡 BudgetExceeded UI crash, empty-skeleton-on-failure, orchestrator dropping the 2nd parallel error — all fixed.

Use-case e2e test layer

New middle tier between UI-smoke and skipped live-e2e: full journeys with mocked LLM but real services + DB + orchestrator (tests/e2e_helpers.py + 9 journeys).

Architecture & quality

  • Layering audited clean; utils/ is a true leaf (usage ledger via observer pattern).
  • Webhooks dispatch from the service layer so every entry point fires them.
  • De-duplication: utils/env typed config (~36 sites), require_owned ownership helper (28 sites), shared strip_code_fence + extract_job_text.
  • CI mypy pinned to 1.x (reproducible gate) + strict-mypy type fixes.
  • CLAUDE.md: architecture/layering section + shared-helper guidelines.

Migrations

Three new revisions (46b9602c99a1 email verification, 5d2f8a1c4e7b TOTP widen, 7c1a9e3b5f02 llm_usage) — CI runs full up → down → up on Postgres; schema-drift guard asserts models match.

https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd

claude added 24 commits June 6, 2026 20:20
Closes the test-coverage gap that let the nested-st.expander bug ship
through CI and only surface on the live Replit deploy: the 462-test suite
exercised every service but never rendered app.py.

tests/test_phase28_ui_smoke.py (4 tests):
- Renders the real app.py through Streamlit's AppTest harness:
    * unauthenticated auth gate,
    * a fully-seeded authenticated account (application + stages + TWO
      tailored artifacts + master CV with a revision + a share link —
      the densest nested-UI path, exactly where the nested-expander bug
      lived), asserting no render-time exception,
    * the public ?share= view.
  Uses the StaticPool in-memory SQLite so the ScriptRunner thread shares
  the seeded DB; demo mode (no provider key) so no network during render.
- A static guard that scans app.py for `with st.expander(` nested inside
  another, verified to flag a true positive and pass the checkbox-inner
  pattern. Belt-and-suspenders for code paths a single render might miss.

services/system_test.py: reconcile MOCK_ANALYSIS["verdict"] to the
canonical {verdict, light, reasons, confidence, source} shape used by
utils/verdict.py + render_result, so the System Test tab renders the
verdict badge identically to a real analysis (it previously used a
divergent {decision, confidence, cautions} shape that render_result
couldn't read).

Full suite 466/466 green.
Beyond initial render, exercise the two highest-value callback paths so a
broken on-click handler fails in CI, not production:
- Analyze form submit in demo mode -> runs the pipeline and renders the
  result (covers the analyze -> render_result path); asserts last_result
  is populated with a final_report.
- Stage quick-action click -> add_stage + st.rerun + dense re-render;
  asserts the stage was persisted and no render exception.

Added _textarea_by_label / _button_by_label / _button_by_key AppTest
helpers. Full suite 468/468 green.
Agent/human onboarding doc covering: what the app is, repo layout, how to
run each surface, the conventions that must be followed (demo mode,
no-fabrication, ownership scoping, best-effort side-effects, bcrypt-at-rest,
migrations + StaticPool testing, no nested expanders), the testing approach,
a summary of the ~28 increments shipped, and a prioritized
production-readiness roadmap (P0/P1/P2) with the concrete gaps that remain
before real multi-user traffic (in-process state vs horizontal scaling, the
dated use_container_width deprecation, account lifecycle/GDPR, schema-drift
guard, CI quality gates, secrets-at-rest, cost controls, observability
shipping, live provider e2e, webhook durability, backups/runbook).
use_container_width was deprecated with removal scheduled after 2025-12-31
(already past). All 5 call sites in app.py (link_button, sidebar button, two
altair_chart, one dataframe) used =True; replaced with width="stretch", the
documented successor. The Streamlit AppTest smoke test confirms the UI
renders with no deprecation warnings. Also closed an unclosed-file
ResourceWarning in the nested-expander static scan.
tests/test_phase29_schema_drift.py applies all migrations to a fresh DB and
uses Alembic's compare_metadata to assert there is no SUBSTANTIVE drift
(add/remove table or column) between the migrated schema and the SQLAlchemy
models. This catches the canonical "added a model field, forgot the
migration" case — which create_all (dev/test) would mask but a migrated prod
DB would not.

Scoped to table/column ops on purpose: the models enforce uniqueness via
column unique=True (a unique index) while the hand-written migrations use
UniqueConstraint — functionally identical, so the cosmetic index/constraint
naming diffs are excluded (documented), as are SQLite reflection artifacts
(BigInteger->INTEGER, server defaults, String lengths). Real types/defaults
are exercised by the Postgres CI migration job.

The guard surfaced those pre-existing cosmetic differences on first run,
confirming it works; it now passes clean and will fail CI on a future
column/table divergence.
In-process state breaks once you run more than one app instance. Rate
limiting already had a Redis backend; this gives the LLM/data-source cache
and the analysis checkpoint store the same treatment, behind the same
REDIS_URL (or CELERY_BROKER_URL) detection.

utils/cache.py:
- RedisCache (JSON-serialised values under a "joc:cache:" namespace, TTL
  via CACHE_TTL_SECONDS) alongside the existing SimpleCache.
- build_cache() picks Redis when configured + importable, else in-memory;
  a failing/absent redis degrades to in-memory (logged, never raised).
- Cache ops never raise into callers (a cache hiccup can't break a request).

services/checkpoint.py:
- RedisCheckpointStore (each key a Redis hash stage->JSON, TTL via
  CHECKPOINT_TTL_SECONDS) so a retry can land on a different replica and
  still resume completed stages. Same factory + graceful fallback.

Both keep cached/checkpointed values JSON-serialisable (they already are:
parsed dicts + report strings). reset_store_for_testing now rebuilds a
fresh in-memory store (tests never use Redis).

.env.example documents REDIS_URL now backs rate-limit + cache + checkpoints
and is REQUIRED for >1 instance.

Tests (tests/test_phase30_redis_state.py - 15): factory selection +
graceful fallback (no URL / import fails / non-redis URL) for both stores;
RedisCache set/get round-trip (dict + str), namespacing, namespaced clear,
unserialisable-skip; RedisCheckpointStore set/get/has, canonical-order
completed_stages, clear, key isolation — all via an injected fake redis.

Full suite 484/484 green.
Account self-service + GDPR data portability, plus a prod-safety fix.

- services/auth.delete_account(user_id, password): password-gated permanent
  deletion. Audited BEFORE the row vanishes (audit row's user_id is SET NULL
  by cascade, so the record + email survive). Deleting the User cascades to
  every child table.
- db/session: enable `PRAGMA foreign_keys=ON` for SQLite connections (via a
  connect event listener, in both get_engine and reset_engine_for_testing).
  SQLite ignores ON DELETE CASCADE/SET NULL without it, which would orphan
  child rows on SQLite while Postgres cascaded — a dev/prod split. Now
  identical. Verified: deleting a fully-seeded user empties all 11 child
  tables; another user's data is untouched.
- services/account_export.build_export / export_json: one JSON bundle of
  everything the user owns (account, applications + stages + artifacts +
  shares, master CV + revisions, projects, API-token + webhook metadata,
  telegram link). Secrets (password/token hashes, webhook secret, TOTP
  secret) are excluded — tested. Audited as user.account.export.
- app.py "🗄 Privacy & account" sidebar panel: download-all-my-data button +
  two-step password-gated delete (wipes session on success).
- Reset-token prod safety: the `print([auth] reset token ...)` log line is
  now gated on RESET_TOKEN_SURFACE_IN_UI (same flag as the UI display), so a
  production deploy never leaks reset tokens to logs.
- AUDIT_KINDS += user.account.{delete,export}, user.email.verify.{request,complete}.

Tests (tests/test_phase31_account_lifecycle.py - 9): FK pragma on; delete
wrong-password rejected; delete cascades all child tables; delete audited +
record survives with SET NULL; delete is user-scoped; export bundles every
domain; export excludes secrets (incl. the live webhook secret value);
export is valid JSON + audited.

Full suite 493/493 green.
Schema (migration 46b9602c99a1):
- users.email_verified (Boolean). server_default=true backfills EXISTING
  rows so no one is locked out; the ORM default is False so new password
  signups start unverified.
- email_verification_tokens: bcrypt-hashed, 24h, one-shot (same shape as
  password reset).

services/email_verify.py: is_verified / start_verification (rate-limited
resend, returns None when already verified) / complete_verification (single
generic error for unknown-email/wrong/expired/used; idempotent if already
verified). Audited request + complete.

services/auth.py:
- AuthedUser gains email_verified; register/authenticate/get_user/
  find_user_by_email all populate it from the DB.
- create_oauth_user sets email_verified=True (the provider verified the
  email) — OAuth users never see the banner.

UI (app.py):
- Signup triggers start_verification + send_verification_email (best-effort;
  never blocks signup).
- An email-verification gate renders for unverified users: a banner with a
  "Resend email" button and a token-entry form. Informational by default;
  set REQUIRE_EMAIL_VERIFICATION=1 to hard-block app usage until verified
  (off by default so the live deploy / existing users aren't impeded).
- A ?verify_token= deep link (from the emailed link) is consumed on load.

services/notifications.send_verification_email (full link when APP_BASE_URL
set, else the raw token). AUDIT_KINDS already extended in part 1.

Tests (tests/test_phase32_email_verify.py - 13): new password user
unverified / OAuth user verified; authenticate reports state; start+complete;
start returns None when verified; one-shot (used token can't verify another
account); wrong/expired/empty token rejected; token hash != raw; resend
rate-limited; audit events. Plus a migration test that inserts a legacy user
at the pre-feature revision and asserts the upgrade backfills it verified.
Schema-drift guard still green (models == migrations). Full suite 506/506.
All four P0 items shipped (Redis-backed cache+checkpoint, width="stretch"
migration, account lifecycle: verification+deletion+export, schema-drift
guard). P1 is now the top priority. Refreshed module/migration/table/test
counts (29 service modules, 15 migrations, 19 tables, 506 Python tests).
New CI jobs in .github/workflows/tests.yml:
- lint: ruff check (E/F/W/I). Config in pyproject ([tool.ruff]); fixed all
  39 findings (36 unused imports auto-removed, 3 unused vars) + applied
  isort ordering across the tree.
- typecheck: mypy on the app packages (services/utils/db/tools/agents/api/
  bot/worker), ignore_missing_imports + import-untyped disabled (we check
  OUR code, not third-party signatures). Fixed the 4 genuine errors
  (email.py None args, url_ingest None.strip guard, analytics/resume_analyzer
  annotations). Clean across 71 files.
- security: bandit -ll (hard gate, currently clean) + pip-audit (ADVISORY/
  continue-on-error — transitive-dep CVEs in the base image are outside our
  control).
- js-tests: setup-node + node chrome-extension/extract.test.mjs (the JS
  suite now runs in CI, not just locally).
- test: now runs under coverage with --fail-under=80 on the logic packages
  (actual ~87%). app.py is excluded from the gate (dense Streamlit UI, only
  smoke-tested).
- FORCE_JAVASCRIPT_ACTIONS_TO_NODE24=true silences the Node-20 action
  deprecation ahead of the forced cutover.

pyproject: [tool.ruff]/[tool.mypy]/[tool.bandit] config + a [project.
optional-dependencies] dev extra (ruff/mypy/bandit/pip-audit/coverage/
types-requests). uv.lock regenerated.

Also extended the Postgres migration job's expected-tables assertion with
email_verification_tokens (added in P0.3).

No behaviour change — lint/type fixes are import cleanups + annotations +
None-guards. Full suite 506/506 green; ruff/mypy/bandit clean; coverage
gate passes.
Fallback so we get REAL company data even with no paid keys. When
NEWS_API_KEY is absent but an LLM provider key is set, company-news fetch
falls through to a keyless agentic web search instead of an empty sentinel.

tools/company_research.py:
- ddg_search(query): keyless DuckDuckGo — ddgs/duckduckgo_search library if
  installed, else the HTML endpoint parsed with BeautifulSoup. [] on any
  failure. ([research] extra adds ddgs.)
- agentic_company_research(company): LLM proposes 3 targeted queries ->
  DuckDuckGo -> dedup results -> optional deep-fetch of the top URL via a
  headless agentic browser -> LLM synthesises a briefing under the SAME
  no-fabrication rule (only use snippet content; label inferences;
  wrap_untrusted on all fetched text). Returns None in demo mode / when no
  results, so the caller keeps its sentinel.
- deep_fetch(url): Browserbase hosted headless browser (BROWSERBASE_API_KEY +
  PROJECT_ID, connects Playwright over CDP) -> local Playwright scraper
  (BROWSER_SCRAPER_ENABLED) -> None. All graceful.
- Everything best-effort: a research hiccup never breaks the pipeline.

tools/data_sources.fetch_company_news: now tier-1 NewsAPI -> tier-2 agentic
fallback (also on NewsAPI failure) -> None.

tests/test_e2e_live.py (gated on RUN_E2E=1; 7 tests, skipped by default since
CI/sandbox are egress-restricted): real round-trip per configured provider;
real keyless DuckDuckGo search; the agentic fallback with news/COL keys
removed (the "no keys -> web search for real data" scenario) asserting a
real briefing; real URL ingest; optional Browserbase deep-fetch; and a full
run_analysis on a real posting asserting a verdict + report.

tests/test_phase33_company_research.py (22, always-run, mocked): DDG HTML
parsing + limit; library-preferred / HTML-fallback / failure-empty search;
query building (LLM JSON, code-fence strip, static fallback); agentic
orchestration (demo-disabled, env-disabled, no-results-None, synthesis uses
snippets + no-fabrication + untrusted-wrap, URL dedup); deep_fetch backend
selection; and the fetch_company_news fallback chain (agentic on missing key,
None when both unavailable, NewsAPI-preferred, NewsAPI-failure-falls-through).

.env.example documents COMPANY_RESEARCH_FALLBACK / DDG_MAX_RESULTS /
BROWSERBASE_*. mypy/ruff clean; full suite 535 (7 e2e skipped) green.
Add utils/crypto (Fernet, key derived from SECRETS_ENCRYPTION_KEY) and wire
it into services/totp: the TOTP secret is stored as enc:v1:<token> when a key
is configured, transparently decrypted on read, and passed through as
plaintext when unkeyed (dev/demo). Legacy plaintext rows are re-encrypted
opportunistically on the next successful verify.

- utils/crypto.py: encrypt/decrypt/is_encrypted/encryption_enabled with a
  transparent prefix scheme; decrypt of a prefixed value with no/wrong key
  raises DecryptionError (never leaks gibberish into a verify).
- db/models.py: widen user_two_factor.secret 64->255 for the ciphertext.
- migration 5d2f8a1c4e7b: column widen (up/down/up verified).
- .env.example: document SECRETS_ENCRYPTION_KEY + rotation caveat.
- pyproject: add cryptography>=41 explicitly; uv.lock regenerated.
- tests: 9 new (crypto primitives + TOTP integration incl. lazy re-encrypt).

https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd
Replace the request-count-only quota with real spend accounting:

- services/usage.py: ledger every real completion's tokens + estimated USD
  cost (env-overridable pricing via LLM_PRICING_JSON), attributed to a user
  through a contextvars scope (account(user_id)). spend_usd() sums a rolling
  window; check_budget() enforces LLM_BUDGET_USD and raises BudgetExceeded.
- db/models.py + migration 7c1a9e3b5f02: new llm_usage table (cost in integer
  micro-USD; nullable owner for unattributed calls).
- utils/llm.py: providers now return (text, usage); get_completion ledgers
  usage best-effort and supports an opt-in identical-completion cache
  (LLM_CACHE_COMPLETIONS=1) that serves free hits with no re-charge.
- analysis_runner.check_user_quota: also enforces the spend budget; user_id
  threaded through run_analysis_sync/enqueue/submit + worker task +
  background_analysis so async runs attribute too.
- orchestrator: re-apply the accounting scope inside the company/salary thread
  pool (contextvars don't cross threads).
- app.py: wrap the sync run in account(user_id).
- CI: assert llm_usage present on Postgres. .env.example documents the knobs.
- tests: 15 new (pricing, ledger, attribution, budget gate, llm wiring+cache).

https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd
…oint

The in-process metrics registry can now be exported, not just snapshotted:

- utils/metrics.render_prometheus(): Prometheus text exposition (v0.0.4) with
  name/label sanitisation; counters -> counter, histograms -> summary
  (quantiles + _sum + _count) plus _min/_max gauges.
- api/main.py: GET /metrics serves it, gated by METRICS_ENABLED (404 when off)
  and an optional METRICS_TOKEN bearer (401 without). Per-process is exactly
  Prometheus's scrape-and-aggregate model.
- worker/metrics_dump.py: --prometheus output + --push to a Pushgateway
  (METRICS_PUSHGATEWAY_URL) as a cron stop-gap when no scraper is available.
- .env.example documents the knobs; tests: 12 new (render format, endpoint
  gating, pushgateway helper).

https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd
Move outbound webhooks off the best-effort daemon thread onto the queue for
at-least-once delivery:

- services/webhooks.py: split delivery into _create_delivery (pending row) +
  attempt_delivery(delivery_id) (re-runnable single POST that rebuilds the
  signed body from the stored row). dispatch_event_durable enqueues a Celery
  task per matching webhook when a broker is configured, else degrades to the
  existing daemon thread. retry_delay_for/_max_attempts drive the schedule
  (WEBHOOK_MAX_ATTEMPTS / WEBHOOK_RETRY_BACKOFF).
- worker/tasks.py: deliver_webhook_task (bind=True) attempts a delivery and
  self.retry()s with exponential backoff until the attempt budget is spent.
- app.py: webhook dispatch sites now call dispatch_event_durable.
- dispatch_event (sync) + redeliver unchanged; existing tests stay green.
- tests: 13 new (backoff schedule, attempt record success/failure/missing,
  durable enqueue per matching hook, broker-down fallback).

https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd
- scripts/backup_db.sh: pg_dump custom-format archive with retention pruning
  and an optional offsite upload hook (BACKUP_UPLOAD_CMD); strict mode, refuses
  non-Postgres URLs, warns on suspiciously small dumps.
- scripts/restore_db.sh: pg_restore --clean --if-exists, confirmation-gated
  (type "restore", or --force for automated drills), masks the target password.
- deploy/RUNBOOK.md: service map, backup schedule (cron/Replit), monthly
  restore drill, migration safety, common incidents, secrets rotation, and a
  data-loss escalation checklist.
- tests/test_phase38_ops_backup.py: 12 tests guarding script syntax, strict
  mode, the early-exit guards (no URL / sqlite / missing dump), and runbook
  coverage — no DB required.

https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd
#10 JS-board scraping:
- tools/url_ingest.py: is_js_board() routes LinkedIn/Indeed/Glassdoor/
  ZipRecruiter straight to a headless browser (skips the doomed plain GET so
  we don't ingest a consent wall). _try_browser_fallback now tries the local
  Playwright scraper THEN a hosted Browserbase session (tools.company_research.
  deep_fetch) — no local chromium, so JS boards work on a vanilla deploy.
  browser_ingest_available() reports either backend. Honest paste-hint error
  when none is configured.

#13 Reverse-proxy edge:
- deploy/README.md: edge topology (TLS + CSP/HSTS + Secure cookies for the
  Streamlit UI, pass-through for the self-hardening API), how to apply the
  Caddy/nginx examples, the Replit/Cloudflare note, and the /metrics privacy
  note.

- tests: phase39 (JS-board detection, routing, local/hosted fallback ordering)
  + phase40 (proxy configs carry the required hardening directives).

https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd
…s, fabrication-check holes

Review fixes (from the holistic technical pass):

- CRITICAL: OAuth auto-link now requires a provider-verified email
  (services/oauth.py). _fetch_userinfo carries email_verified (Google OIDC
  claim; GitHub only a VERIFIED primary from /user/emails — the unverified
  emails[0] fallback is gone). resolve_identity refuses to auto-link an
  unverified email to a pre-existing local account (audited
  user.oauth.link_refused), closing the account-takeover vector. create_oauth_user
  records the real verification status.

- HIGH: REST /v1/analyze enforces the same cost controls as the web/worker
  paths (api/routes.py) — check_user_quota first (429/402 on
  RateLimitExceeded/BudgetExceeded) and run through run_analysis_sync(user_id=)
  so LLM spend is attributed, not ledgered as NULL.

- HIGH: no-fabrication check catches lowercase skills (services/constraint_check.py)
  via a known-skill lexicon scanned case-insensitively on both sides — fixes
  both the lowercase-fabrication false negative and the lowercase-source false
  positive. Year regex broadened to 1900-2099 (pre-1950 dates no longer slip).

- MEDIUM: Streamlit analyze flow catches BudgetExceeded (app.py) instead of
  rendering a raw traceback.

- MEDIUM: analyze_requirements raises on non-JSON when a provider key is set
  (tools/job_tools.py) instead of returning an empty 'successful' analysis;
  empty skeleton kept only for demo mode.

Tests: OAuth verified/unverified link paths + userinfo shape; API 429/402;
lowercase fabrication caught + lowercase source not flagged + pre-1950 year;
job_tools raise-vs-demo. Full suite green (624), bandit clean.

https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd
…mocked LLM)

Closes the structural gap between shallow UI-render smoke and skipped
live-network e2e: full user journeys with mocked LLM/network but the REAL
services, DB, and orchestrator graph, driven through real entry points.

- tests/e2e_helpers.py: mock_llm() runs the real pipeline on the NON-demo path
  (sets a provider key so usage accounting/model resolution/caching execute)
  while stubbing the provider call with stage-appropriate output (reuses the
  demo sample generator for guaranteed-valid stage shapes); disables optional
  network fetchers so nothing egresses. Plus fresh_db()/make_user()/
  issue_api_token() factories (fresh_db also resets the rate-limit + checkpoint
  singletons for inter-journey isolation).
- tests/test_phase41_e2e_journeys.py: 7 journeys —
  1. real graph runs every stage → verdict+report, and threaded company‖salary
     usage is attributed to the user (guards the contextvars re-application);
  2. API token → POST /v1/analyze (real graph) + save → GET the application;
  4. over-budget user refused at the API (402) before any pipeline work;
  6. master CV + project → tailored CV: constraint-check clean, and a
     fabricated skill/percentage is flagged;
  7. enable TOTP → password auth signals 2FA → OTP gate accept/reject +
     one-shot backup code;
  8. no news/COL keys + mocked DuckDuckGo → agentic fallback briefing.

Full suite green (631).

https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd
… both errors

Cleanups from the review:

- Webhook dispatch for stage.added / application.saved moved from app.py into
  services/stages.add_stage and services/applications.save_analysis, so the
  webhooks now fire from EVERY entry point (REST API, bot, UI) instead of only
  the Streamlit handler — a real delivery gap, not just a test seam.
  dispatch_event_durable gains a cheap _has_active_subscriber() pre-check that
  skips the thread/queue (and, in tests, the shared-connection race) entirely
  when nobody is listening.
- agents/orchestrator: surface BOTH company‖salary errors (the second was
  dropped) and convert an unexpected stage raise into an error result so one
  branch crashing can't lose the other branch's checkpoint. Adds a module
  logger.
- utils/llm: replace the three print() calls (incl. the per-attempt failure
  log) with structured logger calls so they reach the JSON drain.
- tests: journey 5 (add_stage → webhook delivery recorded) + orchestrator
  both-errors-surface. CLAUDE.md conventions updated (TOTP encryption, OAuth
  verified-link rule, service-layer webhook dispatch).

Full suite green (633), ruff/mypy/bandit clean.

https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd
Two maintainability cleanups from the review.

Config (utils/env.py):
- Typed env accessors env_str/env_bool/env_int/env_float with one place for
  parsing semantics. env_bool now accepts 1/true/yes/on (any case) — the old
  `== "1"` foot-gun where true/yes silently read as false is gone; bad
  numeric/bool values warn and fall back instead of crashing.
- Every read is recorded; utils.config.log_effective_config() logs the
  resolved NON-default config at startup (api/main, app.py) so a typo'd
  override becomes visible instead of silently using the default. Secrets are
  not read through this, so only tuning knobs are surfaced (never keys).
- Migrated ~36 inline os.getenv parses across services/utils/tools/api/worker/
  bot/db to the helpers (12 boolean flags + 24 numeric limits/timeouts/budgets).

Ownership (services/_ownership.py):
- require_owned(session, Model, id, user_id, exc, msg) centralises the
  fetch-by-pk + "missing OR cross-user -> raise" check behind the 404-not-403
  rule. Migrated all 28 raise-style call sites across 11 services to it, so a
  future site can't forget the user_id comparison. timeline's return-[] read is
  left as-is.

Tests: utils.env parsing + effective-config (test_phase42); existing cross-user
suites continue to guard the migrated ownership sites. mypy clean (76 files),
ruff/bandit clean, full suite green (644).

https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd
… funcs

Final review cleanups.

Layering inversion (observer pattern):
- utils.llm no longer imports the services layer. It exposes
  register_usage_recorder() and notifies registered recorders after each real
  completion, so it's a true leaf (verified: no `import services` in utils/).
- services.usage registers record_completion on import; services/__init__
  imports services.usage so the wiring runs early (every entry point imports a
  service). Recording behaviour is unchanged — usage is still ledgered for all
  real completions and attributed via the account() scope.

Type coverage:
- Annotated _complete_anthropic / _complete_openai_compatible (params +
  Tuple[str, UsageDict] return). With annotations present, mypy now type-checks
  their bodies (the getattr-heavy SDK-response handling most prone to provider
  drift) even under check_untyped_defs=false.

Tests: observer wiring (utils.llm imports no services; importing services
registers the recorder; registration is idempotent). mypy clean (76 files),
ruff/bandit clean, full suite green (647).

https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd
…nt architecture

Acceptance-review cleanups (two read-only audits: layering CLEAN, no violations).

De-duplication:
- utils/text.strip_code_fence: single fenced-JSON stripper; replaces three
  copies (tools/job_tools, services/bulk_import, tools/company_research).
- tools/html_extract.extract_job_text: single posting HTML->text cleaner;
  url_ingest._clean_html and browser_scraper._parse_job_html now delegate.
- services/system_test: last `== "1"` / int(os.getenv) straggler migrated to
  utils.env (env_bool/env_int) — env parsing is now fully centralised.

Dead code / import clarity:
- Removed dead shims utils/llm.get_llm_client() and the generate_mock_response
  alias (no callers).
- utils/__init__.py and tools/__init__.py no longer re-export symbols
  (get_llm_client, cache, the *_tools lists) — that re-export shadowed the
  same-named submodules; consumers already use full submodule paths. Reverted
  the importlib workaround in test_phase2 now that the shadow is gone.
- Replaced three dynamic __import__() calls in app.py with top-level imports
  (datetime, PIPELINE_STAGES).

Docs:
- CLAUDE.md: new "Architecture & layering" section (one-directional flow,
  utils=leaf + observer rule, the two accepted seams, full-submodule-path
  rule) + "Shared helpers" guidelines; refreshed stale counts (31 services,
  17 migrations / 20 tables, 43 test files / 647 tests) and marked P1 done.

ruff/mypy (78 files)/bandit clean, full suite green (647).

https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd
CI's mypy job is unpinned (mypy>=1.10) and had drifted to mypy 2.1.0, which is
materially stricter (third-party stub-shape changes) and surfaced 44 errors —
both pre-existing third-party-typing noise and the two functions newly brought
under checking by recent annotations.

- Pin dev mypy to >=1.10,<2 so the type gate is reproducible (a CI linter must
  not float to "latest"). uv.lock regenerated (2.1.0 -> 1.20.2).
- Fix the genuine type issues so the code is clean under strict mypy too:
  * utils/llm: getattr(block, "text", "") over the Anthropic content union.
  * services/webhooks: None-guard the just-created delivery row in
    attempt_delivery / _deliver (latent None-deref).
  * services/rate_limit: float() the redis zrange score before arithmetic.
  * services/checkpoint: str() the redis hgetall key for the dict index.
  * tools/data_sources: string-valued request params (no mixed int/str).
  * tools/{job,company,salary}_tools: type: ignore the langchain.tools fallback
    (langchain 1.x dropped the attribute; langchain_core path is primary).
  * bot/main: guard Optional update.message / effective_chat and adapt
    reply_markdown (returns Message) to the handlers' Reply contract.

ruff/mypy (78 files)/bandit clean; full suite green (647).

https://claude.ai/code/session_01Vpu7T5ezA2RAJhfpPxBzQd
@Rebell-Leader
Rebell-Leader merged commit e1830cd into main Jun 9, 2026
7 checks passed
@Rebell-Leader Rebell-Leader changed the title Production-readiness (P0–P2) + security review remediation + architecture cleanup Production-readiness (P0–P2) + security remediation + monetization layer Jun 10, 2026
@Rebell-Leader Rebell-Leader changed the title Production-readiness (P0–P2) + security remediation + monetization layer Production-readiness (P0–P2) + security review remediation + architecture cleanup Jun 10, 2026
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