Skip to content

Copy of AGENTS.md from aggregator-2

Generated from aggregator-2/AGENTS.md at commit e26d5055. Edit the source file, not this copy.

AGENTS.md - Smart Bid

Explore in graph

Project Overview

Smart Bid is a job aggregation platform that crawls multiple job boards and normalizes listings into MongoDB. Runs entirely in Docker Compose.

Monorepo structure: - backend/ — Node.js/Express API server (CommonJS, no TypeScript) - python-scraper/ — FastAPI microservice using python-jobspy for Indeed/Glassdoor/ZipRecruiter

Architecture

backend (Express, port 7001)
  -> MongoDB (port 27017)
  -> Redis (port 6379)            <- BullMQ job queue
  -> python-scraper (FastAPI, port 9000)
  -> chrome (Selenium Grid, port 4444, SE_NODE_MAX_SESSIONS=16)

Crawler Queue System (BullMQ + Redis)

Four worker pools process crawlers from four BullMQ queues:

Queue Crawlers Concurrency Schedule Rate Limit
selenium-crawlers 40 Selenium crawlers 5 Hourly (0 * * * * ET) —
api-crawlers 3 API crawlers (remotive, jsjobs, workable) 3 Hourly (0 * * * * ET) —
apify-crawlers 2 Apify LinkedIn crawlers 1 Daily 12 PM PST (0 12 * * *) —
jobspy-crawlers 11 title searches via python-scraper 2 Hourly (0 * * * * ET) 2/min

All config lives in backend/config/queue.js. Crawler functions are registered in backend/workers/queue/crawlers.js. All crawled jobs pass through backend/workers/normalize.js (dedup, title filter, skill extraction, upsert to local + cloud MongoDB).

Crawler Directory Structure

backend/crawlers/
  selenium/   — 50 files (40 registered, 10 inactive)
  api/        — 6 files (remotive, jsjobs, workable, jobspy, activeJobsDB, findworksdev)
  apify/      — 2 files (advanced-linkedin-job-search-api, linkedin-jobs-scraper)

Crawler Design Philosophy

Crawlers run on an hourly schedule shared across 37+ Selenium workers. Reliability and simplicity are the top priorities — a broken crawler silently wastes a Selenium Grid slot every hour.

Rules: - Keep crawlers as simple as possible. One page load, one executeScript batch extraction, normalize(), done. Avoid multi-tab switching, hover simulation, or click chains unless absolutely required by the site. - Prefer driver.executeScript() for data extraction. A single in-page JS call to extract all fields from all cards is faster and more stable than N×M sequential Selenium element lookups. - Never open extra tabs unless the apply URL is genuinely unreachable otherwise. Tab switching adds failure points — always clean up with a finally block if you do. - Paginate conservatively. Cap pagination at 3–10 pages. Use an early-exit condition (no cards found) rather than always hitting the max. - Use setPageLoadStrategy("none") on every crawler. Pair with driver.wait(until.elementsLocated(...)) to wait for the specific content, not the full page load. - Field extraction priority: title and url are required — skip the card if either is missing. All other fields (locations, salary, stack, description, companyLogo) are optional — wrap each in its own try/catch or null-check. - remote field: derive from locations with /remote/i.test(locations) for general crawlers. Hardcode remote: true only when the URL filter guarantees remote-only results. - Never use driver.sleep() as the primary wait. Use it only after navigation (SPA hydration) or after scroll (lazy-load trigger). Always follow with driver.wait(until.elementsLocated(...)). - source field must be the bare hostname, e.g. "overturepartners.com", "hiring.cafe". No https:// prefix, no path.

Build / Run Commands

Docker (primary workflow)

make up          # docker compose up -d (starts all services)
make down        # docker compose down

Backend (inside container: docker exec -it smart-bid-backend bash)

npm run dev      # Start with nodemon (auto-reload)
npm start        # Start with node (production)
npm run lint     # Prettier check
npm run format   # Prettier write (run before committing)
npm run crawl -- --list                                        # List all crawlers
npm run crawl -- remoteok                                      # Test a single Selenium crawler
npm run crawl -- remotive                                      # Test a single API crawler
npm run crawl -- "fantastic-jobs/advanced-linkedin-job-search-api"  # Test an Apify crawler
npm run crawl -- jobspy "AI Engineer"                          # Test a jobspy search

Python Scraper

pip install -r requirements.txt
uvicorn main:app --host 0.0.0.0 --port 9000

Code Style Guidelines

Language & Module System

  • Backend: Plain JavaScript (CommonJS). No TypeScript. Use require() / module.exports.
  • Python scraper: Python 3 with Pydantic type hints.

Formatting

  • Prettier is the sole formatter.
  • Backend: Prettier 2.x.
  • Double quotes for strings. Trailing commas (ES5). 2-space indentation.
  • Always run npm run format before committing.

Import Ordering (Backend)

  1. Node built-ins (path, stream)
  2. Third-party packages (express, axios, mongoose, bullmq, apify-client)
  3. Local config/utilities (../config/..., ../utils/...)
  4. Local models (../models/...)
  5. Local workers/crawlers (../workers/..., ../crawlers/...)

Naming Conventions

  • Files: lowercase with dots or hyphens (queue.js, extract_skills.js, linkedin-jobs-scraper.js). Snake_case for utilities.
  • Variables/functions: camelCase (fetchJobs, handleClickApply).
  • Mongoose models: PascalCase (Job). Named exports: module.exports = { Job }.
  • Constants/env vars: UPPER_SNAKE_CASE (MONGODB_URI, QUEUE_NAMES).
  • Route handlers: Inline async arrow functions in router.get()/router.post().
  • Apify crawler files: Named after the actor slug (e.g., advanced-linkedin-job-search-api.js for actor fantastic-jobs/advanced-linkedin-job-search-api).

API Response Pattern

const serverResponses = require("../utils/helpers/responses");
const messages = require("../config/messages");
serverResponses.sendSuccess(res, messages.SUCCESSFUL, data);
serverResponses.sendError(res, error);

Logging (Crawlers)

All crawler logging goes through backend/utils/job_logger.js — never use console.log inside backend/crawlers/.

const { createJobLogger } = require("../../utils/job_logger");
const fetchMysite = async (job) => {
  const jl = createJobLogger(job);  // job is the BullMQ job object (or null in CLI)
  await jl.log("fetching mysite.com -------");   // Logs tab in Bull Dashboard
  await jl.error(`item ${i} failed: ${err.message}`); // per-item recoverable error
  await jl.fatal(`Error in fetching mysite.com: ${err.message}`); // top-level: logs + throws → marks job failed, populates Error tab
  await jl.progress({ raw, inserted });           // Progress tab
};
  • jl.log(msg) — informational milestone (start, counts, page banners)
  • jl.error(msg) — per-item recoverable failure inside inner try/catch; does not throw
  • jl.fatal(msg) — top-level catch only; logs then throws so BullMQ marks job failed and Error tab shows the reason
  • jl.progress(data) — call with stats object after normalize()
  • When job is null (CLI via bin/crawl.js), methods fall back to console.log/console.error

Error Handling

  • Crawlers: Inner loop try/catch uses jl.error(). Outer catch uses jl.fatal(). No console.log anywhere in backend/crawlers/.
  • Queue workers: BullMQ auto-retries 3 times with exponential backoff (jobspy: 2 retries). Errors visible in Bull Board (/admin/queues) Error tab when jl.fatal() is used.
  • Routes: try/catch around async ops. Return errors via serverResponses.sendError().

Adding a New Crawler

Selenium or API crawler: 1. Create file in backend/crawlers/selenium/ or backend/crawlers/api/. 2. Add one line to SELENIUM_CRAWLERS or API_CRAWLERS in backend/workers/queue/crawlers.js. 3. Test: npm run crawl -- <name>

Apify crawler: 1. Create file in backend/crawlers/apify/ named after the actor slug. 2. Add entry to APIFY_CRAWLERS in backend/workers/queue/crawlers.js — key is author/actor-name. 3. Set source field to match the crawler key (e.g., "curious_coder/linkedin-jobs-scraper"). 4. Use process.env.APIFY_API_TOKEN (stored in backend/config/config.json). 5. Call normalize(result, { skipTitleFilter: true }) since Apify results are pre-filtered. 6. Test: npm run crawl -- "author/actor-name"

Crawler Shape & normalize()

All crawlers must build an array of objects and call normalize(result, options, job):

{ title, url, companyName, source, companyLogo?, companySize?, locations?, description?, salary?, stack?, keyword?, remote? }
- remote (Boolean) — set to true if the job is remote. For location-based crawlers, derive it from locations: remote: /remote/i.test(locations). For crawlers that only return remote jobs (e.g. Apify LinkedIn), hardcode remote: true. - stack can be an array of strings (joined to comma-separated in normalize). - normalize(result, { skipTitleFilter: true }, job) skips title include/exclude filters (used by Apify crawlers). - Always return await normalize(...) so the worker gets stats back as the job return value. - For deferred detail scraping, include meta: { detailUrl, enrichment: "<crawler-key>" } in each listing, export module.exports.enrich = enrich, and implement const enrich = async (driver) => ({ ...fields }) in the crawler file. The key must be registered in ENRICHERS at backend/workers/queue/crawlers.js. - normalize() deduplicates by URL, filters titles, extracts skills, resolves redirect URLs, and upserts to both local and cloud MongoDB. - Returns { raw, afterFilter, afterDedup, inserted, skipped } — pass the BullMQ job as the third arg so normalize logs to Bull Dashboard.

Key Files Reference

Path Purpose
backend/server.js Express entry point, queue init, Bull Board mount
backend/config/queue.js Redis connection, queue names, concurrency, cron schedules
backend/config/titles.js Job title keywords (used by jobspy + Apify crawlers)
backend/config/config.json Dev/test env vars (API keys, DB URIs)
backend/workers/queue/crawlers.js Crawler registry — add new crawlers here
backend/workers/queue/queues.js BullMQ queue instances, repeatable jobs, enqueue function
backend/workers/queue/workers.js BullMQ worker definitions with concurrency
backend/workers/queue/board.js Bull Board monitoring dashboard
backend/workers/queue/index.js Queue bootstrap (called on server ready)
backend/workers/normalize.js Dedup, title filter, skill extraction, redirect resolution, DB upsert
backend/routes/index.js Core API routes (jobs, analytics, sheets)
backend/routes/crawlers.js Crawler trigger + list endpoints
backend/bin/crawl.js CLI tool to test individual crawlers
backend/bin/dedup.js One-off deduplication script
backend/bin/analyze-titles.js AI-powered title filter analysis
backend/models/jobs/job.js Job Mongoose schema (13 fields + timestamps)
backend/utils/job_logger.js Bull Dashboard logger (log, error, fatal, progress)
backend/utils/helpers/responses.js Standardized API response helpers
python-scraper/main.py FastAPI scraper service
compose.yaml Docker Compose (backend, MongoDB, Redis, Chrome, python-scraper)