Skip to content

livery.workshop._governance

livery.workshop._governance

Repository governance from the contracts: owners, the file, the config.

Each package's workshop.toml names who reviews it ([owners] with users, teams, and approvals); the root contract's own [owners] guard the governance declarations themselves, so raising a reviewer count is a reviewed merge like any change. This module turns those declarations into the forge's CODEOWNERS file (a managed generated artifact the drift gate compares offline), into the repository settings configure asserts, and into the generated post-merge workflow that applies them, so nobody carries forge-specific knowledge in their head.

Functions:

Name Description
ci_environments

Resolved deployment environment names from [ci.environments].

owners_of

A contract's (users, teams, approvals) owner declaration.

offline_forge

The contract's forge backend with no credential attached.

privileged_paths

The authoritative root-relative paths guarded by root [owners].

governance_entries

The neutral ownership declarations, packages first and root guard last.

codeowners_file

The rendered codeowners artifact, or None with no declarations.

governance_paths

The paths whose change means governance may need re-applying.

governance_config

The approvals half of the repository settings.

unknown_owners

Declared owners the forge does not know, for configure's check.

Attributes:

Name Type Description
DEFAULT_ENVIRONMENTS dict[str, str]

DEFAULT_ENVIRONMENTS module-attribute

DEFAULT_ENVIRONMENTS: dict[str, str] = {'govern': 'govern', 'bot': 'bot', 'pypi': 'pypi'}

ci_environments

ci_environments(contract: dict[str, Any]) -> dict[str, str]

Resolved deployment environment names from [ci.environments].

Source code in packages/workshop/src/livery/workshop/_governance.py
def ci_environments(contract: dict[str, Any]) -> dict[str, str]:
    """Resolved deployment environment names from ``[ci.environments]``."""
    ci = contract.get("ci") or {}
    overrides = ci.get("environments") or {}
    resolved = dict(DEFAULT_ENVIRONMENTS)
    for role, default in DEFAULT_ENVIRONMENTS.items():
        value = str(overrides.get(role) or "").strip()
        resolved[role] = value or default
    return resolved

owners_of

owners_of(contract: dict[str, Any]) -> tuple[tuple[str, ...], tuple[str, ...], int]

A contract's (users, teams, approvals) owner declaration.

Approvals default to zero: declared owners document and route review without gating the merge until a count is asked for, which is what a solo maintainer needs (a forge that forbids self-approval deadlocks a solo repo on any required review).

Source code in packages/workshop/src/livery/workshop/_governance.py
def owners_of(contract: dict[str, Any]) -> tuple[tuple[str, ...], tuple[str, ...], int]:
    """A contract's ``(users, teams, approvals)`` owner declaration.

    Approvals default to zero: declared owners document and route
    review without gating the merge until a count is asked for,
    which is what a solo maintainer needs (a forge that forbids
    self-approval deadlocks a solo repo on any required review).
    """
    table = _owners_table(contract)
    users = tuple(str(name) for name in table.get("users", []) if str(name).strip())
    teams = tuple(str(name) for name in table.get("teams", []) if str(name).strip())
    approvals = int(table.get("approvals", 0))
    return users, teams, approvals

offline_forge

offline_forge(root: Path) -> Forge

The contract's forge backend with no credential attached.

The codeowners rendering is pure string building, so the drift gate may hold a backend offline; nothing built here may be used for a network call.

Source code in packages/workshop/src/livery/workshop/_governance.py
def offline_forge(root: Path) -> Forge:
    """The contract's forge backend with no credential attached.

    The codeowners rendering is pure string building, so the drift
    gate may hold a backend offline; nothing built here may be used
    for a network call.
    """
    from livery.forge import GiteaForge, GithubForge, GitlabForge

    contract = load_contract(root / "workshop.toml")
    table = contract.get("forge") or {}
    kind = str(table.get("kind", ""))
    url = str(table.get("url", ""))
    if kind == "github":
        return GithubForge.connect(url=url, token="")
    if kind == "gitea":
        return GiteaForge.connect(url=url or "http://offline.invalid", token="")
    if kind == "gitlab":
        return GitlabForge.connect(url=url or "http://offline.invalid", token="")
    fail(f"unknown forge kind {kind!r}: use github, gitea, or gitlab")

privileged_paths

privileged_paths(root: Path) -> tuple[str, ...]

The authoritative root-relative paths guarded by root [owners].

Every path that can alter CI execution, CI credentials, tool resolution, root environment defaults, or governance rules comes from this one function; CODEOWNERS generation, drift checking, and security checks all read it. Per-package workshop.toml files are intentionally omitted: edits to [owners] force a CODEOWNERS diff (including # approvals: <n>), and edits to extensions, dependencies, package names, or new CI points force diffs in guarded root files via drift.check.

Source code in packages/workshop/src/livery/workshop/_governance.py
def privileged_paths(root: Path) -> tuple[str, ...]:
    """The authoritative root-relative paths guarded by root ``[owners]``.

    Every path that can alter CI execution, CI credentials, tool
    resolution, root environment defaults, or governance rules comes
    from this one function; CODEOWNERS generation, drift checking, and
    security checks all read it. Per-package ``workshop.toml`` files
    are intentionally omitted: edits to ``[owners]`` force a CODEOWNERS
    diff (including ``# approvals: <n>``), and edits to extensions,
    dependencies, package names, or new CI points force diffs in
    guarded root files via ``drift.check``.
    """
    contract = load_contract(root / "workshop.toml")
    forge_table = contract.get("forge") or {}
    paths: list[str] = ["/workshop.toml"]
    if str(forge_table.get("kind", "")):
        rendered_path = offline_forge(root).codeowners(()).path
        paths.append(f"/{rendered_path}")
    paths.extend(_PRIVILEGED_WORKFLOW_PATHS)
    paths.extend(_PRIVILEGED_ROOT_PATHS)
    paths.extend(_driver_closure_paths(root))
    return tuple(dict.fromkeys(paths))

governance_entries

governance_entries(root: Path) -> tuple[CodeownersEntry, ...]

The neutral ownership declarations, packages first and root guard last.

Each package's owners guard its directory; the root contract's owners guard every pattern from privileged_paths under the governance section. Package entries come first and the governance section comes last so last-match-wins dialects (GitHub and Gitea) never let a package rule shadow a privileged path, and GitLab renders the governance entries in their own additive [governance] section. A workspace with no owner declarations anywhere answers empty, and no file is generated.

Source code in packages/workshop/src/livery/workshop/_governance.py
def governance_entries(root: Path) -> tuple[CodeownersEntry, ...]:
    """The neutral ownership declarations, packages first and root guard last.

    Each package's owners guard its directory; the root contract's
    owners guard every pattern from `privileged_paths` under the
    ``governance`` section. Package entries come first and the
    governance section comes last so last-match-wins dialects (GitHub
    and Gitea) never let a package rule shadow a privileged path, and
    GitLab renders the governance entries in their own additive
    ``[governance]`` section. A workspace with no owner declarations
    anywhere answers empty, and no file is generated.
    """
    from livery.workshop._packages import discover_packages

    contract = load_contract(root / "workshop.toml")
    forge_table = contract.get("forge") or {}
    owner = str(forge_table.get("owner", ""))
    if not str(forge_table.get("kind", "")):
        # No forge declared: nothing to render a dialect for, and a
        # bare rig must not be forced to invent one.
        return ()

    def _qualified(users: tuple[str, ...], teams: tuple[str, ...]) -> tuple[str, ...]:
        return users + tuple(f"{owner}/{team}" for team in teams)

    entries: list[CodeownersEntry] = []
    if (root / "packages").is_dir():
        for package in discover_packages(root):
            contract_file = package.directory / "workshop.toml"
            users, teams, approvals = owners_of(load_contract(contract_file))
            if not (users or teams):
                continue
            entries.append(
                CodeownersEntry(
                    path=f"/{package.path}/",
                    owners=_qualified(users, teams),
                    min_approvals=approvals,
                )
            )
    root_users, root_teams, root_approvals = owners_of(contract)
    if root_users or root_teams:
        guard = _qualified(root_users, root_teams)
        for path in privileged_paths(root):
            entries.append(
                CodeownersEntry(
                    path=path,
                    owners=guard,
                    min_approvals=root_approvals,
                    section="governance",
                )
            )
    return tuple(entries)

codeowners_file

codeowners_file(root: Path) -> Codeowners | None

The rendered codeowners artifact, or None with no declarations.

Source code in packages/workshop/src/livery/workshop/_governance.py
def codeowners_file(root: Path) -> Codeowners | None:
    """The rendered codeowners artifact, or None with no declarations."""
    entries = governance_entries(root)
    if not entries:
        return None
    return offline_forge(root).codeowners(entries)

governance_paths

governance_paths(root: Path) -> tuple[str, ...]

The paths whose change means governance may need re-applying.

Source code in packages/workshop/src/livery/workshop/_governance.py
def governance_paths(root: Path) -> tuple[str, ...]:
    """The paths whose change means governance may need re-applying."""
    paths = ["workshop.toml", "packages/*/workshop.toml"]
    rendered = codeowners_file(root)
    if rendered is not None:
        paths.append(rendered.path)
    return tuple(paths)

governance_config

governance_config(root: Path) -> RepoConfig

The approvals half of the repository settings.

The repo-wide count is the highest any declaration asks, because GitHub and Gitea express one count through protection; GitLab's per-path sections carry the rest, where a paid tier enforces them. No declarations anywhere means no approval requirement.

Source code in packages/workshop/src/livery/workshop/_governance.py
def governance_config(root: Path) -> RepoConfig:
    """The approvals half of the repository settings.

    The repo-wide count is the highest any declaration asks, because
    GitHub and Gitea express one count through protection; GitLab's
    per-path sections carry the rest, where a paid tier enforces
    them. No declarations anywhere means no approval requirement.
    """
    entries = governance_entries(root)
    if not entries:
        return RepoConfig()
    highest = max(entry.min_approvals for entry in entries)
    # A count of zero asserts zero and requires no codeowner review
    # either: on a forge that forbids self-approval, a codeowner
    # requirement alone still deadlocks a solo repo, and ownership
    # stays documented in the file.
    return RepoConfig(
        min_approvals=highest,
        require_codeowner_review=highest > 0,
        dismiss_stale_reviews=highest > 0,
    )

unknown_owners

unknown_owners(root: Path, forge: Forge, owner: str) -> tuple[str, ...]

Declared owners the forge does not know, for configure's check.

Users are checked against members(owner), teams against teams(owner); the answers are live listings, so this runs only where the forge is already being spoken to, never on the merge path.

Source code in packages/workshop/src/livery/workshop/_governance.py
def unknown_owners(root: Path, forge: Forge, owner: str) -> tuple[str, ...]:
    """Declared owners the forge does not know, for configure's check.

    Users are checked against ``members(owner)``, teams against
    ``teams(owner)``; the answers are live listings, so this runs
    only where the forge is already being spoken to, never on the
    merge path.
    """
    members = set(forge.members(owner))
    teams = set(forge.teams(owner))
    missing: list[str] = []
    for entry in governance_entries(root):
        where = "/workshop.toml" if entry.section == "governance" else entry.path
        for name in entry.owners:
            _, slash, team = name.partition("/")
            if slash:
                if team not in teams and name not in teams:
                    missing.append(f"team {name} (declared on {where})")
            elif name not in members:
                missing.append(f"user {name} (declared on {where})")
    return tuple(dict.fromkeys(missing))