Skip to content

livery.workshop._env_tasks

livery.workshop._env_tasks

The env group: enter, show, set, and verify the environment.

The cascade (livery.workshop._envfile) is the one config mechanism; this module is every way it reaches a consumer: applied to each fm run (a pre-tasks hook, environment always winning), emitted for a shell or an agent or GitHub Actions, shown masked, set scoped, and verified against the tool profile the present package types derive.

Every task here repairs or diagnoses the environment, so none carries an availability gate: they must run on a cold checkout.

Classes:

Name Description
EnvDelta

What entering the environment adds: variables and PATH entries.

Functions:

Name Description
apply_cascade

Fold the cascade into this run's environment; environment wins.

apply_declared

Set the variables the extensions of root's set declare into environ.

sync_first

Bring the checkout current before the command's first task runs.

apply_entry

Enter the venv and the receipts' tools into environ.

runner_placements

What a GitHub job places under the runner's temp: its caches and variables.

with_runner_placements

delta with the runner's placements for a GitHub job, unchanged elsewhere.

windows_temp_policy

The contract's [ci] windows-temp, or the forge kind's default.

with_runner_temp

delta with TEMP and TMP under the runner's temp on a Windows leg.

venv_bin

The venv's executables directory: Scripts on Windows, bin elsewhere.

workspace_delta

The delta an entered shell needs for this workspace.

emit_lines

Serialise delta for dialect (posix or pwsh).

agent_delta

The variables an agent session needs, selected by membership.

rung_file

Write the secrets the entry step carries into the shared slot's file.

github_persist

Append delta to GITHUB_ENV and GITHUB_PATH; what was written.

env_emit

Emit the environment for evaluation by a shell.

env_show

Show the cascade: sources, values, and the PATH breakdown.

env_set

Set or delete one variable in the chosen scope's file.

tool_profile

The tools the declaration sites require on this host, each once.

served_by

Who serves receipt's tool: the host at the version it printed, or the store.

missing_host_tools

The tools the workspace's packages need from the host that do not resolve.

env_check

Verify this shell against the tools the sites require.

Attributes:

Name Type Description
NEVER_AGENT
env
WINDOWS_TEMP_VALUES
START_PATH_VARIABLE

NEVER_AGENT module-attribute

NEVER_AGENT = ('PATH',)

env module-attribute

env = group('env', help='The environment: enter, show, set, verify')

WINDOWS_TEMP_VALUES module-attribute

WINDOWS_TEMP_VALUES = ('runner', 'system')

START_PATH_VARIABLE module-attribute

START_PATH_VARIABLE = 'WORKSHOP_START_PATH_FILE'

EnvDelta dataclass

EnvDelta(values: dict[str, str] = dict(), paths: tuple[str, ...] = ())

What entering the environment adds: variables and PATH entries.

Attributes:

Name Type Description
values dict[str, str]
paths tuple[str, ...]

values class-attribute instance-attribute

values: dict[str, str] = field(default_factory=dict)

paths class-attribute instance-attribute

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

apply_cascade

apply_cascade(inv: Invocation) -> None

Fold the cascade into this run's environment; environment wins.

Every fm command sees the repo's declared environment, so a cold shell still runs with the tokens and settings the files hold. Only absent keys are written, and what the hook itself contributed is remembered: those values look pre-existing to a later load, and the emitters must not misread them as the shell's own. The variables the workspace's extensions declare follow (apply_declared).

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
@pre_tasks
def apply_cascade(inv: footman.Invocation) -> None:
    """Fold the cascade into this run's environment; environment wins.

    Every ``fm`` command sees the repo's declared environment, so a
    cold shell still runs with the tokens and settings the files
    hold. Only absent keys are written, and what the hook itself
    contributed is remembered: those values look pre-existing to a
    later load, and the emitters must not misread them as the
    shell's own. The variables the workspace's extensions declare
    follow (`apply_declared`).
    """
    from livery.workshop._extensions import workspace_root

    _ = inv
    _APPLIED.clear()
    root = workspace_root()
    if root is None:
        return
    stack = load_cascade(root, Path.cwd())
    for key, value in stack.managed().items():
        # Truthiness, not presence, matches the cascade's own
        # env-wins rule: a key exported empty reads as unset.
        if not os.environ.get(key):
            os.environ[key] = value
            _APPLIED[key] = value
    apply_declared(root, os.environ)
    # The tools' half of the entry contract: whatever launched this
    # process, it runs entered.
    apply_entry(root, os.environ)
    _warn_unmounted_extensions(root)

apply_declared

apply_declared(root: Path, environ: MutableMapping[str, str]) -> dict[str, str]

Set the variables the extensions of root's set declare into environ.

On a CI job a value naming {place} takes the job's own directory: RUNNER_TEMP on a GitHub or Gitea job, .workshop under CI_PROJECT_DIR on a GitLab one. Off a CI job it is not set, and a desk keeps its own. A variable environ already carries keeps its value, its declaration's always included: the job's entry already placed it where the job's environment was formed, and a nested run keeps the value its parent set. The cascade's files count as the environment here, since they are folded in first. What the hook contributes is remembered in _APPLIED. A declaration that cannot be read costs these variables alone, said on stderr, never the command: the mount and fm sync name it.

Returns:

Type Description
dict[str, str]

The variables written, each to its value.

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
def apply_declared(root: Path, environ: MutableMapping[str, str]) -> dict[str, str]:
    """Set the variables the extensions of *root*'s set declare into *environ*.

    On a CI job a value naming ``{place}`` takes the job's own
    directory: ``RUNNER_TEMP`` on a GitHub or Gitea job, ``.workshop``
    under ``CI_PROJECT_DIR`` on a GitLab one. Off a CI job it is not
    set, and a desk keeps its own. A variable *environ* already
    carries keeps its value, its declaration's ``always`` included: the
    job's entry already placed it where the job's environment was
    formed, and a nested run keeps the value its parent set. The
    cascade's files count as the environment here, since they are folded
    in first. What the hook contributes is remembered in `_APPLIED`. A
    declaration that cannot be read costs these variables alone, said on
    stderr, never the command: the mount and ``fm sync`` name it.

    Returns:
        The variables written, each to its value.
    """
    import sys

    from livery.footman import Failed
    from livery.workshop._declaration import DeclarationError
    from livery.workshop._variables import job_place, placed, workspace_variables

    try:
        variables = workspace_variables(root)
    except (DeclarationError, Failed) as error:
        sys.stderr.write(f"declared variables skipped ({error})\n")
        return {}
    written: dict[str, str] = {}
    for key, value in placed(variables, job_place(environ), environ).items():
        if environ.get(key) != value:
            environ[key] = value
            _APPLIED[key] = value
            written[key] = value
    return written

sync_first

sync_first(inv: Invocation, task: Any) -> None

Bring the checkout current before the command's first task runs.

Once per process, at the first task's per-task moment, which is inside the run: discovery also runs in the child that rebuilds the completion manifest, where a sync would run on a Tab press. The sync runs on the workspace above the task's directory and decides from the checkout's receipts (livery.workshop._reconcile.apply); the steps it runs are recorded as the task's own. A sync that wrote receipts this process entered without enters again, into the task's own environment, task.env: the task's body, the processes it starts and the tasks it calls read it. Never os.environ: inside a task footman notes that write as a misuse, and a workspace's notes policy can fail the task for it.

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
@pre_task
def sync_first(inv: footman.Invocation, task: Any) -> None:
    """Bring the checkout current before the command's first task runs.

    Once per process, at the first task's per-task moment, which is
    inside the run: discovery also runs in the child that rebuilds the
    completion manifest, where a sync would run on a Tab press. The
    sync runs on the workspace above the task's directory and decides
    from the checkout's receipts ([livery.workshop._reconcile.apply][]);
    the steps it runs are recorded as the task's own. A sync that wrote
    receipts this process entered without enters again, into the
    task's own environment, `task.env`: the task's body, the processes
    it starts and the tasks it calls read it. Never `os.environ`: inside
    a task footman notes that write as a misuse, and a workspace's notes
    policy can fail the task for it.
    """
    from livery.workshop._extensions import workspace_root

    _ = inv
    if _SYNCED:
        return
    _SYNCED.append(True)
    root = workspace_root()
    if root is None:
        return
    # Belt and braces around the whole self-healing step: a raising
    # pre-task hook fails the task, so nothing short of a deliberate
    # SystemExit (the re-run handoff, which derives from
    # BaseException) may escape it.
    try:
        from livery.workshop import _reconcile

        if _reconcile.is_cli_process() and _reconcile.apply(
            root, str(task.name), task.env
        ):
            apply_entry(root, task.env)
    except Exception as error:
        import sys

        sys.stderr.write(f"environment sync skipped ({error})\n")

apply_entry

apply_entry(root: Path, environ: MutableMapping[str, str]) -> tuple[str, ...]

Enter the venv and the receipts' tools into environ.

The same PATH entries and variables env.emit hands an entered shell, so every fm invocation resolves the locked tools whatever launched it: an agent's shell, a CI step, a bare terminal. The cascade hook enters the process environment before the run starts, and every task starts from it; the per-task hook enters a task's own environment (livery.workshop._env_tasks.sync_first). The emission leads PATH in its own order, the venv's bin first and the tools after it, and the rest of PATH follows; an entry the emission names moves to its place in front, since a tool directory ahead of the venv would shadow the venv's pytest and mypy with the store's plain ones. A variable environ already has wins, as the cascade's do, and what the hook contributes is remembered in _APPLIED. A receipts directory holding a file that is not a receipt costs the tools' half alone, said on stderr, never the command. Idempotent: a second application changes nothing.

Returns:

Type Description
tuple[str, ...]

The PATH entries that were not on PATH before, in order.

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
def apply_entry(root: Path, environ: MutableMapping[str, str]) -> tuple[str, ...]:
    """Enter the venv and the receipts' tools into *environ*.

    The same PATH entries and variables `env.emit` hands an entered
    shell, so every `fm` invocation resolves the locked tools whatever
    launched it: an agent's shell, a CI step, a bare terminal. The
    cascade hook enters the process environment before the run starts,
    and every task starts from it; the per-task hook enters a task's
    own environment ([livery.workshop._env_tasks.sync_first][]). The
    emission leads PATH in its own order, the venv's bin first and the
    tools after it, and the rest of PATH follows; an entry the emission
    names moves to its place in front, since a tool directory ahead of
    the venv would shadow the venv's pytest and mypy with the store's
    plain ones. A variable *environ* already has wins, as the cascade's
    do, and what the hook contributes is remembered in `_APPLIED`. A
    receipts directory holding a file that is not a receipt costs the
    tools' half alone, said on stderr, never the command. Idempotent: a
    second application changes nothing.

    Returns:
        The PATH entries that were not on PATH before, in order.
    """
    import sys

    try:
        paths, env = _receipts_emission(root)
    except ValueError as error:
        sys.stderr.write(f"tool receipts skipped ({error})\n")
        paths, env = (), {}
    current = [e for e in environ.get("PATH", "").split(os.pathsep) if e]
    leading: list[str] = []
    seen: set[str] = set()
    for entry in (str(venv_bin(root)), *paths):
        if os.path.normcase(entry) not in seen:
            leading.append(entry)
            seen.add(os.path.normcase(entry))
    added = tuple(
        e
        for e in leading
        if os.path.normcase(e) not in {os.path.normcase(c) for c in current}
    )
    rest = [c for c in current if os.path.normcase(c) not in seen]
    composed = os.pathsep.join([*leading, *rest])
    if composed != environ.get("PATH", ""):
        environ["PATH"] = composed
    values = {"VIRTUAL_ENV": str(root / ".venv"), **env}
    for key, value in values.items():
        if not environ.get(key):
            environ[key] = value
            _APPLIED[key] = value
    return added

runner_placements

runner_placements(environ: dict[str, str], variables: Iterable[DeclaredVariable] = ()) -> dict[str, str]

What a GitHub job places under the runner's temp: its caches and variables.

The runner's temp is the working drive, where the checkout and the venv are; on a Windows runner the home directory is another drive, and a tool store there cannot hardlink into the checkout, nor uv's cache into the venv. The entry script exports the same paths before its sync and materialise, since it runs before any verb can; the workflow's cache step restores and saves the store under the data directory. Empty off a runner that names no temp.

uv's cache and the data directory take many processes at once, so a key the job's environment already sets keeps its value, and that value is what gets persisted: a runner with a persistent cache sets the key for every step and loses nothing, and the entry script, which exports the same keys for its own sync before it asks for the emission, hands them on to the steps after it, where an export of a step's shell never reaches by itself.

variables are the ones the workspace's extensions declare, which apply_declared sets for each run where the environment carries none. A value naming {place} takes the runner's temp, which is the job's own. The emission forms the environment of the job's later steps, so an always one beats a value the runner sets for every job.

Raises:

Type Description
Failed

when one of variables names {place} on a job (GITHUB_ACTIONS set) whose runner names no RUNNER_TEMP, or when RUNNER_TEMP names no directory, naming each such variable and the extension that declares it: the job then has no directory of its own to keep it in.

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
def runner_placements(
    environ: dict[str, str], variables: Iterable[DeclaredVariable] = ()
) -> dict[str, str]:
    """What a GitHub job places under the runner's temp: its caches and *variables*.

    The runner's temp is the working drive, where the checkout and the
    venv are; on a Windows runner the home directory is another drive,
    and a tool store there cannot hardlink into the checkout, nor uv's
    cache into the venv. The entry script exports the same paths
    before its sync and materialise, since it runs before any verb
    can; the workflow's cache step restores and saves the store under
    the data directory. Empty off a runner that names no temp.

    uv's cache and the data directory take many processes at once, so
    a key the job's environment already sets keeps its value, and that
    value is what gets persisted: a runner with a persistent cache sets
    the key for every step and loses nothing, and the entry script,
    which exports the same keys for its own sync before it asks for
    the emission, hands them on to the steps after it, where an export
    of a step's shell never reaches by itself.

    *variables* are the ones the workspace's extensions declare, which
    `apply_declared` sets for each run where the environment carries
    none. A value naming ``{place}`` takes the runner's temp, which is
    the job's own. The emission forms the environment of the job's later
    steps, so an ``always`` one beats a value the runner sets for every
    job.

    Raises:
        Failed: when one of *variables* names ``{place}`` on a job
            (``GITHUB_ACTIONS`` set) whose runner names no
            ``RUNNER_TEMP``, or when ``RUNNER_TEMP`` names no directory,
            naming each such variable and the extension that declares
            it: the job then has no directory of its own to keep it in.
    """
    from livery.footman import directory_variable
    from livery.workshop._variables import declarers, placed

    held = tuple(variables)
    needing = declarers(variable for variable in held if variable.placed)
    runner_temp = environ.get("RUNNER_TEMP", "")
    if not runner_temp:
        if environ.get("GITHUB_ACTIONS") and needing:
            fail(
                f"this job's runner sets no RUNNER_TEMP: {needing} in a directory"
                " of the job's own, so run it on a runner that sets one"
            )
        return {}
    if needing and not Path(runner_temp).is_dir():
        fail(
            f"RUNNER_TEMP names {runner_temp}, which is not a directory: {needing}"
            " in it, so its runner must create it first"
        )
    shared = {
        "UV_CACHE_DIR": f"{runner_temp}/uv-cache",
        directory_variable("DATA_DIR"): f"{runner_temp}/footman",
    }
    found = {key: environ.get(key) or value for key, value in shared.items()}
    found.update(placed(held, runner_temp, environ, forming=True))
    return found

with_runner_placements

with_runner_placements(delta: EnvDelta, environ: dict[str, str], variables: Iterable[DeclaredVariable] = ()) -> EnvDelta

delta with the runner's placements for a GitHub job, unchanged elsewhere.

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
def with_runner_placements(
    delta: EnvDelta, environ: dict[str, str], variables: Iterable[DeclaredVariable] = ()
) -> EnvDelta:
    """*delta* with the runner's placements for a GitHub job, unchanged elsewhere."""
    found = runner_placements(environ, variables)
    if not found:
        return delta
    return EnvDelta(values={**delta.values, **found}, paths=delta.paths)

windows_temp_policy

windows_temp_policy(root: Path) -> str

The contract's [ci] windows-temp, or the forge kind's default.

runner for a GitHub-shaped workspace: GitHub's hosted Windows runners keep the workspace, the uv cache, and the runner's temp on the fast working drive and the system temp on the slow system drive. system for every other forge, whose runners are the workspace's own. A value that is neither refuses naming both.

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
def windows_temp_policy(root: Path) -> str:
    """The contract's ``[ci] windows-temp``, or the forge kind's default.

    ``runner`` for a GitHub-shaped workspace: GitHub's hosted Windows
    runners keep the workspace, the uv cache, and the runner's temp on
    the fast working drive and the system temp on the slow system
    drive. ``system`` for every other forge, whose runners are the
    workspace's own. A value that is neither refuses naming both.
    """
    from livery.workshop._contract import load_contract

    contract = load_contract(root / "workshop.toml")
    value = (contract.get("ci") or {}).get("windows-temp")
    if value is None:
        kind = str((contract.get("forge") or {}).get("kind", ""))
        return "runner" if kind == "github" else "system"
    if value not in WINDOWS_TEMP_VALUES:
        fail(
            f"[ci] windows-temp is {value!r}; it is one of"
            f" {', '.join(WINDOWS_TEMP_VALUES)}"
        )
    return str(value)

with_runner_temp

with_runner_temp(delta: EnvDelta, root: Path, environ: dict[str, str], *, platform: str = '') -> tuple[EnvDelta, str]

delta with TEMP and TMP under the runner's temp on a Windows leg.

The tests' files and the environments they build with uv then share the working drive with the uv cache, which the runner keeps under its temp, so uv links instead of copying. Returns the delta and one line saying what happened. Nothing changes off Windows, under the system policy, or when the runner names no RUNNER_TEMP; the last two say so.

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
def with_runner_temp(
    delta: EnvDelta,
    root: Path,
    environ: dict[str, str],
    *,
    platform: str = "",
) -> tuple[EnvDelta, str]:
    """*delta* with ``TEMP`` and ``TMP`` under the runner's temp on a Windows leg.

    The tests' files and the environments they build with uv then
    share the working drive with the uv cache, which the runner keeps
    under its temp, so uv links instead of copying. Returns the delta
    and one line saying what happened. Nothing changes off Windows,
    under the ``system`` policy, or when the runner names no
    ``RUNNER_TEMP``; the last two say so.
    """
    import sys

    if (platform or sys.platform) != "win32":
        return delta, ""
    if windows_temp_policy(root) == "system":
        return delta, "TEMP: the system temp stays ([ci] windows-temp = system)"
    runner_temp = environ.get("RUNNER_TEMP", "")
    if not runner_temp:
        return delta, "TEMP: the runner names no RUNNER_TEMP; the system temp stays"
    target = Path(runner_temp) / "tmp"
    target.mkdir(parents=True, exist_ok=True)
    values = {**delta.values, "TEMP": str(target), "TMP": str(target)}
    return EnvDelta(values=values, paths=delta.paths), (
        f"TEMP: {target} (the runner's working drive, beside the uv cache)"
    )

venv_bin

venv_bin(root: Path) -> Path

The venv's executables directory: Scripts on Windows, bin elsewhere.

The emission runs on the machine it enters, so the running platform is the right answer (livery.workshop.scripts_dir).

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
def venv_bin(root: Path) -> Path:
    """The venv's executables directory: ``Scripts`` on Windows, ``bin`` elsewhere.

    The emission runs on the machine it enters, so the running
    platform is the right answer ([livery.workshop.scripts_dir][]).
    """
    from livery.workshop._pythons import scripts_dir

    return scripts_dir(root / ".venv")

workspace_delta

workspace_delta(root: Path, cwd: Path, environ: dict[str, str] | None = None) -> EnvDelta

The delta an entered shell needs for this workspace.

The cascade's managed values, plus the venv: VIRTUAL_ENV and the venv's bin on PATH, so fm and the venv tools resolve. The seam a tool store would extend. environ is the process environment the cascade reads; None means os.environ.

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
def workspace_delta(
    root: Path, cwd: Path, environ: dict[str, str] | None = None
) -> EnvDelta:
    """The delta an entered shell needs for this workspace.

    The cascade's managed values, plus the venv: ``VIRTUAL_ENV`` and
    the venv's bin on PATH, so ``fm`` and the venv tools resolve.
    The seam a tool store would extend. *environ* is the process
    environment the cascade reads; None means ``os.environ``.
    """
    seen = dict(os.environ) if environ is None else environ
    stack = load_cascade(root, cwd, environ=seen)
    values = dict(stack.managed())
    for key, value in _APPLIED.items():
        values.setdefault(key, seen.get(key, value))
    values["VIRTUAL_ENV"] = str(root / ".venv")
    paths, env = _receipts_emission(root)
    values.update(env)
    return EnvDelta(values=values, paths=(str(venv_bin(root)), *paths))

emit_lines

emit_lines(delta: EnvDelta, dialect: str) -> list[str]

Serialise delta for dialect (posix or pwsh).

One export per variable, then exactly one PATH prepend. A value or name that cannot be spelled safely is refused: only the value side is quoted, and export A B=1 exports A.

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
def emit_lines(delta: EnvDelta, dialect: str) -> list[str]:
    """Serialise *delta* for *dialect* (``posix`` or ``pwsh``).

    One export per variable, then exactly one PATH prepend. A value
    or name that cannot be spelled safely is refused: only the value
    side is quoted, and ``export A B=1`` exports ``A``.
    """
    lines: list[str] = []
    for name in sorted(delta.values):
        value = delta.values[name]
        _check_emittable(name, value)
        if dialect == "pwsh":
            doubled = value.replace("'", "''")
            lines.append(f"$env:{name} = '{doubled}'")
        else:
            lines.append(f"export {name}={_posix_quote(value)}")
    if delta.paths:
        for entry in delta.paths:
            _check_emittable("PATH", entry)
        if dialect == "pwsh":
            joined = ";".join(entry.replace("'", "''") for entry in delta.paths)
            lines.append(f"$env:PATH = '{joined};' + $env:PATH")
        else:
            joined = ":".join(_posix_quote(entry) for entry in delta.paths)
            lines.append(f'export PATH={joined}:"$PATH"')
    return lines

agent_delta

agent_delta(root: Path, cwd: Path, environ: dict[str, str]) -> EnvDelta

The variables an agent session needs, selected by membership.

Membership, not provenance: a session that already carries these variables would reclassify them as pre-existing, and a provenance filter would silently drop them. Secrets are included on purpose, availability is the point; the PATH family is excluded, it is composed per shell.

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
def agent_delta(root: Path, cwd: Path, environ: dict[str, str]) -> EnvDelta:
    """The variables an agent session needs, selected by membership.

    Membership, not provenance: a session that already carries these
    variables would reclassify them as pre-existing, and a
    provenance filter would silently drop them. Secrets are included
    on purpose, availability is the point; the PATH family is
    excluded, it is composed per shell.
    """
    shared = _shared_dir()
    keys = member_keys(root, cwd, shared)
    values = {
        key: environ.get(key, _APPLIED.get(key, ""))
        for key in sorted(keys)
        if key not in NEVER_AGENT and (environ.get(key) or _APPLIED.get(key))
    }
    values["VIRTUAL_ENV"] = str(root / ".venv")
    paths, env = _receipts_emission(root)
    values.update(env)
    return EnvDelta(values=values, paths=(str(venv_bin(root)), *paths))

rung_file

rung_file(environ: dict[str, str]) -> Path | None

Write the secrets the entry step carries into the shared slot's file.

The rendered entry step hands each declared key's CI secret to the emission as RUNG_<KEY>. The non-empty ones land in repo-shared.env under the runner's temp, readable by its owner alone, and the cascade reads that file as the shared slot (WORKSHOP_SHARED_ENV_FILE): the precedence of a machine's shared file, gone with the runner. An absent secret arrives empty and writes nothing, so it cannot mask a committed value; a job whose secrets all arrive empty still points the slot at the empty file, so a self-hosted runner's own shared file is never read.

Returns:

Type Description
Path | None

The file's path, or None when the step carries no key at all.

Raises:

Type Description
Failed

on a step carrying keys whose runner names no RUNNER_TEMP directory, since the file is the job's own; or on a secret with a line break, which one line of an env file cannot hold.

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
def rung_file(environ: dict[str, str]) -> Path | None:
    """Write the secrets the entry step carries into the shared slot's file.

    The rendered entry step hands each declared key's CI secret to the
    emission as ``RUNG_<KEY>``. The non-empty ones land in
    ``repo-shared.env`` under the runner's temp, readable by its owner
    alone, and the cascade reads that file as the shared slot
    (``WORKSHOP_SHARED_ENV_FILE``): the precedence of a machine's
    shared file, gone with the runner. An absent secret arrives empty
    and writes nothing, so it cannot mask a committed value; a job
    whose secrets all arrive empty still points the slot at the empty
    file, so a self-hosted runner's own shared file is never read.

    Returns:
        The file's path, or None when the step carries no key at all.

    Raises:
        Failed: on a step carrying keys whose runner names no
            ``RUNNER_TEMP`` directory, since the file is the job's own;
            or on a secret with a line break, which one line of an env
            file cannot hold.
    """
    carried = {
        key[len(RUNG_PREFIX) :]: value
        for key, value in environ.items()
        if key.startswith(RUNG_PREFIX) and len(key) > len(RUNG_PREFIX)
    }
    if not carried:
        return None
    runner_temp = environ.get("RUNNER_TEMP", "")
    if not runner_temp or not Path(runner_temp).is_dir():
        fail(
            "this job's runner names no RUNNER_TEMP directory: the entry keeps"
            " the secrets' file in the job's own temporary directory, so run"
            " it on a runner that sets one"
        )
    lines: list[str] = []
    for key, value in sorted(carried.items()):
        if not value:
            continue
        try:
            lines.append(f"{key}={quote_value(value)}\n")
        except ValueError:
            fail(
                f"the secret {key} carries a line break, which one line of"
                " the shared slot's file cannot hold; store it without one"
            )
    path = Path(runner_temp) / "repo-shared.env"
    path.write_text("".join(lines), encoding="utf-8")
    path.chmod(0o600)
    return path

github_persist

github_persist(delta: EnvDelta, environ: dict[str, str]) -> list[str]

Append delta to GITHUB_ENV and GITHUB_PATH; what was written.

Only under GitHub Actions, and never a secret name: the runner's env file is not a secret store, and the workflow's own secrets mechanism carries those.

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
def github_persist(delta: EnvDelta, environ: dict[str, str]) -> list[str]:
    """Append *delta* to GITHUB_ENV and GITHUB_PATH; what was written.

    Only under GitHub Actions, and never a secret name: the runner's
    env file is not a secret store, and the workflow's own secrets
    mechanism carries those.
    """
    if not environ.get("GITHUB_ACTIONS"):
        fail("--github persists into GITHUB_ENV, which only Actions sets")
    written: list[str] = []
    env_file = environ.get("GITHUB_ENV", "")
    if env_file:
        with Path(env_file).open("a", encoding="utf-8") as handle:
            for name in sorted(delta.values):
                if is_secret_name(name):
                    continue
                _check_emittable(name, delta.values[name])
                handle.write(f"{name}={delta.values[name]}\n")
                written.append(name)
    path_file = environ.get("GITHUB_PATH", "")
    if path_file:
        with Path(path_file).open("a", encoding="utf-8") as handle:
            # The runner prepends each line in turn, so the last line
            # written ends up first on PATH. Written last to first, the
            # emission's order holds: the venv's bin ahead of the
            # receipts' directories, as `eval "$(fm env.emit posix)"`
            # puts them, so the venv's pytest and mypy keep winning over
            # the store's copies of the same names.
            for entry in reversed(delta.paths):
                handle.write(f"{entry}\n")
                written.append(f"PATH+{entry}")
    return written

env_emit

env_emit(target: Arg[Literal['posix', 'pwsh', '']] = '', agent: Annotated[bool, doc('the agent selection: membership, secrets included')] = False, github: Annotated[bool, doc('persist into GITHUB_ENV/GITHUB_PATH (Actions only)')] = False) -> Stdout[str]

Emit the environment for evaluation by a shell.

Bare: the entered-shell emission plus the interactive completion hook. --agent: the membership selection for an agent session (evaluated by its env file, so no completion hook). --github writes the runner's env files, and on a Windows leg points TEMP and TMP under the runner's temp when the contract's [ci] windows-temp says runner, the default of a GitHub-shaped workspace; alone it prints what it wrote, and with a target it prints that same emission for the shell to evaluate, so the entry step enters and persists in one call.

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
@env.task(name="emit")
def env_emit(
    target: Arg[Literal["posix", "pwsh", ""]] = "",
    agent: Annotated[
        bool, doc("the agent selection: membership, secrets included")
    ] = False,
    github: Annotated[
        bool, doc("persist into GITHUB_ENV/GITHUB_PATH (Actions only)")
    ] = False,
) -> Stdout[str]:
    """Emit the environment for evaluation by a shell.

    Bare: the entered-shell emission plus the interactive completion
    hook. ``--agent``: the membership selection for an agent session
    (evaluated by its env file, so no completion hook). ``--github``
    writes the runner's env files, and on a Windows leg points
    ``TEMP`` and ``TMP`` under the runner's temp when the contract's
    ``[ci] windows-temp`` says ``runner``, the default of a
    GitHub-shaped workspace; alone it prints what it wrote, and with a
    target it prints that same emission for the shell to evaluate, so
    the entry step enters and persists in one call.
    """
    import sys

    root, cwd = _workspace()
    dialect = target or ("pwsh" if sys.platform == "win32" else "posix")
    if github:
        from livery.workshop._variables import workspace_variables

        environ = dict(os.environ)
        rung = rung_file(environ)
        if rung is not None:
            # The cascade reads the slot from the environment it is
            # handed, and the steps after read it persisted.
            environ["WORKSHOP_SHARED_ENV_FILE"] = str(rung)
        delta, note = with_runner_temp(
            with_runner_placements(
                workspace_delta(root, cwd, environ), environ, workspace_variables(root)
            ),
            root,
            environ,
        )
        if rung is not None:
            delta = EnvDelta(
                values={**delta.values, "WORKSHOP_SHARED_ENV_FILE": str(rung)},
                paths=delta.paths,
            )
        written = github_persist(delta, environ)
        if target:
            return "\n".join(emit_lines(delta, dialect))
        return "\n".join([*written, note] if note else written)
    if agent:
        delta = agent_delta(root, cwd, dict(os.environ))
        return "\n".join(emit_lines(delta, dialect))
    delta = workspace_delta(root, cwd)
    lines = emit_lines(delta, dialect)
    hook = _COMPLETION_PWSH if dialect == "pwsh" else _COMPLETION_HOOK
    lines.append(hook.format(prog=footman.prog()))
    enter = _START_PWSH if dialect == "pwsh" else _START_HOOK
    lines.append(enter.format(prog=footman.prog(), variable=START_PATH_VARIABLE))
    return "\n".join(lines)

env_show

env_show(full: Annotated[bool, doc('show secret values unmasked')] = False) -> None

Show the cascade: sources, values, and the PATH breakdown.

Secrets are masked by the suffix convention unless --full. The PATH breakdown numbers every entry and marks the missing directories; duplicates are shown as they are.

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
@env.task(name="show")
def env_show(
    full: Annotated[bool, doc("show secret values unmasked")] = False,
) -> None:
    """Show the cascade: sources, values, and the PATH breakdown.

    Secrets are masked by the suffix convention unless ``--full``.
    The PATH breakdown numbers every entry and marks the missing
    directories; duplicates are shown as they are.
    """
    root, cwd = _workspace()
    environ = dict(os.environ)
    shared = _shared_dir()
    print("  Sources:")
    for directory in cascade_dirs(root, cwd):
        for name in (".repo.env", ".repo.env.local"):
            candidate = directory / name
            if candidate.is_file():
                print(f"    {candidate}")
    if (shared / ".repo.shared.env").is_file():
        print(f"    {shared / '.repo.shared.env'}")
    # The pre-tasks hook already exported every managed key into this
    # process, so a live-environ load would classify everything as
    # the shell's own. Subtracting the hook's contributions restores
    # the files' provenance; a key the shell genuinely exported still
    # reads as environment.
    seen = {k: v for k, v in environ.items() if k not in _APPLIED}
    stack = load_cascade(root, cwd, environ=seen)
    files_only = load_cascade(root, cwd, environ={})
    if stack.values:
        print("  Variables:")
        width = max(len(key) for key in stack.values)
        for key in sorted(stack.values):
            value = stack.values[key] if full else _mask(key, stack.values[key])
            source = stack.sources[key].name
            if source == "shared" and environ.get("WORKSHOP_SHARED_ENV_FILE"):
                source = "ci rung"
            marker = ""
            declared = files_only.values.get(key)
            if (
                stack.sources[key] is Source.environment
                and declared is not None
                and declared != stack.values[key]
            ):
                # An older export than the file declares: stale until
                # the person re-enters.
                marker = "  [stale - the files say otherwise; re-enter]"
            print(f"    {key:<{width}}  {value}  ({source}){marker}")
    print("  PATH:")
    for index, entry in enumerate(environ.get("PATH", "").split(os.pathsep), 1):
        marker = "" if Path(entry).is_dir() else "  (missing)"
        print(f"    {index:>2}  {entry}{marker}")

env_set

env_set(key: Annotated[str, doc('the variable name')], value: Annotated[str, doc('the value; empty deletes the key')] = '', scope: Annotated[str, doc("local (this machine), shared (this person), repo (committed), ci (the forge's secret store)")] = 'local') -> None

Set or delete one variable in the chosen scope's file.

local writes .repo.env.local at the workspace root, shared the person-wide .repo.shared.env in the runner's config directory, repo the committed .repo.env. ci writes a CI secret through the forge protocol: under CI the entry step hands the declared keys' secrets to the emission, which materialises them into the shared slot, so a secret overrides the committed value the way the shared file does on a machine. After a write the higher-precedence sources are checked: a shadowed value is named rather than discovered later.

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
@env.task(name="set", interactive=True)
def env_set(
    key: Annotated[str, doc("the variable name")],
    value: Annotated[str, doc("the value; empty deletes the key")] = "",
    scope: Annotated[
        str,
        doc(
            "local (this machine), shared (this person), repo"
            " (committed), ci (the forge's secret store)"
        ),
    ] = "local",
) -> None:
    """Set or delete one variable in the chosen scope's file.

    ``local`` writes ``.repo.env.local`` at the workspace root,
    ``shared`` the person-wide ``.repo.shared.env`` in the runner's
    config directory,
    ``repo`` the committed ``.repo.env``. ``ci`` writes a CI secret
    through the forge protocol: under CI the entry step hands the
    declared keys' secrets to the emission, which materialises them
    into the shared slot, so a secret overrides the committed value
    the way the shared file does on a machine. After a write the
    higher-precedence sources are checked: a shadowed value is named
    rather than discovered later.
    """
    root, _cwd = _workspace()
    if scope == "ci":
        _set_ci_secret(root, key, value)
        return
    environ = dict(os.environ)
    shared = _shared_dir()
    files = {
        "local": root / ".repo.env.local",
        "shared": shared / ".repo.shared.env",
        "repo": root / ".repo.env",
    }
    if scope not in files:
        fail(f"unknown scope {scope!r}: local, shared, repo, or ci")
    path = files[scope]
    if not value:
        existing = parse_env_file(path)
        if key not in existing:
            print(f"  {key} is not set in {path}")
            return
        if not footman.confirm(f"Delete {key} from {path}?"):
            print("  Left alone")
            return
        lines = [
            line
            for line in path.read_text(encoding="utf-8").splitlines()
            if not line.strip().startswith(f"{key}=")
        ]
        path.write_text("\n".join(lines) + "\n", encoding="utf-8")
        print(f"  Deleted {key} from {path}")
        return
    try:
        set_value(path, key, value)
    except ValueError as error:
        fail(str(error))
    print(f"  Set {key} in {path}")
    order: dict[str, Source] = {
        "repo": Source.repo,
        "shared": Source.shared,
        "local": Source.local,
    }
    written = order[scope]
    # The pre-tasks hook exported the cascade into this process, so a
    # bare environ check would call every file-defined key the
    # shell's own and warn falsely; only a key the hook did not
    # contribute is genuinely the shell's.
    if environ.get(key) and key not in _APPLIED:
        print(
            f"  Note: {key} is set in your shell's own environment, which"
            " overrides every env file, so this value will not take effect"
            " until that export is gone."
        )
    else:
        for other_scope, source in order.items():
            if source < written and key in parse_env_file(files[other_scope]):
                print(
                    f"  Note: {key} is also defined in {files[other_scope]}"
                    f" ({source.name}), which overrides {written.name}: this"
                    " value will not take effect."
                )
    print("  Restart your terminal (or the editor) for this to take effect.")

tool_profile

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

The tools the declaration sites require on this host, each once.

The base's, the steps', the extensions', the plugins', the packages' own contracts' and the project's, as livery.workshop._tools reads them; a workspace with no package requires the base's uv, since its tasks.py runs in the venv uv makes. A requirement scoped to other hosts alone is none here.

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
def tool_profile(root: Path) -> tuple[str, ...]:
    """The tools the declaration sites require on this host, each once.

    The base's, the steps', the extensions', the plugins', the
    packages' own contracts' and the project's, as
    `livery.workshop._tools` reads them; a workspace with no package
    requires the base's uv, since its `tasks.py` runs in the venv uv
    makes. A requirement scoped to other hosts alone is none here.
    """
    from livery.workshop._tools import this_host, tool_names

    return tool_names(root, this_host())

served_by

served_by(receipt: ToolReceipt) -> str

Who serves receipt's tool: the host at the version it printed, or the store.

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
def served_by(receipt: ToolReceipt) -> str:
    """Who serves *receipt*'s tool: the host at the version it printed, or the store."""
    if receipt.source == "host":
        return f"host {receipt.answered}".rstrip()
    return f"store {receipt.version}"

missing_host_tools

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

The tools the workspace's packages need from the host that do not resolve.

A host tool, such as a C compiler, is one the store never installs: the machine provides it or the build cannot run, so fm doctor and fm env.check name an absence before a build fails midway. Each package's set answers the host-tools query, and the answers join, sorted, each tool once.

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
def missing_host_tools(root: Path) -> tuple[str, ...]:
    """The tools the workspace's packages need from the host that do not resolve.

    A host tool, such as a C compiler, is one the store never installs:
    the machine provides it or the build cannot run, so ``fm doctor``
    and ``fm env.check`` name an absence before a build fails midway.
    Each package's set answers the ``host-tools`` query, and the answers
    join, sorted, each tool once.
    """
    from livery.workshop._packages import discover_packages

    packages = discover_packages(root) if (root / "packages").is_dir() else ()
    needed = {tool for package in packages for tool in _host_tools(package)}
    return tuple(sorted(tool for tool in needed if shutil.which(tool) is None))

env_check

env_check() -> int

Verify this shell against the tools the sites require.

Run it bare from the session being checked: a freshly entered shell would report itself, not yours.

Every required tool must have a receipt, and every claim that receipt makes must hold here: the store wrote it to say what it installed, so it is what gets checked rather than a guess about where a tool of that name might live. A required tool with no receipt is a miss even when something of its name is on PATH, because what would run then is whatever the host happens to carry rather than the version this checkout pins. A receipt the lock has moved under is drift, and a miss prints the PATH breakdown and the remedy. With a lock, the stubs under typings/ are counted, and their absence is a problem too.

Source code in packages/workshop/src/livery/workshop/_env_tasks.py
@env.task(name="check")
def env_check() -> int:
    """Verify this shell against the tools the sites require.

    Run it bare from the session being checked: a freshly entered
    shell would report itself, not yours.

    Every required tool must have a receipt, and every claim that
    receipt makes must hold here: the store wrote it to say what it
    installed, so it is what gets checked rather than a guess about
    where a tool of that name might live. A required tool with no
    receipt is a miss even when something of its name is on PATH,
    because what would run then is whatever the host happens to carry
    rather than the version this checkout pins. A receipt the lock has
    moved under is drift, and a miss prints the PATH breakdown and the
    remedy. With a lock, the stubs under `typings/` are counted, and
    their absence is a problem too.
    """
    from livery.workshop._tools import (
        TYPINGS,
        current_lock,
        has_index,
        receipt_gap,
        store_cannot_supply,
        stubs_present,
        tool_receipts,
    )
    from livery.workshop._tools import drift as receipt_drift

    root, _cwd = _workspace()
    problems: list[str] = []
    bin_dir = venv_bin(root)
    said = receipt_drift(root)
    written = tool_receipts(root)
    for tool in tool_profile(root):
        verdict = said.get(tool, "")
        receipt = written.get(tool)
        if receipt is None:
            problems.append(
                f"{tool}: MISSING (no receipt; `{footman.prog()} sync` writes one)"
                + (f" ({verdict})" if verdict else "")
            )
            continue
        if gap := receipt_gap(tool, receipt, bin_dir):
            problems.append(f"{tool}: {gap}" + (f" ({verdict})" if verdict else ""))
            continue
        if verdict.startswith("DRIFT"):
            problems.append(f"{tool}: {verdict}")
            continue
        if verdict:
            print(f"  {tool}: on PATH; {verdict}")
        else:
            print(f"  {tool}: receipt ok; {served_by(receipt)}")
        if tool == "uv":
            drift = _uv_drift(root)
            if drift:
                problems.append(drift)
    for tool in missing_host_tools(root):
        problems.append(
            f"{tool}: MISSING (a host compiler; install the platform"
            " toolchain: xcode-select --install on macOS,"
            " build-essential on Debian)"
        )
    if has_index(root) and current_lock(root) is not None:
        held = stubs_present(root)
        if held:
            print(f"  stubs: {held} in {TYPINGS}/")
        else:
            problems.append(
                f"stubs: MISSING; run `{footman.prog()} toolroom.restub` to write"
                f" them into {TYPINGS}/"
            )
    if not problems:
        print("  environment ok: every required tool resolves")
        return 0
    for problem in problems:
        print(f"  {problem}")
    print("  PATH:")
    for index, entry in enumerate(os.environ.get("PATH", "").split(os.pathsep), 1):
        marker = "" if Path(entry).is_dir() else "  (missing)"
        print(f"    {index:>2}  {entry}{marker}")
    unsupplied = store_cannot_supply(root)
    if unsupplied:
        # Nothing is locked, so `sync` would supply nothing: the remedy
        # is the declaration and the lock, in that order.
        print(
            "  The tools are what the base, the extensions, the plugins, the"
            " packages and the project require."
        )
        for line in unsupplied.splitlines():
            print(f"  {line}" if line else "")
    else:
        print(
            "  The tools are what the base, the extensions, the plugins, the"
            " packages and the project require."
            f" Run `{footman.prog()} sync` to materialise them, or enter the"
            f" environment with `{footman.prog()} shell`."
        )
    return 1