Skip to content

Document Engine

Mark Crowle-Groves edited this page Oct 19, 2026 · 5 revisions

Checked against v0.6.1 (commit 3b06892) on October 19, 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 and accent. 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.

On any failure, select_config() returns 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.

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 actually runs in v0.5.0

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() is called from one place, the kestrel render MASTER_ID --opportunity N command in kestrel/cli.py. The web route /renders/new builds its render from default_config() and the layout the Documents page was showing, then the operator adjusts it by hand. If you add automatic selection, you need a task type, a handler and the plumbing to store rationale; none of that exists yet.

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 and accent. It is presentation only, so it writes no SelectionOverride row. A layout key the catalog does not have is refused.

Swaps and look changes update the live preview. The route docstring says a fresh PDF comes from a new test render.

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.
  • 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 with half-inch margins.
  • 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. Kestrel does not send them.

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