Architecture
How a click becomes a row in D1, and what may talk to what — app and backend.
Current as of 2026-11-25, verified against backend/src at HEAD. The pre-Cloudflare
descriptions in Readme/SYSTEM-DESIGN.md and Readme/Old Docs/* describe Convex +
Bearer JWT and are historical; this file is the live system.
1. Topology
┌──────────────────────────────────────────────────┐
browser ────────────► │ Cloudflare Worker (backend/) │
│ index.ts fetch · queue · scheduled │
│ transports.ts → static.ts | router.ts | uploads │
│ http/auth.ts cookie · x-api-key · x-service-token
│ features/ → platform/ → lib/ (one direction) │
└───┬─────────┬──────────┬─────────┬──────────────┘
│ │ │ │
D1 (63) R2 blobs KV cache Workers AI
│
┌───────────────────┴──────────────────────────────────────────┐
│ outbound, one credential per surface: │
│ minizrd (Go :8120) · jobindie (Rust :8121) · proxy-gateway │
│ Gmail API · Resend / mail bridge · AI provider (local/OWUI/Groq)
└──────────────────────────────────────────────────────────────┘One hostname family, one Worker (D-13-1): jobwzrd.com, www., api., admin.,
status. are Worker routes from wrangler.jsonc. Pages is not in the request path.
Static assets are answered by the Worker (run_worker_first: true) so /api/* and
SPA routes are decided by code, never by file existence.
2. The app (app/)
Next.js 16 App Router, React 19, TypeScript strict + noUnusedLocals +
noUnusedParameters + exactOptionalPropertyTypes, static export served from the
Worker's ASSETS binding. Three root layouts:
| Layout | Routes |
|---|---|
app/(marketing)/ | / (the landing) and the styled 404 — server-rendered from JSON |
app/(public)/ | /login, /signup, /forgot-password, /reset-password |
app/(app)/ | the 11 authed pages, client-rendered inside shell.tsx |
2.1 The one-way wiring
component ─► store.tsx (the only Context store, 53 members) ─► services/* ─► apiFetch
demo.ts (pure) http.ts (live)- Components never call
fetch, never hold a service, never derive server truth. store.tsxpicks the implementation once at module load (backendOn()).demo.tsholds 12 service interfaces and their pure offline twins;http.tsis the live twin. A capability = interface + demo + http + store + contract entry.services/api.tsownsapiFetch(prefixes/api/v1, sendscredentials: 'include', addsIdempotency-Key, maps errors throughtoUserMessage),SAME_ORIGIN_API,isHttpsApiUrl(plaintext refused except loopback), andnewIdempotencyKey.
2.2 Environment
src/lib/env.ts — one mapping, two shells (browser process.env, Vite-era
import.meta.env). NEXT_PUBLIC_* is read with a literal key (Turbopack inlines
only static access; a computed key becomes undefined and silently disables the
backend). env.test.ts fails if the word convex reappears under src/.
2.3 Head, CSP, metadata
- Static export (
output: 'export');app/scripts/verify-export.mjsenforces one<title>, description, canonical andog:titleper page. - Inline scripts are SHA-256 pinned in
app/public/_headers→ regenerated intobackend/src/generated/assetHeaders.tsbybackend/scripts/sync-web.mjs. Static Assets ignore_headers, so the CSP must travel as code. - Metadata comes from
src/lib/metadata.ts(TITLE_MAX 60, description 50–160) andsrc/features/marketing/metadata.tsfor/.
3. The backend (backend/) — the whole thing
One Worker. 65 handlers over 59 path strings, 16 route modules, 21 platform modules, 11 feature domains, 4 lib groups, 1 generated file.
3.1 Entry points (src/index.ts)
export default {
async fetch(req, env, ctx) // every request: transports.ts decides
async queue(batch, env, ctx) // scrape queues; `-dlq` suffix → dead letters
async scheduled(controller, env) // cron */15: the ordered sweep list
}The cron order is fixed and load-bearing:
sweepExpired— sessions/tokens/upload intentssweepLogBuffer— diagnostic buffer →ops_log_eventssweepTables— retention (platform/retention.ts, bounded pages,remaining: true)reclaimExpired— staleops_worker_tasks(30 min, 3 strikes fail closed)sweepDispatch— the outbox/dispatch ledgerpollReplies— Gmail poll → classify → notifications
A step that throws stops the rest — which is why the dispatch sweep once killed the
poller silently (ops_dispatch_payloads had no id column).
No send ever goes through a queue. A retried Gmail send is a second email.
3.2 Directory map
| Path | Files | What lives there |
|---|---|---|
src/index.ts | 1 | the three entry points above |
src/http/ | 8 | transports.ts (uploads vs assets vs API), static.ts, router.ts, auth.ts, protocol.ts (envelope), respond.ts (ok/fail), idempotency.ts |
src/http/routes/ | 16 | one module per origin: account, applications, companies, config, health, inbox, jobs, logs, outreach, profile, resumes, searches, sources, staging, usage, worker |
src/features/account/ | 5 | ensure (owner bootstrap), config (automation flags), consent (4 gates), apiKeys, erasure |
src/features/jobs/ | 19 | query, ingest, reservation, searches, scrapeQueue/run, workerTasks/Ingest, reclaim, cancel, dlq, dispatch, library (import), savedJobs, rank, jobTools, boardConfig, retention, sourceCatalogue |
src/features/outreach/ | 7 | targets, discover, drafts, sends, send (the money step), accounts, assistant |
src/features/inbox/ | 3 | replies, poller (cron), notifications |
src/features/companies/ | 5 | directory, enrich, providers, ycSource, logs |
src/features/profile/ | 3 | profile, enrich (prompt 07), avatar |
src/features/resume/ | 3 | resume (upload/download), pipeline (bytes→text→links→dossier), links |
src/features/applications/ | 1 | track.ts — a tracker, never a submitter |
src/features/usage/ | 1 | the daily-cap read the Dashboard shows |
src/features/ops/ | 1 | log ingest + read |
src/platform/ | 21 | the only layer allowed to touch the world (see §3.6) |
src/platform/email/ | 5 | gmail, mime, tokens, upstream, resend |
src/lib/ | 4 groups | pure helpers: ai/ (prompts + provider types), jobs/ (canonical, keyword, identity, tools), net/ (safeFetch, urlSafety), outreach/ (prompts, parsing, targeting, drafting, replies), profile/ |
src/generated/assetHeaders.ts | 1 | CSP + cache headers, generated by scripts/sync-web.mjs |
Import direction is enforced by a test: http → features → platform → lib, never
backwards. A lib/ file may not import http/, features/ or platform/.
3.3 Request pipeline (http/transports.ts → router.ts)
- Classify.
/api/v1/uploads/*(10 MB cap) → upload transport;/api/*→ router; anything else →static.ts. - Throttle.
clientBudget— anonymous per-client bucket, 30/min auth surface, 120/min public,sha256(salt ‖ address), fails open. - Authenticate.
http/auth.tsreturns aPrincipal:owner— Better Auth session cookie (browser) orx-api-key(services, hashed at rest);service—x-service-tokenfor one surface, compared withtimingSafeEqual.
- Authorise. Each
Routedeclaresauth: "public" | "owner" | "service" | "service:<surface>". A surface mismatch isSERVICE_FORBIDDEN, not a 401. - Idempotency. For mutating routes with a key: the lookup precedes any cap charge.
- Handle. Feature code, with
withPrimary(owner-scoped),withSystem(platform rows with a nullable owner) orwithCorpus(the job corpus) as its only DB access. - Respond.
protocol.tsbuilds the envelope;respond.tsserialises it with arequestId. Codes are closed:INVALID_INPUT,UNAUTHORIZED,NOT_FOUND,CAP_REACHED,STATE_CONFLICT,RATE_LIMITED,UPSTREAM_ERROR,SERVICE_FORBIDDEN. - Log. One line per request into the diagnostic buffer;
side_effect: none|possible|confirmed. Logging never fails the operation it describes.
3.4 Authentication, in full
src/platform/auth.ts — Better Auth, configured for this Worker.
| Concern | Implementation |
|---|---|
| Tables | auth_user, auth_session, auth_account, auth_verification (Better Auth modelName mapping) |
| Browser session | first-party cookie; Authorization: Bearer <session token> is also accepted, but it is a session token verified by getSession, not a JWT |
| Email + password | on; reset flow registered only when a mail transport exists |
| Reset | one-hour token, every session revoked on success; deliverAuthEmail → Resend first, then the bridge |
| Verification | same seam, different copy |
socialProviders.google only when the client id/secret/redirect are present | |
| Gmail | a separate google-gmail provider carrying gmail.readonly + gmail.send; accounts are linked, never aliased |
| Dev only | google-test provider with the same identity scopes for local runs |
| Trusted origins | ALLOWED_ORIGINS (comma-separated env) → trustedOrigins(env); empty when unset, which refuses every cross-origin call rather than widening it |
Who can call what
| Credential | Scope | Where it lives |
|---|---|---|
| session cookie | the owner's own rows | browser, credentials: 'include' |
x-api-key | the owner, one key per user (D-13-4) | api_keys, hashed |
x-service-token | one surface: scrape, apply, ai, email_sync, export | Worker secret, per surface, fails closed |
| Gmail refresh token | one linked account | Better Auth auth_account; referenced by pointer only (better-auth:account:<id>), refreshed in-action, never written |
Gates before money. claimDraftForSend refuses unless user_preferences.outreach_enabled;
applications.create refuses unless applicationAutomationEnabled. A missing
preference row fails closed and charges nothing. Four consent gates live in
features/account/consent.ts.
3.5 Storage
| Store | Binding | Rule |
|---|---|---|
| D1 | DB | the only durable truth. Three access helpers: withPrimary (owner), withSystem (nullable owner, platform only), withCorpus (shared job corpus). Every RETURNING goes through all() because node:sqlite's run() discards rows |
| R2 | BLOB | résumés, avatars, exports, YC snapshot. Keys are owner-scoped (u/<owner>/…); never swept (D-GAP-1) |
| KV | CATALOGUE | one read: the source catalogue cache. Never a job store |
| Queues | SCRAPE_QUEUE_MINIZRD, SCRAPE_QUEUE_JOBINDIE | one message = one (search_id, source_id); max_batch_size = 1; consumeScrapeBatch (features/jobs/scrapeQueue.ts) handles the live batch, consumeDeadLetterBatch (features/jobs/dlq.ts) the -dlq one — routed by queue name, never by body shape |
| Workers AI | AI | optional provider; the seam in platform/ai.ts prefers local → Open WebUI → Groq |
3.6 What each platform module owns (the "may touch the world" list)
| Module | Responsibility |
|---|---|
env.ts | the only reader of bindings |
db.ts / dbBudget.ts | D1 access + the one statement that spends a client's minute |
limits.ts | the caps — one implementation, two numbers (5 / 50) |
auth.ts | Better Auth + auth mail delivery |
email/{gmail,mime,tokens,upstream,resend} | Gmail transport, RFC 5322 by hand, token reads, one poll of one mailbox, Resend |
ai.ts / aiBudget.ts / aiTools.ts | provider resolution, reservations, tool-calling seam |
queue.ts / retention.ts / storage.ts / kv.ts | queues, bounded sweeps, R2, catalogue cache |
scraperClient.ts | the only code that calls minizrd/jobindie |
log.ts / logStore.ts / logMask.ts / actor.ts / trace.ts | one log line shape, masking, pseudonymous-but-linkable actors, W3C trace context |
clientBudget.ts / rateWindow.ts | throttle + minute windows |
documents.ts | the document→text seam |
3.7 Static assets, hosts, and the quirks that bite
env.ASSETS.fetchis the export;assetHeaders()adds CSP +cache-control(immutable for/_next/static/and/assets/).- A miss falls back to the export's
404.htmlwith a 404 status — never a 200 carrying an error page. www.→ 301 apex;admin.bare visit → 302/logs;status.→/status/in the same bundle (one deploy).- Static Assets answer
/404.htmland/status/index.htmlwith 307s — request the directory form, not the filename. - HTML answers
no-cache; hashed assets answer immutable.
3.8 How the app meets the backend (the wiring map)
apiFetch prefixes /api/v1; these are the 34 relative paths app/src/services/http.ts
actually uses today, and the module that answers each.
| App surface | Path | Backend |
|---|---|---|
| Jobs board | /jobs, /jobs?searchId=…, /jobs/import | features/jobs/{query,library} |
| AI rank | /jobs/ranked/ai | features/jobs/rank |
| Searches | /searches, /searches/list, /searches?searchId=… | features/jobs/searches |
| Sources | /sources | features/jobs/sourceCatalogue |
| Applications | /applications, /applications/advance | features/applications/track |
| Outreach | /outreach/{targets,recruiters,drafts,sends,send,send/resolve,accounts,accounts/switch,discover,assistant} | features/outreach/* |
| Inbox | /inbox/replies, /inbox/notifications | features/inbox/* |
| Companies | /companies/{enrich,reconcile,logs} | features/companies/* |
| Profile | /profiles/avatar(+upload-url), /profiles/me/enrich(/paste) | features/profile/* |
| Résumés | /resumes, /resumes/me, /resumes/upload-url | features/resume/* |
| Logs | /logs | features/ops/logs |
| Usage/caps | /usage | features/usage/usage |
| Config | /config | features/account/config |
| Erasure | DELETE /account | features/account/erasure |
Everything else in the contract (/worker/*, /staging/*, /health, /api/auth/*)
is called by machines or by Better Auth, not by the app.
3.9 Numbers worth remembering
| Fact | Value |
|---|---|
| handlers / path strings | 65 / 59 (contract: 58 paths) |
| route modules | 16 |
| tables | 63 in production D1 — 57 product + 4 Better Auth + ops_migrations + Cloudflare's _cf_KV (the migrations contain 64 CREATE TABLEs; three _new rebuild shadows exist only mid-migration) |
| migrations | 29 files, 28 applied (ledger) |
| backend tests | 534 in 54 files |
| app tests | 296 |
| queue batch size | 1 |
| worker lease | 30 min reclaim, 3 strikes fail closed |
| cron | */15 * * * * |
3.10 What "add a capability" costs, end to end
features/<domain>/module + aRouteinhttp/routes/.- A contract entry only if the wire changes — and the YAML is frozen, so that is an ADR, not a commit.
- App: service interface + demo impl + http impl + store member + the page that uses it.
- A test that fails when the field stops flowing, and an
app/readme/<page>.mdupdate.
Anything less leaves the app calling an endpoint that answers NOT_FOUND, which is
exactly what the wiring pass (milestone v3.0 W2) checks page by page.