Skip to content

Architecture Overview

Claude edited this page Nov 12, 2026 · 7 revisions

Checked against v0.7.6 on November 13, 2026.

Architecture overview

How Kestrel is put together and how one job posting moves through it. For setup, checks and commit rules, see Contributing.

Kestrel is a single-user desktop application. One Python process holds a FastAPI web app, a background worker, a scheduler and a SQLite database. The window is a web view pointed at that app.

The specs in the repository are the authority when code and prose disagree (CLAUDE.md). The ones this page draws on are SPEC.md, SPEC-MODULES.md, SPEC-INTERFACES.md and PROMPTS.md. Build history and decision records are kept privately by the maintainer.

The process at a glance

Desktop shell (kestrel/desktop/shell.py)
  main thread   pywebview window, blocked in webview.start()
  "tray" thread pystray icon and menu
  "uvicorn" thread
      |
      v
  FastAPI app, built by build_app() in kestrel/web/app.py
      page routers (kestrel/web/pages/*.py) + REST routes (/api/*)
      lifespan starts these tasks on uvicorn's single event loop:
          worker loop     scrape -> re-check -> Tier 0 -> embed -> Tier 1 -> Tier 2 -> background drains
                          (stories, questions, titles, summaries, research, follow-ups, Model check)
                          -> drift, liveness, sorting-model training
          scheduler loop  enqueues due scrapes (desktop shell only)
          delivery loop, setup-models loop, update check, stall monitor
          MCP server      optional, off by default
      |
      v
  SQLite file in the data folder (kestrel.db, WAL mode)
      task table = the queue; opportunity, evaluation, pursuit, doc_* tables

Local models: Ollama over HTTP   |   Hosted models: your own key, opt-in

kestrel serve runs the same FastAPI app without a window or a tray. Everything below the "uvicorn" box is identical in both modes, with one difference covered in Desktop shell and web app.

Main modules

All paths are under kestrel/ in the repository.

Path Role
paths.py Every filesystem location, plus access to packaged resources through importlib.resources.
config.py Typed Settings (pydantic), the local and hosted tier sets, Hosted mode.
db/ SQLAlchemy models (models.py), engines (engine.py), Alembic migrations (migrate.py, migrations/), the allowed values for enum-like columns (enums.py).
ingest/ Source adapters, consulting signal sources, the shared HTTP client, the area and title filters, normalization, dedup, compensation parsing, ghost score, the scrape runner and scheduler.
rules/ Tier 0 rule evaluation: the helper whitelist and the simpleeval wrapper.
queue/ TaskQueue (lease, heartbeat, retry, dead-letter) and the "Score again" enqueue logic.
pipeline/ The Worker, the Tier 0, 1, 2 and 3 handlers, the embed handler, post-scoring math, run logging.
llm/ The async LLMClient, the schema guard, provider helpers, Pydantic schemas, prompt files, embeddings, hardware profiles.
docs/ The document engine: catalog, selection, HTML and PDF rendering, import.
services/ Cross-cutting operations: pursuit status changes, the pursuit board, backup and restore, notices, setup state, the update check.
learning/ Label capture, weight calibration, the reranker and its training task, active learning.
research/, interview/, negotiation/ Company research, prep packs and the story bank, offer valuation and comparison.
intelligence/, analytics/ Compensation corpus queries, ghost and liveness checks, funnel metrics and the generated summary.
web/ The FastAPI app, routes, Jinja templates, static files (stylesheets, the UI runtime, page scripts).
desktop/ The window, tray and single-instance logic.
bench/, evals/ The benchmark harness and the Model check task; gold-set regeneration. See Benchmarking.
mcp/ An optional MCP server.
cli.py, setup.py, doctor.py The kestrel command, guided setup and the preflight checks.

How a job flows through the system

1. Ingestion

A source is a row in the source table with a kind (SOURCE_KINDS in db/enums.py). Employment sources have adapters registered in ingest/adapters/__init__.py, twenty-six kinds in all:

  • Company boards: greenhouse, lever, ashby, workday, smartrecruiters, rippling, adp, paylocity, workable, recruitee, teamtailor, personio, breezy and jobvite, plus careers_page, a generic reader for the schema.org JobPosting data any careers page publishes. Paycom has no adapter: its robots.txt disallows the job list.
  • Search boards: jobspy (Indeed and Glassdoor unless it names other boards), usajobs and adzuna (each needs the person's own free key, saved in the data folder's .env), and himalayas, weworkremotely, arbeitnow, jobicy, remotive, fourdayweek and hn_hiring (no key).
  • remoterocketship is optional, needs the user's own paid key (REMOTEROCKETSHIP_API_KEY in .env), is off by default, and is discovery only: its adapter has discovery_only = True and returns just each posting's employer link, which run_source hands to ingest/employer_links.py instead of storing (see item 7 below).

Consulting signal sources are sec_edgar, sam_gov, pe_portfolio and rss (SIGNAL_SOURCE_KINDS in ingest/signal_sources/__init__.py). The page, manual and import kinds are accepted without an automated fetch (ingest/catalog.py). A single posting can also be handed over with manual_ingest in ingest/manual.py, which POST /api/opportunities/ingest and the MCP ingest_opportunity tool both call.

An adapter implements the SourceAdapter protocol in ingest/base.py: a pure validate_config and an async fetch that returns RawPosting objects, as a plain list or as a PostingBatch, a list that also carries partial_error (a key not saved yet, a 429, a per-run cap). Adapters never touch the database. They make every request through the shared HttpClient in ingest/http.py, which sends the User-Agent and rate-limits per host. It checks robots.txt only when the adapter passes check_robots=True. Adding a job board adapter covers all of it, and the outbound call inventory lists every host the code can reach.

run_source in ingest/runner.py does the rest for one source:

  1. It writes a scrape_run row and calls the adapter. A partial_error on the result, or an AdapterError, becomes the run's error text.
  2. Before anything is stored it drops two kinds of role. A posting whose named country is outside geo_rules.remote_country_allowlist in the profile is dropped (_outside_area in ingest/runner.py, parsing in ingest/location.py against the vendored resources/iso3166.csv). A posting whose title smart_filter.keep rejects (ingest/smart_filter.py: a level below the person's floor, or no field word shared with their target titles or learned from their pursuits) is dropped too. The run's counts record dropped_outside_area and dropped_unrelated_title, and no row or task is created. An unknown or missing place and an ambiguous title pass (hard rule 4). Searches and every company board go through it; manual paste does not.
  3. Each remaining RawPosting goes to normalize_and_store (ingest/normalize.py).
  4. Normalization resolves the organization, parses location and compensation, computes the content hash, assigns a dedup group, computes a ghost score and writes a comp_observation.
  5. It commits per posting, in the same transaction as an embed task for that opportunity, so a crash keeps what was already stored.
  6. A recoverable error makes the run partial and never aborts the batch. A 429, a 5xx or a missing key reported through partial_error keeps the postings already collected and does not count against the source. An AdapterError does count, and three consecutive failures disable the source and add a notification.
  7. After a jobspy run, discover_boards (ingest/board_discovery.py) reads the postings' links. When one points at a company's own board on one of 13 hiring systems (the company-board kinds above except careers_page), a new source for that board is added with origin="discovered", read once a day. A board already present in any state is never re-added, so one you turned off stays off, and each track holds at most 40 found boards. board_from_markup also finds Recruitee and Teamtailor boards behind a company's own domain when a pasted careers page names them.

A remoterocketship run feeds the same path. ingest/employer_links.py sends each employer link that board_discovery recognizes (or a grnh.se short link) to discover_boards, so it becomes a found board. A grnh.se short link is followed one hop, with redirects off, to learn which board it points at; that request does not check robots.txt, and at most 20 are made a run. Any other link is fetched once from the employer's public page, with robots.txt checked and redirects not followed, at most 20 pages a run, and read for schema.org JobPosting data. A link nothing can read is dropped and counted as unreadable. Nothing from RemoteRocketship is stored, because its terms allow keeping API results for 24 hours at most. A 429 after a good page keeps the links already collected and makes the run partial.

New opportunities start at stage new.

Dedup has two passes (_assign_dedup_group in ingest/normalize.py). The first matches the exact content hash, which content_hash in ingest/dedup.py builds from organization, title and normalized description. The second matches titles within the same organization and track when token Jaccard similarity is above 0.85. When postings share a group, _PRIORITY in ingest/dedup.py ranks the source: company boards first (rank 0), then USAJobs, Himalayas, We Work Remotely and page, then Adzuna and the JobSpy boards, and an unmapped kind last. A new posting that lands in a group where you already applied is hidden on arrival as a re-post (suppress_if_applied). The semantic dedup pass in SPEC.md 5.5 does not exist yet; the docstring of pipeline/embed.py says so.

Scrapes run as scrape tasks. The scheduler loop in web/app.py calls enqueue_due_scrapes (ingest/scheduler.py) about once a minute. Shipped sources start disabled (_seed_shipped_sources in web/app.py), so nothing scrapes until a source is enabled. The scheduler.enabled setting that earlier versions carried, which nothing read, has been removed. The only unattended-scan guard is that shipped sources start disabled.

2. Tier 0: rules

run_tier0_batch in pipeline/tier0.py sweeps opportunities at stage new and moves each to t0_pass or t0_reject. It commits per opportunity and enqueues one t1 task per survivor. Survivors are sorted by pre_score, so the best candidates reach the models first.

Survivors go straight to Tier 1. Nothing waits in a background lane any more: the roles a company board would have parked there are dropped at ingest (step 1, item 2), and the lane code only drains rows an earlier version left behind (see Task queue and concurrency). When the profile rules change, pipeline/recheck.py gives roles at t0_reject a second look with rules only.

Rules live in resources/config/filters.yml, per track. Hard blockers reject on the first match. Soft signals add weights to pre_score. Expressions run through simpleeval and may call only the helpers in rules/helpers.py, all of which accept None. An unknown title, a missing date or an unparseable location passes. check_filters in rules/helpers.py rejects comprehensions and generator expressions, kestrel doctor runs it (doctor.py), and tests/test_filters_load.py guards the shipped file.

3. Embeddings

The worker drains embed tasks before Tier 1 (Worker._run_tiers in pipeline/worker.py), because the Tier 1 reranker gate and Tier 2 few-shot selection both read the opportunity's vector. LLMClient.embed serves them from Ollama or from the bundled in-process model (llm/inprocess_embed.py). Embeddings are refused for external backends. Each stored vector records its model, and readers ignore vectors from any other model (llm/embeddings.py).

4. Tier 1: triage

handle_t1 in pipeline/tier1.py asks a small model for keep or kill with a confidence (P1Triage in llm/schemas.py; prompts triage/v2 and triage_consulting/v2). It sees the first 1,200 tokens of the description.

  • A confidence below pipeline.tier1_min_confidence (0.6 in settings.yml) is forced to keep.
  • A quarantined call is promoted to Tier 2, not dropped.
  • kill sets t1_reject. keep sets t1_pass and enqueues a t2 task.
  • If a reranker has been promoted for the track, pipeline/reranker_gate.py may decide a confident case without calling the model.

The handler commits the evaluation, the stage change and the next task together. If the process dies after that commit, the re-leased task sees the advanced stage and completes without a second model call.

5. Tier 2: evaluation

handle_t2 in pipeline/tier2.py runs the evaluate/v2 prompt (evaluate_consulting/v2 for the consulting track) against the full description, cut to pipeline.max_jd_tokens. It also receives few-shot examples from your labels once you have enough of them (learning.min_labels_for_few_shot, 15 by default), plus compensation and ghost context.

The model returns six blocks (a_role_summary through f_interview), five dimension scores, a holistic score, its own verdict, blockers and a legitimacy assessment (P2Eval). The model does not decide the outcome. pipeline/scoring.py computes the weighted score from scoring.weights in settings, flags a large gap between holistic and weighted scores for review, applies blocker and legitimacy overrides, and derives the verdict from thresholds (4.0 and 3.0 by default). The model's own verdict is stored beside it. The stage becomes t2_done. A call that fails validation twice sets quarantined.

6. Tier 3: operator-confirmed escalation

pipeline/tier3.py is not a worker stage. You escalate one opportunity, Kestrel shows the exact payload, destination and an estimated cost, and the send is gated on a hash of that payload. Each transmission is recorded in frontier_transmission. The stage becomes t3_done.

Do not confuse this with the tier3 entry in settings.yml, which is a local deep model used by other features. The hosted escalation uses a separate tier named frontier, so nothing local can be routed off the machine by mistake.

7. Tracking

Adding an opportunity to your list (add_to_list in web/pages/opportunity_actions.py) creates a pursuit with the first status for its track. Statuses are track-specific (PURSUIT_STATUS in db/enums.py). set_pursuit_status in services/pursuits.py is the only supported way to change one, and it writes an append-only status_event in the same transaction. The board in services/pursuit_board.py groups the fine statuses into columns, and it never contacts anyone.

8. Documents

Resumes and capability statements are stored as sections, slots and variants (DocMaster, DocSection, DocSlot, DocVariant in db/models.py). Rendering is started by you (the renders page, or kestrel render), never by the worker.

  • docs/select.py builds a prompt from the opportunity's evaluation blocks and calls run_doc_select. The schema is generated per master with an explicit enum of real variant keys for each slot (llm/docselect.py), so the model cannot name a key that does not exist.
  • A selection that fails outright (it cannot be validated after one repair, the send is refused, or a slot has no variants) falls back to the default configuration and sets defaults_used, which the interface flags. When the answer parsed and only some slot picks name a variant that does not exist, docs/select.py keeps the valid picks and marks the failed slots needs_pick (they keep the standard wording and the page asks the person to choose); defaults_used stays false. A bad key is never written either way.
  • docs/catalog.py resolves the configuration to blocks whose text is doc_variant.text unchanged. docs/render.py turns that into HTML, then a PDF through Playwright, with empty header and footer templates, and strips document metadata with pypdf. docs/service.py writes the file under the data folder and records a doc_render row.
  • Changing the model's pick on the render page writes a selection_override row, which the learning loop reads.

The browser for PDFs is chosen by a launch ladder in docs/render.py: KESTREL_BROWSER_PATH if set, then Edge, then Chrome, then Playwright's Chromium. Kestrel does not bundle a browser.

9. Learning

Your decisions feed learning/: capture.py records labels and overrides, calibration.py proposes new dimension weights (you accept or reject them), reranker.py trains a gradient-boosted model that can take over Tier 1 once it passes a promotion gate, and active.py ranks which opportunities to label next. Training is a queued train_reranker task (training.py), started from the Calibrate page or after 50 more rated roles. The worker loop checks reranker drift between cycles. Thresholds are in the learning block of settings.yml.

The worker, the task table and resumability

Every unit of background work is a row in the task table (Task in db/models.py). The columns are type, payload (JSON), status, priority, attempts, max_attempts (3 by default), lease_until, worker_id and last_error.

Task type Created by Handled by
scrape scheduler, Scan now, the run schedule, MCP Worker.drain_scrapes
embed ingestion pipeline/embed.py
t1, t2 Tier 0, Tier 1, Score again handle_t1, handle_t2
t0_recheck saving a profile change pipeline/recheck.py
build_stories the My stories page interview/story_task.py
interview_questions marking a role Applied interview/question_task.py
title_suggestions a resume import, weekly, after 10 newly applied roles services/title_suggest.py
org_summary opening or following a company, Refresh, weekly research/org_summary.py
org_research, org_contacts the research buttons on a role research/jobs.py
follow_up a follow-up draft asked for on the Applications board services/follow_up.py
letter_draft a cover letter or engagement outline asked for on a role docs/letter_task.py, drained by run_letter_drafts in web/pages/role.py
train_reranker Calibrate's train button, or 50 more rated roles learning/training.py
bench Check my models bench/check.py (see Benchmarking)
ollama_pull, ollama_create the Setup page services/model_tasks.py, on its own loop beside the worker

"Score again" is not its own task type. It sets rescore in the payload of a t1 or t2 task (queue/rescore.py).

TaskQueue in queue/queue.py works like this:

  • lease claims one row with a guarded UPDATE and checks that exactly one row changed, so two workers cannot take the same task. Attempts are incremented at lease time, so a worker that crashes without reporting still uses an attempt.
  • A task is claimable when it is pending, or leased with an expired lease_until and attempts remaining.
  • fail returns the task to pending while attempts remain and marks it dead otherwise. reclaim_expired does the same for abandoned leases.
  • Scoring handlers run with a 900 second lease that a heartbeat renews every 120 seconds (_TASK_LEASE_S and _RENEW_S in pipeline/worker.py), so a slow model call is not reclaimed underneath itself.
  • Every queue write is retried with jittered backoff when SQLite reports "database is locked".

enqueue_once in pipeline/tasks.py skips a task if a live one exists for the same type and opportunity. For t1, t2, t3 and rescore, a partial unique index (migration 0014) enforces this in the database, so two processes cannot both insert.

On startup the worker loop calls reclaim_expired, requeues scoring orphans (pipeline/orphans.py), and closes run rows that a killed process left open. On a graceful quit, _graceful_worker_shutdown in web/app.py signals the stop event, gives the worker WORKER_STOP_S (one second) to exit on its own and cancels it otherwise, then calls release_all_leased so a restart resumes without waiting for leases to expire. Quit never waits on a running model call.

The worker drains one tier completely before starting the next. Worker.drain_tier runs up to concurrency.tier1 or concurrency.tier2 leases in parallel (4 and 2 by default). Tier 2 also drains one model at a time: tasks are grouped by the model they will run on, so a mixed queue does not make Ollama swap models. After the tiers, the loop runs the background drains for stories, questions, titles, summaries, research, follow-ups and Model check, each after the tiers so none swaps a model under scoring. Between cycles the loop sleeps 5 seconds when it found nothing to do. Task queue and concurrency has the full cycle.

Model backends

LLMClient in llm/client.py maps each tier name (tier1, tier2, tier3, docsel, trigger, embed, frontier) to a backend and model through settings.llm.tiers. Backends are defined in settings.yml:

Backend Purpose
local Ollama through its OpenAI-compatible endpoint.
inprocess The bundled CPU embedding model. It serves the embed tier only.
frontier, openmodel, anthropic, openai Hosted providers under your own key. Each is marked external: true.

Local models are derived from base models by kestrel setup or kestrel models build, using the Modelfiles in resources/models/ and the context windows in resources/config/models.yml (4096 for tier 1, 16384 for tier 2, 20480 for tier 3, 8192 for document selection). The hardware profiles in the same file choose base models and concurrency. The hosted_only profile skips Ollama entirely.

Two switches decide whether an external backend may be used (LLMClient.complete in llm/client.py):

  • Tier 3 escalation passes allow_external=True after you confirm the preview.
  • Hosted mode lets any tier run on a hosted model. It needs llm.hosted_mode enabled and the disclosure acknowledged, and llm.mode set to hosted with at least tier1 and tier2 assigned (HOSTED_REQUIRED_TIERS in config.py). apply_mode overlays hosted_tiers onto tiers for the run.

Otherwise the client raises ExternalBackendError and nothing is sent. The worker re-reads Hosted mode from the setting rows before each task that would reach an external backend (Worker._task_settings), so turning it off applies mid-run.

When a hosted provider answers that the key has no credit (credit.is_out_of_credit in llm/credit.py: a 402, a billing error code, OpenAI's insufficient_quota, or Anthropic's low-balance 400), LLMClient raises OutOfCredit with a message Kestrel writes itself. It names the provider and its billing page and never repeats the provider's own text. The backend is then held for that key for HOLD_SECONDS (30 minutes) or until the key changes or a new run starts, and calls to it fail at once with nothing sent. The hold is per backend. Nothing falls back to another online provider.

Every model call that expects JSON goes through llm/guard.py. It strips thinking spans, parses and validates against the prompt's Pydantic model, makes one repair call at temperature 0 on failure, and on a second failure writes a quarantine row with the prompt and raw response. Prompts are Markdown files in kestrel/llm/prompts/, loaded by version (llm/prompts.py). Schemas truncate overlong strings and clamp out-of-range numbers instead of rejecting them (llm/schemas.py). The prompt-size analysis is in docs/PROMPT_BUDGETS.md.

Settings resolve in this order, first match wins (Settings.settings_customise_sources in config.py): rows in the setting table, environment variables prefixed KESTREL_, settings.yml, then code defaults. load_settings first loads the data folder's .env into the process environment (load_dotenv_into_environ), which is where API keys come from. get_settings() rereads on each call, so most changes apply without a restart.

Desktop shell and web app

The UI is server-rendered. web/app.py mounts Jinja templates (web/templates/), the page routers named in _PAGE_MODULES, the REST routes in web/routes_api.py, and static files from web/static/ at /static. Nothing loads from a CDN. FastAPI serves its API docs at /docs.

The static files are:

  • Stylesheets: css/tokens.css (the theme tokens), css/components.css and css/shell.css, a sheet per page under css/pages/ (and models.css, sources.css, calibrate.css, retry.css), and css/kestrel.css, the legacy sheet. base.html loads kestrel.css in its legacy_css block, then tokens.css and components.css; a converted screen overrides legacy_css with its own sheet and adds more in head_extra.
  • Scripts: htmx.min.js and alpine.min.js, the scene art in js/scenes/, the UI runtime js/kestrel-ui.js (theme, toasts, flyouts, slide-overs, modals, the page lifecycle and in-place navigation), js/palette.js (the command palette), and one script per page (today.js, pipeline.js, bench.js and so on).
  • Fonts (Manrope under fonts/), icons, manifest.webmanifest and splash.html, the loading page the desktop window opens on.

One executable serves two jobs. desktop/__main__.py opens the window when started with no arguments and runs the kestrel CLI when given any. run_desktop in desktop/shell.py then does the following, in order. The window comes first, so a person never waits on a blank screen:

  1. Make the data folders, configure logging, then take the single-instance lock: a Local\Kestrel mutex on Windows (a data folder other than the default gets Local\Kestrel-<8 hex> from a hash of its real path, so two folders never share a lock), an exclusive lock on kestrel.lock in the data folder on macOS and Linux. A second launch posts to /api/focus on the running instance and exits. A relaunch while the previous copy is still closing shows "Finishing closing the last session" and opens by itself once that copy has exited.
  2. Open the frameless window at its final size on the loading page (static/splash.html, driven by _Splash through window.KSplash; the window controls live in desktop/frame.py). The size and place come from window.json in the data folder, which also holds the theme, and fall back to a centered default when the saved place no longer fits a display.
  3. Behind the loading page, in _start_backend: run Alembic migrations (db/migrate.py), start uvicorn on a non-main thread (start_server), binding the first free port from 8765 to 8774 (PORT_LADDER in web/serve.py), wait up to 30 seconds for /health, write runtime.json and run the quick preflight. Each step is named on the loading page. A failed start shows a problem card in the same window (Try again, Open logs folder, Quit).
  4. Create the tray, then load the app's URL into the window. webview.start() blocks the main thread for the life of the window.

Closing the window hides it when a tray exists and close-to-tray is on; the closing handler returns False. Quit sets a flag and asks uvicorn to exit, which runs the lifespan drain described above, then destroys the window so webview.start() returns. _finish_quit then waits up to QUIT_JOIN_S (30 seconds) for the server thread, though a quit normally takes one to two seconds. If it is still running, the process ends itself; unfinished work is safe because it lives in task rows.

On macOS and Linux, if pywebview has no backend, the shell prints the URL, opens your default browser and keeps the server in the foreground (_run_in_browser).

kestrel serve (web/serve.py) runs the same app with the same port ladder and runtime.json, but no window and no tray. It calls build_app(worker=...) without the scheduler loop. The desktop shell calls build_app(worker=True, scheduler=True).

Two rules shape this code. The worker, the scheduler and every database session must stay on uvicorn's loop, because a second loop produces cross-loop aiosqlite errors that look like corruption. And webview.start() runs once per process, so the window is hidden and shown, never destroyed, until quit.

The optional MCP server (mcp/server.py) is started from the same lifespan when mcp.enabled is true. It serves 15 tools over SSE on port 9110 by default. It is off by default.

The web UI runtime

Three pieces of the web layer decide how a page behaves in the window: versioned static files, the page lifecycle, and in-place navigation. They live in web/deps.py, web/app.py, web/templates/base.html and web/static/js/kestrel-ui.js.

Versioned static files

Templates never write a /static/ path by hand. They call static_url('js/x.js'), a Jinja global that returns /static/js/x.js?v=<token>. static_token() in web/deps.py is a 12 character fingerprint: a SHA-256 over every file under web/static/ (relative path, size and modified time), computed once per process. web/app.py mounts /static with _VersionedStatic, and a request whose v equals the running build's token gets Cache-Control: public, max-age=31536000, immutable. A request without it, or with an older build's token, keeps Starlette's ordinary revalidation.

A new build, or an edited file, has a new token and so new URLs. Within one build the window never asks the server about a file again. This was measured: before it, a fresh install's new file dates made the window re-check 8 to 16 stylesheets and scripts with the server on every page change.

The offline cache is named for the same token. /sw.js (web/pages/chrome.py) caches the versioned URLs under kestrel-<token>, so an upgrade replaces the old copies instead of leaving a LAN browser on the previous build's files. Only the browser and LAN modes register the worker; the desktop window uses none, and base.html removes any an earlier run left. tests/test_static_cache.py fails on a template link to /static/ without its version, and checks the immutable header and the worker's cache name.

The page lifecycle

Every page is a template that names itself and a script that defines it. Adding a page has the full contract. In short:

  • A template fills {% block page_name %} (for example today), which becomes <main class="container" data-k-page="today">, and loads its script in {% block page_scripts %}, after kestrel-ui.js and palette.js and before Alpine.
  • The script calls KUI.page.define(name, { mount(root, ctx), unmount() }) and starts nothing at top level.
  • mount gets a context that owns everything the page starts (listeners, timers, observers, cleanups, an abort signal). Leaving the page ends all of it, and coming back starts exactly one set.
  • On a normal document load, a DOMContentLoaded listener in base.html calls KUI.page.start(), which mounts the page the content root names, once, after every deferred script has run. Only one page is mounted at a time.
  • Each page has a remount leak test, assert_page_remounts_clean in tests/browser.py.

In-place navigation

A click on a sidebar or in-app link changes the content under the window instead of loading a new document. The window, the sidebar, the top row and the scene art stay, so WebView2 never shows its bare background between two documents (the intermittent gray window). KUI.navigate(url) is the one entry point. KUI.go(url) is the same call for page scripts and the command palette, and it falls back to a plain load when the controller is off. One page change runs in this order:

  1. The leave guard. window.kLeaveGuard, which Profile sets while it holds unsaved edits, can refuse a click, the palette or Back.
  2. Fetch the whole page with Accept: text/html and no HX-Request header, so every route answers with its full page, never a fragment. Redirects are followed, and the reply is parsed with DOMParser.
  3. Load, without applying, the stylesheets the new page needs (media="print" until the commit) and any page script not yet run (definitions only).
  4. Commit in one frame, inside a same-document view transition (Reduce motion skips it). The old page's overlays close, its htmx requests abort and it unmounts. The stylesheets change in cascade order, then the title, the sidebar highlight and the preferences rendered on <html>. The content is swapped, with inline scripts run as they land. The scene art moves into the next band when scene and touch match (moveBefore, so its animation keeps running). History, scroll and the arrival motion follow.
  5. After Alpine has seen the new content, the new page mounts, then htmx processes the content and announces htmx:load.

The old page stays on screen until all of that is ready, so no frame is blank.

History. Every entry gets history.state.kNav = {inst, idx, kind}, stamped whoever makes it: the controller (doc), htmx's hx-push-url (hx), or a page's own pushState (page, such as Pipeline's ?open=). htmx's own htmx flag is removed from its entries and its history cache is off, so htmx never restores a stale snapshot; Back to an hx entry shows that URL again in place. Back or Forward to an entry of the page on screen is that page's business (its own popstate listener); any other entry is shown again in place. A page change still loading is overtaken by Back. Scroll positions are the controller's (history.scrollRestoration is manual).

The classic fallback. A full page load remains for:

  • a link marked data-k-reload, or inside such a container (the track switches, whose sidebar labels change);
  • Settings > Preferences > Classic page loads (ui.classic_nav, rendered as data-k-nav="0" on <html>), a switch for a page that misbehaves;
  • a reply that is not a Kestrel page (a bare 404, a file, another origin);
  • another build of the app (a different kestrel-ui.js URL), another set of sidebar pages, or a page script that is not on the lifecycle;
  • a failed fetch, or stylesheets and scripts that take more than 8 seconds;
  • HX-Redirect replies (Documents, the onboarding steps), which stay full loads.

Diagnostics. In the desktop window each page change posts a record to POST /api/diag/page, which logs it as page_change for the diagnostics zip; it never leaves the computer. An in-place change carries inplace, fetch_ms and swap_ms. A full load carries ttfb_ms, reveal_ms, vt (whether the cross-document transition ran) and the page left behind's side (out_vt, out_anims, out_htmx, out_busy_ms).

The data folder

data_home() in paths.py returns the writable root. Nothing is written beside the executable.

OS Default location
Windows %LOCALAPPDATA%\Kestrel
macOS ~/Library/Application Support/Kestrel
Linux $XDG_DATA_HOME/kestrel, or ~/.local/share/kestrel

Setting KESTREL_DATA_HOME overrides all three. The test suite relies on this (tests/conftest.py gives every test its own directory).

<data home>/
  .env                  API keys; never part of a backup
  runtime.json          {"port": ..., "pid": ...} for the running instance
  window.json           the window's place and size and its theme (local only)
  kestrel.lock          single-instance lock (macOS and Linux)
  config/
    settings.yml        seeded from the packaged defaults on first run
    filters.yml
    sources.yml
    profile.example.yml
    profile.yml         yours; never shipped
    hardware_profile.json   written by kestrel setup
    models/             rendered Modelfiles
  data/
    kestrel.db          SQLite (WAL mode)
    documents/          rendered resume and capability PDFs
    prep_packs/         interview prep PDFs
    ml/                 reranker and its PCA
    evals/              gold sets, in packaged builds only
  logs/
    kestrel.log         rotating, 5 MB each, 5 backups
    stdout.log, stderr.log   windowed builds only
  exports/              fallback for saved files when Downloads is unavailable

seed_config copies the packaged config only when config/ holds no .yml file, so your edits are never overwritten. Packaged defaults live in kestrel/resources/ and are read through importlib.resources, never relative to __file__.

kestrel backup writes a zip with a database snapshot, config/*.yml, and the two PDF folders. It leaves out .env (services/backup.py).

Where to read next

Clone this wiki locally