Skip to content

livery.workshop._proved

livery.workshop._proved

The proved record: per-unit step verdicts written beside today's records.

A unit is one thing that gives a verdict: a step over one package (lint.ruff@packages/workshop), or a workspace step over the root (drift.check@.). Each CI check leg writes its unit rows under the keyed family proved/<base>/<leg> in the state store (livery.git), one file per unit holding the newest KEEP_READ_SETS distinct fingerprints seen for that unit on that platform.

A row records the unit, the platform (OS, runner image version, Python version), the verdict (green, red, skipped or unfinished), how many times each verdict was seen under the same fingerprint (so two verdicts under one fingerprint mark the unit flaky), the run metadata, and the fingerprint of what the step read (its matched files, pinned tool versions, and declared options).

Concurrent writers targeting the same ref (such as shards of one platform leg) combine through compare-and-swap with merge_unit_files, so both writers land and per-fingerprint verdict counts accumulate instead of clobbering one another.

Classes:

Name Description
Platform

The execution platform recorded on every proved row.

ItemReadSet

What one test item read while executing, language-agnostic.

ReadSetEntry

One fingerprint's verdict history on a unit row.

UnitRow

One unit's stored row on a proved ref, holding its newest read-sets.

Observation

One unit outcome observed during a gate walk, ready to record.

ShadowDiff

One disagreement between today's decision and the proved record.

ShadowReport

Result of comparing today's gate decision with the proved record.

UnitDecision

Gate decision computed from the proved record for a set of candidate units.

ItemSelection

Shadow (or live) selection verdict for a set of test items.

RanItems

What per-item test execution ran and skipped during one check leg.

Escape

One test item proved green by its row that failed during a scheduled audit.

FingerprintContext

Shared per-walk cache for computing step unit fingerprints quickly.

ProvedTree

Record that a git tree hash was proved green across a set of check legs.

Functions:

Name Description
current_platform

The platform of the current process, including runner image when reported.

read_set_blob_name

Content-addressed blob path on a proved ref for read-set digest.

dir_listing_digest

SHA-256 of sorted direct entry names under root / relative.

item_read_set_matches

Whether read_set still matches root on disk, and the first mismatch.

unit_id

Canonical unit identifier for step over target.

row_name

Stable ref-safe filename for one unit's row file on a proved ref.

current_keys

The keys the world produces: main and every branch on origin, per check leg.

current_parts_keys

Active (extension, base, leg) keys for the proved-parts family.

proved_parts_series

Return the proved-parts series for extension, base, and leg.

proved_parts_prefixes

Return ref prefixes to fetch extension's proved parts for bases.

put_proved_part

Store an opaque payload for extension under unit and row_key.

read_proved_part

Read an opaque payload stored by put_proved_part for unit at row_key.

leg_base

The proved-record base key (main or branch slug) for run.

leg_key

The platform leg key for run, stripping any shard suffix.

merge_unit_files

Combine existing and incoming proved unit files for CAS retry.

write_observations

Write observations to the proved store; "" or the failure reason.

spool_proved_observations

Merge observations into LEG_SPOOL / PROVED_SHARDED_FILE for gate flush.

record_item_observations

Write per-item verdicts and read-sets for step to the proved store.

item_read_details

Find proved rows and decoded read-sets for item across proved refs.

read_unit_rows

Read all proved unit rows from one series; (rows, reason).

flaky_units

Every flagged flaky entry (green and red under one fingerprint) across refs.

rows_for_run

All (base, leg, unit_row, entry) records written by run_id.

is_proved_unit

Whether row proves fingerprint on platform, and the reason.

is_proved_from_rows

Whether candidate rows for one unit prove fingerprint on platform.

lookup_proved_rows

Load candidate proved unit rows for run (CI) or offline mirror (desk).

lookup_proved_rows_for_decision

Load primary proved rows plus lingering branch rows for a main CI run.

decide_units

Decide which candidate_units are proved green and which must run.

copy_branch_rows_to_main

Copy matched branch unit rows and item read-sets onto proved/main/<leg>.

evaluate_shadow

Compare today_running against what rows_by_unit would skip.

write_shadow_report

Record one CI leg's shadow comparison on proved/differences.

read_shadow_differences

Read shadow comparison rows newest first: (total_runs, non_empty, reason).

without_item_selection

Temporarily disable live per-item selection in this process.

item_selection_disabled

Whether live per-item selection is disabled by context or environment.

clear_ran_items

Remove any prior check leg's per-item execution record under root.

read_ran_items

Read the per-item execution record under root; empty when absent.

record_ran_items

Merge ran, skipped, and narrowed into root's ran-items file.

lookup_proved_item_rows

Load candidate proved rows and decoded read-set blobs for target_units.

is_item_proved

Whether candidates prove a test item on root and platform.

shadow_select_items

Compute which items existing proved rows would select or skip.

record_selection_measure

Record one selected share measure row in MEASURES for a CI leg.

read_measures

Read measure rows newest first from MEASURES.

detect_item_escapes

Return Escape rows for any red_items that selection marked proved.

record_escapes

Write escapes to ESCAPES (CI) or LOCAL_ESCAPES (desk/local).

read_escapes

Read recorded escapes newest first from ESCAPES and LOCAL_ESCAPES.

active_escaped_packages

Packages put back to whole runs due to an unaddressed recorded escape.

step_fingerprint

Deterministic SHA-256 fingerprint of what record reads on target.

proving_branch

Return (branch, reason) for the pull request branch proving root's tree.

proved_unit_key

Return the proved row key for target's registered steps in phase.

proved_unit_keys

Return a target -> proved row key mapping for targets in phase.

base_proved

Whether proved/main/* already has green rows for origin/<base>'s tip.

head_tree_id

Return the git tree object id of HEAD:, or "" on error.

tree_row_name

Stable row filename on TREES for git tree hash tree_id.

read_proved_tree

Look up a green ProvedTree stamp for tree_id; (None, "") if absent.

stamp_proved_tree

Record tree_id as proved green across legs on TREES; "" or reason.

sweep_proved_store

Prune unreferenced reads/ blobs and expired proved-parts kept rows.

promote_proved_tree_to_main

Promote branch proved rows and extension proved-parts to main.

Attributes:

Name Type Description
SCHEMA
KEEP_READ_SETS
MAIN
GREEN
RED
SKIPPED
UNFINISHED
VERDICTS tuple[str, ...]
READS_PREFIX
PROVED_SHARDED_FILE
PARTS_SCHEMA
PARTS_BLOBS_PREFIX
PROVED_PARTS Keyed
FAMILY Keyed
LOCAL Series
SHADOW_DIFFS Series
MEASURES Series
ESCAPES Series
TREES Series
LOCAL_ESCAPES Series
MAIN_PREFIX
RAN_ITEMS_FILE
NO_SELECT_VARIABLE
PARTS_KEPT_FOR

SCHEMA module-attribute

SCHEMA = 1

KEEP_READ_SETS module-attribute

KEEP_READ_SETS = 3

MAIN module-attribute

MAIN = 'main'

GREEN module-attribute

GREEN = 'green'

RED module-attribute

RED = 'red'

SKIPPED module-attribute

SKIPPED = 'skipped'

UNFINISHED module-attribute

UNFINISHED = 'unfinished'

VERDICTS module-attribute

VERDICTS: tuple[str, ...] = (GREEN, RED, SKIPPED, UNFINISHED)

READS_PREFIX module-attribute

READS_PREFIX = 'reads/'

PROVED_SHARDED_FILE module-attribute

PROVED_SHARDED_FILE = 'proved-sharded.json'

PARTS_SCHEMA module-attribute

PARTS_SCHEMA = 1

PARTS_BLOBS_PREFIX module-attribute

PARTS_BLOBS_PREFIX = 'blobs/'

PROVED_PARTS module-attribute

PROVED_PARTS: Keyed = git.Keyed('proved-parts', ('extension', 'base', 'leg'), schema=PARTS_SCHEMA, current=current_parts_keys, linger=timedelta(days=1), blobs=PARTS_BLOBS_PREFIX)

FAMILY module-attribute

FAMILY: Keyed = git.Keyed('proved', ('base', 'leg'), schema=SCHEMA, current=current_keys, linger=timedelta(days=1), blobs=READS_PREFIX)

LOCAL module-attribute

LOCAL: Series = git.Series('proved-local', window=None, ci_only=False, local=True, schema=SCHEMA, blobs=READS_PREFIX)

SHADOW_DIFFS module-attribute

SHADOW_DIFFS: Series = git.Series('proved/differences', window=400, schema=SCHEMA)

MEASURES module-attribute

MEASURES: Series = git.Series('measures', window=400, schema=SCHEMA)

ESCAPES module-attribute

ESCAPES: Series = git.Series('proved/escapes', window=400, schema=SCHEMA)

TREES module-attribute

TREES: Series = git.Series('proved/trees', window=600, schema=SCHEMA)

LOCAL_ESCAPES module-attribute

LOCAL_ESCAPES: Series = git.Series('proved-escapes-local', window=200, ci_only=False, local=True, schema=SCHEMA)

MAIN_PREFIX module-attribute

MAIN_PREFIX = f'{FAMILY.name}/{MAIN}/'

RAN_ITEMS_FILE module-attribute

RAN_ITEMS_FILE = '.workshop/ran-items.json'

NO_SELECT_VARIABLE module-attribute

NO_SELECT_VARIABLE = 'WORKSHOP_PROVED_NO_SELECT'

PARTS_KEPT_FOR module-attribute

PARTS_KEPT_FOR = timedelta(days=1)

Platform dataclass

Platform(os: str, image: str, python: str)

The execution platform recorded on every proved row.

Attributes:

Name Type Description
os str

Runner or host OS label (e.g. ubuntu-latest or darwin).

image str

Runner image identifier and version when reported by CI, or the host OS release outside CI.

python str

Exact Python interpreter version (major.minor.micro).

Methods:

Name Description
matches

Whether self proves work for other.

to_dict

Serialize as a JSON-compatible dictionary.

from_dict

Deserialize from a row's platform mapping.

os instance-attribute

os: str

image instance-attribute

image: str

python instance-attribute

python: str

os_family property

os_family: str

Normalized OS family (linux, macos, windows, or raw lower).

python_minor property

python_minor: str

Major.minor interpreter version (e.g. 3.14 from 3.14.6).

matches

matches(other: Platform, *, exact_image: bool) -> bool

Whether self proves work for other.

CI requires an exact OS family, runner image, and exact interpreter version; a desk reading CI's mirrored rows matches OS family and major.minor interpreter version.

Source code in packages/workshop/src/livery/workshop/_proved.py
def matches(self, other: Platform, *, exact_image: bool) -> bool:
    """Whether *self* proves work for *other*.

    CI requires an exact OS family, runner image, and exact interpreter
    version; a desk reading CI's mirrored rows matches OS family and
    major.minor interpreter version.
    """
    if self.os_family != other.os_family:
        return False
    if exact_image:
        return self.image == other.image and self.python == other.python
    return self.python_minor == other.python_minor

to_dict

to_dict() -> dict[str, str]

Serialize as a JSON-compatible dictionary.

Source code in packages/workshop/src/livery/workshop/_proved.py
def to_dict(self) -> dict[str, str]:
    """Serialize as a JSON-compatible dictionary."""
    return {"image": self.image, "os": self.os, "python": self.python}

from_dict classmethod

from_dict(data: Mapping[str, Any]) -> Platform

Deserialize from a row's platform mapping.

Source code in packages/workshop/src/livery/workshop/_proved.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> Platform:
    """Deserialize from a row's ``platform`` mapping."""
    return cls(
        os=str(data.get("os", "")),
        image=str(data.get("image", "")),
        python=str(data.get("python", "")),
    )

ItemReadSet dataclass

ItemReadSet(files: Mapping[str, str], absent: tuple[str, ...] = (), dirs: Mapping[str, str] = dict(), dists: Mapping[str, str] = dict(), native_tools: tuple[str, ...] = (), unrecorded: bool = False)

What one test item read while executing, language-agnostic.

Attributes:

Name Type Description
files Mapping[str, str]

Repository-relative paths opened or imported, mapped to their SHA-256 hex digest at observation time.

absent tuple[str, ...]

Sorted repository-relative paths opened or checked that did not exist at observation time; creating one invalidates the item.

dirs Mapping[str, str]

Repository-relative directories listed during execution, mapped to the SHA-256 digest of their sorted direct child names.

dists Mapping[str, str]

Third-party distributions imported during execution, mapped to their installed version string.

native_tools tuple[str, ...]

Sorted basenames of non-Python executables spawned while the item ran.

unrecorded bool

True when a child process lost the observer hook, so the recorded reads cannot prove the item on their own.

Methods:

Name Description
to_dict

Serialize as a canonical JSON-compatible dictionary.

from_dict

Deserialize from a reads/<digest>.json blob payload.

fingerprint

Deterministic SHA-256 hex digest of this read-set.

files instance-attribute

files: Mapping[str, str]

absent class-attribute instance-attribute

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

dirs class-attribute instance-attribute

dirs: Mapping[str, str] = field(default_factory=dict)

dists class-attribute instance-attribute

dists: Mapping[str, str] = field(default_factory=dict)

native_tools class-attribute instance-attribute

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

unrecorded class-attribute instance-attribute

unrecorded: bool = False

to_dict

to_dict() -> dict[str, Any]

Serialize as a canonical JSON-compatible dictionary.

Source code in packages/workshop/src/livery/workshop/_proved.py
def to_dict(self) -> dict[str, Any]:
    """Serialize as a canonical JSON-compatible dictionary."""
    return {
        "absent": sorted(self.absent),
        "dirs": dict(sorted(self.dirs.items())),
        "dists": dict(sorted(self.dists.items())),
        "files": dict(sorted(self.files.items())),
        "native-tools": sorted(self.native_tools),
        "unrecorded": self.unrecorded,
    }

from_dict classmethod

from_dict(data: Mapping[str, Any]) -> ItemReadSet

Deserialize from a reads/<digest>.json blob payload.

Source code in packages/workshop/src/livery/workshop/_proved.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ItemReadSet:
    """Deserialize from a ``reads/<digest>.json`` blob payload."""
    raw_files = data.get("files")
    raw_dirs = data.get("dirs")
    raw_dists = data.get("dists")
    raw_absent = data.get("absent")
    raw_tools = data.get("native-tools")
    return cls(
        files={str(k): str(v) for k, v in raw_files.items()}
        if isinstance(raw_files, Mapping)
        else {},
        absent=tuple(sorted(str(item) for item in raw_absent))
        if isinstance(raw_absent, list)
        else (),
        dirs={str(k): str(v) for k, v in raw_dirs.items()}
        if isinstance(raw_dirs, Mapping)
        else {},
        dists={str(k): str(v) for k, v in raw_dists.items()}
        if isinstance(raw_dists, Mapping)
        else {},
        native_tools=tuple(sorted(str(item) for item in raw_tools))
        if isinstance(raw_tools, list)
        else (),
        unrecorded=bool(data.get("unrecorded", False)),
    )

fingerprint

fingerprint() -> str

Deterministic SHA-256 hex digest of this read-set.

Source code in packages/workshop/src/livery/workshop/_proved.py
def fingerprint(self) -> str:
    """Deterministic SHA-256 hex digest of this read-set."""
    canonical = json.dumps(self.to_dict(), sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()

ReadSetEntry dataclass

ReadSetEntry(fingerprint: str, verdict: str, counts: Mapping[str, int], run: str = '', sha: str = '', branch: str = '', attempt: str = '', trigger: str = '', when: str = '', platform: Platform | None = None, read_set: str = '')

One fingerprint's verdict history on a unit row.

Attributes:

Name Type Description
fingerprint str

SHA-256 hex digest of what the unit read.

verdict str

Latest verdict observed for this fingerprint.

counts Mapping[str, int]

Cumulative counts per verdict in VERDICTS.

run str

Forge run identifier that last wrote this entry.

sha str

Commit SHA of the run.

branch str

Branch name of the run.

attempt str

Run attempt string (empty when unreported).

trigger str

CI point / trigger name (e.g. gate, nightly).

when str

ISO 8601 UTC timestamp of the observation.

Methods:

Name Description
to_dict

Serialize as a JSON-compatible dictionary.

from_dict

Deserialize one entry from a unit row's entries list.

fingerprint instance-attribute

fingerprint: str

verdict instance-attribute

verdict: str

counts instance-attribute

counts: Mapping[str, int]

run class-attribute instance-attribute

run: str = ''

sha class-attribute instance-attribute

sha: str = ''

branch class-attribute instance-attribute

branch: str = ''

attempt class-attribute instance-attribute

attempt: str = ''

trigger class-attribute instance-attribute

trigger: str = ''

when class-attribute instance-attribute

when: str = ''

platform class-attribute instance-attribute

platform: Platform | None = None

read_set class-attribute instance-attribute

read_set: str = ''

flaky property

flaky: bool

Whether both green and red verdicts were observed for this read-set.

to_dict

to_dict() -> dict[str, Any]

Serialize as a JSON-compatible dictionary.

Source code in packages/workshop/src/livery/workshop/_proved.py
def to_dict(self) -> dict[str, Any]:
    """Serialize as a JSON-compatible dictionary."""
    out: dict[str, Any] = {
        "attempt": self.attempt,
        "branch": self.branch,
        "counts": {v: self.counts.get(v, 0) for v in VERDICTS},
        "fingerprint": self.fingerprint,
        "run": self.run,
        "sha": self.sha,
        "trigger": self.trigger,
        "verdict": self.verdict,
        "when": self.when,
    }
    if self.platform is not None:
        out["platform"] = self.platform.to_dict()
    if self.read_set:
        out["read-set"] = self.read_set
    return out

from_dict classmethod

from_dict(data: Mapping[str, Any], *, default_platform: Platform | None = None) -> ReadSetEntry

Deserialize one entry from a unit row's entries list.

Source code in packages/workshop/src/livery/workshop/_proved.py
@classmethod
def from_dict(
    cls, data: Mapping[str, Any], *, default_platform: Platform | None = None
) -> ReadSetEntry:
    """Deserialize one entry from a unit row's ``entries`` list."""
    raw_counts = data.get("counts")
    counts = {
        v: int(raw_counts.get(v, 0)) if isinstance(raw_counts, dict) else 0
        for v in VERDICTS
    }
    raw_plat = data.get("platform")
    plat = (
        Platform.from_dict(raw_plat)
        if isinstance(raw_plat, Mapping)
        else default_platform
    )
    return cls(
        fingerprint=str(data.get("fingerprint", "")),
        verdict=str(data.get("verdict", "")),
        counts=counts,
        run=str(data.get("run", "")),
        sha=str(data.get("sha", "")),
        branch=str(data.get("branch", "")),
        attempt=str(data.get("attempt", "")),
        trigger=str(data.get("trigger", "")),
        when=str(data.get("when", "")),
        platform=plat,
        read_set=str(data.get("read-set", "")),
    )

UnitRow dataclass

UnitRow(unit: str, step: str, target: str, platform: Platform, entries: tuple[ReadSetEntry, ...])

One unit's stored row on a proved ref, holding its newest read-sets.

Attributes:

Name Type Description
unit str

Canonical unit identifier (<step>@<target>).

step str

Step name (lint.ruff, drift.check).

target str

Target unit path (. for workspace, or package path).

platform Platform

Execution platform that produced the row.

entries tuple[ReadSetEntry, ...]

Newest distinct read-set entries, newest first.

Methods:

Name Description
to_dict

Serialize as a JSON-compatible dictionary (without store stamp).

from_dict

Deserialize from a store row's data mapping.

unit instance-attribute

unit: str

step instance-attribute

step: str

target instance-attribute

target: str

platform instance-attribute

platform: Platform

entries instance-attribute

entries: tuple[ReadSetEntry, ...]

latest property

latest: ReadSetEntry | None

The most recent read-set entry, or None if empty.

to_dict

to_dict() -> dict[str, Any]

Serialize as a JSON-compatible dictionary (without store stamp).

Source code in packages/workshop/src/livery/workshop/_proved.py
def to_dict(self) -> dict[str, Any]:
    """Serialize as a JSON-compatible dictionary (without store stamp)."""
    return {
        "entries": [entry.to_dict() for entry in self.entries],
        "platform": self.platform.to_dict(),
        "step": self.step,
        "target": self.target,
        "unit": self.unit,
    }

from_dict classmethod

from_dict(data: Mapping[str, Any]) -> UnitRow

Deserialize from a store row's data mapping.

Source code in packages/workshop/src/livery/workshop/_proved.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> UnitRow:
    """Deserialize from a store row's data mapping."""
    raw_platform = data.get("platform")
    plat = (
        Platform.from_dict(raw_platform)
        if isinstance(raw_platform, Mapping)
        else Platform("", "", "")
    )
    raw_entries = data.get("entries")
    entries = (
        tuple(
            ReadSetEntry.from_dict(item, default_platform=plat)
            for item in raw_entries
            if isinstance(item, Mapping)
        )
        if isinstance(raw_entries, list)
        else ()
    )
    return cls(
        unit=str(data.get("unit", "")),
        step=str(data.get("step", "")),
        target=str(data.get("target", "")),
        platform=plat,
        entries=entries,
    )

Observation dataclass

Observation(step: str, target: str, verdict: str, fingerprint: str, platform: Platform, run: str = '', sha: str = '', branch: str = '', attempt: str = '', trigger: str = '', when: str = '', read_set: ItemReadSet | None = None)

One unit outcome observed during a gate walk, ready to record.

Attributes:

Name Type Description
step str

Registered step name (lint.ruff, drift.check).

target str

Package path (packages/workshop) or "." for workspace.

verdict str

One of VERDICTS (green, red, skipped, unfinished).

fingerprint str

SHA-256 hex digest of the step unit's inputs.

platform Platform

Platform that ran (or skipped) the unit.

run str

Forge run id (empty locally).

sha str

Commit SHA of the run.

branch str

Branch name of the run.

attempt str

Run attempt string.

trigger str

CI point / trigger name.

when str

ISO 8601 UTC timestamp (stamped now when omitted).

Methods:

Name Description
__post_init__
to_dict

Serialize this observation (including any item read-set) for spooling.

from_dict

Deserialize a spooled observation written by to_dict.

step instance-attribute

step: str

target instance-attribute

target: str

verdict instance-attribute

verdict: str

fingerprint instance-attribute

fingerprint: str

platform instance-attribute

platform: Platform

run class-attribute instance-attribute

run: str = ''

sha class-attribute instance-attribute

sha: str = ''

branch class-attribute instance-attribute

branch: str = ''

attempt class-attribute instance-attribute

attempt: str = ''

trigger class-attribute instance-attribute

trigger: str = ''

when class-attribute instance-attribute

when: str = ''

read_set class-attribute instance-attribute

read_set: ItemReadSet | None = None

__post_init__

__post_init__() -> None
Source code in packages/workshop/src/livery/workshop/_proved.py
def __post_init__(self) -> None:
    if self.verdict not in VERDICTS:
        raise ValueError(
            f"verdict {self.verdict!r} is not one of {', '.join(VERDICTS)}"
        )

to_dict

to_dict() -> dict[str, Any]

Serialize this observation (including any item read-set) for spooling.

Source code in packages/workshop/src/livery/workshop/_proved.py
def to_dict(self) -> dict[str, Any]:
    """Serialize this observation (including any item read-set) for spooling."""
    out: dict[str, Any] = {
        "step": self.step,
        "target": self.target,
        "verdict": self.verdict,
        "fingerprint": self.fingerprint,
        "platform": self.platform.to_dict(),
        "run": self.run,
        "sha": self.sha,
        "branch": self.branch,
        "attempt": self.attempt,
        "trigger": self.trigger,
        "when": self.when,
    }
    if self.read_set is not None:
        out["read_set"] = self.read_set.to_dict()
    return out

from_dict classmethod

from_dict(data: Mapping[str, Any]) -> Observation

Deserialize a spooled observation written by to_dict.

Source code in packages/workshop/src/livery/workshop/_proved.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> Observation:
    """Deserialize a spooled observation written by `to_dict`."""
    raw_plat = data.get("platform")
    plat = (
        Platform.from_dict(raw_plat)
        if isinstance(raw_plat, Mapping)
        else Platform(os="", image="", python="")
    )
    raw_rs = data.get("read_set")
    read_set = (
        ItemReadSet.from_dict(raw_rs) if isinstance(raw_rs, Mapping) else None
    )
    return cls(
        step=str(data.get("step", "")),
        target=str(data.get("target", "")),
        verdict=str(data.get("verdict", "")),
        fingerprint=str(data.get("fingerprint", "")),
        platform=plat,
        run=str(data.get("run", "")),
        sha=str(data.get("sha", "")),
        branch=str(data.get("branch", "")),
        attempt=str(data.get("attempt", "")),
        trigger=str(data.get("trigger", "")),
        when=str(data.get("when", "")),
        read_set=read_set,
    )

ShadowDiff dataclass

ShadowDiff(unit: str, today: str, proved: str, reason: str)

One disagreement between today's decision and the proved record.

Attributes:

Name Type Description
unit str

Canonical unit identifier (<step>@<target>).

today str

Today's decision for this unit (run or skip).

proved str

What the proved record would decide (run or skip).

reason str

Why the proved record made its decision.

Methods:

Name Description
to_dict

Serialize as a JSON-compatible dictionary.

from_dict

Deserialize one difference entry.

unit instance-attribute

unit: str

today instance-attribute

today: str

proved instance-attribute

proved: str

reason instance-attribute

reason: str

to_dict

to_dict() -> dict[str, str]

Serialize as a JSON-compatible dictionary.

Source code in packages/workshop/src/livery/workshop/_proved.py
def to_dict(self) -> dict[str, str]:
    """Serialize as a JSON-compatible dictionary."""
    return {
        "proved": self.proved,
        "reason": self.reason,
        "today": self.today,
        "unit": self.unit,
    }

from_dict classmethod

from_dict(data: Mapping[str, Any]) -> ShadowDiff

Deserialize one difference entry.

Source code in packages/workshop/src/livery/workshop/_proved.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> ShadowDiff:
    """Deserialize one difference entry."""
    return cls(
        unit=str(data.get("unit", "")),
        today=str(data.get("today", "")),
        proved=str(data.get("proved", "")),
        reason=str(data.get("reason", "")),
    )

ShadowReport dataclass

ShadowReport(checked: int, would_skip: int, today_skip: int, differences: tuple[ShadowDiff, ...])

Result of comparing today's gate decision with the proved record.

Methods:

Name Description
format_lines

Concise human-readable lines for gate logs.

Attributes:

Name Type Description
checked int
would_skip int
today_skip int
differences tuple[ShadowDiff, ...]

checked instance-attribute

checked: int

would_skip instance-attribute

would_skip: int

today_skip instance-attribute

today_skip: int

differences instance-attribute

differences: tuple[ShadowDiff, ...]

format_lines

format_lines(*, max_items: int = 20) -> list[str]

Concise human-readable lines for gate logs.

Source code in packages/workshop/src/livery/workshop/_proved.py
def format_lines(self, *, max_items: int = 20) -> list[str]:
    """Concise human-readable lines for gate logs."""
    if not self.differences:
        return [
            f"  proved (shadow): agrees with today"
            f" ({self.checked} unit(s), {self.would_skip} would skip)"
        ]
    lines = [
        f"  proved (shadow): {len(self.differences)} difference(s)"
        f" across {self.checked} unit(s)"
        f" (today skips {self.today_skip}, proved skips {self.would_skip})"
    ]
    for diff in self.differences[:max_items]:
        lines.append(
            f"    {diff.unit}: today={diff.today},"
            f" proved={diff.proved} ({diff.reason})"
        )
    extra = len(self.differences) - max_items
    if extra > 0:
        lines.append(f"    ... and {extra} more")
    return lines

UnitDecision dataclass

UnitDecision(proved: frozenset[str], running: tuple[tuple[StepRecord, str, str], ...], copied: tuple[Observation, ...] = (), matched_branches: tuple[str, ...] = ())

Gate decision computed from the proved record for a set of candidate units.

Attributes:

Name Type Description
proved frozenset[str]

Canonical unit ids proved green and skipped.

running tuple[tuple[StepRecord, str, str], ...]

(record, target, reason) tuples for units that must run.

copied tuple[Observation, ...]

Observations matched on lingering branch refs during a main run, ready to copy onto proved/main/<leg>.

matched_branches tuple[str, ...]

Sorted branch base keys whose rows supplied copied.

proved instance-attribute

proved: frozenset[str]

running instance-attribute

running: tuple[tuple[StepRecord, str, str], ...]

copied class-attribute instance-attribute

copied: tuple[Observation, ...] = ()

matched_branches class-attribute instance-attribute

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

ItemSelection dataclass

ItemSelection(selected: tuple[str, ...], skipped: tuple[str, ...], reasons: Mapping[str, str], fingerprints: Mapping[str, str] = dict())

Shadow (or live) selection verdict for a set of test items.

Attributes:

Name Type Description
selected tuple[str, ...]

Repository-relative test items that would run.

skipped tuple[str, ...]

Repository-relative test items proved by existing rows.

reasons Mapping[str, str]

Per-item explanation ("proved" for skipped items, or the first mismatch / refusal reason for selected items).

fingerprints Mapping[str, str]

Matched proved row fingerprint for each skipped item.

selected instance-attribute

selected: tuple[str, ...]

skipped instance-attribute

skipped: tuple[str, ...]

reasons instance-attribute

reasons: Mapping[str, str]

fingerprints class-attribute instance-attribute

fingerprints: Mapping[str, str] = field(default_factory=dict)

RanItems dataclass

RanItems(ran: Mapping[str, str] = dict(), skipped: Mapping[str, str] = dict(), narrowed: bool = False)

What per-item test execution ran and skipped during one check leg.

Attributes:

Name Type Description
ran Mapping[str, str]

Executed test item path to its recorded read-set fingerprint (empty string when the item collected no tests).

skipped Mapping[str, str]

Live-skipped (or carried) test item path to its matched proved read-set fingerprint.

narrowed bool

Whether live per-item selection skipped at least one test item during the gate run.

ran class-attribute instance-attribute

ran: Mapping[str, str] = field(default_factory=dict)

skipped class-attribute instance-attribute

skipped: Mapping[str, str] = field(default_factory=dict)

narrowed class-attribute instance-attribute

narrowed: bool = False

Escape dataclass

Escape(unit: str, item: str, package: str, changed_files: tuple[str, ...], proved_sha: str = '', proved_run: str = '', audit_sha: str = '', audit_run: str = '', leg: str = '', contract_digest: str = '', item_digest: str = '', when: str = '', resolved: bool = False)

One test item proved green by its row that failed during a scheduled audit.

Attributes:

Name Type Description
unit str

Canonical unit identifier (<step>@<item>).

item str

Repository-relative test file path.

package str

Owning package path (or "." for workspace tests).

changed_files tuple[str, ...]

Repository-relative files changed since proved_sha.

proved_sha str

Commit SHA of the row that proved the item.

proved_run str

Forge run id of the proving row.

audit_sha str

Commit SHA of the audit run that caught the escape.

audit_run str

Forge run id of the audit run.

leg str

Platform leg label of the audit run.

contract_digest str

SHA-256 of <package>/workshop.toml at audit time; changing the contract (to declare [tests] reads) clears the block.

item_digest str

SHA-256 of item at audit time; fixing item clears the block.

when str

ISO 8601 UTC timestamp of the audit run.

resolved bool

Whether this escape has been explicitly marked resolved.

Methods:

Name Description
to_dict

Serialize as a JSON-compatible dictionary.

from_dict

Deserialize from a stored escape row.

unit instance-attribute

unit: str

item instance-attribute

item: str

package instance-attribute

package: str

changed_files instance-attribute

changed_files: tuple[str, ...]

proved_sha class-attribute instance-attribute

proved_sha: str = ''

proved_run class-attribute instance-attribute

proved_run: str = ''

audit_sha class-attribute instance-attribute

audit_sha: str = ''

audit_run class-attribute instance-attribute

audit_run: str = ''

leg class-attribute instance-attribute

leg: str = ''

contract_digest class-attribute instance-attribute

contract_digest: str = ''

item_digest class-attribute instance-attribute

item_digest: str = ''

when class-attribute instance-attribute

when: str = ''

resolved class-attribute instance-attribute

resolved: bool = False

to_dict

to_dict() -> dict[str, Any]

Serialize as a JSON-compatible dictionary.

Source code in packages/workshop/src/livery/workshop/_proved.py
def to_dict(self) -> dict[str, Any]:
    """Serialize as a JSON-compatible dictionary."""
    return {
        "audit-run": self.audit_run,
        "audit-sha": self.audit_sha,
        "changed-files": list(self.changed_files),
        "contract-digest": self.contract_digest,
        "item": self.item,
        "item-digest": self.item_digest,
        "leg": self.leg,
        "package": self.package,
        "proved-run": self.proved_run,
        "proved-sha": self.proved_sha,
        "resolved": self.resolved,
        "unit": self.unit,
        "when": self.when,
    }

from_dict classmethod

from_dict(data: Mapping[str, Any]) -> Escape

Deserialize from a stored escape row.

Source code in packages/workshop/src/livery/workshop/_proved.py
@classmethod
def from_dict(cls, data: Mapping[str, Any]) -> Escape:
    """Deserialize from a stored escape row."""
    raw_changed = data.get("changed-files")
    changed = (
        tuple(str(p) for p in raw_changed) if isinstance(raw_changed, list) else ()
    )
    return cls(
        unit=str(data.get("unit", "")),
        item=str(data.get("item", "")),
        package=str(data.get("package", "")),
        changed_files=changed,
        proved_sha=str(data.get("proved-sha", "")),
        proved_run=str(data.get("proved-run", "")),
        audit_sha=str(data.get("audit-sha", "")),
        audit_run=str(data.get("audit-run", "")),
        leg=str(data.get("leg", "")),
        contract_digest=str(data.get("contract-digest", "")),
        item_digest=str(data.get("item-digest", "")),
        when=str(data.get("when", "")),
        resolved=bool(data.get("resolved", False)),
    )

FingerprintContext dataclass

FingerprintContext(root: Path, packages: tuple[Package, ...], files: tuple[str, ...] = tuple(), _tool_versions: dict[str, str] | None = None, _digests: dict[str, str] = dict(), _channels: dict[str, str] | None = None, _categories: dict[str, tuple[str, str]] | None = None, _sets: dict[str, frozenset[str]] | None = None, _dep_paths: dict[str, tuple[str, ...]] = dict(), _dep_files: dict[str, tuple[str, ...]] = dict(), _root_configs: tuple[str, ...] | None = None)

Shared per-walk cache for computing step unit fingerprints quickly.

Methods:

Name Description
for_root

Build a context listing the workspace's git-held files once.

tool_version

Pinned version token for tool name from toolroom.lock.

digest

Cached SHA-256 digest for relative.

category_of_path

(unit_key, category_name) for relative, cached across steps.

channel_of_path

Provenance channel for relative, cached across steps.

sets_of_path

Named sets containing relative, cached across steps.

dependency_paths

Sorted paths of upstream workspace dependencies of target.

dependency_files

Sorted non-test, non-doc files under upstream dependency dep_path.

root_config_files

Sorted root workspace configuration files that can affect package steps.

Attributes:

Name Type Description
root Path
packages tuple[Package, ...]
files tuple[str, ...]

root instance-attribute

root: Path

packages instance-attribute

packages: tuple[Package, ...]

files class-attribute instance-attribute

files: tuple[str, ...] = field(default_factory=tuple)

for_root classmethod

for_root(root: Path, packages: tuple[Package, ...]) -> FingerprintContext

Build a context listing the workspace's git-held files once.

Source code in packages/workshop/src/livery/workshop/_proved.py
@classmethod
def for_root(cls, root: Path, packages: tuple[Package, ...]) -> FingerprintContext:
    """Build a context listing the workspace's git-held files once."""
    from livery.workshop._scope import MARKER

    try:
        raw_files = git.ls_files(root, others=True)
    except git.GitError:
        raw_files = [
            p.relative_to(root).as_posix()
            for p in root.rglob("*")
            if p.is_file() and ".git" not in p.parts
        ]
    listed = tuple(
        path
        for path in sorted(raw_files)
        if path != MARKER
        and not path.startswith("fm-profile")
        and not (
            path.startswith(".workshop/")
            and not path.startswith(".workshop/graphs/")
        )
    )
    return cls(root=root, packages=packages, files=listed)

tool_version

tool_version(name: str) -> str

Pinned version token for tool name from toolroom.lock.

Source code in packages/workshop/src/livery/workshop/_proved.py
def tool_version(self, name: str) -> str:
    """Pinned version token for tool *name* from ``toolroom.lock``."""
    if self._tool_versions is None:
        self._tool_versions = _read_toolroom_versions(self.root)
    return (
        self._tool_versions.get(name)
        or self._tool_versions.get(name.replace("-", "_"))
        or self._tool_versions.get(name.replace("_", "-"))
        or "unlocked"
    )

digest

digest(relative: str) -> str

Cached SHA-256 digest for relative.

Source code in packages/workshop/src/livery/workshop/_proved.py
def digest(self, relative: str) -> str:
    """Cached SHA-256 digest for *relative*."""
    found = self._digests.get(relative)
    if found is None:
        found = _file_digest(self.root, relative)
        self._digests[relative] = found
    return found

category_of_path

category_of_path(relative: str) -> tuple[str, str]

(unit_key, category_name) for relative, cached across steps.

Source code in packages/workshop/src/livery/workshop/_proved.py
def category_of_path(self, relative: str) -> tuple[str, str]:
    """``(unit_key, category_name)`` for *relative*, cached across steps."""
    if self._categories is None:
        from livery.workshop._categories import category_of
        from livery.workshop._provenance import unit_of

        cats: dict[str, tuple[str, str]] = {}
        for path in self.files:
            unit, inside = unit_of(self.root, self.packages, path)
            if unit is None:
                cats[path] = ("", "")
            else:
                cats[path] = (unit.path, category_of(unit, inside).name)
        self._categories = cats
    return self._categories.get(relative, ("", ""))

channel_of_path

channel_of_path(relative: str) -> str

Provenance channel for relative, cached across steps.

Source code in packages/workshop/src/livery/workshop/_proved.py
def channel_of_path(self, relative: str) -> str:
    """Provenance channel for *relative*, cached across steps."""
    if self._channels is None:
        from livery.workshop._provenance import classify_channels

        self._channels = classify_channels(self.root, self.files)
    return self._channels.get(relative, "")

sets_of_path

sets_of_path(relative: str) -> frozenset[str]

Named sets containing relative, cached across steps.

Source code in packages/workshop/src/livery/workshop/_proved.py
def sets_of_path(self, relative: str) -> frozenset[str]:
    """Named sets containing *relative*, cached across steps."""
    if self._sets is None:
        from livery.workshop._extensions import extension_names, extension_provider
        from livery.workshop._influence import sets_of

        pkg_dirs = frozenset(p.path for p in self.packages)
        providers: tuple[str, ...] = ()
        if (self.root / "workshop.toml").is_file() and self.packages:
            providers = tuple(
                sorted(
                    {
                        provider
                        for name in extension_names(self.root)
                        if (provider := extension_provider(name, self.packages))
                    }
                )
            )
        self._sets = {
            path: sets_of(
                self.root,
                path,
                package_dirs=pkg_dirs,
                providers=providers,
            )
            for path in self.files
        }
    return self._sets.get(relative, frozenset())

dependency_paths

dependency_paths(target: str) -> tuple[str, ...]

Sorted paths of upstream workspace dependencies of target.

Source code in packages/workshop/src/livery/workshop/_proved.py
def dependency_paths(self, target: str) -> tuple[str, ...]:
    """Sorted paths of upstream workspace dependencies of *target*."""
    found = self._dep_paths.get(target)
    if found is None:
        from livery.workshop._graph import dependencies_closure

        closure = dependencies_closure(self.packages, {target})
        found = tuple(sorted(p.path for p in closure if p.path != target))
        self._dep_paths[target] = found
    return found

dependency_files

dependency_files(dep_path: str) -> tuple[str, ...]

Sorted non-test, non-doc files under upstream dependency dep_path.

Source code in packages/workshop/src/livery/workshop/_proved.py
def dependency_files(self, dep_path: str) -> tuple[str, ...]:
    """Sorted non-test, non-doc files under upstream dependency *dep_path*."""
    found = self._dep_files.get(dep_path)
    if found is None:
        prefix = dep_path + "/"
        selected: list[str] = []
        for path in self.files:
            if not path.startswith(prefix):
                continue
            _, cat = self.category_of_path(path)
            if cat in _DEP_IGNORED_CATEGORIES:
                continue
            selected.append(path)
        found = tuple(selected)
        self._dep_files[dep_path] = found
    return found

root_config_files

root_config_files() -> tuple[str, ...]

Sorted root workspace configuration files that can affect package steps.

Source code in packages/workshop/src/livery/workshop/_proved.py
def root_config_files(self) -> tuple[str, ...]:
    """Sorted root workspace configuration files that can affect package steps."""
    if self._root_configs is None:
        from livery.workshop._graph import is_prose, is_site, reaches_no_package
        from livery.workshop._packages import WORKSPACE_TESTS

        pkg_prefixes = tuple(p.path + "/" for p in self.packages)
        ws_tests_prefix = WORKSPACE_TESTS + "/"
        configs: list[str] = []
        for path in self.files:
            if path.startswith(pkg_prefixes) or path.startswith(ws_tests_prefix):
                continue
            if path in ("toolroom.lock", "tasks.py"):
                continue
            if is_prose(path) or is_site(path) or reaches_no_package(path):
                continue
            configs.append(path)
        self._root_configs = tuple(configs)
    return self._root_configs

ProvedTree dataclass

ProvedTree(tree: str, branch: str, run: str, sha: str, legs: tuple[str, ...], when: str = '')

Record that a git tree hash was proved green across a set of check legs.

Attributes:

Name Type Description
tree str

Git tree object id (HEAD:).

branch str

Proved-record base key (main or branch slug) that proved it.

run str

Forge run id that stamped this tree.

sha str

Commit SHA checked out by that run.

legs tuple[str, ...]

Sorted platform leg labels proved green for this tree.

when str

ISO 8601 UTC timestamp stamped on the row.

Methods:

Name Description
to_dict

Serialize as a JSON-compatible dictionary.

from_dict

Deserialize from a TREES row; returns None if malformed.

tree instance-attribute

tree: str

branch instance-attribute

branch: str

run instance-attribute

run: str

sha instance-attribute

sha: str

legs instance-attribute

legs: tuple[str, ...]

when class-attribute instance-attribute

when: str = ''

to_dict

to_dict() -> dict[str, Any]

Serialize as a JSON-compatible dictionary.

Source code in packages/workshop/src/livery/workshop/_proved.py
def to_dict(self) -> dict[str, Any]:
    """Serialize as a JSON-compatible dictionary."""
    return {
        "branch": self.branch,
        "legs": list(self.legs),
        "run": self.run,
        "sha": self.sha,
        "tree": self.tree,
    }

from_dict classmethod

from_dict(data: Mapping[str, Any], *, when: str = '') -> ProvedTree | None

Deserialize from a TREES row; returns None if malformed.

Source code in packages/workshop/src/livery/workshop/_proved.py
@classmethod
def from_dict(cls, data: Mapping[str, Any], *, when: str = "") -> ProvedTree | None:
    """Deserialize from a `TREES` row; returns ``None`` if malformed."""
    tree = str(data.get("tree", "") or "")
    branch = str(data.get("branch", "") or "")
    run = str(data.get("run", "") or "")
    sha = str(data.get("sha", "") or "")
    raw_legs = data.get("legs")
    if not tree or not branch or not isinstance(raw_legs, list):
        return None
    legs = tuple(sorted({str(leg) for leg in raw_legs if str(leg)}))
    if not legs:
        return None
    return cls(
        tree=tree,
        branch=branch,
        run=run,
        sha=sha,
        legs=legs,
        when=when or str(data.get("when", "") or ""),
    )

current_platform

current_platform(leg: str = '', environ: Mapping[str, str] | None = None) -> Platform

The platform of the current process, including runner image when reported.

Source code in packages/workshop/src/livery/workshop/_proved.py
def current_platform(
    leg: str = "", environ: Mapping[str, str] | None = None
) -> Platform:
    """The platform of the current process, including runner image when reported."""
    env = os.environ if environ is None else environ
    os_name = env.get("RUNNER_OS", "").strip()
    if not os_name and leg:
        parts = leg.removeprefix("check-").split("-")
        if len(parts) >= 2:
            os_name = "-".join(parts[:2])
    if not os_name:
        os_name = sys.platform
    image_os = env.get("ImageOS", "").strip()
    image_ver = env.get("ImageVersion", "").strip()
    if image_os and image_ver:
        image = f"{image_os}:{image_ver}"
    elif image_ver:
        image = image_ver
    else:
        image = _platform.release()
    py = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
    return Platform(os=os_name, image=image, python=py)

read_set_blob_name

read_set_blob_name(digest: str) -> str

Content-addressed blob path on a proved ref for read-set digest.

Source code in packages/workshop/src/livery/workshop/_proved.py
def read_set_blob_name(digest: str) -> str:
    """Content-addressed blob path on a proved ref for read-set *digest*."""
    return f"{READS_PREFIX}{digest}.json"

dir_listing_digest

dir_listing_digest(root: Path, relative: str) -> str

SHA-256 of sorted direct entry names under root / relative.

Source code in packages/workshop/src/livery/workshop/_proved.py
def dir_listing_digest(root: Path, relative: str) -> str:
    """SHA-256 of sorted direct entry names under ``root / relative``."""
    target = root if relative in ("", ".") else root / relative
    if not target.is_dir():
        return "missing"
    try:
        names = sorted(
            entry.name
            for entry in target.iterdir()
            if not _is_ignored_dir_entry(entry.name)
        )
    except OSError:
        return "unreadable"
    return hashlib.sha256("\n".join(names).encode("utf-8")).hexdigest()

item_read_set_matches

item_read_set_matches(read_set: ItemReadSet, root: Path, *, installed_dists: Mapping[str, str] | None = None) -> tuple[bool, str]

Whether read_set still matches root on disk, and the first mismatch.

Refuses an unrecorded read-set first, then checks opened files, absent paths (a created file invalidates the item), listed directories (an added or removed entry invalidates the item), and imported third-party distributions.

Source code in packages/workshop/src/livery/workshop/_proved.py
def item_read_set_matches(
    read_set: ItemReadSet,
    root: Path,
    *,
    installed_dists: Mapping[str, str] | None = None,
) -> tuple[bool, str]:
    """Whether *read_set* still matches *root* on disk, and the first mismatch.

    Refuses an ``unrecorded`` read-set first, then checks opened files,
    absent paths (a created file invalidates the item), listed
    directories (an added or removed entry invalidates the item), and
    imported third-party distributions.
    """
    return _item_read_set_matches_cached(
        read_set,
        root,
        file_cache={},
        dir_cache={},
        installed_dists=installed_dists,
    )

unit_id

unit_id(step: str, target: str) -> str

Canonical unit identifier for step over target.

Source code in packages/workshop/src/livery/workshop/_proved.py
def unit_id(step: str, target: str) -> str:
    """Canonical unit identifier for *step* over *target*."""
    return f"{step}@{target}"

row_name

row_name(step: str, target: str) -> str

Stable ref-safe filename for one unit's row file on a proved ref.

Source code in packages/workshop/src/livery/workshop/_proved.py
def row_name(step: str, target: str) -> str:
    """Stable ref-safe filename for one unit's row file on a proved ref."""
    return f"{git.slug(step)}--{git.slug(target)}.json"

current_keys

current_keys(root: Path) -> set[tuple[str, ...]] | None

The keys the world produces: main and every branch on origin, per check leg.

Source code in packages/workshop/src/livery/workshop/_proved.py
def current_keys(root: Path) -> set[tuple[str, ...]] | None:
    """The keys the world produces: main and every branch on origin, per check leg."""
    from livery.workshop import check_legs

    try:
        legs = check_legs(root)
    except (Exception, SystemExit):
        return None
    heads = _branches(root)
    if heads is None:
        return None
    bases = {MAIN, *(git.slug(branch) for branch in heads)}
    return {(base, git.slug(leg)) for base in bases for leg in legs}

current_parts_keys

current_parts_keys(root: Path) -> set[tuple[str, ...]] | None

Active (extension, base, leg) keys for the proved-parts family.

Combines every extension listed by the workspace with every active (base, leg) from current_keys. Returns None when the contract or remote cannot be read so the janitor drops nothing.

Source code in packages/workshop/src/livery/workshop/_proved.py
def current_parts_keys(root: Path) -> set[tuple[str, ...]] | None:
    """Active ``(extension, base, leg)`` keys for the proved-parts family.

    Combines every extension listed by the workspace with every active
    ``(base, leg)`` from `current_keys`. Returns ``None`` when the contract
    or remote cannot be read so the janitor drops nothing.
    """
    from livery.workshop._extensions import extension_names

    base_legs = current_keys(root)
    if base_legs is None:
        return None
    try:
        exts = {git.slug(name) for name in extension_names(root)}
    except (Exception, SystemExit):
        return None
    return {(ext, base, leg) for ext in exts for base, leg in base_legs}

proved_parts_series

proved_parts_series(extension: str, base: str, leg: str, *, schema: int | None = None) -> Series

Return the proved-parts series for extension, base, and leg.

The ref lives under proved-parts/<extension>/<base>/<platform-leg>, separate from proved/. schema lets the owning extension stamp and validate its own row schema without the base reading the part's format.

Source code in packages/workshop/src/livery/workshop/_proved.py
def proved_parts_series(
    extension: str,
    base: str,
    leg: str,
    *,
    schema: int | None = None,
) -> git.Series:
    """Return the proved-parts series for *extension*, *base*, and *leg*.

    The ref lives under ``proved-parts/<extension>/<base>/<platform-leg>``,
    separate from ``proved/``. *schema* lets the owning extension stamp and
    validate its own row schema without the base reading the part's format.
    """
    from livery.workshop._shard import platform_leg

    series = PROVED_PARTS.series(extension, base, platform_leg(leg))
    if schema is not None and schema != series.schema:
        return replace(series, schema=schema)
    return series

proved_parts_prefixes

proved_parts_prefixes(extension: str, bases: Sequence[str]) -> tuple[str, ...]

Return ref prefixes to fetch extension's proved parts for bases.

Source code in packages/workshop/src/livery/workshop/_proved.py
def proved_parts_prefixes(extension: str, bases: Sequence[str]) -> tuple[str, ...]:
    """Return ref prefixes to fetch *extension*'s proved parts for *bases*."""
    ext = git.slug(extension)
    return tuple(f"{PROVED_PARTS.prefix}{ext}/{git.slug(base)}/" for base in bases)

put_proved_part

put_proved_part(root: Path, *, extension: str, base: str, leg: str, unit: str, row_key: str, payload: Mapping[str, Any], message: str = '') -> str

Store an opaque payload for extension under unit and row_key.

The proved record keeps the payload untouched and does not inspect its schema or keys. Returns "" on success or an error description.

Source code in packages/workshop/src/livery/workshop/_proved.py
def put_proved_part(
    root: Path,
    *,
    extension: str,
    base: str,
    leg: str,
    unit: str,
    row_key: str,
    payload: Mapping[str, Any],
    message: str = "",
) -> str:
    """Store an opaque *payload* for *extension* under *unit* and *row_key*.

    The proved record keeps the payload untouched and does not inspect its
    schema or keys. Returns ``""`` on success or an error description.
    """
    from livery.workshop._ci_context import run_context, state_store

    active_run = run_context()
    if active_run is not None and active_run.is_fork_pr:
        return ""

    if not extension:
        return "refusing: extension name is required"
    if not base:
        return "refusing: base branch is required"
    if not leg:
        return "refusing: leg label is required"
    if not unit or not row_key:
        return "refusing: unit and row key are required"
    series = proved_parts_series(extension, base, leg)
    file_name = f"{git.slug(unit)}.json"
    row = {
        "unit": unit,
        "key": row_key,
        "payload": dict(payload),
    }
    return series.put(
        state_store(root),
        {file_name: row},
        message=message or f"proved-parts: {extension}/{base}/{leg} {unit}",
    )

read_proved_part

read_proved_part(root: Path, *, extension: str, base: str, leg: str, unit: str, row_key: str) -> dict[str, Any] | None

Read an opaque payload stored by put_proved_part for unit at row_key.

Returns None when no part exists, the ref cannot be read, or the stored key does not match row_key.

Source code in packages/workshop/src/livery/workshop/_proved.py
def read_proved_part(
    root: Path,
    *,
    extension: str,
    base: str,
    leg: str,
    unit: str,
    row_key: str,
) -> dict[str, Any] | None:
    """Read an opaque payload stored by `put_proved_part` for *unit* at *row_key*.

    Returns ``None`` when no part exists, the ref cannot be read, or the
    stored key does not match *row_key*.
    """
    from livery.workshop._ci_context import state_store

    if not extension or not base or not leg or not unit or not row_key:
        return None
    series = proved_parts_series(extension, base, leg)
    found, why = series.row(state_store(root), f"{git.slug(unit)}.json")
    if why or found is None:
        return None
    if str(found.data.get("key", "")) != row_key:
        return None
    payload = found.data.get("payload")
    return dict(payload) if isinstance(payload, dict) else None

leg_base

leg_base(run: RunContext) -> str

The proved-record base key (main or branch slug) for run.

Source code in packages/workshop/src/livery/workshop/_proved.py
def leg_base(run: RunContext) -> str:
    """The proved-record base key (``main`` or branch slug) for *run*."""
    if run.is_fork_pr:
        return MAIN
    if run.event == "pull_request" and run.head_ref:
        return git.slug(run.head_ref)
    branch = run.ref.removeprefix("refs/heads/")
    if branch == MAIN or not branch:
        return MAIN
    return git.slug(branch)

leg_key

leg_key(run: RunContext) -> str

The platform leg key for run, stripping any shard suffix.

Source code in packages/workshop/src/livery/workshop/_proved.py
def leg_key(run: RunContext) -> str:
    """The platform leg key for *run*, stripping any shard suffix."""
    from livery.workshop._shard import platform_leg

    label = platform_leg(run.leg) if run.leg else ""
    if label:
        return git.slug(label)
    plat = current_platform()
    return git.slug(f"{plat.os}-{sys.version_info.major}.{sys.version_info.minor}")

merge_unit_files

merge_unit_files(existing: dict[str, str], incoming: dict[str, str], *, keep: int = KEEP_READ_SETS) -> dict[str, str]

Combine existing and incoming proved unit files for CAS retry.

Files present in only one side stand as-is. When both sides write the same unit file, their read-set entries merge by fingerprint, accumulating verdict counts across concurrent writers and retaining the newest keep distinct fingerprints.

Source code in packages/workshop/src/livery/workshop/_proved.py
def merge_unit_files(
    existing: dict[str, str],
    incoming: dict[str, str],
    *,
    keep: int = KEEP_READ_SETS,
) -> dict[str, str]:
    """Combine *existing* and *incoming* proved unit files for CAS retry.

    Files present in only one side stand as-is. When both sides write
    the same unit file, their read-set entries merge by fingerprint,
    accumulating verdict counts across concurrent writers and retaining
    the newest *keep* distinct fingerprints.
    """
    merged = dict(existing)
    for name, raw_new in incoming.items():
        if name.startswith(READS_PREFIX) or name not in merged:
            merged[name] = raw_new
            continue
        try:
            old_data = json.loads(merged[name])
            new_data = json.loads(raw_new)
        except ValueError:
            merged[name] = raw_new
            continue
        if not isinstance(old_data, dict) or not isinstance(new_data, dict):
            merged[name] = raw_new
            continue
        old_row = UnitRow.from_dict(old_data)
        new_row = UnitRow.from_dict(new_data)
        entries = _merge_entries(old_row.entries, new_row.entries, keep=keep)
        combined = UnitRow(
            unit=new_row.unit or old_row.unit,
            step=new_row.step or old_row.step,
            target=new_row.target or old_row.target,
            platform=new_row.platform if new_row.platform.os else old_row.platform,
            entries=entries,
        )
        stamp = max(str(old_data.get("when", "")), str(new_data.get("when", "")))
        merged[name] = json.dumps(
            {**combined.to_dict(), "schema": SCHEMA, "when": stamp},
            sort_keys=True,
        )
    return merged

write_observations

write_observations(root: Path, observations: Sequence[Observation], *, base: str = MAIN, leg: str = '', local: bool = False, keep: int = KEEP_READ_SETS, store: StateStore | None = None) -> str

Write observations to the proved store; "" or the failure reason.

Source code in packages/workshop/src/livery/workshop/_proved.py
def write_observations(
    root: Path,
    observations: Sequence[Observation],
    *,
    base: str = MAIN,
    leg: str = "",
    local: bool = False,
    keep: int = KEEP_READ_SETS,
    store: git.StateStore | None = None,
) -> str:
    """Write *observations* to the proved store; ``""`` or the failure reason."""
    if not observations:
        return ""
    from livery.workshop._ci_context import state_store

    target_store = state_store(root) if store is None else store
    series = LOCAL if local else FAMILY.series(base, leg)
    rows = _rows_from_observations(observations, keep=keep)
    blobs: dict[str, str] = {}
    for obs in observations:
        if obs.read_set is not None:
            digest = obs.read_set.fingerprint()
            blobs[read_set_blob_name(digest)] = json.dumps(
                obs.read_set.to_dict(), sort_keys=True
            )

    def _merge(existing: dict[str, str], incoming: dict[str, str]) -> dict[str, str]:
        return merge_unit_files(existing, incoming, keep=keep)

    return series.put(
        target_store,
        rows,
        message=f"proved: {len(rows)} unit(s)",
        blobs=blobs or None,
        merge=_merge,
    )

spool_proved_observations

spool_proved_observations(root: Path, observations: Sequence[Observation], *, base: str, leg: str, matched_branches: Sequence[str] = (), platform: Platform | None = None, exact_image: bool = True) -> None

Merge observations into LEG_SPOOL / PROVED_SHARDED_FILE for gate flush.

Keeps check legs read-only by carrying proved observations in the ephemeral leg artifact so the gate job flushes them once.

Source code in packages/workshop/src/livery/workshop/_proved.py
def spool_proved_observations(
    root: Path,
    observations: Sequence[Observation],
    *,
    base: str,
    leg: str,
    matched_branches: Sequence[str] = (),
    platform: Platform | None = None,
    exact_image: bool = True,
) -> None:
    """Merge *observations* into ``LEG_SPOOL / PROVED_SHARDED_FILE`` for gate flush.

    Keeps ``check`` legs read-only by carrying proved observations in the
    ephemeral leg artifact so the ``gate`` job flushes them once.
    """
    if not observations and not matched_branches:
        return
    from livery.workshop._metrics import LEG_SPOOL, leave_leg_file

    spool_path = root / LEG_SPOOL / PROVED_SHARDED_FILE
    collected: list[dict[str, Any]] = []
    branches: set[str] = set(matched_branches)
    stored_platform: dict[str, str] | None = (
        platform.to_dict() if platform is not None else None
    )
    stored_exact = exact_image
    if spool_path.is_file():
        try:
            existing = json.loads(spool_path.read_text("utf-8"))
        except (OSError, ValueError):
            existing = {}
        if isinstance(existing, dict):
            if isinstance(existing.get("observations"), list):
                for raw in existing["observations"]:
                    if isinstance(raw, dict):
                        collected.append(raw)
            if isinstance(existing.get("matched_branches"), list):
                branches.update(str(b) for b in existing["matched_branches"] if b)
            if stored_platform is None and isinstance(existing.get("platform"), dict):
                stored_platform = {
                    str(k): str(v) for k, v in existing["platform"].items()
                }
            if "exact_image" in existing:
                stored_exact = bool(existing["exact_image"]) and exact_image
    for obs in observations:
        collected.append(obs.to_dict())
    payload: dict[str, Any] = {
        "base": base,
        "leg": leg,
        "observations": collected,
    }
    if branches:
        payload["matched_branches"] = sorted(branches)
        payload["exact_image"] = stored_exact
        if stored_platform is not None:
            payload["platform"] = stored_platform
    leave_leg_file(root, PROVED_SHARDED_FILE, payload)

record_item_observations

record_item_observations(root: Path, step: str, results: Sequence[tuple[str, str, ItemReadSet]], *, local: bool = False, store: StateStore | None = None) -> str

Write per-item verdicts and read-sets for step to the proved store.

results is a sequence of (item_path, verdict, read_set) tuples. Inside CI gate/merge check legs (without an explicit store), spools observations into the leg bundle so check stays read-only and gate flushes them once. Otherwise writes to proved/<base>/<leg> in CI or proved-local when local is true. Outside CI with local=False, writes nothing and returns "".

Source code in packages/workshop/src/livery/workshop/_proved.py
def record_item_observations(
    root: Path,
    step: str,
    results: Sequence[tuple[str, str, ItemReadSet]],
    *,
    local: bool = False,
    store: git.StateStore | None = None,
) -> str:
    """Write per-item verdicts and read-sets for *step* to the proved store.

    *results* is a sequence of ``(item_path, verdict, read_set)`` tuples.
    Inside CI gate/merge ``check`` legs (without an explicit *store*),
    spools observations into the leg bundle so ``check`` stays read-only
    and ``gate`` flushes them once. Otherwise writes to
    ``proved/<base>/<leg>`` in CI or ``proved-local`` when *local* is
    true. Outside CI with ``local=False``, writes nothing and returns
    ``""``.
    """
    if not results:
        return ""
    from livery.workshop._ci_context import POINT_VARIABLE, run_context

    run = run_context()
    if run is None and not local:
        return ""
    plat = current_platform(run.leg if run is not None else "")
    branch = (
        (run.head_ref or run.ref.removeprefix("refs/heads/")) if run is not None else ""
    )
    trigger = os.environ.get(POINT_VARIABLE, "gate")
    observations = [
        Observation(
            step=step,
            target=item,
            verdict=verdict,
            fingerprint=read_set.fingerprint(),
            platform=plat,
            run=run.run_id if run is not None else "",
            sha=run.head_sha if run is not None else "",
            branch=branch,
            attempt=run.attempt if run is not None else "",
            trigger=trigger,
            read_set=read_set,
        )
        for item, verdict, read_set in results
    ]
    if local or run is None:
        return write_observations(root, observations, local=True, store=store)
    if store is None and trigger in ("gate", "merge"):
        spool_proved_observations(
            root,
            observations,
            base=leg_base(run),
            leg=leg_key(run),
        )
        return ""
    return write_observations(
        root,
        observations,
        base=leg_base(run),
        leg=leg_key(run),
        store=store,
    )

item_read_details

item_read_details(root: Path, item: str, *, store: StateStore | None = None) -> tuple[tuple[tuple[str, str, UnitRow, ReadSetEntry, ItemReadSet | None], ...], str]

Find proved rows and decoded read-sets for item across proved refs.

Searches remote proved/<base>/<leg> refs (and local proved-local when remote has none), matching units whose target equals item or whose unit equals item.

Source code in packages/workshop/src/livery/workshop/_proved.py
def item_read_details(
    root: Path,
    item: str,
    *,
    store: git.StateStore | None = None,
) -> tuple[tuple[tuple[str, str, UnitRow, ReadSetEntry, ItemReadSet | None], ...], str]:
    """Find proved rows and decoded read-sets for *item* across proved refs.

    Searches remote ``proved/<base>/<leg>`` refs (and local ``proved-local``
    when remote has none), matching units whose ``target`` equals *item*
    or whose ``unit`` equals *item*.
    """
    from livery.workshop._ci_context import state_store

    target_store = state_store(root) if store is None else store
    normalized = item.replace("\\", "/").lstrip("./")
    matched: list[tuple[str, str, UnitRow, ReadSetEntry, ItemReadSet | None]] = []

    def _scan_series(base: str, leg: str, series: git.Series) -> str:
        found = series.rows(target_store)
        if found.failed:
            return found.reason
        for raw in found.rows:
            unit_row = UnitRow.from_dict(raw.data)
            if unit_row.target != normalized and unit_row.unit != normalized:
                continue
            for entry in unit_row.entries:
                decoded: ItemReadSet | None = None
                if entry.read_set:
                    text = found.blobs.get(read_set_blob_name(entry.read_set))
                    if text is not None:
                        try:
                            blob_data = json.loads(text)
                        except ValueError:
                            blob_data = None
                        if isinstance(blob_data, Mapping):
                            decoded = ItemReadSet.from_dict(blob_data)
                matched.append((base, leg, unit_row, entry, decoded))
        return ""

    keys = FAMILY.listed(target_store)
    if keys is None:
        return (), "proved: keys could not be listed"
    for base, leg in keys:
        why = _scan_series(base, leg, FAMILY.at(base, leg))
        if why:
            return (), why
    if not matched:
        _scan_series("local", "local", LOCAL)
    matched.sort(key=lambda rec: (rec[3].when, rec[0], rec[1]), reverse=True)
    return tuple(matched), ""

read_unit_rows

read_unit_rows(root: Path, *, base: str = MAIN, leg: str = '', local: bool = False, store: StateStore | None = None) -> tuple[tuple[UnitRow, ...], str]

Read all proved unit rows from one series; (rows, reason).

Source code in packages/workshop/src/livery/workshop/_proved.py
def read_unit_rows(
    root: Path,
    *,
    base: str = MAIN,
    leg: str = "",
    local: bool = False,
    store: git.StateStore | None = None,
) -> tuple[tuple[UnitRow, ...], str]:
    """Read all proved unit rows from one series; ``(rows, reason)``."""
    from livery.workshop._ci_context import state_store

    target_store = state_store(root) if store is None else store
    series = LOCAL if local else FAMILY.series(base, leg)
    found = series.rows(target_store)
    if found.failed:
        return (), found.reason
    return tuple(UnitRow.from_dict(row.data) for row in found.rows), ""

flaky_units

flaky_units(root: Path, *, store: StateStore | None = None) -> tuple[tuple[tuple[str, str, UnitRow, ReadSetEntry], ...], str]

Every flagged flaky entry (green and red under one fingerprint) across refs.

Source code in packages/workshop/src/livery/workshop/_proved.py
def flaky_units(
    root: Path,
    *,
    store: git.StateStore | None = None,
) -> tuple[tuple[tuple[str, str, UnitRow, ReadSetEntry], ...], str]:
    """Every flagged flaky entry (green and red under one fingerprint) across refs."""
    from livery.workshop._ci_context import state_store

    target_store = state_store(root) if store is None else store
    matched: list[tuple[str, str, UnitRow, ReadSetEntry]] = []

    def _scan(base: str, leg: str, series: git.Series) -> str:
        found = series.rows(target_store)
        if found.failed:
            return found.reason
        for raw in found.rows:
            unit_row = UnitRow.from_dict(raw.data)
            for entry in unit_row.entries:
                if entry.flaky:
                    matched.append((base, leg, unit_row, entry))
        return ""

    keys = FAMILY.listed(target_store)
    if keys is None:
        return (), "proved: keys could not be listed"
    for base, leg in keys:
        why = _scan(base, leg, FAMILY.at(base, leg))
        if why:
            return (), why
    _scan("local", "local", LOCAL)
    matched.sort(key=lambda item: (item[3].when, item[0], item[1]), reverse=True)
    return tuple(matched), ""

rows_for_run

rows_for_run(root: Path, run_id: str, *, store: StateStore | None = None) -> tuple[tuple[tuple[str, str, UnitRow, ReadSetEntry], ...], str]

All (base, leg, unit_row, entry) records written by run_id.

Source code in packages/workshop/src/livery/workshop/_proved.py
def rows_for_run(
    root: Path,
    run_id: str,
    *,
    store: git.StateStore | None = None,
) -> tuple[tuple[tuple[str, str, UnitRow, ReadSetEntry], ...], str]:
    """All ``(base, leg, unit_row, entry)`` records written by *run_id*."""
    from livery.workshop._ci_context import state_store

    target_store = state_store(root) if store is None else store
    keys = FAMILY.listed(target_store)
    if keys is None:
        return (), "proved: keys could not be listed"
    matched: list[tuple[str, str, UnitRow, ReadSetEntry]] = []
    for base, leg in keys:
        found = FAMILY.at(base, leg).rows(target_store)
        if found.failed:
            return (), found.reason
        for raw in found.rows:
            unit_row = UnitRow.from_dict(raw.data)
            for entry in unit_row.entries:
                if entry.run == run_id:
                    matched.append((base, leg, unit_row, entry))
    matched.sort(key=lambda item: (item[0], item[1], item[2].unit))
    return tuple(matched), ""

is_proved_unit

is_proved_unit(row: UnitRow | None, fingerprint: str, platform: Platform, *, exact_image: bool) -> tuple[bool, str]

Whether row proves fingerprint on platform, and the reason.

Refuses absence, platform mismatch, fingerprint mismatch, flaky units (both green and red observed for the same fingerprint), and any non-green verdict (skipped, red, unfinished).

Source code in packages/workshop/src/livery/workshop/_proved.py
def is_proved_unit(
    row: UnitRow | None,
    fingerprint: str,
    platform: Platform,
    *,
    exact_image: bool,
) -> tuple[bool, str]:
    """Whether *row* proves *fingerprint* on *platform*, and the reason.

    Refuses absence, platform mismatch, fingerprint mismatch, flaky units
    (both green and red observed for the same fingerprint), and any
    non-green verdict (``skipped``, ``red``, ``unfinished``).
    """
    if row is None:
        return False, "no row"
    return is_proved_from_rows((row,), fingerprint, platform, exact_image=exact_image)

is_proved_from_rows

is_proved_from_rows(rows: Sequence[UnitRow], fingerprint: str, platform: Platform, *, exact_image: bool) -> tuple[bool, str]

Whether candidate rows for one unit prove fingerprint on platform.

Matches each entry's own platform (falling back to the row's platform), and combines verdict counts across all matching entries for the same fingerprint so a red on one ref and a green on another still surface as flaky, while a later skipped observation never erases an existing green proof.

Source code in packages/workshop/src/livery/workshop/_proved.py
def is_proved_from_rows(
    rows: Sequence[UnitRow],
    fingerprint: str,
    platform: Platform,
    *,
    exact_image: bool,
) -> tuple[bool, str]:
    """Whether candidate *rows* for one unit prove *fingerprint* on *platform*.

    Matches each entry's own platform (falling back to the row's platform),
    and combines verdict counts across all matching entries for the same
    fingerprint so a red on one ref and a green on another still surface
    as flaky, while a later ``skipped`` observation never erases an
    existing green proof.
    """
    if not rows:
        return False, "no row"
    platform_entries = [
        entry
        for row in rows
        for entry in row.entries
        if _entry_platform(entry, row).matches(platform, exact_image=exact_image)
    ]
    if not platform_entries:
        return False, "platform differs"
    matching_entries = [
        entry for entry in platform_entries if entry.fingerprint == fingerprint
    ]
    if not matching_entries:
        return False, "fingerprint changed"
    counts = {
        v: sum(entry.counts.get(v, 0) for entry in matching_entries) for v in VERDICTS
    }
    if counts[GREEN] > 0 and counts[RED] > 0:
        return False, "flaky"
    if counts[GREEN] > 0:
        return True, "proved"
    latest = max(matching_entries, key=lambda entry: entry.when)
    return False, f"verdict is {latest.verdict}"

lookup_proved_rows

lookup_proved_rows(root: Path, *, run: RunContext | None, platform: Platform, store: StateStore | None = None) -> tuple[dict[str, list[UnitRow]], str]

Load candidate proved unit rows for run (CI) or offline mirror (desk).

In CI, fetches only the branch's leg ref (when not on main) and main's leg ref in one snapshot. On a desk, reads local proved-local rows and every mirrored proved/main/* ref without touching origin.

Source code in packages/workshop/src/livery/workshop/_proved.py
def lookup_proved_rows(
    root: Path,
    *,
    run: RunContext | None,
    platform: Platform,
    store: git.StateStore | None = None,
) -> tuple[dict[str, list[UnitRow]], str]:
    """Load candidate proved unit rows for *run* (CI) or offline mirror (desk).

    In CI, fetches only the branch's leg ref (when not on main) and main's
    leg ref in one snapshot. On a desk, reads local ``proved-local`` rows
    and every mirrored ``proved/main/*`` ref without touching origin.
    """
    from livery.workshop._ci_context import state_store

    target_store = state_store(root) if store is None else store
    grouped: dict[str, list[UnitRow]] = {}

    def _collect(rows: Sequence[UnitRow]) -> None:
        for row in rows:
            grouped.setdefault(row.unit, []).append(row)

    if run is not None:
        base = leg_base(run)
        leg = leg_key(run)
        targets: list[tuple[str, str]] = []
        if base != MAIN:
            targets.append((base, leg))
        targets.append((MAIN, leg))
        prefixes = tuple(f"{FAMILY.name}/{b}/{lg}" for b, lg in targets)
        with git.remote_snapshot(target_store, fetch=prefixes):
            for b, lg in targets:
                rows, reason = read_unit_rows(root, base=b, leg=lg, store=target_store)
                if reason:
                    return grouped, reason
                _collect(rows)
        return grouped, ""

    # Desk: local rows first, then mirrored proved/main/* refs matching platform.
    local_rows, local_reason = read_unit_rows(root, local=True, store=target_store)
    if not local_reason:
        _collect(local_rows)
    main_keys = FAMILY.listed(target_store, MAIN)
    if main_keys is None:
        return grouped, "proved mirror unavailable"
    for key in main_keys:
        found = FAMILY.at(*key).rows(target_store)
        if found.failed:
            return grouped, found.reason
        for raw in found.rows:
            row = UnitRow.from_dict(raw.data)
            if any(
                _entry_platform(entry, row).matches(platform, exact_image=False)
                for entry in row.entries
            ) or row.platform.matches(platform, exact_image=False):
                grouped.setdefault(row.unit, []).append(row)
    return grouped, ""

lookup_proved_rows_for_decision

lookup_proved_rows_for_decision(root: Path, *, run: RunContext | None, platform: Platform, store: StateStore | None = None) -> tuple[dict[str, list[UnitRow]], dict[str, list[tuple[str, UnitRow]]], str]

Load primary proved rows plus lingering branch rows for a main CI run.

Returns (primary_rows_by_unit, branch_rows_by_unit, reason). On desks and PR branches, branch_rows_by_unit is empty. On a main CI run, lingering proved/<branch>/<leg> refs for the same platform leg are also loaded so main's run can reuse and copy a branch's proved rows without re-executing unchanged units.

Source code in packages/workshop/src/livery/workshop/_proved.py
def lookup_proved_rows_for_decision(
    root: Path,
    *,
    run: RunContext | None,
    platform: Platform,
    store: git.StateStore | None = None,
) -> tuple[
    dict[str, list[UnitRow]],
    dict[str, list[tuple[str, UnitRow]]],
    str,
]:
    """Load primary proved rows plus lingering branch rows for a ``main`` CI run.

    Returns ``(primary_rows_by_unit, branch_rows_by_unit, reason)``.
    On desks and PR branches, ``branch_rows_by_unit`` is empty. On a
    ``main`` CI run, lingering ``proved/<branch>/<leg>`` refs for the
    same platform leg are also loaded so main's run can reuse and copy a
    branch's proved rows without re-executing unchanged units.
    """
    from livery.workshop._ci_context import state_store

    if run is None or run.is_fork_pr or leg_base(run) != MAIN:
        found_rows, why = lookup_proved_rows(
            root, run=run, platform=platform, store=store
        )
        return found_rows, {}, why

    target_store = state_store(root) if store is None else store
    leg = leg_key(run)
    primary: dict[str, list[UnitRow]] = {}
    branch_rows: dict[str, list[tuple[str, UnitRow]]] = {}
    with git.remote_snapshot(target_store):
        main_rows, why = read_unit_rows(root, base=MAIN, leg=leg, store=target_store)
        if why:
            return primary, branch_rows, why
        for row in main_rows:
            primary.setdefault(row.unit, []).append(row)
        keys = FAMILY.listed(target_store)
        if keys is None:
            return primary, branch_rows, ""
        branch_bases = sorted(b for b, lg in keys if lg == leg and b != MAIN)
        for base_key in branch_bases:
            rows, b_why = read_unit_rows(
                root, base=base_key, leg=leg, store=target_store
            )
            if b_why:
                continue
            for row in rows:
                branch_rows.setdefault(row.unit, []).append((base_key, row))
    return primary, branch_rows, ""

decide_units

decide_units(ctx: PhaseContext, *, candidate_units: Sequence[tuple[StepRecord, str]], primary_rows: Mapping[str, Sequence[UnitRow]], branch_rows: Mapping[str, Sequence[tuple[str, UnitRow]]] | None = None, platform: Platform, exact_image: bool, fp_cache: FingerprintContext | None = None) -> UnitDecision

Decide which candidate_units are proved green and which must run.

Source code in packages/workshop/src/livery/workshop/_proved.py
def decide_units(
    ctx: PhaseContext,
    *,
    candidate_units: Sequence[tuple[StepRecord, str]],
    primary_rows: Mapping[str, Sequence[UnitRow]],
    branch_rows: Mapping[str, Sequence[tuple[str, UnitRow]]] | None = None,
    platform: Platform,
    exact_image: bool,
    fp_cache: FingerprintContext | None = None,
) -> UnitDecision:
    """Decide which *candidate_units* are proved green and which must run."""
    cache = (
        fp_cache
        if fp_cache is not None
        else FingerprintContext.for_root(ctx.root, ctx.packages)
    )
    proved_ids: set[str] = set()
    running: list[tuple[StepRecord, str, str]] = []
    copied: list[Observation] = []
    matched_branches: set[str] = set()
    branches = branch_rows or {}

    for record, target in candidate_units:
        unit = unit_id(record.name, target)
        fp = step_fingerprint(record, ctx, target, cache=cache)
        own = primary_rows.get(unit, ())
        ok, reason = is_proved_from_rows(own, fp, platform, exact_image=exact_image)
        if ok:
            proved_ids.add(unit)
            continue
        branch_pairs = branches.get(unit, ())
        if branch_pairs:
            combined = (*own, *(row for _, row in branch_pairs))
            b_ok, b_reason = is_proved_from_rows(
                combined, fp, platform, exact_image=exact_image
            )
            if b_ok:
                best: tuple[str, UnitRow, ReadSetEntry] | None = None
                for base_key, row in branch_pairs:
                    for entry in row.entries:
                        if entry.fingerprint != fp:
                            continue
                        if not _entry_platform(entry, row).matches(
                            platform, exact_image=exact_image
                        ):
                            continue
                        if entry.counts.get(GREEN, 0) <= 0:
                            continue
                        if best is None or entry.when > best[2].when:
                            best = (base_key, row, entry)
                if best is not None:
                    base_key, row, entry = best
                    matched_branches.add(base_key)
                    copied.append(
                        Observation(
                            step=record.name,
                            target=target,
                            verdict=GREEN,
                            fingerprint=fp,
                            platform=_entry_platform(entry, row),
                            run=entry.run,
                            sha=entry.sha,
                            branch=entry.branch or base_key,
                            attempt=entry.attempt,
                            trigger=entry.trigger,
                            when=entry.when,
                        )
                    )
                    proved_ids.add(unit)
                    continue
            reason = b_reason
        running.append((record, target, reason))

    return UnitDecision(
        proved=frozenset(proved_ids),
        running=tuple(running),
        copied=tuple(copied),
        matched_branches=tuple(sorted(matched_branches)),
    )

copy_branch_rows_to_main

copy_branch_rows_to_main(root: Path, *, observations: Sequence[Observation], leg: str, matched_branches: Sequence[str] = (), platform: Platform | None = None, exact_image: bool = True, store: StateStore | None = None) -> str

Copy matched branch unit rows and item read-sets onto proved/main/<leg>.

Source code in packages/workshop/src/livery/workshop/_proved.py
def copy_branch_rows_to_main(
    root: Path,
    *,
    observations: Sequence[Observation],
    leg: str,
    matched_branches: Sequence[str] = (),
    platform: Platform | None = None,
    exact_image: bool = True,
    store: git.StateStore | None = None,
) -> str:
    """Copy matched branch unit rows and item read-sets onto ``proved/main/<leg>``."""
    if not observations and not matched_branches:
        return ""
    from livery.workshop._ci_context import state_store

    target_store = state_store(root) if store is None else store
    all_obs = list(observations)
    with git.remote_snapshot(target_store):
        if matched_branches:
            for base_key in matched_branches:
                series = FAMILY.series(base_key, leg)
                found = series.rows(target_store)
                if found.failed:
                    continue
                blob_cache: dict[str, ItemReadSet | None] = {}
                for raw in found.rows:
                    row = UnitRow.from_dict(raw.data)
                    for entry in row.entries:
                        if not entry.read_set:
                            continue
                        if entry.counts.get(GREEN, 0) <= 0 or entry.flaky:
                            continue
                        entry_plat = _entry_platform(entry, row)
                        if platform is not None and not entry_plat.matches(
                            platform, exact_image=exact_image
                        ):
                            continue
                        if entry.read_set not in blob_cache:
                            text, why = series.file(
                                target_store, read_set_blob_name(entry.read_set)
                            )
                            decoded: ItemReadSet | None = None
                            if not why and text is not None:
                                try:
                                    blob_data = json.loads(text)
                                except ValueError:
                                    blob_data = None
                                if isinstance(blob_data, Mapping):
                                    decoded = ItemReadSet.from_dict(blob_data)
                            blob_cache[entry.read_set] = decoded
                        read_set = blob_cache[entry.read_set]
                        if read_set is None:
                            continue
                        all_obs.append(
                            Observation(
                                step=row.step,
                                target=row.target,
                                verdict=GREEN,
                                fingerprint=entry.fingerprint,
                                platform=entry_plat,
                                run=entry.run,
                                sha=entry.sha,
                                branch=entry.branch or base_key,
                                attempt=entry.attempt,
                                trigger=entry.trigger,
                                when=entry.when,
                                read_set=read_set,
                            )
                        )
        return write_observations(root, all_obs, base=MAIN, leg=leg, store=target_store)

evaluate_shadow

evaluate_shadow(ctx: PhaseContext, *, today_running: frozenset[str], candidate_units: Sequence[tuple[StepRecord, str]], rows_by_unit: Mapping[str, Sequence[UnitRow]], platform: Platform, exact_image: bool, fp_cache: FingerprintContext | None = None) -> ShadowReport

Compare today_running against what rows_by_unit would skip.

Source code in packages/workshop/src/livery/workshop/_proved.py
def evaluate_shadow(
    ctx: PhaseContext,
    *,
    today_running: frozenset[str],
    candidate_units: Sequence[tuple[StepRecord, str]],
    rows_by_unit: Mapping[str, Sequence[UnitRow]],
    platform: Platform,
    exact_image: bool,
    fp_cache: FingerprintContext | None = None,
) -> ShadowReport:
    """Compare *today_running* against what *rows_by_unit* would skip."""
    cache = (
        fp_cache
        if fp_cache is not None
        else FingerprintContext.for_root(ctx.root, ctx.packages)
    )
    diffs: list[ShadowDiff] = []
    would_skip = 0
    today_skip = 0
    for record, target in candidate_units:
        unit = unit_id(record.name, target)
        fp = step_fingerprint(record, ctx, target, cache=cache)
        proved, reason = is_proved_from_rows(
            rows_by_unit.get(unit, ()),
            fp,
            platform,
            exact_image=exact_image,
        )
        proved_action = "skip" if proved else "run"
        today_action = "run" if unit in today_running else "skip"
        if proved:
            would_skip += 1
        if today_action == "skip":
            today_skip += 1
        if proved_action != today_action:
            diffs.append(
                ShadowDiff(
                    unit=unit,
                    today=today_action,
                    proved=proved_action,
                    reason=reason,
                )
            )
    return ShadowReport(
        checked=len(candidate_units),
        would_skip=would_skip,
        today_skip=today_skip,
        differences=tuple(diffs),
    )

write_shadow_report

write_shadow_report(root: Path, report: ShadowReport, *, run: RunContext, leg: str, trigger: str, platform: Platform, store: StateStore | None = None) -> str

Record one CI leg's shadow comparison on proved/differences.

Source code in packages/workshop/src/livery/workshop/_proved.py
def write_shadow_report(
    root: Path,
    report: ShadowReport,
    *,
    run: RunContext,
    leg: str,
    trigger: str,
    platform: Platform,
    store: git.StateStore | None = None,
) -> str:
    """Record one CI leg's shadow comparison on ``proved/differences``."""
    from livery.workshop._ci_context import state_store

    if run.is_fork_pr:
        return ""

    target_store = state_store(root) if store is None else store
    attempt_part = f"-{git.slug(run.attempt)}" if run.attempt else ""
    filename = f"{git.slug(run.run_id)}{attempt_part}-{git.slug(leg)}.json"
    branch = run.head_ref or run.ref.removeprefix("refs/heads/")
    payload: dict[str, Any] = {
        "attempt": run.attempt,
        "branch": branch,
        "checked": report.checked,
        "differences": [diff.to_dict() for diff in report.differences],
        "leg": leg,
        "platform": platform.to_dict(),
        "run": run.run_id,
        "sha": run.head_sha,
        "today-skip": report.today_skip,
        "trigger": trigger,
        "would-skip": report.would_skip,
    }
    return SHADOW_DIFFS.put(
        target_store,
        {filename: payload},
        message=f"proved shadow: run {run.run_id} ({leg})",
    )

read_shadow_differences

read_shadow_differences(root: Path, *, limit: int = 0, store: StateStore | None = None) -> tuple[int, tuple[dict[str, Any], ...], str]

Read shadow comparison rows newest first: (total_runs, non_empty, reason).

Source code in packages/workshop/src/livery/workshop/_proved.py
def read_shadow_differences(
    root: Path,
    *,
    limit: int = 0,
    store: git.StateStore | None = None,
) -> tuple[int, tuple[dict[str, Any], ...], str]:
    """Read shadow comparison rows newest first: ``(total_runs, non_empty, reason)``."""
    from livery.workshop._ci_context import state_store

    target_store = state_store(root) if store is None else store
    found = SHADOW_DIFFS.rows(target_store)
    if found.failed:
        return 0, (), found.reason
    total = len(found.rows)
    non_empty = [dict(row.data) for row in found.rows if row.data.get("differences")]
    if limit > 0:
        non_empty = non_empty[:limit]
    return total, tuple(non_empty), ""

without_item_selection

without_item_selection() -> Generator[None]

Temporarily disable live per-item selection in this process.

Source code in packages/workshop/src/livery/workshop/_proved.py
@contextlib.contextmanager
def without_item_selection() -> Generator[None]:
    """Temporarily disable live per-item selection in this process."""
    global _NO_SELECT_DEPTH
    with _NO_SELECT_LOCK:
        _NO_SELECT_DEPTH += 1
    try:
        yield
    finally:
        with _NO_SELECT_LOCK:
            _NO_SELECT_DEPTH -= 1

item_selection_disabled

item_selection_disabled(env: Mapping[str, str] | None = None) -> bool

Whether live per-item selection is disabled by context or environment.

Source code in packages/workshop/src/livery/workshop/_proved.py
def item_selection_disabled(env: Mapping[str, str] | None = None) -> bool:
    """Whether live per-item selection is disabled by context or environment."""
    with _NO_SELECT_LOCK:
        if _NO_SELECT_DEPTH > 0:
            return True
    source = os.environ if env is None else env
    return bool(source.get(NO_SELECT_VARIABLE, os.environ.get(NO_SELECT_VARIABLE, "")))

clear_ran_items

clear_ran_items(root: Path) -> None

Remove any prior check leg's per-item execution record under root.

Source code in packages/workshop/src/livery/workshop/_proved.py
def clear_ran_items(root: Path) -> None:
    """Remove any prior check leg's per-item execution record under *root*."""
    (root / RAN_ITEMS_FILE).unlink(missing_ok=True)

read_ran_items

read_ran_items(root: Path) -> RanItems

Read the per-item execution record under root; empty when absent.

Source code in packages/workshop/src/livery/workshop/_proved.py
def read_ran_items(root: Path) -> RanItems:
    """Read the per-item execution record under *root*; empty when absent."""
    path = root / RAN_ITEMS_FILE
    if not path.is_file():
        return RanItems()
    try:
        raw = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, ValueError):
        return RanItems()
    if not isinstance(raw, Mapping):
        return RanItems()
    raw_ran = raw.get("ran")
    raw_skipped = raw.get("skipped")
    ran = (
        {str(k): str(v) for k, v in raw_ran.items()}
        if isinstance(raw_ran, Mapping)
        else {}
    )
    skipped = (
        {str(k): str(v) for k, v in raw_skipped.items()}
        if isinstance(raw_skipped, Mapping)
        else {}
    )
    return RanItems(ran=ran, skipped=skipped, narrowed=bool(raw.get("narrowed", False)))

record_ran_items

record_ran_items(root: Path, *, ran: Mapping[str, str] | None = None, skipped: Mapping[str, str] | None = None, narrowed: bool = False) -> None

Merge ran, skipped, and narrowed into root's ran-items file.

Items that execute supersede any earlier skipped entry for the same item (for example when a top-up pass runs an item that the gate skipped).

Source code in packages/workshop/src/livery/workshop/_proved.py
def record_ran_items(
    root: Path,
    *,
    ran: Mapping[str, str] | None = None,
    skipped: Mapping[str, str] | None = None,
    narrowed: bool = False,
) -> None:
    """Merge *ran*, *skipped*, and *narrowed* into *root*'s ran-items file.

    Items that execute supersede any earlier skipped entry for the same item
    (for example when a top-up pass runs an item that the gate skipped).
    """
    existing = read_ran_items(root)
    merged_ran = {**existing.ran, **(dict(ran) if ran else {})}
    merged_skipped = {
        k: v
        for k, v in {**existing.skipped, **(dict(skipped) if skipped else {})}.items()
        if k not in merged_ran
    }
    payload = {
        "ran": dict(sorted(merged_ran.items())),
        "skipped": dict(sorted(merged_skipped.items())),
        "narrowed": existing.narrowed or narrowed,
    }
    target = root / RAN_ITEMS_FILE
    target.parent.mkdir(parents=True, exist_ok=True)
    target.write_text(json.dumps(payload, sort_keys=True), encoding="utf-8")

lookup_proved_item_rows

lookup_proved_item_rows(root: Path, target_units: frozenset[str], *, run: RunContext | None, platform: Platform, store: StateStore | None = None, bases: Sequence[str] | None = None) -> tuple[dict[str, list[tuple[UnitRow, dict[str, ItemReadSet]]]], str]

Load candidate proved rows and decoded read-set blobs for target_units.

Fetches only the branch and main leg refs in CI (or reads local plus mirrored proved/main/* offline on a desk), decoding only blobs referenced by entries belonging to target_units.

Source code in packages/workshop/src/livery/workshop/_proved.py
def lookup_proved_item_rows(
    root: Path,
    target_units: frozenset[str],
    *,
    run: RunContext | None,
    platform: Platform,
    store: git.StateStore | None = None,
    bases: Sequence[str] | None = None,
) -> tuple[dict[str, list[tuple[UnitRow, dict[str, ItemReadSet]]]], str]:
    """Load candidate proved rows and decoded read-set blobs for *target_units*.

    Fetches only the branch and main leg refs in CI (or reads local plus
    mirrored ``proved/main/*`` offline on a desk), decoding only blobs
    referenced by entries belonging to *target_units*.
    """
    from livery.workshop._ci_context import state_store

    target_store = state_store(root) if store is None else store
    grouped: dict[str, list[tuple[UnitRow, dict[str, ItemReadSet]]]] = {}

    def _load_series(series: git.Series, *, filter_platform: bool) -> str:
        found = series.rows(target_store)
        if found.failed:
            return found.reason
        blob_cache: dict[str, ItemReadSet | None] = {}
        for raw in found.rows:
            row = UnitRow.from_dict(raw.data)
            if row.unit not in target_units:
                continue
            if filter_platform and not (
                any(
                    _entry_platform(entry, row).matches(platform, exact_image=False)
                    for entry in row.entries
                )
                or row.platform.matches(platform, exact_image=False)
            ):
                continue
            decoded_map: dict[str, ItemReadSet] = {}
            for entry in row.entries:
                if not entry.read_set:
                    continue
                if entry.read_set not in blob_cache:
                    text = found.blobs.get(read_set_blob_name(entry.read_set))
                    decoded: ItemReadSet | None = None
                    if text is not None:
                        try:
                            blob_data = json.loads(text)
                        except ValueError:
                            blob_data = None
                        if isinstance(blob_data, Mapping):
                            decoded = ItemReadSet.from_dict(blob_data)
                    blob_cache[entry.read_set] = decoded
                cached = blob_cache[entry.read_set]
                if cached is not None:
                    decoded_map[entry.read_set] = cached
            grouped.setdefault(row.unit, []).append((row, decoded_map))
        return ""

    if run is not None:
        leg = leg_key(run)
        targets: list[tuple[str, str]] = []
        if bases is not None:
            for base_name in bases:
                slug_base = MAIN if base_name == MAIN else git.slug(base_name)
                if (slug_base, leg) not in targets:
                    targets.append((slug_base, leg))
        else:
            base = leg_base(run)
            if base != MAIN:
                targets.append((base, leg))
            targets.append((MAIN, leg))
        prefixes = tuple(f"{FAMILY.name}/{b}/{lg}" for b, lg in targets)
        with git.remote_snapshot(target_store, fetch=prefixes):
            for b, lg in targets:
                why = _load_series(FAMILY.series(b, lg), filter_platform=False)
                if why:
                    return grouped, why
        return grouped, ""

    _load_series(LOCAL, filter_platform=False)
    main_keys = FAMILY.listed(target_store, MAIN)
    if main_keys is None:
        return grouped, "proved mirror unavailable"
    for key in main_keys:
        why = _load_series(FAMILY.at(*key), filter_platform=True)
        if why:
            return grouped, why
    return grouped, ""

is_item_proved

is_item_proved(candidates: Sequence[tuple[UnitRow, Mapping[str, ItemReadSet]]], root: Path, platform: Platform, *, exact_image: bool, file_cache: dict[str, str] | None = None, dir_cache: dict[str, str] | None = None, installed_dists: Mapping[str, str] | None = None, check_missing_dists: bool = True) -> tuple[bool, str]

Whether candidates prove a test item on root and platform.

Refuses absence, platform mismatch, flaky fingerprints (both green and red observed across refs), missing or unrecorded read-sets, non-green verdicts, and any changed file, created absent path, modified listed directory, or moved third-party distribution.

Source code in packages/workshop/src/livery/workshop/_proved.py
def is_item_proved(
    candidates: Sequence[tuple[UnitRow, Mapping[str, ItemReadSet]]],
    root: Path,
    platform: Platform,
    *,
    exact_image: bool,
    file_cache: dict[str, str] | None = None,
    dir_cache: dict[str, str] | None = None,
    installed_dists: Mapping[str, str] | None = None,
    check_missing_dists: bool = True,
) -> tuple[bool, str]:
    """Whether *candidates* prove a test item on *root* and *platform*.

    Refuses absence, platform mismatch, flaky fingerprints (both green and
    red observed across refs), missing or unrecorded read-sets, non-green
    verdicts, and any changed file, created absent path, modified listed
    directory, or moved third-party distribution.
    """
    proved, reason, _fp = _check_item_proved(
        candidates,
        root,
        platform,
        exact_image=exact_image,
        file_cache=file_cache,
        dir_cache=dir_cache,
        installed_dists=installed_dists,
        check_missing_dists=check_missing_dists,
    )
    return proved, reason

shadow_select_items

shadow_select_items(root: Path, items: Sequence[str], *, step: str, run: RunContext | None = None, store: StateStore | None = None, exact_image: bool | None = None, platform: Platform | None = None, check_missing_dists: bool = True, bases: Sequence[str] | None = None, file_cache: dict[str, str] | None = None, dir_cache: dict[str, str] | None = None, installed_dists: Mapping[str, str] | None = None) -> tuple[ItemSelection, str]

Compute which items existing proved rows would select or skip.

Fails open on store errors (selecting every item) while returning the reason string so callers can log it without failing the run.

Source code in packages/workshop/src/livery/workshop/_proved.py
def shadow_select_items(
    root: Path,
    items: Sequence[str],
    *,
    step: str,
    run: RunContext | None = None,
    store: git.StateStore | None = None,
    exact_image: bool | None = None,
    platform: Platform | None = None,
    check_missing_dists: bool = True,
    bases: Sequence[str] | None = None,
    file_cache: dict[str, str] | None = None,
    dir_cache: dict[str, str] | None = None,
    installed_dists: Mapping[str, str] | None = None,
) -> tuple[ItemSelection, str]:
    """Compute which *items* existing proved rows would select or skip.

    Fails open on store errors (selecting every item) while returning the
    reason string so callers can log it without failing the run.
    """
    from livery.workshop._ci_context import run_context

    normalized = tuple(
        dict.fromkeys(item.replace("\\", "/").lstrip("./") for item in items)
    )
    if not normalized:
        return ItemSelection(selected=(), skipped=(), reasons={}), ""
    active_run = run_context() if run is None else run
    plat = (
        platform
        if platform is not None
        else current_platform(active_run.leg if active_run is not None else "")
    )
    strict = (
        (active_run is not None and not _is_sharded_leg(active_run.leg))
        if exact_image is None
        else exact_image
    )
    target_units = frozenset(unit_id(step, item) for item in normalized)
    rows_by_unit, why = lookup_proved_item_rows(
        root,
        target_units,
        run=active_run,
        platform=plat,
        store=store,
        bases=bases,
    )
    if why:
        return (
            ItemSelection(
                selected=normalized,
                skipped=(),
                reasons=dict.fromkeys(normalized, why),
            ),
            why,
        )
    files_memo = {} if file_cache is None else file_cache
    dirs_memo = {} if dir_cache is None else dir_cache
    dists_memo = (
        _installed_distributions() if installed_dists is None else installed_dists
    )
    selected: list[str] = []
    skipped: list[str] = []
    reasons: dict[str, str] = {}
    fingerprints: dict[str, str] = {}
    for item in normalized:
        proved, reason, fp = _check_item_proved(
            rows_by_unit.get(unit_id(step, item), ()),
            root,
            plat,
            exact_image=strict,
            file_cache=files_memo,
            dir_cache=dirs_memo,
            installed_dists=dists_memo,
            check_missing_dists=check_missing_dists,
        )
        reasons[item] = reason
        if proved:
            skipped.append(item)
            fingerprints[item] = fp
        else:
            selected.append(item)
    return (
        ItemSelection(
            selected=tuple(selected),
            skipped=tuple(skipped),
            reasons=reasons,
            fingerprints=fingerprints,
        ),
        "",
    )

record_selection_measure

record_selection_measure(root: Path, *, run: RunContext, selection: ItemSelection, durations: Mapping[str, float], step: str, trigger: str = '', store: StateStore | None = None) -> str

Record one selected share measure row in MEASURES for a CI leg.

Source code in packages/workshop/src/livery/workshop/_proved.py
def record_selection_measure(
    root: Path,
    *,
    run: RunContext,
    selection: ItemSelection,
    durations: Mapping[str, float],
    step: str,
    trigger: str = "",
    store: git.StateStore | None = None,
) -> str:
    """Record one ``selected`` share measure row in `MEASURES` for a CI leg."""
    from livery.workshop._ci_context import state_store

    if run.is_fork_pr:
        return ""

    total_items = len(selection.selected) + len(selection.skipped)
    if total_items == 0:
        return ""
    selected_items = len(selection.selected)
    skipped_items = len(selection.skipped)
    selected_seconds = sum(
        float(durations.get(item, 0.0)) for item in selection.selected
    )
    skipped_seconds = sum(float(durations.get(item, 0.0)) for item in selection.skipped)
    total_seconds = selected_seconds + skipped_seconds
    items_ratio = round(selected_items / total_items, 4)
    seconds_ratio = (
        round(selected_seconds / total_seconds, 4)
        if total_seconds > 0.0
        else items_ratio
    )
    reason_counts: dict[str, int] = {}
    for item in selection.selected:
        cause = selection.reasons.get(item, "unknown")
        reason_counts[cause] = reason_counts.get(cause, 0) + 1
    top_reasons = dict(
        sorted(reason_counts.items(), key=lambda kv: (-kv[1], kv[0]))[:10]
    )
    leg = run.leg or "check"
    branch = run.head_ref or run.ref.removeprefix("refs/heads/")
    row_file = f"{run.run_id}-{git.slug(leg)}.json"
    payload: dict[str, Any] = {
        "branch": branch,
        "items-ratio": items_ratio,
        "items-selected": selected_items,
        "items-skipped": skipped_items,
        "items-total": total_items,
        "leg": leg,
        "measure": "selected",
        "reasons": top_reasons,
        "run": run.run_id,
        "schema": SCHEMA,
        "seconds-ratio": seconds_ratio,
        "seconds-selected": round(selected_seconds, 2),
        "seconds-skipped": round(skipped_seconds, 2),
        "seconds-total": round(total_seconds, 2),
        "sha": run.head_sha,
        "step": step,
        "trigger": trigger,
        "when": datetime.now(UTC).isoformat(),
    }
    target_store = state_store(root) if store is None else store
    return MEASURES.put(
        target_store,
        {row_file: payload},
        message=f"measures: selected {selected_items}/{total_items} on {leg}",
    )

read_measures

read_measures(root: Path, *, measure: str = '', limit: int = 0, store: StateStore | None = None) -> tuple[tuple[dict[str, Any], ...], str]

Read measure rows newest first from MEASURES.

Source code in packages/workshop/src/livery/workshop/_proved.py
def read_measures(
    root: Path,
    *,
    measure: str = "",
    limit: int = 0,
    store: git.StateStore | None = None,
) -> tuple[tuple[dict[str, Any], ...], str]:
    """Read measure rows newest first from `MEASURES`."""
    from livery.workshop._ci_context import state_store

    target_store = state_store(root) if store is None else store
    found = MEASURES.rows(target_store)
    if found.failed:
        return (), found.reason
    rows = [
        dict(row.data)
        for row in found.rows
        if not measure or row.data.get("measure") == measure
    ]
    if limit > 0:
        rows = rows[:limit]
    return tuple(rows), ""

detect_item_escapes

detect_item_escapes(root: Path, *, step: str, selection: ItemSelection, red_items: Sequence[str], packages: Sequence[Package] = (), run: RunContext | None = None, store: StateStore | None = None) -> tuple[Escape, ...]

Return Escape rows for any red_items that selection marked proved.

Source code in packages/workshop/src/livery/workshop/_proved.py
def detect_item_escapes(
    root: Path,
    *,
    step: str,
    selection: ItemSelection,
    red_items: Sequence[str],
    packages: Sequence[Package] = (),
    run: RunContext | None = None,
    store: git.StateStore | None = None,
) -> tuple[Escape, ...]:
    """Return `Escape` rows for any *red_items* that *selection* marked proved."""
    from livery.workshop._ci_context import run_context

    skipped = set(selection.skipped)
    escaped_items = [
        item.replace("\\", "/").lstrip("./")
        for item in red_items
        if item.replace("\\", "/").lstrip("./") in skipped
    ]
    if not escaped_items:
        return ()
    active_run = run_context() if run is None else run
    plat = current_platform(active_run.leg if active_run is not None else "")
    target_units = frozenset(unit_id(step, item) for item in escaped_items)
    rows_by_unit, _why = lookup_proved_item_rows(
        root, target_units, run=active_run, platform=plat, store=store
    )
    audit_sha = active_run.head_sha if active_run is not None else ""
    if not audit_sha:
        try:
            audit_sha = git.head_sha(root)
        except git.GitError:
            audit_sha = ""
    audit_run = active_run.run_id if active_run is not None else ""
    leg = active_run.leg if active_run is not None else "local"
    now = datetime.now(UTC).isoformat(timespec="microseconds")

    found: list[Escape] = []
    for item in escaped_items:
        u_id = unit_id(step, item)
        proved_sha = ""
        proved_run = ""
        best_when = ""
        for row, _rs in rows_by_unit.get(u_id, ()):
            for entry in row.entries:
                if entry.counts.get(GREEN, 0) > 0 and entry.when >= best_when:
                    best_when = entry.when
                    proved_sha = entry.sha
                    proved_run = entry.run
        changed = _changed_since_sha(root, proved_sha)
        pkg_path = _owner_package_path(item, packages)
        contract_digest = (
            _file_digest(root, f"{pkg_path}/workshop.toml") if pkg_path != "." else ""
        )
        found.append(
            Escape(
                unit=u_id,
                item=item,
                package=pkg_path,
                changed_files=changed,
                proved_sha=proved_sha,
                proved_run=proved_run,
                audit_sha=audit_sha,
                audit_run=audit_run,
                leg=leg,
                contract_digest=contract_digest,
                item_digest=_file_digest(root, item),
                when=now,
            )
        )
    return tuple(found)

record_escapes

record_escapes(root: Path, escapes: Sequence[Escape], *, local: bool = False, store: StateStore | None = None) -> str

Write escapes to ESCAPES (CI) or LOCAL_ESCAPES (desk/local).

Source code in packages/workshop/src/livery/workshop/_proved.py
def record_escapes(
    root: Path,
    escapes: Sequence[Escape],
    *,
    local: bool = False,
    store: git.StateStore | None = None,
) -> str:
    """Write *escapes* to `ESCAPES` (CI) or `LOCAL_ESCAPES` (desk/local)."""
    if not escapes:
        return ""
    from livery.workshop._ci_context import run_context, state_store

    target_store = state_store(root) if store is None else store
    series = LOCAL_ESCAPES if (local or run_context() is None) else ESCAPES
    rows: dict[str, dict[str, Any]] = {}
    for idx, esc in enumerate(escapes):
        run_part = git.slug(esc.audit_run or esc.audit_sha[:12] or "local")
        fname = (
            f"{run_part}-{git.slug(esc.leg or 'local')}-{git.slug(esc.item)}-{idx}.json"
        )
        rows[fname] = esc.to_dict()
    return series.put(
        target_store,
        rows,
        message=f"proved escapes: {len(rows)} escape(s)",
    )

read_escapes

read_escapes(root: Path, *, limit: int = 0, store: StateStore | None = None) -> tuple[tuple[Escape, ...], str]

Read recorded escapes newest first from ESCAPES and LOCAL_ESCAPES.

Source code in packages/workshop/src/livery/workshop/_proved.py
def read_escapes(
    root: Path,
    *,
    limit: int = 0,
    store: git.StateStore | None = None,
) -> tuple[tuple[Escape, ...], str]:
    """Read recorded escapes newest first from `ESCAPES` and `LOCAL_ESCAPES`."""
    from livery.workshop._ci_context import state_store

    target_store = state_store(root) if store is None else store
    collected: list[Escape] = []
    remote_found = ESCAPES.rows(target_store)
    if not remote_found.failed:
        collected.extend(Escape.from_dict(r.data) for r in remote_found.rows)
    local_found = LOCAL_ESCAPES.rows(target_store)
    if not local_found.failed:
        collected.extend(Escape.from_dict(r.data) for r in local_found.rows)
    if remote_found.failed and local_found.failed:
        return (), remote_found.reason
    collected.sort(key=lambda e: e.when, reverse=True)
    if limit > 0:
        collected = collected[:limit]
    return tuple(collected), ""

active_escaped_packages

active_escaped_packages(root: Path, *, store: StateStore | None = None) -> tuple[frozenset[str], str]

Packages put back to whole runs due to an unaddressed recorded escape.

An escape stays active until the package's contract ([tests] reads) or the escaped test item itself changes on disk, or the row is marked resolved.

Source code in packages/workshop/src/livery/workshop/_proved.py
def active_escaped_packages(
    root: Path,
    *,
    store: git.StateStore | None = None,
) -> tuple[frozenset[str], str]:
    """Packages put back to whole runs due to an unaddressed recorded escape.

    An escape stays active until the package's contract (``[tests] reads``)
    or the escaped test item itself changes on disk, or the row is marked
    resolved.
    """
    escapes, why = read_escapes(root, store=store)
    if why:
        return frozenset(), why
    blocked: set[str] = set()
    for esc in escapes:
        if esc.resolved or esc.package in ("", "."):
            continue
        contract_still_same = (
            not esc.contract_digest
            or _file_digest(root, f"{esc.package}/workshop.toml") == esc.contract_digest
        )
        item_still_same = (
            not esc.item_digest or _file_digest(root, esc.item) == esc.item_digest
        )
        if contract_still_same and item_still_same:
            blocked.add(esc.package)
    return frozenset(blocked), ""

step_fingerprint

step_fingerprint(record: StepRecord, ctx: PhaseContext, target: str, *, cache: FingerprintContext | None = None) -> str

Deterministic SHA-256 fingerprint of what record reads on target.

Source code in packages/workshop/src/livery/workshop/_proved.py
def step_fingerprint(
    record: StepRecord,
    ctx: PhaseContext,
    target: str,
    *,
    cache: FingerprintContext | None = None,
) -> str:
    """Deterministic SHA-256 fingerprint of what *record* reads on *target*."""
    from livery.workshop._extensions import extension_provider
    from livery.workshop._steps import option_value

    fp_cache = (
        cache
        if cache is not None
        else FingerprintContext.for_root(ctx.root, ctx.packages)
    )
    hasher = hashlib.sha256()

    def feed(tag: str, value: str) -> None:
        hasher.update(f"{tag}:{value}\n".encode())

    feed("schema", str(SCHEMA))
    feed("step", record.name)
    feed("scope", record.scope)
    feed("target", target)
    feed("extension", record.extension)

    # Pinned tool versions.
    for tool in sorted(record.tools):
        feed(f"tool:{tool}", fp_cache.tool_version(tool))

    # Provider's own code or uv.lock for installed tools.
    provider = extension_provider(record.extension, ctx.packages)
    if provider:
        prefix = f"{provider}/src/"
        for path in fp_cache.files:
            if path.startswith(prefix):
                feed(f"provider:{path}", fp_cache.digest(path))
    else:
        feed("lock:uv.lock", fp_cache.digest("uv.lock"))

    # Step options for the target package (if package target).
    package = next((p for p in ctx.packages if p.path == target), None)
    if package is not None:
        feed("opt:enabled", str(option_value(record, package, "enabled")))
        for opt in sorted(record.options, key=lambda o: o.name):
            feed(f"opt:{opt.name}", repr(option_value(record, package, opt.name)))

    # Matched files and their content digests.
    for path in _matched_files(record, target, fp_cache):
        feed(f"file:{path}", fp_cache.digest(path))

    # Package targets also depend on root workspace configuration and upstream
    # workspace dependencies (so changing a dependency's source invalidates its
    # consumers without invalidating unrelated packages).
    if target != ".":
        from livery.workshop._packages import WORKSPACE_TESTS

        for path in fp_cache.root_config_files():
            feed(f"root:{path}", fp_cache.digest(path))
        dep_targets = (
            tuple(sorted(p.path for p in ctx.packages))
            if target == WORKSPACE_TESTS
            else fp_cache.dependency_paths(target)
        )
        for dep in dep_targets:
            for path in fp_cache.dependency_files(dep):
                feed(f"dep:{path}", fp_cache.digest(path))

    return hasher.hexdigest()

proving_branch

proving_branch(root: Path, *, store: StateStore | None = None) -> tuple[str, str]

Return (branch, reason) for the pull request branch proving root's tree.

Scans proved/main/* and lingering proved/<branch>/* refs for the newest green entry naming a non-main branch whose recorded fingerprint matches a current judge unit on root (or whose SHA matches HEAD when no registered step matches). Returns ("", reason) when the store cannot be listed.

Source code in packages/workshop/src/livery/workshop/_proved.py
def proving_branch(
    root: Path, *, store: git.StateStore | None = None
) -> tuple[str, str]:
    """Return ``(branch, reason)`` for the pull request branch proving *root*'s tree.

    Scans ``proved/main/*`` and lingering ``proved/<branch>/*`` refs for the
    newest green entry naming a non-main branch whose recorded fingerprint
    matches a current judge unit on *root* (or whose SHA matches ``HEAD``
    when no registered step matches). Returns ``("", reason)`` when the store
    cannot be listed.
    """
    from livery.footman import Failed
    from livery.workshop import _steps
    from livery.workshop._ci_context import state_store
    from livery.workshop._packages import discover_packages
    from livery.workshop._phases import PhaseContext
    from livery.workshop._shard import ONE

    target_store = state_store(root) if store is None else store
    keys = FAMILY.listed(target_store)
    if keys is None:
        return "", "proved: keys could not be listed"
    if not keys:
        return "", ""
    try:
        packages = discover_packages(root)
    except ValueError:
        packages = ()
    try:
        head = git.head_sha(root)
    except git.GitError:
        head = ""
    fp_cache = FingerprintContext.for_root(root, packages)
    ctx = PhaseContext(root=root, packages=packages, point="gate", shard=ONE)
    computed_fps: dict[tuple[str, str], str] = {}

    def _current_fp(step_name: str, target: str) -> str:
        key = (step_name, target)
        if key not in computed_fps:
            try:
                record = _steps.step_for(step_name)
            except (KeyError, Failed):
                computed_fps[key] = ""
            else:
                computed_fps[key] = step_fingerprint(
                    record, ctx, target, cache=fp_cache
                )
        return computed_fps[key]

    best_when = ""
    best_branch = ""
    for base_key, leg_name in keys:
        found = FAMILY.at(base_key, leg_name).rows(target_store)
        if found.failed:
            continue
        for raw in found.rows:
            row = UnitRow.from_dict(raw.data)
            for entry in row.entries:
                if not entry.branch or entry.branch == MAIN:
                    continue
                if entry.counts.get(GREEN, 0) <= 0 or entry.flaky:
                    continue
                if entry.when < best_when:
                    continue
                expected_fp = _current_fp(row.step, row.target)
                matched = (bool(expected_fp) and entry.fingerprint == expected_fp) or (
                    not expected_fp and bool(head) and entry.sha == head
                )
                if matched:
                    best_when = entry.when
                    best_branch = entry.branch
    return best_branch, ""

proved_unit_key

proved_unit_key(root: Path, packages: Sequence[Package], target: str, *, phase: str = 'test', cache: FingerprintContext | None = None) -> str

Return the proved row key for target's registered steps in phase.

When a single registered step in phase judges target (the common case), returns its exact step_fingerprint. When multiple steps in phase judge target, returns a SHA-256 digest over their sorted step=fingerprint pairs. Returns "" when no step in phase applies to target.

Source code in packages/workshop/src/livery/workshop/_proved.py
def proved_unit_key(
    root: Path,
    packages: Sequence[Package],
    target: str,
    *,
    phase: str = "test",
    cache: FingerprintContext | None = None,
) -> str:
    """Return the proved row key for *target*'s registered steps in *phase*.

    When a single registered step in *phase* judges *target* (the common case),
    returns its exact `step_fingerprint`. When multiple steps in *phase* judge
    *target*, returns a SHA-256 digest over their sorted ``step=fingerprint``
    pairs. Returns ``""`` when no step in *phase* applies to *target*.
    """
    return proved_unit_keys(root, packages, (target,), phase=phase, cache=cache).get(
        target, ""
    )

proved_unit_keys

proved_unit_keys(root: Path, packages: Sequence[Package], targets: Sequence[str], *, phase: str = 'test', cache: FingerprintContext | None = None) -> dict[str, str]

Return a target -> proved row key mapping for targets in phase.

Computes one shared FingerprintContext across all targets so callers measuring or unioning a whole workspace hash each file once.

Source code in packages/workshop/src/livery/workshop/_proved.py
def proved_unit_keys(
    root: Path,
    packages: Sequence[Package],
    targets: Sequence[str],
    *,
    phase: str = "test",
    cache: FingerprintContext | None = None,
) -> dict[str, str]:
    """Return a ``target -> proved row key`` mapping for *targets* in *phase*.

    Computes one shared `FingerprintContext` across all *targets* so callers
    measuring or unioning a whole workspace hash each file once.
    """
    from livery.workshop import _steps
    from livery.workshop._packages import WORKSPACE_TESTS, workspace_suite
    from livery.workshop._phases import PhaseContext

    if not targets:
        return {}
    phase_steps = sorted(
        (rec for rec in _steps.steps_by_name().values() if rec.phase == phase),
        key=lambda rec: rec.name,
    )
    if not phase_steps:
        return dict.fromkeys(targets, "")
    pkg_tuple = tuple(packages)
    by_path = {pkg.path: pkg for pkg in pkg_tuple}
    suite = workspace_suite(root)
    applicable: dict[str, list[StepRecord]] = {}
    for target in targets:
        if target == WORKSPACE_TESTS:
            matched = (
                [
                    rec
                    for rec in phase_steps
                    if rec.scope != _steps.PACKAGE and _steps.judges_unit(rec, suite)
                ]
                if suite is not None
                else []
            )
        else:
            pkg = by_path.get(target)
            matched = (
                [rec for rec in phase_steps if _steps.judges_unit(rec, pkg)]
                if pkg is not None
                else []
            )
        applicable[target] = matched
    if not any(applicable.values()):
        return dict.fromkeys(targets, "")
    fp_cache = (
        cache if cache is not None else FingerprintContext.for_root(root, pkg_tuple)
    )
    ctx = PhaseContext(root=root, packages=pkg_tuple)
    result: dict[str, str] = {}
    for target in targets:
        recs = applicable[target]
        if not recs:
            result[target] = ""
            continue
        fps = [
            (rec.name, step_fingerprint(rec, ctx, target, cache=fp_cache))
            for rec in recs
        ]
        if len(fps) == 1:
            result[target] = fps[0][1]
        else:
            digest = hashlib.sha256(
                "\n".join(f"{name}={fp}" for name, fp in fps).encode("utf-8")
            ).hexdigest()
            result[target] = digest
    return result

base_proved

base_proved(root: Path, base: str, *, store: StateStore | None = None) -> tuple[bool, str]

Whether proved/main/* already has green rows for origin/<base>'s tip.

Source code in packages/workshop/src/livery/workshop/_proved.py
def base_proved(
    root: Path, base: str, *, store: git.StateStore | None = None
) -> tuple[bool, str]:
    """Whether ``proved/main/*`` already has green rows for ``origin/<base>``'s tip."""
    from livery.workshop._ci_context import state_store
    from livery.workshop._points import check_legs

    try:
        sha = git.remote_head(root, base)
    except git.GitError as error:
        return False, str(error)
    if not sha:
        return False, f"no commit at origin/{base}"
    target_store = state_store(root) if store is None else store
    legs = check_legs(root)
    if not legs:
        return False, ""
    for leg in legs:
        found = FAMILY.series(MAIN, git.slug(leg)).rows(target_store)
        if found.failed:
            return False, found.reason
        if not any(
            entry.sha == sha and entry.counts.get(GREEN, 0) > 0 and not entry.flaky
            for raw in found.rows
            for entry in UnitRow.from_dict(raw.data).entries
        ):
            return False, ""
    return True, ""

head_tree_id

head_tree_id(root: Path) -> str

Return the git tree object id of HEAD:, or "" on error.

Source code in packages/workshop/src/livery/workshop/_proved.py
def head_tree_id(root: Path) -> str:
    """Return the git tree object id of ``HEAD:``, or ``""`` on error."""
    try:
        return git.run(root, "rev-parse", "HEAD:").strip()
    except git.GitError:
        return ""

tree_row_name

tree_row_name(tree_id: str) -> str

Stable row filename on TREES for git tree hash tree_id.

Source code in packages/workshop/src/livery/workshop/_proved.py
def tree_row_name(tree_id: str) -> str:
    """Stable row filename on `TREES` for git tree hash *tree_id*."""
    return f"{tree_id}.json"

read_proved_tree

read_proved_tree(root: Path, tree_id: str, *, store: StateStore | None = None) -> tuple[ProvedTree | None, str]

Look up a green ProvedTree stamp for tree_id; (None, "") if absent.

Source code in packages/workshop/src/livery/workshop/_proved.py
def read_proved_tree(
    root: Path,
    tree_id: str,
    *,
    store: git.StateStore | None = None,
) -> tuple[ProvedTree | None, str]:
    """Look up a green `ProvedTree` stamp for *tree_id*; ``(None, "")`` if absent."""
    if not tree_id:
        return None, ""
    from livery.workshop._ci_context import state_store

    target_store = state_store(root) if store is None else store
    found, why = TREES.row(target_store, tree_row_name(tree_id))
    if why:
        return None, why
    if found is None:
        return None, ""
    parsed = ProvedTree.from_dict(found.data, when=found.when)
    if parsed is None or parsed.tree != tree_id:
        return None, ""
    return parsed, ""

stamp_proved_tree

stamp_proved_tree(root: Path, *, tree_id: str, branch: str, run_id: str, sha: str, legs: Sequence[str], store: StateStore | None = None) -> str

Record tree_id as proved green across legs on TREES; "" or reason.

Source code in packages/workshop/src/livery/workshop/_proved.py
def stamp_proved_tree(
    root: Path,
    *,
    tree_id: str,
    branch: str,
    run_id: str,
    sha: str,
    legs: Sequence[str],
    store: git.StateStore | None = None,
) -> str:
    """Record *tree_id* as proved green across *legs* on `TREES`; ``""`` or reason."""
    if not tree_id:
        return "no git tree id for HEAD"
    normalized_legs = tuple(sorted({leg for leg in legs if leg}))
    if not normalized_legs:
        return "no check legs to stamp"
    from livery.workshop._ci_context import state_store

    target_store = state_store(root) if store is None else store
    record = ProvedTree(
        tree=tree_id,
        branch=MAIN if branch == MAIN else git.slug(branch),
        run=run_id,
        sha=sha,
        legs=normalized_legs,
    )
    return TREES.put(
        target_store,
        {tree_row_name(tree_id): record.to_dict()},
        message=f"proved: tree {tree_id[:12]} ({len(normalized_legs)} leg(s))",
    )

sweep_proved_store

sweep_proved_store(root: Path, *, dry_run: bool = False, now: datetime | None = None, store: StateStore | None = None) -> list[str]

Prune unreferenced reads/ blobs and expired proved-parts kept rows.

Runs inside the janitor's remote snapshot. Each proved/<base>/<leg> ref reads only its unit rows (never decompressing reads/ blobs) and drops any reads/<digest>.json blob no live row's entries reference. Each proved-parts/<ext>/<base>/<leg> ref inspects filenames alone and drops kept rows older than PARTS_KEPT_FOR. All rewrites land in a single OID-preserving git.merge_refs batch push.

Source code in packages/workshop/src/livery/workshop/_proved.py
def sweep_proved_store(
    root: Path,
    *,
    dry_run: bool = False,
    now: datetime | None = None,
    store: git.StateStore | None = None,
) -> list[str]:
    """Prune unreferenced ``reads/`` blobs and expired ``proved-parts`` kept rows.

    Runs inside the janitor's remote snapshot. Each ``proved/<base>/<leg>`` ref
    reads only its unit rows (never decompressing ``reads/`` blobs) and drops
    any ``reads/<digest>.json`` blob no live row's entries reference. Each
    ``proved-parts/<ext>/<base>/<leg>`` ref inspects filenames alone and drops
    kept rows older than `PARTS_KEPT_FOR`. All rewrites land in a single
    OID-preserving `git.merge_refs` batch push.
    """
    from livery.workshop._ci_context import state_store

    moment = now or datetime.now(UTC)
    target_store = state_store(root) if store is None else store
    verb = "would drop" if dry_run else "dropped"
    lines: list[str] = []
    ops: list[git.RefMerge] = []

    def _make_drop(
        drop_set: frozenset[str],
    ) -> Callable[
        [dict[str, bytes], dict[str, bytes], Callable[[bytes], str]],
        tuple[dict[str, bytes], dict[str, str]],
    ]:
        def _drop_entries(
            existing: dict[str, bytes],
            _incoming: dict[str, bytes],
            _read: Callable[[bytes], str],
        ) -> tuple[dict[str, bytes], dict[str, str]]:
            return {k: v for k, v in existing.items() if k not in drop_set}, {}

        return _drop_entries

    proved_keys = FAMILY.listed(target_store)
    for key in proved_keys or ():
        series = FAMILY.at(*key)
        found = series.rows(
            target_store, only=lambda name: not name.startswith(READS_PREFIX)
        )
        if found.failed or found.skipped:
            continue
        referenced = {
            read_set_blob_name(entry.read_set)
            for raw in found.rows
            for entry in UnitRow.from_dict(raw.data).entries
            if entry.read_set
        }
        orphans = frozenset(
            name
            for name in found.unread
            if name.startswith(READS_PREFIX) and name not in referenced
        )
        if orphans:
            lines.append(
                f"  {series.ref}: {verb} {len(orphans)} unreferenced read-set blob(s)"
            )
            ops.append(
                git.RefMerge(
                    source=series.ref,
                    target=series.ref,
                    message=f"proved: prune {len(orphans)} unreferenced read-set(s)",
                    merge=_make_drop(orphans),
                )
            )

    parts_keys = PROVED_PARTS.listed(target_store)
    for key in parts_keys or ():
        series = PROVED_PARTS.at(*key)
        found = series.rows(target_store, only=lambda _name: False)
        if found.failed:
            continue
        expired = frozenset(
            name for name in found.unread if _is_expired_kept_part(name, moment)
        )
        if expired:
            lines.append(f"  {series.ref}: {verb} {len(expired)} expired kept part(s)")
            ops.append(
                git.RefMerge(
                    source=series.ref,
                    target=series.ref,
                    message=f"proved-parts: prune {len(expired)} expired kept row(s)",
                    merge=_make_drop(expired),
                )
            )

    if ops and not dry_run:
        why = git.merge_refs(target_store, ops, ci_only=True)
        if why:
            lines.append(f"  proved sweep: {why}")
    return lines

promote_proved_tree_to_main

promote_proved_tree_to_main(root: Path, proved_tree: ProvedTree, *, expected_legs: Sequence[str], store: StateStore | None = None) -> tuple[bool, str]

Promote branch proved rows and extension proved-parts to main.

Merges proved/<branch>/<leg> into proved/main/<leg> and every extension's proved-parts/<ext>/<branch>/<leg> into proved-parts/<ext>/main/<leg> for each leg in expected_legs in one OID-preserving batch push. Returns (True, "") when already on main or when every ref promotes cleanly; returns (False, reason) on any store read/write failure so callers fail open and run checks normally.

Source code in packages/workshop/src/livery/workshop/_proved.py
def promote_proved_tree_to_main(
    root: Path,
    proved_tree: ProvedTree,
    *,
    expected_legs: Sequence[str],
    store: git.StateStore | None = None,
) -> tuple[bool, str]:
    """Promote branch proved rows and extension proved-parts to ``main``.

    Merges ``proved/<branch>/<leg>`` into ``proved/main/<leg>`` and every
    extension's ``proved-parts/<ext>/<branch>/<leg>`` into
    ``proved-parts/<ext>/main/<leg>`` for each leg in *expected_legs* in one
    OID-preserving batch push. Returns ``(True, "")`` when already on ``main``
    or when every ref promotes cleanly; returns ``(False, reason)`` on any
    store read/write failure so callers fail open and run checks normally.
    """
    if proved_tree.branch == MAIN:
        return True, ""
    from livery.workshop._ci_context import state_store
    from livery.workshop._shard import platform_leg

    target_store = state_store(root) if store is None else store
    branch_slug = git.slug(proved_tree.branch)
    leg_slugs = sorted({git.slug(platform_leg(leg)) for leg in expected_legs if leg})
    if not leg_slugs:
        return True, ""

    # Discover which extensions hold proved-parts for this branch and legs.
    parts_keys = PROVED_PARTS.listed(target_store)
    if parts_keys is None:
        return False, "proved-parts refs could not be listed"
    matching_parts = sorted(
        (ext, leg_slug)
        for ext, base, leg_slug in parts_keys
        if base == branch_slug and leg_slug in leg_slugs
    )

    prefixes: list[str] = []
    for leg_slug in leg_slugs:
        prefixes.append(f"{FAMILY.name}/{branch_slug}/{leg_slug}")
        prefixes.append(f"{FAMILY.name}/{MAIN}/{leg_slug}")
    for ext, leg_slug in matching_parts:
        prefixes.append(f"{PROVED_PARTS.name}/{ext}/{branch_slug}/{leg_slug}")
        prefixes.append(f"{PROVED_PARTS.name}/{ext}/{MAIN}/{leg_slug}")

    stamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")

    def _merge_units(
        existing: dict[str, bytes],
        incoming: dict[str, bytes],
        read_text: Callable[[bytes], str],
    ) -> tuple[dict[str, bytes], dict[str, str]]:
        return _merge_unit_entries_for_promotion(
            existing, incoming, read_text, keep=KEEP_READ_SETS
        )

    def _merge_parts(
        existing: dict[str, bytes],
        incoming: dict[str, bytes],
        read_text: Callable[[bytes], str],
    ) -> tuple[dict[str, bytes], dict[str, str]]:
        return _merge_parts_entries_for_promotion(
            existing, incoming, read_text, stamp=stamp
        )

    ops: list[git.RefMerge] = [
        git.RefMerge(
            source=FAMILY.at(branch_slug, leg_slug).ref,
            target=FAMILY.at(MAIN, leg_slug).ref,
            message=(
                f"proved: promote {branch_slug} ({proved_tree.tree[:12]})"
                f" to main on {leg_slug}"
            ),
            merge=_merge_units,
        )
        for leg_slug in leg_slugs
    ]
    ops.extend(
        git.RefMerge(
            source=PROVED_PARTS.at(ext, branch_slug, leg_slug).ref,
            target=PROVED_PARTS.at(ext, MAIN, leg_slug).ref,
            message=(
                f"proved-parts({ext}): promote {branch_slug}"
                f" ({proved_tree.tree[:12]}) to main on {leg_slug}"
            ),
            merge=_merge_parts,
        )
        for ext, leg_slug in matching_parts
    )

    with git.remote_snapshot(target_store, fetch=tuple(dict.fromkeys(prefixes))):
        why = git.merge_refs(target_store, ops, ci_only=True)
        if why:
            return False, why

    return True, ""