Coverage for src/romfarmer/intent/guards.py: 96%

48 statements  

« prev     ^ index     » next       coverage.py v7.15.4, created at 2026-09-05 02:19 -0700

1"""Deterministic guards on stochastic proposals (intent brief v3 §Q4). 

2 

3Moved from ``farmhand/optimizer/nodes.py::_apply_guards``. In the intent 

4loop the *agent* is the critic, so these guards run inside 

5``validate_spec`` on a spec **revision**: a proposal that loosens a 

6threshold while the previous plan overshot the budget is rejected before it 

7ever reaches PLAN. No LLM, no LangGraph — a while loop and arithmetic. 

8""" 

9 

10from __future__ import annotations 

11 

12from collections.abc import Mapping, Sequence 

13from typing import Any 

14 

15from romfarmer.ir.spec import Spec 

16 

17STEP_SNAP = 0.05 

18 

19 

20def apply_guards( 

21 proposed: Mapping[str, float], 

22 current: Mapping[str, float], 

23 delta_bytes: int, 

24 history: Sequence[Any] = (), 

25 *, 

26 floor_keys: frozenset[str] = frozenset(), 

27 step: float = STEP_SNAP, 

28) -> dict[str, float]: 

29 """Sanitise proposed per-key thresholds against the current ones. 

30 

31 1. Unknown keys (invented by the proposer) are ignored. 

32 2. ``floor_keys`` are pinned to 0.0. 

33 3. Values are clamped to [0, 1] and snapped to ``step``. 

34 4. After a spike (``history[-1].is_spike``) a change is capped at one step. 

35 5. Overshoot invariant: while ``delta_bytes > 0`` (over budget) a key may 

36 not be loosened (lowered) — the proposer may only tighten. 

37 """ 

38 result = dict(current) 

39 is_overshoot = delta_bytes > 0 

40 last_spike = False 

41 if history: 

42 last = history[-1] 

43 last_spike = bool( 

44 last.get("is_spike", False) 

45 if isinstance(last, dict) 

46 else getattr(last, "is_spike", False) 

47 ) 

48 

49 for key, proposed_val in proposed.items(): 

50 if key not in current: 

51 continue 

52 if key in floor_keys: 

53 result[key] = 0.0 

54 continue 

55 clamped = max(0.0, min(1.0, float(proposed_val))) 

56 snapped = round(round(clamped / step) * step, 10) 

57 if last_spike: 

58 diff = snapped - current[key] 

59 if abs(diff) > step: 

60 snapped = current[key] + (step if diff > 0 else -step) 

61 snapped = round(round(snapped / step) * step, 10) 

62 if is_overshoot and snapped < current.get(key, 0.0) - 1e-6: 

63 snapped = current.get(key, 0.0) 

64 result[key] = round(snapped, 4) 

65 return result 

66 

67 

68def guard_spec_revision( 

69 previous: Spec, revised: Spec, previous_headroom_p50: int | None 

70) -> list[str]: 

71 """Violations when *revised* loosens *previous* although the previous plan overshot. 

72 

73 Returns human-readable reasons (empty = OK). Only applies when the 

74 previous dry run reported ``headroom_p50 < 0``; otherwise any change is 

75 allowed (the agent is exploring an under-full card). 

76 """ 

77 if previous_headroom_p50 is None or previous_headroom_p50 >= 0: 

78 return [] 

79 prev = {p.platform: p for p in previous.platforms} 

80 out: list[str] = [] 

81 for p in revised.platforms: 

82 q = prev.get(p.platform) 

83 if q is None: 

84 out.append( 

85 f"{p.platform}: added a platform while over budget by {-previous_headroom_p50:,} bytes" 

86 ) 

87 continue 

88 pm, qm = p.passes.rating.min, q.passes.rating.min 

89 if qm is not None and (pm is None or pm < qm - 1e-9): 

90 out.append( 

91 f"{p.platform}: rating.min loosened {qm} → {pm} while over budget (only tighten on overshoot)" 

92 ) 

93 pb, qb = p.passes.budget.max_bytes, q.passes.budget.max_bytes 

94 if qb is not None and (pb is None or pb > qb): 

95 out.append(f"{p.platform}: budget.max_bytes raised {qb:,} → {pb} while over budget") 

96 if p.passes.rating.unrated == "keep" and q.passes.rating.unrated == "drop": 

97 out.append(f"{p.platform}: rating.unrated loosened drop → keep while over budget") 

98 return out