Repository navigation
Learning Loop Internals
Checked against commit 234f8b9 (v0.5.0) on October 18, 2026.
This page describes how Kestrel learns from the operator's own decisions: what gets recorded, how scoring weights are recalibrated, how few-shot examples reach the prompt, how the reranker is trained and promoted, how the Calibrate queue picks items, and how drift demotes a reranker. It also lists the code signals that show how far to trust a score. The code is in kestrel/learning/, with the Tier 1 fast path in kestrel/pipeline/reranker_gate.py.
Nothing here trains a language model. kestrel/learning/ledger.py states the boundary: Kestrel changes what the model is shown (few-shot examples), how dimension scores are combined (accepted calibration weights), and whether a learned reranker gates Tier 1. The loop also never acts outside the app. It does not apply, message or contact anyone on the operator's behalf (hard rule 1 in CLAUDE.md).
All thresholds below are defaults in Learning in kestrel/config.py and kestrel/resources/config/settings.yml, and the operator can override them.
| Setting | Default | Used by |
|---|---|---|
learning.min_labels_for_few_shot |
15 | Few-shot injection |
learning.few_shot_k |
3 | Few-shot injection |
learning.min_labels_for_calibration |
30 | Weight calibration |
learning.min_labels_for_reranker |
200 | Reranker training |
learning.reranker_max_mae |
0.6 | Promotion gate |
learning.reranker_uncertain_band |
0.4 | Tier 1 fast path |
learning.drift_threshold |
0.8 | Drift demotion |
Three tables hold the operator's judgments, written from places where the operator is already acting.
-
verdict_override: written by Agree, Adjust and Override on an opportunity, throughrecord_override()inkestrel/web/queries.py. Agree copies the system's verdict and score as the operator's. Adjust keeps the verdict and sets a score. Override sets both and requires a reason. -
label: written by the Calibrate queue throughrecord_label()inkestrel/learning/capture.py, viaPOST /api/learning/label. -
selection_override: written when a document slot changes after model selection (record_selection_override()). The reranker and calibration do not read it.
The UI speaks in fit words (strong fit, good fit, maybe, not a fit). verdict_for_fit() in kestrel/web/fit.py maps each word back to a stored verdict and a training score so the loop still receives a pair: strong fit is apply at 4.75, good fit apply at 4.0, maybe consider at 3.0, not a fit pass at 1.5. On the consulting track apply is stored as pursue.
labeled_examples() merges label rows and verdict_override rows that carry an operator score into one list per track. When one opportunity has several judgments, the most recent wins across both tables, so a later correction supersedes an earlier label. Each example carries the Tier 2 dimension scores the operator judged, taken from the override's evaluation, the label's stored dimensions, or the latest Tier 2 evaluation as a fallback. The list is oldest first so callers can take the most recent N.
Outcomes (record_outcome()) are a fourth signal, used only for analytics and the score-discrimination check below, not for training.
propose_calibration() in kestrel/learning/calibration.py fits new dimension weights that best predict the operator's own score from the sum of each dimension times its weight. It runs per track and needs min_labels_for_calibration examples that also have usable dimension scores. Below that it returns None.
The fit (fit_weights()) minimizes mean squared error plus a ridge penalty (_RIDGE_ALPHA = 0.02) with SciPy's SLSQP, under two constraints: every weight is between 0 and 1, and the weights sum to 1. The dimensions are fixed per track:
employment role_fit, domain_match, company_context, comp_logistics, trajectory
consulting engagement_fit, buyer_access, economics, delivery_feasibility, strategic_value
The proposal stores both weight sets and a cross-validated MAE for each. _cv_mae() uses five-fold CV (fewer folds when there are fewer than five samples), scoring the current weights as fixed and refitting the proposed weights inside each fold, on the same held-out folds. The result is a Calibration row with status proposed. Nothing is applied.
accept_calibration() writes the weights as setting rows named scoring.weights.<track>.<dimension>, which is the highest-precedence configuration layer, and marks the proposal accepted. reject_calibration() marks it rejected. Both are the operator's explicit action. kestrel calibrate only proposes. The operator accepts or rejects on the Settings page (POST /settings/calibration/{id}/{action}, kestrel/web/pages/settings.py) or through the /api/learning/calibration/... routes in kestrel/web/routes_learning.py.
Post-processing in kestrel/pipeline/scoring.py applies the weights. The verdict is derived from the score and the thresholds (4.0 for apply or pursue, 3.0 for consider), not taken from the model. Blockers and a reject legitimacy status force pass, and a suspect status caps the displayed score at 3.5.
Tier 2 can show the model a few of the operator's past judgments. _gather_few_shot() in kestrel/pipeline/tier2.py selects from label rows only, for the same track, excluding the opportunity being scored, and only those with an embedding from the current embedding model. Vectors from different models live in different spaces and are never compared.
select_few_shot() in kestrel/llm/fewshot.py then does three things:
- Returns nothing (zero-shot) if fewer than
min_labels_for_few_shotcandidates exist. - Ranks candidates by cosine similarity to the current description.
- Buckets them by verdict and takes them round-robin, ordering buckets by their best similarity, so the
few_shot_kexamples spread across verdicts. The aim is to avoid showing three positives and teaching the model to inflate.
The chosen opportunity ids are saved on the evaluation as few_shot_ids. few_shot_block() in kestrel/pipeline/context.py renders them as a "prior evaluations" block. The summary and rationale are both built from label.rationale, so the Why: line is dropped when it repeats the summary. See Prompts and Context Budgets for the token cost.
The reranker is a HistGradientBoostingRegressor (kestrel/learning/reranker.py). It replaces the Tier 1 model call for items it is confident about. The LLM path is never deleted, because it is the cold-start and fallback path.
kestrel/learning/features.py builds one vector per opportunity: the description embedding reduced by PCA to at most 64 dimensions (fewer if the corpus is smaller), plus tabular columns. The tabular columns are seniority rank, comp minimum and maximum (in thousands), whether comp is known, the Tier 0 pre-score, description tokens, times seen, ghost score, days since posted, one-hot source kind, remote type, org size band and ownership, and a binary per soft signal read from Tier 0's stage_reason. Consulting rows add one-hot trigger event type and trigger confidence. Vocabularies are fixed, so an unseen category becomes all zeros instead of shifting columns.
train_reranker() runs on demand from kestrel train or POST /api/learning/train. Nothing schedules it, and the Calibrate page shows promotion progress (promotion_status()) but has no train button. It:
- Fits the PCA on all embeddings of the current embedding model for the track.
- Builds rows for every opportunity that has an embedding and a target: the operator's score where they judged it, else the Tier 2 holistic score where they did not override it.
- Counts usable labels, meaning labeled rows that have an embedding. If that is below
min_labels_for_reranker, it returns "insufficient usable labels" and saves nothing. - Holds out 25 percent of the labeled rows (at least one, seeded), trains on the rest plus all unlabeled rows, and evaluates on the held-out set only.
The model is promoted only if all four criteria hold on the held-out set. A criterion that cannot be measured counts as failed, not as passed.
| Criterion | Rule |
|---|---|
enough_labels |
Usable labels at or above min_labels_for_reranker
|
mae_ok |
At least 5 held-out rows and MAE below reranker_max_mae
|
beats_llm |
At least 5 held-out items with an LLM Tier 1 verdict, and reranker keep/kill agreement with the operator higher than the LLM's on those same items |
recall_ok |
At least 5 held-out items the operator rated apply or pursue, and recall above 0.95 on them |
"Keep" means a score at or above thresholds.consider (3.0). Recall is measured against the operator's own verdict, not a score proxy. Each refusal reason states its sample size, so "too few held-out items" reads differently from "does not beat the LLM". The constants are _MIN_APPLY_FOR_RECALL, _MIN_HELD_FOR_MAE, _MIN_LLM_FOR_COMPARISON and _RECALL_MIN_THRESHOLD, and promotion_status() reads the same ones to render the Calibrate progress panel, so the page cannot drift from the gate.
_save_model() writes two pickles to the ML folder from kestrel/paths.py, the model and the fitted features (PCA and column layout), and an MlModel row with the sklearn version, feature names and metrics, including the embedding model name. A promoted model deactivates the previous one for that track. A model that fails the gate is still saved, inactive.
load_active_reranker() returns None, so Tier 1 falls back to the LLM, when:
- the row's embedding model differs from the current one (quiet, expected after switching embedding engines until the next retrain);
- the sklearn version differs, because pickles are version-locked (a warning notification is raised);
- an artifact file is missing or unreadable (also a notification).
try_reranker_tier1() runs before the LLM. It needs a current-model embedding of the right width. If the predicted score is within reranker_uncertain_band (0.4) of the keep cutoff (3.0), it returns None and the LLM decides. Outside the band it records a Tier 1 evaluation with forced_by="reranker", then either queues Tier 2 (keep) or sets stage t1_reject with the predicted score in the reason (kill).
Hard rule 4 still applies here: uncertainty escalates and never rejects. A reranker kill only happens at least 0.4 below the cutoff.
rank_uncertain() in kestrel/learning/active.py ranks Tier 2-evaluated opportunities that have no label or override, for the Calibrate page. Four components combine, each in the range 0 to 1:
uncertainty = 0.40 * proximity + 0.25 * divergence + 0.20 * novelty + 0.15 * recency
- proximity: how close the score is to the apply threshold (4.0), falling to zero at 1.5 points away.
- divergence: the gap between the model's holistic score and the weighted score, over 1.5, capped at 1.
- novelty: 1 minus the highest cosine similarity to any labeled example, or 0.5 when nothing can be compared.
- recency: falls to zero over 90 days since first seen.
The spec's fifth component, reranker prediction variance, is deliberately not implemented. The docstring notes that the gradient-boosted model exposes no per-tree variance. The page and GET /api/learning/queue return the top 10.
check_drift() looks at the labels recorded after the active reranker was trained, takes the last 50, scores each with the reranker and averages the absolute error. If the mean exceeds drift_threshold (0.8), it sets is_active to false, raises a reranker_drift notification and Tier 1 returns to the LLM.
Fewer than five usable post-training labels returns an "insufficient" result and never demotes. Labels the model trained on are excluded, otherwise right after promotion the window would be mostly rows the model fits by construction.
The worker calls it from kestrel/web/app.py after any cycle that completed Tier 1 work, and otherwise at most once every 900 seconds (_DRIFT_INTERVAL_S).
Use these signals the code produces, not a fixed accuracy claim.
- A fit word of "your call" means
needs_reviewis set: the holistic and weighted scores differ by more thanscoring.divergence_flag(0.75). Read the dimensions before relying on either number. - "New" and "Scoring failed" are never a rejection. A quarantined item is parked, not scored down (
fit_for()inkestrel/web/fit.py). - A
suspectlegitimacy status caps the displayed score at 3.5, and a blocker forcespass, so a low score can be a rule, not a fit judgment.forced_byon the evaluation says which. - With few labels the score reflects the shipped weights and prompt alone. Few-shot examples start at 15 labels, and a calibration proposal needs 30.
-
analyze_outcomes()inkestrel/learning/outcomes.pychecks whether the score predicted anything real. It compares response rates across score bands (below 3.0, 3.0 to 4.0, 4.0 to 4.5, 4.5 and up), requires a score-to-response correlation of at least 0.15 and a spread of at least 5 points across bands, and says plainly that the score is not discriminating when it fails. With fewer than two bands holding five or more outcomes it reports insufficient data instead of a verdict.
Every rate in these reports is shown beside its sample size and labeled insufficient under five observations (hard rule 6). The same module suggests a ghosting threshold from the 90th percentile of time to first response, again only with five or more responses. See Analytics Internals for the shared rule.
reset_learning() in kestrel/learning/ledger.py removes the three things the loop accumulates, each optional: all label and verdict_override rows, all ml_model rows plus the pickle files Kestrel wrote, and calibrations (marked rejected, with the scoring.weights.* rows deleted so shipped weights apply again). It does not touch opportunities, evaluations, pursuits, documents or outcomes.
Start here
Interfaces
Extending Kestrel
How it works
- Prompts and context budgets
- Document engine
- Learning loop internals
- Analytics internals
- Task queue and concurrency
- Database schema
Shipping and safety
- Packaging and releases
- Preflight and diagnostics
- Security and privacy model
- Outbound calls
- Benchmarking
Workarounds and Troubleshooting