Skip to content

Plugin Module

plugin

Public plugin author API for functualize.

This module re-exports symbols that plugin authors need to build functualize plugins: event infrastructure, job provider protocols, adapter protocols, plugin metadata, and TUI extension protocols.

Usage

from functualize.plugin import EventBus, JobProvider, AdapterPlugin, PluginMetadata from functualize.plugin import DisplayProvider, PanelProvider, ThemeProvider

DOTENV_PATH = Setting('dotenv_path', 'str', 'Explicit .env file path', cli_flag='--dotenv-file', phase='early') module-attribute

EXCLUDE_PATTERNS = Setting('discovery.exclude_patterns', 'list', 'Glob patterns to skip', places=('', 'discovery'), cli_flag='--exclude', phase='early') module-attribute

EXTRA_DIRECTORIES = Setting('discovery.extra_directories', 'list', 'Additional job directories', places=('', 'discovery'), env='FUNCTUALIZE_DISCOVERY_EXTRA_DIRECTORIES') module-attribute

FUNCTUALIZE_SETTINGS = AppSettingsSchema(settings=(THEME, DISPLAY_AUTO_SWITCH, DEFAULT_SURFACE, SHOW_SESSION_STAMP, HISTORY_RETENTION, SIGNATURE_ENABLED, DEFAULT_OVERRIDE_TARGET, OUTPUT, SHOW_TIMING, REQUIRE_FILE_PREFIX, REQUIRE_FILE_POSTFIX, REQUIRE_FILE_IMPORT, REQUIRE_FILE_MARKER, REQUIRE_JOB_DECORATORS, REQUIRE_JOB_PREFIX, REQUIRE_JOB_POSTFIX, EXTRA_DIRECTORIES, EXCLUDE_PATTERNS, SCAN_DEPTH, PLUGINS_STRICT, SHELL_PROGRAM, SHELL_SUDO_PASSWORD, INLINE_TUI, KEYRING_TIMEOUT, DOTENV, DOTENV_PATH, IMPORT_LIBS, JOBS_DIRECTORIES, PLUGINS_DIRECTORIES, RUN_TAGS), freeform_sections=(frozenset({'aliases'}))) module-attribute

IMPORT_LIBS = Setting('import_libs', 'list', 'Paths importable by job modules', cli_flag='--import-libs', phase='early') module-attribute

JOBS_DIRECTORIES = Setting('jobs_directories', 'list', 'Job directories', listed=False) module-attribute

REQUIRE_JOB_DECORATORS = Setting('discovery.require_job_decorators', 'list', 'Only register decorated functions', cli_flag='--require-job-decorators', phase='early') module-attribute

REQUIRE_JOB_POSTFIX = Setting('discovery.require_job_postfix', 'str', 'Only register jobs named *<postfix>', cli_flag='--require-job-postfix', phase='early') module-attribute

REQUIRE_JOB_PREFIX = Setting('discovery.require_job_prefix', 'str', 'Only register jobs named <prefix>*', cli_flag='--require-job-prefix', phase='early') module-attribute

ROOT_KEY = 'root' module-attribute

SCAN_DEPTH = Setting('discovery.scan_depth', 'int', 'Directory scan depth (0 = unlimited)', default='0', min_value=0, max_value=32, cli_flag='--discovery-depth', phase='early') module-attribute

SCRIPT_METADATA = frozenset({'job'}) module-attribute

GATE_ACCEPTED_TOPIC = 'gate.accepted' module-attribute

DEFAULT_SIGIL = '' module-attribute

EPILOGUE_STEP_KEY = '__epilogue__' module-attribute

__all__ = ['FUNCTUALIZE_SETTINGS', 'DOTENV_PATH', 'EXCLUDE_PATTERNS', 'EXTRA_DIRECTORIES', 'IMPORT_LIBS', 'JOBS_DIRECTORIES', 'REQUIRE_JOB_DECORATORS', 'REQUIRE_JOB_POSTFIX', 'REQUIRE_JOB_PREFIX', 'ROOT_KEY', 'SCAN_DEPTH', 'SCRIPT_METADATA', 'EventBus', 'HookEvent', 'StructuredEvent', 'JobProvider', 'JobTransform', 'Job', 'StaticProvider', 'ModulePreFilter', 'AdapterPlugin', 'SubstrateInstallError', 'PluginHost', 'AppSettingsSchema', 'ResolvedSettings', 'resolve_settings', 'CommandNode', 'CommandProvider', 'DEFAULT_SIGIL', 'InputMode', 'InputModeRegistry', 'Setting', 'SettingsLayer', 'SettingsSources', 'PromptCollector', 'Surface', 'LiveConstruct', 'PromptRequest', 'PromptResponse', 'PromptIntent', 'PromptSeverity', 'PromptChoice', 'PluginMetadata', 'PluginWithShutdown', 'Source', 'FormatProvider', 'VaultKeyInitializer', 'VaultKeyProvider', 'VaultKeyProbe', 'KeyAvailability', 'VaultKeyUnlocker', 'AgentStepExecutor', 'AgentCapability', 'AgentStepContext', 'AgentStepResult', 'DecisionProvider', 'ChoiceRequest', 'DecisionResult', 'DecisionProvenance', 'DecisionFailure', 'DecisionUnavailableError', 'DecisionGateResolver', 'discover_domains', 'scan_domain_providers', 'BarRenderer', 'DisplayProvider', 'HeaderItemProvider', 'InteractiveContent', 'PanelProvider', 'PostRunStampProvider', 'SessionState', 'SignatureProvider', 'StatusBarItemProvider', 'ThemeProvider', 'validate_extension_id', 'StepView', 'StoreProfile', 'ClaimWorkflow', 'MoveScope', 'RecordBranch', 'RecordStep', 'RenewLease', 'ReleaseLease', 'StartWalk', 'CompleteStep', 'SuspendAtGate', 'ResumeWorkflow', 'ConsumeInput', 'CancelWorkflow', 'StateBatch', 'StartAttempt', 'FinishAttempt', 'Claimed', 'Conflict', 'Resumed', 'CancelResult', 'Attempt', 'InputRequest', 'GateCandidate', 'CandidateEvaluation', 'EvaluationOutcome', 'EPILOGUE_STEP_KEY', 'RunView', 'WorkflowView', 'EventView', 'RunTree', 'RunQuery', 'WorkflowQuery', 'RunWriter', 'WorkflowWriter', 'InputWriter', 'EventWriter', 'EffectWriter', 'RunReader', 'WorkflowReader', 'InputReader', 'RuntimeStore', 'RuntimeTransaction', 'RuntimeStoreConfig', 'PreparedStore', 'RuntimeStoreFactory', 'SupersedeRequest', 'EffectIntent', 'EffectView', 'EffectQueue', 'OutboxStore', 'EffectReceiver', 'EvidenceRef', 'GateDecision', 'GATE_ACCEPTED_TOPIC', 'IllegalTransition', 'RuntimeStoreCapabilityError', 'RuntimeStoreSelectionError'] module-attribute

SettingsLayer(path, kind, section_prefix, values, text='') dataclass

One file and its application-scoped values, before precedence is applied.

text is the file exactly as it was read, kept beside the parsed values because a writer that appends an edit has to preserve everything it is not editing — comments, order, unrelated tables. Reading happens here, once; consumers never open a settings file themselves.

path instance-attribute

kind instance-attribute

section_prefix instance-attribute

values instance-attribute

text = '' class-attribute instance-attribute

exists property

read(path, kind, section_prefix) classmethod

Load one file as a layer.

The single-file entry point for a caller that has a path but no walk — a file a picker is about to create, or one the walk did not pick. A missing or unparsable file yields a layer with no values and no text; a file without the application table keeps its text and contributes no values, so a later save appends to the real file instead of replacing it.

Source code in src/functualize/_config/settings_layers.py
@classmethod
def read(cls, path: Path, kind: str, section_prefix: str) -> SettingsLayer:
    """Load one file as a layer.

    The single-file entry point for a caller that has a path but no walk —
    a file a picker is about to create, or one the walk did not pick. A
    missing or unparsable file yields a layer with no values and no text;
    a file without the application table keeps its text and contributes no
    values, so a later save appends to the real file instead of replacing
    it.
    """
    parsed = _read(path)
    if parsed is None:
        return cls(path, kind, section_prefix, {}, "")
    text, data = parsed
    values = _app_values(data, section_prefix)
    return cls(path, kind, section_prefix, values or {}, text)

ResolvedSettings(values, provenance, layers, contributes) dataclass

Values with the source that supplied each declared setting.

values instance-attribute

provenance instance-attribute

layers instance-attribute

contributes instance-attribute

get(name, default=None)

Source code in src/functualize/_config/settings_resolution.py
def get(self, name: str, default: Any = None) -> Any:
    return self.values.get(name, default)

Job(function, name=None, group=None) dataclass

Explicit job definition with overrides.

Used with StaticProvider to provide metadata overrides for a callable. When name is None, the function's name is used.

Attributes:

Name Type Description
function Callable[..., Any]

The callable to wrap as a job.

name str | None

Override for the job name. Defaults to function.name.

group str | None

Override for the job group. Defaults to None.

function instance-attribute

name = None class-attribute instance-attribute

group = None class-attribute instance-attribute

StaticProvider(functions)

Wraps pre-imported callables as JobDescriptors with zero I/O.

Accepts a list of plain callables, job classes, or Job dataclass instances. Plain callables derive job name from function.name; a job class contributes one job per method, exactly as it does from a directory scan (it is the same helper). Job instances allow overriding name and group for a function.

A class is a source, not an item, so Job(function=SomeClass) is a ValueError: the class already names its own jobs and its own group, and a wrapper that renamed them would be describing something the class does not say.

Satisfies the JobProvider Protocol via structural typing.

Parameters:

Name Type Description Default
functions list[Callable[..., Any] | Job]

List of callables, job classes, or Job dataclass instances.

required

Raises:

Type Description
ValueError

If a Job instance wraps a class instead of a function.

Source code in src/functualize/_discovery/providers.py
def __init__(self, functions: list[Callable[..., Any] | Job]) -> None:
    self._descriptors: list[JobDescriptor] = []
    self._by_name: dict[str, JobDescriptor] = {}

    for item in functions:
        for descriptor in self._descriptors_for(item):
            self._descriptors.append(descriptor)
            self._by_name[descriptor.name] = descriptor

list_jobs()

Return all job descriptors from this source.

Source code in src/functualize/_discovery/providers.py
def list_jobs(self) -> Sequence[JobDescriptor]:
    """Return all job descriptors from this source."""
    return self._descriptors

get_job(name)

Retrieve a specific job by name. None if not found.

Source code in src/functualize/_discovery/providers.py
def get_job(self, name: str) -> JobDescriptor | None:
    """Retrieve a specific job by name. None if not found."""
    found = self._by_name.get(name)
    if found is None:
        canonical = normalize_name(name) or name
        found = self._by_name.get(canonical) if canonical != name else None
    return found

EventBus()

Central event emission and subscriber routing.

The EventBus is the primary interface for emitting structured events and registering subscribers. It delegates pattern matching to an internal TrieRouter and maintains an EventCatalog for introspection.

Zero-cost guarantee: when no subscribers are registered, emit() returns after a single self._router.has_subscribers check — no event object construction, no string formatting, no time.time() call.

Usage::

bus = EventBus()
handle = bus.subscribe("config.file.*", my_callback)
bus.emit("config.file.parse.end", resource="/path/to/file.toml", duration=0.05)
bus.unsubscribe(handle)
Source code in src/functualize/_events/bus.py
def __init__(self) -> None:
    self._router = TrieRouter()
    self._catalog = EventCatalog()

has_subscribers property

True if any subscriber is registered on the bus.

subscribe(pattern, callback)

Subscribe to events matching the given pattern.

Parameters:

Name Type Description Default
pattern str

One of: - Exact event name ("config.file.parse.end") - Prefix wildcard ("config.") - Global wildcard ("")

required
callback SubscriberCallback

Callable receiving a StructuredEvent.

required

Returns:

Type Description
SubscriptionHandle

SubscriptionHandle for later unsubscription.

Source code in src/functualize/_events/bus.py
def subscribe(
    self, pattern: str, callback: SubscriberCallback
) -> SubscriptionHandle:
    """Subscribe to events matching the given pattern.

    Args:
        pattern: One of:
            - Exact event name ("config.file.parse.end")
            - Prefix wildcard ("config.*")
            - Global wildcard ("*")
        callback: Callable receiving a StructuredEvent.

    Returns:
        SubscriptionHandle for later unsubscription.
    """
    return self._router.subscribe(pattern, callback)

unsubscribe(handle)

Remove a previously registered subscriber.

Parameters:

Name Type Description Default
handle SubscriptionHandle

The SubscriptionHandle returned by subscribe().

required
Source code in src/functualize/_events/bus.py
def unsubscribe(self, handle: SubscriptionHandle) -> None:
    """Remove a previously registered subscriber.

    Args:
        handle: The SubscriptionHandle returned by subscribe().
    """
    self._router.unsubscribe(handle)

emit(event_name, resource='', related=None, **payload)

Emit a structured event to all matching subscribers.

Implements a zero-cost bypass path: 1. If no subscribers exist at all → return immediately. 2. If no subscribers match this specific event → return. 3. Validate event name format. 4. Attach PropagationContext (trace_id, span_id). 5. Construct StructuredEvent. 6. Dispatch to matching callbacks in registration order.

If a subscriber raises an exception, it is logged at ERROR level and dispatch continues to remaining subscribers.

Parameters:

Name Type Description Default
event_name str

Must match the grammar {domain}.{resource}.{action} (at least 3 dot-separated segments of lowercase alphanumeric/underscores).

required
resource str

Primary resource identifier (e.g., file path, job name).

''
related list[str] | None

Optional list of associated resource identifiers.

None
**payload Any

Arbitrary event-specific key-value data.

{}
Source code in src/functualize/_events/bus.py
def emit(
    self,
    event_name: str,
    resource: str = "",
    related: list[str] | None = None,
    **payload: Any,
) -> None:
    """Emit a structured event to all matching subscribers.

    Implements a zero-cost bypass path:
    1. If no subscribers exist at all → return immediately.
    2. If no subscribers match this specific event → return.
    3. Validate event name format.
    4. Attach PropagationContext (trace_id, span_id).
    5. Construct StructuredEvent.
    6. Dispatch to matching callbacks in registration order.

    If a subscriber raises an exception, it is logged at ERROR level
    and dispatch continues to remaining subscribers.

    Args:
        event_name: Must match the grammar
            ``{domain}.{resource}.{action}`` (at least 3 dot-separated
            segments of lowercase alphanumeric/underscores).
        resource: Primary resource identifier (e.g., file path, job name).
        related: Optional list of associated resource identifiers.
        **payload: Arbitrary event-specific key-value data.
    """
    # ZERO-COST CHECK 1: bail if no subscribers at all
    if not self._router.has_subscribers:
        return

    # ZERO-COST CHECK 2: bail if no subscribers match this event
    if not self._router.has_subscribers_for(event_name):
        return

    # Fast-path: known events in catalog skip regex validation
    if not self._catalog.contains(event_name) and not _EVENT_NAME_RE.match(
        event_name
    ):
        logger.warning(
            f"Invalid event name format: {event_name!r}. "
            f"Expected {{domain}}.{{resource}}.{{action}}."
        )
        return

    # Attach propagation context automatically
    ctx = current_context()
    event = StructuredEvent(
        event_name=event_name,
        resource=resource,
        related=related or [],
        payload=payload,
        trace_id=ctx.trace_id,
        span_id=ctx.span_id,
    )

    # Dispatch to subscribers synchronously in registration order
    callbacks = self._router.match(event_name)
    for callback in callbacks:
        try:
            callback(event)
        except Exception as exc:
            logger.error(
                f"Subscriber {callback!r} raised during event "
                f"'{event_name}': {exc}",
                exc_info=True,
            )

catalog()

Return the full event catalog for plugin introspection.

Returns:

Type Description
dict[str, EventMetadata]

Mapping of event names to their EventMetadata.

Source code in src/functualize/_events/bus.py
def catalog(self) -> dict[str, EventMetadata]:
    """Return the full event catalog for plugin introspection.

    Returns:
        Mapping of event names to their EventMetadata.
    """
    return self._catalog.all()

register_event_metadata(metadata)

Register event metadata in the catalog.

Allows plugins to register custom event metadata alongside framework-defined events.

Parameters:

Name Type Description Default
metadata EventMetadata

The EventMetadata to register.

required
Source code in src/functualize/_events/bus.py
def register_event_metadata(self, metadata: EventMetadata) -> None:
    """Register event metadata in the catalog.

    Allows plugins to register custom event metadata alongside
    framework-defined events.

    Args:
        metadata: The EventMetadata to register.
    """
    self._catalog.register(metadata)

StructuredEvent(event_name, resource, related=list(), payload=dict(), timestamp=time.time(), trace_id=None, span_id=None) dataclass

Immutable structured event emitted through the EventBus.

Attributes:

Name Type Description
event_name str

Hierarchical name following {domain}.{resource}.{action} grammar.

resource str

Primary resource identifier (e.g., file path, job name).

related list[str]

Associated resource identifiers.

payload dict[str, Any]

Event-specific data dictionary.

timestamp float

Seconds since epoch (from time.time()).

trace_id str | None

Active trace ID (auto-attached from PropagationContext).

span_id str | None

Active span ID (auto-attached from PropagationContext).

event_name instance-attribute

resource instance-attribute

related = field(default_factory=list) class-attribute instance-attribute

payload = field(default_factory=dict) class-attribute instance-attribute

timestamp = field(default_factory=(time.time)) class-attribute instance-attribute

trace_id = None class-attribute instance-attribute

span_id = None class-attribute instance-attribute

HookEvent

Constants for lifecycle hook events.

BEFORE_JOB = 'before_job' class-attribute instance-attribute

AFTER_SUCCESS = 'after_success' class-attribute instance-attribute

AFTER_FAILURE = 'after_failure' class-attribute instance-attribute

ON_TEARDOWN = 'on_teardown' class-attribute instance-attribute

JOB_REGISTERED = 'job_registered' class-attribute instance-attribute

Fired when a job is registered with the framework.

PRE_EXECUTE = 'pre_execute' class-attribute instance-attribute

Fired after config resolution and before the job function is called.

APP_READY = 'app_ready' class-attribute instance-attribute

Fired after the application has fully booted.

INVOKE_START = 'invoke_start' class-attribute instance-attribute

Fired before a nested rc.invoke() child job begins execution.

INVOKE_END = 'invoke_end' class-attribute instance-attribute

Fired after a nested rc.invoke() child job completes execution.

INVOKE_FAILURE = 'invoke_failure' class-attribute instance-attribute

Fired after a nested rc.invoke() child ends with a failed TOOL-family status.

ON_PHASE_START = 'on_phase_start' class-attribute instance-attribute

Fired when track_phase() creates a NEW phase.

ON_PHASE_FAILURE = 'on_phase_failure' class-attribute instance-attribute

Fired when track_phase() transitions a phase to FAILURE status.

ON_PHASE_COMPLETE = 'on_phase_complete' class-attribute instance-attribute

Fired when track_phase() transitions a phase to SUCCESS status.

ON_SCOPE_CREATED = 'on_scope_created' class-attribute instance-attribute

Fired when a WorkflowScope is created.

TUI_STARTED = 'tui_started' class-attribute instance-attribute

Fired when the TUI application launches.

DecisionGateResolver(provider)

Gate resolver that fills one field from a decision provider's proposal.

Satisfies GateResolver. Performs at most one provider call per resolution and never retries: whether to try again is the workflow's business, and a below-threshold proposal is meant to reach a person.

Source code in src/functualize/_gate/decision_strategy.py
def __init__(self, provider: DecisionProvider) -> None:
    self._provider = provider

resolve(ctx)

Source code in src/functualize/_gate/decision_strategy.py
def resolve(self, ctx: GateContext) -> BaseModel:
    decision = ctx.decision
    if decision is None:
        raise ValueError("gate has no decision declared")

    step = decision.state.name
    if step not in ctx.workflow_context:
        raise ValueError(
            f"decision state step {step!r} has no recorded result in this "
            f"walk; it must run before the gate"
        )
    recorded = ctx.workflow_context[step]
    state = (
        recorded
        if isinstance(recorded, str)
        else json.dumps(recorded, sort_keys=True, default=str)
    )

    def record(
        latency_seconds: float,
        verdict: str,
        *,
        result: DecisionResult[str] | None = None,
        error: DecisionUnavailableError | None = None,
        probability: float | None = None,
        margin: float | None = None,
    ) -> None:
        if ctx.evidence is not None:
            ctx.evidence.record(
                build_decision_evidence(
                    decision,
                    state=state,
                    latency_seconds=latency_seconds,
                    result=result,
                    error=error,
                    probability=probability,
                    margin=margin,
                    verdict=verdict,
                )
            )

    started = time.monotonic()
    try:
        result = self._provider.choose(
            ChoiceRequest(
                state=state,
                instructions=decision.instructions,
                options=decision.options,
                model=decision.model,
            )
        )
    except DecisionUnavailableError as exc:
        record(time.monotonic() - started, "provider_failed", error=exc)
        raise
    latency_seconds = time.monotonic() - started

    distribution = result.distribution
    if distribution is None:
        record(latency_seconds, "no_distribution", result=result)
        raise ValueError(
            f"{result.provider}/{result.model} proposed {result.value!r} with "
            f"no distribution; the gate's thresholds need one"
        )
    value = result.value
    if value not in distribution:
        # The provider was called, so the rung stays auditable: the
        # verdict names the shape it returned, and the rule never ran,
        # so probability and margin are absent rather than invented.
        record(latency_seconds, "uncovered_proposal", result=result)
        raise ValueError(
            f"{result.provider}/{result.model} proposed {value!r}, which its "
            f"distribution does not cover"
        )
    p = distribution[value]
    runner_up = max((v for k, v in distribution.items() if k != value), default=0.0)
    margin = p - runner_up

    if p >= decision.accept_at and margin >= decision.min_margin:
        record(
            latency_seconds,
            "accepted",
            result=result,
            probability=p,
            margin=margin,
        )
        return ctx.model_class(**{**ctx.resolved_fields, decision.field: value})
    record(
        latency_seconds,
        "below_threshold",
        result=result,
        probability=p,
        margin=margin,
    )
    raise DecisionBelowThresholdError(
        f"{result.provider}/{result.model} proposed '{value}' at {p:.2f} "
        f"(margin {margin:.2f}); workflow requires >= "
        f"{decision.accept_at:.2f}, margin >= {decision.min_margin:.2f}"
    )

PluginMetadata

Bases: Protocol

Protocol that plugins must satisfy to be loaded.

Attributes:

Name Type Description
name str

Plugin name, maximum 64 characters.

version str

Plugin version conforming to PEP 440.

description str

Plugin description, maximum 256 characters.

name instance-attribute

version instance-attribute

description instance-attribute

CommandNode

Bases: Protocol

One runnable-or-navigable position in the shell's command tree.

A node may be runnable (execute), navigable (children), or both — the duality case the trie already models (a deploy job that also has deploy web beneath it). Nothing here distinguishes a job from a builtin; that is the point.

Attributes:

Name Type Description
name str

The node's own segment as typed, not its full path.

help_text str

One-line description for listings and completion.

needs_terminal bool

True when running this node takes over the controlling terminal, so a TUI front-end must suspend itself around it rather than capture its output. Read by the orchestrator handoff, and by nothing else.

Decision — needs_terminal is a plain bool, not a predicate over args. It exists today in two incompatible shapes: a method on _cli/builtins.BuiltinCommand (needs_terminal(args) -> bool, computed as any(arg in self.terminal_subcommands for arg in args)) and a bool field on _cli/tui/panel_live_zone's surface. The method form exists only because BuiltinCommand models a whole command family: config carries terminal_subcommands=("edit",), so the answer depends on which subcommand was typed.

A CommandNode is not a family — the tree splits config into distinct config edit and config show nodes, and at that granularity the answer is static. So the bool wins, and the args-dependence is resolved once, at node construction: a provider wrapping BuiltinCommand evaluates needs_terminal([segment]) for each child it emits (this is ClickCommandProvider's job). No information is lost and the consumer — the orchestrator handoff — stops re-deriving it per invocation.

Distinct from a descriptor's requires_tty, which is a job author's declaration about the job function; needs_terminal is a property of the command node the shell is about to run.

name property

The node's own segment as typed, not its full path.

help_text property

One-line description for listings and completion.

needs_terminal property

True when running this node takes over the controlling terminal.

children()

Direct children, for drill-down. Empty for a leaf.

Backed by GroupTrie.children() for job nodes; by the click group's registered subcommands for builtin nodes.

Source code in src/functualize/_types/commands.py
def children(self) -> list[CommandNode]:
    """Direct children, for drill-down. Empty for a leaf.

    Backed by ``GroupTrie.children()`` for job nodes; by the click group's
    registered subcommands for builtin nodes.
    """
    ...

params()

The node's CLI-facing parameters.

Deliberately the existing FieldDescriptor — the same type build_click_params consumes — rather than a parallel param model invented for the shell. There is one description of a job's parameters and every surface reads it.

May be expensive: for a lazily-cached job this can force materialization (one module import). Callers that must stay import-free — completion of a command name, drill-down listing — must not call it.

Source code in src/functualize/_types/commands.py
def params(self) -> list[FieldDescriptor]:
    """The node's CLI-facing parameters.

    Deliberately the **existing** ``FieldDescriptor`` — the same type
    ``build_click_params`` consumes — rather than a parallel param model
    invented for the shell. There is one description of a job's parameters
    and every surface reads it.

    May be expensive: for a lazily-cached job this can force materialization
    (one module import). Callers that must stay import-free — completion of
    a *command name*, drill-down listing — must not call it.
    """
    ...

execute(args)

Run this node with args; return a process-style exit code.

Source code in src/functualize/_types/commands.py
def execute(self, args: Sequence[str]) -> int:
    """Run this node with ``args``; return a process-style exit code."""
    ...

CommandProvider

Bases: Protocol

A source of top-level :class:CommandNode s the shell composes into one tree.

nodes()

This provider's top-level nodes, in display order.

Source code in src/functualize/_types/commands.py
def nodes(self) -> list[CommandNode]:
    """This provider's top-level nodes, in display order."""
    ...

ChoiceRequest(state, instructions, options, model=None) dataclass

A question with a closed set of answers.

options maps each option to its meaning, and is stored as given.

state instance-attribute

instructions instance-attribute

options instance-attribute

model = None class-attribute instance-attribute

__post_init__()

Source code in src/functualize/_types/decision.py
def __post_init__(self) -> None:
    count = len(self.options)
    if not _MIN_OPTIONS <= count <= _MAX_OPTIONS:
        raise ValueError(
            f"a ChoiceRequest needs {_MIN_OPTIONS} to {_MAX_OPTIONS} "
            f"options, got {count}"
        )
    if "" in self.options:
        raise ValueError("a ChoiceRequest option may not be the empty string")

DecisionProvenance(requested_model, latency_seconds, input_tokens=None, output_tokens=None) dataclass

Where a result came from: what was asked for, and what it cost.

requested_model instance-attribute

latency_seconds instance-attribute

input_tokens = None class-attribute instance-attribute

output_tokens = None class-attribute instance-attribute

DecisionProvider

Bases: Protocol

The whole port a decision provider implements.

Obligations on every implementation, which the Protocol cannot express:

  • choose either returns a DecisionResult whose value is a key of request.options, or raises DecisionUnavailableError (functualize._types.errors). It never returns an answer outside the options it was offered.
  • It performs at most one round trip per call. It never sleeps and never retries: a rate limit or an outage is reported, and what to do about it is the caller's decision, not the provider's.

name property

choose(request)

Source code in src/functualize/_types/decision.py
def choose(self, request: ChoiceRequest) -> DecisionResult[str]: ...

DecisionResult(value, provider, model, provenance, distribution=None, confidence=None) dataclass

Bases: Generic[T]

One proposed candidate, as a provider reported it.

distribution is copied into a read-only mapping on construction, so a caller mutating the dict it passed in cannot change a recorded result, and equality compares it as a mapping — key order never affects ==.

value instance-attribute

provider instance-attribute

model instance-attribute

provenance instance-attribute

distribution = None class-attribute instance-attribute

confidence = None class-attribute instance-attribute

__post_init__()

Source code in src/functualize/_types/decision.py
def __post_init__(self) -> None:
    if self.distribution is not None:
        frozen: Mapping[T, float] = MappingProxyType(dict(self.distribution))
        object.__setattr__(self, "distribution", frozen)
        for option, probability in frozen.items():
            _check_unit_interval(f"distribution[{option!r}]", probability)
    if self.confidence is not None:
        _check_unit_interval("confidence", self.confidence)

DecisionFailure

Bases: StrEnum

Why a decision provider produced no candidate.

Five kinds, because each asks the operator something different: configure the provider, wait, change the request, check the network, or report a provider defect. The value is what a failed rung's detail carries.

NOT_CONFIGURED = 'not_configured' class-attribute instance-attribute

RATE_LIMITED = 'rate_limited' class-attribute instance-attribute

REFUSED = 'refused' class-attribute instance-attribute

UNREACHABLE = 'unreachable' class-attribute instance-attribute

MALFORMED = 'malformed' class-attribute instance-attribute

DecisionUnavailableError(*, kind, provider, detail, status=None, retry_after=None)

Bases: Exception

A decision provider could not propose a candidate.

Raised by DecisionProvider.choose (_types/decision.py) instead of returning a result. It is a report, not a retry signal: a provider never sleeps or retries, so retry_after is carried exactly as the service sent it for the caller to act on.

The message is "<provider> <kind>[ HTTP <status>][ retry after <n> s]: <detail>" — the string a failed rung carries into blocked_reason.

Attributes:

Name Type Description
kind DecisionFailure

Which of the five failures this is.

provider str

The provider's name.

status int | None

The HTTP status, when there was one.

retry_after float | None

Seconds, for RATE_LIMITED only, as the service sent it.

detail str

Clipped to 300 characters on construction, so the clip holds for every caller. Never contains the credential.

Source code in src/functualize/_types/errors.py
def __init__(
    self,
    *,
    kind: DecisionFailure,
    provider: str,
    detail: str,
    status: int | None = None,
    retry_after: float | None = None,
) -> None:
    self.kind = kind
    self.provider = provider
    self.status = status
    self.retry_after = retry_after
    self.detail = detail[:_DECISION_DETAIL_LIMIT]
    super().__init__(self._message())

kind = kind instance-attribute

provider = provider instance-attribute

status = status instance-attribute

retry_after = retry_after instance-attribute

detail = detail[:_DECISION_DETAIL_LIMIT] instance-attribute

__reduce__()

Rebuild from the five attributes, not from the rendered message.

The constructor is keyword-only, so BaseException.__reduce__ — which calls the class with self.args positionally — would raise TypeError on a copy or a pickle round trip, as IllegalTransition records above.

Source code in src/functualize/_types/errors.py
def __reduce__(
    self,
) -> tuple[partial[DecisionUnavailableError], tuple[()]]:
    """Rebuild from the five attributes, not from the rendered message.

    The constructor is keyword-only, so ``BaseException.__reduce__`` —
    which calls the class with ``self.args`` positionally — would raise
    `TypeError` on a copy or a pickle round trip, as `IllegalTransition`
    records above.
    """
    return (
        partial(
            type(self),
            kind=self.kind,
            provider=self.provider,
            detail=self.detail,
            status=self.status,
            retry_after=self.retry_after,
        ),
        (),
    )

IllegalTransition(machine, current, target)

Bases: Exception

A state change the machine's transition table does not name.

runtime-schema-migrations/T2, from the machines in contributor/reference/runtime-persistence-data-model.md §1. The tables are data and the refusal belongs where a write was about to happen, so the caller that raises this is the transition check at _primitives/transitions.py (T4, wave 1) and the two store writers behind it (T6). Nothing raises it in this wave: the error type is what has to exist before they can.

The message carries all three facts — machine, current, target — because the reader's question is always which pair, and a refusal that cannot answer it sends the reader back to the table by hand.

Attributes:

Name Type Description
machine

The machine whose table refused the move ("scope", "run", "attempt", "input_request").

current

The state the record is in, or None when it does not exist yet — the absent record an insert would create.

target

The state the caller asked for.

Source code in src/functualize/_types/errors.py
def __init__(self, machine: str, current: str | None, target: str) -> None:
    self.machine = machine
    self.current = current
    self.target = target
    where = "an absent record" if current is None else repr(current)
    super().__init__(f"{machine}: {where} -> {target!r} is not a legal transition")

machine = machine instance-attribute

current = current instance-attribute

target = target instance-attribute

__reduce__()

Rebuild from the three facts, not from the rendered message.

BaseException.__reduce__ reconstructs by calling the class with self.args — which here is the one rendered message — and this constructor takes three facts, so the default would raise TypeError on a round trip. Naming the constructor's arguments is the whole fix.

Source code in src/functualize/_types/errors.py
def __reduce__(self) -> tuple[type[IllegalTransition], tuple[str, str | None, str]]:
    """Rebuild from the three facts, not from the rendered message.

    `BaseException.__reduce__` reconstructs by calling the class with
    ``self.args`` — which here is the one rendered message — and this
    constructor takes three facts, so the default would raise `TypeError` on
    a round trip. Naming the constructor's arguments is the whole fix.
    """
    return (type(self), (self.machine, self.current, self.target))

RuntimeStoreCapabilityError(*, store, field, config_key, needed, actual, because='')

Bases: Exception

A required capability is absent from the selected store's profile.

runtime-persistence-ports/T13, acceptance criterion 3. Raised at selection time, in boot step 6.5, before the engine is built: boot refuses rather than degrading to a weaker store, because a silent downgrade is the failure mode :class:~functualize._types.persistence.StoreProfile exists to make impossible.

The message names the store, the field and the config key, because the reader's question on hitting this refusal is always "which setting do I change" — an error that cannot answer it sends the reader grepping for who declared the requirement.

Attributes:

Name Type Description
store

The profile name of the store that was selected.

field

The StoreProfile field the requirement reads.

config_key

The configuration key that declared the requirement — the setting to change, or the store to reselect.

needed

The value the requirement needs.

actual

The value the selected store declares.

because

Why the requirement exists, in the declarer's words.

Source code in src/functualize/_types/errors.py
def __init__(
    self,
    *,
    store: str,
    field: str,
    config_key: str,
    needed: bool | str | int | None,
    actual: bool | str | int | None,
    because: str = "",
) -> None:
    self.store = store
    self.field = field
    self.config_key = config_key
    self.needed = needed
    self.actual = actual
    self.because = because
    reason = f" ({because})" if because else ""
    super().__init__(
        f"Store {store!r} cannot serve this configuration: {config_key} "
        f"requires {field}={needed!r}{reason}, and the store declares "
        f"{field}={actual!r}. Change {config_key} or select a store "
        f"that has the capability — boot refuses rather than degrading "
        f"to a weaker store."
    )

store = store instance-attribute

field = field instance-attribute

config_key = config_key instance-attribute

needed = needed instance-attribute

actual = actual instance-attribute

because = because instance-attribute

RuntimeStoreSelectionError

Bases: Exception

Boot step 6.5 cannot select one runtime store from the configuration.

Raised for a scheme no registered factory serves, for two factories claiming one scheme, and when nothing is configured but a registered backend holds runtime data the default store would not see. Uncaught: boot aborts rather than coming up on a store nobody chose. The message names the setting to change and the remedy, because the reader's next question is always which line of configuration to edit.

SubstrateInstallError

Bases: Exception

A plugin could not install the project's configured substrate.

Substrate installation is the one APP_READY failure that aborts boot: continuing would silently fall back to a different backend and split the project's persisted documents across substrates.

CandidateEvaluation(outcome, detail='', errors=(), evidence=None) dataclass

One candidate's verdict, frozen at the moment it was made.

errors is (field, message) pairs from the validation failure, not a rendered string: a caller that wants to highlight the offending field in a UI should not have to parse prose to find it. Empty for every outcome but invalid — a strategy failure's text lives in detail.

evidence is JSON-safe context a strategy rung records beside its verdict — what it saw, and what it cost to see it. Written by a rung, never by an answer surface: a person or an agent answering a gate records a candidate, and fabricating rung evidence beside it would be a forgery. None for every candidate a rung did not produce.

outcome instance-attribute

detail = '' class-attribute instance-attribute

errors = () class-attribute instance-attribute

evidence = None class-attribute instance-attribute

EvaluationOutcome

Bases: StrEnum

How one candidate fared. Recorded once, never recomputed.

Five outcomes, and the difference between them is the whole point of recording candidates at all:

  • accepted — the payload validated and was taken as the answer. At most one candidate per request ends here.
  • invalid — a human or agent submitted a payload that failed validation. The gate stays open; the attempt is kept because "who tried and why it failed" is the question an audit or an agent evaluation asks first.
  • failed — a strategy ran and raised. The detail is the error.
  • unavailable — a strategy named in the ladder is not registered. A missing package is a fact about the environment, not an attempt that went wrong, and the outcome says which it is.
  • not_reached — the ladder never got this far because an earlier rung was accepted. Distinguishing "did not run" from "ran and failed" is what makes a recorded ladder readable.

ACCEPTED = 'accepted' class-attribute instance-attribute

INVALID = 'invalid' class-attribute instance-attribute

FAILED = 'failed' class-attribute instance-attribute

UNAVAILABLE = 'unavailable' class-attribute instance-attribute

NOT_REACHED = 'not_reached' class-attribute instance-attribute

EvidenceRef(ref, digest, media_type=None, size=None) dataclass

Evidence attached to an answer: where its bytes live, and their digest.

A reference, never the bytes. A runtime row is the wrong home for an attachment — it is copied into every read of the request, and a store that keeps rows in one file grows with every screenshot — so the record carries only what identifies the bytes and what proves they are the ones that were attached. ref is opaque here (a path, a URI, an artifact id); digest is sha256:<64 hex>, checked by the recorder.

A matching digest proves the bytes at ref are the attached ones. It cannot prove who produced them — that is the candidate's attribution.

ref instance-attribute

digest instance-attribute

media_type = None class-attribute instance-attribute

size = None class-attribute instance-attribute

GateCandidate(candidate_id, request_id, ordinal, source, submitted_at, evaluation, payload=None, resolver_class='', channel='', schema_id='', schema_version='', payload_hash='', supersedes_candidate_id=None, evidence_refs=()) dataclass

One proposed answer to a gate request.

Append-only by contract: a second candidate never overwrites the first, and the store refuses an :meth:append <functualize._types.persistence.InputWriter.append> against a request that is no longer open rather than silently replacing an earlier answer.

source attributes the candidate — strategy:<name> for a ladder rung, cli/mcp/api for a surface, whatever an answering agent names itself. It is recorded, not parsed: attribution is for the reader of a resolution, never for a decision.

ordinal orders the candidates within one request. The recorder mints it and continues it across ladders, so two strategy runs on one request read as one sequence rather than two unrelated lists.

The provenance fields answer an audit's questions without a second lookup, and the recorder fills them all; they default to empty only so a record written before they existed still reads. resolver_class is human, agent, program or policy; channel is the surface (cli, mcp) or the strategy that produced the candidate. schema_id/schema_version name the model the payload was evaluated against, the version being the digest of its JSON schema, and payload_hash the digest of the payload as submitted. supersedes_candidate_id names the earlier, unaccepted candidate this one corrects — the correction is a new row, the earlier one is untouched.

candidate_id instance-attribute

request_id instance-attribute

ordinal instance-attribute

source instance-attribute

submitted_at instance-attribute

evaluation instance-attribute

payload = None class-attribute instance-attribute

resolver_class = '' class-attribute instance-attribute

channel = '' class-attribute instance-attribute

schema_id = '' class-attribute instance-attribute

schema_version = '' class-attribute instance-attribute

payload_hash = '' class-attribute instance-attribute

supersedes_candidate_id = None class-attribute instance-attribute

evidence_refs = () class-attribute instance-attribute

GateDecision(request_id, accepted_id, policy_id, policy_version, observed_candidate_ids, decided_at) dataclass

Why a request was accepted: the policy, and exactly what it looked at.

Recorded once, in the unit that records the accepted candidate, and never recomputed. observed_candidate_ids is the candidate set as it stood at that moment, in ordinal order and including the accepted one — a reader asking "what did the gate weigh" gets that list, not whichever rows happen to exist when the question is asked.

policy_id names the rule that accepted (gate.validate for a surface answer, gate.ladder for a strategy rung) and policy_version pins which version of it.

request_id instance-attribute

accepted_id instance-attribute

policy_id instance-attribute

policy_version instance-attribute

observed_candidate_ids instance-attribute

decided_at instance-attribute

PluginHost

Bases: Protocol

What a plugin needs from the application, and nothing else.

Peer of :class:~functualize._types.protocols.EngineHost for the plugin boundary. Members ask; none of them lends — the rule that port inherits. A member that hands a plugin a mutable internal, or the machinery to fire lifecycle events at the rest of the app, is not a narrowing of app: Any; it is the same reach with a type on it.

Twelve members. What is absent is as deliberate as what is present:

hook_registry Four plugin clients, and refused. Seven public methods, of which four are invoke* — the firing half. On the port, every plugin could fire arbitrary lifecycle events at every other. T6 migrated all four clients to hooks.on_ready, which registers and cannot fire. execution_engine Five apparent clients, one real: four were the chain app.execution_engine.substrate, collapsed to substrate by T4. The survivor wants materialize_job (functualize-mcp/…/_workflow_tools.py:447). One call site does not buy handing plugins the whole engine. run One client, -> None, and it is the CLI entrypoint. A plugin calling it re-enters delivery from inside delivery. workflows Zero plugin clients. A port lists what is needed, not what exists. di.resolve Zero clients after T1 and T2. Its only consumer was inside a permanently dead block, which is why this port has no read side for DI.

di property

Register what jobs can ask for, by type or by name.

extensions property

Hang commands, surfaces and constructs off the application.

configuration property

Read this project's resolved configuration.

gates property

Register gate strategies and presets.

hooks property

Register lifecycle callbacks — for a plugin, on_ready.

substrate property

The storage in effect — never None, boot's one selection.

Renamed from the install slot by T3, which is what lets this member be declared without | None. The slot is substrate_override and runtime-persistence-ports/T12 settled who reads it: boot, at step 6.5, which hands the answer to the engine — so the slot is absent here.

fresh_root property

Where this project's derived run state lives.

The other single-client member, for the same reason — and already a declared member of the sibling port EngineHost.

get_jobs()

Every discovered job descriptor.

Source code in src/functualize/_types/host.py
def get_jobs(self) -> list[JobDescriptor]:
    """Every discovered job descriptor."""
    ...

get_job(name)

One descriptor by name, or None when nothing is registered.

Source code in src/functualize/_types/host.py
def get_job(self, name: str) -> JobDescriptor | None:
    """One descriptor by name, or None when nothing is registered."""
    ...

execute(request)

Run a job. Takes a :class:RunRequest and nothing else.

Source code in src/functualize/_types/host.py
def execute(self, request: RunRequest) -> JobResult:
    """Run a job. Takes a :class:`RunRequest` and nothing else."""
    ...

install_substrate(substrate)

Install a backend. Before boot selects a store — refused after.

For a plugin whose choice needs no configuration: it can build its substrate at registration and hand it over there. No shipped plugin is such a plugin since runtime-persistence-ports/T12 moved functualize-substrate-sqlite to :meth:offer_substrate, so this member has no plugin client — kept for the config-free case and because the app's own door is this one, and recorded as a deviation from "sized to measured use" in plan.md → Surviving smells. An install and an offer are both storage claims; two claims refuse at selection rather than one winning.

Source code in src/functualize/_types/host.py
def install_substrate(self, substrate: StoreSubstrate) -> None:
    """Install a backend. Before boot selects a store — refused after.

    For a plugin whose choice needs **no configuration**: it can build its
    substrate at registration and hand it over there. No shipped plugin is
    such a plugin since runtime-persistence-ports/T12 moved ``functualize-substrate-sqlite`` to
    :meth:`offer_substrate`, so this member has no plugin client — kept for
    the config-free case and because the app's own door is this one, and
    recorded as a deviation from "sized to measured use" in ``plan.md`` →
    *Surviving smells*. An install and an offer are both storage *claims*;
    two claims refuse at selection rather than one winning.
    """
    ...

offer_substrate(offer)

Offer a backend that boot asks for once configuration has resolved.

Called from a plugin's registration call. Boot invokes offer inside step 6.5 — after the configuration chain exists, before the store is selected — and uses what it returns; the plugin never names a boot step. That is the window a config-driven substrate plugin needs and :meth:install_substrate cannot give it, since on the standard path registration runs before configuration resolves.

A storage member, not a lifecycle hook, and so not on :class:HooksView: it registers a question boot will ask, and nothing but that one selection site ever invokes it. A failure inside offer aborts boot — step 6.5 is deliberately uncaught — and more than one claim (offers and installs alike) is refused with SubstrateInstallError naming every claimant.

Source code in src/functualize/_types/host.py
def offer_substrate(self, offer: SubstrateOffer) -> None:
    """Offer a backend that boot asks for once configuration has resolved.

    Called from a plugin's registration call. Boot invokes ``offer`` inside
    step 6.5 — after the configuration chain exists, before the store is
    selected — and uses what it returns; the plugin never names a boot
    step. That is the window a *config-driven* substrate plugin needs and
    :meth:`install_substrate` cannot give it, since on the standard path
    registration runs before configuration resolves.

    A storage member, not a lifecycle hook, and so not on
    :class:`HooksView`: it registers a question boot will ask, and nothing
    but that one selection site ever invokes it. A failure inside ``offer``
    aborts boot — step 6.5 is deliberately uncaught — and more than one
    claim (offers and installs alike) is refused with
    ``SubstrateInstallError`` naming every claimant.
    """
    ...

register_runtime_store_factory(factory)

Make a runtime store selectable by runtime_store.url.

Called from a plugin's registration call; boot registers the built-in documents factory the same way, first. Installing a backend no longer selects it: boot step 6.5 reads runtime_store.url and prepares the one factory whose scheme it names. Two factories for one scheme are both kept here and refused at selection, naming both, so plugin load order never decides storage. Refused with SubstrateInstallError once step 6.5 has run, as an offer is.

Source code in src/functualize/_types/host.py
def register_runtime_store_factory(self, factory: RuntimeStoreFactory) -> None:
    """Make a runtime store selectable by ``runtime_store.url``.

    Called from a plugin's registration call; boot registers the built-in
    ``documents`` factory the same way, first. Installing a backend no
    longer selects it: boot step 6.5 reads ``runtime_store.url`` and
    prepares the one factory whose ``scheme`` it names. Two factories for
    one scheme are both kept here and refused at selection, naming both,
    so plugin load order never decides storage. Refused with
    ``SubstrateInstallError`` once step 6.5 has run, as an offer is.
    """
    ...

InputMode(sigil, name, candidate_source, is_ready, submit, history_namespace) dataclass

One thing the input bar can be doing.

Attributes:

Name Type Description
sigil str

First character that selects this mode ("!", "?"), or :data:DEFAULT_SIGIL for the fallback command mode.

name str

Short identifier, used in logs and history namespacing.

candidate_source Callable[[str, int], list[Any]]

Returns completion candidates for (text, cursor). The text excludes the sigil, and the cursor offset is relative to that stripped text. Completion is cursor-sensitive in every mode — a command mode needs to know which token is being edited, a shell mode needs it for path completion — so it is part of the contract rather than something each mode smuggles in via instance state.

is_ready Callable[[str], bool]

Readiness rule for the input FSM — may this be submitted?

submit Callable[[str], None]

Runs the input. Also receives text without the sigil.

history_namespace str

Where this mode's history is recorded. Distinct namespaces stop !ls from polluting job-argument history.

sigil instance-attribute

name instance-attribute

candidate_source instance-attribute

is_ready instance-attribute

submit instance-attribute

history_namespace instance-attribute

strip_sigil(text)

text with this mode's sigil removed, if present.

Source code in src/functualize/_types/input_modes.py
def strip_sigil(self, text: str) -> str:
    """``text`` with this mode's sigil removed, if present."""
    if self.sigil and text.startswith(self.sigil):
        return text[len(self.sigil) :]
    return text

InputModeRegistry()

Sigil -> mode. One default mode, any number of sigil modes.

Registration is explicit and collision-checked: two modes claiming ! would make dispatch order decide behavior, which is exactly the kind of silent precedence the convergence exists to remove.

Source code in src/functualize/_types/input_modes.py
def __init__(self) -> None:
    self._modes: dict[str, InputMode] = {}

__slots__ = ('_modes',) class-attribute instance-attribute

sigils property

Registered sigils, default first.

register(mode)

Add mode.

Raises:

Type Description
ValueError

another mode already claims this sigil, or the sigil is longer than one character (dispatch reads exactly one).

Source code in src/functualize/_types/input_modes.py
def register(self, mode: InputMode) -> None:
    """Add ``mode``.

    Raises:
        ValueError: another mode already claims this sigil, or the sigil is
            longer than one character (dispatch reads exactly one).
    """
    if len(mode.sigil) > 1:
        raise ValueError(
            f"sigil {mode.sigil!r} must be a single character "
            f"(or empty for the default mode)"
        )
    existing = self._modes.get(mode.sigil)
    if existing is not None:
        raise ValueError(
            f"sigil {mode.sigil!r} is already registered to "
            f"{existing.name!r}; cannot also register {mode.name!r}"
        )
    self._modes[mode.sigil] = mode

resolve(text)

The mode that owns text, by its first character.

Falls back to the default mode. Returns None only when no default has been registered — a shell always registers one, so that is a programming error rather than a user-visible state.

Source code in src/functualize/_types/input_modes.py
def resolve(self, text: str) -> InputMode | None:
    """The mode that owns ``text``, by its first character.

    Falls back to the default mode. Returns None only when no default has
    been registered — a shell always registers one, so that is a
    programming error rather than a user-visible state.
    """
    if text:
        mode = self._modes.get(text[0])
        if mode is not None:
            return mode
    return self._modes.get(DEFAULT_SIGIL)

get(sigil)

The mode registered for sigil, if any.

Source code in src/functualize/_types/input_modes.py
def get(self, sigil: str) -> InputMode | None:
    """The mode registered for ``sigil``, if any."""
    return self._modes.get(sigil)

__contains__(sigil)

Source code in src/functualize/_types/input_modes.py
def __contains__(self, sigil: object) -> bool:
    return sigil in self._modes

__len__()

Source code in src/functualize/_types/input_modes.py
def __len__(self) -> int:
    return len(self._modes)

LiveConstruct

Bases: Protocol

A renderable hosted in a surface's live zone (the Live capability).

The construct owns only its state and how to render it; the surface owns the cursor/mount and repaints. The contract is a single Rich renderable via __rich__ (a Table / Tree / Progress / Group / Text). The "raw" fallback needs no second renderer — it is Rich's own degradation: a non-terminal Console prints plain text, and rich.live.Live off-TTY prints the final state only.

Interactivity is a separate, optional capability. A construct that also implements the PanelHost action contract (get_available_actions(focused) plus Textual action_* methods, made focusable) can be mounted via Live.panel(...) where an event loop exists (PANEL / EXCLUSIVE); it degrades to passive render in STDOUT and to event-emission in MCP.

Return type is Any because _types is stdlib-only (no Rich import); the value is any Rich renderable.

__rich__()

Return a Rich renderable for the construct's current state.

Source code in src/functualize/_types/interactivity.py
def __rich__(self) -> Any:
    """Return a Rich renderable for the construct's current state."""
    ...

PromptChoice(value, label=None, description=None, disabled=False, group=None) dataclass

A single selectable choice within a prompt.

Attributes:

Name Type Description
value str

The programmatic value returned when this choice is selected.

label str | None

Display label (falls back to value if None).

description str | None

Optional longer description for the choice.

disabled bool

If True, shown but not selectable.

group str | None

Optional group name for visual grouping of choices.

value instance-attribute

label = None class-attribute instance-attribute

description = None class-attribute instance-attribute

disabled = False class-attribute instance-attribute

group = None class-attribute instance-attribute

PromptCollector

Bases: Protocol

Something that can ask the user a question and return the answer.

Exactly one collector is active at a time — whichever owns the terminal (or the modal) right now. Implementations include the stdin fallback, a TUI's input bar, and a job-owned app's modal.

collect(request)

Ask the user, blocking until answered, timed out, or cancelled.

Source code in src/functualize/_types/interactivity.py
def collect(self, request: PromptRequest) -> PromptResponse:
    """Ask the user, blocking until answered, timed out, or cancelled."""
    ...

PromptIntent

Bases: Enum

Semantic intent of a prompt, guiding surface presentation.

CONFIRM_DESTRUCTIVE = 'confirm_destructive' class-attribute instance-attribute

CONFIRM_NEUTRAL = 'confirm_neutral' class-attribute instance-attribute

CONFIRM_PROCEED = 'confirm_proceed' class-attribute instance-attribute

SELECT = 'select' class-attribute instance-attribute

MULTI_SELECT = 'multi_select' class-attribute instance-attribute

TEXT_INPUT = 'text_input' class-attribute instance-attribute

SECRET_INPUT = 'secret_input' class-attribute instance-attribute

ACKNOWLEDGE = 'acknowledge' class-attribute instance-attribute

PromptRequest(question, intent=PromptIntent.TEXT_INPUT, choices=None, default=None, severity=PromptSeverity.INFO, context_message=None, context_data=None, placeholder=None, help_text=None, timeout=None, required=True, validator=None, validation_message=None, source_job=None, source_step=None) dataclass

A structured request for user input during job execution.

The wire format between a job and whatever is rendering it. Carries intent, severity, choices, context, and validation rules so that one request can be presented as a terminal question, a Textual modal, or an MCP gate checkpoint without the job knowing which.

Attributes:

Name Type Description
question str

The prompt question text displayed to the user.

intent PromptIntent

Semantic intent guiding surface presentation.

choices list[PromptChoice] | None

Available choices for SELECT/MULTI_SELECT intents.

default Any

Default value used on timeout or when no input provided.

severity PromptSeverity

Visual severity level for styling.

context_message str | None

Optional context message displayed alongside the prompt.

context_data dict[str, Any] | None

Optional structured data displayed in a context panel.

placeholder str | None

Placeholder text for text input fields.

help_text str | None

Additional help text displayed below the prompt.

timeout float | None

Timeout in seconds; None means wait indefinitely.

required bool

If True and no Surface is available with no default, raises InputNotAvailable.

validator str | Any | None

Regex pattern string or object with .validate_python() method.

validation_message str | None

Custom message shown on validation failure.

source_job str | None

Name of the job that initiated this prompt (auto-filled by rc.prompts.ask).

source_step str | None

Name of the workflow step that initiated this prompt.

question instance-attribute

intent = PromptIntent.TEXT_INPUT class-attribute instance-attribute

choices = None class-attribute instance-attribute

default = None class-attribute instance-attribute

severity = PromptSeverity.INFO class-attribute instance-attribute

context_message = None class-attribute instance-attribute

context_data = None class-attribute instance-attribute

placeholder = None class-attribute instance-attribute

help_text = None class-attribute instance-attribute

timeout = None class-attribute instance-attribute

required = True class-attribute instance-attribute

validator = None class-attribute instance-attribute

validation_message = None class-attribute instance-attribute

source_job = None class-attribute instance-attribute

source_step = None class-attribute instance-attribute

PromptResponse(value, source='user') dataclass

Response from a user prompt interaction.

Attributes:

Name Type Description
value Any

The response value (user input, default, or None if cancelled).

source str

How the response was obtained. Constrained to: "user", "default", "timeout", "cancelled".

value instance-attribute

source = 'user' class-attribute instance-attribute

was_cancelled property

True if the user cancelled the prompt.

was_timeout property

True if the prompt timed out without user response.

is_user_input property

True if the response came from direct user input.

PromptSeverity

Bases: Enum

Visual severity level for prompt presentation.

Largely derivable from :class:PromptIntent — a destructive confirmation is a danger prompt, everything else is informational — so prefer letting :func:severity_for_intent supply it rather than passing it by hand. It remains settable for the cases where a caller genuinely wants to override the styling (a warning on a non-destructive action).

INFO = 'info' class-attribute instance-attribute

WARNING = 'warning' class-attribute instance-attribute

DANGER = 'danger' class-attribute instance-attribute

SUCCESS = 'success' class-attribute instance-attribute

Surface

Bases: Protocol

Something that renders a job's events.

Implementations include the TUI's output panel, flow-viz's plain-stdout tree, a job-owned Textual app, a log-file writer, and test recorders. Registered on the app; the engine fans every non-framework event out to all of them.

An implementation that can also answer questions additionally satisfies :class:PromptCollector.

Threading contract — the part that bites. handle_event is called from whatever thread the job runs on, which is a worker thread whenever a host owns the terminal (see _cli/tui/job_execution.py). An implementation that touches a UI must marshal onto its own loop (Textual: post_message / call_from_thread). Writing to a widget directly from handle_event freezes the app with no exception and no stack trace — the failure is silent, so it must be designed out here rather than debugged later.

handle_event(event)

Render or record one structured event. Called on worker threads.

Source code in src/functualize/_types/interactivity.py
def handle_event(self, event: StructuredEvent) -> None:
    """Render or record one structured event. Called on worker threads."""
    ...

Attempt(run_id, attempt_no, status, started_at, ended_at=None, failure_code=None, failure_detail=None) dataclass

One execution of a job body, identified inside its run.

Vocabulary only in this wave — nothing renders it yet, and what a failed twice-then-succeeded run shows a user is D-6's to decide. A retry never mutates a terminal attempt; it inserts the next one, same run_id.

run_id instance-attribute

attempt_no instance-attribute

status instance-attribute

started_at instance-attribute

ended_at = None class-attribute instance-attribute

failure_code = None class-attribute instance-attribute

failure_detail = None class-attribute instance-attribute

CancelResult(scope_id, generation, terminal_at) dataclass

The cancel succeeded: the scope is terminal as of terminal_at.

scope_id instance-attribute

generation instance-attribute

terminal_at instance-attribute

CancelWorkflow(scope_id, generation, now, force=False, reason='') dataclass

Move a non-terminal scope to cancelled.

The state machine's guard is "holds the current generation or explicit force" — the command carries both, so an unfenced cancel (the defect app/_workflow_control.py's bare except hides today) has no shape to arrive in. A terminal scope is refused on commit; it is never mutated.

scope_id instance-attribute

generation instance-attribute

now instance-attribute

force = False class-attribute instance-attribute

reason = '' class-attribute instance-attribute

Claimed(scope_id, generation, expires_at) dataclass

The claim succeeded: this walk now holds the generation.

scope_id instance-attribute

generation instance-attribute

expires_at instance-attribute

ClaimWorkflow(scope_id, owner, now, lease_seconds, force=False) dataclass

Take a workflow scope, fencing every later write this walk makes.

A single-command transaction that commits on the spot, which is why claim is the one writer allowed to return something read back.

scope_id instance-attribute

owner instance-attribute

now instance-attribute

lease_seconds instance-attribute

force = False class-attribute instance-attribute

CompleteStep(scope_id, generation, step_key, now, iteration=0, status='success', result=None, decision_key=None, chosen_target=None, position=None, scope_status='running', reusable=False, result_kind=None, result_type=None, inputs=None, effecting=False, attempt=0, started_at=None) dataclass

One step's outcome, and the scope's advance to its next position.

Mid-walk the scope stays running; reaching END makes it completed and a terminal failure makes it failed. Which of those this is, is the engine's decision (ADR-025: the engine owns transition meaning, stores own durability) — the command carries the resulting scope status as a value so the store never has to contain the word "resume" in a conditional.

scope_id instance-attribute

generation instance-attribute

step_key instance-attribute

now instance-attribute

iteration = 0 class-attribute instance-attribute

status = 'success' class-attribute instance-attribute

result = None class-attribute instance-attribute

decision_key = None class-attribute instance-attribute

chosen_target = None class-attribute instance-attribute

position = None class-attribute instance-attribute

scope_status = 'running' class-attribute instance-attribute

reusable = False class-attribute instance-attribute

result_kind = None class-attribute instance-attribute

result_type = None class-attribute instance-attribute

inputs = None class-attribute instance-attribute

effecting = False class-attribute instance-attribute

attempt = 0 class-attribute instance-attribute

started_at = None class-attribute instance-attribute

Conflict(scope_id, held_by, held_generation) dataclass

The claim was refused: someone else holds the scope.

A value, never an exception. Names the holder and the held generation — the reader's question on hitting it is always who, and how stale am I.

scope_id instance-attribute

held_by instance-attribute

held_generation instance-attribute

ConsumeInput(scope_id, generation, request_id, now) dataclass

Mark a request's accepted answer as used by the walk.

Consumption has one writer: the walk that feeds the payload to the gate's consumer. A deposit records that an answer exists; this command records that the workflow moved on it — two different facts, which is why accepting a candidate does not consume it and why a surface answering a gate never issues this.

Idempotent by rule: consuming a request that is already consumed is a no-op, so a replayed resume cannot fail for having done its work twice.

scope_id instance-attribute

generation instance-attribute

request_id instance-attribute

now instance-attribute

EffectIntent(namespace, topic, payload, idempotency_key) dataclass

An effect to deliver once the transition it belongs to has committed.

What a recorder hands :meth:EffectWriter.append, as a value, so the decision to publish is made beside the transition and the store only records it. idempotency_key is required here, unlike on the port: an intent this framework records is always one a receiver must be able to deduplicate, because delivery is at-least-once.

namespace instance-attribute

topic instance-attribute

payload instance-attribute

idempotency_key instance-attribute

EffectQueue

Bases: Protocol

The outbox's claim-and-acknowledge side.

claim(topics, *, now, lease_seconds, limit)

Atomically take up to limit due intents for topics.

Due means pending with available_at <= now, or claimed under a lease that has expired. Each returned view carries a fresh claim_token and its incremented attempts.

Source code in src/functualize/_types/persistence.py
def claim(
    self,
    topics: Sequence[str],
    *,
    now: datetime,
    lease_seconds: float,
    limit: int,
) -> Sequence[EffectView]:
    """Atomically take up to ``limit`` due intents for ``topics``.

    Due means ``pending`` with ``available_at <= now``, or ``claimed``
    under a lease that has expired. Each returned view carries a fresh
    ``claim_token`` and its incremented ``attempts``.
    """
    ...

published(effect, *, now)

Acknowledge delivery; a stale claim_token changes nothing.

Source code in src/functualize/_types/persistence.py
def published(self, effect: EffectView, *, now: datetime) -> None:
    """Acknowledge delivery; a stale ``claim_token`` changes nothing."""

failed(effect, *, error, retry_at)

Return the intent to pending with its error and next try.

Source code in src/functualize/_types/persistence.py
def failed(self, effect: EffectView, *, error: str, retry_at: datetime) -> None:
    """Return the intent to ``pending`` with its error and next try."""

effect(effect_id)

One outbox row by id, whatever its status.

Source code in src/functualize/_types/persistence.py
def effect(self, effect_id: str) -> EffectView | None:
    """One outbox row by id, whatever its status."""

EffectReceiver

Bases: Protocol

What consumes one outbox topic.

receive may be called more than once for the same intent — after a crash, or after it raised — so it deduplicates on effect.idempotency_key before acting. Raising reschedules the intent; returning acknowledges it.

topic instance-attribute

receive(effect)

Source code in src/functualize/_types/persistence.py
def receive(self, effect: EffectView) -> None: ...

EffectView(effect_id, topic, aggregate_type, aggregate_id, payload, idempotency_key, status, attempts, available_at, claimed_at=None, published_at=None, last_error=None, claim_token=None) dataclass

One outbox row, as a dispatcher and a receiver see it.

status is pending, claimed or published (_types/lifecycle.OUTBOX). attempts counts claims, so a receiver handed attempts > 1 knows it may have seen this effect before — which it must assume anyway: delivery is at-least-once, and idempotency_key is what a receiver deduplicates on. claim_token identifies the claim this view was handed under; an acknowledgement carrying a stale token changes nothing.

effect_id instance-attribute

topic instance-attribute

aggregate_type instance-attribute

aggregate_id instance-attribute

payload instance-attribute

idempotency_key instance-attribute

status instance-attribute

attempts instance-attribute

available_at instance-attribute

claimed_at = None class-attribute instance-attribute

published_at = None class-attribute instance-attribute

last_error = None class-attribute instance-attribute

claim_token = None class-attribute instance-attribute

EffectWriter

Bases: Protocol

The outbox, appended to — an intent to reach the outside world.

Recording the intent is all that happens inside the transaction: claiming a row, calling the provider and acknowledging the result run outside it (contributor/reference/runtime-persistence-data-model.md §4), which is the difference between an outbox and a retry loop. idempotency_key is optional because the column is unique only where present.

append(namespace, topic, payload=None, idempotency_key=None)

Source code in src/functualize/_types/persistence.py
def append(
    self,
    namespace: str,
    topic: str,
    payload: Any = None,
    idempotency_key: str | None = None,
) -> None: ...

EventView(seq, type, occurred_at, payload=None, run_id=None) dataclass

One append-only event, at its sequence number.

Events answer "what happened after point N" — the sequence is the contract, and no event is ever rewritten.

seq instance-attribute

type instance-attribute

occurred_at instance-attribute

payload = None class-attribute instance-attribute

run_id = None class-attribute instance-attribute

EventWriter

Bases: Protocol

The append-only event streams, appended to.

Scope events and run events share this shape, which is why run_id is optional: it names the run whose step produced the event when one did. The store assigns seq and nothing rewrites a row, which is what makes "what happened after point N" answerable. A scope event may name its scope and held generation directly, without another write in the transaction. A generation of 0 is unfenced. When the scope is omitted, it is inferred from the transaction's single scope write. Naming both run_id and scope_id raises ValueError.

append(type, payload=None, run_id=None, *, scope_id=None, generation=0)

Source code in src/functualize/_types/persistence.py
def append(
    self,
    type: str,
    payload: Any = None,
    run_id: str | None = None,
    *,
    scope_id: str | None = None,
    generation: int = 0,
) -> None: ...

FinishAttempt(run_id, attempt_no, status, now, failure_code=None, failure_detail=None) dataclass

Record how one attempt ended, and the run's outcome when terminal.

The attempt's own outcome is final here; the run's status is derived from its last attempt plus its cancellation flag, and the store settles both in the one commit. Rendering and EventBus notification run outside the transaction.

run_id instance-attribute

attempt_no instance-attribute

status instance-attribute

now instance-attribute

failure_code = None class-attribute instance-attribute

failure_detail = None class-attribute instance-attribute

InputReader

Bases: Protocol

Questions about gates waiting on an answer.

open_for is the blocked walk asking about its own gate; awaiting is the workspace-wide question a human-facing surface asks ("what is waiting on me"). One OPEN request per scope, gate and generation is the invariant both read against.

:meth:request and :meth:candidates_for are the resolution read: a notification or surface that holds a request id — which is the point of the id — asks for the request and its candidates without knowing the scope and gate it was opened for. The candidates come back with their recorded evaluations and are never re-validated: the outcome is a fact about submission time, and re-evaluating on read would make the record drift with the model classes instead of preserving what happened.

open_for(scope_id)

Source code in src/functualize/_types/persistence.py
def open_for(self, scope_id: str) -> InputRequest | None: ...

awaiting()

Source code in src/functualize/_types/persistence.py
def awaiting(self) -> Sequence[InputRequest]: ...

request(request_id)

Source code in src/functualize/_types/persistence.py
def request(self, request_id: str) -> InputRequest | None: ...

candidates_for(request_id)

Source code in src/functualize/_types/persistence.py
def candidates_for(self, request_id: str) -> Sequence[GateCandidate]: ...

decision(request_id)

The recorded decision on this request, None while undecided.

Source code in src/functualize/_types/persistence.py
def decision(self, request_id: str) -> GateDecision | None:
    """The recorded decision on this request, ``None`` while undecided."""

for_gate(scope_id, gate_name)

The newest request on this scope's gate, whatever its status.

Source code in src/functualize/_types/persistence.py
def for_gate(self, scope_id: str, gate_name: str) -> InputRequest | None:
    """The newest request on this scope's gate, whatever its status."""

deposited_answer(scope_id, gate_name)

The answer this store holds on the gate that no candidate records.

Only a store with a legacy deposit path can hold one: a gate record written before requests existed, or by the legacy deposit helper, keeps its answer as a bare payload. Read-only, never re-validated, fed to replay as it was.

Source code in src/functualize/_types/persistence.py
def deposited_answer(self, scope_id: str, gate_name: str) -> Any | None:
    """The answer this store holds on the gate that no candidate records.

    Only a store with a legacy deposit path can hold one: a gate record
    written before requests existed, or by the legacy deposit helper,
    keeps its answer as a bare payload. Read-only, never re-validated,
    fed to replay as it was.
    """

InputRequest(request_id, scope_id, gate_name, generation, status, created_at, schema=None, prompt=None, resolved_at=None, run_id=None, position=None) dataclass

A gate's question, and where its answer stands.

One OPEN request per scope, gate and generation. Consumption is a write (consumed, not a silent read): a replayed read is idempotent, but the moment an agent rather than a human can deposit a second candidate, "was this answer used?" stops being benign to leave unrecorded.

request_id is the request's identity, stable across resumes and carries-able by a notification that points at it. A scope-and-gate pair that is reopened does not reuse the id: the superseded request keeps its own, and the new request mints a new one.

The causal identity of an answer is its request's: run_id (the run executing when the gate opened, None when none was recorded), scope_id (the workflow), position (the step — the gate's node) and generation (the walk attempt; every resume claims a new one).

request_id instance-attribute

scope_id instance-attribute

gate_name instance-attribute

generation instance-attribute

status instance-attribute

created_at instance-attribute

schema = None class-attribute instance-attribute

prompt = None class-attribute instance-attribute

resolved_at = None class-attribute instance-attribute

run_id = None class-attribute instance-attribute

position = None class-attribute instance-attribute

InputWriter

Bases: Protocol

The inputs aggregate, appended to.

Append-only in fact, not only in shape: a second candidate never overwrites the first (contributor/reference/runtime-persistence-data-model.md §2.4 — today's overwrite is the defect it names). The request row itself is opened by SuspendAtGate; accepting a candidate is this port's job and consuming it is :meth:consume's.

Store rules, which every backend binds:

  • Appending to a request that is not open raises InputRequestNotOpenError and applies nothing from the unit — an answered or consumed request is never rewritten, and a refusal that half-applied would be.
  • An accepted candidate moves the request to accepted. Consuming it is a separate, later write.
  • Consuming a request that is already consumed is a no-op, so a replayed resume is idempotent.

The ids are minted by the recorder, not the store. This port accumulates: a writer call buffers a command and issues nothing until the unit commits, so a store-minted id could not be referenced by a later command in the same batch — nothing has been written yet to mint it in. The recorder mints both the request id (when the gate opens) and the candidate id (at submission) before anything is buffered, which is what lets one unit open a request, record its candidates and consume the accepted one by name.

append(candidate)

Source code in src/functualize/_types/persistence.py
def append(self, candidate: GateCandidate) -> None: ...

consume(cmd)

Source code in src/functualize/_types/persistence.py
def consume(self, cmd: ConsumeInput) -> None: ...

decide(decision)

Record why a request was accepted, beside the accepted candidate.

Issued in the unit that appends the accepted candidate. One decision per request; a second is refused, because a decision is a fact about one moment and a later one would be a different request (reopen).

Source code in src/functualize/_types/persistence.py
def decide(self, decision: GateDecision) -> None:
    """Record why a request was accepted, beside the accepted candidate.

    Issued in the unit that appends the accepted candidate. One decision
    per request; a second is refused, because a decision is a fact about
    one moment and a later one would be a different request (reopen).
    """

supersede(cmd)

Withdraw the gate's accepted answer and open a new request.

Source code in src/functualize/_types/persistence.py
def supersede(self, cmd: SupersedeRequest) -> None:
    """Withdraw the gate's accepted answer and open a new request."""

MoveScope(scope_id, generation, status, position, now) dataclass

A status-and-position move with no step record.

The moves that are not a step completing: a nested gate blocking the scope, and END reached by a path that records no step of its own.

scope_id instance-attribute

generation instance-attribute

status instance-attribute

position instance-attribute

now instance-attribute

OutboxStore

Bases: RuntimeStore, Protocol

A runtime store with an outbox — every store whose profile declares durable_outbox=True, and only those. Boot refuses a store whose profile and type disagree, so the capability has one meaning.

effects instance-attribute

PreparedStore(store, substrate) dataclass

What a factory hands boot: the store, and the substrate for derived data.

store instance-attribute

substrate instance-attribute

RecordBranch(scope_id, generation, decision_key, chosen_target, now) dataclass

An immutable decision: a conditional choice, a failure route, a marker.

Recording the same (scope, decision_key) with the same target again is a no-op (a replay); a different target raises, because the branch a resumed walk reads is the one it originally took.

scope_id instance-attribute

generation instance-attribute

decision_key instance-attribute

chosen_target instance-attribute

now instance-attribute

RecordStep(scope_id, generation, step_key, now, completed_at, iteration=0, status='success', result=None, reusable=False, result_kind=None, result_type=None, inputs=None, effecting=False, attempt=0, started_at=None) dataclass

A step record that moves neither position nor status.

The step records that are not a node completing in the frontier's sense: a step timed out on takeover, a failure routed to its fallback, and the epilogue — the workflow body's return value under EPILOGUE_STEP_KEY.

scope_id instance-attribute

generation instance-attribute

step_key instance-attribute

now instance-attribute

completed_at instance-attribute

iteration = 0 class-attribute instance-attribute

status = 'success' class-attribute instance-attribute

result = None class-attribute instance-attribute

reusable = False class-attribute instance-attribute

result_kind = None class-attribute instance-attribute

result_type = None class-attribute instance-attribute

inputs = None class-attribute instance-attribute

effecting = False class-attribute instance-attribute

attempt = 0 class-attribute instance-attribute

started_at = None class-attribute instance-attribute

ReleaseLease(scope_id, generation, now) dataclass

Expire the held lease while preserving its generation.

scope_id instance-attribute

generation instance-attribute

now instance-attribute

RenewLease(scope_id, generation, owner, now, lease_seconds) dataclass

Extend the held lease without advancing its generation.

scope_id instance-attribute

generation instance-attribute

owner instance-attribute

now instance-attribute

lease_seconds instance-attribute

Resumed(scope_id, generation, expires_at) dataclass

The resume succeeded: the request was consumed and a new generation taken, so writes from the suspended walk are now fenced out.

scope_id instance-attribute

generation instance-attribute

expires_at instance-attribute

ResumeWorkflow(scope_id, owner, gate_name, now, lease_seconds, force=False) dataclass

Consume an accepted input request and reclaim the scope it paused.

Resume is a claim at a new generation, one transaction — today the deposit and the claim are two locked writes in different call frames, and the window between them is why this command exists. Acquisition-shaped like ClaimWorkflow: no held generation, because it takes one.

scope_id instance-attribute

owner instance-attribute

gate_name instance-attribute

now instance-attribute

lease_seconds instance-attribute

force = False class-attribute instance-attribute

RunQuery(job=None, status=None, scope_id=None, parent_run_id=None, limit=None, tags=()) dataclass

Filters for "what ran recently". None means "do not filter".

Every tag must match for a run to be included.

job = None class-attribute instance-attribute

status = None class-attribute instance-attribute

scope_id = None class-attribute instance-attribute

parent_run_id = None class-attribute instance-attribute

limit = None class-attribute instance-attribute

tags = () class-attribute instance-attribute

RunReader

Bases: Protocol

Questions about runs and their attempts.

run(run_id)

Source code in src/functualize/_types/persistence.py
def run(self, run_id: str) -> RunView | None: ...

recent(query)

Source code in src/functualize/_types/persistence.py
def recent(self, query: RunQuery) -> Sequence[RunView]: ...

tree(root_run_id)

Source code in src/functualize/_types/persistence.py
def tree(self, root_run_id: str) -> RunTree: ...

RuntimeStore

Bases: Protocol

One selected store. Constructed once, by _app, after config resolves.

Reads are question-shaped and always available; everything written goes through :meth:transaction, so a read never needs a unit to be open. close() is the lifecycle the port never had: SQLiteSubstrate caches one connection per thread in threading.local() and nothing closes them, which had no answer at all while storage was discovered lazily inside the engine.

profile instance-attribute

runs instance-attribute

workflows instance-attribute

inputs instance-attribute

transaction()

Source code in src/functualize/_types/persistence.py
def transaction(self) -> AbstractContextManager[RuntimeTransaction]: ...

close()

Source code in src/functualize/_types/persistence.py
def close(self) -> None: ...

RuntimeStoreConfig(url, scheme, project_root, config_key='runtime_store.url') dataclass

What boot resolved for the store: the URL and where the project lives.

url instance-attribute

scheme instance-attribute

project_root instance-attribute

config_key = 'runtime_store.url' class-attribute instance-attribute

RuntimeStoreFactory

Bases: Protocol

A backend boot can select by URL scheme.

profile is declared before :meth:prepare runs, so a refusal on a missing capability needs no I/O.

scheme instance-attribute

profile instance-attribute

prepare(config)

Open, migrate, health-check. Raise to abort boot; never degrade.

Source code in src/functualize/_types/persistence.py
def prepare(self, config: RuntimeStoreConfig) -> PreparedStore:
    """Open, migrate, health-check. Raise to abort boot; never degrade."""
    ...

unselected_data(project_root)

A sentence naming runtime data this backend holds, or None.

Asked only when nothing is configured: a backend that holds data the default store would not see refuses boot rather than strand it.

Source code in src/functualize/_types/persistence.py
def unselected_data(self, project_root: Path) -> str | None:
    """A sentence naming runtime data this backend holds, or ``None``.

    Asked only when nothing is configured: a backend that holds data the
    default store would not see refuses boot rather than strand it.
    """
    ...

RuntimeTransaction

Bases: Protocol

Everything written inside one short transition.

A transaction NEVER wraps a job body, a prompt, an agent call or any network effect — user code may block or run for hours, and holding a unit open across it holds locks and connections for that long. A transaction surrounds a transition, and nothing else.

Writers accumulate; __exit__ commits once. Calling a writer appends a command to this transaction and issues no statement; the whole batch is applied as one unit when the block exits cleanly and discarded otherwise. Forced by the backend, not chosen for style: Cloudflare D1 has no interactive transaction, so a streaming port is unimplementable there (the module docstring carries the measured citation). Locally the same batch is one BEGIN/COMMIT; on D1 it is one batch request; on a store declaring cross_aggregate_atomicity=False it is a documented refusal raised on commit with nothing applied — applied in parts would be defect B3 under a new name.

runs instance-attribute

workflows instance-attribute

inputs instance-attribute

events instance-attribute

effects instance-attribute

RunTree(run, children=()) dataclass

A run and everything it invoked, nested as it was invoked.

run instance-attribute

children = () class-attribute instance-attribute

RunView(run_id, job, surface, status, started_at, scope_id=None, parent_run_id=None, invoke_depth=0, args_hash=None, ended_at=None, run_tags=dict()) dataclass

A run as history sees it: identity, placement and outcome.

Derived display states (stalled, abandoned and friends) are functions of the lease clock and are never stored or carried here.

run_id instance-attribute

job instance-attribute

surface instance-attribute

status instance-attribute

started_at instance-attribute

scope_id = None class-attribute instance-attribute

parent_run_id = None class-attribute instance-attribute

invoke_depth = 0 class-attribute instance-attribute

args_hash = None class-attribute instance-attribute

ended_at = None class-attribute instance-attribute

run_tags = field(default_factory=dict) class-attribute instance-attribute

RunWriter

Bases: Protocol

The runs-and-attempts aggregate, written.

Two commands, both issued by a recorder (_engine/recording/, T9): a run is opened once and attempts are appended to it, never mutated in place.

start_attempt(cmd)

Source code in src/functualize/_types/persistence.py
def start_attempt(self, cmd: StartAttempt) -> None: ...

finish_attempt(cmd)

Source code in src/functualize/_types/persistence.py
def finish_attempt(self, cmd: FinishAttempt) -> None: ...

StartAttempt(job, surface, now, scope_id=None, parent_run_id=None, invoke_depth=0, args_hash=None, run_tags=dict(), run_id=None) dataclass

Open a run and its first attempt as one transition.

start_attempt and not start_run: an attempt is one execution of a job body, a run is the logical unit the user asked for, and a retry inserts the next attempt rather than overwriting — which is what makes "how many times did this fail before it worked" answerable. The store mints the run and attempt identity when run_id is absent. The engine supplies its run-log identity when it also records the relational run. This port does not hand the identity back: every writer but claim returns None (contracts.md §1.3).

job instance-attribute

surface instance-attribute

now instance-attribute

scope_id = None class-attribute instance-attribute

parent_run_id = None class-attribute instance-attribute

invoke_depth = 0 class-attribute instance-attribute

args_hash = None class-attribute instance-attribute

run_tags = field(default_factory=dict) class-attribute instance-attribute

run_id = None class-attribute instance-attribute

StartWalk(scope_id, generation, workflow, entry, graph_digest, now) dataclass

Ensure the scope exists, stamp it running, and settle its position.

The walk's entry write: the first entry creates the scope at the graph's entry node, and a resume keeps the persisted position it finds (replay resumes there rather than re-entering at the entry).

scope_id instance-attribute

generation instance-attribute

workflow instance-attribute

entry instance-attribute

graph_digest instance-attribute

now instance-attribute

StateBatch(scope_id, generation, now, upserts, deletes=()) dataclass

Upsert and delete one scope's state keys under the fence.

Every write carries the held generation in the store's predicate, which is what makes a stale writer's update match zero rows structurally rather than by a caller remembering to check. Arguments are hashes only, never values — argument content is a redaction and retention decision that belongs to someone else.

upserts is shallow-frozen: frozen=True pins the attribute binding, not the mapping's contents, and from T6 a transaction buffers this command until __exit__ — a caller that mutated the mapping after handing it over would change what commits. The discipline is stated rather than enforced, because a zero-logic vocabulary type cannot deep-freeze a mapping without growing a constructor, and it binds two parties: a recorder hands over a mapping it will not touch again, and a transaction that cannot rely on that copies on append.

scope_id instance-attribute

generation instance-attribute

now instance-attribute

upserts instance-attribute

deletes = () class-attribute instance-attribute

StepView(scope_id, step_key, iteration, status, result=None, reusable=False, result_kind=None, result_type=None, inputs=None, effecting=False, attempt=0, started_at=None, completed_at=None) dataclass

One step record as a reader finds it.

Carries the classified-return metadata the walk records on the step, so a resumed process can answer "was this reusable, and as what" without the declaration that produced it — which may have changed since it ran.

scope_id instance-attribute

step_key instance-attribute

iteration instance-attribute

status instance-attribute

result = None class-attribute instance-attribute

reusable = False class-attribute instance-attribute

result_kind = None class-attribute instance-attribute

result_type = None class-attribute instance-attribute

inputs = None class-attribute instance-attribute

effecting = False class-attribute instance-attribute

attempt = 0 class-attribute instance-attribute

started_at = None class-attribute instance-attribute

completed_at = None class-attribute instance-attribute

StoreProfile(name, cross_aggregate_atomicity, fencing, multi_process, multi_machine, durable_outbox, versioned_migrations, interactive_transaction, remote, max_document_bytes, offline_capable, description='') dataclass

What this store can actually promise. Checked at boot, never probed.

The authority for every field's value across the eight measured backends is contributor/reference/substrate-capability-matrix.md; nothing here is re-derived from vendor documentation. A feature declares what it needs and boot refuses rather than degrading — a silent downgrade is the failure mode this type exists to make impossible.

name instance-attribute

cross_aggregate_atomicity instance-attribute

fencing instance-attribute

multi_process instance-attribute

multi_machine instance-attribute

durable_outbox instance-attribute

versioned_migrations instance-attribute

interactive_transaction instance-attribute

remote instance-attribute

max_document_bytes instance-attribute

offline_capable instance-attribute

description = '' class-attribute instance-attribute

SupersedeRequest(scope_id, gate_name, request_id, new_request_id, now) dataclass

Withdraw an accepted answer and reopen its gate under a new request.

Reopen through the port. The accepted request moves to cancelled (member decision D-4: accepted → cancelled is legal exactly here) and keeps every candidate it recorded; a new open request at the same generation takes the gate. Refused unless request_id is the gate's accepted, unconsumed request — an answer the walk has already used cannot be withdrawn underneath it.

new_request_id is the recorder's, for the reason every id here is (see :class:InputWriter).

scope_id instance-attribute

gate_name instance-attribute

request_id instance-attribute

new_request_id instance-attribute

now instance-attribute

SuspendAtGate(scope_id, generation, gate_name, request_id, position, now, schema=None, prompt=None, model='', tools=(), scope_status='blocked', run_id=None, supersedes=None) dataclass

Open a gate request and record the scope's resulting status.

A gate that waits moves the scope to blocked. A ladder that answers inline leaves it running; both paths create the request through the same transaction and the same lifecycle-checked scope writer.

request_id is the request's own identity, minted by the recorder before this command is buffered — see :class:InputWriter for why the id is the caller's and never the store's. model and tools are what an answering agent needs to learn the question without importing the declaring module: the model's class name and the gate's bound tool specs.

scope_id instance-attribute

generation instance-attribute

gate_name instance-attribute

request_id instance-attribute

position instance-attribute

now instance-attribute

schema = None class-attribute instance-attribute

prompt = None class-attribute instance-attribute

model = '' class-attribute instance-attribute

tools = () class-attribute instance-attribute

scope_status = 'blocked' class-attribute instance-attribute

run_id = None class-attribute instance-attribute

supersedes = None class-attribute instance-attribute

WorkflowQuery(workflow=None, status=None, limit=None) dataclass

Filters for "what can I resume". None means "do not filter".

workflow = None class-attribute instance-attribute

status = None class-attribute instance-attribute

limit = None class-attribute instance-attribute

WorkflowReader

Bases: Protocol

Questions about scopes: what can I resume, and what happened since.

workflow(scope_id)

Source code in src/functualize/_types/persistence.py
def workflow(self, scope_id: str) -> WorkflowView | None: ...

resumable(query)

Source code in src/functualize/_types/persistence.py
def resumable(self, query: WorkflowQuery) -> Sequence[WorkflowView]: ...

events_after(scope_id, seq)

Source code in src/functualize/_types/persistence.py
def events_after(self, scope_id: str, seq: int) -> Sequence[EventView]: ...

step(scope_id, step_key, iteration=0)

Source code in src/functualize/_types/persistence.py
def step(
    self, scope_id: str, step_key: str, iteration: int = 0
) -> StepView | None: ...

steps(scope_id)

Source code in src/functualize/_types/persistence.py
def steps(self, scope_id: str) -> Sequence[StepView]: ...

branch(scope_id, decision_key)

Source code in src/functualize/_types/persistence.py
def branch(self, scope_id: str, decision_key: str) -> str | None: ...

branches(scope_id)

Every decision record of one scope, in one read.

Raw: {decision_key: chosen_target} exactly as RecordBranch wrote them, bookkeeping keys included — sorting records into kinds is the engine's, never a store's. Iterates in recording order. An unknown scope, or one with no records, is an empty mapping, never an error.

Source code in src/functualize/_types/persistence.py
def branches(self, scope_id: str) -> Mapping[str, str]:
    """Every decision record of one scope, in one read.

    Raw: ``{decision_key: chosen_target}`` exactly as ``RecordBranch``
    wrote them, bookkeeping keys included — sorting records into kinds is
    the engine's, never a store's. Iterates in recording order. An unknown
    scope, or one with no records, is an empty mapping, never an error.
    """
    ...

state(scope_id)

Source code in src/functualize/_types/persistence.py
def state(self, scope_id: str) -> Mapping[str, Any]: ...

WorkflowView(scope_id, workflow, status, position=None, generation=None, owner=None, expires_at=None, created_at=None, updated_at=None, terminal_at=None, graph_digest=None) dataclass

A workflow scope as a reader finds it, lease included.

generation is None when the scope has never been claimed. The stored status is one of the state machine's four; everything a user sees beyond them is derived at render time.

scope_id instance-attribute

workflow instance-attribute

status instance-attribute

position = None class-attribute instance-attribute

generation = None class-attribute instance-attribute

owner = None class-attribute instance-attribute

expires_at = None class-attribute instance-attribute

created_at = None class-attribute instance-attribute

updated_at = None class-attribute instance-attribute

terminal_at = None class-attribute instance-attribute

graph_digest = None class-attribute instance-attribute

WorkflowWriter

Bases: Protocol

The workflow scope aggregate, written.

claim is the only method in the whole writer contract that answers with something read back; everything else returns None.

claim(cmd)

Source code in src/functualize/_types/persistence.py
def claim(self, cmd: ClaimWorkflow) -> Claimed | Conflict: ...

renew(cmd)

Source code in src/functualize/_types/persistence.py
def renew(self, cmd: RenewLease) -> None: ...

release(cmd)

Source code in src/functualize/_types/persistence.py
def release(self, cmd: ReleaseLease) -> None: ...

start(cmd)

Source code in src/functualize/_types/persistence.py
def start(self, cmd: StartWalk) -> None: ...

complete_step(cmd)

Source code in src/functualize/_types/persistence.py
def complete_step(self, cmd: CompleteStep) -> None: ...

record_step(cmd)

Source code in src/functualize/_types/persistence.py
def record_step(self, cmd: RecordStep) -> None: ...

record_branch(cmd)

Source code in src/functualize/_types/persistence.py
def record_branch(self, cmd: RecordBranch) -> None: ...

move(cmd)

Source code in src/functualize/_types/persistence.py
def move(self, cmd: MoveScope) -> None: ...

suspend(cmd)

Source code in src/functualize/_types/persistence.py
def suspend(self, cmd: SuspendAtGate) -> None: ...

resume(cmd)

Source code in src/functualize/_types/persistence.py
def resume(self, cmd: ResumeWorkflow) -> None: ...

cancel(cmd)

Source code in src/functualize/_types/persistence.py
def cancel(self, cmd: CancelWorkflow) -> None: ...

write_state(cmd)

Source code in src/functualize/_types/persistence.py
def write_state(self, cmd: StateBatch) -> None: ...

AdapterPlugin

Bases: Protocol

Protocol for delivery surface adapters.

Adapters decouple delivery surfaces (CLI, HTTP, Lambda, MCP) from the application kernel. Each adapter implements a setup/run/shutdown lifecycle.

name instance-attribute

version instance-attribute

description instance-attribute

adapter_type instance-attribute

__call__(app)

Setup phase — called during boot to wire the adapter.

app: PluginHost since plugin-host-protocol/T9, replacing Any. This is the framework's own front door: an adapter is the thing the kernel hands itself to, so if any signature in the repository should name what it is being handed, it is this one.

Widening, not narrowing. An adapter that declares app: FunctualizeApp no longer satisfies this protocol — a parameter type is contravariant, so an implementation must accept at least what the protocol promises to pass, and FunctualizeApp is one PluginHost rather than any. The four concrete adapters that did were widened by T10.

Source code in src/functualize/_types/protocols.py
def __call__(self, app: PluginHost) -> None:
    """Setup phase — called during boot to wire the adapter.

    ``app: PluginHost`` since `plugin-host-protocol`/T9, replacing ``Any``.
    This is the framework's own front door: an adapter is the thing the
    kernel hands itself to, so if any signature in the repository should
    name what it is being handed, it is this one.

    **Widening, not narrowing.** An adapter that declares
    ``app: FunctualizeApp`` no longer satisfies this protocol — a parameter
    type is contravariant, so an implementation must accept *at least* what
    the protocol promises to pass, and ``FunctualizeApp`` is one
    ``PluginHost`` rather than any. The four concrete adapters that did
    were widened by T10.
    """
    ...

run(*args, **kwargs)

Universal entrypoint with platform-specific signatures.

Source code in src/functualize/_types/protocols.py
def run(self, *args: Any, **kwargs: Any) -> Any:
    """Universal entrypoint with platform-specific signatures."""
    ...

shutdown()

Graceful shutdown. No-op if not needed.

Source code in src/functualize/_types/protocols.py
def shutdown(self) -> None:
    """Graceful shutdown. No-op if not needed."""
    ...

AgentCapability

Bases: StrEnum

A constraint an executor promises it can enforce on a step's behalf.

Declared by the executor, required by the step, and compared before the walk starts. A step whose requirement the executor cannot honour is refused rather than run, because running it would leave the constraint silently unenforced — a workflow that appears to have restricted tools it left wide open.

A StrEnum rather than (str, Enum) for the same reason :class:~functualize._types.outcome.Family is one: the contracts spell it (str, Enum), and on this interpreter that is the same type with a UP042 warning attached.

ENFORCES_TOOL_ALLOWLIST = 'enforces_tool_allowlist' class-attribute instance-attribute

PRESERVES_ACTIVE_TIME_BUDGET = 'preserves_active_time_budget' class-attribute instance-attribute

SUPPORTS_VISIBLE_OUTPUT = 'supports_visible_output' class-attribute instance-attribute

AgentStepContext(request, step_name, instructions, tools, inputs, time_budget_s) dataclass

Everything an executor is given to perform one agent step.

It carries the run's :class:~functualize._types.run_request.RunRequest rather than restating its fields: the request already holds where the run came from and what it was asked for, and a second shape for those would be a second answer to where a run came from.

Attributes:

Name Type Description
request RunRequest

The request the run reaching this step was built from.

step_name str

The declaring node's name — the step being executed.

instructions str

What the step asks the agent to do.

tools tuple[str, ...]

The tool allowlist the step declared, normalized to a tuple. An empty tuple means the step declared no constraint, which is not the same statement as "this step may use no tools".

inputs Mapping[str, Any]

The values the step binds into the agent's work. TRANSITIONAL(workflow-graph-semantics) — always empty today. The port's single construction site passes an empty mapping, because binding an upstream node's output into a downstream step is the typed-outcome plumbing that feature builds; there is no other source for it. An executor may read it and will get nothing (asp M-3). Declared now rather than added later so the payload shape a plugin compiles against does not change under it.

time_budget_s float | None

The step's active-time budget in seconds, when it declared one.

request instance-attribute

step_name instance-attribute

instructions instance-attribute

tools instance-attribute

inputs instance-attribute

time_budget_s instance-attribute

AgentStepExecutor

Bases: Protocol

Protocol for running a workflow step by delegating it to an agent.

Registered by an app method — app.extensions.register_agent_step_executor — and never auto-discovered: auto-discovery is how a surface acquires behaviour nobody declared. GateResolver is the template, down to the registration door.

The engine asks an executor only for steps that named it, or for every agent step when exactly one executor is registered. Nothing falls back to a different executor, and nothing falls back to a human.

capabilities is a promise, and a missing flag is a refusal, not a default: a step requiring :attr:AgentCapability.ENFORCES_TOOL_ALLOWLIST from an executor that does not declare it fails validation, because running anyway would grant every tool the step meant to leave out.

Implementations are checked with isinstance; issubclass raises TypeError on this Protocol, because name and capabilities are data members — a fact no type checker will point out at the call site.

name instance-attribute

capabilities instance-attribute

execute(ctx)

Perform one agent step.

Parameters:

Name Type Description Default
ctx AgentStepContext

The step, its inputs, and the request that reached it.

required

Returns:

Type Description
AgentStepResult

The step's result.

Raises:

Type Description
Exception

Any exception fails the step. How a failure is routed around a step is not this port's business, and no exception here is answered by asking a human instead.

Source code in src/functualize/_types/protocols.py
def execute(self, ctx: AgentStepContext) -> AgentStepResult:
    """Perform one agent step.

    Args:
        ctx: The step, its inputs, and the request that reached it.

    Returns:
        The step's result.

    Raises:
        Exception: Any exception fails the step. How a failure is routed
            around a step is not this port's business, and no exception
            here is answered by asking a human instead.
    """
    ...

AgentStepResult(value, tool_calls=()) dataclass

What an executor returns for one agent step.

Attributes:

Name Type Description
value Any

The step's result, recorded as the step's outcome.

tool_calls tuple[Mapping[str, Any], ...]

The tool invocations the agent reported, in order. Empty for an executor that does not surface them — an audit trail, not a contract, so nothing may require a non-empty tuple. TRANSITIONAL(durable-run-layer) — the walker takes result.value and drops this, so an executor that fills it is writing the audit trail into nowhere. It lands when there is a run event stream to write it to; recording it in the step record first would put an unbounded, agent-controlled payload in the scope store (asp M-3).

value instance-attribute

tool_calls = () class-attribute instance-attribute

FormatProvider

Bases: Protocol

Protocol for configuration file format plugins.

Implementations parse configuration files into normalized dictionaries and serialize dictionaries back to formatted strings.

extensions()

Return file extensions this provider handles (e.g., ['.toml']).

Each extension MUST include the leading dot.

Source code in src/functualize/_types/protocols.py
def extensions(self) -> list[str]:
    """Return file extensions this provider handles (e.g., ['.toml']).

    Each extension MUST include the leading dot.
    """
    ...

parse(path)

Parse a configuration file and return a normalized dictionary.

Parameters:

Name Type Description Default
path str

Absolute path to the configuration file.

required

Returns:

Type Description
dict[str, Any]

Normalized dict with primitive values, lists, or nested dicts.

Source code in src/functualize/_types/protocols.py
def parse(self, path: str) -> dict[str, Any]:
    """Parse a configuration file and return a normalized dictionary.

    Args:
        path: Absolute path to the configuration file.

    Returns:
        Normalized dict with primitive values, lists, or nested dicts.
    """
    ...

serialize(data)

Serialize a configuration dictionary to the provider's format.

Parameters:

Name Type Description Default
data dict[str, Any]

Configuration dictionary to serialize.

required

Returns:

Type Description
str

Formatted string representation.

Source code in src/functualize/_types/protocols.py
def serialize(self, data: dict[str, Any]) -> str:
    """Serialize a configuration dictionary to the provider's format.

    Args:
        data: Configuration dictionary to serialize.

    Returns:
        Formatted string representation.
    """
    ...

JobProvider

Bases: Protocol

Protocol for job descriptor sources.

Implementations provide job descriptors from various sources (filesystem scan, entry points, static definitions, etc.).

Note on workflows: the cached JobDescriptor.workflow shape is populated only by directory discovery, which projects it via the internal workflow_shape_of. A provider building descriptors by hand leaves it None and has no public way to set it — deliberately, to keep the cache projection one-sided. Consumers that need a provider-declared workflow's topology read it live from descriptor.function.__functualize_workflow__ when the cached shape is absent (e.g. the MCP WorkflowToolProvider); providers do not populate the field.

list_jobs()

Return all job descriptors from this source.

Source code in src/functualize/_types/protocols.py
def list_jobs(self) -> Sequence[JobDescriptor]:
    """Return all job descriptors from this source."""
    ...

get_job(name)

Retrieve a specific job by name. None if not found.

Source code in src/functualize/_types/protocols.py
def get_job(self, name: str) -> JobDescriptor | None:
    """Retrieve a specific job by name. None if not found."""
    ...

JobTransform

Bases: Protocol

Protocol for intercepting and modifying job descriptors.

Implementations transform job descriptors as they flow from providers to the registry.

transform_list(jobs)

Transform a list of job descriptors.

Source code in src/functualize/_types/protocols.py
def transform_list(self, jobs: Sequence[JobDescriptor]) -> Sequence[JobDescriptor]:
    """Transform a list of job descriptors."""
    ...

transform_get(name, descriptor)

Transform a single job descriptor lookup.

Source code in src/functualize/_types/protocols.py
def transform_get(
    self, name: str, descriptor: JobDescriptor | None
) -> JobDescriptor | None:
    """Transform a single job descriptor lookup."""
    ...

KeyAvailability

Bases: Enum

Whether a key provider can answer without prompting a person.

Asked by :class:~functualize.plugin.VaultKeyProbe, which exists so diagnostic surfaces (vault status, vault inspect) can report the key's state without ever raising an unlock dialog. The three values map exactly to the states those surfaces print: available / locked / unknown.

UNLOCKED = 'unlocked' class-attribute instance-attribute

A read will not prompt — asking for the key is safe to do silently.

LOCKED = 'locked' class-attribute instance-attribute

A read may prompt or block — report it, do not attempt the read.

UNKNOWN = 'unknown' class-attribute instance-attribute

The backend cannot say (no probe support, no Secret Service, non-Linux).

ModulePreFilter

Bases: Protocol

Decide whether a module is worth importing, without importing it.

Discovery reads a candidate file's AST before executing it, and a filter answers from that alone. The built-in filters (_primitives/pre_filter.py) express the require_* settings; a host whose jobs are, say, methods on classes cannot express itself in any of those and supplies its own.

Implementations satisfy this structurally -- there is nothing to inherit, and _primitives does not import this module's package upward.

fingerprint() is not decorative. The discovery cache persists negative pre-filter decisions and replays them, trusting them only while the discovery fingerprint matches. A caller-supplied predicate cannot join that hash by identity: _normalize_discovery_value renders an unknown value with str(), and str() of a function carries its address, so the digest would differ on every boot and invalidate the cache on every run. Omitting it instead reproduces the X1-X4 replay defect that CACHE_VERSION 15->16->17 and ADR-010/ADR-011 exist to close. A stable, caller-declared string is the only option that keeps the cache both warm and correct.

should_import(source_file)

Return whether this module should be imported for discovery.

Source code in src/functualize/_types/protocols.py
def should_import(self, source_file: Path) -> bool:
    """Return whether this module should be imported for discovery."""
    ...

fingerprint()

Stable identity of this filter's logic, for cache invalidation.

Must be identical across processes for identical behaviour, and must change when the predicate's behaviour changes. A host that forgets to bump it gets a stale cache -- the same contract as any cache key, and the same failure the require_* fields already have when a config is edited without invalidation.

Source code in src/functualize/_types/protocols.py
def fingerprint(self) -> str:
    """Stable identity of this filter's logic, for cache invalidation.

    Must be identical across processes for identical behaviour, and must
    change when the predicate's behaviour changes. A host that forgets to
    bump it gets a stale cache -- the same contract as any cache key, and
    the same failure the ``require_*`` fields already have when a config
    is edited without invalidation.
    """
    ...

PluginWithShutdown

Bases: Protocol

Protocol for plugins requiring cleanup on application shutdown.

Plugins satisfying this protocol will have on_shutdown called in reverse loading order when the application completes execution.

on_shutdown(app)

Called during application shutdown for resource cleanup.

Parameters:

Name Type Description Default
app PluginHost

The host being shut down, as the plugin port rather than Any (plugin-host-protocol/T9). A shutdown handler that reaches past these eleven members is reaching into an application that is already tearing itself down.

required
Source code in src/functualize/_types/protocols.py
def on_shutdown(self, app: PluginHost) -> None:
    """Called during application shutdown for resource cleanup.

    Args:
        app: The host being shut down, as the plugin port rather than
            ``Any`` (`plugin-host-protocol`/T9). A shutdown handler that
            reaches past these eleven members is reaching into an
            application that is already tearing itself down.
    """
    ...

Source

Bases: Protocol

Protocol for configuration value sources in the Resolution Chain.

Each source represents one origin of configuration values (CLI args, environment variables, remote providers, file-based config, defaults).

scope says whether the section names a group or a job. Most sources ignore it — a file section or a default is spelled the same either way — but the two sources whose lookup spelling depends on it (the vault's storage identity, the environment's GROUP__FIELD form) read it. Every implementation must accept it, so a scope-blind source is a compile-time visible deviation rather than a silent one.

source_type property

Source type identifier (e.g., 'cli', 'env', 'remote', 'file', 'default').

source_id property

Source identifier (e.g., file path, provider name, 'environ').

get(key, section=None, *, scope='job')

Retrieve a value for the given key.

Parameters:

Name Type Description Default
key str

The configuration key name.

required
section str | None

Optional section/namespace.

None
scope Literal['group', 'job']

Whether section names a group or a job.

'job'

Returns:

Type Description
Any | None

The value if found, None if not present in this source.

Source code in src/functualize/_types/protocols.py
def get(
    self,
    key: str,
    section: str | None = None,
    *,
    scope: Literal["group", "job"] = "job",
) -> Any | None:
    """Retrieve a value for the given key.

    Args:
        key: The configuration key name.
        section: Optional section/namespace.
        scope: Whether ``section`` names a group or a job.

    Returns:
        The value if found, None if not present in this source.
    """
    ...

has(key, section=None, *, scope='job')

Check if this source can provide a value for the key.

Source code in src/functualize/_types/protocols.py
def has(
    self,
    key: str,
    section: str | None = None,
    *,
    scope: Literal["group", "job"] = "job",
) -> bool:
    """Check if this source can provide a value for the key."""
    ...

keys(section, *, scope='job')

Return all keys available for the given section.

Parameters:

Name Type Description Default
section str

The section/namespace to query.

required
scope Literal['group', 'job']

Whether section names a group or a job.

'job'

Returns:

Type Description
set[str]

Set of key names this source can provide for the section.

Source code in src/functualize/_types/protocols.py
def keys(self, section: str, *, scope: Literal["group", "job"] = "job") -> set[str]:
    """Return all keys available for the given section.

    Args:
        section: The section/namespace to query.
        scope: Whether ``section`` names a group or a job.

    Returns:
        Set of key names this source can provide for the section.
    """
    ...

VaultKeyInitializer

Bases: VaultKeyProvider, Protocol

A key provider that can also create the key, not only read it.

Separate from :class:VaultKeyProvider rather than a method added to it, because widening that protocol would retroactively invalidate every structural implementation that satisfies it today — read-only providers are valid providers and must stay so. A provider opts in by having the method; nothing registers, and nothing inherits.

func builtin vault init looks for this capability. A provider that lacks it is not an error: the environment provider cannot create anything, because only the operator can set an environment variable, and init refuses with instructions rather than pretending otherwise.

Key scope is this provider's choice, and both shipped providers choose user-scope. project_id is carried here for symmetry with :meth:VaultKeyProvider.get_key and so a third-party KMS or hosted provider can hold one key per project — but the environment provider ignores it (one variable, many projects) and the keychain provider matches it deliberately. Isolation between projects comes from the separate vault files, not from separate keys. A seam whose two implementations disagreed about scope meant that which scope applied depended on whether an environment variable happened to be exported.

initialize_key(project_id)

Return the existing key, or create, persist, and return one.

Args:
    project_id: Carried for providers that scope per project. Both
        shipped implementations ignore it; see the class docstring.

Returns:
    Exactly ``KEY_BYTES`` bytes. Idempotent: a second call returns what
    the first one persisted, never a fresh key — a provider that
    generated a new key each time would silently strand every value
    already written under the old one.

The key is never logged, printed or returned through any report. init reports which provider holds it, never the key itself; keygen is the one command that puts a key on screen, and it is explicitly the operator's to place.

Source code in src/functualize/_types/protocols.py
def initialize_key(self, project_id: str) -> bytes:
    """Return the existing key, or create, persist, and return one.

        Args:
            project_id: Carried for providers that scope per project. Both
                shipped implementations ignore it; see the class docstring.

        Returns:
            Exactly ``KEY_BYTES`` bytes. Idempotent: a second call returns what
            the first one persisted, never a fresh key — a provider that
            generated a new key each time would silently strand every value
            already written under the old one.

    The key is never logged, printed or returned through any report. `init`
    reports *which provider* holds it, never the key itself; `keygen` is the
    one command that puts a key on screen, and it is explicitly the
    operator's to place.
    """
    ...

VaultKeyProbe

Bases: VaultKeyProvider, Protocol

A key provider that can say whether it would prompt, without prompting.

Separate from :class:VaultKeyProvider rather than a method added to it, exactly as :class:VaultKeyInitializer is: widening that protocol would retroactively invalidate every structural implementation that satisfies it today. A provider opts in by having the method; nothing registers, and nothing inherits.

vault status and vault inspect look for this capability. They must never raise a dialog and never wait on one, so they ask probe() first and read the key only when the answer is :attr:~functualize._types.enums.KeyAvailability.UNLOCKED.

probe()

Report whether this provider can answer without prompting.

Never prompts, never blocks beyond a short fixed bound, never raises: a backend that cannot answer the question returns UNKNOWN rather than failing the surface that asked.

Source code in src/functualize/_types/protocols.py
def probe(self) -> KeyAvailability:
    """Report whether this provider can answer without prompting.

    Never prompts, never blocks beyond a short fixed bound, never raises:
    a backend that cannot answer the question returns ``UNKNOWN`` rather
    than failing the surface that asked.
    """
    ...

VaultKeyProvider

Bases: Protocol

Protocol for supplying the key that opens the local secrets vault.

The vault caches values synced from remote providers (AWS Secrets Manager, Bitwarden, …) so that jobs resolve configuration without touching the network. It is encrypted at rest; this protocol is where the key comes from, and it is a seam rather than a fixed source so that an OS keychain, a cloud KMS, a password manager or a hosted control plane are all the same shape (ADR-016).

Two implementations ship: an environment-variable provider and an OS keychain provider.

Reading the key is not gated on a terminal, and never prompts. A run that needs the key consults providers whether or not stdin and stdout are TTYs, so :meth:get_key must answer silently: return the key, return None, or raise a typed locked/unavailable error — promptly, and without ever asking a keyring to unlock. A run must never create an unlock prompt, because a prompt the client later abandons (a deadline, Ctrl-C, an agent killing its child) can crash the keyring daemon and re-lock every keyring the user has. Unlocking is a separate, explicit capability: :class:VaultKeyUnlocker.

The terminal rule survives only for providers that need a person at this terminal: a provider whose :meth:interactive is True is still consulted only on a real TTY, so an unattended run cannot block forever on a prompt nobody can answer.

identifier()

Return the short provider name, e.g. 'env' or 'keychain'.

Source code in src/functualize/_types/protocols.py
def identifier(self) -> str:
    """Return the short provider name, e.g. 'env' or 'keychain'."""
    ...

interactive()

Whether obtaining the key requires a person at a terminal.

True means the provider can only work through a prompt a pipe cannot answer; such a provider is consulted only on a real TTY. A provider backed by an OS keyring returns False: its :meth:get_key reads silently, and unlocking it is :class:VaultKeyUnlocker's job, done only when a person asks for it.

Source code in src/functualize/_types/protocols.py
def interactive(self) -> bool:
    """Whether obtaining the key **requires a person at a terminal**.

    True means the provider can only work through a prompt a pipe cannot
    answer; such a provider is consulted only on a real TTY. A provider
    backed by an OS keyring returns False: its :meth:`get_key` reads
    silently, and unlocking it is :class:`VaultKeyUnlocker`'s job, done
    only when a person asks for it.
    """
    ...

is_available()

Whether this provider can supply a key in this environment.

Reports capability, not success: a keychain provider returns False where no keyring exists, rather than raising when asked for a key.

Source code in src/functualize/_types/protocols.py
def is_available(self) -> bool:
    """Whether this provider can supply a key in this environment.

    Reports capability, not success: a keychain provider returns False
    where no keyring exists, rather than raising when asked for a key.
    """
    ...

get_key(project_id)

Return the 32-byte key for a project's vault, or None.

Parameters:

Name Type Description Default
project_id str

The project identity the vault is scoped to. Vaults are per-project, so a provider may hold a distinct key per project.

required

Returns:

Type Description
bytes | None

Exactly 32 bytes, or None when this provider has no key to offer.

bytes | None

Returning None is normal and lets resolution continue; it is not an

bytes | None

error.

Must not prompt, and must return promptly. A locked backend is reported by raising a typed locked error (or returning None), never by asking it to unlock: the caller may be a pipe, an agent or a cron job, and nobody there can answer a dialog.

Source code in src/functualize/_types/protocols.py
def get_key(self, project_id: str) -> bytes | None:
    """Return the 32-byte key for a project's vault, or None.

    Args:
        project_id: The project identity the vault is scoped to. Vaults are
            per-project, so a provider may hold a distinct key per project.

    Returns:
        Exactly 32 bytes, or None when this provider has no key to offer.
        Returning None is normal and lets resolution continue; it is not an
        error.

    **Must not prompt, and must return promptly.** A locked backend is
    reported by raising a typed locked error (or returning None), never
    by asking it to unlock: the caller may be a pipe, an agent or a cron
    job, and nobody there can answer a dialog.
    """
    ...

VaultKeyUnlocker

Bases: VaultKeyProvider, Protocol

A key provider that can ask its backend to unlock — the one call that may prompt.

Separate from :class:VaultKeyProvider for the same reason :class:VaultKeyInitializer and :class:VaultKeyProbe are: widening that protocol would invalidate every read-only implementation. A provider opts in by having the method.

func builtin vault unlock is the only caller. It runs because a person asked for it, so it may show the keyring's own unlock dialog and waits, with no deadline, for the dialog's own outcome. An implementation must never cancel an active prompt from its side: ending a prompt from the client can crash the keyring daemon.

unlock()

Ask the backend to unlock, waiting for the prompt's own outcome.

Returns:

Type Description
bool

True when a key is available afterwards (already unlocked, or

bool

unlocked now); False when the person cancelled or no key could be

bool

reached.

Source code in src/functualize/_types/protocols.py
def unlock(self) -> bool:
    """Ask the backend to unlock, waiting for the prompt's own outcome.

    Returns:
        True when a key is available afterwards (already unlocked, or
        unlocked now); False when the person cancelled or no key could be
        reached.
    """
    ...

AppSettingsSchema(settings, env_prefix='FUNCTUALIZE', sources=SettingsSources(), file_section_prefixes=_default_file_section_prefixes(), freeform_sections=frozenset()) dataclass

The full settings declaration one app hands to the store.

Attributes:

Name Type Description
settings tuple[Setting, ...]

The catalog, in display order.

env_prefix str

Environment-variable prefix without the trailing underscore ("FUNCTUALIZE" → FUNCTUALIZE_TUI_THEME). Replaces the hardcoded literal in env_var_for.

sources SettingsSources

File discovery declaration.

file_section_prefixes Mapping[str, str]

{filename: section prefix}. A shared file such as pyproject.toml nests an app's settings under its own table (tool.functualize); a dedicated file uses the bare section. Declared as data — this replaces the "tool.functualize" if path.name == "pyproject.toml" else "" branch, which hardcodes both the filename and func's own table name and so cannot answer the question for a second app.

settings instance-attribute

env_prefix = 'FUNCTUALIZE' class-attribute instance-attribute

sources = field(default_factory=SettingsSources) class-attribute instance-attribute

file_section_prefixes = field(default_factory=_default_file_section_prefixes) class-attribute instance-attribute

freeform_sections = frozenset() class-attribute instance-attribute

extend(*settings)

Return a new schema with additional settings, rejecting name clashes.

Source code in src/functualize/_types/settings.py
def extend(self, *settings: Setting) -> AppSettingsSchema:
    """Return a new schema with additional settings, rejecting name clashes."""
    existing = {setting.name for setting in self.settings}
    added: set[str] = set()
    for setting in settings:
        if setting.name in existing or setting.name in added:
            raise ValueError(f"setting {setting.name!r} is already declared")
        added.add(setting.name)
    return replace(self, settings=(*self.settings, *settings))

setting(name)

Find a setting by its canonical dotted name.

Source code in src/functualize/_types/settings.py
def setting(self, name: str) -> Setting | None:
    """Find a setting by its canonical dotted name."""
    return next(
        (setting for setting in self.settings if setting.name == name), None
    )

sections()

File sections that the declaration recognizes.

Source code in src/functualize/_types/settings.py
def sections(self) -> frozenset[str]:
    """File sections that the declaration recognizes."""
    return frozenset(
        (
            *self.freeform_sections,
            *(place for s in self.settings for place in s.accepted_places if place),
        )
    )

keys_in(section)

Declared keys accepted in one file section.

Source code in src/functualize/_types/settings.py
def keys_in(self, section: str) -> frozenset[str]:
    """Declared keys accepted in one file section."""
    return frozenset(
        setting.key
        for setting in self.settings
        if section in setting.accepted_places
    )

flag(spelling)

Find the setting controlled by a root CLI option.

Source code in src/functualize/_types/settings.py
def flag(self, spelling: str) -> Setting | None:
    """Find the setting controlled by a root CLI option."""
    return next(
        (setting for setting in self.settings if setting.cli_flag == spelling),
        None,
    )

value_in(values, name)

Read a declared key from a file table, preferring its canonical place.

Source code in src/functualize/_types/settings.py
def value_in(self, values: Mapping[str, Any], name: str) -> Any | None:
    """Read a declared key from a file table, preferring its canonical place."""
    setting = self.setting(name)
    if setting is None:
        return None
    for place in setting.accepted_places:
        table = values if not place else values.get(place)
        if isinstance(table, Mapping) and setting.key in table:
            return table[setting.key]
    return None

env_var_for(setting)

The environment variable that overrides setting.

Byte-identical to the shipped env_var_for when env_prefix == "FUNCTUALIZE".

Source code in src/functualize/_types/settings.py
def env_var_for(self, setting: Setting) -> str:
    """The environment variable that overrides ``setting``.

    Byte-identical to the shipped ``env_var_for`` when
    ``env_prefix == "FUNCTUALIZE"``.
    """
    if setting.env is not None:
        return setting.env
    if setting.section:
        return f"{self.env_prefix}_{setting.section.upper()}_{setting.key.upper()}"
    return f"{self.env_prefix}_{setting.key.upper()}"

section_prefix_for(file_name)

The TOML table an app's settings nest under inside file_name.

Source code in src/functualize/_types/settings.py
def section_prefix_for(self, file_name: str) -> str:
    """The TOML table an app's settings nest under inside ``file_name``."""
    return self.file_section_prefixes.get(file_name, "")

section_in_file(setting, file_name)

Full dotted TOML section for setting inside file_name.

What the shipped store used to derive per call: prefix and section joined, empty parts dropped.

Source code in src/functualize/_types/settings.py
def section_in_file(self, setting: Setting, file_name: str) -> str:
    """Full dotted TOML section for ``setting`` inside ``file_name``.

    What the shipped store used to derive per call: prefix and section
    joined, empty parts dropped.
    """
    parts = [p for p in (self.section_prefix_for(file_name), setting.section) if p]
    return ".".join(parts)

Setting(name, type, description, default=None, choices=None, min_value=None, max_value=None, max_items=None, cli_flag=None, phase=None, places=(), listed=True, surface=None, env=None) dataclass

One declared setting.

Attributes:

Name Type Description
name str

Dotted canonical identity — "tui.theme", or a bare "dotenv" for a top-level key. This is the row key everywhere.

type str

"enum" | "int" | "bool" | "list" | "str".

description str

Human-readable help.

default str | None

Built-in default as display text, or None when the setting genuinely has no default (most [discovery] filters).

choices / min_value / max_value / max_items

Validation bounds, carried over from the shipped SettingSchema unchanged.

cli_flag str | None

Generated root CLI flag ("--log-level"), or None for a settings-only knob. Read by the root-flag generator (app/adapters/settings_flags.py), which func and an embedded app both call, so the two surfaces cannot disagree about which settings a command line may override.

phase str | None

"early" marks a setting whose flag must be honoured by the pre-boot argv scan, before app construction. Consumed by C3.2.

places tuple[str, ...]

File sections that may contain this key. The dotted name's section is canonical, even when an accepted legacy place comes first in this tuple.

listed bool

Whether to show the setting in an interactive settings list.

surface str | None

The delivery surface that owns this setting, if any.

env str | None

Explicit environment-variable name; otherwise the schema derives one from its prefix and the canonical dotted name.

name instance-attribute

type instance-attribute

description instance-attribute

default = None class-attribute instance-attribute

choices = None class-attribute instance-attribute

min_value = None class-attribute instance-attribute

max_value = None class-attribute instance-attribute

max_items = None class-attribute instance-attribute

cli_flag = None class-attribute instance-attribute

phase = None class-attribute instance-attribute

places = () class-attribute instance-attribute

listed = True class-attribute instance-attribute

surface = None class-attribute instance-attribute

env = None class-attribute instance-attribute

section property

TOML section this setting lives in; "" for a top-level key.

Derived from the dotted name rather than stored, so a setting cannot have a name and a section that disagree.

key property

The bare key inside :attr:section.

accepted_places property

Canonical section first, followed by accepted legacy sections.

SettingsSources(global_file_name='config.toml', project_file_names=PROJECT_FILE_NAMES, env=True) dataclass

Where an app's settings are read from, in precedence order.

Precedence is fixed (default < global < project < env); what varies per app is the file names. Declaring them makes the store app-agnostic.

Attributes:

Name Type Description
global_file_name str

File inside the user config dir (XDG-resolved).

project_file_names tuple[str, ...]

Candidates for the upward project walk, nearest wins, in the order they are probed at each level.

env bool

Whether environment variables participate at all.

global_file_name = 'config.toml' class-attribute instance-attribute

project_file_names = PROJECT_FILE_NAMES class-attribute instance-attribute

env = True class-attribute instance-attribute

BarRenderer

Bases: Protocol

Overrides default header or status bar rendering.

When registered, replaces the default "join with double-space" rendering for the specified bar type. Last registered wins.

bar_type instance-attribute

render(items, context)

Render the bar from collected (id, text) pairs and context.

Source code in src/functualize/plugin/protocols.py
def render(self, items: list[tuple[str, str]], context: dict[str, object]) -> str:
    """Render the bar from collected (id, text) pairs and context."""
    ...

DisplayProvider

Bases: Protocol

Provides an above-header display panel with CWD-contextual visibility.

Display panels show ambient situational awareness (Docker services, Git status, etc.) and support auto-refresh and job-linking.

The widgets yielded by :meth:compose_display may satisfy :class:InteractiveContent (plus can_focus/action_*) to become interactive when the DISPLAY zone is focused — same contract as PanelHost panels.

display_id instance-attribute

display_title instance-attribute

display_priority instance-attribute

refresh_interval instance-attribute

linked_jobs instance-attribute

linked_groups instance-attribute

should_show(cwd, app)

Return True if this display should be visible for the given CWD.

Source code in src/functualize/plugin/protocols.py
def should_show(self, cwd: Path, app: FunctualizeApp) -> bool:
    """Return True if this display should be visible for the given CWD."""
    ...

compose_display()

Compose the display widget tree.

Source code in src/functualize/plugin/protocols.py
def compose_display(self) -> ComposeResult:
    """Compose the display widget tree."""
    ...

refresh()

Called at refresh_interval to update display content.

Source code in src/functualize/plugin/protocols.py
def refresh(self) -> None:
    """Called at refresh_interval to update display content."""
    ...

get_available_actions(focused)

Return (key, label) tuples for the dynamic footer.

Source code in src/functualize/plugin/protocols.py
def get_available_actions(self, focused: bool) -> list[tuple[str, str]]:
    """Return (key, label) tuples for the dynamic footer."""
    ...

HeaderItemProvider

Bases: Protocol

Provides an item rendered in the header bar.

Items are collected, filtered (None skipped), sorted by priority, and joined with double-space separator.

item_id instance-attribute

item_priority instance-attribute

render_item(app)

Render header item text, or None to skip.

Source code in src/functualize/plugin/protocols.py
def render_item(self, app: FunctualizeApp) -> str | None:
    """Render header item text, or None to skip."""
    ...

InteractiveContent

Bases: Protocol

The one interaction contract shared by every key-receiving widget.

Whether a widget lives in the PanelHost ring, a drill-down sub-view, or the display slot, it becomes interactive the same way (the PanelHost idiom — there is no second key-routing mechanism):

  • can_focus = True so zone focus can land on it,
  • action_* methods (action_cursor_down, action_drill_down, …) reached via KEYMAPS[mode] → KeyDispatcher._resolve_target,
  • :meth:get_available_actions for the dynamic footer,
  • drill-down via a namespaced Message the app routes to the host's push_view.

Implementing this protocol is opt-in: hosts fall back gracefully (footer default, keys inert) when a widget omits it.

get_available_actions(focused)

Return (key, label) tuples for the dynamic footer.

Source code in src/functualize/plugin/protocols.py
def get_available_actions(self, focused: bool) -> list[tuple[str, str]]:
    """Return (key, label) tuples for the dynamic footer."""
    ...

PanelProvider

Bases: Protocol

Provides a panel for the pre-flight or general ring.

Panels are shown in the Panel Slot below the SmartBar, navigable via Ctrl+H/J/K/L within their ring.

panel_id instance-attribute

panel_title instance-attribute

panel_priority instance-attribute

panel_category instance-attribute

should_show(pending)

Return True if this panel should appear in the ring.

Source code in src/functualize/plugin/protocols.py
def should_show(self, pending: PendingExecution | None) -> bool:
    """Return True if this panel should appear in the ring."""
    ...

compose_panel()

Compose the panel widget tree.

Source code in src/functualize/plugin/protocols.py
def compose_panel(self) -> ComposeResult:
    """Compose the panel widget tree."""
    ...

on_activate(pending)

Called when this panel becomes the active panel in the ring.

Source code in src/functualize/plugin/protocols.py
def on_activate(self, pending: PendingExecution | None) -> None:
    """Called when this panel becomes the active panel in the ring."""
    ...

get_available_actions(focused)

Return (key, label) tuples for the dynamic footer.

Source code in src/functualize/plugin/protocols.py
def get_available_actions(self, focused: bool) -> list[tuple[str, str]]:
    """Return (key, label) tuples for the dynamic footer."""
    ...

PostRunStampProvider

Bases: Protocol

Provides output printed to stdout on TUI exit.

Stamps are rendered after the TUI unmounts, giving plugins a chance to print summary information to the terminal.

render_stamp(session)

Render stamp text, or None to skip.

Source code in src/functualize/plugin/protocols.py
def render_stamp(self, session: SessionState) -> str | None:
    """Render stamp text, or None to skip."""
    ...

SessionState

Placeholder for runtime session state (to be implemented).

SignatureProvider

Bases: Protocol

Provides content for the signature slot above display panels.

Implementations render a single-line signature string shown at the top of the TUI. Multiple providers are stacked by priority (lower first).

priority instance-attribute

render_signature(app)

Render signature text, or None to skip this provider.

Source code in src/functualize/plugin/protocols.py
def render_signature(self, app: FunctualizeApp) -> str | None:
    """Render signature text, or None to skip this provider."""
    ...

StatusBarItemProvider

Bases: Protocol

Provides an item rendered in the status bar.

Items are collected, filtered (None skipped), sorted by priority, and joined with double-space separator.

item_id instance-attribute

item_priority instance-attribute

render_item(app, state)

Render status bar item text, or None to skip.

Source code in src/functualize/plugin/protocols.py
def render_item(self, app: FunctualizeApp, state: SessionState) -> str | None:
    """Render status bar item text, or None to skip."""
    ...

ThemeProvider

Bases: Protocol

Provides a CSS-based color theme for the TUI.

Themes are registered by theme_id. The active theme's CSS is loaded at startup and can be hot-switched via settings.

theme_id instance-attribute

theme_name instance-attribute

get_css()

Return the CSS string for this theme.

Source code in src/functualize/plugin/protocols.py
def get_css(self) -> str:
    """Return the CSS string for this theme."""
    ...

resolve_settings(schema, cwd, *, flags=None, env=None, global_dir=None)

Apply the declared precedence ladder, retaining file provenance.

Flags outrank environment; project files are nearest first; global is last. Scalar settings take the first value. Lists concatenate in that same order, with first-occurrence deduplication.

Source code in src/functualize/_config/settings_resolution.py
def resolve_settings(
    schema: AppSettingsSchema,
    cwd: Path,
    *,
    flags: Mapping[str, Any] | None = None,
    env: Mapping[str, str] | None = None,
    global_dir: Path | None = None,
) -> ResolvedSettings:
    """Apply the declared precedence ladder, retaining file provenance.

    Flags outrank environment; project files are nearest first; global is
    last. Scalar settings take the first value. Lists concatenate in that
    same order, with first-occurrence deduplication.
    """
    layers = settings_layers(schema, cwd, global_dir=global_dir)
    file_sources = tuple(LayerSource(layer, schema) for layer in layers)
    environ = dict(os.environ if env is None else env)
    env_source = EnvSource(environ, prefix=schema.env_prefix)
    supplied_flags = flags or {}
    values: dict[str, Any] = {}
    provenance: dict[str, str] = {}
    contributors: dict[Path, set[str]] = {layer.path: set() for layer in layers}

    for setting in schema.settings:
        name = setting.name
        if name == "run.tags":
            # Run tags have a strict per-source grammar and per-key overlay.
            # The ordinary list merger must not accept the schema-derived
            # FUNCTUALIZE_RUN_TAGS value or flatten the selected file layers.
            for layer in layers:
                run_section = layer.values.get("run")
                if isinstance(run_section, dict) and "tags" in run_section:
                    contributors[layer.path].add(name)
            continue
        candidates: list[tuple[Any, str, Path | None]] = []
        flag_value = supplied_flags.get(name, supplied_flags.get(setting.key))
        if flag_value is not None:
            candidates.append((flag_value, "cli", None))
        if schema.sources.env:
            env_name = schema.env_var_for(setting)
            # Explicit names such as discovery.extra_directories are read
            # directly; the legacy unprefixed spelling is never consulted.
            env_value = (
                environ.get(env_name)
                if setting.env is not None
                else env_source.get(setting.key, setting.section or None)
            )
            if env_value:
                candidates.append((env_value, "env", None))
        for source in file_sources:
            file_value = source.get(setting.key, setting.section or None)
            if file_value is not None:
                candidates.append((file_value, source.source_id, source.layer.path))
        if setting.default is not None:
            candidates.append((setting.default, "default", None))

        if not candidates:
            continue
        if setting.type == "list":
            seen: set[str] = set()
            merged: list[str] = []
            for raw, _source, path in candidates:
                for item in _list_values(raw):
                    if item not in seen:
                        seen.add(item)
                        merged.append(item)
                        if path is not None:
                            contributors[path].add(name)
            values[name] = tuple(merged)
        else:
            raw, _source, path = candidates[0]
            values[name] = _coerce(setting, raw)
            if path is not None:
                contributors[path].add(name)
        provenance[name] = candidates[0][1]

    return ResolvedSettings(
        values=values,
        provenance=provenance,
        layers=layers,
        contributes={path: frozenset(names) for path, names in contributors.items()},
    )

discover_domains()

Discover all installed domain SDKs by scanning entry points.

Scans the functualize.domains entry point group and loads each entry point, expecting a DomainMetadata-compatible instance (any frozen dataclass with the required fields).

Returns:

Type Description
list[DomainMetadata]

List of successfully loaded DomainMetadata instances.

Source code in src/functualize/_plugins/domain_registry.py
def discover_domains() -> list[DomainMetadata]:
    """Discover all installed domain SDKs by scanning entry points.

    Scans the ``functualize.domains`` entry point group and loads each
    entry point, expecting a ``DomainMetadata``-compatible instance
    (any frozen dataclass with the required fields).

    Returns:
        List of successfully loaded DomainMetadata instances.
    """
    discovered: list[DomainMetadata] = []
    eps = entry_points(group=DOMAINS_ENTRY_POINT_GROUP)

    for ep in eps:
        try:
            metadata = ep.load()
        except Exception as exc:
            logger.warning(f"Failed to load domain entry point '{ep.name}': {exc}")
            continue

        # Validate structurally — the loaded object may be from a domain SDK's
        # local DomainMetadata copy. Convert to our canonical DomainMetadata.
        canonical = _to_canonical_metadata(metadata, ep.name)
        if canonical is None:
            continue

        discovered.append(canonical)
        logger.debug(f"Discovered domain '{canonical.name}' ({canonical.display_name})")

    return discovered

scan_domain_providers(metadata)

Scan a domain's entry point group for available implementation plugins.

Parameters:

Name Type Description Default
metadata DomainMetadata

The DomainMetadata instance whose entry_point_group to scan.

required

Returns:

Type Description
dict[str, EntryPoint]

Dictionary mapping provider names to their entry points.

Source code in src/functualize/_plugins/domain_registry.py
def scan_domain_providers(
    metadata: DomainMetadata,
) -> dict[str, importlib.metadata.EntryPoint]:
    """Scan a domain's entry point group for available implementation plugins.

    Args:
        metadata: The DomainMetadata instance whose entry_point_group to scan.

    Returns:
        Dictionary mapping provider names to their entry points.
    """
    eps = entry_points(group=metadata.entry_point_group)
    return {ep.name: ep for ep in eps}

validate_extension_id(extension_id)

Validate an extension ID string.

Valid IDs are: - Non-empty - Lowercase alphanumeric, hyphens, and underscores only - Maximum 64 characters

Parameters:

Name Type Description Default
extension_id str

The ID string to validate.

required

Returns:

Type Description
bool

True if valid, False otherwise.

Source code in src/functualize/plugin/protocols.py
def validate_extension_id(extension_id: str) -> bool:
    """Validate an extension ID string.

    Valid IDs are:
    - Non-empty
    - Lowercase alphanumeric, hyphens, and underscores only
    - Maximum 64 characters

    Args:
        extension_id: The ID string to validate.

    Returns:
        True if valid, False otherwise.
    """
    if not extension_id:
        return False
    if len(extension_id) > _EXTENSION_ID_MAX_LENGTH:
        return False
    return _EXTENSION_ID_PATTERN.match(extension_id) is not None

Overview

The functualize.plugin module is the entry point for plugin authors. It exports all protocols and types needed to build functualize plugins.

Module location: src/functualize/plugin/

from functualize.plugin import (
    EventBus,
    HookEvent,
    StructuredEvent,
    JobProvider,
    JobTransform,
    Job,
    AdapterPlugin,
    Surface,
    PromptCollector,
    LiveConstruct,
    PromptRequest,
    PromptSeverity,
    PluginMetadata,
    PluginWithShutdown,
    Source,
    FormatProvider,
    ModulePreFilter,
    DEFAULT_SIGIL,
    SettingsSources,
)

PluginMetadata

A typing.Protocol with runtime_checkable. Every plugin object must satisfy this protocol.

from functualize.plugin import PluginMetadata

@runtime_checkable
class PluginMetadata(Protocol):
    name: str
    version: str
    description: str
Attribute Type Constraint
name str Maximum 64 characters.
version str Must be a valid PEP 440 version string.
description str Maximum 256 characters.

Surface

A protocol for objects that render a job's events. The engine's single engine→UI channel: every non-framework event is fanned out to every registered surface.

from functualize.plugin import Surface

@runtime_checkable
class Surface(Protocol):
    def handle_event(self, event: StructuredEvent) -> None: ...

Register with app.extensions.register_surface(obj). handle_event is called on worker threads — a UI implementation must marshal onto its own loop (see functualize.ui.TextualApp, which does this for you). A surface may set needs_terminal = False to keep receiving events while a job owns the screen (log files, MCP progress, test recorders).

Exception safety

Exceptions raised inside handle_event are caught and logged at ERROR level by the event bus; dispatch continues, so a failing surface never interrupts job execution or starves other surfaces.


PromptCollector

A protocol for objects that answer a job's prompts. Exactly one collector is active at a time — the one that owns the terminal (or the modal) right now.

from functualize.plugin import PromptCollector

@runtime_checkable
class PromptCollector(Protocol):
    def collect(self, request: PromptRequest) -> PromptResponse: ...

An object may satisfy both Surface and PromptCollector (a full-screen TextualApp does). Also registered with app.extensions.register_surface(obj).


LiveConstruct

A protocol for a renderable hosted in a surface's live zone — a job's live: Live capability mounts these via live.add(construct).

from functualize.plugin import LiveConstruct

@runtime_checkable
class LiveConstruct(Protocol):
    def __rich__(self) -> Any: ...   # any Rich renderable

The surface owns the cursor and repaint; the construct just returns its current state as a Rich renderable. The "raw" fallback is Rich's own off-TTY degradation.


PromptRequest

A frozen dataclass carrying the complete specification for a user prompt.

from functualize.plugin import PromptRequest

request = PromptRequest(
    question="Select environment",
    intent=PromptIntent.SELECT,
    choices=[PromptChoice(value="staging"), PromptChoice(value="prod")],
)

PromptSeverity

Visual severity level for prompt presentation.

from functualize.plugin import PromptSeverity

class PromptSeverity(Enum):
    INFO = "info"
    WARNING = "warning"
    DANGER = "danger"
    SUCCESS = "success"

Largely derivable from PromptIntent — a destructive confirmation is a danger prompt, everything else is informational — so a PromptRequest normally lets the engine's own intent→severity mapping supply it rather than passing it by hand. It remains settable on PromptRequest for the cases where a caller genuinely wants to override the styling (e.g. a warning on a non-destructive action).


PluginWithShutdown

A protocol for plugins that need graceful shutdown:

from functualize.plugin import PluginWithShutdown

class MyPlugin:
    def on_shutdown(self, app) -> None:
        """Called during application shutdown."""
        ...

Shutdown methods are called in reverse loading order with a 5-second per-plugin timeout.


ModulePreFilter

Decides whether a module is worth importing, before discovery imports it. The built-in filters express the require_* settings; a host whose jobs no setting can describe supplies its own.

from pathlib import Path

from functualize.plugin import ModulePreFilter


class HasJobSuffix:
    def should_import(self, source_file: Path) -> bool:
        return source_file.stem.endswith(("_tasks", "_ops"))

    def fingerprint(self) -> str:
        return "has-job-suffix:v1"

Satisfied structurally — there is nothing to inherit. Supply it through DiscoveryConfig(pre_filter=...), where it is ANDed onto the built-in stack rather than replacing it, and runs last because its cost is unknown.

fingerprint() is not optional

The discovery cache persists negative pre-filter decisions and replays them while the fingerprint matches. Identity cannot stand in for it: str() of an object carries its memory address, so a digest built from the object would differ on every boot — invalidating the cache on every run while appearing to work. A filter with no fingerprint() is refused with a TypeError rather than cached wrongly.

Return the same string across processes for the same behaviour, and a new one when the predicate changes. Forgetting to bump it gives a stale cache — the same contract as any cache key.

See Jobs and Auto-Discovery for the full treatment and Hosting Functualize for the other host seams.


DEFAULT_SIGIL

The sigil the shell's default (command) input mode is registered under — the empty string. A mode is selected by the first character of the input text; the default mode's sigil is empty so it is the fallback for any input that starts with no other registered sigil, and cannot collide with a real one.

from functualize.plugin import DEFAULT_SIGIL, InputMode, InputModeRegistry

registry = InputModeRegistry()
registry.register(InputMode(
    sigil=DEFAULT_SIGIL,
    name="command",
    candidate_source=my_candidates,
    is_ready=lambda text: True,
    submit=run_command,
    history_namespace="command",
))

InputModeRegistry.resolve(text) falls back to whatever mode is registered under DEFAULT_SIGIL when text's first character matches no other registered sigil.


SettingsSources

Where a host app's settings are read from, in precedence order. Precedence itself is fixed (default < global < project < env); what varies per app is the file names — declaring them is what makes the settings store app-agnostic rather than hardcoded to func's own filenames.

from functualize.plugin import SettingsSources

@dataclass(frozen=True)
class SettingsSources:
    global_file_name: str = "config.toml"
    project_file_names: tuple[str, ...] = (
        "pyproject.toml",
        ".functualize.toml",
        ".functualize/.functualize.toml",
    )
    env: bool = True
Attribute Type Description
global_file_name str File inside the user config dir (XDG-resolved).
project_file_names tuple[str, ...] Candidates for the upward project walk, nearest wins, probed in this order at each level.
env bool Whether environment variables participate in resolution at all.

It is the sources field of AppSettingsSchema (also exported from functualize.plugin) — the full declaration a second app hands to the settings store to get the same machinery func uses under its own name.


Internal Location

Plugin loading machinery lives in functualize._plugins/:

  • _plugins/loader.py — Discovery + dependency sort + loading (also defines PluginMetadata protocol)
  • _plugins/config.py — PluginConfigRegistry

Internal API

Modules under functualize._plugins are implementation details. Import from functualize.plugin instead.