Skip to content

livery.workshop._quality

livery.workshop._quality

The quality verbs: the gate and its parts, over the packages the contracts declare.

Each verb discovers the packages by their workshop.toml and runs its phase's registered steps over them, each step over the packages whose extensions it judges. check is the whole local gate; CI runs the same command.

Functions:

Name Description
walk

Walk the registry: the one place the gate's order lives.

affected_legs

The contract's [ci] affected-legs; false when undeclared.

ci_affected_base

The base branch a pull request's check leg narrows against, or empty.

ci_changes

What this CI run changed against the base it measures from; None for everything.

check

Run the gate: every registered step, the rewriters first under --fix.

named_files

paths as the files they name, root-relative: a file, or a directory's files.

run_steps

Run the steps names through the walk: a generated verb's body.

run_phase_over

Run the steps of phase over packages whole; nothing recorded as proved.

fix_files

Run the gate's fixers over paths, judging nothing.

say_skipped

Print a skip, and put it on the timeline as an event.

caches_clear

Remove build artifacts, checker caches, and legacy root cache directories.

Attributes:

Name Type Description
GATE_INPUTS Mapping[str, Mapping[str, object]]
VERB_INPUTS Mapping[str, Mapping[str, object]]
AFFECTED_LEGS_KEY
caches

GATE_INPUTS module-attribute

GATE_INPUTS: Mapping[str, Mapping[str, object]] = {'build': {'isolated': False, 'configuration': 'instrumented'}}

VERB_INPUTS module-attribute

VERB_INPUTS: Mapping[str, Mapping[str, object]] = {'build': {'isolated': False, 'configuration': 'debug'}}

AFFECTED_LEGS_KEY module-attribute

AFFECTED_LEGS_KEY = 'affected-legs'

caches module-attribute

caches = group('caches', help="The workspace's derived caches")

walk

walk(ctx: PhaseContext, *, between: Callable[[], None] | None = None, judge: bool = True, only: frozenset[str] | None = None, inputs: Mapping[str, Mapping[str, object]] = GATE_INPUTS, record_proved: bool = False, skip_units: frozenset[str] = frozenset()) -> None

Walk the registry: the one place the gate's order lives.

Every gate comes here, the whole one, CI's narrowed legs and a machine's narrowed step alike, and runs the registry's steps through the one walk (livery.workshop._phases.walk_steps). Each step an extension registered is named first. Under --fix every fixer that applies runs, one at a time in the rewriters' order, before any judge reads the tree, and a step that rewrote is not judged again in the run; then between runs, where a machine's run measures the tree the judges read; then every judge runs in one parallel block, the steps a judge runs after among them, and one refusal is the verdict. A step whose claims reach no file in scope is said and not started. On a shard other than the first, a step that does not read the shard is left to the first shard and said (livery.workshop._steps.on_this_shard). Without judge the walk stops after the fixers, the post-edit hook's run. only keeps the named steps alone, a generated verb's run. inputs are the keys the walk gives each phase, the gate's own (livery.workshop._quality.GATE_INPUTS) unless another engine names its. With record_proved inside CI, every step unit outcome is written to the proved store family beside today's records.

Source code in packages/workshop/src/livery/workshop/_quality.py
def walk(
    ctx: PhaseContext,
    *,
    between: Callable[[], None] | None = None,
    judge: bool = True,
    only: frozenset[str] | None = None,
    inputs: Mapping[str, Mapping[str, object]] = GATE_INPUTS,
    record_proved: bool = False,
    skip_units: frozenset[str] = frozenset(),
) -> None:
    """Walk the registry: the one place the gate's order lives.

    Every gate comes here, the whole one, CI's narrowed legs and a
    machine's narrowed step alike, and runs the registry's steps
    through the one walk ([livery.workshop._phases.walk_steps][]). Each
    step an extension registered is named first. Under ``--fix`` every
    fixer that applies runs, one at a time in the rewriters' order,
    before any judge reads the tree, and a step that rewrote is not
    judged again in the run; then *between* runs, where a machine's
    run measures the tree the judges read; then every judge runs in
    one parallel block, the steps a judge runs after among them, and
    one refusal is the verdict. A step whose claims reach no file in
    scope is said and not started. On a shard other than the first, a
    step that does not read the shard is left to the first shard and
    said ([livery.workshop._steps.on_this_shard][]). Without *judge*
    the walk stops after the fixers, the post-edit hook's run. *only*
    keeps the named steps alone, a generated verb's run. *inputs* are
    the keys the walk gives each phase, the gate's own
    ([livery.workshop._quality.GATE_INPUTS][]) unless another engine
    names its. With *record_proved* inside CI, every step unit outcome
    is written to the ``proved`` store family beside today's records.
    """
    from livery.workshop._phases import StepOutcome

    for line in _steps.narrowings():
        print(line)
    ctx = replace(ctx, catalogue=_steps.catalogue(ctx))

    def kept(names: tuple[str, ...]) -> tuple[str, ...]:
        if only is not None:
            names = tuple(n for n in names if n in only)
        return _steps.on_this_shard(_steps.with_files(names, ctx), ctx)

    for name in kept(_steps.rewriters(ctx)):
        walk_steps(ctx, (_steps.step_for(name),), inputs=inputs, fixing=True)
    if ctx.fix and between is not None:
        between()
    if not judge:
        return
    if not record_proved:
        walk_steps(
            ctx,
            _steps.with_earlier(kept(_steps.judges(ctx))),
            inputs=inputs,
            skip_units=skip_units,
        )
        return
    outcomes: list[StepOutcome] = []
    candidates = _steps.judges(ctx)
    if only is not None:
        candidates = tuple(n for n in candidates if n in only)
    after_files = _steps.with_files(candidates, ctx)
    dropped_by_files = tuple(n for n in candidates if n not in after_files)
    # Record steps skipped for having no matching files only on the shard
    # that owns them (shard 1 for unsharded steps), never as green.
    for name in _steps.on_this_shard(dropped_by_files, ctx):
        record = _steps.step_for(name)
        if record.scope == _steps.PACKAGE or record.extensions:
            matched = [p for p in ctx.judged if _steps.judges_unit(record, p)]
            if matched:
                for package in matched:
                    if f"{record.name}@{package.path}" not in skip_units:
                        outcomes.append(StepOutcome(record, package.path, "skipped"))
                continue
        if f"{record.name}@." not in skip_units:
            outcomes.append(StepOutcome(record, ".", "skipped"))
    running = _steps.on_this_shard(after_files, ctx)
    try:
        walk_steps(
            ctx,
            _steps.with_earlier(running),
            inputs=inputs,
            outcomes=outcomes,
            skip_units=skip_units,
        )
    finally:
        _flush_proved(ctx, outcomes)

affected_legs

affected_legs(root: Path) -> bool

The contract's [ci] affected-legs; false when undeclared.

The contract's judge holds the value to a boolean: the legs either narrow or they do not, and a stray string would read as true.

Source code in packages/workshop/src/livery/workshop/_quality.py
def affected_legs(root: Path) -> bool:
    """The contract's ``[ci] affected-legs``; false when undeclared.

    The contract's judge holds the value to a boolean: the legs either
    narrow or they do not, and a stray string would read as true.
    """
    from livery.workshop._contract import load_contract

    ci = load_contract(root / "workshop.toml").get("ci") or {}
    return bool(ci.get(AFFECTED_LEGS_KEY, False))

ci_affected_base

ci_affected_base(root: Path, run: RunContext | None) -> str

The base branch a pull request's check leg narrows against, or empty.

Empty outside CI, when the contract does not declare [ci] affected-legs, on any event but a pull request, and when the payload names no base.

Source code in packages/workshop/src/livery/workshop/_quality.py
def ci_affected_base(root: Path, run: RunContext | None) -> str:
    """The base branch a pull request's check leg narrows against, or empty.

    Empty outside CI, when the contract does not declare
    ``[ci] affected-legs``, on any event but a pull request, and when
    the payload names no base.
    """
    if run is None or not affected_legs(root):
        return ""
    if run.event == "push":
        return ""
    if run.event != "pull_request":
        print(
            f"  affected-legs: a {run.event or 'non pull request'} run pays"
            " the full gate"
        )
        return ""
    if not run.base_ref:
        print("  affected-legs: the event payload names no base branch; full gate")
        return ""
    return run.base_ref

ci_changes

ci_changes(root: Path) -> Changes | None

What this CI run changed against the base it measures from; None for everything.

A pull request's run in a workspace that declares [ci] affected-legs measures from its base branch: the paths changed since the merge base with origin/<base>, committed or not, with that merge base, so a widen reference can read a file as it was. None at a desk, on any other event, without affected-legs, and when git cannot answer; the run then judges everything, and the line printed says why.

Source code in packages/workshop/src/livery/workshop/_quality.py
def ci_changes(root: Path) -> Changes | None:
    """What this CI run changed against the base it measures from; None for everything.

    A pull request's run in a workspace that declares ``[ci]
    affected-legs`` measures from its base branch: the paths changed
    since the merge base with ``origin/<base>``, committed or not, with
    that merge base, so a ``widen`` reference can read a file as it
    was. None at a desk, on any other event, without
    ``affected-legs``, and when git cannot answer; the run then judges
    everything, and the line printed says why.
    """
    from livery.workshop._ci_context import run_context
    from livery.workshop._influence import Changes

    run = run_context()
    base = ci_affected_base(root, run) if run is not None else ""
    if not base:
        return None
    try:
        git.fetch(root)
        paths = tuple(git.changed_paths(root, base))
        before = git.merge_base(root, base)
    except git.GitError as error:
        print(
            f"  affected-legs: no diff against origin/{base}; everything is"
            f" judged ({error})"
        )
        return None
    return Changes(root, paths, before)

check

check(*paths: str, full: Annotated[bool, doc('run everything, whatever the record proves')] = False, fix: Forward[bool] = False, safe_fix: Annotated[bool, doc('fix, removing no code: safe for an edit in flight')] = False, base: Annotated[str, doc("the branch the chain's root is taken from")] = 'main', point: Annotated[str, doc('run the tests of this CI point, nightly say')] = '', shard: Annotated[str, doc("run this shard's share of a sharded check leg: <i>of<n>, such as 2of4")] = '') -> None

Run the gate: every registered step, the rewriters first under --fix.

With paths, exactly those files are checked, or the files under those directories: every step whose claims reach one of them runs over them and no other, a step without claims does not run, and nothing is recorded as proved. --safe-fix runs the fixers in their in-flight mode, which removes no code, and refuses beside --fix. --point hands a CI point to the test phase, which selects that point's tests instead of the gate's.

--shard names the shard of a sharded check leg this run is, 2of4: a step that reads the shard runs its share, every other step runs on the first shard alone, and the walk names each step it leaves there. Inside CI the leg's label names the shard and the flag is not needed. A sharded run records no tree as proved, since a share of the gate ran. A shard outside the form, 0of2, refuses naming it.

On a machine and inside CI, the gate reads the proved record (livery.workshop._proved): each unit whose inputs match an existing green row for this platform is skipped, and every unproved unit runs and records its verdict. --full runs everything whatever the record says. On a push to main, matched branch rows are copied onto proved/main/<leg> so an already-proved tree skips the gate.

--fix runs format and lint in their fix modes: each prints what it found, rewrites what is mechanical, and still fails on what is not. The two rewrite the same files, so under --fix they run one after the other before the rest of the gate.

--fix refuses inside CI: a runner's checkout is judged, never rewritten, because a fix there mutates a copy nobody keeps and hides the finding from the verdict. Run the fix locally and push the result.

On a machine the state store is read from what the last sync or start fetched (livery.git.fetched_snapshot): nothing the gate runs reaches origin, and a checkout the store was never fetched into roots its chain on a full gate and says so. Inside CI the legs read the store as the run's own snapshot.

Source code in packages/workshop/src/livery/workshop/_quality.py
@task
def check(
    *paths: str,
    full: Annotated[bool, doc("run everything, whatever the record proves")] = False,
    fix: Forward[bool] = False,
    safe_fix: Annotated[
        bool, doc("fix, removing no code: safe for an edit in flight")
    ] = False,
    base: Annotated[str, doc("the branch the chain's root is taken from")] = "main",
    point: Annotated[str, doc("run the tests of this CI point, nightly say")] = "",
    shard: Annotated[
        str,
        doc("run this shard's share of a sharded check leg: <i>of<n>, such as 2of4"),
    ] = "",
) -> None:
    """Run the gate: every registered step, the rewriters first under --fix.

    With *paths*, exactly those files are checked, or the files under
    those directories: every step whose claims reach one of them runs
    over them and no other, a step without claims does not run, and
    nothing is recorded as proved. ``--safe-fix`` runs the fixers in
    their in-flight mode, which removes no code, and refuses beside
    ``--fix``. ``--point`` hands a CI point to the test phase, which
    selects that point's tests instead of the gate's.

    ``--shard`` names the shard of a sharded check leg this run is,
    ``2of4``: a step that reads the shard runs its share, every other
    step runs on the first shard alone, and the walk names each step
    it leaves there. Inside CI the leg's label names the shard and the
    flag is not needed. A sharded run records no tree as proved, since
    a share of the gate ran. A shard outside the form, ``0of2``,
    refuses naming it.

    On a machine and inside CI, the gate reads the proved record
    ([livery.workshop._proved][]): each unit whose inputs match an
    existing green row for this platform is skipped, and every unproved
    unit runs and records its verdict. ``--full`` runs everything
    whatever the record says. On a push to ``main``, matched branch rows
    are copied onto ``proved/main/<leg>`` so an already-proved tree
    skips the gate.

    ``--fix`` runs format and lint in their fix modes: each prints
    what it found, rewrites what is mechanical, and still fails on
    what is not. The two rewrite the same files, so under ``--fix``
    they run one after the other before the rest of the gate.

    ``--fix`` refuses inside CI: a runner's checkout is judged,
    never rewritten, because a fix there mutates a copy nobody
    keeps and hides the finding from the verdict. Run the fix
    locally and push the result.

    On a machine the state store is read from what the last ``sync``
    or ``start`` fetched ([livery.git.fetched_snapshot][]):
    nothing the gate runs reaches origin, and a checkout the store was
    never fetched into roots its chain on a full gate and says so.
    Inside CI the legs read the store as the run's own snapshot.
    """
    from contextlib import nullcontext

    from livery.git import fetched_snapshot
    from livery.workshop._ci_context import run_context
    from livery.workshop._steps import arguments_refusal, split_arguments

    _refuse_both(fix, safe_fix)
    chosen = _current_shard(shard)
    paths, arguments = split_arguments(paths)
    if arguments:
        verb = f"{footman.prog()} check"
        fail(arguments_refusal(verb, _steps.steps_by_name().values()))
    if paths:
        _check_files(
            paths, fix=fix or safe_fix, safe=safe_fix, point=point, shard=chosen
        )
        return
    root = workspace_root()
    scope = (
        fetched_snapshot(state_store(root))
        if root is not None and run_context() is None
        else nullcontext()
    )
    with scope:
        _run_check(
            full=full,
            fix=fix or safe_fix,
            base=base,
            point=point,
            safe=safe_fix,
            shard=chosen,
        )

named_files

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

paths as the files they name, root-relative: a file, or a directory's files.

A directory stands for the files git holds under it, tracked or untracked and not ignored, or every file under it outside a git checkout. A path outside the root, or naming nothing, is left out.

Source code in packages/workshop/src/livery/workshop/_quality.py
def named_files(root: Path, paths: tuple[str, ...]) -> tuple[str, ...]:
    """*paths* as the files they name, root-relative: a file, or a directory's files.

    A directory stands for the files git holds under it, tracked or
    untracked and not ignored, or every file under it outside a git
    checkout. A path outside the root, or naming nothing, is left out.
    """
    found: set[str] = set()
    for path in paths:
        target = Path(path).resolve()
        try:
            relative = target.relative_to(root.resolve()).as_posix()
        except ValueError:
            continue
        if target.is_file():
            found.add(relative)
        elif target.is_dir():
            try:
                found.update(git.ls_files(root, relative, others=True))
            except git.GitError:
                found.update(
                    p.relative_to(root.resolve()).as_posix()
                    for p in target.rglob("*")
                    if p.is_file()
                )
    return tuple(sorted(name for name in found if (root / name).is_file()))

run_steps

run_steps(names: tuple[str, ...], paths: tuple[str, ...] = (), *, fix: bool = False, safe_fix: bool = False, point: str = '', shard: str = '', arguments: tuple[str, ...] = ()) -> None

Run the steps names through the walk: a generated verb's body.

Over the named paths, or the whole workspace; nothing is recorded as proved, since a part of the gate ran. arguments, the words after -- on a step's own verb, reach that step's tool. shard is the --shard flag's text, read as check reads it. The phases take the verb's inputs (livery.workshop._quality.VERB_INPUTS), not the gate's.

Source code in packages/workshop/src/livery/workshop/_quality.py
def run_steps(
    names: tuple[str, ...],
    paths: tuple[str, ...] = (),
    *,
    fix: bool = False,
    safe_fix: bool = False,
    point: str = "",
    shard: str = "",
    arguments: tuple[str, ...] = (),
) -> None:
    """Run the steps *names* through the walk: a generated verb's body.

    Over the named paths, or the whole workspace; nothing is recorded
    as proved, since a part of the gate ran. *arguments*, the words
    after ``--`` on a step's own verb, reach that step's tool. *shard*
    is the ``--shard`` flag's text, read as `check` reads it. The
    phases take the verb's inputs
    ([livery.workshop._quality.VERB_INPUTS][]), not the gate's.
    """
    import os

    _refuse_both(fix, safe_fix)
    if (fix or safe_fix) and os.environ.get("CI"):
        fail(
            "a fix inside CI: the runner's checkout is judged, never rewritten."
            f" Run `{footman.prog()} check --fix` locally and push the result."
        )
    chosen = _current_shard(shard)
    only = frozenset(names)
    if paths:
        _check_files(
            paths,
            fix=fix or safe_fix,
            safe=safe_fix,
            point=point,
            shard=chosen,
            only=only,
            arguments=arguments,
            inputs=VERB_INPUTS,
        )
        return
    context = _context(
        fix=fix or safe_fix,
        safe=safe_fix,
        point=point,
        shard=chosen,
        arguments=arguments,
    )
    walk(context, only=only, inputs=VERB_INPUTS)

run_phase_over

run_phase_over(phase: str, packages: tuple[Package, ...], *, tests: Mapping[str, tuple[str, ...]] | None = None) -> None

Run the steps of phase over packages whole; nothing recorded as proved.

The gate's walk (livery.workshop._quality.walk) narrowed to the steps the extensions register for phase, and the steps they run after, over the named packages alone, with the gate's inputs. A package no step of the phase judges is skipped by the walk, and a phase with no step runs nothing. An extension runs a phase this way over packages the gate did not run it on. When tests names specific test items per package, only those items run and live per-item selection is bypassed so every requested item executes. Inside CI the leg's label names the shard the run is, as check reads it without the flag.

Source code in packages/workshop/src/livery/workshop/_quality.py
def run_phase_over(
    phase: str,
    packages: tuple[Package, ...],
    *,
    tests: Mapping[str, tuple[str, ...]] | None = None,
) -> None:
    """Run the steps of *phase* over *packages* whole; nothing recorded as proved.

    The gate's walk ([livery.workshop._quality.walk][]) narrowed to the
    steps the extensions register for *phase*, and the steps they run
    after, over the named packages alone, with the gate's inputs. A
    package no step of the phase judges is skipped by the walk, and a
    phase with no step runs nothing. An extension runs a phase this
    way over packages the gate did not run it on. When *tests* names
    specific test items per package, only those items run and live
    per-item selection is bypassed so every requested item executes.
    Inside CI the leg's label names the shard the run is, as `check`
    reads it without the flag.
    """
    from livery.workshop import _proved

    names = tuple(
        record.name
        for record in _steps.steps_by_name().values()
        if record.phase == phase
    )
    if not names:
        return
    with _proved.without_item_selection():
        walk(
            _context(subset=packages, shard=_current_shard(), tests=tests),
            only=frozenset(names),
        )

fix_files

fix_files(paths: tuple[str, ...], *, safe: bool = True) -> None

Run the gate's fixers over paths, judging nothing.

Every step whose claims reach a file fixes it, and a file no claim reaches is left alone. safe keeps to the fixes a step marks safe, which never remove code an edit in flight still needs; an agent's post-edit hook runs it after each edit.

Source code in packages/workshop/src/livery/workshop/_quality.py
def fix_files(paths: tuple[str, ...], *, safe: bool = True) -> None:
    """Run the gate's fixers over *paths*, judging nothing.

    Every step whose claims reach a file fixes it, and a file no claim
    reaches is left alone. *safe* keeps to the fixes a step marks
    safe, which never remove code an edit in flight still needs; an
    agent's post-edit hook runs it after each edit.
    """
    _check_files(paths, fix=True, safe=safe, point="", judge=False)

say_skipped

say_skipped(text: str) -> None

Print a skip, and put it on the timeline as an event.

Work left undone because something already proves it is the one thing an account of a run must not show as merely fast: a gate that skipped and a gate that flew look identical from outside. The printed line is unchanged, so a log reads as it always did, and the mark is what makes the picture honest about why a leg was quick.

Marks only inside a task, since that is where a timeline exists; a plain call outside a run prints and nothing more.

Source code in packages/workshop/src/livery/workshop/_quality.py
def say_skipped(text: str) -> None:
    """Print a skip, and put it on the timeline as an event.

    Work left undone because something already proves it is the one thing
    an account of a run must not show as merely fast: a gate that skipped
    and a gate that flew look identical from outside. The printed line is
    unchanged, so a log reads as it always did, and the mark is what makes
    the picture honest about why a leg was quick.

    Marks only inside a task, since that is where a timeline exists; a
    plain call outside a run prints and nothing more.
    """
    print(f"  {text}")
    if footman.current().in_task:
        footman.mark(f"skipped: {text}")

caches_clear

caches_clear() -> None

Remove build artifacts, checker caches, and legacy root cache directories.

A step's own cache directory, .workshop/.cache/<step>/, goes whole; legacy root caches left by older checkouts (.mypy_cache, .ruff_cache, .pytest_cache, .docs-build, .cache) are cleaned alongside dist. Never touches .workshop/ whole so tracked .workshop/graphs/ stays intact.

Source code in packages/workshop/src/livery/workshop/_quality.py
@caches.task(name="clear")
def caches_clear() -> None:
    """Remove build artifacts, checker caches, and legacy root cache directories.

    A step's own cache directory, ``.workshop/.cache/<step>/``, goes
    whole; legacy root caches left by older checkouts (``.mypy_cache``,
    ``.ruff_cache``, ``.pytest_cache``, ``.docs-build``, ``.cache``) are
    cleaned alongside ``dist``. Never touches ``.workshop/`` whole so
    tracked ``.workshop/graphs/`` stays intact.
    """
    import shutil

    root = workspace_root()
    if root is None:
        return
    for name in (
        "dist",
        ".workshop/.cache",
        ".mypy_cache",
        ".ruff_cache",
        ".pytest_cache",
        ".docs-build",
        ".cache",
    ):
        shutil.rmtree(root / name, ignore_errors=True)