Coverage for src/governed_harness/capabilities/phase.py: 95%
96 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"""Capabilities per phase (issue #4, ``governance.phaseCapabilities``).
3Before, every grant of a run was the union of the profile's and the project's capabilities,
4issued for the whole run whatever the phase; a project could only widen a profile, and the
5workflow's ``allowedCapabilities`` had no effect. Under ``governance.phaseCapabilities``:
7* the resolver narrows instead of widening: a capability the project declares keeps only the
8 scopes that both the profiles and the project allow (``profile ∩ project``); a capability the
9 project does not mention keeps the profiles' scopes, and one only the project declares is
10 dropped. The scopes the harness derives from the validators the project selects (its own
11 toolchain validators, the interpreter, the standards tools) are added after it;
12* every grant issued while a phase runs keeps only the capabilities that phase allows (the
13 workflow's ``allowedCapabilities`` plus what the harness itself runs in it, see
14 ``HARNESS_PHASE_CAPABILITIES``);
15* an agent call outside IMPLEMENTATION is read-only (no ``filesystem.write``) and the only
16 process it may start is its own configured command; a reviewer is one such call;
17* an agent's own command (the command of the configured provider it is, ``agent.ID``) keeps its
18 grant in every phase only when the run's ``process.execute`` grants allow it (the profiles',
19 narrowed by the project, plus ``capabilities.extend``). A command no grant allows is refused
20 before it starts (#87): the refusal is a HIGH ``capabilities.command-denied`` finding and the
21 phase is ``BLOCKED`` (:class:`CommandRefused`).
23The policy of the running phase lives in a context variable, so every grant made while the
24phase runs (validators, probes, agent calls) goes through it without each caller passing it."""
26from __future__ import annotations
28import fnmatch
29from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
30from contextlib import contextmanager
31from contextvars import ContextVar
32from dataclasses import dataclass, field
33from typing import Any
35from governed_harness.capabilities.denial import CapabilityDenied, command_in_scope
36from governed_harness.configuration.models import CapabilityRule
37from governed_harness.domain.enums import ActorType
38from governed_harness.domain.models import Actor
40WRITE = "filesystem.write"
41EXECUTE = "process.execute"
43HARNESS_PHASE_CAPABILITIES: dict[str, tuple[str, ...]] = {
44 "SPECIFICATION": (EXECUTE,),
45 "PLANNING": (EXECUTE,),
46 "INDEPENDENT_REVIEW": (EXECUTE,),
47}
48"""What the harness itself runs in a phase beyond the workflow's 1.0.0 declaration: the frozen
49acceptance tests before the change (SPECIFICATION), the preflight probes on a copy of the
50baseline (PLANNING), the project's consistency checks before the reviewers (INDEPENDENT_REVIEW).
51Applied only under ``governance.phaseCapabilities`` and recorded in the resolved workflow."""
54class CommandRefused(CapabilityDenied):
55 """A command of an agent that no grant of the running phase allows, refused before it
56 started under ``governance.phaseCapabilities``: the phase is ``BLOCKED``, not ``ERROR``."""
59def launch_granted(argv: Sequence[str], rules: Iterable[CapabilityRule]) -> bool:
60 """Whether the run's ``process.execute`` rules allow the command ``argv`` (a rule that needs
61 an approval does not)."""
62 return any(
63 rule.capability == EXECUTE
64 and not rule.approval_required
65 and any(command_in_scope(argv, scope) for scope in rule.scope)
66 for rule in rules
67 )
70@dataclass(frozen=True)
71class PhasePolicy:
72 phase: str
73 allowed: frozenset[str]
74 launch: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
75 """``agent.ID`` -> the argv of the command of that configured provider (its own launch)."""
76 on_refused: Callable[[Actor, Sequence[str]], None] | None = None
77 """Told when a command of an agent is refused (the harness records the finding)."""
79 def apply(self, actor: Actor, rules: Iterable[CapabilityRule]) -> list[CapabilityRule]:
80 rules = tuple(rules)
81 kept = [rule for rule in rules if rule.capability in self.allowed]
82 if actor.actor_type is ActorType.AGENT:
83 if self.phase != "IMPLEMENTATION":
84 kept = [rule for rule in kept if rule.capability not in {WRITE, EXECUTE}]
85 launch = self.launch.get(actor.actor_id)
86 # Its own command keeps a grant only when the run's grants allow it (#87).
87 if launch and launch_granted(launch, rules):
88 kept.append(CapabilityRule(capability=EXECUTE, scope=(" ".join(launch),)))
89 return kept
91 def refuse(self, actor: Actor, argv: Sequence[str], error: CapabilityDenied) -> None:
92 """A command of an agent that its grants do not allow: report it and raise
93 :class:`CommandRefused`; any other actor's refusal is left as it was."""
94 if actor.actor_type is not ActorType.AGENT:
95 return
96 if self.on_refused is not None: 96 ↛ 98line 96 didn't jump to line 98 because the condition on line 96 was always true
97 self.on_refused(actor, argv)
98 raise CommandRefused(
99 f"{actor.actor_id} may not start {' '.join(argv)[:200]!r}: no process.execute grant "
100 f"allows it in {self.phase}; add it to capabilities.extend in project.yaml if it is "
101 "intended"
102 ) from error
104 def describe(self, rules: Iterable[CapabilityRule], agent: str | None) -> dict[str, Any]:
105 tool = Actor(actor_type=ActorType.TOOL, actor_id="validator.phase", version="1")
106 value: dict[str, Any] = {
107 "phase": self.phase,
108 "allowed": sorted(self.allowed),
109 "validators": [_rule(item) for item in self.apply(tool, rules)],
110 }
111 if agent is not None: 111 ↛ 117line 111 didn't jump to line 117 because the condition on line 111 was always true
112 actor = Actor(actor_type=ActorType.AGENT, actor_id=agent, version="1")
113 value["agent"] = {
114 "actor": agent,
115 "grants": [_rule(item) for item in self.apply(actor, rules)],
116 }
117 return value
120def _rule(rule: CapabilityRule) -> dict[str, Any]:
121 value: dict[str, Any] = {"capability": rule.capability, "scope": list(rule.scope)}
122 if rule.approval_required: 122 ↛ 123line 122 didn't jump to line 123 because the condition on line 122 was never true
123 value["approvalRequired"] = True
124 return value
127_CURRENT: ContextVar[PhasePolicy | None] = ContextVar("harness_phase_policy", default=None)
130def current_policy() -> PhasePolicy | None:
131 return _CURRENT.get()
134@contextmanager
135def phase_scope(policy: PhasePolicy | None) -> Iterator[None]:
136 token = _CURRENT.set(policy)
137 try:
138 yield
139 finally:
140 _CURRENT.reset(token)
143# ----- profile ∩ project ----------------------------------------------------------------------
144def _within(narrow: str, wide: str) -> bool:
145 """Whether every resource ``narrow`` matches is also matched by ``wide`` (conservative:
146 ``False`` when it cannot tell)."""
147 if wide == "**" or narrow == wide:
148 return True
149 if narrow == "**":
150 return False
151 if wide.endswith("/**"):
152 base = wide[:-3].rstrip("/")
153 stem = narrow[:-3].rstrip("/") if narrow.endswith("/**") else narrow
154 return stem == base or stem.startswith(f"{base}/")
155 if not any(char in narrow for char in "*?["):
156 return fnmatch.fnmatchcase(narrow, wide) or narrow.startswith(f"{wide} ")
157 return False
160def intersect_scopes(left: Iterable[str], right: Iterable[str]) -> tuple[str, ...]:
161 """The scopes allowed by both lists: each scope of one list that lies within a scope of
162 the other."""
163 first, second = list(dict.fromkeys(left)), list(dict.fromkeys(right))
164 kept = [item for item in first if any(_within(item, other) for other in second)]
165 kept += [item for item in second if any(_within(item, other) for other in first)]
166 return tuple(sorted(dict.fromkeys(kept)))
169def intersect_capabilities(
170 profile: Iterable[CapabilityRule], project: Iterable[CapabilityRule]
171) -> tuple[CapabilityRule, ...]:
172 """``profile ∩ project`` by capability (see the module docstring)."""
173 merged: dict[tuple[str, bool], set[str]] = {}
174 for rule in profile:
175 merged.setdefault((rule.capability, rule.approval_required), set()).update(rule.scope)
176 declared: dict[tuple[str, bool], set[str]] = {}
177 for rule in project:
178 declared.setdefault((rule.capability, rule.approval_required), set()).update(rule.scope)
179 result: list[CapabilityRule] = []
180 for key in sorted(set(merged) | set(declared)):
181 if key not in merged: 181 ↛ 182line 181 didn't jump to line 182 because the condition on line 181 was never true
182 continue
183 scopes = (
184 intersect_scopes(merged[key], declared[key])
185 if key in declared
186 else tuple(sorted(merged[key]))
187 )
188 if scopes:
189 result.append(CapabilityRule(capability=key[0], scope=scopes, approvalRequired=key[1]))
190 return tuple(result)
193__all__ = [
194 "HARNESS_PHASE_CAPABILITIES",
195 "CommandRefused",
196 "PhasePolicy",
197 "current_policy",
198 "intersect_capabilities",
199 "intersect_scopes",
200 "launch_granted",
201 "phase_scope",
202]