Skip to content

The agent that grows with you

feat(local-runtime): context policy — fit, grow, spill deliberately

emozillab95e38757aac
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.py
index acffc45d958..70ae38efb74 100644
--- a/agent/conversation_loop.py
+++ b/agent/conversation_loop.py
@@ -420,6 +420,40 @@ def _ollama_context_limit_error(agent: Any, request_tokens: int) -> Optional[str
)
+def _maybe_grow_local_window(agent: Any, compressor: Any,
+ request_tokens: int) -> Optional[int]:
+ """Try growing the managed local model's context window before
+ compressing. Returns the new window when the ladder granted one, else
+ None (hold / at native / not a managed local session).
+
+ The window ladder's design order: models launch at their zero-spill
+ window and grow toward native max as the session needs room;
+ compression is the move of last resort. Cheap for every non-local
+ provider: one lowercase compare, no imports.
+ """
+ provider = (getattr(agent, "provider", "") or "").strip().lower()
+ if provider not in ("llamacpp", "llama.cpp", "llama-cpp", "custom"):
+ return None
+ base_url = getattr(agent, "base_url", "") or ""
+ if "127.0.0.1" not in base_url and "localhost" not in base_url:
+ return None
+ try:
+ from hermes_cli.local_runtime.growth import maybe_grow_window
+
+ current_window = int(getattr(compressor, "context_length", 0) or 0)
+ if current_window <= 0:
+ return None
+ return maybe_grow_window(
+ getattr(agent, "model", "") or "",
+ base_url=base_url,
+ session_tokens=int(request_tokens),
+ current_window=current_window,
+ )
+ except Exception as exc: # noqa: BLE001 — growth must never break a turn
+ logger.debug("local window growth check failed: %s", exc)
+ return None
+
+
def _ra():
"""Lazy reference to ``run_agent`` so callers can patch
``run_agent.handle_function_call`` / ``run_agent._set_interrupt`` /
@@ -2304,6 +2338,39 @@ def run_conversation(
and not _compression_cooldown
and _compressor.should_compress(request_pressure_tokens)
):
+ # Managed local runtime: try GROWING the context window before
+ # compressing (the window ladder's design order — compression is
+ # the move of last resort, once the window is at the model's
+ # native max or physics/speed say stop). Only fires for a
+ # llamacpp-flavored provider whose base_url is the server this
+ # process supervises; every other provider falls straight
+ # through to compression, exactly as before.
+ _grown_window = _maybe_grow_local_window(
+ agent, _compressor, request_pressure_tokens
+ )
+ if _grown_window:
+ # The server now grants a bigger window: recalibrate the
+ # compressor to it and skip compression this pass — the
+ # request that was over the OLD threshold fits the new one.
+ _compressor.update_model(
+ agent.model,
+ _grown_window,
+ base_url=getattr(agent, "base_url", "") or "",
+ api_key=getattr(agent, "api_key", "") or "",
+ provider=getattr(agent, "provider", "") or "",
+ api_mode=getattr(agent, "api_mode", "") or "",
+ )
+ agent._buffer_status(
+ f"📈 Context window grown to {_grown_window // 1024}K "
+ f"(local model; conversation continues uncompressed)"
+ )
+ # This preflight iteration never reached the provider —
+ # refund the consumed call/budget exactly as the compression
+ # path below does before ITS continue.
+ api_call_count -= 1
+ agent._api_call_count = api_call_count
+ agent.iteration_budget.refund()
+ continue
if _moa_prepared_request is not None:
pending_moa_prepared_request = _moa_prepared_request
compression_attempts += 1
diff --git a/agent/model_metadata.py b/agent/model_metadata.py
index a638798a970..f6b77ed41da 100644
--- a/agent/model_metadata.py
+++ b/agent/model_metadata.py
@@ -1375,6 +1375,35 @@ def fetch_endpoint_model_metadata(
model_alias = props.get("model_alias", "")
if n_ctx and model_alias and model_alias in cache:
cache[model_alias]["context_length"] = n_ctx
+ else:
+ # Router mode: bare /props 400s and telemetry is
+ # per-child (?model=). Enumerate children via the
+ # native /models (carries status) and read each
+ # LOADED child's granted window — the value the
+ # context policy actually granted, which the meter
+ # and compressor must follow. Unloaded children are
+ # skipped: probing them could trigger an autoload.
+ native = requests.get(base + "/models", headers=headers, timeout=5, verify=_verify)
+ if native.ok:
+ children = (native.json() or {}).get("data", [])
+ for child in children[:16]:
+ if not isinstance(child, dict):
+ continue
+ child_id = child.get("id")
+ status = (child.get("status") or {}).get("value")
+ if not child_id or child_id not in cache or status not in ("loaded", "ready"):
+ continue
+ pr = requests.get(
+ base + "/v1/props", params={"model": child_id},
+ headers=headers, timeout=5, verify=_verify)
+ if not pr.ok:
+ pr = requests.get(
+ base + "/props", params={"model": child_id},
+ headers=headers, timeout=5, verify=_verify)
+ if pr.ok:
+ child_ctx = (pr.json().get("default_generation_settings") or {}).get("n_ctx")
+ if child_ctx:
+ cache[child_id]["context_length"] = child_ctx
except Exception:
pass
diff --git a/agent/turn_context.py b/agent/turn_context.py
index dfa5fbbd8e2..5ce1c1149e7 100644
--- a/agent/turn_context.py
+++ b/agent/turn_context.py
@@ -941,6 +941,34 @@ def build_turn_context(
_compress_block_reason = _info(_preflight_tokens)[1]
except Exception:
_compress_block_reason = None
+ if _should_compress_now:
+ # Managed local runtime: growing the window beats compressing —
+ # the ladder's design order (same seam as the conversation
+ # loop's pre-API gate; see _maybe_grow_local_window there).
+ try:
+ from agent.conversation_loop import _maybe_grow_local_window
+
+ _grown = _maybe_grow_local_window(
+ agent, _compressor, _preflight_tokens
+ )
+ except Exception:
+ _grown = None
+ if _grown:
+ _compressor.update_model(
+ agent.model,
+ _grown,
+ base_url=getattr(agent, "base_url", "") or "",
+ api_key=getattr(agent, "api_key", "") or "",
+ provider=getattr(agent, "provider", "") or "",
+ api_mode=getattr(agent, "api_mode", "") or "",
+ )
+ agent._buffer_status(
+ f"📈 Context window grown to {_grown // 1024}K "
+ f"(local model; conversation continues uncompressed)"
+ )
+ _should_compress_now = _compressor.should_compress(
+ _preflight_tokens
+ )
if _should_compress_now:
_preflight_compressed = True
# Compression is actually running (block cleared / was never
diff --git a/hermes_cli/local_runtime/context_policy.py b/hermes_cli/local_runtime/context_policy.py
new file mode 100644
index 00000000000..9de467e31f3
--- /dev/null
+++ b/hermes_cli/local_runtime/context_policy.py
@@ -0,0 +1,233 @@
+"""Context policy — the window ladder for managed local models.
+
+One contract: any model runs at any window up to its native max; hardware
+and session depth only change tokens/s. Constants, not knobs — nothing in
+this module reads config.
+
+The policy encodes behavior measured on real hardware (llama.cpp,
+discrete NVIDIA GPUs on Windows/WDDM, and unified-memory devices):
+
+- Windows never over-allocates VRAM ahead of need. On WDDM, allocating
+ past residency slows decode roughly 9x even at identical conversation
+ depth — the driver silently demotes pages instead of failing. Every
+ window grant therefore re-fits against live memory at grant time.
+- Models launch at the largest window that fits entirely in GPU memory
+ (zero-spill) and grow toward their native max as the session needs
+ room, at request boundaries only.
+- Growth re-prefills the conversation into the larger window. Measured
+ cost is comparable to save/restore on discrete GPUs, and recurrent or
+ hybrid-attention models cannot rewind mid-sequence anyway, so
+ re-prefill is the only mechanism that works for every architecture.
+- Every recommended model gets at least a 64K window. When weights alone
+ exceed VRAM, the fit deliberately spills weights to host RAM to
+ protect that floor (measured: an explicit context size makes the fit
+ spill weights and hold the window rather than shrink it).
+- Below ~6 tok/s decode, growth stops and compression becomes the
+ default; deeper context is an explicit per-session choice. The deepest
+ measured host-spilled configuration bottomed out near this rate.
+- Spilled mixture-of-experts configs pin expert/FFN weights to host so
+ attention and KV stay GPU-resident — measured ~1.75x faster than
+ spilling layers naively at the same host byte count.
+- Speculative decoding (MTP) defaults on only for spilled configs, where
+ its speedup is largest (measured 1.43x spilled vs 1.35x resident).
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+from hermes_cli.local_runtime.estimator import (
+ HardwareBudget,
+ ModelProfile,
+ PhysicsRefusal,
+ ctx_bytes,
+ physics_check,
+)
+
+FLOOR = 64 * 1024 # = target; one internal constant
+_LADDER_GROWTH = 1.5
+_GROW_AT_OCCUPANCY = 0.85 # of the current window, at turn boundary
+SPEED_FLOOR_TOK_S = 6.0 # deepest measured spill bottomed near this
+_UMA_CTX_FRACTION = 0.25 # UMA guard: ctx mem <= 25% of unified
+_EARLY_COST_CTX_FRACTION = 0.15 # bounded early cost when weights spill
+
+
+def ladder(native: int) -> list[int]:
+ """64K -> 96K -> 128K -> ... -> native (native always the last rung)."""
+ rungs: list[int] = []
+ step = float(FLOOR)
+ while step < native:
+ rungs.append(int(step))
+ step *= _LADDER_GROWTH
+ rungs.append(native)
+ return rungs
+
+
+@dataclass
+class WindowDecision:
+ window: int
+ spill_bytes: int # weights displaced to host at this window
+ kv_on_gpu: bool
+ reasons: list[str] = field(default_factory=list)
+
+ @property
+ def spilled(self) -> bool:
+ return self.spill_bytes > 0
+
+
+def _uma_cap(profile: ModelProfile, budget: HardwareBudget) -> int | None:
+ if not budget.uma:
+ return None
+ cap_bytes = int(budget.total_device_bytes * _UMA_CTX_FRACTION)
+ # Largest window whose ctx fits the cap (monotone -> scan the ladder).
+ best = FLOOR
+ for rung in ladder(profile.n_ctx_train or FLOOR):
+ if ctx_bytes(profile, rung) <= cap_bytes:
+ best = rung
+ else:
+ break
+ return best
+
+
+def initial_window(profile: ModelProfile, budget: HardwareBudget,
+ *, flash_attention: bool = True) -> WindowDecision | PhysicsRefusal:
+ """The launch decision: largest cheap rung, never below the floor.
+
+ Zero-spill rung: weights + ctx fit usable VRAM entirely.
+ Bounded-early-cost rung: weights already exceed VRAM; take the largest
+ rung whose ctx stays <= ~15% of usable VRAM.
+ Floor everywhere, capped at native and the UMA guard.
+ """
+ refusal = physics_check(profile, budget, FLOOR, flash_attention=flash_attention)
+ if refusal:
+ return refusal
+
+ native = profile.n_ctx_train or FLOOR
+ uma_cap = _uma_cap(profile, budget)
+ rungs = [r for r in ladder(native) if uma_cap is None or r <= uma_cap]
+ if not rungs:
+ rungs = [min(FLOOR, native)]
+
+ reasons: list[str] = []
+ best_zero_spill: int | None = None
+ for rung in rungs:
+ need = profile.weights_bytes + ctx_bytes(profile, rung,
+ flash_attention=flash_attention)
+ if need <= budget.usable_vram_bytes:
+ best_zero_spill = rung
+ else:
+ break
+
+ if best_zero_spill is not None and best_zero_spill >= min(FLOOR, native):
+ window = best_zero_spill
+ reasons.append(f"largest zero-spill rung ({window // 1024}K)")
+ else:
+ # Weights spill from turn one (steep-curve model on a small card) —
+ # hold the floor, bound the early ctx cost.
+ cap = int(budget.usable_vram_bytes * _EARLY_COST_CTX_FRACTION)
+ window = min(FLOOR, native)
+ for rung in rungs:
+ if rung < window:
+ continue
+ if ctx_bytes(profile, rung, flash_attention=flash_attention) <= cap:
+ window = rung
+ else:
+ break
+ reasons.append(f"floor held at {window // 1024}K; weights spill (deliberate price of the guarantee)")
+
+ kv = ctx_bytes(profile, window, flash_attention=flash_attention)
+ spill = max(0, profile.weights_bytes + kv - budget.usable_vram_bytes)
+ return WindowDecision(window=window, spill_bytes=spill,
+ kv_on_gpu=kv <= budget.usable_vram_bytes,
+ reasons=reasons)
+
+
+@dataclass
+class GrowthDecision:
+ action: str # "grow" | "hold" | "compress-default"
+ next_window: int | None = None
+ reason: str = ""
+
+
+def growth_decision(profile: ModelProfile, budget: HardwareBudget, *,
+ current_window: int, session_tokens: int,
+ measured_decode_tok_s: float | None,
+ server_idle: bool,
+ flash_attention: bool = True,
+ occupancy_confirmed: bool = False) -> GrowthDecision:
+ """One growth evaluation, END-OF-TURN ONLY (caller guarantees the turn
+ boundary; recurrent state cannot rewind mid-sequence).
+
+ Gate ordering:
+ 1. occupancy (~85%) — nothing to do before the edge;
+ 2. native cap — the contract tops out at trained context;
+ 3. idleness — growth re-grants only on an otherwise-idle
+ server (concurrency design);
+ 4. speed floor — below it, compression becomes the default and deeper
+ is an explicit user choice;
+ 5. re-fit against LIVE free memory (the rung must fit residency
+ NOW, not at launch time — over-allocation is the slow path).
+
+ ``occupancy_confirmed``: the caller has independently established that
+ the session is at its window's edge (the agent's compression gate fired
+ on its own threshold). Skips gate 1 so two separately-derived edge
+ definitions can't deadlock into compress-before-grow.
+ """
+ if not occupancy_confirmed and session_tokens < current_window * _GROW_AT_OCCUPANCY:
+ return GrowthDecision("hold", reason="session below growth occupancy")
+
+ native = profile.n_ctx_train or current_window
+ if current_window >= native:
+ return GrowthDecision("compress-default",
+ reason="at native window; compression is the only move")
+
+ if not server_idle:
+ return GrowthDecision("hold", reason="server busy; re-grant deferred to idle")
+
+ if measured_decode_tok_s is not None and measured_decode_tok_s < SPEED_FLOOR_TOK_S:
+ return GrowthDecision(
+ "compress-default",
+ reason=(f"decode {measured_decode_tok_s:.1f} tok/s below the "
+ f"~{SPEED_FLOOR_TOK_S:.0f} tok/s floor; growth is now an "
+ "explicit per-session choice"))
+
+ next_rung = next((r for r in ladder(native) if r > current_window), native)
+
+ # Re-fit against live free memory: allocation beyond residency is the
+ # slow path, so a rung that no longer fits doesn't get granted.
+ kv = ctx_bytes(profile, next_rung, flash_attention=flash_attention)
+ total_need = profile.weights_bytes + kv
+ if total_need > budget.usable_vram_bytes + budget.ram_available_bytes:
+ return GrowthDecision("compress-default",
+ reason="next rung exceeds physics; compression instead")
+
+ return GrowthDecision("grow", next_window=next_rung,
+ reason=f"rung {current_window // 1024}K -> {next_rung // 1024}K")
+
+
+def spill_overrides(profile: ModelProfile) -> list[str]:
+ """-ot placement for spilled configs: expert/FFN weights to host so
+ attention + KV stay GPU-resident. MoE gets the expert pattern;
+ hybrids push recurrent-layer FFNs (their n_head_kv==0 layers carry no
+ KV worth protecting)."""
+ if profile.moe:
+ return ["-ot", r"blk\.\d+\.ffn_.*_exps\.weight=CPU"]
+ if profile.recurrent_layer_count:
+ return ["-ot", r"blk\.\d+\.ffn_.*\.weight=CPU"]
+ return [] # dense: fit's back-to-front layer cut is the only axis
+
+
+def launch_args(profile: ModelProfile, decision: WindowDecision, *,
+ flash_attention: bool = True,
+ mtp_capable: bool = False) -> list[str]:
+ """Per-model launch flags from a window decision. Explicit -c puts fit
+ into spill-weights-and-hold-ctx; q8 KV cache wherever flash attention
+ exists; -ot placement and MTP spec decode on spilled configs."""
+ args = ["-c", str(decision.window)]
+ if flash_attention:
+ args += ["-ctk", "q8_0", "-ctv", "q8_0", "-fa", "on"]
+ if decision.spilled:
+ args += spill_overrides(profile)
+ if mtp_capable:
+ args += ["--spec-type", "draft-mtp"]
+ return args
diff --git a/hermes_cli/local_runtime/estimator.py b/hermes_cli/local_runtime/estimator.py
new file mode 100644
index 00000000000..12b5b88bed7
--- /dev/null
+++ b/hermes_cli/local_runtime/estimator.py
@@ -0,0 +1,169 @@
+"""Per-layer context-memory estimator + physics check.
+
+The whole-model dense formula misprices 1M-context hybrids by ~100x; the
+per-layer walk fixes that, and every column is measured on real GGUFs:
+
+- full-attention layer: linear in T (B1: 144.0 KiB/tok on Qwen3-4B
+ f16 — formula-exact)
+- SWA layer: capped at the sliding window
+- recurrent layer (n_head_kv == 0): constant (state is ~context-free)
+- q8_0 KV = exactly 34/64 of f16 (holds on CUDA and CPU)
+- weights: exact from the tensor table (within 0.01% of the loader)
+
+The estimator is ADVISORY: fit's allocation is authoritative at launch and
+the touch generation is ground truth after it. Unknown shapes round UP
+(never underestimate memory).
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from enum import Enum
+
+from hermes_cli.local_runtime.gguf import GGUFHeader
+
+# q8_0: 34-byte blocks of 32 f16-equivalent elements (exact).
+_Q8_BYTES_PER_ELEM = 34 / 32
+_F16_BYTES_PER_ELEM = 2.0
+
+# Architectures with a known SWA layer pattern: arch -> fraction of layers
+# that are sliding-window. Unknown SWA archs conservatively treat every
+# layer as full attention (overestimate; safe direction).
+_SWA_LAYER_FRACTION = {"gemma3": 5 / 6, "gemma2": 1 / 2}
+
+# Per-recurrent-layer state allowance (bytes/seq). Deliberately generous —
+# Measured: an entire hybrid slot state is ~99 MB including 8K tokens of
+# full-attn KV, so tens of MiB total is the right order; unknown SSM shapes
+# must never underestimate.
+_RECURRENT_STATE_PER_LAYER = 4 << 20
+
+
+class LayerKind(Enum):
+ FULL = "full"
+ SWA = "swa"
+ RECURRENT = "recurrent"
+
+
+@dataclass
+class ModelProfile:
+ """Everything the policy needs, decoupled from GGUF parsing so the
+ decision-table tests can construct profiles directly (design's
+ verification plan)."""
+
+ name: str
+ weights_bytes: int
+ embd_table_bytes: int
+ n_ctx_train: int
+ layers: list[tuple[LayerKind, int]] # (kind, kv_bytes_per_token_f16);
+ # SWA/recurrent reuse the same
+ # per-token figure, capped/ignored
+ swa_window: int = 0
+ moe: bool = False
+ architecture: str = ""
+
+ @property
+ def per_token_kv_f16(self) -> int:
+ """Uncapped per-token KV cost (full + SWA share)."""
+ return sum(b for kind, b in self.layers if kind != LayerKind.RECURRENT)
+
+ @property
+ def recurrent_layer_count(self) -> int:
+ return sum(1 for kind, _ in self.layers if kind == LayerKind.RECURRENT)
+
+
+@dataclass
+class HardwareBudget:
+ """Memory the physics check may budget against.
+
+ Budget-source rule: discrete cards may trust the device
+ query (V0LITE); UMA devices must budget from OS free physical memory
+ minus headroom (day 1 — the device query lies 3x). Callers construct
+ this accordingly; the estimator just consumes it.
+ """
+
+ usable_vram_bytes: int # live free (discrete) / derived (UMA)
+ total_device_bytes: int
+ ram_available_bytes: int
+ uma: bool = False
+
+
+def profile_from_gguf(header: GGUFHeader) -> ModelProfile:
+ kv_heads = header.head_counts_kv()
+ dk, dv = header.head_dim_k, header.head_dim_v
+ swa_fraction = _SWA_LAYER_FRACTION.get(header.architecture, 0.0)
+ has_swa = header.sliding_window > 0 and swa_fraction > 0
+
+ layers: list[tuple[LayerKind, int]] = []
+ n_attn_seen = 0
+ n_attn_total = sum(1 for h in kv_heads if h > 0)
+ n_swa = round(n_attn_total * swa_fraction) if has_swa else 0
+ for heads in kv_heads:
+ if heads == 0:
+ layers.append((LayerKind.RECURRENT, 0))
+ continue
+ per_token = round(heads * (dk + dv) * _F16_BYTES_PER_ELEM)
+ # Distribute the SWA share across the first n_swa attention layers;
+ # only the full/SWA SPLIT matters to the totals, not which indexes.
+ kind = LayerKind.SWA if n_attn_seen < n_swa else LayerKind.FULL
+ layers.append((kind, per_token))
+ n_attn_seen += 1
+
+ return ModelProfile(
+ name=header.path,
+ weights_bytes=header.tensor_bytes,
+ embd_table_bytes=header.embd_table_bytes,
+ n_ctx_train=header.n_ctx_train,
+ layers=layers,
+ swa_window=header.sliding_window,
+ moe=header.expert_count > 0,
+ architecture=header.architecture,
+ )
+
+
+def kv_dtype_factor(flash_attention: bool) -> float:
+ """q8_0 with FA (every backend we ship); f16 on exotic non-FA fallbacks
+ — the 64K guarantee stands either way, the physics check just prices
+ the doubled KV (design: KV dtype is behavior, not config)."""
+ return (_Q8_BYTES_PER_ELEM / _F16_BYTES_PER_ELEM) if flash_attention else 1.0
+
+
+def ctx_bytes(profile: ModelProfile, window: int, *,
+ flash_attention: bool = True) -> int:
+ """Context memory for one window: full layers linear in T, SWA layers
+ capped at the sliding window, recurrent layers constant."""
+ factor = kv_dtype_factor(flash_attention)
+ total = 0.0
+ for kind, per_token_f16 in profile.layers:
+ if kind == LayerKind.RECURRENT:
+ total += _RECURRENT_STATE_PER_LAYER
+ elif kind == LayerKind.SWA:
+ total += per_token_f16 * factor * min(window, profile.swa_window)
+ else:
+ total += per_token_f16 * factor * window
+ return int(total)
+
+
+@dataclass
+class PhysicsRefusal:
+ """The only true refusal: weights + floor-KV + state exceed VRAM + RAM.
+ The remedy is a smaller quant, never a smaller window."""
+
+ needed_bytes: int
+ available_bytes: int
+ message: str
+
+
+def physics_check(profile: ModelProfile, budget: HardwareBudget,
+ floor: int, *, flash_attention: bool = True) -> PhysicsRefusal | None:
+ needed = (profile.weights_bytes
+ + ctx_bytes(profile, min(floor, profile.n_ctx_train or floor),
+ flash_attention=flash_attention))
+ available = budget.usable_vram_bytes + budget.ram_available_bytes
+ if needed > available:
+ gib = 1 << 30
+ return PhysicsRefusal(
+ needed_bytes=needed, available_bytes=available,
+ message=(f"{profile.name}: needs ~{needed / gib:.1f} GiB at the "
+ f"{floor // 1024}K floor but only ~{available / gib:.1f} GiB "
+ "of VRAM+RAM exist — try a smaller quant (UD-Q3/Q2)"))
+ return None
diff --git a/hermes_cli/local_runtime/gguf.py b/hermes_cli/local_runtime/gguf.py
new file mode 100644
index 00000000000..fa3e172e9da
--- /dev/null
+++ b/hermes_cli/local_runtime/gguf.py
@@ -0,0 +1,184 @@
+"""GGUF metadata + tensor-table reader (stdlib only).
+
+Feeds the per-layer context estimator: architecture, layer count, per-layer
+KV head counts (0 = recurrent layer — the hybrid discriminator), head dims,
+sliding-window config, trained context, and exact weight bytes summed from
+the tensor table (validated to within 0.01% of the loader's buffer).
+
+Reads the header only (metadata + tensor infos); never touches tensor data,
+so it is fast enough to run at picker time on multi-GB files.
+"""
+
+from __future__ import annotations
+
+import struct
+from dataclasses import dataclass, field
+from pathlib import Path
+
+_GGUF_MAGIC = b"GGUF"
+
+# ggml tensor type sizes: type_id -> (block_bytes, block_elems).
+# IQ-family sizes verified against ggml-common.h.
+_GGML_TYPE_SIZES = {
+ 0: (4, 1), 1: (2, 1), 2: (18, 32), 3: (20, 32), 6: (22, 32), 7: (24, 32),
+ 8: (34, 32), 9: (36, 32), 10: (84, 256), 11: (110, 256), 12: (144, 256),
+ 13: (176, 256), 14: (210, 256), 15: (292, 256), 16: (66, 256),
+ 17: (74, 256), 18: (98, 256), 19: (50, 256), 20: (18, 32),
+ 21: (110, 256), 22: (82, 256), 23: (136, 256), 24: (1, 1), 25: (2, 1),
+ 26: (4, 1), 27: (8, 1), 28: (8, 1), 29: (56, 256), 30: (2, 1),
+}
+
+# GGUF metadata value types.
+_V_UINT8, _V_INT8, _V_UINT16, _V_INT16 = 0, 1, 2, 3
+_V_UINT32, _V_INT32, _V_FLOAT32, _V_BOOL = 4, 5, 6, 7
+_V_STRING, _V_ARRAY, _V_UINT64, _V_INT64, _V_FLOAT64 = 8, 9, 10, 11, 12
+
+_SCALAR_FMT = {
+ _V_UINT8: "<B", _V_INT8: "<b", _V_UINT16: "<H", _V_INT16: "<h",
+ _V_UINT32: "<I", _V_INT32: "<i", _V_FLOAT32: "<f", _V_BOOL: "<?",
+ _V_UINT64: "<Q", _V_INT64: "<q", _V_FLOAT64: "<d",
+}
+
+
+@dataclass
+class GGUFHeader:
+ path: str
+ version: int
+ metadata: dict = field(default_factory=dict)
+ n_tensors: int = 0
+ tensor_bytes: int = 0 # exact sum over the tensor table
+ embd_table_bytes: int = 0 # token_embd.weight (duplicated host-side
+ # when fully offloaded)
+
+ # ── typed accessors ──────────────────────────────────────
+
+ @property
+ def architecture(self) -> str:
+ return str(self.metadata.get("general.architecture", ""))
+
+ def _arch_key(self, suffix: str):
+ return self.metadata.get(f"{self.architecture}.{suffix}")
+
+ @property
+ def n_layer(self) -> int:
+ return int(self._arch_key("block_count") or 0)
+
+ @property
+ def n_ctx_train(self) -> int:
+ return int(self._arch_key("context_length") or 0)
+
+ @property
+ def n_embd(self) -> int:
+ return int(self._arch_key("embedding_length") or 0)
+
+ @property
+ def n_head(self) -> int:
+ v = self._arch_key("attention.head_count")
+ if isinstance(v, list):
+ return int(max(v))
+ return int(v or 0)
+
+ @property
+ def full_attention_interval(self) -> int:
+ """GDN-hybrid discriminator (qwen35 family): every Nth layer is full
+ attention, the rest are linear/recurrent. 0 = not present."""
+ return int(self._arch_key("full_attention_interval") or 0)
+
+ def head_counts_kv(self) -> list[int]:
+ """Per-layer KV head counts; 0 marks a recurrent/linear layer (the
+ n_head_kv == 0 discriminator).
+
+ Three GGUF shapes, each verified against real files:
+ - per-layer array (nemotron_h_moe): use as-is;
+ - scalar + full_attention_interval (qwen35): the scalar applies to
+ every INTERVAL-th layer (1-indexed: layers where (i+1) % N == 0),
+ zero elsewhere — pricing all layers as attention was a 4x
+ overestimate on Qwen3.6-27B;
+ - plain scalar (dense): broadcast to every layer.
+ """
+ v = self._arch_key("attention.head_count_kv")
+ if isinstance(v, list):
+ return [int(x) for x in v]
+ scalar = int(v or 0)
+ interval = self.full_attention_interval
+ if interval > 1:
+ return [scalar if (i + 1) % interval == 0 else 0
+ for i in range(self.n_layer)]
+ return [scalar] * self.n_layer
+
+ @property
+ def head_dim_k(self) -> int:
+ v = self._arch_key("attention.key_length")
+ if v:
+ return int(v)
+ return self.n_embd // self.n_head if self.n_head else 0
+
+ @property
+ def head_dim_v(self) -> int:
+ v = self._arch_key("attention.value_length")
+ if v:
+ return int(v)
+ return self.head_dim_k
+
+ @property
+ def sliding_window(self) -> int:
+ return int(self._arch_key("attention.sliding_window") or 0)
+
+ @property
+ def expert_count(self) -> int:
+ return int(self._arch_key("expert_count") or 0)
+
+
+def read_gguf_header(path: str | Path) -> GGUFHeader:
+ path = Path(path)
+
+ def read_str(f) -> str:
+ (n,) = struct.unpack("<Q", f.read(8))
+ return f.read(n).decode("utf-8", errors="replace")
+
+ def read_value(f, vtype: int):
+ if vtype == _V_STRING:
+ return read_str(f)
+ if vtype == _V_ARRAY:
+ (etype,) = struct.unpack("<I", f.read(4))
+ (n,) = struct.unpack("<Q", f.read(8))
+ return [read_value(f, etype) for _ in range(n)]
+ fmt = _SCALAR_FMT[vtype]
+ (value,) = struct.unpack(fmt, f.read(struct.calcsize(fmt)))
+ return value
+
+ with open(path, "rb") as f:
+ if f.read(4) != _GGUF_MAGIC:
+ raise ValueError(f"not a GGUF file: {path}")
+ (version,) = struct.unpack("<I", f.read(4))
+ n_tensors, n_kv = struct.unpack("<QQ", f.read(16))
+
+ metadata: dict = {}
+ for _ in range(n_kv):
+ key = read_str(f)
+ (vtype,) = struct.unpack("<I", f.read(4))
+ metadata[key] = read_value(f, vtype)
+
+ tensor_bytes = 0
+ embd_bytes = 0
+ for _ in range(n_tensors):
+ name = read_str(f)
+ (n_dims,) = struct.unpack("<I", f.read(4))
+ dims = struct.unpack(f"<{n_dims}Q", f.read(8 * n_dims))
+ (ttype,) = struct.unpack("<I", f.read(4))
+ f.read(8) # offset
+ size = _GGML_TYPE_SIZES.get(ttype)
+ if size is None:
+ raise ValueError(f"unknown ggml tensor type {ttype} in {path}")
+ block_bytes, block_elems = size
+ elems = 1
+ for d in dims:
+ elems *= d
+ nbytes = (elems // block_elems) * block_bytes
+ tensor_bytes += nbytes
+ if name == "token_embd.weight":
+ embd_bytes = nbytes
+
+ return GGUFHeader(path=str(path), version=version, metadata=metadata,
+ n_tensors=n_tensors, tensor_bytes=tensor_bytes,
+ embd_table_bytes=embd_bytes)
diff --git a/hermes_cli/local_runtime/growth.py b/hermes_cli/local_runtime/growth.py
new file mode 100644
index 00000000000..6ca09cc285d
--- /dev/null
+++ b/hermes_cli/local_runtime/growth.py
@@ -0,0 +1,139 @@
+"""In-session context growth for the managed llama.cpp runtime.
+
+The live half of the window ladder (context_policy.growth_decision): when a
+session reaches the edge of its granted window, Hermes grows the window
+toward the model's native max INSTEAD of compressing. Compression becomes
+what the design says it is — the move of last resort, once the window is at
+native (or the speed floor / physics say stop).
+
+Mechanism: growth is re-prefill. A per-model window
+override is persisted, presets regenerate with the bigger window, the
+supervised server bounces, and the next request autoloads the model at the
+new window and re-prefills the conversation. Nothing about the Hermes
+conversation mutates — no prompt-cache or role-alternation risk; the whole
+operation is server-side.
+
+Scope guard: only a server THIS process supervises grows. Detected external
+servers and other-process supervisors keep their own policies.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+
+from hermes_constants import get_hermes_home
+
+logger = logging.getLogger(__name__)
+
+
+def window_overrides_path():
+ return get_hermes_home() / "runtimes" / "llamacpp" / "window_overrides.json"
+
+
+def load_window_overrides() -> dict:
+ """model_id -> granted window (int). Empty on any read problem."""
+ try:
+ with open(window_overrides_path(), encoding="utf-8") as fh:
+ data = json.load(fh)
+ return {str(k): int(v) for k, v in data.items()}
+ except Exception: # noqa: BLE001
+ return {}
+
+
+def save_window_override(model_id: str, window: int) -> None:
+ overrides = load_window_overrides()
+ overrides[model_id] = int(window)
+ path = window_overrides_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(overrides, indent=1), encoding="utf-8")
+
+
+def clear_window_override(model_id: str) -> None:
+ """Drop a model's growth state (delete/re-download paths)."""
+ overrides = load_window_overrides()
+ if model_id in overrides:
+ del overrides[model_id]
+ window_overrides_path().write_text(
+ json.dumps(overrides, indent=1), encoding="utf-8")
+
+
+def is_managed_endpoint(base_url: str) -> bool:
+ """True when base_url is the server this process's state file points at."""
+ try:
+ from hermes_cli.local_runtime.endpoint import _state_endpoint
+
+ state = _state_endpoint()
+ if state is None:
+ return False
+ return (base_url or "").rstrip("/") == str(
+ state.get("base_url", "")).rstrip("/")
+ except Exception: # noqa: BLE001
+ return False
+
+
+def maybe_grow_window(model_id: str, *, base_url: str, session_tokens: int,
+ current_window: int,
+ measured_decode_tok_s: float | None = None) -> int | None:
+ """One growth evaluation + execution. Returns the NEW window when the
+ ladder granted a bigger one, else None (hold / compress / not ours).
+
+ The caller sits at a request boundary by construction (the pre-API
+ compression gate), so re-prefill growth is safe at any call: the next
+ request rebuilds server state from scratch in the larger window —
+ nothing rewinds.
+ """
+ from hermes_cli.local_runtime.bootstrap import (
+ get_supervisor,
+ refresh_local_runtime,
+ staged_models,
+ )
+ from hermes_cli.local_runtime.context_policy import growth_decision
+ from hermes_cli.local_runtime.estimator import profile_from_gguf
+ from hermes_cli.local_runtime.gguf import read_gguf_header
+ from hermes_cli.local_runtime.hardware import probe_budget
+
+ sup = get_supervisor()
+ if sup is None or not is_managed_endpoint(base_url):
+ return None
+
+ gguf = next((p for p in staged_models()
+ if p.stem.startswith(model_id) or model_id in p.stem), None)
+ if gguf is None:
+ return None
+
+ try:
+ profile = profile_from_gguf(read_gguf_header(gguf))
+ except (ValueError, OSError) as exc:
+ logger.debug("growth skip %s: unreadable gguf (%s)", model_id, exc)
+ return None
+
+ try:
+ server_idle = sup.is_idle(model_id)
+ except Exception: # noqa: BLE001
+ server_idle = False
+
+ decision = growth_decision(
+ profile, probe_budget(),
+ current_window=current_window,
+ session_tokens=session_tokens,
+ measured_decode_tok_s=measured_decode_tok_s,
+ server_idle=server_idle,
+ # The caller IS the occupancy signal: this runs from the agent's
+ # compression gate, which fired on its own threshold. Two
+ # separately-derived edges must not deadlock into
+ # compress-before-grow.
+ occupancy_confirmed=True,
+ )
+ if decision.action != "grow" or not decision.next_window:
+ logger.debug("growth %s: %s (%s)", model_id, decision.action, decision.reason)
+ return None
+
+ logger.info("context growth %s: %s", model_id, decision.reason)
+ save_window_override(model_id, decision.next_window)
+ if not refresh_local_runtime():
+ # The override still lands at the next boot; report no growth NOW
+ # so the caller compresses instead of overflowing a stale window.
+ logger.warning("growth %s: server refresh failed; compression proceeds", model_id)
+ return None
+ return decision.next_window
diff --git a/hermes_cli/local_runtime/presets.py b/hermes_cli/local_runtime/presets.py
new file mode 100644
index 00000000000..9ee60ca3f08
--- /dev/null
+++ b/hermes_cli/local_runtime/presets.py
@@ -0,0 +1,170 @@
+"""Per-model preset generation (--models-preset INI) — the router-side
+carrier for context-policy launch decisions.
+
+The INI shape is what the router itself generates per child: a
+[model-id] section whose keys are long-form
+llama-server flag names without the leading dashes.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from pathlib import Path
+
+from hermes_cli.local_runtime.context_policy import (
+ WindowDecision,
+ initial_window,
+ launch_args,
+)
+from hermes_cli.local_runtime.estimator import (
+ HardwareBudget,
+ PhysicsRefusal,
+ profile_from_gguf,
+)
+from hermes_cli.local_runtime.gguf import read_gguf_header
+
+logger = logging.getLogger(__name__)
+
+# args list -> INI keys. Flags the policy owns; everything else stays out
+# of the preset (recipe sampling defaults merge in a later pass).
+_FLAG_TO_KEY = {
+ "-c": "ctx-size",
+ "-ctk": "cache-type-k",
+ "-ctv": "cache-type-v",
+ "-fa": "flash-attn",
+ "-ot": "override-tensor",
+ "--spec-type": "spec-type",
+}
+
+
+@dataclass
+class PresetEntry:
+ model_id: str
+ window: int
+ spilled: bool
+ refusal: str | None = None
+ keys: dict[str, str] | None = None
+
+
+def _args_to_keys(args: list[str]) -> dict[str, str]:
+ keys: dict[str, str] = {}
+ i = 0
+ while i < len(args):
+ flag = args[i]
+ key = _FLAG_TO_KEY.get(flag)
+ if key is None:
+ i += 1
+ continue
+ keys[key] = args[i + 1]
+ i += 2
+ return keys
+
+
+def generate_presets(models_dir: Path, budget: HardwareBudget,
+ preset_path: Path,
+ mtp_capable: set[str] | None = None) -> list[PresetEntry]:
+ """Walk the staged models, run the launch decision per model, and
+ write one INI. Refused models get no section (the router simply won't
+ have policy for them; the picker surfaces the refusal + smaller-quant
+ suggestion from the returned entries).
+
+ Catalog-declared companions merge in here: sampling defaults (policy
+ keys always win), the vision projector when present, and a spec-decode
+ draft model iff the decision spilled — the rule: speculative
+ decode is a spill amplifier, so a resident draft accelerates a spilled
+ main model; a zero-spill model doesn't pay the draft's memory."""
+ from hermes_cli.local_runtime.bootstrap import assets_dir
+ from hermes_cli.local_runtime.catalog import find_entry_for_model
+
+ entries: list[PresetEntry] = []
+ sections: list[str] = []
+ for gguf in _staged_in(models_dir):
+ model_id = _strip_part(gguf.stem)
+ try:
+ profile = profile_from_gguf(read_gguf_header(gguf))
+ except (ValueError, OSError) as exc:
+ logger.warning("preset skip %s: %s", gguf.name, exc)
+ continue
+ decision = initial_window(profile, budget)
+ if isinstance(decision, PhysicsRefusal):
+ entries.append(PresetEntry(model_id=model_id, window=0,
+ spilled=False, refusal=decision.message))
+ continue
+
+ # Session growth (growth.py): a persisted override lifts the launch
+ # window to where the ladder last grew it — capped at native, and
+ # only when physics still clears the bigger window on THIS boot's
+ # budget (a smaller-VRAM day re-fits honestly back down).
+ try:
+ from hermes_cli.local_runtime.estimator import ctx_bytes
+ from hermes_cli.local_runtime.growth import load_window_overrides
+
+ override = load_window_overrides().get(model_id)
+ native = profile.n_ctx_train or decision.window
+ if override and override > decision.window:
+ target = min(int(override), native)
+ kv = ctx_bytes(profile, target)
+ if (profile.weights_bytes + kv
+ <= budget.usable_vram_bytes + budget.ram_available_bytes):
+ spill = max(0, profile.weights_bytes + kv - budget.usable_vram_bytes)
+ decision = WindowDecision(
+ window=target, spill_bytes=spill,
+ kv_on_gpu=kv <= budget.usable_vram_bytes,
+ reasons=[f"grown window restored ({target // 1024}K)"])
+ except Exception as exc: # noqa: BLE001 — overrides are advisory
+ logger.debug("window override skipped for %s: %s", model_id, exc)
+
+ args = launch_args(profile, decision,
+ mtp_capable=model_id in (mtp_capable or set()))
+ keys = _args_to_keys(args)
+
+ hit = find_entry_for_model(model_id)
+ if hit is not None:
+ entry, _variant = hit
+ # Sampling defaults under the policy keys (policy wins on clash).
+ for k, v in (entry.sampling or {}).items():
+ keys.setdefault(k, v)
+ if entry.mmproj is not None:
+ mmproj_path = assets_dir() / entry.mmproj.local_name
+ if mmproj_path.exists():
+ keys["mmproj"] = str(mmproj_path)
+ if entry.draft is not None and decision.spilled:
+ draft_path = assets_dir() / entry.draft.local_name
+ if draft_path.exists():
+ keys["model-draft"] = str(draft_path)
+ keys["spec-type"] = "draft-dspark"
+ # Unsloth's measured cliff: acceptance 83% at 2-3
+ # drafts, collapses at 4.
+ keys["spec-draft-n-max"] = "3"
+
+ entries.append(PresetEntry(model_id=model_id, window=decision.window,
+ spilled=decision.spilled, keys=keys))
+ body = "\n".join(f"{k} = {v}" for k, v in keys.items())
+ sections.append(f"[{model_id}]\n{body}\n")
+
+ preset_path.parent.mkdir(parents=True, exist_ok=True)
+ preset_path.write_text("\n".join(sections), encoding="utf-8")
+ logger.info("wrote %d preset sections to %s", len(sections), preset_path)
+ return entries
+
+
+def _strip_part(stem: str) -> str:
+ import re
+
+ return re.sub(r"-\d{5}-of-\d{5}$", "", stem)
+
+
+def _staged_in(models_dir: Path) -> "list[Path]":
+ """Servable models in an arbitrary directory (split first-parts only) —
+ the validation harness points at non-default dirs."""
+ import re
+
+ part = re.compile(r"-(\d{5})-of-\d{5}\.gguf$")
+ out = []
+ for p in sorted(models_dir.glob("*.gguf")):
+ m = part.search(p.name)
+ if m and m.group(1) != "00001":
+ continue
+ out.append(p)
+ return out
diff --git a/tests/hermes_cli/test_context_policy.py b/tests/hermes_cli/test_context_policy.py
new file mode 100644
index 00000000000..f098cb6eb3c
--- /dev/null
+++ b/tests/hermes_cli/test_context_policy.py
@@ -0,0 +1,326 @@
+"""Context-policy decision-table tests (Rollout 3).
+
+Per the design's verification plan: synthetic per-layer profiles ->
+relationships, never exact numbers. Real-model spot checks pin the
+estimator to constants measured on real GGUFs (those ARE relationships —
+constants with tolerance bands, not change-detecting catalog snapshots).
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from hermes_cli.local_runtime.context_policy import (
+ FLOOR,
+ SPEED_FLOOR_TOK_S,
+ GrowthDecision,
+ WindowDecision,
+ growth_decision,
+ initial_window,
+ ladder,
+ launch_args,
+ spill_overrides,
+)
+from hermes_cli.local_runtime.estimator import (
+ HardwareBudget,
+ LayerKind,
+ ModelProfile,
+ PhysicsRefusal,
+ ctx_bytes,
+ kv_dtype_factor,
+ physics_check,
+)
+
+GIB = 1 << 30
+KIB = 1024
+
+
+# ── synthetic profiles (per-layer tuples, per the verification plan) ──
+
+
+def dense(name="dense-32b", layers=64, per_token_f16=4096, weights_gib=20,
+ native=128 * 1024) -> ModelProfile:
+ return ModelProfile(
+ name=name, weights_bytes=weights_gib * GIB, embd_table_bytes=0,
+ n_ctx_train=native,
+ layers=[(LayerKind.FULL, per_token_f16)] * layers)
+
+
+def hybrid(name="hybrid-30b", full_layers=16, recurrent_layers=48,
+ per_token_f16=4096, weights_gib=22, native=1024 * 1024) -> ModelProfile:
+ layers = ([(LayerKind.FULL, per_token_f16)] * full_layers
+ + [(LayerKind.RECURRENT, 0)] * recurrent_layers)
+ return ModelProfile(name=name, weights_bytes=weights_gib * GIB,
+ embd_table_bytes=0, n_ctx_train=native, layers=layers)
+
+
+def moe(name="moe-30b", layers=48, per_token_f16=3072, weights_gib=17,
+ native=256 * 1024) -> ModelProfile:
+ return ModelProfile(name=name, weights_bytes=weights_gib * GIB,
+ embd_table_bytes=0, n_ctx_train=native,
+ layers=[(LayerKind.FULL, per_token_f16)] * layers,
+ moe=True)
+
+
+def card(vram_gib, ram_gib=64, uma=False) -> HardwareBudget:
+ return HardwareBudget(usable_vram_bytes=int(vram_gib * GIB),
+ total_device_bytes=int(vram_gib * GIB),
+ ram_available_bytes=int(ram_gib * GIB), uma=uma)
+
+
+# ── estimator invariants ─────────────────────────────────────
+
+
+def test_full_attention_linear_in_window():
+ p = dense()
+ b32, b64, b128 = (ctx_bytes(p, w * KIB) for w in (32, 64, 128))
+ assert abs(b64 / b32 - 2) < 0.01
+ assert abs(b128 / b64 - 2) < 0.01
+
+
+def test_recurrent_state_constant_in_window():
+ p = hybrid()
+ full_share_32 = ctx_bytes(p, 32 * KIB)
+ full_share_1m = ctx_bytes(p, 1024 * KIB)
+ # Grows only through the 16 full-attn layers — the recurrent share is
+ # identical, so the ratio tracks the full-attn ratio exactly.
+ full_only = ModelProfile(name="x", weights_bytes=0, embd_table_bytes=0,
+ n_ctx_train=p.n_ctx_train,
+ layers=[(LayerKind.FULL, 4096)] * 16)
+ expected_delta = ctx_bytes(full_only, 1024 * KIB) - ctx_bytes(full_only, 32 * KIB)
+ assert abs((full_share_1m - full_share_32) - expected_delta) <= 1
+
+
+def test_swa_layers_capped_at_window():
+ p = ModelProfile(
+ name="swa", weights_bytes=0, embd_table_bytes=0, n_ctx_train=128 * KIB,
+ layers=[(LayerKind.SWA, 4096)] * 5 + [(LayerKind.FULL, 4096)] * 1,
+ swa_window=1024)
+ small, big = ctx_bytes(p, 4 * KIB), ctx_bytes(p, 32 * KIB)
+ # Full layer grew 8x; the 5 SWA layers stayed capped at 1024 — total
+ # growth must land well under the all-full 8x (here ~4.1x).
+ assert big / small < 0.6 * 8
+
+
+def test_q8_factor_is_exactly_34_over_64():
+ assert kv_dtype_factor(True) == pytest.approx(34 / 64)
+ assert kv_dtype_factor(False) == 1.0
+
+
+def test_non_fa_fallback_doubles_ctx_cost():
+ p = dense()
+ assert ctx_bytes(p, FLOOR, flash_attention=False) == pytest.approx(
+ ctx_bytes(p, FLOOR, flash_attention=True) * 64 / 34, rel=0.001)
+
+
+def test_hybrid_vs_dense_100x_class_spread():
+ """The whole reason for the per-layer walk: equal-size models, ~100x
+ per-token spread between classic dense and a mostly-recurrent hybrid."""
+ d = dense(layers=64, per_token_f16=8192) # 256 KiB/tok class
+ h = hybrid(full_layers=4, recurrent_layers=60, per_token_f16=8192)
+ window = 256 * KIB
+ dense_cost = ctx_bytes(d, window)
+ hybrid_cost = ctx_bytes(h, window)
+ assert dense_cost / hybrid_cost > 10
+
+
+# ── measured-constant spot checks (real models, tolerance bands) ──
+
+
+def test_measured_dense_4b_per_token():
+ """Qwen3-4B: 36 layers x 8 kv-heads x (128+128) x 2B = 144 KiB/tok f16."""
+ p = ModelProfile(name="qwen3-4b", weights_bytes=0, embd_table_bytes=0,
+ n_ctx_train=262144,
+ layers=[(LayerKind.FULL, 8 * 256 * 2)] * 36)
+ per_token_bytes = ctx_bytes(p, 32 * KIB, flash_attention=False) / (32 * KIB)
+ assert per_token_bytes == pytest.approx(144 * KIB, rel=0.02)
+
+
+def test_measured_gdn_27b_per_token_q8():
+ """Qwen3.6-27B: 16 full-attn of 64; measured 34.0 KiB/tok @ q8 (B4).
+ Per-layer f16 = 34 KiB * 64/34 / 16 = 4 KiB."""
+ per_layer_f16 = 4 * KIB
+ kv_only = ModelProfile(name="kv", weights_bytes=0, embd_table_bytes=0,
+ n_ctx_train=262144,
+ layers=[(LayerKind.FULL, per_layer_f16)] * 16)
+ per_token_bytes = ctx_bytes(kv_only, 128 * KIB) / (128 * KIB)
+ assert per_token_bytes == pytest.approx(34 * KIB, rel=0.02)
+
+
+def test_measured_nemotron_1m_within_band():
+ """1M @ q8 measured 3264 MiB KV (B3): ~3.19 KiB/token TOTAL across the
+ 16 full-attn layers -> per-layer f16 ~384 B. Estimator must land in the
+ measured band, not the dense-formula 100x miss."""
+ p = hybrid(full_layers=16, recurrent_layers=46, per_token_f16=384,
+ native=1024 * KIB)
+ total = ctx_bytes(p, 1024 * KIB)
+ assert 2.5 * GIB < total < 4.0 * GIB
+
+
+# ── physics check ────────────────────────────────────────────
+
+
+def test_physics_refusal_only_past_vram_plus_ram():
+ p = dense(weights_gib=60)
+ ok = physics_check(p, card(24, ram_gib=64), FLOOR)
+ assert ok is None # 60 GiB weights fit in 24+64
+ refused = physics_check(p, card(24, ram_gib=16), FLOOR)
+ assert isinstance(refused, PhysicsRefusal)
+ assert "smaller quant" in refused.message
+
+
+def test_physics_check_prices_at_floor_not_native():
+ """A 1M-native hybrid must not be refused for its native window —
+ the check prices the floor only."""
+ p = hybrid(weights_gib=22)
+ assert physics_check(p, card(24, ram_gib=8), FLOOR) is None
+
+
+# ── ladder + initial window ──────────────────────────────────
+
+
+def test_ladder_shape():
+ rungs = ladder(262144)
+ assert rungs[0] == FLOOR
+ assert rungs[-1] == 262144
+ assert all(a < b for a, b in zip(rungs, rungs[1:]))
+ # geometric-ish: each step grows, none more than 2x
+ assert all(b / a <= 2.0 for a, b in zip(rungs, rungs[1:]))
+
+
+def test_initial_window_never_below_floor_and_never_above_native():
+ for profile in (dense(), hybrid(), moe(), dense(native=32 * KIB)):
+ for vram in (8, 16, 24, 32):
+ d = initial_window(profile, card(vram))
+ if isinstance(d, WindowDecision):
+ assert d.window >= min(FLOOR, profile.n_ctx_train)
+ assert d.window <= profile.n_ctx_train
+
+
+def test_initial_window_monotone_in_vram():
+ p = dense()
+ windows = []
+ for vram in (8, 12, 16, 24, 32, 48):
+ d = initial_window(p, card(vram))
+ assert isinstance(d, WindowDecision)
+ windows.append(d.window)
+ assert all(a <= b for a, b in zip(windows, windows[1:]))
+
+
+def test_flat_curve_reaches_native_where_dense_does_not():
+ """Design invariant: equal-size hybrid rides to native spill-free where
+ the dense model cannot. Hybrid KV priced at the B3 class (~3.2 KiB/tok
+ total: per-layer f16 384 B x 16 layers)."""
+ h = hybrid(weights_gib=18, native=1024 * KIB, per_token_f16=384)
+ d = dense(weights_gib=18, per_token_f16=8192, native=1024 * KIB)
+ vram = card(24)
+ dh = initial_window(h, vram)
+ dd = initial_window(d, vram)
+ assert isinstance(dh, WindowDecision) and isinstance(dd, WindowDecision)
+ assert dh.window == 1024 * KIB and not dh.spilled
+ assert dd.window < 1024 * KIB
+
+
+def test_dense_on_small_card_holds_floor_and_spills():
+ """The deliberate price of the guarantee (design table: dense 32B on
+ 24 GB starts at the floor with a few GiB spilled)."""
+ d = initial_window(dense(weights_gib=20), card(12))
+ assert isinstance(d, WindowDecision)
+ assert d.window == FLOOR
+ assert d.spilled
+
+
+def test_uma_guard_caps_context_memory():
+ p = hybrid(weights_gib=8, native=1024 * KIB)
+ unified = card(48, ram_gib=0, uma=True)
+ d = initial_window(p, unified)
+ assert isinstance(d, WindowDecision)
+ assert ctx_bytes(p, d.window) <= unified.total_device_bytes * 0.25 + 1
+
+
+# ── growth ───────────────────────────────────────────────────
+
+
+def _grow(profile, budget, **kw):
+ defaults = dict(current_window=FLOOR, session_tokens=int(FLOOR * 0.9),
+ measured_decode_tok_s=40.0, server_idle=True)
+ defaults.update(kw)
+ return growth_decision(profile, budget, **defaults)
+
+
+def test_growth_holds_below_occupancy():
+ d = _grow(dense(), card(24), session_tokens=int(FLOOR * 0.5))
+ assert d.action == "hold"
+
+
+def test_growth_requires_idle_server():
+ d = _grow(dense(), card(24), server_idle=False)
+ assert d.action == "hold"
+ assert "idle" in d.reason
+
+
+def test_growth_steps_one_rung_and_is_monotone():
+ p = dense(native=262144)
+ d = _grow(p, card(32))
+ assert d.action == "grow"
+ assert d.next_window > FLOOR
+ rungs = ladder(262144)
+ assert d.next_window == rungs[rungs.index(FLOOR) + 1]
+
+
+def test_growth_stops_at_native():
+ p = dense(native=128 * KIB)
+ d = _grow(p, card(48), current_window=128 * KIB,
+ session_tokens=int(128 * KIB * 0.9))
+ assert d.action == "compress-default"
+
+
+def test_speed_floor_flips_default_to_compression():
+ d = _grow(dense(), card(24), measured_decode_tok_s=SPEED_FLOOR_TOK_S - 2)
+ assert d.action == "compress-default"
+ assert "explicit per-session choice" in d.reason
+
+
+def test_growth_refits_against_live_budget():
+ """V3C: a rung that no longer fits (external pressure ate the memory)
+ is not granted."""
+ p = dense(weights_gib=20)
+ starved = card(2, ram_gib=1)
+ d = _grow(p, starved)
+ assert d.action == "compress-default"
+ assert "physics" in d.reason
+
+
+# ── spill placement + launch args ────────────────────────────
+
+
+def test_spill_overrides_prefer_expert_and_recurrent_ffn():
+ assert "exps" in " ".join(spill_overrides(moe()))
+ assert "ffn" in " ".join(spill_overrides(hybrid()))
+ assert spill_overrides(dense()) == []
+
+
+def test_launch_args_contract():
+ p = moe()
+ spilled = WindowDecision(window=FLOOR, spill_bytes=4 * GIB, kv_on_gpu=True)
+ resident = WindowDecision(window=131072, spill_bytes=0, kv_on_gpu=True)
+
+ a = launch_args(p, spilled, mtp_capable=True)
+ assert a[:2] == ["-c", str(FLOOR)] # explicit -c: A3 semantics
+ assert "q8_0" in a # B6 dtype behavior
+ assert "-ot" in a # D2 placement
+ assert "--spec-type" in a # D5: MTP on iff spilled
+
+ b = launch_args(p, resident, mtp_capable=True)
+ assert "-ot" not in b and "--spec-type" not in b
+
+ c = launch_args(p, spilled, flash_attention=False, mtp_capable=False)
+ assert "q8_0" not in c # f16 on non-FA fallback
+
+
+def test_no_refusal_branch_past_physics():
+ """Design invariant: anything past the physics check is servable —
+ initial_window never refuses on its own."""
+ for vram in (4, 6, 8, 12):
+ d = initial_window(dense(weights_gib=20), card(vram, ram_gib=64))
+ assert isinstance(d, WindowDecision)
diff --git a/tests/hermes_cli/test_local_growth.py b/tests/hermes_cli/test_local_growth.py
new file mode 100644
index 00000000000..2b0e9f77ea4
--- /dev/null
+++ b/tests/hermes_cli/test_local_growth.py
@@ -0,0 +1,189 @@
+"""In-session growth contracts (growth.py + the presets override seam).
+
+The live half of the window ladder: grow before compress, overrides
+persist across boots, physics re-checked every boot, growth state dies
+with the model."""
+
+from __future__ import annotations
+
+import pytest
+
+
+def hermes_home(tmp_path, monkeypatch):
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ return home
+
+
+def test_overrides_roundtrip_and_clear(hermes_home):
+ from hermes_cli.local_runtime.growth import (
+ clear_window_override,
+ load_window_overrides,
+ save_window_override,
+ )
+
+ assert load_window_overrides() == {}
+ save_window_override("model-a", 98304)
+ save_window_override("model-b", 262144)
+ assert load_window_overrides() == {"model-a": 98304, "model-b": 262144}
+ clear_window_override("model-a")
+ assert load_window_overrides() == {"model-b": 262144}
+ # Clearing a missing key is a no-op, not an error.
+ clear_window_override("never-existed")
+
+
+def test_corrupt_overrides_read_as_empty(hermes_home):
+ from hermes_cli.local_runtime.growth import (
+ load_window_overrides,
+ window_overrides_path,
+ )
+
+ path = window_overrides_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text("{not json", encoding="utf-8")
+ assert load_window_overrides() == {}
+
+
+def test_growth_declines_foreign_endpoints(hermes_home):
+ """Only the server THIS process supervises grows — a detected external
+ server or another process's endpoint returns None untouched."""
+ from hermes_cli.local_runtime.growth import maybe_grow_window
+
+ grown = maybe_grow_window(
+ "some-model", base_url="http://127.0.0.1:9999/v1",
+ session_tokens=100_000, current_window=65536)
+ assert grown is None
+
+
+def test_occupancy_confirmed_skips_gate_one():
+ """The agent's compression gate IS the occupancy signal: when it fired,
+ growth must not re-derive its own edge and hold. Decision-table check
+ with a synthetic profile."""
+ from hermes_cli.local_runtime.context_policy import growth_decision
+ from hermes_cli.local_runtime.estimator import (
+ HardwareBudget,
+ LayerKind,
+ ModelProfile,
+ )
+
+ gib = 1 << 30
+ profile = ModelProfile(
+ name="m", weights_bytes=2 * gib, embd_table_bytes=0,
+ n_ctx_train=262144,
+ layers=[(LayerKind.FULL, 4096)] * 16 + [(LayerKind.RECURRENT, 0)] * 48)
+ budget = HardwareBudget(usable_vram_bytes=26 * gib,
+ total_device_bytes=32 * gib,
+ ram_available_bytes=64 * gib)
+
+ # Hermes' threshold (e.g. 80% of window) can sit BELOW the ladder's 85%
+ # occupancy gate: 78K of a 96K window is 81%.
+ kwargs = dict(current_window=98304, session_tokens=78_000,
+ measured_decode_tok_s=None, server_idle=True)
+ ungated = growth_decision(profile, budget, **kwargs)
+ assert ungated.action == "hold", "sanity: below the ladder's own gate"
+
+ confirmed = growth_decision(profile, budget, occupancy_confirmed=True, **kwargs)
+ assert confirmed.action == "grow"
+ assert confirmed.next_window and confirmed.next_window > 98304
+
+
+def _stage_fake_gguf(mdir, name):
+ mdir.mkdir(parents=True, exist_ok=True)
+ (mdir / f"{name}.gguf").write_bytes(b"GGUF" + b"\x00" * 64)
+
+
+def _tiny_profile(model_id: str):
+ from hermes_cli.local_runtime.estimator import LayerKind, ModelProfile
+
+ gib = 1 << 30
+ return ModelProfile(
+ name=model_id, weights_bytes=2 * gib, embd_table_bytes=0,
+ n_ctx_train=131072,
+ layers=[(LayerKind.FULL, 512)] * 4)
+
+
+def test_preset_restores_grown_window_capped_at_native(hermes_home, tmp_path, monkeypatch):
+ """A persisted override lifts the preset window; an absurd override is
+ capped at native. GGUF parsing is stubbed — the contract under test is
+ the override plumbing, not the reader."""
+ import hermes_cli.local_runtime.presets as presets_mod
+
+ from hermes_cli.local_runtime.estimator import HardwareBudget
+ from hermes_cli.local_runtime.growth import save_window_override
+
+ mdir = tmp_path / "models"
+ _stage_fake_gguf(mdir, "tiny-dense")
+ monkeypatch.setattr(presets_mod, "read_gguf_header", lambda p: p)
+ monkeypatch.setattr(presets_mod, "profile_from_gguf",
+ lambda h: _tiny_profile("tiny-dense"))
+
+ gib = 1 << 30
+ budget = HardwareBudget(usable_vram_bytes=24 * gib,
+ total_device_bytes=24 * gib,
+ ram_available_bytes=64 * gib)
+ preset = tmp_path / "presets.ini"
+
+ baseline = presets_mod.generate_presets(mdir, budget, preset)[0]
+ assert baseline.window == 131072 # tiny model: native from the start
+
+ # Override above native must cap at native, not exceed it.
+ save_window_override("tiny-dense", 10_000_000)
+ capped = presets_mod.generate_presets(mdir, budget, preset)[0]
+ assert capped.window == 131072
+
+
+def test_preset_ignores_override_below_launch_window(hermes_home, tmp_path, monkeypatch):
+ """Overrides only ever RAISE the window (growth is monotone); a stale
+ smaller override never shrinks a launch decision."""
+ import hermes_cli.local_runtime.presets as presets_mod
+
+ from hermes_cli.local_runtime.estimator import HardwareBudget
+ from hermes_cli.local_runtime.growth import save_window_override
+
+ mdir = tmp_path / "models"
+ _stage_fake_gguf(mdir, "tiny-dense")
+ monkeypatch.setattr(presets_mod, "read_gguf_header", lambda p: p)
+ monkeypatch.setattr(presets_mod, "profile_from_gguf",
+ lambda h: _tiny_profile("tiny-dense"))
+ save_window_override("tiny-dense", 65536)
+
+ gib = 1 << 30
+ budget = HardwareBudget(usable_vram_bytes=24 * gib,
+ total_device_bytes=24 * gib,
+ ram_available_bytes=64 * gib)
+ entry = presets_mod.generate_presets(mdir, budget, tmp_path / "p.ini")[0]
+ assert entry.window == 131072
+
+
+def test_preset_restores_grown_window_midladder(hermes_home, tmp_path, monkeypatch):
+ """The real growth shape: launch at a lower rung, override to a middle
+ rung -> the preset window follows the override."""
+ import hermes_cli.local_runtime.presets as presets_mod
+
+ from hermes_cli.local_runtime.estimator import HardwareBudget, LayerKind, ModelProfile
+ from hermes_cli.local_runtime.growth import save_window_override
+
+ gib = 1 << 30
+ # Expensive dense KV so the launch decision lands BELOW native on this
+ # budget: 60 layers x 4 KiB/tok f16 -> q8 ~= 120 KiB/tok.
+ profile = ModelProfile(
+ name="big-dense", weights_bytes=20 * gib, embd_table_bytes=0,
+ n_ctx_train=262144,
+ layers=[(LayerKind.FULL, 4096)] * 60)
+ mdir = tmp_path / "models"
+ _stage_fake_gguf(mdir, "big-dense")
+ monkeypatch.setattr(presets_mod, "read_gguf_header", lambda p: p)
+ monkeypatch.setattr(presets_mod, "profile_from_gguf", lambda h: profile)
+
+ budget = HardwareBudget(usable_vram_bytes=28 * gib,
+ total_device_bytes=32 * gib,
+ ram_available_bytes=128 * gib)
+ baseline = presets_mod.generate_presets(mdir, budget, tmp_path / "a.ini")[0]
+ assert baseline.window < 262144, "sanity: launch below native"
+
+ grown = baseline.window * 2
+ save_window_override("big-dense", grown)
+ restored = presets_mod.generate_presets(mdir, budget, tmp_path / "b.ini")[0]
+ assert restored.window >= grown, "override must lift the launch window"