Skip to content

policies — API Reference

Policy plugin packages. The base class, PolicyRuntime, and registry live in core.policy; the types below are the concrete plugins in policies/.

policy (core)

core.policy.PolicyBase(policy_id, config)

Bases: ABC

Base control loop. Subclasses implement step(obs) → action.

Source code in core/policy.py
def __init__(self, policy_id: str, config: "PolicyConfig") -> None:
    self.id = policy_id
    self.config = config
    self.enabled = config.enabled
    self.observation_names: list[str] = list(config.observation)
    self.target_effector_id: str | None = config.action.get("effector")
    self._target_channels: list[str] = []
    self.last_obs: dict = {}
    self.last_action: dict = {}

bind_effector(effector)

Learn the effector's channel names so actions can target them.

Source code in core/policy.py
def bind_effector(self, effector: "EffectorBase") -> None:
    """Learn the effector's channel names so actions can target them."""
    self._target_channels = [c.name for c in effector.channels]

step(obs) abstractmethod

Map observation {signal_name: value} → action {channel_name: value}.

Source code in core/policy.py
@abstractmethod
def step(self, obs: dict) -> dict:
    """Map observation {signal_name: value} → action {channel_name: value}."""

core.policy.PolicyRuntime(policies, sensors, effectors, relay, hz=10.0)

Runs the node's policy stack on a fixed tick.

Each tick: snapshot sensor readings into the relay, then for each enabled policy build its observation, step, and apply the action to its effector via the request lane. always_on policies are ordered first so reflexes run even if a later cortical policy errors.

Source code in core/policy.py
def __init__(self, policies, sensors, effectors, relay: "Relay", hz: float = 10.0):
    # always-on (reflex) policies first
    self._policies = sorted(policies, key=lambda p: not p.always_on)
    self._sensors: dict[str, "SensorBase"] = sensors
    self._effectors: dict[str, "EffectorBase"] = effectors
    self._relay = relay
    self._period = 1.0 / hz if hz > 0 else 0.1
    self._thread: threading.Thread | None = None
    self._stop = threading.Event()
    # bind each policy to its target effector's channels
    for p in self._policies:
        eff = self._effectors.get(p.target_effector_id)
        if eff is not None:
            p.bind_effector(eff)

tick()

One control step (also called directly in tests).

Source code in core/policy.py
def tick(self) -> None:
    """One control step (also called directly in tests)."""
    for sid, sensor in self._sensors.items():
        reading = sensor.latest
        if reading is not None:
            self._relay.publish_tree(sid, reading.data)

    for policy in self._policies:
        if not policy.enabled:
            continue
        obs = {name: self._relay.latest(name) for name in policy.observation_names}
        try:
            action = policy.step(obs)
        except Exception:
            log.exception("policy %s: step failed", policy.id)
            continue
        policy.last_obs, policy.last_action = obs, action
        eff = self._effectors.get(policy.target_effector_id)
        if eff is not None and action:
            eff.handle_request({"levels": action})
        self._relay.publish(f"{policy.id}.action", action)

core.policy.create_policy(config)

Source code in core/policy.py
def create_policy(config: "PolicyConfig") -> "PolicyBase":
    cls = _registry.get(config.type)
    if cls is None:
        raise ValueError(
            f"Unknown policy type '{config.type}'. Known: {sorted(_registry)}."
        )
    return cls(config.id, config)

curve

policies.curve.policy.CurvePolicy(policy_id, config)

Bases: PolicyBase

A reflex: drive every target channel by a curve over normalized inputs.

params: in_min[], in_max[] (aligned with observation), out_min, out_max. kind "max_linear" (default): drive = out_min + (out_max-out_min) * max_i clamp((x_i - in_min_i)/(in_max_i - in_min_i), 0, 1). Missing inputs are ignored (fail-safe: an absent sensor never forces high output).

Source code in core/policy.py
def __init__(self, policy_id: str, config: "PolicyConfig") -> None:
    self.id = policy_id
    self.config = config
    self.enabled = config.enabled
    self.observation_names: list[str] = list(config.observation)
    self.target_effector_id: str | None = config.action.get("effector")
    self._target_channels: list[str] = []
    self.last_obs: dict = {}
    self.last_action: dict = {}

threshold

policies.threshold.policy.ThresholdPolicy(policy_id, config)

Bases: PolicyBase

A guard reflex: trip an effector off when a signal crosses a bound.

Instantiated as the overcurrent guard (ACS712 amps → servo power rail), but generic: any observed signal, any on/off effector driven over the levels lane (1.0 = armed/on, 0.0 = tripped/off).

Config keys (params): trip_above — trip when ANY observed signal exceeds this release_below — re-arm only when ALL signals fall below this (hysteresis: keep well under trip_above) latch — true: once tripped, stay tripped until the policy is disabled/re-enabled or the node restarts (default false)

Behavior notes, deliberate: - Emits an action ONLY on state transitions (trip / release). A guard that re-asserts "on" every tick would fight manual rail control via the effector API; returning {} between transitions leaves the rail alone (PolicyRuntime skips empty actions). - Missing observations never trip (an absent sensor is not an emergency) — but they also never release.

Source code in policies/threshold/policy.py
def __init__(self, policy_id, config) -> None:
    super().__init__(policy_id, config)
    self._tripped = False