Coverage for src/governed_harness/configuration/engineering.py: 86%
202 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 the engineering settings (since 2.0, issue #56).
3Forges, language standards packs, engineering principles, the testing strategy, the
4architecture and the project setup questions of a new project. Every section and key is
5optional: a key that is absent keeps the 1.0.0 behaviour and is left out of the serialized
6configuration, so the configuration snapshot (and its digest) of a project written before these
7settings existed does not change. ``harness init`` writes them.
9Token cost rule of the whole section: tools verify, models only judge what tools cannot. The
10standards cards sent to an agent are the ones that apply to the files it works on, the
11principles checklist rides on the existing review call, and the architecture survey of an
12existing project is one call per project, cached."""
14from __future__ import annotations
16import re
17from pathlib import PurePosixPath
18from typing import Any, Literal
20from pydantic import Field, field_validator, model_validator
22from governed_harness.configuration.agent_results import (
23 AgentCallConfig,
24 Policy,
25 _Section,
26 off_from_yaml,
27)
28from governed_harness.domain.enums import FindingSeverity
30_ENV_NAME = re.compile(r"^[A-Za-z_]\w{0,127}$", re.ASCII)
31_NAME = re.compile(r"^[a-z][a-z0-9_-]{0,63}$")
34def _relative(value: str, what: str) -> str:
35 path = PurePosixPath(value.replace("\\", "/"))
36 if not value.strip() or value.startswith("/") or ".." in path.parts:
37 raise ValueError(f"{what} must be relative to the workspace: {value!r}")
38 return value
41# ----- forges (#56, item 1) ------------------------------------------------------------------
42ForgeKind = Literal["auto", "github", "gitlab", "bitbucket", "azure-devops", "gitea"]
43ForgeTransport = Literal["cli", "api"]
46class ForgeConfig(_Section):
47 """Where pull or merge requests, comments, statuses and quality reports go.
49 ``kind: auto`` (or absent) detects the forge from the ``origin`` remote: github.com,
50 gitlab.com or a host with ``gitlab`` in its name, bitbucket.org, dev.azure.com or
51 ``*.visualstudio.com``, and a host with ``gitea`` or ``forgejo`` in its name. Tokens are
52 read only from the environment variable ``tokenEnv`` (default per forge) and never logged.
53 """
55 kind: ForgeKind | None = None
56 transport: ForgeTransport | None = None
57 repository: str | None = None
58 """``owner/name`` (GitHub, Gitea, Bitbucket ``workspace/repo``), a GitLab project path
59 (``group/subgroup/project``) or ``organization/project/repository`` (Azure DevOps).
60 Default: derived from the ``origin`` remote."""
61 api_url: str | None = Field(default=None, alias="apiUrl")
62 token_env: str | None = Field(default=None, alias="tokenEnv")
63 base_branch: str | None = Field(default=None, alias="baseBranch")
64 labels: tuple[str, ...] | None = None
65 template: str | None = None
66 """A pull request template in the repository whose text heads the description."""
67 draft: bool | None = None
68 code_quality: bool | None = Field(default=None, alias="codeQuality")
69 """Also attach the findings as a GitLab Code Quality report (written next to SARIF)."""
71 @field_validator("token_env")
72 @classmethod
73 def _env(cls, value: str | None) -> str | None:
74 if value is not None and not _ENV_NAME.match(value):
75 raise ValueError(f"tokenEnv is not an environment variable name: {value!r}")
76 return value
78 @field_validator("api_url")
79 @classmethod
80 def _https(cls, value: str | None) -> str | None:
81 if value is None: 81 ↛ 82line 81 didn't jump to line 82 because the condition on line 81 was never true
82 return None
83 if not value.startswith(("https://", "http://127.0.0.1", "http://localhost")): 83 ↛ 85line 83 didn't jump to line 85 because the condition on line 83 was always true
84 raise ValueError("apiUrl must use https (or point to localhost)")
85 return value.rstrip("/")
87 @field_validator("template")
88 @classmethod
89 def _template(cls, value: str | None) -> str | None:
90 return _relative(value, "template") if value is not None else None
92 @field_validator("repository")
93 @classmethod
94 def _repository(cls, value: str | None) -> str | None:
95 if value is not None and not re.fullmatch(r"[A-Za-z0-9_.~-]+(/[A-Za-z0-9_. ~-]+)+", value): 95 ↛ 96line 95 didn't jump to line 96 because the condition on line 95 was never true
96 raise ValueError(f"repository must be a path such as owner/name: {value!r}")
97 return value
100# ----- standards packs (#56, item 2) --------------------------------------------------------
101CardsMode = Literal["auto", "off"]
102ToolsMode = Literal["detect", "off"]
103DEFAULT_STANDARDS_PATH = ".harness/standards"
104DEFAULT_MAX_CARDS = 12
107class StandardsConfig(_Section):
108 """Language standards packs shipped with the harness.
110 * ``packs``: ``[auto]`` (or absent) selects the packs of the detected languages; otherwise
111 pack ids (``python``, ``typescript``, ``java``, ...).
112 * ``cards: auto``: the cards that apply to the files a call works on are added, compact, to
113 the implement request; the cards a tool cannot verify become the checklist of the
114 existing review call. Selected deterministically and cached by digest.
115 * ``tools: detect``: each pack tool whose configuration file is in the repository becomes
116 an optional validator (parsed output, never installed by the harness).
117 * ``path``: repository overrides (``<path>/<pack>/cards.yaml``) take precedence over the
118 pack: a card with the same id replaces the pack's card, ``disabled`` drops cards.
119 """
121 packs: tuple[str, ...] | None = None
122 cards: CardsMode | None = None
123 max_cards: int | None = Field(default=None, alias="maxCards", ge=1, le=100)
124 tools: ToolsMode | None = None
125 path: str | None = None
126 disabled: tuple[str, ...] | None = None
128 @field_validator("cards", "tools", mode="before")
129 @classmethod
130 def _bare_off(cls, value: Any) -> Any:
131 return off_from_yaml(value)
133 @field_validator("path")
134 @classmethod
135 def _path(cls, value: str | None) -> str | None:
136 return _relative(value, "standards.path") if value is not None else None
138 @property
139 def cards_enabled(self) -> bool:
140 return self.cards == "auto"
142 @property
143 def tools_enabled(self) -> bool:
144 return self.tools == "detect"
146 @property
147 def overrides_path(self) -> str:
148 return self.path or DEFAULT_STANDARDS_PATH
150 @property
151 def card_limit(self) -> int:
152 return self.max_cards or DEFAULT_MAX_CARDS
155# ----- engineering principles (#56, item 3) -------------------------------------------------
156DEFAULT_DUPLICATION_WINDOW = 6
157DEFAULT_INHERITANCE_DEPTH = 3
160class PrinciplesConfig(_Section):
161 """Engineering principles checked by deterministic proxies in VERIFICATION, with a
162 checklist for the rest inside the existing review call (no extra agent call).
164 ``mode: enforce`` makes the proxies a mandatory check whose HIGH findings block; ``warn``
165 records them as LOW. ``duplicationWindow`` (lines), ``maxInheritanceDepth``,
166 ``unusedPublic`` (YAGNI), ``boyScout`` (changes in files outside the task scope) and
167 ``checklist`` (the review call) may be set one by one."""
169 mode: Policy | None = None
170 duplication_window: int | None = Field(default=None, alias="duplicationWindow", ge=3, le=200)
171 max_inheritance_depth: int | None = Field(
172 default=None, alias="maxInheritanceDepth", ge=1, le=20
173 )
174 unused_public: bool | None = Field(default=None, alias="unusedPublic")
175 boy_scout: bool | None = Field(default=None, alias="boyScout")
176 checklist: bool | None = None
177 severity: FindingSeverity | None = None
178 """Severity of a principle finding under ``enforce`` (default ``MEDIUM``: shown, not
179 blocking under the default ``findingBlockSeverities``; ``HIGH`` makes them block)."""
181 @field_validator("mode", mode="before")
182 @classmethod
183 def _bare_off(cls, value: Any) -> Any:
184 return off_from_yaml(value)
186 @property
187 def enabled(self) -> bool:
188 return self.mode in {"enforce", "warn"}
190 @property
191 def window(self) -> int:
192 return self.duplication_window or DEFAULT_DUPLICATION_WINDOW
194 @property
195 def inheritance_depth(self) -> int:
196 return self.max_inheritance_depth or DEFAULT_INHERITANCE_DEPTH
199# ----- testing strategy (#56, item 4) -------------------------------------------------------
200TestingStrategy = Literal["auto", "tdd", "bdd", "conventional"]
201DEFAULT_FEATURES_DIRECTORY = "features"
204class TestingConfig(_Section):
205 """How the change is tested.
207 * ``strategy: auto`` follows what the repository does (feature files or a BDD framework:
208 ``bdd``; tests: ``conventional``) and, when nothing is known, asks in INTENT;
209 * ``tdd``: the tests the change adds must fail on the code before it (red), pass after it
210 (green) and stay green with the principles checks clean (refactor); recorded as evidence;
211 * ``bdd``: the acceptance call writes the criteria as Gherkin scenarios, a person approves
212 them, the agent writes the step definitions; the scenarios are frozen.
214 ``featuresDirectory``, ``bddCommand`` and ``testCommand`` override the pack defaults."""
216 __test__ = False # not a pytest test class
218 strategy: TestingStrategy | None = None
219 features_directory: str | None = Field(default=None, alias="featuresDirectory")
220 bdd_command: tuple[str, ...] | None = Field(default=None, alias="bddCommand")
221 test_command: tuple[str, ...] | None = Field(default=None, alias="testCommand")
223 @field_validator("features_directory")
224 @classmethod
225 def _directory(cls, value: str | None) -> str | None:
226 return _relative(value, "featuresDirectory") if value is not None else None
228 @field_validator("bdd_command", "test_command")
229 @classmethod
230 def _command(cls, value: tuple[str, ...] | None) -> tuple[str, ...] | None:
231 if value is not None and not value: 231 ↛ 232line 231 didn't jump to line 232 because the condition on line 231 was never true
232 raise ValueError("a command must not be empty")
233 return value
235 @property
236 def features_path(self) -> str:
237 return (self.features_directory or DEFAULT_FEATURES_DIRECTORY).rstrip("/")
240# ----- architecture (#56, item 5) -----------------------------------------------------------
241ArchitectureStyle = Literal[
242 "ddd",
243 "hexagonal",
244 "clean",
245 "layered",
246 "modular-monolith",
247 "microservices",
248 "mvvm",
249 "mvi",
250 "event-driven",
251 "cqrs",
252 "custom",
253]
254BASE_STYLES: tuple[str, ...] = (
255 "ddd",
256 "hexagonal",
257 "clean",
258 "layered",
259 "modular-monolith",
260 "microservices",
261 "mvvm",
262 "mvi",
263 "custom",
264)
265"""The styles the architecture calls listed before the catalogue (wave 11): without
266``architecture.catalogue`` the requests keep this list and so their prompt digests."""
267CATALOGUE_STYLES: tuple[str, ...] = (
268 "layered",
269 "hexagonal",
270 "clean",
271 "ddd",
272 "modular-monolith",
273 "microservices",
274 "mvvm",
275 "mvi",
276 "event-driven",
277 "cqrs",
278)
279"""The ten styles of the catalogue (wave 11, #97): each has packaged documentation and an
280expert prompt (``resources/architecture``)."""
281ARCHITECTURE_STYLES: tuple[str, ...] = (*BASE_STYLES[:-1], "event-driven", "cqrs", "custom")
282ArchitectureMode = Literal["agent", "off"]
283RefreshMode = Literal["auto", "manual"]
284LayerCheckMode = Literal["differential", "full"]
285BaselineConflicts = Literal["allow", "enforce"]
286CatalogueMode = Literal["experts", "off"]
287DocumentationMode = Literal["project", "off"]
290class LayerConfig(_Section):
291 """A layer: the files that belong to it (``paths``, globs relative to the workspace) and/or
292 the module prefixes (``modules``, dotted: ``shop.domain``) imports name it by."""
294 name: str
295 paths: tuple[str, ...] | None = None
296 modules: tuple[str, ...] | None = None
298 @field_validator("name")
299 @classmethod
300 def _name(cls, value: str) -> str:
301 if not _NAME.match(value):
302 raise ValueError(f"layer name must be lower case letters, digits, - or _: {value!r}")
303 return value
305 @model_validator(mode="after")
306 def _has_members(self) -> LayerConfig:
307 if not self.paths and not self.modules:
308 raise ValueError(f"layer {self.name!r} needs paths or modules")
309 return self
312class ArchitectureSettings(_Section):
313 """The architecture of the project and how it is enforced.
315 ``style`` and ``layers`` with ``allow`` (the layers each layer may depend on; a layer may
316 always use itself) are the rules: every import across layers that ``allow`` does not list is
317 a forbidden dependency (the #40 check), ``enforce`` makes it HIGH, ``warn`` LOW. With
318 ``mode: agent`` a new project gets one advise call (options with trade-offs, a person
319 chooses, an ADR is recorded) and an existing project one survey call whose inferred rules a
320 person approves; the survey is cached in ``.harness/architecture.md`` and refreshed only on
321 demand (``harness architecture refresh``) or, under ``refresh: auto``, when the layout of
322 the source directories changed materially.
324 Since 2.0 (#93), two keys keep the rules from blaming a change for what the baseline has:
326 * ``layerCheck: differential`` judges only the layers a changed file did not import on the
327 baseline (a new file is judged whole); ``full`` (or absent) judges every import of a
328 changed file;
329 * ``baselineConflicts: allow`` checks the rules a survey infers against the baseline when
330 they are proposed: the dependencies between layers the baseline already has and the
331 rules forbid are listed in the proposal (and in the inbox) and added to ``allow`` in the
332 rules a person approves; ``enforce`` (or absent) keeps the rules as inferred.
334 Since 2.0 (#97), two more keys:
336 * ``catalogue: experts`` offers the ten styles of the catalogue to a new project: the advise
337 call recommends one with its reasons and the characteristics of the project that support
338 it, a person accepts it or chooses another style of the catalogue, and an expert for the
339 chosen style organises the project and travels, as a prompt, with every later request;
340 * ``documentation: project`` makes the survey of an existing project write persistent
341 reverse engineering documents under ``.harness/reverse-engineering`` (structure,
342 components, conventions and how the harness acts) that later requests point to; the
343 survey is not repeated while they hold."""
345 mode: ArchitectureMode | None = None
346 style: ArchitectureStyle | None = None
347 layers: tuple[LayerConfig, ...] | None = None
348 allow: dict[str, tuple[str, ...]] | None = None
349 enforce: Policy | None = None
350 refresh: RefreshMode | None = None
351 agent: AgentCallConfig | None = None
352 layer_check: LayerCheckMode | None = Field(default=None, alias="layerCheck")
353 baseline_conflicts: BaselineConflicts | None = Field(default=None, alias="baselineConflicts")
354 catalogue: CatalogueMode | None = None
355 documentation: DocumentationMode | None = None
357 @field_validator("mode", "enforce", "catalogue", "documentation", mode="before")
358 @classmethod
359 def _bare_off(cls, value: Any) -> Any:
360 return off_from_yaml(value)
362 @model_validator(mode="after")
363 def _known_layers(self) -> ArchitectureSettings:
364 names = [item.name for item in self.layers or ()]
365 if len(names) != len(set(names)): 365 ↛ 366line 365 didn't jump to line 366 because the condition on line 365 was never true
366 raise ValueError("layer names must be unique")
367 for source, targets in (self.allow or {}).items(): 367 ↛ 368line 367 didn't jump to line 368 because the loop on line 367 never started
368 unknown = [item for item in (source, *targets) if item not in names]
369 if unknown:
370 raise ValueError(f"allow names unknown layer(s): {', '.join(sorted(set(unknown)))}")
371 return self
373 @property
374 def agent_enabled(self) -> bool:
375 return self.mode == "agent"
377 @property
378 def policy(self) -> str:
379 return self.enforce or "enforce"
381 @property
382 def differential(self) -> bool:
383 return self.layer_check == "differential"
385 @property
386 def allows_baseline_conflicts(self) -> bool:
387 return self.baseline_conflicts == "allow"
389 @property
390 def experts(self) -> bool:
391 return self.catalogue == "experts"
393 @property
394 def documents(self) -> bool:
395 return self.documentation == "project"
398# ----- project setup questions (#56, item 6) ------------------------------------------------
399ProjectSetupMode = Literal["ask", "off"]