Skip to content

Document Engine

Claude edited this page Nov 12, 2026 · 5 revisions

Checked against v0.7.6 on November 13, 2026.

Document engine

This page explains how Kestrel stores a resume or capability statement, how a render configuration is chosen and validated, and how the result becomes a PDF. It is for people changing code in kestrel/docs/. For the pipeline around it, see Architecture overview.

The engine exists to protect one property, hard rule 2 in CLAUDE.md: the model selects, it never invents. Every bullet in a PDF is the operator's own text, taken byte for byte from doc_variant.text. The model chooses between wordings the operator already owns.

Kestrel never submits a document, sends it or attaches it to an application on a third-party site. It renders a PDF and hands it over.

The data model

Five tables in kestrel/db/models.py hold a document, plus one for output.

Table Role
doc_master One document: track, name, doc_kind (resume or capability_statement), a header dict, summary_variants and skill_groups as JSON lists, and the optional typed sections (education, certifications, licenses, projects)
doc_section A block under a master with a section_kind (role, service_line, proof_engagement, credential), org_label, title, dates, a context_line, and org_label_redacted for the current employer
doc_slot One bullet position in a section: key, optional, default_variant_key
doc_variant One wording for a slot: key, text, tags, derived
doc_layout A named layout: key, label, description, section_order, max_roles_shown
doc_render A produced PDF: the config used, rationale, pdf_path, filename, page_count, defaults_used

Slot keys must be unique across a master, because they key both the render configuration and the selection schema. Variants marked derived: true are alternate wordings the operator accepted one at a time. Each slot allows at most two (_MAX_DERIVED_PER_SLOT in kestrel/docs/imports.py).

Summary wordings and skill groups live as JSON on doc_master, not as slots. A summary is chosen by key like a bullet. Skill groups are shown or hidden by key.

The render configuration

A render configuration is a plain dict, and default_config() in kestrel/docs/catalog.py builds the baseline:

{
  "layout": "executive",
  "summary": "summary_general",
  "slots": {"r1b1": "original", "r1b2": "original"},
  "skill_groups": {"infrastructure": true},
  "redact_orgs": false
}

The keys above are examples; real slot and summary keys come from the master. The defaults are the first layout, the first summary, each slot's default_variant_key (or its first variant), and each skill group's default_visible. The renderer also reads optional keys: hide_summary, hide_skills, font, header_align, accent, size and margins. The value "hide" in a slot drops that bullet from the render. Hiding never deletes the operator's text.

resolve() turns a configuration and a catalog into a RenderDoc of ordered blocks. It applies, in order: confidential-mode redaction, per-slot choice, max_roles_shown, and the layout's section_order. If a configured key does not exist, resolve() falls back to the slot default but records the miss in RenderDoc.unresolved, so a page can name it. The fallback is never silent: render_document() sets defaults_used whenever unresolved is non-empty.

Selection and validation

Model-driven selection is select_config() in kestrel/docs/select.py. It uses the doc_select/v1 prompt and the docsel model tier.

The safety comes from two layers in kestrel/llm/docselect.py.

  1. A schema built per master at call time. build_doc_select_schema() gives every slot an explicit enum of that slot's real variant keys, adds "hide" only where optional is true, and makes layout and summary enums of the real keys. A hallucinated variant key is structurally impossible on a backend that enforces the grammar. schema_inputs() in catalog.py supplies the inputs.
  2. Strict validation afterward. validate_doc_selection() checks every key against the catalog, because a backend running plain JSON mode enforces no grammar. A bad key makes the guard result ok=False; run_doc_select() never substitutes one.

The builder refuses to produce an unsatisfiable schema. A slot with no variants, a master with no summary wordings, or an empty layout list raises ValueError naming the gap, because an empty enum makes every call quarantine with no hint why. select_config() catches that and returns the defaults with an error string.

A reply that fails as a whole (invalid JSON after repair, a layout or summary key that does not exist, a transport error) makes select_config() return default_config() with defaults_used=True. The bad key is never written to the configuration. The CLI prints [DEFAULTS USED when this happens, and the review page flags it.

A reply that parses, names a real layout and summary, and fails only on some slot picks is handled by _partial_selection(). It keeps every valid pick and gives each failed slot the standard wording (the slot's default_variant_key, else its first variant). It returns those slots in Selection.needs_pick, and defaults_used stays False. The Tailor page's Pick again route stores them as needs_pick in the render configuration and badges each as "Needs your pick" until the operator chooses. The line shows the operator's standard wording meanwhile, and the key the model named stays in model_picks, never in slots. Downloading while any line still needs a pick returns a 409 until the operator confirms with anyway=1, and the choice is recorded on the render as left_unresolved.

Hosted models get extra handling. The catalog contains the operator's resume text, so plan_hosted_send() redacts the confidential employer before anything leaves the machine, and refuses the send if no redaction map exists. A refusal returns the defaults, flagged.

Every slot is listed under required, including optional ones, so the model is asked to answer all of them. The validator is more lenient and accepts an omitted optional slot.

Where selection runs

SPEC-MODULES.md section 1.3 describes a doc_select task queued when an opportunity reaches an apply verdict. The code does not do that. Nothing in kestrel/pipeline/ or kestrel/queue/ creates or handles a document selection task. select_config() has two callers, and both are operator actions:

  • kestrel render MASTER_ID --opportunity N in kestrel/cli.py.
  • Pick again on the Tailor page, POST /renders/{id}/pick in kestrel/web/pages/renders.py (through _run_selection(), a seam tests replace). On a local model it runs at once. On an online model the route first requires the operator's confirmation of that exact send: it checks the confirmation against the configured destination on the server, shows what will be sent (the wordings and a short summary of the role), and refuses when Confidential mode is on and no current employer is chosen. A failed or defaulted pick changes nothing and says why. The operator's own swaps stay as they set them, and the model's picks are kept beside them in model_picks so the page can show both.

The route /renders/new still builds its first render from default_config() and the layout the Documents page was showing, with the look the operator chose beside it. If you add automatic selection, you need a task type, a handler and the plumbing to store rationale; none of that exists.

Operator edits and the audit trail

The review page (kestrel/web/pages/renders.py) shows the chosen wording beside the alternatives for each slot.

  • Swap (POST /renders/{id}/swap) validates the key with operator_slot_keys(), which allows any real variant key plus "hide" for any slot. It writes a SelectionOverride row (model_choice, operator_choice) before changing the configuration. The learning loop reads those rows.
  • Edit wording (POST /renders/{id}/wording) saves the operator's typed text as a new variant with derived=False, then selects it through the same override path. The verbatim check does not apply, because the operator wrote it. A wording that contains a privacy stand-in code is refused, and text is capped at 2,000 characters (_WORDING_MAX).
  • Look (POST /renders/{id}/look) changes layout, font, alignment, accent, size and margins. It is presentation only, so it writes no SelectionOverride row. A layout key the catalog does not have is refused. POST /renders/{id}/look/default saves the choice as the master's look, and an Undo route restores the earlier one.

Swaps, look changes and the privacy switch (POST /renders/{id}/privacy, hide the current employer for this application) update the live preview and mark the render stale. The PDF file is not rewritten at that point. refresh_pdf() in kestrel/docs/service.py writes it again from the current picks, using the same resolve() and render_html() as the preview, and GET /renders/{id}/download calls it when the render is stale or the file is missing. The download is therefore never older than the preview. If no browser is available it answers 503 with the reason and leaves the old file as it was.

On the Documents page, "suggest" asks the variant_suggest/v1 prompt for up to two alternate wordings of one bullet. facts_changed() compares the numbers in the original and the candidate, normalizing units, so "$2.5M" and "$2.5 million" match while "$40 million" and "$40 billion" do not. A candidate that changes a number is marked with a problem and cannot be added, and add_slot_variant re-checks that and the two-per-slot limit server side instead of trusting the form. The check does not compare order, so a swapped pair gets through. The operator's review is the safeguard there.

The resume assessment (kestrel/docs/assess.py, prompt P13) is advisory. Its schema has no field for replacement text and nothing it returns reaches a PDF.

Import

Import turns an existing resume into a master. It writes nothing until the operator accepts a proposal.

  1. convert_to_markdown() (kestrel/docs/convert.py) reads .md, .txt, .docx, .pdf or legacy .doc (through LibreOffice when present). It never rewrites wording, because later checks compare against this text. PDF extraction drops repeated headers, footers and page numbers and rejoins wrapped bullets, and warns that structure is best effort.
  2. propose_import() (kestrel/docs/imports.py) numbers the lines and has the model map them by line reference. An outline call finds roles, then one call per role (up to ROLE_CONCURRENCY, 4) maps bullets. The application copies the referenced lines, so the model never writes resume text. An invented or out-of-range line reference is an error, not a default.
  3. flag_proposal() checks that every derived: false variant appears verbatim in the source. It tolerates whitespace reflow and bold markers. Anything else is flagged.
  4. accept_import() is the only writer. _validate_for_accept() re-runs the checks at the write boundary and rejects duplicate slot keys, slots with no variants and defaults that name a missing variant. Proof points go to the profile.

Layouts and looks

A layout decides which sections appear and in what order. Eight ship in kestrel/docs/seed.py: executive, condensed, technical, classic, modern, compact, capability and capability_short. condensed and capability_short cap max_roles_shown at 2. The optional sections (education, certifications, licenses, projects) print in every layout when they have entries, appended in fixed order if the layout's section_order does not name them.

_ensure_layouts() runs at every app start (_seed_shipped_layouts in kestrel/web/app.py). It inserts missing shipped layouts and resets label, description, section_order and max_roles_shown on existing shipped rows. If you edit a shipped layout in the database, that edit does not survive a restart. A layout under a new key is never touched.

How a layout looks is separate, in kestrel/docs/styles.py:

  • LAYOUT_STYLES maps a layout key to a style class, font, header alignment and accent. A layout with no entry reads as classic in Georgia, left aligned.
  • FONTS is a fixed list of six stacks (Georgia, Cambria, Garamond, Calibri, Arial, Segoe UI). A font arrives as a name checked against that list, never as free text, because the stack is written into the stylesheet.
  • SIZES scales the body text: smaller (0.92), default (1.0) or larger (1.08) times 10.5 pt. MARGINS sets the page margin: normal (0.5 in) or narrow (0.35 in). Both are chosen from these lists only, and render_html() falls back to default and normal for anything else.
  • The accent must be exactly #RRGGBB, checked by valid_accent(). Seven presets exist (Navy, Slate, Forest, Burgundy, Charcoal, Teal, Orange). Precedence is the render configuration, then doc_master.look, then the layout default.

render_html() re-validates style, alignment, font and accent against these whitelists before they reach the template, so a caller that builds a style by hand cannot inject CSS.

doc_layout.template_file exists as a column, but no code reads it. There is exactly one template, kestrel/docs/templates/document.html, and each style is a body.style-<name> CSS block inside it. The STYLES tuple lists the names it knows. To add a layout:

  1. Add a DocLayout row (a new entry in _LAYOUTS in seed.py gets it inserted at startup).
  2. Add a LAYOUT_STYLES entry that uses an existing style, or add a new name to STYLES and a matching body.style-<name> block to document.html.
  3. If it should apply to one document kind only, update _layout_kind() in catalog.py, which hard-codes the keys it recognizes. An unknown key is offered for every kind.
  4. Add tests. tests/test_docs.py, tests/test_docselect.py and tests/test_pipeline_render.py are the nearest.

The PDF render

render_document() in kestrel/docs/service.py runs the whole path: load the catalog, resolve(), render_html(), render_pdf(), then write the file and a doc_render row.

  • The HTML is the single source for the preview and the PDF, so they match. Each bullet is <li data-vk="<variant key>">, which lets bullets_in_html() assert in tests that each rendered bullet equals a doc_variant.text row.
  • The template is ATS safe by design: one column, no layout tables, real Unicode bullets, selectable text, Letter page. The margin is 0.5 inch unless the operator chose narrow (0.35 inch).
  • render_pdf() uses Playwright with print_background=True, prefer_css_page_size=True, display_header_footer=False, and explicitly empty header_template and footer_template.
  • The browser comes from launch_plan(): KESTREL_BROWSER_PATH if set, then Edge, then Chrome, then Playwright's Chromium. Doctor uses the same plan, so it cannot disagree with what a render will use. If nothing launches, BrowserUnavailable names every attempt and the fix.
  • _scrub_and_count() copies the pages into a fresh pypdf writer and blanks /Producer, /Creator, /Author and /Title, so no generator string or organization name sits in the metadata. It also counts pages.
  • If the count exceeds settings.docs.max_pages (default 2), the result sets over_page_limit and lists optional slots that are currently shown as hide candidates. SPEC-MODULES.md says these are ranked by model confidence; the code notes that ranking is deferred and returns them unranked.
  • The file is saved as <render id>_<LastName>_<Org>_<Role>.pdf under the data folder's documents directory. Org and Role come from the target opportunity, or General when there is none. The operator's own employer never goes in a filename. Slugs keep the original casing.

Confidential mode swaps the marked current employer for its "show it as" text in bullets, titles, context lines, summary, skills, header free text and optional sections, at render time only. Stored text is never changed. The web path and the CLI both OR settings.confidential_mode into redact_orgs.

Cover letters and engagement outlines (kestrel/docs/letters.py) are the one place generated prose is allowed. They are drafts the operator copies out or downloads as a PDF. Kestrel does not send them. A cover letter is written in the first person (cover/v3) and opens "Dear Hiring Team,". The closing, "Sincerely," and the operator's name are added by code, so the name never goes to an online model. Anything in a draft that the notes do not support is marked for the operator to check. Each draft is a letter_draft task, so one in progress survives a restart (see Task queue and concurrency). An online draft needs the ticked confirmation first (see Security and privacy model).

Since 0.7.6 a letter is stored in its own letter table (migration 0028), not in a render's config. The doc_render row keeps the PDF, and the letter row keeps the text, the claims, the marks, the prompt version and the word count (kestrel/docs/letter_store.py). Letters saved by 0.7.5 are moved over when you update.

  • Sources. A letter can draw on up to three of the operator's proof points and resume lines together (MAX_LINES), and on up to two stories (MAX_STORIES) that the operator wrote or edited in the story bank. Only the one or two most relevant stories are chosen, and only one action line and the result of each go to the model. A story Kestrel proposed but the operator has not saved is never used. A claim's source is shown as the text that was sent when the letter was drafted, with a note when that line or story has since changed or been deleted. Two sources sharing one key are refused before anything is sent.
  • Length. The target is 250 to 350 words for a cover letter (WORD_RANGE) and at most four paragraphs. A draft over that is asked once to shorten, which is the one extra request the ask-first panel already names. One that is still too long is kept and marked "Over length". The editor warns above 350 words and refuses to save above 600 (MAX_SAVE_WORDS).
  • Marks. verify_claims and unverified_details mark what the sources do not support: a number or length of time that does not match the operator's own text exactly, a company the operator never named, and promises such as starting immediately or relocating. The employer's own name is not marked unless the letter says the operator worked there.
  • Draft again. A new draft is saved as proposed beside the current letter, which stays in Documents and on the application. The operator chooses Keep new draft, or Keep previous draft, which discards the proposal. Keeping the new one makes it current and the old current one the previous letter. Undo then asks first, since it deletes the newer draft and any edits to it, and brings the previous letter back exactly as it was stored. At most one proposed and one previous letter exist per role and kind, and every move between states is a conditional update, so two requests at once cannot both act.

Testing

PDF generation needs a real browser, so it is a local-required check (CLAUDE.md). Selection, resolution, validation, HTML and import logic are all testable without one. The invariants to keep covered are an enum per slot, rejection of a hallucinated key, hide only for optional slots, fallback to defaults with defaults_used, and byte-for-byte equality between bullets in the HTML and doc_variant.text.

Related

Clone this wiki locally