Coverage for src/governed_harness/standards/selection.py: 89%
63 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"""Which cards an agent call receives, and which tools verify the rest (#56).
3Token cost rule: the implement request carries only the cards that apply to the files the call
4works on (the task's paths, the context manifest, the files changed so far), compact (id, rule,
5exceptions) and capped by ``standards.maxCards``; the review call's checklist carries only the
6cards no tool verifies, for the files the ChangeSet changed. The selection is a pure function of
7the packs' digests and the paths, so the same inputs give the same cards (and the same prompt
8prefix), and the harness caches it by that digest."""
10from __future__ import annotations
12from collections.abc import Iterable
13from pathlib import Path
14from typing import Any
16from governed_harness.configuration.models import ValidatorDefinition
17from governed_harness.evidence.hashing import sha256_json
18from governed_harness.standards.packs import Card, PackTool, ProjectStandards
20TOOL_VALIDATOR_PREFIX = "standards"
23def selection_digest(standards: ProjectStandards, paths: Iterable[str], limit: int) -> str:
24 return sha256_json({"packs": standards.digest, "paths": sorted(set(paths)), "limit": limit})
27def select_cards(
28 standards: ProjectStandards,
29 paths: Iterable[str],
30 limit: int,
31 *,
32 review_only: bool = False,
33) -> list[Card]:
34 """The cards that apply to any of ``paths``, in pack order, at most ``limit``.
35 ``review_only`` keeps the cards no tool verifies (the reviewer's checklist)."""
36 wanted = sorted(set(paths))
37 selected: list[Card] = []
38 for pack in standards.packs:
39 for card in pack.cards:
40 if review_only and not card.needs_review:
41 continue
42 if any(card.applies(path) for path in wanted):
43 selected.append(card)
44 return selected[:limit]
47def cards_payload(cards: list[Card], digest: str, *, packs: list[str]) -> dict[str, Any]:
48 """The ``standards`` block of a request."""
49 return {
50 "digest": digest,
51 "packs": packs,
52 "cards": [item.compact() for item in cards],
53 }
56def checklist_payload(cards: list[Card]) -> list[dict[str, Any]]:
57 return [{"id": item.card_id, "rule": item.rule} for item in cards]
60# ----- the tools of the packs as validators ------------------------------------------------------
61def _config_present(workspace: Path, entry: str) -> bool:
62 name, _, section = entry.partition("#")
63 target = (workspace / name).resolve()
64 try:
65 target.relative_to(workspace.resolve())
66 except ValueError:
67 return False
68 if any(char in name for char in "*?["): 68 ↛ 69line 68 didn't jump to line 69 because the condition on line 68 was never true
69 return any(workspace.glob(name))
70 if not target.is_file():
71 return False
72 if not section:
73 return True
74 try:
75 return section in target.read_text(encoding="utf-8", errors="replace")
76 except OSError:
77 return False
80def _configured(tool: PackTool, workspace: Path, known: set[str]) -> bool:
81 """The tool has a command, the repository configures it and no selected validator
82 covers it."""
83 if not tool.command or not tool.config_files: 83 ↛ 84line 83 didn't jump to line 84 because the condition on line 83 was never true
84 return False
85 if any(item in known for item in tool.covered_by):
86 return False
87 return any(_config_present(workspace, entry) for entry in tool.config_files)
90def _tool_validator(validator_id: str, tool: PackTool) -> ValidatorDefinition:
91 """An optional validator that runs the tool only when it is installed."""
92 return ValidatorDefinition.model_validate(
93 {
94 "id": validator_id,
95 "command": list(tool.command or ()),
96 "mandatory": False,
97 "whenAvailable": True,
98 "timeoutSeconds": 600,
99 **({"parser": tool.parser} if tool.parser else {}),
100 }
101 )
104def tool_validators(
105 standards: ProjectStandards,
106 workspace: Path,
107 existing: Iterable[str],
108) -> list[tuple[str, PackTool, ValidatorDefinition]]:
109 """An optional validator for each pack tool the repository configures (one of its
110 ``configFiles`` exists) and no selected validator already runs (``coveredBy``). Detection
111 only: a tool that is not installed is ``NOT_APPLICABLE``, and nothing is installed."""
112 known = set(existing)
113 found: list[tuple[str, PackTool, ValidatorDefinition]] = []
114 for pack in standards.packs:
115 for tool in pack.tools:
116 if not _configured(tool, workspace, known):
117 continue
118 validator_id = f"{TOOL_VALIDATOR_PREFIX}.{pack.pack_id}.{tool.tool_id}"
119 if validator_id in known: 119 ↛ 120line 119 didn't jump to line 120 because the condition on line 119 was never true
120 continue
121 known.add(validator_id)
122 found.append((pack.pack_id, tool, _tool_validator(validator_id, tool)))
123 return found
126__all__ = [
127 "TOOL_VALIDATOR_PREFIX",
128 "cards_payload",
129 "checklist_payload",
130 "select_cards",
131 "selection_digest",
132 "tool_validators",
133]