Skip to content

livery.workshop._graph

livery.workshop._graph

The affected engine: which packages a change can influence.

The workspace graph is the [[depends]] edges the contracts declare. A changed file maps to the package whose directory holds it, and the affected set is that package plus everything that depends on it, transitively (the dependents' closure): a change can break its consumers, never its dependencies. A change outside every package, the root configuration, the templates, the workspace tests, affects everything, because the root files configure every gate. A change can reach further than its package's dependents: a listed extension says how far through the reaches query, as python does for a module pytest loads as a plugin into every suite it runs.

fm graph.affected prints the verdict; the quality family's the reflex and the CI legs scope work to it.

Classes:

Name Description
Scope

What a change reaches: the packages, and the tests that stand for some.

Functions:

Name Description
dependents_closure

seeds (package paths) plus everything depending on them.

dependencies_closure

seeds (package paths) plus everything they depend on, transitively.

reaches_no_package

Whether path is a root file no package's steps read.

is_site

Whether path is the site's own: the root zensical.toml or docs/ tree.

is_prose

Whether path is prose: under notes/, or a markdown file anywhere.

affected_packages

The packages this branch's changes can influence, and the workspace's own tests.

affected_by

What paths, changed since before, reach among the workspace's packages.

docs_page

The package whose authored docs page path is, or None for any other path.

affected_from_paths

What a change to paths reaches: the packages, and the tests that stand alone.

graph_affected

Print the affected packages for this branch, one per line.

order_topologically

packages in release order: every dependency before its dependents.

Attributes:

Name Type Description
graph
NOTES
SITE_CONFIG
SITE_DOCS
NO_PACKAGE

graph module-attribute

graph = group('graph', help='The workspace dependency graph')

NOTES module-attribute

NOTES = 'notes/'

SITE_CONFIG module-attribute

SITE_CONFIG = 'zensical.toml'

SITE_DOCS module-attribute

SITE_DOCS = 'docs/'

NO_PACKAGE module-attribute

NO_PACKAGE = ('LICENSE', '.github/**', '.gitea/**', '.gitlab/**', '.gitlab-ci.yml', 'CODEOWNERS', 'docs/CODEOWNERS', '.vscode/**', '.claude/**', '.gitattributes', '.gitignore', 'setup.sh', '.release-manifest.json', 'overrides/**', '.workshop-rendered')

Scope dataclass

Scope(packages: tuple[Package, ...], tests: Mapping[str, tuple[str, ...]] = dict(), examples: tuple[str, ...] = ())

What a change reaches: the packages, and the tests that stand for some.

Attributes:

Name Type Description
packages tuple[Package, ...]

The packages to gate, in discovery order, the workspace's own tests unit last when its files changed.

tests Mapping[str, tuple[str, ...]]

Per package, the test files that stand for its suite; the walk names none until a better narrowing exists, so every package runs its suite whole.

examples tuple[str, ...]

The package paths whose changed files are examples and nothing else: their examples run and no suite. A package reached through its source runs both.

packages instance-attribute

packages: tuple[Package, ...]

tests class-attribute instance-attribute

tests: Mapping[str, tuple[str, ...]] = field(default_factory=dict)

examples class-attribute instance-attribute

examples: tuple[str, ...] = ()

dependents_closure

dependents_closure(packages: tuple[Package, ...], seeds: set[str]) -> tuple[Package, ...]

seeds (package paths) plus everything depending on them.

Follows the reversed [[depends]] edges to a fixed point, and answers in discovery order so output stays deterministic.

Source code in packages/workshop/src/livery/workshop/_graph.py
def dependents_closure(
    packages: tuple[Package, ...], seeds: set[str]
) -> tuple[Package, ...]:
    """*seeds* (package paths) plus everything depending on them.

    Follows the reversed ``[[depends]]`` edges to a fixed point, and
    answers in discovery order so output stays deterministic.
    """
    dependents: dict[str, set[str]] = {package.path: set() for package in packages}
    for package in packages:
        for edge in package.depends:
            dependents.setdefault(edge.path, set()).add(package.path)
    affected = set(seeds)
    frontier = list(seeds)
    while frontier:
        for consumer in dependents.get(frontier.pop(), ()):
            if consumer not in affected:
                affected.add(consumer)
                frontier.append(consumer)
    return tuple(package for package in packages if package.path in affected)

dependencies_closure

dependencies_closure(packages: tuple[Package, ...], seeds: set[str]) -> tuple[Package, ...]

seeds (package paths) plus everything they depend on, transitively.

Follows the [[depends]] edges to a fixed point, and answers in discovery order; livery.workshop.order_topologically puts each dependency before its dependents.

Source code in packages/workshop/src/livery/workshop/_graph.py
def dependencies_closure(
    packages: tuple[Package, ...], seeds: set[str]
) -> tuple[Package, ...]:
    """*seeds* (package paths) plus everything they depend on, transitively.

    Follows the ``[[depends]]`` edges to a fixed point, and answers in
    discovery order; [livery.workshop.order_topologically][]
    puts each dependency before its dependents.
    """
    by_path = {package.path: package for package in packages}
    needed = set(seeds)
    frontier = list(seeds)
    while frontier:
        package = by_path.get(frontier.pop())
        for edge in package.depends if package is not None else ():
            if edge.path not in needed:
                needed.add(edge.path)
                frontier.append(edge.path)
    return tuple(package for package in packages if package.path in needed)

reaches_no_package

reaches_no_package(path: str) -> bool

Whether path is a root file no package's steps read.

A change to one gates no package; the workspace steps that read it still judge it (livery.workshop._steps.selected).

Source code in packages/workshop/src/livery/workshop/_graph.py
def reaches_no_package(path: str) -> bool:
    """Whether *path* is a root file no package's steps read.

    A change to one gates no package; the workspace steps that read it
    still judge it ([livery.workshop._steps.selected][]).
    """
    from livery.workshop._categories import matches

    return any(matches(pattern, path) for pattern in NO_PACKAGE)

is_site

is_site(path: str) -> bool

Whether path is the site's own: the root zensical.toml or docs/ tree.

Only the site build reads them, and it runs on every run, so they reach no format, lint, type, or test gate. A package's docs/ directory is the package's, not the site's.

Source code in packages/workshop/src/livery/workshop/_graph.py
def is_site(path: str) -> bool:
    """Whether *path* is the site's own: the root ``zensical.toml`` or ``docs/`` tree.

    Only the site build reads them, and it runs on every run, so
    they reach no format, lint, type, or test gate. A package's
    ``docs/`` directory is the package's, not the site's.
    """
    return path == SITE_CONFIG or path.startswith(SITE_DOCS)

is_prose

is_prose(path: str) -> bool

Whether path is prose: under notes/, or a markdown file anywhere.

Prose reaches no format, lint, type, or test gate. The site build is where markdown is judged, and it runs on every run.

Source code in packages/workshop/src/livery/workshop/_graph.py
def is_prose(path: str) -> bool:
    """Whether *path* is prose: under ``notes/``, or a markdown file anywhere.

    Prose reaches no format, lint, type, or test gate. The site build
    is where markdown is judged, and it runs on every run.
    """
    return path.startswith(NOTES) or path.endswith(".md")

affected_packages

affected_packages(root: Path, *, base: str = 'main') -> tuple[Package, ...] | None

The packages this branch's changes can influence, and the workspace's own tests.

None means everything: a touched file outside every package (the root configuration, templates) configures every gate, so no narrowing is honest, and the file is named. Prose (is_prose) and the site's own files (is_site) affect no package wherever they live, so a diff confined to them affects nothing. A change under the workspace's own tests/ affects that unit alone, which the answer then carries as a package of its own (livery.workshop.workspace_suite): its tests reach every package, and every leg that runs a suite runs them anyway, so no package's suite has to run for it. An empty tuple means the branch changes nothing a gate reads.

Source code in packages/workshop/src/livery/workshop/_graph.py
def affected_packages(root: Path, *, base: str = "main") -> tuple[Package, ...] | None:
    """The packages this branch's changes can influence, and the workspace's own tests.

    None means everything: a touched file outside every package (the
    root configuration, templates) configures every gate, so no
    narrowing is honest, and the file is named. Prose (`is_prose`)
    and the site's own files (`is_site`) affect no package wherever
    they live, so a diff confined to them affects nothing. A change
    under the workspace's own ``tests/`` affects that unit alone,
    which the answer then carries as a package of its own
    ([livery.workshop.workspace_suite][]): its tests
    reach every package, and every leg that runs a suite runs them
    anyway, so no package's suite has to run for it. An empty tuple
    means the branch changes nothing a gate reads.
    """
    scope = affected_by(
        root,
        git.changed_paths(root, base),
        # Asked only for a change outside every package, or one inside a
        # package the listed extensions are asked about.
        before=lambda: git.merge_base(root, base),
    )
    return None if scope is None else scope.packages

affected_by

affected_by(root: Path, paths: Iterable[str], *, before: str | Callable[[], str]) -> Scope | None

What paths, changed since before, reach among the workspace's packages.

affected_from_paths over the packages discovered under root. None means everything.

Source code in packages/workshop/src/livery/workshop/_graph.py
def affected_by(
    root: Path, paths: Iterable[str], *, before: str | Callable[[], str]
) -> Scope | None:
    """What *paths*, changed since *before*, reach among the workspace's packages.

    `affected_from_paths` over the packages discovered under *root*.
    ``None`` means everything.
    """
    packages = discover_packages(root)
    return affected_from_paths(root, packages, paths, before=before)

docs_page

docs_page(packages: tuple[Package, ...], path: str) -> Package | None

The package whose authored docs page path is, or None for any other path.

Source code in packages/workshop/src/livery/workshop/_graph.py
def docs_page(packages: tuple[Package, ...], path: str) -> Package | None:
    """The package whose authored docs page *path* is, or None for any other path."""
    if not path.endswith(".md") or "/_generated/" in path:
        return None
    for package in packages:
        if path.startswith(package.path + "/docs/"):
            return package
    return None

affected_from_paths

affected_from_paths(root: Path, packages: tuple[Package, ...], paths: Iterable[str], *, before: str | Callable[[], str] = '') -> Scope | None

What a change to paths reaches: the packages, and the tests that stand alone.

The classification affected_packages applies to a branch's changes, for any set of paths: the reflex hands it the paths between a proved tree and the working tree. Each path is classified by its package's kind: a test file reaches its own package alone, since nothing imports a test, and that package runs its whole suite; source, test support, and configuration reach the package's dependents and run the suites. A change under the workspace's own tests runs that unit whole. A docs page reaches nothing: the site build reads it. An example file reaches its package's examples step and no suite, unless source of the package changed too. A file outside every package reaches everything, unless before (the commit or tree the paths were taken from) shows the change is about the packages added or removed, or, for uv.lock, about the members whose resolution it moves (livery.workshop._root_attribution): then it reaches those. A change inside a package reaches further when a listed extension says so: each answer to the reaches query is called with the change, and every member it names for a changed path runs with its dependents (_reached). before may be a function answering it, asked once, and only when a path outside every package or an answer to reaches needs it. None means everything, an empty scope nothing a gate reads.

Source code in packages/workshop/src/livery/workshop/_graph.py
def affected_from_paths(
    root: Path,
    packages: tuple[Package, ...],
    paths: Iterable[str],
    *,
    before: str | Callable[[], str] = "",
) -> Scope | None:
    """What a change to *paths* reaches: the packages, and the tests that stand alone.

    The classification `affected_packages` applies to a branch's
    changes, for any set of paths: the reflex hands it the paths
    between a proved tree and the working tree. Each path is
    classified by its package's kind: a test file reaches its own
    package alone, since nothing imports a test, and that package
    runs its whole suite; source, test support, and configuration
    reach the package's dependents and run the suites. A change under
    the workspace's own tests runs that unit whole. A docs page
    reaches nothing: the site build reads it. An example file reaches
    its package's examples step
    and no suite, unless source of the package changed too. A file
    outside every package reaches everything, unless *before* (the
    commit or tree the paths were taken from) shows the change is
    about the packages added or removed, or, for ``uv.lock``, about
    the members whose resolution it moves
    ([livery.workshop._root_attribution][]): then it reaches those.
    A change inside a package reaches further when a listed extension
    says so: each answer to the ``reaches`` query is called with the
    change, and every member it names for a changed path runs with
    its dependents (`_reached`).
    *before* may be a function answering it, asked once, and only
    when a path outside every package or an answer to ``reaches``
    needs it.
    ``None`` means everything, an empty scope nothing a gate reads.
    """
    from livery.workshop._categories import EXAMPLE, TEST, category_of
    from livery.workshop._packages import WORKSPACE_TESTS, workspace_suite

    paths = tuple(paths)
    if not isinstance(before, str):
        before = functools.cache(before)
    seeds: set[str] = set()
    # A package whose test files changed runs its whole suite; nothing
    # imports a test, so its dependents' suites do not run. The suite
    # is not narrowed to the changed files until a better narrowing
    # exists: the tests a change reaches are more than the ones it edits.
    suites: set[str] = set()
    examples: set[str] = set()
    tests_changed = False
    inside = False
    outside: list[str] = []
    for path in paths:
        if docs_page(packages, path) is not None:
            continue
        if is_prose(path) or is_site(path) or reaches_no_package(path):
            continue
        if path.startswith(WORKSPACE_TESTS + "/"):
            tests_changed = True
            continue
        for package in packages:
            if path.startswith(package.path + "/"):
                inside = True
                relative = path[len(package.path) + 1 :]
                category = category_of(package, relative).name
                if category == EXAMPLE:
                    examples.add(package.path)
                elif category == TEST:
                    suites.add(package.path)
                else:
                    seeds.add(package.path)
                break
        else:
            outside.append(path)
    if outside:
        attributed = _attribute(root, packages, outside, before=before)
        if attributed is None:
            return None
        seeds |= attributed
    if inside:
        widened = _reached(root, packages, paths, before=before)
        if widened is None:
            return None
        seeds |= widened
    reached = {package.path for package in dependents_closure(packages, seeds)}
    alone = tuple(
        sorted(path for path in examples if path not in reached and path not in suites)
    )
    members = tuple(
        package
        for package in packages
        if package.path in reached or package.path in suites or package.path in alone
    )
    if not tests_changed:
        return Scope(members, {}, alone)
    unit = workspace_suite(root)
    if unit is None:
        print(f"  {WORKSPACE_TESTS}/: changed and gone; everything runs")
        return None
    return Scope((*members, unit), {}, alone)

graph_affected

graph_affected(base: str = 'main') -> None

Print the affected packages for this branch, one per line.

Parameters:

Name Type Description Default
base str

the branch the change will merge into

'main'
Source code in packages/workshop/src/livery/workshop/_graph.py
@graph.task(name="affected")
def graph_affected(base: str = "main") -> None:
    """Print the affected packages for this branch, one per line.

    Args:
        base: the branch the change will merge into
    """
    from livery.workshop._extensions import workspace_root

    root = workspace_root()
    if root is None:
        print("  no workspace: no workshop.toml above the working directory")
        return
    git.fetch(root)
    affected = affected_packages(root, base=base)
    if affected is None:
        print("  everything: a change outside the packages configures every gate")
        return
    if not affected:
        print("  nothing: the branch changes no files")
        return
    for package in affected:
        print(f"  {package.path} ({package.name})")

order_topologically

order_topologically(packages: tuple[Package, ...]) -> tuple[Package, ...]

packages in release order: every dependency before its dependents.

Kahn's walk over the [[depends]] edges restricted to the given set; ties keep the input order so the result is deterministic. A cycle cannot arise, the layering lint refuses one long before a release asks.

Source code in packages/workshop/src/livery/workshop/_graph.py
def order_topologically(packages: tuple[Package, ...]) -> tuple[Package, ...]:
    """*packages* in release order: every dependency before its dependents.

    Kahn's walk over the ``[[depends]]`` edges restricted to the given
    set; ties keep the input order so the result is deterministic. A
    cycle cannot arise, the layering lint refuses one long before a
    release asks.
    """
    chosen = {p.path for p in packages}
    remaining = list(packages)
    ordered: list[Package] = []
    placed: set[str] = set()
    while remaining:
        for index, package in enumerate(remaining):
            needs = {
                edge.path
                for edge in package.depends
                if edge.path in chosen and edge.path not in placed
            }
            if not needs:
                ordered.append(package)
                placed.add(package.path)
                del remaining[index]
                break
        else:  # pragma: no cover - guarded by the layering lint
            ordered.extend(remaining)
            break
    return tuple(ordered)