Skip to content

Latest commit

 

History

History
334 lines (274 loc) · 28.5 KB

AGENTS.md

File metadata and controls

334 lines (274 loc) · 28.5 KB

AGENTS.md

The guide for any coding agent working in this repository. CLAUDE.md points here; keep this file as the single copy so the two cannot drift.

Project Overview

Fredy is a self-hosted real estate finder for Germany. It scrapes German real estate portals (ImmoScout24, Immowelt, Immonet, Kleinanzeigen, WG-Gesucht, etc.), deduplicates results across providers, and sends notifications via Slack, Telegram, Email, Discord, ntfy, etc. It includes a React web UI and a built-in MCP server for LLM access to listings data.

  • Node.js >= 22, ESM-only ("type": "module")
  • Default port: 9998, default login: admin / admin
  • SQLite via better-sqlite3 (synchronous - all DB ops are sync; only network I/O is async)

Commands

# Development
yarn run start:backend:dev    # nodemon backend
yarn run start:frontend:dev   # Vite dev server (proxies /api → :9998)

# Production
yarn run start:backend        # NODE_ENV=production node index.js
yarn run build:frontend       # vite build → ui/public/

# Tests
yarn test                     # Live tests (hits actual providers)
yarn test:offline             # Offline tests using HTML/JSON fixtures (fast, preferred)
yarn test:download-fixtures   # Re-download fresh provider HTML fixtures

# Single test file
TEST_MODE=offline npx vitest run test/provider/immoscout.test.js

# Lint / Format (oxlint + oxfmt, from the oxc toolchain)
yarn lint && yarn lint:fix
yarn format && yarn format:check

# DB migrations
yarn migratedb

Architecture

Core data flow

index.js (startup)
  ├── runMigrations()
  ├── getProviders()            # lazily imports lib/provider/*.js
  ├── similarityCache.init()    # preloads hash cache from DB
  ├── api.js                    # starts fastify HTTP server
  └── initJobExecutionService() # registers event-bus listeners + starts scheduler

scheduler (every N minutes) or manual trigger via POST /api/jobs/:id/run
  └── FredyPipelineExecutioner.execute()
      1. queryStringMutator(url)           # inject sort-by-date param
      2. provider.getListings()            # API or Puppeteer+Cheerio, once per result page the job reads
      3. provider.normalize(listing)       # raw → ParsedListing
      4. provider.filter(listing)          # blacklist + required fields
      5. filter to hashes not yet in DB; for price-tracked providers, a stored row with the same
         link is the same advert at a new price: price change notification, not a new listing
      6. provider.fetchDetails()           # optional enrichment
      7. geocodeAddress()                  # optional lat/lng
      8. storeListings()
      9. similarityCache.checkAndAddEntry() # cross-provider dedup (exact hash, then fingerprint)
      10. _filterBySpecs() + _filterByArea()
      11. notify.send()                    # fan-out to all adapters

Plugin systems

Providers (lib/provider/*.js) - each module exports:

  • metaInformation - { id, name, baseUrl }, plus an optional hosts (every domain the portal serves the same application under, defaulting to baseUrl's host; read by the job form's url check in ui/src/services/jobs/providerUrl.js) and an optional countries (ISO 3166-1 alpha-2, lowercase). Absent means ['de'], which is why no shipped provider declares it and why adding the field changed no existing installation. Resolved in lib/services/providers/: countries.js is the pure half (the default, normalisation, union) and is all the Nominatim client imports, since providerCountries.js reaches for the job storage and would drag SQLite in behind it. The geocoder searches within the resolved countries; the map's maxBounds is the union of their boxes from ui/src/components/map/countryBounds.js. Where no provider exists to ask - home addresses, the listings map, the listing detail - the answer is the union across the jobs the user can see, and where the job form is open it is the providers ticked in it. An optional currency (ISO 4217, absent means EUR) and currencyByHost (the exceptions, for a provider whose national sites price differently) are read once, when the pipeline stores a listing; after that listings.currency is the only source, because comparisons happen in SQL. currency.js in the same directory holds the resolver. A row without one fails on the NOT NULL column by design, so every writer has to set it
  • config - the static ProviderConfig template: requiredFieldNames, crawlContainer, crawlFields, sortByDateParam, normalize(), optional getListings(), fetchDetails(), activityProbe(), and needsBrowser: false on a provider whose search and details never touch the browser (ImmoScout's mobile API, flatfox, the tecnocasa network), so a job run or detail fetch with only such providers starts no Chromium. url is null here and there is no bound filter. A portal whose pages only answer a browser session (DataDome answers node with 403 whether an advert is online or not - immowelt, SeLoger) declares browserActivityProbe(link, browser) and priceTracking.browserProbe(listing, browser) instead; the alive-checker and the price tracker start one browser per run for them, and only when a due listing needs it.
  • createConfig(sourceConfig, blacklist) - returns a fresh ProviderConfig per job run: the template plus this run's url, enabled, and a filter closed over this run's blacklist.
  • pageUrl(url, page) on the static template - how result page N of a search is addressed, so a job's page count reaches the provider. A job reads one page unless its owner raises jobs.paging ({ pages, waitSeconds, jitterSeconds }, NULL = one page, bounds in lib/utils/paging.js). The pipeline owns the walk (_readPages in FredyPipelineExecutioner): it waits the job's wait plus jitter before each further page, stops at a page that brings nothing or nothing new to this run, and ends the walk without a retry when a later page fails. A provider only says how to reach page N and reads one page per call: queryPageUrl(param) in lib/utils/pageUrl.js covers a page number in a query parameter; path schemes (kleinanzeigen seite:N, wg-gesucht's last number, imaxx /page/N/, idealista lista-N.htm) bring their own. A body-driven API reads the page back out of the URL it is handed (leboncoin's offset, bienici's from, the casa/idealista apis). A later page past the end must come back as [], not as an error or as a redirect followed to somewhere else (imaxx redirects to its unfiltered list, so it refuses redirects there). readPages(url, browser), an async iterator, is the alternative for a pager that can only be clicked; no provider needs it today. A provider declaring neither always reads one page, because its answer already is the whole result: tecnocasa, tecnorete, deutscheWohnen and inberlinwohnen cannot sort by date and walk every page themselves, betterhomes and zvgPortal answer the whole search at once. test/provider/providerPaging.test.js keeps that list, so a new provider has to choose. /api/jobs/provider reports pagesConfigurable per provider for the job form.
  • Optional fetchListingByUrl(url, browser) on the static template - reads one advert's page into a complete ParsedListing, or null when the page is no single advert or could not be read. It is what "Add listing" in the listings view calls. Build the provider's own search-card shape from the exposé and pass it through its normalize, so link and hash come out as a search run would produce them: a later run of the job recognises the stored row by both, and a different spelling stores the advert twice. The /api/jobs/provider response carries addByUrl per provider so the dialog can say "not supported yet" before anything is sent.

Providers are stateless. Nothing run-specific may live at module scope: two jobs can execute concurrently (a manual run started while the scheduler is working), and shared mutable state let the second job overwrite the first one's URL and blacklist mid-run, storing listings under the wrong job. The same rule is why the Cheerio parser builds its document inside parse() instead of keeping a module-level $.

Notification adapters (lib/notification/adapter/*.js) - each exports:

  • config - { id, name, description, fields } (drives the UI form)
  • send({ serviceName, newListings, notificationConfig, jobKey, baseUrl })
  • Loaded dynamically at startup via fs.readdirSync

Field definitions carry two optional flags that the UI and the API read declaratively, so neither needs per-adapter code:

  • secret: true - a credential. Never serialised to anyone who may not edit the channel, and masked in the form. Every token, password, API key and webhook URL must carry it.
  • target: true - the one field naming the destination. Drives the "Destination" column.
  • generated: true - Fredy creates the value, the user never types it (the rss adapter's feed token). settleGeneratedFields in lib/services/security/adapterFields.js fills it on create and whenever a save sends it empty, and otherwise keeps the stored value, whatever the client sent. The form shows it masked and, with urlPath, copies it as a url on Fredy's own origin.

The rss adapter is the one adapter nobody is pushed to: it keeps each notification as a row in notification_feed_item (lib/services/storage/notificationFeedStorage.js), and the public route GET /api/feed/:token (lib/api/routes/feedRouter.js, outside authHook) serves the channel's latest 100 as RSS 2.0. The token in the path is the only credential, since feed readers cannot sign in.

An adapter configuration is separate from the adapter itself: it is a row in configured_adapter ("a notification channel" in the UI) that many jobs can reference.

Key services

Service Location Notes
Event bus lib/services/events/event-bus.js Plain EventEmitter; events: jobs:runAll, jobs:runOne, jobs:status
SSE broker lib/services/sse/sse-broker.js Per-userId Set<ServerResponse>; heartbeat every 25s; pushes job status to UI
Similarity cache lib/services/similarity-check/ Per-job dedup, refreshed hourly. Two tiers: an exact SHA-256 over jobId|title|price|address, then listingFingerprint.js, which matches the same flat across different providers on living space, rooms and location. Portals never agree on the headline, the address format, or what "price" means, so the hash tier alone never fired across providers. Holds only listings still on the market (not hidden, is_active not 0): deactivateListings evicts, reactivateListings adds back, and hard deletes skip rows the cache does not hold. An inactive row left in there swallowed the same flat re-listed on another portal. The pipeline hides duplicates with hideAsDuplicates (listings.hidden_as_duplicate), and deactivating a listing brings back the hidden copy that looked like it, unless another listing still online does too. Rows the user hid never come back this way
Notification channels lib/services/storage/configuredAdapterStorage.js Saved adapter configurations (configured_adapter). Jobs store [{configuredAdapterId}]; jobStorage hydrates those back into {id, name, fields} on every read, so the pipeline never sees the indirection. Who may use vs. edit a channel: lib/services/security/channelAccess.js
SqliteConnection lib/services/storage/SqliteConnection.js Singleton, WAL mode; execute(), query(), withTransaction()
Migrations lib/services/storage/migrations/ Numbered JS files each exporting up(db); checksum-tracked in schema_migrations
Extractor lib/services/extractor/ Orchestrates Puppeteer + Cheerio; shared browser instance per job
Browser engine lib/services/extractor/browserEngine.js Which stealth Chromium runs: Clearcote's open build (no key, any number of browsers) on linux-x64, win32-x64 and darwin-arm64, driven through serve() + puppeteer.connect; CloakBrowser everywhere else, Linux arm64 above all. CloakBrowser stays on 0.6.x: from 0.7 every user needs a licence key and a free one allows one browser at a time, enforced by the binary. The Dockerfile repeats the platform rule with uname -m
Listing documents lib/services/storage/listingAttachmentsStorage.js Uploaded exposés (listing_attachments), bytes and all. Type and filename guards in lib/services/listings/attachmentTypes.js; routes in lib/api/routes/listingAttachmentsRouter.js
Adding a listing by URL lib/services/listings/manualListingService.js POST /api/listings. Resolves the provider by exact host (resolveProviderForUrl in lib/services/jobs/providerUrl.js, mirrored in the UI copy), reads the advert with fetchListingByUrl, then runs FredyPipelineExecutioner.ingest(): the tail of a run (geocode, store, distances, similarity entry, picture, benchmark, scam check, travel times) without the filters and without a notification. The listing is stored under a job the user picks, so everything keyed on the job applies to it; listings.added_manually marks it, written on insert only
Listing pictures lib/services/storage/listingMediaStorage.js First picture as WebP bytes, the rest of the gallery as deflated urls (listing_media). Download and shrinking in lib/services/listings/listingPictures.js (sharp), background queue in previewCaptureQueue.js, served by GET /api/listings/:id/image

Uploaded documents live in the database

The exposé a user attaches to a listing is a BLOB in listing_attachments, not a file next to listings.db. Fredy usually runs in a container whose filesystem is discarded, and the only thing users are told to persist is the /db volume, so the database is the one place uploaded bytes are already safe. Three things follow from that for free, and all three would otherwise be code:

  • Backups already carry them, because backupRestoreService copies the whole database.
  • foreign_keys = ON plus ON DELETE CASCADE disposes of them exactly when the listing goes - retention purge, deleted job, manual hard delete, all of them, none of which know this table exists. Files would need an unlink in each of those paths plus a sweeper for the ones missed.
  • There is no filename that can escape anywhere, because no filename ever reaches a filesystem.

The one thing that is not free is the size, hence the two admin settings (listingAttachmentMaxMb, listingAttachmentMaxPerListing) and the rule that nothing reading attachment metadata may SELECT *.

Uploading also exempts a listing from purgeExpiredInactiveListings, alongside the watch list. Preserving a record of an ad that has been taken down is the point of the feature, so deleting it on a timer would delete exactly what the upload was for.

The type stored on a row comes from the file's magic bytes, never from the Content-Type the browser sent, because these files are served back from Fredy's own origin: a renamed .html getting through would be stored cross-site scripting. Responses carry nosniff, and only images go out inline.

Listing pictures live in the database too

The browser used to load listings.image_url straight from the portal's CDN, so a listing's picture disappeared the day the portal took the advert down. Now the first picture is kept as bytes in listing_media, for the same reasons the exposés are (see above): the /db volume is what users persist, backups carry it, and the cascade disposes of it on every path a listing can leave by.

  • First picture: bytes, small. Downloaded once, scaled to at most 800px and re-encoded as WebP q75 with sharp, typically 30 to 70 KB. Where re-encoding would not shrink it, the original is kept. A platform without a sharp build keeps the portal's bytes up to 512 KB instead.
  • Every further picture: urls, deflated. The gallery a provider already loaded (listing.images, see lib/utils/listingImages.js) costs no request, and twenty urls of one listing differ in little but an id, so they deflate to about a quarter of their JSON. Bytes for twenty pictures would be a megabyte per listing.
  • Its own table. The overview and detail reads select l.*, so a BLOB column on listings would ride along on every page. preview is the table's last column, and nothing may SELECT * from it.
  • Never on the critical path. The pipeline queues the capture after the area filter and does not wait for it (previewCaptureQueue.js, two downloads at a time); a notification is never late because a CDN is slow. A failed download is recorded and not retried for 24 hours.
  • Backfill by looking. Every <img> in the interface points at GET /api/listings/:id/image (listingPictureSrc in ui/src/services/listings/listingPictures.js). With bytes kept it serves them; otherwise it redirects to the portal, which is exactly what the browser did before, and queues the capture so the next request finds them. Nothing walks the old listings.
  • The download is guarded like the MCP photo tool's, which now shares it: every redirect hop has to pass isPubliclyFetchableUrl, and the stored type comes from the magic bytes (JPEG, PNG, GIF, WebP only), served with nosniff, because these bytes are third-party content on Fredy's origin.

A manual detail refetch stores the gallery the detail page carried, which is how a listing found before galleries were kept gets one.

Frontend

  • React 19 SPA, Vite build → ui/public/ (served as static by backend)
  • State: Zustand single store with per-domain slices
  • UI library: @douyinfe/semi-ui
  • Map: MapLibre GL + @mapbox/mapbox-gl-draw + @turf/boolean-point-in-polygon for GeoJSON polygon filters
  • In dev: Vite proxies /api to :9998

Theming (light and dark)

The interface ships two themes. Which one an account gets is a user setting like language, stored in the settings table under theme and served from /api/user/settings.

The whole switch is one attribute on <body>:

<body theme-mode="dark">   <body theme-mode="light">

Semi UI already keys its own component styles off body[theme-mode=dark], and Fredy hangs its palette off the same attribute, so setting it repaints both at once and nothing has to re-render for the CSS to follow.

The two palettes live in ui/src/themes.less, and nowhere else. That file has exactly two blocks - :root for dark, body[theme-mode='light'] for light - and it is the only stylesheet in the app allowed to contain a colour literal. Both blocks are complete rather than one plus a set of overrides: a token added to one and forgotten in the other inherits whatever the first theme left behind, and nothing looks wrong until someone switches. test/ui/theme.test.js fails the build on both mistakes - a token missing from a block, and a colour literal appearing in any other stylesheet.

ui/src/tokens.less is the layer everything else styles against. Every @color-* there is a thin alias onto a custom property (@color-surface: var(--f-surface)), which is what makes a theme switchable at all - a Less variable holding a hex is resolved at build time and can never be anything else at runtime. Two consequences when adding to it:

  • Less colour functions (fade, darken, lighten) cannot operate on a custom property. A colour that needs an alpha variant needs its channels published as well; those are the -rgb aliases, used as rgb(@color-accent-rgb / 20%).
  • tokens.less must stay free of rules. Roughly forty stylesheets import it, and anything that emits CSS from there is emitted forty times. themes.less is imported once, from Index.less.

Where the choice comes from. The settings table, and nowhere else. theme.js caches nothing

  • no localStorage, no cookie - and test/ui/theme.test.js fails if one is reintroduced. A user setting has one home, and a second copy is a second answer waiting to disagree with it.
  1. index.html ships <body theme-mode="dark">, which is DEFAULT_THEME. That covers the login screen and the moment a cold load spends fetching settings; the app renders nothing until they land, so all that is on screen is a background in the default.
  2. App.jsx reads userSettings.settings.theme straight off the store and applies it. Before the settings arrive that selector is undefined, which normalises to the default already painted, so nothing repaints.
  3. PreferencesPage writes through actions.userSettings.setTheme, which POSTs to /api/user/settings/theme and updates the store; the repaint happens through step 2, so a theme picked in the form and one arriving on login take the same path.

Things CSS cannot switch, and how they are handled. Two kinds:

  • Canvas. Charts are painted onto a canvas and keep whatever they were last painted with, so chartTheme.js reads its colours from the custom properties through getters when a chart is built. The theme is only switched on the preferences page, where no chart is on screen, so every chart is built after the switch. Nothing is remounted for it: <Layout> used to be keyed on the theme, and that threw away whatever had been typed on the page and not saved. A chart placed where the theme can change would have to be keyed on the theme itself. Never reintroduce a hardcoded hex there - the file used to carry a hand-maintained copy of the palette and it is gone.
  • Assets. The wordmark has a light and a dark cut, and no custom property can swap a PNG. Logo reads the theme from the store, as App.jsx does, so a switch re-renders it. Everything expressible as a colour should use the tokens and let CSS do the work.

Colours that are legitimately literal: scrims and hairlines drawn over listing photography, which stays photography in both themes; #000 used as a mask stencil; white on the accent, which is dark red either way; and MapLibre paint and marker colours (ui/src/components/map/overlayLayers.js, darkBasemapPaint.js, markerColors.js), because a map layer or marker takes a colour string and cannot read a custom property. Anything drawn in HTML around the map (legend, badges) still uses the tokens.

The map follows the theme. The vector basemap is OpenFreeMap's bright style in the light theme and its dark style in the dark theme; satellite imagery is the same in both (isDarkBasemap in ui/src/components/map/Map.jsx). The overlays carry one paint set per basemap (OVERLAY_PAINT.light and .dark), and the canvas is dimmed on a bright basemap and lifted on the dark one.

Tracking. Switching theme fires CHANGE_THEME_DARK or CHANGE_THEME_LIGHT. A tracking event carries a feature name and nothing else (trackPoi sends one string), so any value worth reporting has to be part of the name - which is why there is a POI per theme rather than one for the setting. It fires on the transition only: re-saving the theme you are already on, including the first-ever save of dark by an account that was on the dark default, is not somebody changing theme.

Contrast is not a matter of taste here: the light accent is two steps darker than the dark one (#b04a3f against #c0564a) because the dark red that carries white text at 4.5:1 on near-black falls below AA against paper, and every primary button in the app depends on it.

MCP server

Two transports:

  1. stdio (lib/mcp/stdio.js) - for Claude Desktop/LM Studio; opens its own DB connection (main process need not be running)
  2. HTTP (/api/mcp) - authenticated via Bearer token (mcp_token column in users table)

Read tools: list_jobs, get_job, list_listings, get_listing, get_photo_for_listing, get_application_letter, calculate_financing, get_current_date_time, plus the administration reads list_channels, list_adapters, get_user_settings. Write tools: add_listing_note, set_listing_notes, watch_listing, unwatch_listing, the four that create a job (start_job_draft … discard_job_draft), and the administration writes - run_job/run_all_jobs (queued on the event bus, so they answer "not running" over stdio, where no execution service is attached), set_job_enabled, update_job (an edit runs the interview's own validation over the stored job as the draft, preserves the drawn area filter, refuses anything that would leave the job without name, search, deal type or channel, and is then stored through saveJob like a form save), delete_job, create_channel/update_channel/delete_channel/test_channel (channel secrets are never serialised back, so update_channel merges the fields it is sent instead of replacing the bag as the web route does; unknown field names and empty required ones are refused by the save both use; delete_channel names the jobs still using it), set_listing_status (watches the listing, as the web route does), add_listing_by_url (the manualListingService, imported on call so the stdio server does not load the browser stack), delete_listing (soft by default, hard: true for the row, which also finds a listing already hidden), and update_user_settings (language, theme, home addresses through the shared homeAddressService, and the finance and applicant profiles merged key by key into what is stored, which get_user_settings shows in full). The rule behind those choices: a model can only change what it can read back, so every list a tool replaces whole is shown in full by the matching read tool (get_job prints each search URL), and what a model cannot be shown, or would only change part of, is merged. The REST routes and the MCP tools call the same services for every change - jobService.js (run, switch, delete, save), channelService.js (list, save, delete, test), listingActionService.js (status, notes, watch, delete), userSettingsService.js and homeAddressService.js (settings), manualListingService.js (add by URL). All but the last answer a refusal as { ok: false, reason, error, code? } (lib/services/serviceResult.js): a route answers it with sendFailure, which maps reason to a status code through httpStatusOf, and a tool turns error into its answer and may add a hint by code. manualListingService.js predates that shape and answers with a status, which each caller words for itself. The one thing a home-address save does that the MCP tool does not is the geocoding retry sweep (#418): it stays in the /home-address route, because the stdio server is a second process with a Nominatim throttle and backoff of its own. A rule goes into the service, never into one caller. What differs between the two callers is passed in as an option (mergeFields, mergeProfiles) or stays in the tool (confirmation, dryRun checks before it, answers for a model). Responses are Markdown via lib/mcp/mcpNormalizer.js.

Each user can switch the server off, or single tools, under Settings → MCP server (user setting mcp_server, { enabled, disabledTools }, read through lib/mcp/mcpUserSettings.js). authenticateToolCall enforces both on every call; applyMcpToolSettings trims tools/list per request. The settings page gets its tool list from GET /api/user/mcp-server, which reads it off the registered tools (mcpToolCatalog), so a new tool needs no UI change. Register tools through server.tool() inside createMcpServer: that is what records them.

Job creation is a draft-based interview, not a single call: lib/mcp/jobDraftStore.js holds the state (in memory, per user, 30 min) and computes the next question; lib/mcp/jobDraftContext.js is the only part that reads the database and is what strips channel secrets. Write tools go through authenticateWriteToolCall, which also enforces the mcp:write OAuth scope and refuses non-admins while demo mode is on.

Key Conventions

  • ESM only - import/export everywhere, no CommonJS
  • JSDoc typedefs (no TypeScript) in lib/types/ - listing.js, job.js, filter.js, providerConfig.js
  • Lint / format - oxlint (.oxlintrc.json) and oxfmt (.oxfmtrc.json), both from the oxc toolchain. There is no ESLint and no Prettier; eslint-disable comments still work because oxlint reads them
  • Copyright header required on all .js files - enforced by lint-staged pre-commit hook via copyright.js
  • NoNewListingsWarning (lib/errors.js) is used as control flow to short-circuit the pipeline (not an error)
  • Test fixtures in test/testFixtures/ - HTML/JSON snapshots per provider; TEST_MODE=offline mocks puppeteerExtractor and global fetch via test/offlineFixtures.js
  • conf/config.json is the only runtime config file; created with defaults if missing

Coding

  • After building the task, run the linter
  • After building the task, run the tests
  • New features must be tested
  • New features must be properly documented with JsDoc
  • You do not commit any changes, you do not create a new branch unless I told you so