Coverage for src/governed_harness/configuration/friction.py: 100%
99 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
1"""Configuration of low-friction small changes and local metrics (since 2.0, issue #58).
3Every section and key here is optional. A key that is absent keeps the 1.0.0 behaviour and is
4left out of the serialized configuration, so the configuration snapshot (and its digest) of a
5project written before these settings existed does not change. ``harness init`` writes the
6``friction`` section; ``metrics`` only configures ``harness metrics`` (a price table for
7providers that report tokens without cost, and the optional narrative command), which runs
8without it.
9"""
11from __future__ import annotations
13import re
14from typing import Any, Literal
16from pydantic import (
17 BaseModel,
18 ConfigDict,
19 Field,
20 SerializerFunctionWrapHandler,
21 field_validator,
22 model_serializer,
23)
25from governed_harness.configuration.agent_results import off_from_yaml
27SizeName = Literal["S", "M", "L"]
30class _Section(BaseModel):
31 """A section whose unset (``None``) keys are left out of the serialized configuration."""
33 model_config = ConfigDict(extra="forbid", populate_by_name=True, frozen=True)
35 @model_serializer(mode="wrap")
36 def _omit_unset(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
37 data: dict[str, Any] = handler(self)
38 for name, field in type(self).model_fields.items():
39 if getattr(self, name) is None:
40 data.pop(name, None)
41 data.pop(field.alias or name, None)
42 return data
45FastLaneStep = Literal[
46 "ambiguityReview",
47 "decomposition",
48 "agentReview",
49 "preflight",
50 "mutation",
51 "acceptanceTests",
52]
53FAST_LANE_STEPS: tuple[FastLaneStep, ...] = (
54 "ambiguityReview",
55 "decomposition",
56 "agentReview",
57 "preflight",
58 "mutation",
59 "acceptanceTests",
60)
61DEFAULT_FAST_LANE_SKIP: tuple[FastLaneStep, ...] = (
62 "ambiguityReview",
63 "decomposition",
64 "agentReview",
65 "preflight",
66 "mutation",
67)
68"""What a fast-lane run leaves out when ``fastLane.skip`` is not set (the list of issue #58):
69the agent's ambiguity review, the decomposition, the agent review unless a signal asks for it,
70the preflight on the baseline and the light mutation. ``acceptanceTests`` can be added; it is
71not left out by default because the frozen acceptance tests are evidence of the criteria."""
74class FastVerificationConfig(_Section):
75 """Faster VERIFICATION in the fast lane (#58, item 5). Nothing here skips a mandatory
76 validator before the decision: the affected tests run first and stop a failing attempt
77 early, the full suite still runs before the gate, independent validators run side by side,
78 and a validator result is reused only for the same validator, ChangeSet, baseline and
79 configuration."""
81 affected_tests_first: bool | None = Field(default=None, alias="affectedTestsFirst")
82 parallel: bool | None = None
83 cache: bool | None = None
86class FastLaneConfig(_Section):
87 """Risk-proportional governance (#58, item 1). ``mode: auto`` classifies each task at
88 INTENT: size ``S`` by the router (#44) and no risk flag takes the fast lane, everything
89 else the full flow; the lane and why are recorded. ``skip`` lists what the fast lane leaves
90 out. A run leaves the fast lane (``lane.escalated``) when its ChangeSet shows a risk factor
91 or outgrows ``S``; the human decision and the mandatory validators are never skipped."""
93 mode: Literal["auto", "off"] | None = None
94 skip: tuple[FastLaneStep, ...] | None = None
95 verification: FastVerificationConfig | None = None
97 @field_validator("mode", mode="before")
98 @classmethod
99 def _bare_off(cls, value: Any) -> Any:
100 return off_from_yaml(value)
102 @property
103 def enabled(self) -> bool:
104 return self.mode == "auto"
106 @property
107 def skipped(self) -> tuple[FastLaneStep, ...]:
108 return DEFAULT_FAST_LANE_SKIP if self.skip is None else self.skip
111DEFAULT_PRE_AUTHORIZATION_HOURS = 24
112MAX_PRE_AUTHORIZATION_HOURS = 168
115class PreAuthorizationConfig(_Section):
116 """Pre-authorised approval (#58, item 3). ``mode: allow`` lets a person, when they confirm
117 the operational contract (``harness task confirm --pre-approve`` or ``harness do
118 --pre-approve``), approve in advance under a condition with an expiry. The approval is a
119 human decision recorded in advance, bound to the contract digest and the condition (gate
120 passed, no risk factor, size ``S``); when the condition does not hold at DECISION, the
121 person is asked as usual."""
123 mode: Literal["allow", "off"] | None = None
124 default_hours: int | None = Field(
125 default=None, alias="defaultHours", ge=1, le=MAX_PRE_AUTHORIZATION_HOURS
126 )
127 max_hours: int | None = Field(
128 default=None, alias="maxHours", ge=1, le=MAX_PRE_AUTHORIZATION_HOURS
129 )
131 @field_validator("mode", mode="before")
132 @classmethod
133 def _bare_off(cls, value: Any) -> Any:
134 return off_from_yaml(value)
136 @property
137 def enabled(self) -> bool:
138 return self.mode == "allow"
140 @property
141 def hours(self) -> int:
142 return self.default_hours or DEFAULT_PRE_AUTHORIZATION_HOURS
144 @property
145 def limit_hours(self) -> int:
146 return self.max_hours or MAX_PRE_AUTHORIZATION_HOURS
149class FrictionTarget(_Section):
150 """The friction a task of one size should cost: human interactions and wall-clock
151 minutes from the first event of its first run to the end of its last."""
153 interactions: int | None = Field(default=None, ge=0, le=1000)
154 minutes: float | None = Field(default=None, gt=0, le=525_600)
157DEFAULT_FRICTION_TARGETS: dict[str, dict[str, float]] = {
158 "S": {"interactions": 1, "minutes": 30},
159 "M": {"interactions": 3, "minutes": 240},
160 "L": {"interactions": 6, "minutes": 1440},
161}
162"""Targets ``harness init`` writes: starting points to calibrate, not measured optima."""
165PlanApprovalMode = Literal["risk", "always", "off"]
168class FrictionConfig(_Section):
169 """Low friction for small changes (#58, items 1, 3, 5, 6 and 7)."""
171 fast_lane: FastLaneConfig | None = Field(default=None, alias="fastLane")
172 pre_authorization: PreAuthorizationConfig | None = Field(default=None, alias="preAuthorization")
173 change_types: bool | None = Field(default=None, alias="changeTypes")
174 """Documentation-only or configuration-only ChangeSets (detected from the paths) do not
175 require new tests or requirement traceability."""
176 targets: dict[SizeName, FrictionTarget] | None = None
177 """Friction targets per task size, reported by ``harness metrics`` and the brief."""
178 plan_approval: PlanApprovalMode | None = Field(default=None, alias="planApproval")
179 """Since #58 (closes #8): the plan-approval checkpoint of PLANNING. ``risk``: a task the
180 router sizes ``L`` or that carries a risk flag waits for a person to approve its plan, bound
181 to the plan digest, before IMPLEMENTATION; other tasks skip it and the reason is recorded.
182 ``always``: every task waits. ``off``: no checkpoint (1.0.0)."""
184 @field_validator("plan_approval", mode="before")
185 @classmethod
186 def _bare_off(cls, value: Any) -> Any:
187 return off_from_yaml(value)
190_PRICE_KEY = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,199}$")
193class ModelPrice(_Section):
194 """Prices in US dollars per million tokens. Used only to estimate the cost of calls whose
195 provider reported tokens without a cost; the estimate is labelled as such and never stored
196 on a run or counted against the budget."""
198 input: float = Field(ge=0)
199 output: float = Field(ge=0)
200 cache: float | None = Field(default=None, ge=0)
201 """Price of cached input tokens; without it cached tokens are priced as input."""
204class NarrativeConfig(_Section):
205 """The optional narrative summary of a period (#58, item 12): one call, on demand only
206 (``harness metrics --narrative``), to a command that reads the prompt and the metrics on
207 standard input and prints the summary."""
209 command: tuple[str, ...] = Field(min_length=1)
210 timeout_seconds: int | None = Field(default=None, alias="timeoutSeconds", ge=1, le=3600)
212 @property
213 def timeout(self) -> int:
214 return self.timeout_seconds or 300
217class MetricsConfig(_Section):
218 """``harness metrics`` settings: the price table (by model id, or ``provider/model``) and
219 the narrative command."""
221 prices: dict[str, ModelPrice] | None = None
222 narrative: NarrativeConfig | None = None
224 @field_validator("prices")
225 @classmethod
226 def _price_keys(cls, value: dict[str, ModelPrice] | None) -> dict[str, ModelPrice] | None:
227 for key in value or {}:
228 if not _PRICE_KEY.match(key):
229 raise ValueError(f"not a model id: {key!r}")
230 return value
233__all__ = [
234 "DEFAULT_FAST_LANE_SKIP",
235 "DEFAULT_FRICTION_TARGETS",
236 "DEFAULT_PRE_AUTHORIZATION_HOURS",
237 "FAST_LANE_STEPS",
238 "MAX_PRE_AUTHORIZATION_HOURS",
239 "FastLaneConfig",
240 "FastLaneStep",
241 "FastVerificationConfig",
242 "FrictionConfig",
243 "FrictionTarget",
244 "MetricsConfig",
245 "ModelPrice",
246 "NarrativeConfig",
247 "PlanApprovalMode",
248 "PreAuthorizationConfig",
249 "SizeName",
250]