pub fn reduce_to_fit<F>(
full_msgs: &[ChatMessage],
base_policy: &ReductionPolicy,
prior_log: &ReductionLog,
fits: F,
) -> (Vec<ChatMessage>, ReductionLog, ReductionPolicy)Expand description
PARITY-18 v3 — the “aggressive reduction” half of the fix (SPEC.md
scaling-context-guard): apply project_messages with base_policy
first, then, if fits says the projected view still doesn’t pass,
retry with progressively tighter policies (see tighten) up to
MAX_AGGRESSIVE_LEVELS times, then escalate to A10 turn-clearing,
keeping whichever attempt is smallest. Never fails and never loops
unboundedly — it always returns SOME projection (the caller’s own
preflight guard is responsible for deciding whether even the tightest
attempt still exceeds the target model’s context limit and refusing to
send in that case, PARITY-18 dev/01).
fits is a closure over the REDUCED VIEW ALONE (this function has no
knowledge of the system prompt, tool schemas, or a trailing user
prompt — those live with the caller). It exists to close a v2 defect a
skeptical review caught (the flagship rescue-path regression): v2 had
two INDEPENDENTLY-derived boundaries — this function stopped escalating
once estimate_view_tokens(view) <= target_tokens where
target_tokens = context_limit - CONTEXT_RESPONSE_RESERVE_TOKENS, while
tokens::context_guard only ACCEPTS a request when
with_guard_margin(view + tools) + CONTEXT_RESPONSE_RESERVE_TOKENS <= context_limit — a materially tighter bound (no margin, no tools, no
system-prompt overhead counted by the reducer’s stop condition at all).
Any session whose reduced view landed in the band between those two
boundaries was declared “fits” here and then refused by the guard, with
D6 turn-clearing never triggered because this function had already
stopped. Passing tokens::context_guard itself (wrapped with the
caller’s real system prompt/tools/prompt) as fits makes that
impossible BY CONSTRUCTION: the reducer’s stopping condition and the
guard’s acceptance are now the same boundary, so a session this function
says it reduced-to-fit is a session the guard will actually send.
(resume_cmd is the sole real caller; see its fits closure there.)
Returns (view, log, policy_actually_applied) so the caller can seed
a runtime agent’s reduction policy/log setters with the exact
policy that produced the returned view (subsequent turns keep re-applying
it, resume_cmd’s existing re-reduce path).