Coverage for packages/workshop/src/livery/workshop/_governance.py: 96%
Measured by coverage.py 7.16.2 on CPython 3.14 while the suites of tests, packages/workshop/tests/test_workshop_workflow.py, packages/workshop/tests/test_workshop_without_docs.py, packages/workshop/tests/test_workshop_walk.py, packages/workshop/tests/test_workshop_vocabulary.py, packages/workshop/tests/test_workshop_update.py, packages/workshop/tests/test_workshop_templates.py, packages/workshop/tests/test_workshop_sync.py, packages/workshop/tests/test_workshop_shipped_files.py, packages/workshop/tests/test_workshop_shells.py, packages/workshop/tests/test_workshop_security.py, packages/workshop/tests/test_workshop_render.py, packages/workshop/tests/test_workshop_release_render.py, packages/workshop/tests/test_workshop_queries.py, packages/workshop/tests/test_workshop_quality.py, packages/workshop/tests/test_workshop_pythons.py, packages/workshop/tests/test_workshop_proved.py, packages/workshop/tests/test_workshop_prose.py, packages/workshop/tests/test_workshop_points_contributed.py, packages/workshop/tests/test_workshop_points.py, packages/workshop/tests/test_workshop_package_templates.py, packages/workshop/tests/test_workshop_new_project.py, packages/workshop/tests/test_workshop_layering.py, packages/workshop/tests/test_workshop_inputs_pins.py, packages/workshop/tests/test_workshop_governance.py, packages/workshop/tests/test_workshop_entry.py, packages/workshop/tests/test_workshop_dispatch.py, packages/workshop/tests/test_workshop_currency.py, packages/workshop/tests/test_workshop_c7_shards.py, packages/extensions/nanobind/tests/test_extensions_nanobind.py, packages/extensions/lfs/tests/test_lfs.py, packages/extensions/docs/tests/test_task_links.py, packages/extensions/docs/tests/test_docs.py ran.
Keys
- r m x p show or hide the lines of a kind
- j k the next or previous highlighted chunk
- 0 the top of the page
- 1 the first highlighted chunk
- [ ] the previous or next file
- u the index
- ? show or hide this help
1"""Repository governance from the contracts: owners, the file, the config.
3Each package's ``workshop.toml`` names who reviews it (``[owners]``
4with ``users``, ``teams``, and ``approvals``); the root contract's
5own ``[owners]`` guard the governance declarations themselves, so
6raising a reviewer count is a reviewed merge like any change. This
7module turns those declarations into the forge's CODEOWNERS file (a
8managed generated artifact the drift gate compares offline), into
9the repository settings ``configure`` asserts, and into the
10generated post-merge workflow that applies them, so nobody carries
11forge-specific knowledge in their head.
14from __future__ import annotations
16from pathlib import Path
17from typing import Any
19from livery.footman import fail
20from livery.forge import Codeowners, CodeownersEntry, Forge, RepoConfig
21from livery.workshop._contract import load_contract
22from livery.workshop._shipped_files import PROJECT_FILE
24#: Default deployment environment names for privileged CI jobs.
25DEFAULT_ENVIRONMENTS: dict[str, str] = {
32def ci_environments(contract: dict[str, Any]) -> dict[str, str]:
33 """Resolved deployment environment names from ``[ci.environments]``."""
34 ci = contract.get("ci") or {}
35 overrides = ci.get("environments") or {}
36 resolved = dict(DEFAULT_ENVIRONMENTS)
37 for role, default in DEFAULT_ENVIRONMENTS.items():
38 value = str(overrides.get(role) or "").strip()
39 resolved[role] = value or default
40 return resolved
43def _owners_table(contract: dict[str, Any]) -> dict[str, Any]:
44 return dict(contract.get("owners") or {})
47def owners_of(contract: dict[str, Any]) -> tuple[tuple[str, ...], tuple[str, ...], int]:
48 """A contract's ``(users, teams, approvals)`` owner declaration.
50 Approvals default to zero: declared owners document and route
51 review without gating the merge until a count is asked for,
52 which is what a solo maintainer needs (a forge that forbids
53 self-approval deadlocks a solo repo on any required review).
55 table = _owners_table(contract)
56 users = tuple(str(name) for name in table.get("users", []) if str(name).strip())
57 teams = tuple(str(name) for name in table.get("teams", []) if str(name).strip())
58 approvals = int(table.get("approvals", 0))
59 return users, teams, approvals
62def offline_forge(root: Path) -> Forge:
63 """The contract's forge backend with no credential attached.
65 The codeowners rendering is pure string building, so the drift
66 gate may hold a backend offline; nothing built here may be used
69 from livery.forge import GiteaForge, GithubForge, GitlabForge
71 contract = load_contract(root / "workshop.toml")
72 table = contract.get("forge") or {}
73 kind = str(table.get("kind", ""))
74 url = str(table.get("url", ""))
75 if kind == "github":
76 return GithubForge.connect(url=url, token="")
77 if kind == "gitea":
78 return GiteaForge.connect(url=url or "http://offline.invalid", token="")
79 if kind == "gitlab":79 ↛ 81line 79 didn't jump to line 81 because the condition on line 79 was always true
80 return GitlabForge.connect(url=url or "http://offline.invalid", token="")
81 fail(f"unknown forge kind {kind!r}: use github, gitea, or gitlab")
84#: The distribution name of the workshop itself; when a workspace
85#: builds it as a member (self-hosting / dogfooding), the workshop and
86#: its transitive workspace dependencies execute in privileged jobs and
87#: belong in the governance guard.
88_DRIVER_DIST = "livery-workshop"
90#: Root-relative paths that can alter CI execution, tool resolution,
91#: environment defaults, or governance rules on any forge.
92_PRIVILEGED_WORKFLOW_PATHS: tuple[str, ...] = (
93 "/.github/workflows/",
99_PRIVILEGED_ROOT_PATHS: tuple[str, ...] = (
110def _driver_closure_paths(root: Path) -> tuple[str, ...]:
111 """Workspace package paths in the workshop's own dependency closure.
113 Empty in a consumer repository where ``livery-workshop`` is an
114 external dependency in ``uv.lock``; in a self-hosting workspace
115 such as ``livery`` itself, every workspace member that
116 ``livery-workshop`` transitively depends on executes beside
117 privileged credentials and is guarded under root ``[owners]``.
119 from livery.workshop._graph import dependencies_closure
120 from livery.workshop._packages import discover_packages
122 if not (root / "packages").is_dir():
124 packages = discover_packages(root)
125 driver = next((pkg for pkg in packages if pkg.name == _DRIVER_DIST), None)
126 if driver is None:
128 closure = dependencies_closure(packages, {driver.path})
129 return tuple(f"/{pkg.path}/" for pkg in closure)
132def privileged_paths(root: Path) -> tuple[str, ...]:
133 """The authoritative root-relative paths guarded by root ``[owners]``.
135 Every path that can alter CI execution, CI credentials, tool
136 resolution, root environment defaults, or governance rules comes
137 from this one function; CODEOWNERS generation, drift checking, and
138 security checks all read it. Per-package ``workshop.toml`` files
139 are intentionally omitted: edits to ``[owners]`` force a CODEOWNERS
140 diff (including ``# approvals: <n>``), and edits to extensions,
141 dependencies, package names, or new CI points force diffs in
142 guarded root files via ``drift.check``.
144 contract = load_contract(root / "workshop.toml")
145 forge_table = contract.get("forge") or {}
146 paths: list[str] = ["/workshop.toml"]
147 if str(forge_table.get("kind", "")):147 ↛ 150line 147 didn't jump to line 150 because the condition on line 147 was always true
148 rendered_path = offline_forge(root).codeowners(()).path
149 paths.append(f"/{rendered_path}")
150 paths.extend(_PRIVILEGED_WORKFLOW_PATHS)
151 paths.extend(_PRIVILEGED_ROOT_PATHS)
152 paths.extend(_driver_closure_paths(root))
153 return tuple(dict.fromkeys(paths))
156def governance_entries(root: Path) -> tuple[CodeownersEntry, ...]:
157 """The neutral ownership declarations, packages first and root guard last.
159 Each package's owners guard its directory; the root contract's
160 owners guard every pattern from `privileged_paths` under the
161 ``governance`` section. Package entries come first and the
162 governance section comes last so last-match-wins dialects (GitHub
163 and Gitea) never let a package rule shadow a privileged path, and
164 GitLab renders the governance entries in their own additive
165 ``[governance]`` section. A workspace with no owner declarations
166 anywhere answers empty, and no file is generated.
168 from livery.workshop._packages import discover_packages
170 contract = load_contract(root / "workshop.toml")
171 forge_table = contract.get("forge") or {}
172 owner = str(forge_table.get("owner", ""))
173 if not str(forge_table.get("kind", "")):
174 # No forge declared: nothing to render a dialect for, and a
175 # bare rig must not be forced to invent one.
178 def _qualified(users: tuple[str, ...], teams: tuple[str, ...]) -> tuple[str, ...]:
179 return users + tuple(f"{owner}/{team}" for team in teams)
181 entries: list[CodeownersEntry] = []
182 if (root / "packages").is_dir():
183 for package in discover_packages(root):
184 contract_file = package.directory / "workshop.toml"
185 users, teams, approvals = owners_of(load_contract(contract_file))
186 if not (users or teams):
188 entries.append(
190 path=f"/{package.path}/",
191 owners=_qualified(users, teams),
192 min_approvals=approvals,
195 root_users, root_teams, root_approvals = owners_of(contract)
196 if root_users or root_teams:
197 guard = _qualified(root_users, root_teams)
198 for path in privileged_paths(root):
199 entries.append(
203 min_approvals=root_approvals,
204 section="governance",
207 return tuple(entries)
210def codeowners_file(root: Path) -> Codeowners | None:
211 """The rendered codeowners artifact, or None with no declarations."""
212 entries = governance_entries(root)
213 if not entries:
215 return offline_forge(root).codeowners(entries)
218def governance_paths(root: Path) -> tuple[str, ...]:
219 """The paths whose change means governance may need re-applying."""
220 paths = ["workshop.toml", "packages/*/workshop.toml"]
221 rendered = codeowners_file(root)
222 if rendered is not None:222 ↛ 223line 222 didn't jump to line 223 because the condition on line 222 was never true
223 paths.append(rendered.path)
224 return tuple(paths)
227def governance_config(root: Path) -> RepoConfig:
228 """The approvals half of the repository settings.
230 The repo-wide count is the highest any declaration asks, because
231 GitHub and Gitea express one count through protection; GitLab's
232 per-path sections carry the rest, where a paid tier enforces
233 them. No declarations anywhere means no approval requirement.
235 entries = governance_entries(root)
236 if not entries:
237 return RepoConfig()
238 highest = max(entry.min_approvals for entry in entries)
239 # A count of zero asserts zero and requires no codeowner review
240 # either: on a forge that forbids self-approval, a codeowner
241 # requirement alone still deadlocks a solo repo, and ownership
242 # stays documented in the file.
243 return RepoConfig(
244 min_approvals=highest,
245 require_codeowner_review=highest > 0,
246 dismiss_stale_reviews=highest > 0,
250def unknown_owners(root: Path, forge: Forge, owner: str) -> tuple[str, ...]:
251 """Declared owners the forge does not know, for configure's check.
253 Users are checked against ``members(owner)``, teams against
254 ``teams(owner)``; the answers are live listings, so this runs
255 only where the forge is already being spoken to, never on the
258 members = set(forge.members(owner))
259 teams = set(forge.teams(owner))
260 missing: list[str] = []
261 for entry in governance_entries(root):
262 where = "/workshop.toml" if entry.section == "governance" else entry.path
263 for name in entry.owners:
264 _, slash, team = name.partition("/")
266 if team not in teams and name not in teams:266 ↛ 267line 266 didn't jump to line 267 because the condition on line 266 was never true
267 missing.append(f"team {name} (declared on {where})")
268 elif name not in members:
269 missing.append(f"user {name} (declared on {where})")
270 return tuple(dict.fromkeys(missing))