Skip to Content
JobWzrd Docs

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:

LayoutRoutes
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.tsx picks the implementation once at module load (backendOn()).
  • demo.ts holds 12 service interfaces and their pure offline twins; http.ts is the live twin. A capability = interface + demo + http + store + contract entry.
  • services/api.ts owns apiFetch (prefixes /api/v1, sends credentials: 'include', adds Idempotency-Key, maps errors through toUserMessage), SAME_ORIGIN_API, isHttpsApiUrl (plaintext refused except loopback), and newIdempotencyKey.

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.mjs enforces one <title>, description, canonical and og:title per page.
  • Inline scripts are SHA-256 pinned in app/public/_headers → regenerated into backend/src/generated/assetHeaders.ts by backend/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) and src/features/marketing/metadata.ts for /.

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:

  1. sweepExpired — sessions/tokens/upload intents
  2. sweepLogBuffer — diagnostic buffer → ops_log_events
  3. sweepTables — retention (platform/retention.ts, bounded pages, remaining: true)
  4. reclaimExpired — stale ops_worker_tasks (30 min, 3 strikes fail closed)
  5. sweepDispatch — the outbox/dispatch ledger
  6. pollReplies — 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

PathFilesWhat lives there
src/index.ts1the three entry points above
src/http/8transports.ts (uploads vs assets vs API), static.ts, router.ts, auth.ts, protocol.ts (envelope), respond.ts (ok/fail), idempotency.ts
src/http/routes/16one module per origin: account, applications, companies, config, health, inbox, jobs, logs, outreach, profile, resumes, searches, sources, staging, usage, worker
src/features/account/5ensure (owner bootstrap), config (automation flags), consent (4 gates), apiKeys, erasure
src/features/jobs/19query, ingest, reservation, searches, scrapeQueue/run, workerTasks/Ingest, reclaim, cancel, dlq, dispatch, library (import), savedJobs, rank, jobTools, boardConfig, retention, sourceCatalogue
src/features/outreach/7targets, discover, drafts, sends, send (the money step), accounts, assistant
src/features/inbox/3replies, poller (cron), notifications
src/features/companies/5directory, enrich, providers, ycSource, logs
src/features/profile/3profile, enrich (prompt 07), avatar
src/features/resume/3resume (upload/download), pipeline (bytes→text→links→dossier), links
src/features/applications/1track.ts — a tracker, never a submitter
src/features/usage/1the daily-cap read the Dashboard shows
src/features/ops/1log ingest + read
src/platform/21the only layer allowed to touch the world (see §3.6)
src/platform/email/5gmail, mime, tokens, upstream, resend
src/lib/4 groupspure helpers: ai/ (prompts + provider types), jobs/ (canonical, keyword, identity, tools), net/ (safeFetch, urlSafety), outreach/ (prompts, parsing, targeting, drafting, replies), profile/
src/generated/assetHeaders.ts1CSP + 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)

  1. Classify. /api/v1/uploads/* (10 MB cap) → upload transport; /api/* → router; anything else → static.ts.
  2. Throttle. clientBudget — anonymous per-client bucket, 30/min auth surface, 120/min public, sha256(salt ‖ address), fails open.
  3. Authenticate. http/auth.ts returns a Principal:
    • owner — Better Auth session cookie (browser) or x-api-key (services, hashed at rest);
    • service — x-service-token for one surface, compared with timingSafeEqual.
  4. Authorise. Each Route declares auth: "public" | "owner" | "service" | "service:<surface>". A surface mismatch is SERVICE_FORBIDDEN, not a 401.
  5. Idempotency. For mutating routes with a key: the lookup precedes any cap charge.
  6. Handle. Feature code, with withPrimary (owner-scoped), withSystem (platform rows with a nullable owner) or withCorpus (the job corpus) as its only DB access.
  7. Respond. protocol.ts builds the envelope; respond.ts serialises it with a requestId. Codes are closed: INVALID_INPUT, UNAUTHORIZED, NOT_FOUND, CAP_REACHED, STATE_CONFLICT, RATE_LIMITED, UPSTREAM_ERROR, SERVICE_FORBIDDEN.
  8. 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.

ConcernImplementation
Tablesauth_user, auth_session, auth_account, auth_verification (Better Auth modelName mapping)
Browser sessionfirst-party cookie; Authorization: Bearer <session token> is also accepted, but it is a session token verified by getSession, not a JWT
Email + passwordon; reset flow registered only when a mail transport exists
Resetone-hour token, every session revoked on success; deliverAuthEmail → Resend first, then the bridge
Verificationsame seam, different copy
GooglesocialProviders.google only when the client id/secret/redirect are present
Gmaila separate google-gmail provider carrying gmail.readonly + gmail.send; accounts are linked, never aliased
Dev onlygoogle-test provider with the same identity scopes for local runs
Trusted originsALLOWED_ORIGINS (comma-separated env) → trustedOrigins(env); empty when unset, which refuses every cross-origin call rather than widening it

Who can call what

CredentialScopeWhere it lives
session cookiethe owner's own rowsbrowser, credentials: 'include'
x-api-keythe owner, one key per user (D-13-4)api_keys, hashed
x-service-tokenone surface: scrape, apply, ai, email_sync, exportWorker secret, per surface, fails closed
Gmail refresh tokenone linked accountBetter 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

StoreBindingRule
D1DBthe 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
R2BLOBrésumés, avatars, exports, YC snapshot. Keys are owner-scoped (u/<owner>/…); never swept (D-GAP-1)
KVCATALOGUEone read: the source catalogue cache. Never a job store
QueuesSCRAPE_QUEUE_MINIZRD, SCRAPE_QUEUE_JOBINDIEone 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 AIAIoptional 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)

ModuleResponsibility
env.tsthe only reader of bindings
db.ts / dbBudget.tsD1 access + the one statement that spends a client's minute
limits.tsthe caps — one implementation, two numbers (5 / 50)
auth.tsBetter 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.tsprovider resolution, reservations, tool-calling seam
queue.ts / retention.ts / storage.ts / kv.tsqueues, bounded sweeps, R2, catalogue cache
scraperClient.tsthe only code that calls minizrd/jobindie
log.ts / logStore.ts / logMask.ts / actor.ts / trace.tsone log line shape, masking, pseudonymous-but-linkable actors, W3C trace context
clientBudget.ts / rateWindow.tsthrottle + minute windows
documents.tsthe document→text seam

3.7 Static assets, hosts, and the quirks that bite

  • env.ASSETS.fetch is the export; assetHeaders() adds CSP + cache-control (immutable for /_next/static/ and /assets/).
  • A miss falls back to the export's 404.html with 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.html and /status/index.html with 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 surfacePathBackend
Jobs board/jobs, /jobs?searchId=…, /jobs/importfeatures/jobs/{query,library}
AI rank/jobs/ranked/aifeatures/jobs/rank
Searches/searches, /searches/list, /searches?searchId=…features/jobs/searches
Sources/sourcesfeatures/jobs/sourceCatalogue
Applications/applications, /applications/advancefeatures/applications/track
Outreach/outreach/{targets,recruiters,drafts,sends,send,send/resolve,accounts,accounts/switch,discover,assistant}features/outreach/*
Inbox/inbox/replies, /inbox/notificationsfeatures/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-urlfeatures/resume/*
Logs/logsfeatures/ops/logs
Usage/caps/usagefeatures/usage/usage
Config/configfeatures/account/config
ErasureDELETE /accountfeatures/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

FactValue
handlers / path strings65 / 59 (contract: 58 paths)
route modules16
tables63 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)
migrations29 files, 28 applied (ledger)
backend tests534 in 54 files
app tests296
queue batch size1
worker lease30 min reclaim, 3 strikes fail closed
cron*/15 * * * *

3.10 What "add a capability" costs, end to end

  1. features/<domain>/ module + a Route in http/routes/.
  2. A contract entry only if the wire changes — and the YAML is frozen, so that is an ADR, not a commit.
  3. App: service interface + demo impl + http impl + store member + the page that uses it.
  4. A test that fails when the field stops flowing, and an app/readme/<page>.md update.

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.

On this page