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
ResolvedSettings(values, provenance, layers, contributes)
dataclass
¶
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. |
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
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
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
unsubscribe(handle)
¶
Remove a previously registered subscriber.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handle
|
SubscriptionHandle
|
The SubscriptionHandle returned by subscribe(). |
required |
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
|
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
catalog()
¶
Return the full event catalog for plugin introspection.
Returns:
| Type | Description |
|---|---|
dict[str, EventMetadata]
|
Mapping of event names to their EventMetadata. |
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
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
resolve(ctx)
¶
Source code in src/functualize/_gate/decision_strategy.py
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | |
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. |
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.
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
CommandProvider
¶
Bases: Protocol
A source of top-level :class:CommandNode s the shell composes into one tree.
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
DecisionProvenance(requested_model, latency_seconds, input_tokens=None, output_tokens=None)
dataclass
¶
DecisionProvider
¶
Bases: Protocol
The whole port a decision provider implements.
Obligations on every implementation, which the Protocol cannot express:
chooseeither returns aDecisionResultwhosevalueis a key ofrequest.options, or raisesDecisionUnavailableError(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.
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
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 |
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
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
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 ( |
|
current |
The state the record is in, or |
|
target |
The state the caller asked for. |
Source code in src/functualize/_types/errors.py
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
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 |
|
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
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.
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.
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.
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()
¶
get_job(name)
¶
execute(request)
¶
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
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
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
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 ( |
name |
str
|
Short identifier, used in logs and history namespacing. |
candidate_source |
Callable[[str, int], list[Any]]
|
Returns completion candidates for |
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 |
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
__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
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
get(sigil)
¶
__contains__(sigil)
¶
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.
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. |
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.
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
¶
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).
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.
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.
CancelResult(scope_id, generation, terminal_at)
dataclass
¶
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.
Claimed(scope_id, generation, expires_at)
dataclass
¶
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.
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
¶
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.
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.
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
published(effect, *, now)
¶
failed(effect, *, error, retry_at)
¶
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.
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.
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.
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)
¶
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.
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
awaiting()
¶
Source code in src/functualize/_types/persistence.py
request(request_id)
¶
Source code in src/functualize/_types/persistence.py
candidates_for(request_id)
¶
Source code in src/functualize/_types/persistence.py
decision(request_id)
¶
for_gate(scope_id, gate_name)
¶
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
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
openraisesInputRequestNotOpenErrorand applies nothing from the unit — an answered or consumed request is never rewritten, and a refusal that half-applied would be. - An
acceptedcandidate moves the request toaccepted. Consuming it is a separate, later write. - Consuming a request that is already
consumedis 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
consume(cmd)
¶
Source code in src/functualize/_types/persistence.py
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
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.
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
¶
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.
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
¶
RenewLease(scope_id, generation, owner, now, lease_seconds)
dataclass
¶
Resumed(scope_id, generation, expires_at)
dataclass
¶
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.
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
¶
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.
RuntimeStoreConfig(url, scheme, project_root, config_key='runtime_store.url')
dataclass
¶
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)
¶
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
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.
RunTree(run, children=())
dataclass
¶
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.
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).
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.
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).
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
¶
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
resumable(query)
¶
Source code in src/functualize/_types/persistence.py
events_after(scope_id, seq)
¶
Source code in src/functualize/_types/persistence.py
step(scope_id, step_key, iteration=0)
¶
steps(scope_id)
¶
Source code in src/functualize/_types/persistence.py
branch(scope_id, decision_key)
¶
Source code in src/functualize/_types/persistence.py
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
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
renew(cmd)
¶
Source code in src/functualize/_types/persistence.py
release(cmd)
¶
Source code in src/functualize/_types/persistence.py
start(cmd)
¶
Source code in src/functualize/_types/persistence.py
complete_step(cmd)
¶
Source code in src/functualize/_types/persistence.py
record_step(cmd)
¶
Source code in src/functualize/_types/persistence.py
record_branch(cmd)
¶
Source code in src/functualize/_types/persistence.py
move(cmd)
¶
Source code in src/functualize/_types/persistence.py
suspend(cmd)
¶
Source code in src/functualize/_types/persistence.py
resume(cmd)
¶
Source code in src/functualize/_types/persistence.py
cancel(cmd)
¶
Source code in src/functualize/_types/persistence.py
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
run(*args, **kwargs)
¶
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.
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. |
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
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
|
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.
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
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
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()
¶
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)
¶
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)
¶
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
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
|
required |
Source code in src/functualize/_types/protocols.py
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 |
'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
has(key, section=None, *, scope='job')
¶
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 |
'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
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
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
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()
¶
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
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
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
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
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
( |
sources |
SettingsSources
|
File discovery declaration. |
file_section_prefixes |
Mapping[str, str]
|
|
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
setting(name)
¶
sections()
¶
File sections that the declaration recognizes.
keys_in(section)
¶
Declared keys accepted in one file section.
flag(spelling)
¶
Find the setting controlled by a root CLI option.
value_in(values, name)
¶
Read a declared key from a file table, preferring its canonical place.
Source code in src/functualize/_types/settings.py
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
section_prefix_for(file_name)
¶
The TOML table an app's settings nest under inside 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
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 — |
type |
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 |
choices |
/ min_value / max_value / max_items
|
Validation bounds, carried
over from the shipped |
cli_flag |
str | None
|
Generated root CLI flag ( |
phase |
str | None
|
|
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. |
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
¶
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.
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.
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 = Trueso zone focus can land on it,action_*methods (action_cursor_down,action_drill_down, …) reached viaKEYMAPS[mode] → KeyDispatcher._resolve_target,- :meth:
get_available_actionsfor the dynamic footer, - drill-down via a namespaced
Messagethe app routes to the host'spush_view.
Implementing this protocol is opt-in: hosts fall back gracefully (footer default, keys inert) when a widget omits it.
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.
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.
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).
StatusBarItemProvider
¶
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.
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
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
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
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
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 definesPluginMetadataprotocol)_plugins/config.py— PluginConfigRegistry
Internal API
Modules under functualize._plugins are implementation details. Import from functualize.plugin instead.