Skip to main content

Module sop

Module sop 

Modules§

active_scope
approval
Out-of-band SOP approval plane (EPIC C; EPIC G broker).
audit
binding
Argument bindings for planned tool calls. A string value inside a planned call’s args may embed {{steps.N.path}} (data captured from a prior step) or {{calls.K.path}} (an earlier call in the same step, zero-based). Extraction feeds strict-save validation; resolution substitutes live or pinned run data at execution/preview time.
capability
condition
dispatch
Unified SOP event dispatch helpers.
engine
executor
Live SOP action executor.
graph
Blueprint graph projection of a Sop.
metrics
procedural_memory
Procedural-memory proposal lifecycle for SOP definitions.
route
rundata
schema
scope
step_contract
store
Durable SOP run-state store (EPIC B) — the keystone contract.
trigger_registry
Trigger-source registry projected for the SOP authoring surfaces.
trigger_source
One matcher per SOP trigger source. SopTrigger::behavior is the only place that names every variant for matching; field specs are generated separately by the TriggerFields derive, so neither matching nor the authoring registry hand-lists a source. Add a variant and the compiler forces its arm here (matching) and the derive supplies its fields.
types
wire
Wire-edit application: translates a visual editor’s connect/disconnect gesture into the corresponding StepRouting/StepFailure mutation on a draft Sop. The graph is a projection; these edits write back to the source of truth it was projected from.

Structs§

BindingContext
Data a resolution pass draws from: per-step values keyed by step number and the ordered values of calls already executed in the current step.
BindingRef
One parsed {{...}} reference.
BoundTriggerSource
A non-channel trigger source and the fields needed to configure it.
CapabilityContext
CapabilityInfo
CapabilityResult
ChannelAlias
One configured channel instance an SOP channel trigger can bind to.
ChannelTriggerKind
One channel type row: every inbound-capable ChannelKind appears, configured or not, so editors can offer setup for missing ones.
ClaimToken
CAS claim handle. Opaque to the engine; the store validates it. The single admission primitive A1’s concurrency tick and C’s out-of-band approver share.
ConditionField
One field of a trigger payload a condition can reference. path is the JSON path suffix after $. (empty for a scalar payload compared directly), label is the human name, value_type drives the value control, and options carries the choices when value_type is Enum.
ConfiguredChannel
Config-derived channel instance used as input to build_registry; decoupled from zeroclaw_config so the walk is testable without a full Config.
DeterministicRunState
Persisted state for a deterministic workflow run, enabling resume after interruption. Serialized to a JSON file alongside the SOP.
DeterministicSavings
Tracks how many LLM round-trips were saved by deterministic execution.
GraphDiagnostic
A validation finding anchored to a step. Errors block saving (validate_sop_strict); warnings render but do not block.
GraphLayout
Deterministic auto-layout so every surface renders the same picture without a client-side layout engine.
GraphLegend
The canonical legend for the SOP canvas: flow-wire roles, pin classes, and run states. The single authority a surface reads to render a legend and per-handle/per-wire hover context, so no surface hardcodes these lists.
GraphNode
A node in the projected graph: one SOP step, or one synthetic trigger entry (step >= TRIGGER_NODE_BASE, trigger_index set).
GraphPin
One connection point on a node. Flow pins order execution; data pins carry the step’s declared input/output schema type.
GraphWire
A directed edge between two nodes. flow_role is set for flow wires; data wires carry the producer/consumer pin names instead.
LayoutGeometry
Canvas geometry carried on every serialized graph so the web canvas reads placement pitch from the wire instead of a local literal. The values are fixed by LayoutGeometry::CANONICAL; the struct rides on GraphLayout only to expose them to non-Rust surfaces.
LegendEntry
One legend row: a graph concept plus its human description. The stable key is the snake_case wire value the canvas maps tones/handles against.
MaintenanceSummary
Outcome of one SopEngine::run_maintenance_tick pass (EPIC A1), for observability. All counts are 0 on a quiet tick.
NodePosition
Grid placement for one node: column = longest flow path from an entry, row = order of insertion within that column. x/y carry a persisted canvas coordinate when the node has been dragged; absent otherwise.
NodeRunOverlay
Run state for one step node. Trigger nodes carry no run state and are omitted from overlays.
PayloadContract
The set of payload fields a condition may reference for a given source. open marks sources whose payload is arbitrary user JSON (MQTT, AMQP, webhook body, channel message): the surface offers a guided path/op/value builder plus a sample-payload probe rather than a fixed field list. direct marks a scalar payload (peripheral signal) compared with the bare op value form and no path.
PersistedRun
PlannedToolCall
An authored tool invocation planned for a step. Args may embed {{steps.N.path}} / {{calls.K.path}} bindings (see sop::binding) that resolve against captured run data before dispatch. pinned carries a sample output (typically lifted from a real run’s StepToolCall.output_data) so downstream bindings can be authored and previewed without re-executing the tool.
ProposalRecord
A captured-and-distilled SOP refinement awaiting approval + write-back.
RunOverlay
Live run state layered over a SopGraph, letting a canvas animate an execution without re-fetching the graph. Served by sops/run-overlay.
Sop
A complete Standard Operating Procedure definition.
SopAuditLogger
SopCapabilityRegistry
SopEngine
Central SOP orchestrator: loads SOPs, matches triggers, manages run lifecycle.
SopEngineAdapters
Injected side-effect adapters for build_sop_engine. Each is optional and fail-closed when absent: the route falls back to the log-only no-op adapter, and the forge.comment / llm.generate capabilities report a clear failure instead of acting. The daemon injects real implementations; CLI / standalone callers pass SopEngineAdapters::default().
SopEvent
An incoming event that may trigger one or more SOPs.
SopEventRecord
SopGraph
The full projected graph: nodes, wires, validation diagnostics, and a precomputed layout. Serialized as-is over RPC (sops/graph) and HTTP.
SopMetricsCollector
Thread-safe SOP metrics aggregator. Bridges raw SOP audit events into queryable metrics for gate evaluation, health endpoints, and diagnostics.
SopRun
A full SOP execution run (from trigger to completion).
SopRunSummary
Lightweight projection of a run for list surfaces (Runs page). Carries just enough to render a row and open the per-run overlay, without the full step-result payload.
SopStep
A single step in an SOP procedure, parsed from SOP.md.
SopStepResult
Result of executing a single SOP step.
SopValidation
Result of validate_sop_strict: blocking problems reject a save, warnings surface in editors but do not block.
SqliteRunStore
Durable run store. Selected by build_run_store when persist_runs = true with the default "sqlite" backend.
StepRouting
Conditional routing metadata for a single SOP step.
StepSchema
JSON Schema fragment for validating step input/output data. Stored as a raw serde_json::Value so callers can validate without pulling in a full JSON Schema library.
StepToolCall
One tool invocation captured during a step’s execution. A step may make any number of calls (including the same tool repeatedly); index preserves invocation order so authoring surfaces can replay the sequence and map data between calls.
StepToolScope
Per-step allow/deny tool scope. Enforcement is opt-in through SOP config.
SwitchRule
A single named output port on a switch step. Rules are evaluated top to bottom; the first whose when guard passes routes the run to goto. A rule with when unset is the catch-all (n8n’s “unknown”/default port) and should be ordered last.
TriggerField
One editable field of a trigger source (e.g. topic for MQTT).
TriggerSourceRegistry
Everything an authoring surface needs to offer trigger configuration: the full ordered source list, the bound (non-channel) sources with their field shapes, and per-channel availability. Channel is special-cased into channels because its options depend on live config, not just the enum; sources still names it so surfaces render the picker from one backend-walked list instead of reconstructing it.
WireEdit
One editor gesture. role picks which routing field is mutated; port is required for Switch (index into routing.switch) and ignored otherwise. Accepted over RPC (sops/wire-draft) and HTTP.

Enums§

ApprovalDecision
Approve or deny a waiting SOP gate.
BindingScope
Scope a binding draws from.
ConditionValueType
Value-input widget hint for one condition field, so the authoring surface renders the right control (text box, number, checkbox, enum select) and quotes string comparands correctly.
ExtractedBinding
Extraction result: valid reference or a malformed body with a reason.
FilesystemEventKind
A normalized filesystem change kind reported by the watcher.
FlowRole
Why a flow wire exists. Mirrors the StepRouting/StepFailure field it was derived from, so an editor can write edits back to the right place.
GraphSeverity
NodeKind
NodeRunState
Per-node execution state projected from a run’s step results.
PinClass
ProposalKind
Whether a proposal creates a new SOP or updates an existing one.
ProposalStatus
Lifecycle of a procedural-memory proposal (EPIC F, strictly-last consumer).
SopAuthorError
Typed classification of an authoring failure so transports map it to the right status/RPC code without matching on stringified message substrings.
SopExecutionMode
How much autonomy the agent has when executing an SOP.
SopPriority
SOP priority level, used for execution mode resolution and scheduling.
SopRunAction
What the engine instructs the caller to do next after a state transition.
SopRunStatus
Status of an SOP execution run.
SopStepKind
The kind of a workflow step.
SopStepStatus
Result status of a single step execution.
SopTrigger
What event can activate an SOP.
SopTriggerSource
The source type of an incoming event that may trigger an SOP. Derived from SopTrigger; one discriminant per trigger variant.
StepFailure
Failure handling policy for a single SOP step.
StoreError
Errors a store may surface. Never swallowed by callers.
TextGraphFormat
Rendering style for render_graph_text.
TriggerFieldKind
Input widget hint for a trigger field.
WireError
Why a wire edit was rejected. The draft SOP is left untouched on error.
WireOp

Constants§

TRIGGER_NODE_BASE
Node-id offset for synthetic trigger nodes, keeping them disjoint from real step numbers. Trigger i gets node id TRIGGER_NODE_BASE + i.

Traits§

SopCapability
SopGraphExt
Projection constructors for the shared SopGraph type. SopGraph lives in zeroclaw-sop-graph, so the build logic that needs the runtime’s Sop/ToolSpec hangs off this extension trait instead of an inherent impl. Call sites keep using SopGraph::from_sop(..) with the trait in scope.
SopRunStore

Functions§

apply_wire
Apply one wire edit to a draft SOP, mutating the routing field the edit’s role maps to. Validates both endpoints first; on Err the SOP is unchanged. Semantics per role:
build_registry
Every SopTriggerSource except Channel becomes a bound source whose field specs come from the source’s own TriggerBehavior; every inbound-capable ChannelKind becomes a channel row with whatever configured aliases match it. No per-source field list lives here: the source describes its own fields.
build_run_store
Build the configured run store.
build_sop_engine
Build a single shared SopEngine + SopAuditLogger pair. This is the sole construction site for SOP state within a daemon. Callers receive Arc<Mutex<SopEngine>> and Arc<SopAuditLogger> handles — never call SopEngine::new or SopAuditLogger::new directly outside this module.
create_sop
Create a new SOP on disk, refusing to overwrite an existing one. Same normalization and validation as save_sop.
create_sop_typed
delete_sop
Delete an SOP’s directory (manifest, steps, everything). Errors if no SOP with that name exists.
delete_sop_typed
drive_resumed_broker_action
Drive a broker-approved run from a headless approval surface.
err_is_resume_at_capacity
True when err is the typed ResumeAtCapacity backpressure marker (an over-cap resume was refused), as opposed to a store fault. Lets a caller in another module or crate (e.g. resolve_gate, or the gateway resume endpoint) render it as backpressure (HTTP 503) rather than a fault without depending on the private struct.
extract_bindings
Walk a JSON value and extract every {{...}} binding found in string leaves, in document order.
extract_bold_title
Extract **title** from the beginning of text, returning (title, rest).
handle_command
load_sop_by_name
Load a single SOP by directory name from the SOPs root. Errors if the directory or its SOP.toml is missing or malformed.
load_sops
Load all SOPs from the configured directory.
load_sops_from_directory
Load SOPs from a specific directory. Each subdirectory may contain SOP.toml (metadata + triggers) and SOP.md (procedure steps).
normalize_step_numbers
Renumber steps to a contiguous 1..=N sequence (positional order wins) and remap every internal reference: routing.next, depends_on, switch goto targets, and on_failure: goto. References to steps that no longer exist are dropped (goto falls back to Fail). No-op when step numbers are ambiguous (duplicates), since a remap would guess. Runs automatically inside save_sop.
parse_execution_mode
Parse an execution mode string into SopExecutionMode, falling back to Supervised for unknown values.
parse_steps
Parse procedure steps from SOP.md content. Expects a ## Steps heading followed by numbered items (1., 2., …). Each item’s first bold text (**...**) is the step title; the rest is body. Sub-bullets parse execution hints and dark per-step contract metadata.
registry_from_config
Build the registry from live config: collects configured channel aliases (normalizing - to _ to match ChannelKind wire names) and delegates to build_registry.
remap_step_refs
Rewrite steps.N references inside string leaves after a step renumber. Dangling references are left as-is for strict validation to surface.
render_graph_text
Render a graph as plain text for CLI output and agent-readable summaries. Diagnostics are appended as a trailing block in non-JSON formats.
render_steps
Render steps back to SOP.md markdown, the inverse of parse_steps. Every contract field (tools, scope, schema, routing, failure policy, mode) becomes a sub-bullet, so render -> parse is lossless.
resolve_args
Resolve every binding in args, returning a new value. A string that is exactly one binding resolves to the referenced JSON value (any type); bindings embedded in longer strings interpolate as text. Unresolvable references error rather than passing template text to a tool.
resolve_sops_dir
Resolve the SOPs directory from config, falling back to workspace default.
run_overlay_for
Project the live run state for run_id onto sop’s graph. Errors if the run is unknown or the engine lock is poisoned.
run_summaries_for
Enumerate every run the engine holds (active + retained terminal), newest first, optionally scoped to one SOP. Errors only if the engine lock is poisoned. This is the Runs surface’s data source.
save_sop
Persist an SOP to <sops_dir>/<name>/ as SOP.toml + SOP.md. Normalizes step numbers first, then rejects the write entirely if strict validation finds blocking problems; nothing touches disk on failure.
spawn_headless_run_driver
Spawn a background task that drives a resumed SOP action to its next blocking or terminal state. Gate-clearing surfaces without an ambient agent turn (HTTP decide, WS approvals, manual dashboard runs) land here: ExecuteStep runs through a fresh agent loop under the step’s resolved agent, DeterministicStep routes through the engine’s headless deterministic driver, and every other action is already parked or terminal.
tool_specs_from_config
Build the tool-spec map an SOP graph projection uses to type step pins. Keys are tool names; values are the tool’s declared parameters (input pins) and output (output pin) schema. Derived once from the agent’s resolved security policy so the pins mirror the exact tools the step can call, not a hand-authored list.
validate_sop
Validate a loaded SOP and return a list of warnings.
validate_sop_strict
Authoring-gate validation: empty name, empty step titles, and duplicate step numbers block, as do graph projection errors (dangling next / depends_on / switch / goto targets, unsatisfiable required inputs). Graph warnings and the legacy validate_sop findings are advisory.

Type Aliases§

ToolSpecs