Skip to content

livery.workshop._workflow_tasks

livery.workshop._workflow_tasks

The workflow group: the reserved-branch lifecycles' surface.

workflow.abort stops a reserved workflow, policy layered over the same teardown mechanism fm abandon uses. The hidden workflow.configure asserts repository settings from the workspace contract, run at birth, as release aftercare, and after an abort. The lifecycle drivers (workflow.release, workflow.update) arrive with their own modules; this one owns what every kind shares.

Functions:

Name Description
render_workflows

Print one line per workflow: name, state, author, the way forward.

abort_policy

The abort's state gates, then the shared teardown.

workflow_abort

Stop a reserved workflow: disarm, close its PR, tear its branch down.

required_context_string

The status context string protection must require, per forge.

contract_config

The repository settings the workspace contract states.

contract_changed

The governed paths HEAD's own commit changed; empty is none.

workflow_configure

Assert the contract's repository settings; idempotent drift repair.

assert_configuration

The configure flow, root-taking so birth can call it too.

reconcile_schedules

Make the forge's clock match the points that run on it; what was done.

Attributes:

Name Type Description
workflow
GOVERNED_PATHS
SCHEDULE_PREFIX

workflow module-attribute

workflow = group('workflow', help='The reserved-branch lifecycles')

GOVERNED_PATHS module-attribute

GOVERNED_PATHS = ('workshop.toml', 'CODEOWNERS', '.gitea/CODEOWNERS', '.github/CODEOWNERS')

SCHEDULE_PREFIX module-attribute

SCHEDULE_PREFIX = 'workshop: '

render_workflows

render_workflows(states: tuple[WorkflowStatus, ...]) -> None

Print one line per workflow: name, state, author, the way forward.

Source code in packages/workshop/src/livery/workshop/_workflow_tasks.py
def render_workflows(states: tuple[WorkflowStatus, ...]) -> None:
    """Print one line per workflow: name, state, author, the way forward."""
    if not states:
        print("  no reserved workflows in flight")
        return
    for wf in states:
        author = f" ({wf.author})" if wf.author else ""
        extra = f" - {wf.detail}" if wf.detail else ""
        tagged = (
            f" [tagged: {', '.join(wf.tagged)}]"
            if wf.tagged and wf.state is not WorkflowState.SUCCEEDED
            else ""
        )
        print(f"  {wf.name}: {wf.state.value}{author}{extra}{tagged}")

abort_policy

abort_policy(repo: Repository, root: Path, states: tuple[WorkflowStatus, ...], name: str, *, force: bool, base: str = 'main', interactive: bool = False) -> None

The abort's state gates, then the shared teardown.

Bare with one workflow targets it; several ask interactively or refuse by name, silence never picks a teardown target. UNKNOWN refuses without force, never tear down on a blip; a live state refuses without force; a bare --force with several in flight refuses, force one by name.

Source code in packages/workshop/src/livery/workshop/_workflow_tasks.py
def abort_policy(
    repo: Repository,
    root: Path,
    states: tuple[WorkflowStatus, ...],
    name: str,
    *,
    force: bool,
    base: str = "main",
    interactive: bool = False,
) -> None:
    """The abort's state gates, then the shared teardown.

    Bare with one workflow targets it; several ask interactively or
    refuse by name, silence never picks a teardown target. UNKNOWN
    refuses without force, never tear down on a blip; a live state
    refuses without force; a bare ``--force`` with several in flight
    refuses, force one by name.
    """
    if not states:
        print("  no reserved workflows to abort")
        return
    target: WorkflowStatus | None = None
    if name:
        target = next((wf for wf in states if wf.name == name), None)
        if target is None:
            known = ", ".join(wf.name for wf in states)
            fail(f"no workflow named {name!r}; in flight: {known}")
    elif len(states) == 1:
        target = states[0]
    elif interactive:
        options: list[tuple[str, WorkflowStatus | None]] = [
            (f"{wf.name} ({wf.author or 'unknown author'}, {wf.state.value})", wf)
            for wf in states
        ]
        options.append(("nothing - leave them all running", None))
        picked = footman.select("abort which?", options)
        # The select's typing admits a bare-label pick; every option
        # here carries a value, so a str can only mean no target.
        target = picked if not isinstance(picked, str) else None
        if target is None:
            raise SystemExit("  nothing aborted")
    else:
        listed = "\n".join(
            f"    {footman.prog()} workflow.abort {wf.name}"
            + (f"  ({wf.author}, {wf.state.value})" if wf.author else "")
            for wf in states
        )
        fail(
            "several workflows are in flight, and silence must not pick a"
            f" teardown target. Abort one by name:\n{listed}"
        )
    assert target is not None
    if force and not name and len(states) > 1:
        fail(
            "--force with several workflows in flight needs a name: a bare"
            " force must not sweep what someone else is running"
        )
    if target.state is WorkflowState.UNKNOWN and not force:
        fail(
            f"{target.name}'s state could not be read, and a blip must never"
            " look like permission to tear down. Retry when the forge"
            f" answers, or `{footman.prog()} workflow.abort {target.name}"
            " --force` if you"
            " know it is dead."
        )
    if target.state not in TEARDOWN_SAFE and not force:
        who = target.author or "someone"
        fail(
            f"{target.name} is {target.state.value} ({who}); aborting it"
            " loses in-flight work. Wait for it, coordinate with its"
            f" author, or `{footman.prog()} workflow.abort {target.name}"
            " --force` to tear"
            " it down deliberately."
        )
    from livery.workshop._submit import teardown_branch

    head_sha = ""
    try:
        head_sha = git.any_head(root, target.branch)
    except Exception:
        head_sha = ""
    teardown_branch(repo, root, target.branch, base)
    _reconcile_configuration(root, head_sha)

workflow_abort

workflow_abort(name: Annotated[str, suggest(_active_names, strict=False), doc('the workflow to stop; bare targets the only one in flight')] = '', force: Annotated[bool, doc('tear down a live or unreadable workflow')] = False) -> None

Stop a reserved workflow: disarm, close its PR, tear its branch down.

Bare targets the only workflow in flight; with several, an interactive run lists them and asks, a non-interactive run refuses naming each. A live or unreadable workflow refuses without --force, and a bare --force never sweeps several. Ends by re-asserting the repository configuration, so an aborted workflow that had moved settings forward cannot leave protection demanding contexts that never report again.

Source code in packages/workshop/src/livery/workshop/_workflow_tasks.py
@workflow.task(name="abort", interactive=True)
def workflow_abort(
    name: Annotated[
        str,
        suggest(_active_names, strict=False),
        doc("the workflow to stop; bare targets the only one in flight"),
    ] = "",
    force: Annotated[bool, doc("tear down a live or unreadable workflow")] = False,
) -> None:
    """Stop a reserved workflow: disarm, close its PR, tear its branch down.

    Bare targets the only workflow in flight; with several, an
    interactive run lists them and asks, a non-interactive run
    refuses naming each. A live or unreadable workflow refuses
    without ``--force``, and a bare ``--force`` never sweeps several.
    Ends by re-asserting the repository configuration, so an aborted
    workflow that had moved settings forward cannot leave protection
    demanding contexts that never report again.
    """
    repo, root = _resolved()
    states = workflow_states(repo, root)
    abort_policy(
        repo,
        root,
        states,
        name,
        force=force,
        interactive=footman.attended(),
    )

required_context_string

required_context_string(forge_kind: str, context: str) -> str

The status context string protection must require, per forge.

The name in the contract is the gate job's; forges report it differently. GitHub reports the job name itself. Gitea reports Actions statuses as <workflow name> / <job> (<event>), so a bare job name never matches and the required check can never pass; the workflow's emitted name is ci, and the merge- deciding event is the pull request's. GitLab has no required contexts (the capability probe drops the half), so its spelling never reaches a forge.

Source code in packages/workshop/src/livery/workshop/_workflow_tasks.py
def required_context_string(forge_kind: str, context: str) -> str:
    """The status context string protection must require, per forge.

    The name in the contract is the gate job's; forges report it
    differently. GitHub reports the job name itself. Gitea reports
    Actions statuses as ``<workflow name> / <job> (<event>)``, so a
    bare job name never matches and the required check can never
    pass; the workflow's emitted name is ``ci``, and the merge-
    deciding event is the pull request's. GitLab has no required
    contexts (the capability probe drops the half), so its spelling
    never reaches a forge.
    """
    if forge_kind == "gitea":
        return f"ci / {context} (pull_request)"
    return context

contract_config

contract_config(root: Path) -> RepoConfig

The repository settings the workspace contract states.

The approvals half derives from the owner declarations (livery.workshop._governance): the highest declared count, with codeowner review required whenever anyone is declared. A forge without the min_approvals capability gets the config without that half rather than a refusal: governance degrades to the codeowners file alone, which is what the forge can honour.

Source code in packages/workshop/src/livery/workshop/_workflow_tasks.py
def contract_config(root: Path) -> RepoConfig:
    """The repository settings the workspace contract states.

    The approvals half derives from the owner declarations
    (livery.workshop._governance): the highest declared count, with
    codeowner review required whenever anyone is declared. A forge
    without the min_approvals capability gets the config without
    that half rather than a refusal: governance degrades to the
    codeowners file alone, which is what the forge can honour.
    """
    from livery.workshop._governance import governance_config
    from livery.workshop._points import EVERY_RUNNER_LABEL

    contract = load_contract(root / "workshop.toml")
    ci = contract.get("ci") or {}
    context = str(ci.get("required-context") or "gate")
    forge_kind = str((contract.get("forge") or {}).get("kind", ""))
    approvals = governance_config(root)
    return RepoConfig(
        squash_only=True,
        delete_branch_on_merge=True,
        allow_auto_merge=True,
        required_contexts=(required_context_string(forge_kind, context),),
        # The release train's receipts: once cut, no ordinary push
        # may delete or move them. A forge's glob stops at a slash, so
        # a package in a group directory needs the second pattern.
        protected_tag_patterns=("packages/*/v*", "packages/*/*/v*"),
        # The same truth spelled for a forge that cannot name
        # contexts: the server refuses merges while the head is not
        # green, the UI's merge button included.
        require_pipeline_success=True,
        min_approvals=approvals.min_approvals,
        require_codeowner_review=approvals.require_codeowner_review,
        # The label `submit --every-runner` sets, so a forge that
        # refuses a label it does not carry has it before any submit.
        labels=(
            Label(
                name=EVERY_RUNNER_LABEL,
                color="1d76db",
                description="the gate runs every runner for this pull request",
            ),
        ),
    )

contract_changed

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

The governed paths HEAD's own commit changed; empty is none.

The merge point's commit is one squash on main, so its file list is the merge's whole diff. A shallow checkout of depth one reads a squash as a root commit and lists every file, so the shell fetches two.

Source code in packages/workshop/src/livery/workshop/_workflow_tasks.py
def contract_changed(root: Path) -> tuple[str, ...]:
    """The governed paths HEAD's own commit changed; empty is none.

    The merge point's commit is one squash on main, so its file list
    is the merge's whole diff. A shallow checkout of depth one reads
    a squash as a root commit and lists every file, so the shell
    fetches two.
    """
    changed = git.files_in_commit(root, "HEAD")
    return tuple(
        path
        for path in changed
        if path in GOVERNED_PATHS
        or (path.startswith("packages/") and path.endswith("/workshop.toml"))
    )

workflow_configure

workflow_configure(if_changed: Annotated[bool, doc('only when HEAD changed a contract or the owners file')] = False) -> None

Assert the contract's repository settings; idempotent drift repair.

Run at repository birth, as release aftercare, after an abort, and at the merge point, where --if-changed makes it classify its own commit and exit fast when no contract path changed. Resolves the admin ladder (FORGE_ADMIN_TOKEN, host-qualified first, the everyday token as the fallback); a refused write teaches the grant and the variable. Declared owners the forge does not know refuse before anything is applied: a review chain pointing at nobody is worse than unapplied settings.

Source code in packages/workshop/src/livery/workshop/_workflow_tasks.py
@workflow.task(name="configure", hidden=True)
def workflow_configure(
    if_changed: Annotated[
        bool, doc("only when HEAD changed a contract or the owners file")
    ] = False,
) -> None:
    """Assert the contract's repository settings; idempotent drift repair.

    Run at repository birth, as release aftercare, after an abort,
    and at the merge point, where ``--if-changed`` makes it classify
    its own commit and exit fast when no contract path changed.
    Resolves the admin ladder (``FORGE_ADMIN_TOKEN``, host-qualified
    first, the everyday token as the fallback); a refused write
    teaches the grant and the variable. Declared owners the forge
    does not know refuse before anything is applied: a review chain
    pointing at nobody is worse than unapplied settings.
    """
    root = _root()
    if if_changed:
        changed = contract_changed(root)
        if not changed:
            print("  no contract or owners path changed in HEAD; nothing to reconcile")
            return
        print(f"  governed paths changed: {', '.join(changed)}")
    assert_configuration(root)

assert_configuration

assert_configuration(root: Path) -> None

The configure flow, root-taking so birth can call it too.

Source code in packages/workshop/src/livery/workshop/_workflow_tasks.py
def assert_configuration(root: Path) -> None:
    """The configure flow, root-taking so birth can call it too."""
    from livery.forge import ForgeError, Unsupported
    from livery.workshop._forge_lane import admin_forge, admin_repository
    from livery.workshop._governance import unknown_owners

    repo, admin_var = admin_repository(root)
    forge, _ = admin_forge(root)
    contract = load_contract(root / "workshop.toml")
    owner = str((contract.get("forge") or {}).get("owner", ""))
    missing = unknown_owners(root, forge, owner)
    if missing:
        listed = "\n".join(f"    {entry}" for entry in missing)
        fail(
            "the owner declarations name people or teams this forge does"
            f" not know:\n{listed}\n  Fix the declarations (or the org"
            " membership) and re-run."
        )
    from dataclasses import replace

    config = contract_config(root)
    if config.min_approvals is not None and not forge.supports("min_approvals"):
        # The forge cannot enforce the count (GitLab's paid tiers);
        # the codeowners file still documents it, so the rest of the
        # contract applies rather than nothing.
        print(
            "  note: this instance cannot enforce approval counts"
            " (capability: min_approvals); the codeowners file still"
            " names the reviewers"
        )
        config = replace(config, min_approvals=None, require_codeowner_review=None)
    if config.required_contexts is not None and not forge.supports("required_contexts"):
        # GitLab: protection cannot name check contexts, and the
        # pipeline-success block carries the same truth there, the
        # UI's merge button included.
        print(
            "  note: this forge cannot name required check contexts"
            " (capability: required_contexts); the pipeline-success"
            " block enforces green-before-merge instead, the forge"
            " UI included"
        )
        config = replace(config, required_contexts=None)
    try:
        repo.configure(config)
    except Unsupported as error:
        # A decline the probes above did not predict: name it
        # verbatim, never half-teach a token that would not help.
        fail(
            f"the forge declined part of the configuration:\n{error}\n"
            f"  `{footman.prog()} doctor` says what this forge grants."
        )
    except ForgeError as error:
        used = admin_var or "the everyday token"
        fail(
            f"the forge refused the configuration using {used}:\n{error}\n"
            "  An administrator's token applies it: set FORGE_ADMIN_TOKEN"
            " (host-qualified FORGE_ADMIN_TOKEN__<HOST> where one machine"
            f" serves several forges) and re-run"
            f" `{footman.prog()} workflow.configure`."
        )
    from livery.workshop._points import job_seams

    if "pages" in job_seams(root).values() and forge.supports("pages_config"):
        repo.ensure_pages(build_type="workflow")
        print("  pages hosting asserted (workflow build type)")
    for line in reconcile_schedules(repo, forge):
        print(line)
    print("  repository configuration asserted from the contract")

reconcile_schedules

reconcile_schedules(repo: Repository, forge: Forge) -> list[str]

Make the forge's clock match the points that run on it; what was done.

A forge whose clock is in the workflow file (GitHub, Gitea) has nothing to reconcile and says so. On a forge with pipeline schedules (GitLab) every declared point whose events include schedule gets one schedule on main, named workshop: <point>, at the point's cron, starting its pipeline with FORGE_WORKFLOW set to the point's workflow file so the document routes it; a schedule the reconcile named for a point no longer declared is deleted.

Source code in packages/workshop/src/livery/workshop/_workflow_tasks.py
def reconcile_schedules(repo: Repository, forge: Forge) -> list[str]:
    """Make the forge's clock match the points that run on it; what was done.

    A forge whose clock is in the workflow file (GitHub, Gitea) has
    nothing to reconcile and says so. On a forge with pipeline
    schedules (GitLab) every declared point whose events include
    ``schedule`` gets one schedule on ``main``, named
    ``workshop: <point>``, at the point's cron, starting its pipeline
    with ``FORGE_WORKFLOW`` set to the point's workflow file so the
    document routes it; a schedule the reconcile named for a point
    no longer declared is deleted.
    """
    from livery.workshop._points import DECLARED

    if not forge.supports("pipeline_schedules"):
        return ["  schedules: the clock is in the workflow file; nothing to reconcile"]
    wanted = {
        f"{SCHEDULE_PREFIX}{point.name}": point
        for point in DECLARED
        if "schedule" in point.events
    }
    lines: list[str] = []
    for description, point in wanted.items():
        schedule = repo.schedule.ensure(
            description,
            ref="main",
            cron=point.cron,
            variables={"FORGE_WORKFLOW": point.workflow},
        )
        lines.append(
            f"  schedule {description!r}: {schedule.cron} on {schedule.ref},"
            f" FORGE_WORKFLOW={point.workflow}"
        )
    for schedule in repo.schedule.list():
        if (
            schedule.description.startswith(SCHEDULE_PREFIX)
            and schedule.description not in wanted
        ):
            repo.schedule.delete(schedule.description)
            lines.append(f"  schedule {schedule.description!r}: deleted, no such point")
    return lines