# Arachnite

> A biologically-inspired reactive agent framework for Python.
> Models the nervous system of arachnids: sense → context → reflex → instinct → decide → act.
> Designed for edge devices (Raspberry Pi, Jetson Nano), laptops, and cloud servers.

Full spec: spec/  |  Examples: examples/  |  Tests: tests/ (1646)

---

## Where the docs live (read this first)

Arachnite's documentation spans several top-level trees — sweep *all* of them
before concluding something is undocumented:

- **`llms.txt`** (this file) — condensed, LLM-oriented overview of the architecture,
  public API, and invariants. Start here.
- **`README.md`** — human quick-start and project overview.
- **`spec/`** — the formal specification, numbered `01`–`08` (introduction/architecture,
  nodes, runtime, extension & testing, distributed, infrastructure, reference,
  benchmarks). Source docstrings cite these section numbers.
- **`tutorials/`** — hands-on course: `01`–`09` core lessons, `advanced/01`–`13` deep
  dives (incl. `08_llm_instincts.md`, `09_testing_your_agents.md`,
  `12_safety_monitors.md`), plus `exercises/` and `glossary.md`.
- **`docs/uml/`** — class/sequence diagrams (`.puml` sources + rendered `.png`).
- **`examples/`** — runnable reference agents (e.g. `robot_arm/`).

---

## Architecture

One pipeline cycle ("tick") in order:

0. **on_tick_start(tick)** — called on all leaf nodes (sense, instinct, action) via masters; default implementation syncs `self.logger._set_tick(tick)` so every LogEvent.tick reflects the current tick (subclasses overriding must call `super().on_tick_start(tick)`). Runtime additionally syncs its own logger and the four master loggers directly each tick. Masters isolate every node call (hooks, `read()`, `evaluate()`): one that raises, or ends in its own `CancelledError`, is reported as that node's fault to its supervisor and never aborts the tick.
1. **ActionMasterNode.drain_completed()** — collects the Results of action tasks that finished since the previous tick (completion order), for this tick's context.
2. **SenseMasterNode.read_all()** — SenseNodes read hardware → list[Signal] (poll_interval_s enforced per node; throttle timestamps are per-sensor, not batch-start). Signals pushed with `BaseSenseNode.push()` since the last tick are appended once (they were already published on the bus when pushed).
3. **Supervisor signal injection** — buffered supervisor signals appended to signals: lifecycle transitions as `SupervisorSignal` (kind `supervisor`: RUNNING/STOPPED/RESTARTING) plus, for FAULTED/DEAD, a typed `NodeFaultSignal` (kind `node_fault`, carrying error_type/error_message). When a leaf node raises during a tick, its master reports the fault to the supervisor; the resulting signals are buffered and surface in `ctx.signals` on the **next** tick (N+1), as both a `supervisor` and a `node_fault` signal. Bus-published StateUpdateSignals buffered since the last tick are appended after them.
4. **ContextNode.update(signals, results, action_states)** — merge signals + drained results + the `execution_state()` of every running multi-step action → Context snapshot (StateUpdateSignals applied to state here; ctx.state is a shallow copy; history deque and inner lists are shallow-copied per snapshot so subsequent ticks do not mutate previously returned Context objects). The drained results become `ctx.last_results` / `ctx.last_result` (first completed) for exactly this tick.
5. **InstinctMasterNode.evaluate_reflex_pairs(ctx)** — reflex instincts are evaluated before deliberation and bypass the decision layer. Each reflex proposal (priority order) goes to `ActionMasterNode.launch_reflex(proposal, node.preemption)` with the `preemption` of the reflex node that produced it (never looked up by `Proposal.instinct_id`), which starts the action as a task or arms it and preempts the resource owners (see *Reflex arbitration*). Nothing is awaited. Unknown action → WARNING. Under `reflex_conflict="raise"` a priority tie is logged at ERROR and all tied reflexes are still launched in priority order. With `reflex_mode="event"`, reflexes that declare `trigger_on_signals` are skipped here: the event lane evaluates them instead.
6. **InstinctMasterNode.evaluate_all(ctx)** — normal instincts produce list[Proposal] (trigger_interval_s throttling applied). In both stages an `evaluate()` that returns anything but a Proposal or None is that node's fault (logged, reported to its supervisor) and counts as None.
7. **DecisionMasterNode.on_new_proposals_many(..., conflicts=action_master.conflicting_owners)** — pick proposals + interrupt requests. Selection is the strategy's: `decide_many()` calls `strategy.decide()` repeatedly (each choice removes its action_id) until it returns None. A proposal that shares an `action_id` **or a declared resource** with a running action is a conflict. When every owner is deliberative and of lower priority, an `InterruptRequest(target_action_id=owner)` is issued — inside a mandatory block too, where it is latched until the block ends; otherwise the proposal is held. Reflex-owned actions are reported non-interruptible. Rejected instincts are notified via on_proposal_rejected() (covers fresh, carried-forward pending, and parked hand-off proposals).
7b. **Interrupt dispatch** — `request_interrupt(req, action_id=req.target_action_id)` for each; it never refuses (inside a mandatory block the request is latched and honoured at the first stop point after it, ADR 0009); exceptions logged as ERROR
8. **ActionMasterNode.launch(proposal, origin="decision")** for each chosen proposal (highest priority per action_id), in the strategy's selection order, so of two chosen actions sharing a resource the one chosen first gets it — starts `execute()` as a tracked `asyncio.Task` and returns a `LaunchOutcome` at once; **the tick never waits for an action**. `BLOCKED` (owner still unwinding after an interrupt) → `DecisionMasterNode.park(proposal)` for hand-off; `NOT_FOUND` → WARNING.
9. **on_tick_end(tick, duration_s)** — called on all leaf nodes via masters

**Actions run beside the tick (ADR 0005).** A long `MultiStepActionNode` keeps executing while later ticks sense, evaluate reflexes and deliberate. A Result is buffered when the task ends and appears in `ctx.last_results` on the **next** tick after completion (one-tick lifetime), so `tick()` returning does *not* mean the dispatched actions have finished. Use `await runtime.wait_idle(timeout)` to wait for in-flight actions. Different actions run concurrently unless they conflict. Two actions conflict when they share an `action_id` or any declared `resources`, and at most one running action owns a resource at any time (actuator exclusivity).

Nodes never hold references to each other — all communication goes through SignalBus.

---

## The tick loop is a sampling cadence — slow work runs *beside* it, not *inside* it

A common mistake when building on Arachnite is assuming every node must do all of
its work synchronously inside the tick. It must not. The tick is a fast, fixed-cadence
cycle (default 10 Hz): the per-tick methods it awaits — `read()` and `evaluate()` —
must each return quickly so the next tick fires on time (rule 6: all node I/O is
async; wrap blocking calls in `asyncio.to_thread()`). `execute()` is different: the
runtime launches it as a tracked task and does not wait for it, so a multi-second
physical action (a `MultiStepActionNode` sequence) is fine there. It must still never
block the event loop synchronously, because it shares that loop with the tick. Work that is slow,
latency-unbounded, or event-driven (LLM inference, heavy CV analysis, network
round-trips, hardware event streams) does **not** belong on the synchronous tick
path. It runs in a *background task* alongside the loop, and the tick only reads the
most recent result that background work has already produced.

**Canonical example — `LLMInstinctNode` (`nodes/llm.py`):**
- `evaluate(ctx)` never calls the model inline. It returns the last cached `Proposal`
  immediately, and — only when `min_interval_s` has elapsed and no call is in flight —
  spawns the LLM call as a background task via `spawn_background_task()`.
- That call finishes seconds later and swaps in the fresh proposal under an
  `asyncio.Lock`. The *next* tick picks it up. The loop never blocks on the model.
- This means `LLMInstinctNode` is **not** a request/response primitive: it is a cached,
  cooldown-throttled reactive control input. For an interactive "user asks, waits for an
  answer" flow, call the model SDK directly in your own loop — don't reach for this node.

So when modelling any slow or asynchronous capability, don't force it into the tick.
Instead:
1. Run the slow work in a background task (`spawn_background_task()` — kicked off from
   `setup()` for continuous listeners, or from `evaluate()`/`read()` for on-demand
   work; see *Background task lifecycle*).
2. Cache the result; have the per-tick method return the latest cached value (or
   `None`/no-op while nothing new is ready).
3. Throttle how often the work is launched (`min_interval_s`, `trigger_interval_s`,
   `poll_interval_s`) so background launches don't pile up.

The event-driven `read()` in *Background task lifecycle* and the non-blocking
`LLMInstinctNode` are the same pattern: **produce off the loop, hand the loop a ready
value.** Only deterministic, statically-bounded logic (classical instincts, reflexes,
fast sensor reads) should compute its result inline on the tick.

---

## Using nodes without the runtime (direct-drive)

The node primitives do **not** require `ArachniteRuntime` or the tick loop. They are
usable standalone with a bare `SignalBus`, driven on a loop you own:

```python
bus = SignalBus()
sensor = MySenseNode(bus)
action_master = ActionMasterNode(bus)
action_master.register(MyActionNode(bus))

# Drive it yourself — no RuntimeBuilder, no tick loop:
signals = await sensor.read()
result  = await action_master.dispatch(Proposal(
    instinct_id="caller", action_id="MyActionNode", priority=100, urgency=1.0,
))
```

`dispatch()` / `dispatch_many()` **await** the Result (runtime-less use). The runtime
itself uses the non-blocking `launch()` instead. Resource exclusivity holds on both
paths. A direct `dispatch()` that conflicts with a running action returns at once with
`Result(success=False, error=ResourceConflictError)`, or `RuntimeError("action already
running")` for the same action_id. Pass `origin="reflex"` to skip guards; with the default
`origin=None` the legacy rule applies (priority ≥ 200 bypasses guards).

**When do you actually need `InstinctMaster` / `DecisionMaster` / the tick loop?**
Only when **≥2 autonomous behaviors compete continuously on dynamic priority** — the
robotics/edge control shape the deliberative layer is built for. For a single agent or a
human-in-the-loop app with a *static* priority order (e.g. a coding cockpit, a one-shot
pipeline, a request-driven service), prefer direct dispatch: construct the nodes, call
`read()` / `evaluate()` / `execute()` / `dispatch()` yourself. The same direct-drive
pattern used in unit tests is a legitimate production deployment shape.

---

## Imports — everything you need is at the root

```python
from arachnite import (
    # Runtime & bus
    ArachniteRuntime, RuntimeBuilder, SignalBus, ContextNode,
    ShutdownCoordinator,
    TickInstrumenter, TICK_STAGE_NAMES,    # optional per-stage tick instrumentation

    # Models
    Signal, StateUpdateSignal, Context, Proposal, Result,
    ActionStep, StepResult,
    InterruptPolicy, InterruptRequest, ActionExecutionState,
    ReflexPreemption,                      # PREEMPT (default) | WAIT_FOR_BLOCK
    NodeState, RestartPolicy, MergePolicy, SupervisorSignal, NodeFaultSignal,
    LogLevel, LogEvent, ShutdownPhase, HistoryConfig,
    Permission, DecisionEvent, RemoteNodeState,

    # Node base classes — extend these
    BaseNode,
    BaseSenseNode,    SenseMasterNode,
    BaseInstinctNode, BaseReflexInstinctNode, InstinctMasterNode,
    LLMInstinctNode,
    BaseDecisionNode, DecisionMasterNode,
    GreedyDecisionNode, WeightedDecisionNode, RandomDecisionNode,
    ActiveInferenceDecisionNode,
    BaseActionNode,   MultiStepActionNode,    ActionMasterNode,
    LaunchStatus, LaunchOutcome,           # result of ActionMasterNode.launch()/launch_reflex()
    ActionGuard, GuardVerdict,

    # LLM providers
    LLMProvider, AnthropicProvider, OllamaProvider, LocalProvider,
    ThreadSafeProvider, SharedModelRegistry,

    # Safety monitors
    BaseSafetyMonitor, SafetyMonitorRegistry, SafetyViolationSignal,
    SafetySeverity, MonitorState,
    ReflexBypassMonitor, MandatoryBlockMonitor, ReflexDispatchMonitor,
    ActuatorExclusivityMonitor, ReflexAvailabilityMonitor, TickBudgetMonitor,
    # usage: await registry.check_all(rt.tick_count, rt.monitor_state())

    # Media
    MediaStore,

    # Infrastructure
    NodeSupervisor, HealthMonitor,
    NodeConfig,
    StructuredLogger, BaseLogSink, StdoutLogSink, JSONLogSink,
    SignalCodec, CodecRegistry, default_registry,

    # Config ([runtime], [transport], [logging], [supervisor], [context] sections)
    FrameworkConfig, RuntimeSettings, TransportSettings, MQTTSettings, NATSSettings,
    RedisSettings, LoggingSettings, SupervisorSettings, ContextSettings,

    # Tool-call codec (text-embedded tool calls; ADR 0004)
    ParsedToolCall, parse_tool_calls, render_tool_schemas,

    # Web dashboard (requires: pip install arachnite[web])
    SignalDashboard, FileLogSink,

    # Testing helpers
    make_signal, make_proposal, make_result, make_context, MockBus,

    # Exceptions
    ArachniteError,                        # base class of every framework exception
    DependencyValidationError, PermissionValidationError, PathTraversalError,
    ResourceConflictError,                 # action needs a resource a running action owns
    ActionVetoed,
    UnsafeCodecError,
)
# Not re-exported at the root — import from arachnite.exceptions:
#   RollbackError (.failures), StepAbortError, MandatoryBlockViolation,
#   ReflexConflictError (.proposals), ActionNotFoundError, ActionTimeoutError
```

---

## Extension patterns

### Sensor node
```python
import time
from arachnite import BaseSenseNode, Signal

class MySensor(BaseSenseNode):
    node_id         = "MySensor"       # must be unique; used as Proposal.action_id target
    signal_kind     = "temperature"    # filters for this kind on the bus
    poll_interval_s = 0.1              # default: read at most 10x/sec; set 0.0 for every tick

    async def read(self) -> Signal | None:
        raw = await read_hardware()        # must be async
        return Signal(
            source=self.node_id, kind=self.signal_kind,
            value=raw, confidence=1.0, timestamp=time.monotonic(),
        )
        # Return None to indicate "nothing to report this tick"

    async def on_error(self, exc: Exception) -> Signal | None:
        return None  # return None to skip this tick on error
```

### Normal instinct node
```python
from arachnite import BaseInstinctNode, Context, Proposal

class MyInstinct(BaseInstinctNode):
    node_id  = "MyInstinct"
    priority = 80   # 1-49 exploratory, 50-99 goal, 100-199 safety

    async def evaluate(self, ctx: Context) -> Proposal | None:
        signals = [s for s in ctx.signals if s.kind == "temperature"]
        if signals and signals[-1].value > 40.0:
            return Proposal(
                instinct_id=self.node_id, action_id="CoolDown",
                priority=self.priority, urgency=0.8,
                parameters={"target_temp": 35.0},
                # evidence={"sensor_value": signals[-1].value},  # optional
            )
        return None  # return None explicitly when not applicable
```

### Reflex instinct node (priority >= 200, bypasses decision)
```python
from arachnite import BaseReflexInstinctNode, Context, Proposal, ReflexPreemption

class EmergencyReflex(BaseReflexInstinctNode):
    node_id    = "EmergencyReflex"
    priority   = 250   # must be >= 200
    preemption = ReflexPreemption.PREEMPT   # default; see *Reflex arbitration*
    # trigger_on_signals = ["temperature"]  # with reflex_mode="event": evaluated per signal

    async def evaluate(self, ctx: Context) -> Proposal | None:
        critical = [s for s in ctx.signals if s.kind == "temperature" and s.value > 90.0]
        if critical:
            return Proposal(instinct_id=self.node_id, action_id="EmergencyShutdown",
                            priority=self.priority, urgency=1.0)
        return None
    # RULE: EmergencyReflex and EmergencyShutdown must be on the same AgentNode
```

### Decision strategy
```python
from arachnite import BaseDecisionNode, Proposal

class CheapestFirst(BaseDecisionNode):
    node_id = "CheapestFirst"

    async def decide(self, proposals: list[Proposal]) -> Proposal | None:
        # proposals: the remaining candidates, priority descending. Return one of
        # them (the same object) or None to start nothing more this tick.
        return min(proposals, key=lambda p: p.parameters.get("cost", 0), default=None)
```
The runtime calls `decide_many()`, whose default calls `decide()` repeatedly: after each
choice every candidate with the same `action_id` (and any already running) is dropped,
until `decide()` returns None or nothing is left. A strategy returning None on the first
call idles the agent; returning a proposal it was not offered stops the selection (logged
at ERROR). Override `decide_many()` only for custom multi-select. Greedy keeps its old
selection (best per action_id, highest priority first); Greedy and Weighted compute the
delegation's result directly unless a subclass overrides their `decide()`. `RandomDecisionNode(bus=bus, seed=7)`
and `ActiveInferenceDecisionNode(..., seed=7)` give reproducible choices.

### LLM-backed instinct node
```python
from arachnite import LLMInstinctNode, Context, Proposal, LLMProvider

class SmartInstinct(LLMInstinctNode):
    node_id        = "SmartInstinct"
    priority       = 60
    min_interval_s = 2.0   # throttle LLM calls
    call_timeout_s = 30.0  # default; a slower call is abandoned (None = no bound)

    def available_actions(self) -> dict[str, str]:
        return {"CoolDown": "Activate cooling", "Alert": "Send alert"}

    # Optional overrides:
    # def system_prompt(self) -> str: ...
    # def context_to_text(self, ctx: Context) -> str: ...
```

A call that raises, times out or returns an invalid `propose_action` (args not an object,
unknown action, urgency not a finite number in [0, 1]) **clears** the cached proposal — the
node proposes nothing until a call succeeds again. Calls run in a daemon thread: an abandoned
call never delays `stop()` or process exit, and no new call starts until it returns.

LLMProvider exposes two surfaces: `complete(system, user, tools) -> ToolResult | None`
(sync, tool-calling; what `LLMInstinctNode` uses) and `async complete_text(prompt, *,
system="", max_tokens=None) -> str` (plain text; overridden per provider because the
tool-calling path discards assistant text blocks).

### Simple action node
```python
from arachnite import BaseActionNode, Proposal, Result

class CoolDown(BaseActionNode):
    node_id    = "CoolDown"   # must match Proposal.action_id
    timeout_s  = 10.0         # bounds each execute() attempt; on expiry execute() is
                              # cancelled, on_preempted() runs, then on_timeout()
    max_retries = 1           # never retried after an interrupted/preempted run
    resources  = frozenset({"fan"})   # actuators this action commands (exclusive)

    async def execute(self, proposal: Proposal) -> Result:
        target = proposal.parameters.get("target_temp", 35.0)
        await set_fan_speed(100)          # async hardware call
        return Result(action_id=self.node_id, success=True, output={"target": target})
        # RULE: always return Result — never raise
```

The runtime runs `execute()` as a task, so it may take as long as the physical
operation needs. It must be **cancellation-safe**: a reflex preemption, `emergency_stop()`
or shutdown arrives as `asyncio.CancelledError` at an `await`.

### Multi-step action node
```python
from arachnite import MultiStepActionNode, ActionStep, Proposal, Result, StepResult, InterruptPolicy

class CoolSequence(MultiStepActionNode):
    node_id          = "CoolSequence"
    interrupt_policy = InterruptPolicy.ROLLBACK
    resources        = frozenset({"fan"})

    def steps(self) -> list[ActionStep]:
        return [
            ActionStep("ramp_up",  interruptible=True),
            ActionStep("sustain",  interruptible=False, rollback=self._undo_sustain),
            ActionStep("ramp_down", interruptible=True),
        ]

    async def execute_step(self, step: ActionStep, proposal: Proposal,
                           completed: list[StepResult]) -> StepResult:
        match step.name:
            case "ramp_up":
                await ramp_fan(0, 100)
                return StepResult(step_name="ramp_up", success=True)
            case "sustain":
                await asyncio.sleep(5.0)
                return StepResult(step_name="sustain", success=True)
            case "ramp_down":
                await ramp_fan(100, 0)
                return StepResult(step_name="ramp_down", success=True)

    async def _undo_sustain(self) -> None:
        await ramp_fan(100, 0)   # rollback: always stop the fan

    async def on_preempted(self, proposal: Proposal, preempted_by: Proposal) -> None:
        await hold_fan()         # safe-stop after a reflex took "fan"; no undo here
```

Multi-step semantics to rely on:
- A deliberative interrupt is honoured at the next safe stop point (per
  `interrupt_policy`): any step boundary not strictly inside a mandatory block. That
  includes the boundary *before* a block, so a request pending there stops the action
  before the block starts. A request arriving inside a block is held until the block
  completes. Deliberation can never cut into a mandatory block.
- ROLLBACK: `on_interrupted()` (default) runs the rollback of every completed
  non-interruptible step in reverse order and attempts **all** of them. Failures are
  raised together as one `RollbackError` whose `failures` lists `(step_name, exc)`.
  `execute()` reports that as `Result(interrupted=True, rolled_back=False, error=RollbackError)`.
- An aborting step (it returns `abort_sequence=True`, times out, or raises) goes through
  `on_aborted(completed, failed_step, proposal)`. Its default runs the same rollback walk
  under ROLLBACK and does nothing otherwise. `Result.error` is a `StepAbortError`.
- `max_retries` never retries an interrupted or preempted run, a failed rollback, or a run
  the action timeout cut inside a mandatory block.
- The action-level `timeout_s` is a cancellation like preemption: `on_preempted()` runs
  first (stand-in proposal with `instinct_id="timeout"`, bounded by `safe_stop_timeout_s`,
  no `rollback_on_preempt` walk), then `on_aborted()` for the step that was cut (rollback
  under ROLLBACK only), then `on_timeout()`. The Result keeps `step_results` and
  `stopped_at_step` and has `cancelled=True`.
- Under `ActionMasterNode` the run state is reset when the action is reserved (inside
  `launch()`), not when `execute()` starts. An interrupt requested in between survives
  and is honoured at the first interruptible boundary. A direct `await node.execute(p)`
  outside a master still resets at entry.

### Wire it all together (using RuntimeBuilder — recommended)
```python
import asyncio
from arachnite import RuntimeBuilder

async def main() -> None:
    rt = (
        RuntimeBuilder()
        .sense(MySensor)
        .instinct(MyInstinct)
        .instinct(EmergencyReflex)      # reflex auto-routes
        .action(CoolDown)
        .action(EmergencyShutdown)
        .tick_rate(10.0)
        .build()
    )
    await rt.start()
    await rt.wait()          # blocks until rt.stop() is called

asyncio.run(main())
```

RuntimeBuilder defaults: GreedyDecisionNode strategy, 10 Hz tick rate, dispatch_all reflex conflict,
`reflex_mode="tick"`, `strict_resources=False`.
Pass node **classes** to auto-instantiate with the builder's bus, or pre-built **instances** for custom args.
Access the shared bus via `builder.bus`. `.log_sinks()` (like `ArachniteRuntime(log_sinks=...)`)
reaches every master and leaf logger that has no sinks of its own — a node built with its own
`log_sinks` keeps only those. Sink delivery: synchronous sinks (stdout/JSON/file) have written an
event before the log call returns (Python 3.12+); stop()/emergency_stop() flush sinks that await I/O
(`flush_log_sinks()` for standalone use); events logged outside a loop are delivered synchronously.
`rt.health.report()` is keyed by supervisor id. Other chainable options: `.strategy()`, `.log_sinks()`,
`.reflex_conflict()`, `.reflex_mode("tick" | "event")`, `.strict_resources()`, `.permissions()`,
`.shutdown()`, `.overrun_warn()`, `.overrun_warn_consecutive()`.

### Wire it all together (manual — full control)
```python
import asyncio
from arachnite import (
    ArachniteRuntime, SignalBus, ContextNode,
    SenseMasterNode, InstinctMasterNode,
    DecisionMasterNode, GreedyDecisionNode,
    ActionMasterNode,
)

async def main() -> None:
    bus             = SignalBus()
    sense_master    = SenseMasterNode(bus=bus)
    instinct_master = InstinctMasterNode(bus=bus)
    decision_master = DecisionMasterNode(bus=bus, strategy=GreedyDecisionNode(bus=bus))
    action_master   = ActionMasterNode(bus=bus)

    sense_master.register(MySensor(bus=bus))
    instinct_master.register(MyInstinct(bus=bus))
    instinct_master.register(EmergencyReflex(bus=bus))   # reflex auto-routes
    action_master.register(CoolDown(bus=bus))
    action_master.register(EmergencyShutdown(bus=bus))

    rt = ArachniteRuntime(
        sense_master=sense_master, context=ContextNode(),
        instinct_master=instinct_master, decision_master=decision_master,
        action_master=action_master, bus=bus,
        tick_rate_hz=10.0,
    )
    await rt.start()
    await rt.wait()          # blocks until rt.stop() is called

asyncio.run(main())
```

---

## Live node registration and hot-swap

Nodes can be added and removed while the runtime is running — no restart needed.

```python
# Register a new node at runtime (calls setup(), starts supervisor tracking;
# before start() it is registered and supervised like a built-in node)
await rt.register_sense_live(new_sensor)
await rt.register_instinct_live(new_instinct)
await rt.register_action_live(new_action)

# Unregister (removes from master, untracks from supervisor — cancelling a restart
# of it still pending — cancels its background tasks, then calls teardown())
# Uses master.get_node(node_id) to look up the node for teardown.
# unregister_instinct_live also calls DecisionMasterNode.clear_pending(node_id)
# to remove any pending proposal and age tracking for the removed instinct.
await rt.unregister_sense_live("OldSensor")
await rt.unregister_instinct_live("OldInstinct")
await rt.unregister_action_live("OldAction")

# Full hot-swap: unregister old, register replacement
await rt.unregister_sense_live("CameraSense")
await rt.register_sense_live(CameraSenseV2(bus=rt.bus))
```

---

## Tick instrumentation — per-stage timing hook

Opt-in hook delivering wall-clock duration of each pipeline stage per tick. Zero cost when
not installed (one branch-predicted null check per stage). Errors from the instrumenter are
caught, logged at WARNING, and never fail the tick.

- `TickInstrumenter` — `@runtime_checkable` `typing.Protocol` with `on_stage(stage: str, duration_s: float) -> None` and `on_tick_complete(tick_index: int, total_s: float) -> None`.
- `TICK_STAGE_NAMES: tuple[str, ...] = ("sense", "context", "reflex", "instinct", "decide", "act")` — six stages in pipeline order.
- `ArachniteRuntime(..., tick_instrumenter=None)` — optional constructor kwarg.
- `rt.set_tick_instrumenter(inst | None)` — attach/detach at any time; takes effect next tick.

Stage mapping (§7.5 of spec): `sense` = `notify_tick_start` + completed-result drain + `read_all()` + supervisor-buffer drain; `context` = `ContextNode.update()`; `reflex` = reflex evaluate + `launch_reflex()` (bypass arc — fused; launch only); `instinct` = `evaluate_all()` (evaluate only); `decide` = interruptibility map + `on_new_proposals_many` + `notify_rejected` + interrupts; `act` = `launch()` of the chosen proposals + `notify_tick_end`. Since actions run as tasks (ADR 0005), `act` and `reflex` measure **launch cost only**, not action execution time.

```python
from arachnite import ArachniteRuntime, TickInstrumenter, TICK_STAGE_NAMES

class MyCollector:
    def __init__(self) -> None:
        self.samples: dict[str, list[float]] = {s: [] for s in TICK_STAGE_NAMES}
    def on_stage(self, stage: str, duration_s: float) -> None:
        self.samples[stage].append(duration_s * 1000.0)  # ms
    def on_tick_complete(self, tick_index: int, total_s: float) -> None:
        pass

coll = MyCollector()
rt = ArachniteRuntime(..., tick_instrumenter=coll)
# or later:
rt.set_tick_instrumenter(coll)   # takes effect on the next tick
rt.set_tick_instrumenter(None)   # detach
```

Built-in use: `benchmarks/stage_breakdown.py` ships a `StageTimingCollector` (benchmark-
private, not exported from `arachnite`) that feeds samples into `DescriptiveStats.from_runs(
..., run_samples=...)` for per-stage median/P95/P99 bootstrap CIs. OpenTelemetry and
Prometheus adapters (backlog items B-15 / B-16) are expected to implement this same
protocol.

---

## LLM providers

Three backends, one interface. `complete()` is sync; `LLMInstinctNode` calls it in a daemon thread:

```python
from arachnite import AnthropicProvider, OllamaProvider, LocalProvider

# Cloud (Anthropic API)
provider = AnthropicProvider(model="claude-haiku-4-5-20251001")

# Local server (Ollama, OpenAI-compatible)
provider = OllamaProvider(model="llama3.1", base_url="http://localhost:11434/v1")

# Embedded (llama-cpp-python, no server)
provider = LocalProvider(model_path="/models/llama-8b.gguf", n_gpu_layers=-1)

# Inject into any LLMInstinctNode:
node = SmartInstinct(bus=bus, provider=provider)
```

### Shared models on constrained devices

```python
from arachnite import SharedModelRegistry, LocalProvider

registry = SharedModelRegistry()
provider = registry.get_or_create(
    "llama-8b",
    lambda: LocalProvider(model_path="/models/llama-8b.gguf"),
)
# All nodes share one model instance, one threading.Lock:
curiosity  = CuriosityInstinct(bus=bus, provider=provider)
social     = SocialInstinct(bus=bus, provider=provider)
reflection = ReflectionInstinct(bus=bus, provider=provider)
```

If you need a provider-native call the `complete()` abstraction doesn't
expose (e.g. driving `LocalProvider._llm` for the full OpenAI-style
`create_chat_completion` response), use `locked()` to run it under the *same*
lock that serialises every node's `complete()` — otherwise your raw call races
the shared, non-thread-safe model handle:

```python
with provider.locked() as inner:          # holds the shared lock
    resp = inner._llm.create_chat_completion(...)
```

Only use the yielded provider inside the block, keep the block to one inference
(the lock is shared across all nodes), and don't call back into `complete()` /
`locked()` from within it — the model is not reentrant, so re-entry raises
`RuntimeError` rather than deadlocking.

---

## StateUpdateSignal — write to context state via bus

Any node can update ContextNode.state without a direct reference:

```python
import time
from arachnite import StateUpdateSignal

await bus.publish(StateUpdateSignal(
    source=self.node_id, kind="state_update",
    value=None, confidence=1.0, timestamp=time.monotonic(),
    key="world_model", state_value={"temp": 42, "faces": 1},
))
# Published on the bus → the runtime buffers it and instincts see it in
# ctx.state["world_model"] at the start of the NEXT tick (N+1): instincts and
# actions run after ContextNode.update(), so it cannot land any earlier.
# A sense node RETURNING one from read() is applied in the same tick instead,
# and stays current — the copy read_all() publishes for bus subscribers is
# recognised by the runtime and not buffered back into the next tick.
# ctx.state is a shallow copy — mutations do not affect ContextNode's internal state
# ctx.state is per AgentNode: a StateUpdateSignal from ANOTHER agent (over the
# transport) reaches bus subscribers but never writes this agent's state.
```

---

## Context state persistence

```python
from arachnite import ContextNode

# State survives reboots:
ctx = ContextNode(
    state_path="state/self_model.json",
    flush_on_write=True,   # flush on every set()/delete() and state-changing StateUpdateSignal
    max_state_keys=100,    # evict oldest key (by insertion order) when exceeded
                           # None (default) = no limit; enforced on set(), StateUpdateSignal, and load
)
ctx.set("capabilities", {"camera": True, "speaker": False})
# Reloaded automatically on next construction with the same path
```

---

## MediaStore — large payloads (images, audio, video)

For multi-modal agents, save large payloads to disk and pass paths through the pipeline.

```python
from arachnite import MediaStore, BaseSenseNode, Signal, BaseInstinctNode, Proposal
import time, asyncio

# 1. Create a shared store
media = MediaStore(base_dir="/tmp/arachnite/media")

# 2. SenseNode saves payload, puts path in signal
class CameraSense(BaseSenseNode):
    node_id = "CameraSense"
    signal_kind = "camera"

    async def read(self) -> Signal:
        frame = await asyncio.to_thread(capture_frame)
        path = media.store(frame, kind=self.signal_kind, source=self.node_id)
        return Signal(
            source=self.node_id, kind=self.signal_kind,
            value=str(path), confidence=1.0, timestamp=time.monotonic(),
            metadata={"media_path": str(path)},
        )

# 3. InstinctNode reads file, attaches path + summary in evidence
class VisionInstinct(BaseInstinctNode):
    node_id = "VisionInstinct"
    priority = 80
    trigger_on_signals = ["camera"]

    async def evaluate(self, ctx) -> Proposal | None:
        for sig in ctx.signals:
            if sig.kind == "camera":
                path = sig.metadata.get("media_path")
                summary = await asyncio.to_thread(analyze_image, path)
                if "fire" in summary.lower():
                    return Proposal(
                        instinct_id=self.node_id, action_id="Evacuate",
                        priority=150, urgency=0.95,
                        evidence={
                            "camera_path": path,
                            "camera_summary": summary,
                        },
                    )
        return None

# 4. DecisionNode can inspect evidence for smarter choices
# 5. ActionNode can load file: media.load(proposal.evidence["camera_path"])

# Cleanup old files periodically
media.cleanup(max_age_s=300)   # remove files older than 5 minutes

# store() never overwrites: a name already taken (same source/tick/100 us bucket)
# gets a _1, _2, ... suffix. `extension` must be '.name' segments of
# [a-zA-Z0-9_-] (else PathTraversalError); containment is a real path check.
# A path string on kind 'visual' crosses network transports unchanged (NumpyCodec
# only array-encodes ndarrays; other values fall back to msgpack).
media.clear()                   # remove everything
```

---

## Instinct throttling and signal gating

```python
class ReflectionInstinct(BaseInstinctNode):
    node_id            = "Reflection"
    priority           = 20
    trigger_interval_s = 60.0   # fire at most once per 60 seconds
    # Interval measured from evaluation *completion*, not start.
    # None (default) = fire every tick. Does not apply to reflex nodes.

class SocialInstinct(BaseInstinctNode):
    node_id            = "Social"
    priority           = 65
    trigger_on_signals = ["face", "speech", "proximity"]
    # evaluate() only called when at least one matching signal is present.
    # None (default) = fire every tick. Not a gate for reflex nodes (see below).
    # Can be combined with trigger_interval_s (signal gate checked first).
```

On a **reflex** node, `trigger_on_signals` does not gate tick-mode evaluation (reflexes
are evaluated every tick). With `ArachniteRuntime(reflex_mode="event")`, it moves the
reflex onto the event-driven lane instead (see *Event-driven reflexes*).

---

## Action dispatch, actuator resources and arbitration (ADR 0005)

**Non-blocking launch.** The runtime starts every action with
`ActionMasterNode.launch(proposal, origin="decision")` or
`launch_reflex(proposal, preemption)`. The lookup, conflict check, guards and resource
reservation all happen synchronously, then `execute()` starts as a tracked task and a
`LaunchOutcome(status, action_id, owners)` is returned at once:

| `LaunchStatus` | Meaning |
|---|---|
| `LAUNCHED` | `execute()` started as a task |
| `BLOCKED` | deliberative launch conflicts with a running owner (or an armed reflex's claim); not started |
| `ARMED` | reflex waits for its owners to release; owners are being preempted |
| `DEDUPED` | that reflex action is already running or armed as a reflex |
| `VETOED` | an `ActionGuard` denied it (a failed `ActionVetoed` Result is buffered) |
| `NOT_FOUND` | no ActionNode registered under that action_id |
| `CLOSED` | the master is shutting down (`close()` / `cancel_all()`); nothing new starts until `setup()` |

`cancel(action_id)` withdraws a reflex armed under that id if there is one, otherwise
cancels the running run; a run the master cancels (`cancel()`, `cancel_all()`) ends
with `Result(interrupted=True, cancelled=True)`, for `launch()` and awaited `dispatch()`
alike. `Result.cancelled` marks every stop by cancellation at an `await` after which the
safe-stop ran (preemption, `cancel()`, shutdown, emergency stop, action timeout), as
opposed to a stop at a step boundary.

Results of launched actions are collected with `drain_completed()` (the runtime does
this each tick). `await action_master.wait_idle(timeout)` / `await runtime.wait_idle(timeout)`
waits until nothing is running or armed, and returns False on timeout.

**Declaring resources.** `resources` names the actuators an action commands. Two actions
conflict if they share an `action_id` or any resource. Resources are acquired
all-or-nothing at launch and released when the task ends, so at most one running action
owns a resource. An action with no declared resources conflicts only on its own
`action_id` (the behaviour before ADR 0005). Undeclared actuator access is invisible to the
framework. To make declaration mandatory, use `strict_resources` (registration of an
action with empty `resources` raises `NodeRegistrationError`):

```python
class ArmMove(BaseActionNode):
    node_id   = "ArmMove"
    resources = frozenset({"arm"})

class Gripper(BaseActionNode):
    node_id   = "Gripper"
    resources = frozenset({"gripper"})          # disjoint → may run alongside ArmMove

class PickAndPlace(MultiStepActionNode):
    node_id   = "PickAndPlace"
    resources = frozenset({"arm", "gripper"})   # conflicts with both of the above

am = ActionMasterNode(bus=bus, strict_resources=True)
# or: RuntimeBuilder().strict_resources()
```

**Deliberative proposals vs. running owners** (inside `DecisionMasterNode`):
- No conflict → launched.
- Every conflicting owner is deliberative and of **lower** priority → an
  `InterruptRequest(target_action_id=owner)` goes to each owner, which stops under its
  own `InterruptPolicy`. An owner inside a mandatory block holds (latches) the request
  and honours it at the first stop point after the block: requests are never refused,
  only deferred (ADR 0009). The proposal is **parked for hand-off**
  (`DecisionMasterNode.park()`; see `dm.handoff_proposals`). It is retried every tick
  ahead of fresh proposals until the owners release. It is superseded only by a new
  proposal from the same instinct and dropped after `max_handoff_ticks` (default 100).
- Otherwise it is **held** (not dispatched; kept only if `persist=True`). This covers a
  reflex-owned action and an owner of equal or higher priority. Deliberation never cuts
  into a mandatory block.

```python
# Query what's running:
running = action_master.current_actions()      # dict[str, BaseActionNode]
ids     = action_master.running_action_ids()   # set[str]
owners  = action_master.resource_owners()      # dict[resource, action_id]
armed   = action_master.armed_reflexes()       # dict[action_id, Proposal]
origin  = action_master.origin_of("ArmMove")   # "reflex" | "decision" | "direct" | None
blocks  = action_master.conflicting_owners(p)  # set[action_id]; empty = can start now

# Interrupt a specific running action (deliberative; latched while it is in a block):
await action_master.request_interrupt(req, action_id="CoolDown")

# Runtime-less, awaiting dispatch (dedups by action_id, keeps highest priority):
results = await action_master.dispatch_many([proposal_a, proposal_b])

# Context provides plural fields:
ctx.last_results   # list[Result] — actions that completed since the previous tick (completion order)
ctx.action_states  # list[ActionExecutionState] — every running multi-step action
# Singular ctx.last_result (first completed) / ctx.action_state still work
```

---

## Reflex arbitration — `ReflexPreemption`

When a reflex's target action needs a resource that a running action owns, the reflex
node's `preemption` decides what happens:

- **`ReflexPreemption.PREEMPT` (default)**: the owner's task is cancelled at its current
  `await`, **even inside a mandatory block**. Its `on_preempted(proposal, preempted_by)`
  safe-stop hook then runs, shielded and bounded by `safe_stop_timeout_s` (default 1.0 s;
  an overrunning hook is cancelled, and abandoned — left running, logged — if it has not
  ended 0.1 s later). Only then are its resources released and the
  reflex action started. The owner's Result has `preempted=True, interrupted=True` and is
  never retried. No rollback runs unless the owner sets `rollback_on_preempt = True`,
  because undoing a physical operation during a hazard can itself be unsafe. A run walks
  at most once: a preemption during or after an interrupt/abort rollback walk does not
  start it again. Each rollback callable is timed out at its step's `timeout_s`.
  Retries (`max_retries`) never re-run a block that was cut: not after the action's own
  timeout inside a block, nor after a step aborted inside a block unless its rollback walk
  undid it. A step's `interrupted=True` ends the run only where the policy allows a stop
  (interruptible step under ALWAYS/ROLLBACK, checkpoint step under CHECKPOINT, never NEVER).
- **`ReflexPreemption.WAIT_FOR_BLOCK`**: if the owner is inside a mandatory block, the
  reflex is **armed** and the owner is preempted at the first step boundary after the
  block, whatever its `InterruptPolicy`. Outside a block it behaves like PREEMPT. The
  wait is bounded by the remaining mandatory-step timeouts.
- An armed reflex **claims** its resources, so no deliberative launch can take them in
  between. It starts the moment its owners release, ahead of any deliberative proposal.
- A reflex **never preempts a running reflex**: it is armed until that action releases.
  A reflex whose action is already running or armed as a reflex is de-duplicated
  (`DEDUPED`, logged). A reflex with disjoint resources simply runs alongside the owner.
- Reflex launches bypass `ActionGuard`s by **origin** (`origin="reflex"`), not by priority.
  A deliberative proposal at priority ≥ 200 is still guarded.
- Preemption happens only on the runtime's `launch_reflex()` path. A direct
  `dispatch()` never preempts anything.

**Choosing a mode.** Use PREEMPT when stopping now is safer than finishing the block,
for example a collision or a person in the workspace, and the owner has a meaningful
safe-stop. Use WAIT_FOR_BLOCK when an interrupted block is itself a hazard, for example
half-poured material or a weld, and the hazard tolerates the remaining block time.

**Context-dependent modes.** `preemption` belongs to the reflex node and is read when the
proposal is launched; do not reassign it inside `evaluate()`. A re-fire while the reflex is
armed is de-duplicated, so its mode cannot change mid-wait. When the right response depends
on the situation (cut the block for an obstacle, finish it when a person is down beside the
load), write two reflex nodes with disjoint predicates and distinct target actions, one per
mode. A higher-priority PREEMPT reflex still cuts a block that a WAIT_FOR_BLOCK reflex is
armed to wait out, so a waiting response can be escalated.

**Scope of exclusion.** Exclusion covers the commands the framework schedules, in one
runtime. A cancellation stops the action's coroutine, not a command it handed to a worker
thread or a device controller; the safe-stop hook must halt such a command. Actions on
different AgentNodes (or machines sharing a workspace) are not arbitrated against each other.

**Writing a safe-stop.** `on_preempted()` brings actuators to a safe *hold*: brake, freeze
the joints, keep the grip. It must not undo work, and it must finish within
`safe_stop_timeout_s`. Hardware calls made through `asyncio.to_thread()` cannot be
cancelled, so the hook must cope with a command that is still in flight. The same hook
runs when `emergency_stop()` or shutdown cancels the action; `preempted_by` is then a
stand-in proposal with `action_id="__shutdown__"`.

```python
class PickAndPlace(MultiStepActionNode):
    node_id             = "PickAndPlace"
    resources           = frozenset({"arm", "gripper"})
    interrupt_policy    = InterruptPolicy.ROLLBACK   # governs deliberative interrupts
    safe_stop_timeout_s = 0.5
    rollback_on_preempt = False                      # default: no undo on preemption

    async def on_preempted(self, proposal: Proposal, preempted_by: Proposal) -> None:
        await self.arm.brake()                       # hold position, keep the grip
        self.logger.warning("Preempted; arm held", by=preempted_by.instinct_id)

class CollisionReflex(BaseReflexInstinctNode):
    node_id    = "CollisionReflex"
    priority   = 250
    preemption = ReflexPreemption.PREEMPT            # or WAIT_FOR_BLOCK
    async def evaluate(self, ctx): ...               # → Proposal(action_id="Retract", ...)

class Retract(BaseActionNode):
    node_id   = "Retract"
    resources = frozenset({"arm"})                   # takes "arm" only; the grip is kept
```

See `examples/robot_arm/` for the complete pattern, including a recovery instinct that
finishes the job once the hazard has cleared.

---

## Event-driven reflexes — `reflex_mode="event"` and `BaseSenseNode.push()`

By default (`reflex_mode="tick"`) reflexes are evaluated once per tick, so reflex latency
includes up to one tick period of quantisation. Opt in to the event lane per runtime:

```python
rt = ArachniteRuntime(..., reflex_mode="event",
                      reflex_signal_ttl_s=None,      # default: one tick period
                      reflex_eval_timeout_s=0.05)
# or: RuntimeBuilder().reflex_mode("event")
```

- A reflex node that declares `trigger_on_signals` is evaluated **the moment a matching
  signal is published on the bus**, not once per tick. That signal may come from a polled
  sensor during the sense stage or from `push()` outside any tick. Reflexes without
  `trigger_on_signals` stay in the tick's reflex stage.
- The reflex sees `ContextNode.reflex_view(signals)`: the freshest signal per
  `(source, kind)` of its trigger kinds no older than `reflex_signal_ttl_s`, plus current
  state, results and action states. The history is **empty** (no per-event copy).
- Evaluation is bounded by `reflex_eval_timeout_s`. Errors and timeouts are logged and
  never raised into the publisher. Launching goes through the same arbitration as above.
  The lane stays live while the runtime is paused.
- A reflex is not re-evaluated by a signal published during its own evaluation (e.g. the
  `node_fault` of a `node_fault`-triggered reflex that raised); the signal is still kept
  as the latest of its kind for the next evaluation.

**Event-driven sensor.** Call `await self.push(signal)` from a background listener started
in `setup()`. It publishes immediately, so an event-mode reflex triggered by that kind
runs before `push()` returns. The signal is also queued so that the next tick's
`read_all()` hands it to the context once, for deliberation.

```python
class ToFSense(BaseSenseNode):
    node_id     = "ToFSense"
    signal_kind = "proximity"

    async def setup(self) -> None:
        self.spawn_background_task(self._listen())

    async def _listen(self) -> None:
        async for mm in tof_interrupt_stream():          # hardware-driven events
            await self.push(Signal(source=self.node_id, kind=self.signal_kind,
                                   value=mm / 1000, confidence=1.0,
                                   timestamp=time.monotonic()))

    async def read(self) -> Signal | None:
        return None                                      # nothing polled
```

---

## Shutdown — `stop()` vs. `emergency_stop()`

- **`await rt.stop()`** (graceful, 7 phases via `ShutdownCoordinator`):
  1. Sensing stops.
  2. The in-flight tick finishes.
  3. A shutdown interrupt goes to every running action. It is held through a running
     mandatory block, and the coordinator waits for the blocks to finish (bounded by
     the remaining block timeouts).
  4. Actions stop at their next boundary, so ROLLBACK actions unwind. Whatever is still
     running is then cancelled through its safe-stop.
  5–7. Supervisors stop, nodes tear down, the transport disconnects.
- **`await rt.emergency_stop()`** closes the action master (launches return `CLOSED`),
  stops the loop and the reflex lane, then cancels every action. Each one runs its
  `on_preempted()` safe-stop (bounded; one already running is waited for); **no rollback** runs.
  The shutdown runs in its own task: `await rt.wait()` returns when it has *finished*
  (safe-stops done, nodes torn down). A second call waits; one during `stop()` takes
  it over. Called from inside the tick or a running action, `stop()` /
  `emergency_stop()` return once the shutdown has started; so do calls from the
  shutdown's own code (a node's `teardown()`, `on_shutdown_action`) and from an
  `on_preempted()` safe-stop. A stop at any point of `start()` before the loop runs
  aborts the start; a restart waits for the previous shutdown (following an emergency
  take-over); `wait()` during `start()` waits for that run. A `pause()` during `start()`
  holds (the runtime starts paused); a restart after a paused stop resumes the nodes.
  A teardown that raises (or ends in its own `CancelledError`, reported as
  `RuntimeError`) does not stop the shutdown from completing; the error is re-raised
  to `stop()` / `wait()` afterwards.
  Then the nodes tear down. This is a *shutdown* path, not a hazard response: to cut
  into a mandatory block and keep the agent running, use a PREEMPT reflex.

---

## Proposal persistence across ticks

By default, proposals that lose the decision competition are discarded. Set `persist=True`
on a Proposal to carry it forward to subsequent ticks until it is dispatched or superseded.

```python
class DoorbellInstinct(BaseInstinctNode):
    node_id            = "Doorbell"
    priority           = 70
    trigger_on_signals = ["audio"]   # only fires on audio signals
    trigger_interval_s = 60.0        # at most once per minute

    async def evaluate(self, ctx: Context) -> Proposal | None:
        audio = [s for s in ctx.signals if s.kind == "audio" and "doorbell" in str(s.value)]
        if audio:
            return Proposal(
                instinct_id=self.node_id, action_id="AnswerDoor",
                priority=self.priority, urgency=0.8,
                persist=True,  # survive while held (owner busy, in a block, or outranks it)
            )
        return None
```

Supersession rules (managed by DecisionMasterNode):
- New persist=True proposal from same instinct → replaces pending
- Instinct evaluated, returns None or persist=False → clears pending (conditions changed)
- Instinct throttled/gated (not evaluated) → pending stays
- Proposal dispatched → removed from pending
- Pending exceeds max_pending_ticks (default 50) → dropped
- Instinct unregistered via unregister_instinct_live() → clear_pending(instinct_id) removes pending + age (and any parked hand-off)

Separate from `persist`: a proposal that was selected and interrupted its owner, but could not
start yet, is **parked for hand-off** (`dm.park()`), whatever its `persist` flag. It is re-offered
every tick until it starts, is superseded by any new proposal from the same instinct, or exceeds
`max_handoff_ticks` (default 100). An instinct going quiet does not cancel it.

```python
# Configure staleness caps:
dm = DecisionMasterNode(bus=bus, strategy=strategy, max_pending_ticks=100, max_handoff_ticks=100)

# Introspect pending / parked proposals:
dm.pending_proposals  # dict[str, Proposal] keyed by instinct_id
dm.handoff_proposals  # dict[str, Proposal] keyed by instinct_id

# All proposals considered in the most recent on_new_proposals_many() call
# (includes both fresh proposals and carried-forward pending proposals):
dm.last_considered  # list[Proposal] — used by runtime for rejection notifications

# InstinctMasterNode tracks which instincts were actually evaluated:
im.last_evaluated_ids  # set[str] — passed to DecisionMasterNode by the runtime
```

---

## Permission whitelist (opt-in sandbox)

Nodes declare capabilities they need; the manifest or runtime config defines what is allowed.
Validation is startup-only — zero runtime cost. If no permissions are configured, validation
is skipped entirely (backward compatible).

```python
from arachnite import Permission

class MyNetworkSense(BaseSenseNode):
    node_id = "MyNetworkSense"
    signal_kind = "remote"
    permissions = frozenset({Permission.NETWORK})  # declares it needs network access
    ...
```

Available permissions: `NETWORK`, `FILESYSTEM_READ`, `FILESYSTEM_WRITE`, `SUBPROCESS`, `GPU`.

**Manifest syntax** — `permissions` on a node def is the allowed whitelist:
```yaml
agents:
  - id: edge-01
    nodes:
      sense:
        - kind: myapp.nodes.MyNetworkSense
          permissions: [network]  # allowed — matches node's declaration
```

**Programmatic** — pass `allowed_permissions` to `ArachniteRuntime`:
```python
rt = ArachniteRuntime(
    ...,
    allowed_permissions={"MyNetworkSense": {Permission.NETWORK}},
)
```

If a node declares a permission not in its allowed set, `PermissionValidationError` is raised
before the tick loop starts. Nodes not listed in the map are unrestricted.

---

## Egress allowlist — keep signal kinds off the wire

A bus with a transport forwards **every** published kind to the broker by default; not
subscribing elsewhere only stops *consumption*, not egress. To keep a kind local, gate it at
the publisher with `SignalBus(wire_kinds=…)`. Egress-only — inbound delivery is unaffected, so
a node can still receive a kind it does not publish onto the wire. Unrelated to
`permissions.py`, which is a startup capability validator, not a router.

```python
from arachnite import SignalBus

# Only 'alert' and 'remote_command' leave this device; everything else stays local.
bus = SignalBus(transport=transport, agent_node_id="edge-1",
                wire_kinds={"alert", "remote_command"})
```

- `wire_kinds=None` (default) forwards every kind — unchanged behaviour.
- A set restricts egress to those kinds; `'*'` is a catch-all; an empty set forwards nothing.
- `bus.wire_kinds()` returns the allowlist (or `None`).

**Manifest syntax** — per agent; omit to forward every kind, empty list forwards nothing:
```yaml
agents:
  - id: edge-01
    transport: mqtt
    wire_kinds: [alert, remote_command]   # egress allowlist; ManifestValidationError if not a list
```

Prefer an explicit allowlist over relying on remote nodes not subscribing: the kinds that must
cross the mesh are usually far fewer than internal chatter, so it is less error-prone and
auditable.

---

## Distributed bridge — remote signals, manifests, transports (spec §10–§11)

**Manifest node entries** take only `kind`, `config`, `reflex`, `action_id`, `permissions`;
any other key (e.g. `priority` — set it on the class) raises `ManifestValidationError`. A node
is a reflex for the co-location check if the entry says `reflex: true`, its class subclasses
`BaseReflexInstinctNode`, or its class sets `reflex = True` (the runtime's routing rule).

**Remote signals reach the tick.** `AgentNode` attaches a remote listener to its bus
(`SignalBus.add_remote_listener`); the bus then subscribes `'*'` on the transport, and every
signal another AgentNode publishes is queued with `ArachniteRuntime.inject_remote_signal()`
into this agent's **next** tick's `ctx.signals`, after the local sense output. Local signals are
never doubled (only transport-delivered signals reach the listener). Bounded at 1024 between
ticks (oldest dropped, warning). `supervisor`/`node_fault` are not injected twice (the runtime
buffers them itself); a remote `state_update` is never applied (ctx.state is per agent).
Remote SupervisorSignals also feed `agent.health.remote_states()` / `mesh_healthy()`.
Hand-built bus + runtime: `bus.add_remote_listener(runtime.inject_remote_signal)`.
Proposals do NOT cross the bus: an instinct's proposal goes to its own agent's actions.

```python
bus = SignalBus(transport=NATSTransport(agent_node_id="pi"))  # bus id defaults to "pi"
bus.is_remote(signal)          # True for a signal published by another agent's bus
await bus.stop_transport()     # withdraw subscriptions (AgentNode.stop() does this)
```

- Agent ids must be unique across the mesh (they are the echo-suppression key).
- `'*'` works on every transport (MQTT `prefix#`, NATS `prefix.>`, Redis PSUBSCRIBE); a callback
  under both a kind and `'*'` is called once; a raising subscriber never stops delivery.
- Bus transport interest follows local subscribers (withdrawn on the last unsubscribe); a
  failed transport subscribe is retried with backoff.
- The wire keeps `SupervisorSignal` / `NodeFaultSignal` / `StateUpdateSignal` fields and dicts
  with int keys.

**Manifests are validated on load.** `DeploymentManifest.from_dict()/from_yaml()` raise
`ManifestValidationError`, and `AgentNode.from_manifest()` / `MeshRuntime.start()` re-validate.
Checks use each class's `node_id` (not its class name): reflex co-location, duplicates. Also:
sections must be sense/instinct/decision/action with matching base classes, permission
whitelists, known transport kinds, `transport_config` keys per transport (mqtt: broker_host,
broker_port, topic_prefix, qos, username, password, tls, reconnect_interval_s,
max_reconnect_attempts; nats: servers, subject_prefix, reconnect_*; redis: url,
channel_prefix, db, password, reconnect_*). Mesh-level defaults: `mqtt_broker: host:port`,
`nats_server`, `redis_url`. `on_transport_fault` is rejected (no TransportFaultReflex exists).

**MeshRuntime**: agents with `transport: local` share one in-process LocalTransport; a failed
start stops every agent of that attempt before raising.

**Codecs**: once a network transport connected with a `CodecRegistry`, `register()` of an unsafe
codec (PickleCodec) raises `UnsafeCodecError`; received values are decoded with
`decode_network()`, which refuses unsafe codecs.

**Reconnect**: MQTT/Redis `connect()` retry `max_reconnect_attempts` times then raise
`TransportConnectionError` (Redis PINGs — `from_url` is lazy); `disconnect()` cancels a pending
reconnect; NATS re-subscribes after a disconnect()/connect() cycle.

---

## Signal merge policies

When multiple SenseNodes emit the same signal kind in one tick (redundant sensors),
`SenseMasterNode` can merge them per-kind using a `MergePolicy`:

```python
from arachnite import SenseMasterNode, SignalBus
from arachnite.models import MergePolicy

sm = SenseMasterNode(
    bus=SignalBus(),
    merge_policies={
        "temperature": MergePolicy.MEAN,               # average numeric values
        "proximity":   MergePolicy.HIGHEST_CONFIDENCE,  # keep most confident
        "visual":      MergePolicy.LATEST,              # keep newest timestamp
        # kinds not listed → MergePolicy.ALL (keep all, default)
    },
)
```

| Policy | Behaviour |
|---|---|
| `ALL` (default) | Keep all signals — no merging |
| `LATEST` | Keep signal with latest timestamp |
| `HIGHEST_CONFIDENCE` | Keep signal with highest confidence |
| `MEAN` | Average numeric values and confidences; falls back to `HIGHEST_CONFIDENCE` for non-numeric |
| `BAYESIAN` | Inverse-variance (precision-weighted) fusion, confidence read as precision; metadata adds `fused_variance`; non-numeric falls back to `HIGHEST_CONFIDENCE` |
| `ENSEMBLE` | Confidence-weighted mean; confidence from epistemic + aleatoric variance (in metadata); non-numeric falls back to `HIGHEST_CONFIDENCE` |

Merged signals carry metadata: `merge_policy`, `merged_from` (source node_ids), `sample_count` (MEAN, BAYESIAN, ENSEMBLE).
Single signals pass through unchanged. Zero overhead when no policies are configured.

---

## Hardware integration pattern

No built-in HAL — nodes own their drivers. The framework provides the abstraction boundary
(`read()` / `execute()`) and config injection. Hardware APIs vary too widely for a useful
thin wrapper.

**Pattern:** declare hardware config in manifest, lazy-import driver in `setup()`, wrap all
I/O in `asyncio.to_thread()`, clean up in `teardown()`.

```yaml
# Manifest
nodes:
  sense:
    - kind: myapp.nodes.ProximitySense
      config:
        gpio_pin: 17
        backend: libgpiod
```

```python
class ProximitySense(BaseSenseNode):
    node_id = "ProximitySense"
    signal_kind = "proximity"

    async def setup(self) -> None:
        pin = self.config.get_int("gpio_pin", 17)
        self._driver = await asyncio.to_thread(_open_gpio, pin)

    async def read(self) -> Signal:
        value = await asyncio.to_thread(self._driver.read)
        return Signal(source=self.node_id, kind=self.signal_kind,
                      value=value, confidence=1.0, timestamp=time.monotonic())

    async def teardown(self) -> None:
        await asyncio.to_thread(self._driver.cleanup)
```

Test with stubs — inject a fake driver via config, no framework changes needed.

---

## Background task lifecycle

Long-running listeners (hardware event streams, MQTT subscribers) belong in `setup()`,
registered via `spawn_background_task()`. The framework cancels all tracked tasks automatically
before `teardown()`.

```python
class EventDrivenSense(BaseSenseNode):
    node_id = "EventDrivenSense"
    signal_kind = "event"

    async def setup(self) -> None:
        self._queue: asyncio.Queue = asyncio.Queue()
        self.spawn_background_task(self._listen())  # tracked; auto-cancelled on shutdown

    async def _listen(self) -> None:
        async for event in hardware_event_stream():
            await self._queue.put(event)

    async def read(self) -> Signal | None:
        try:
            event = self._queue.get_nowait()
        except asyncio.QueueEmpty:
            return None
        return Signal(source=self.node_id, kind=self.signal_kind,
                      value=event, confidence=1.0, timestamp=time.monotonic())
```

For hazard events that a reflex must see at once, have the listener call
`await self.push(signal)` instead of queueing for `read()` (see *Event-driven reflexes*).

`cancel_background_tasks()` is called by all three master nodes (SenseMasterNode,
InstinctMasterNode, ActionMasterNode) before their own `teardown()`, by every supervisor
restart before the node's `teardown()`/`setup()`, and by a master whose leaf `setup()` failed
during `start()` (siblings already set up are also torn down). Override it only if
custom cleanup ordering is required.

**Supervisor restarts are bounded.** One restart per node is pending at a time (faults
meanwhile are reported, not re-scheduled); every attempt counts against `max_restarts`. DEAD is
terminal — masters stop running the node (`read()`/`evaluate()`/tick hooks skipped via the
supervisor's `dead_node_ids`) and further faults publish nothing; only `restart()` or a fresh
`track()` revives it.

---

## Node dependency declaration

Declare which node_ids must exist before this node can operate. Validated once at startup by
`ArachniteRuntime.start()` before any `setup()` call. Raises `DependencyValidationError` if
a required node_id is missing.

```python
from arachnite import BaseInstinctNode, DependencyValidationError

class VisionInstinct(BaseInstinctNode):
    node_id  = "VisionInstinct"
    priority = 80
    requires = ("CameraSense", "ObjectDetectionSense")  # must be registered

    async def evaluate(self, ctx: Context) -> Proposal | None:
        ...
```

If `CameraSense` or `ObjectDetectionSense` is not registered, startup raises:
`DependencyValidationError: VisionInstinct requires ['CameraSense', 'ObjectDetectionSense'] but
['CameraSense'] are not registered`.

---

## Artifact directory

Each node has an `artifact_dir` property that returns a `Path` for writing large outputs
(model checkpoints, debug frames, analysis dumps). The directory is created lazily and scoped
per agent and node.

```python
class AnalysisAction(BaseActionNode):
    node_id = "AnalysisAction"

    async def execute(self, proposal: Proposal) -> Result:
        out_path = self.artifact_dir / "analysis.json"  # created on first access
        out_path.write_text(json.dumps(result_data))
        return Result(action_id=self.node_id, success=True, output=str(out_path))
```

Default path: `artifacts/{agent_node_id}/{node_id}/`. Override the root via constructor:

```python
node = AnalysisAction(bus=bus, artifact_root="/mnt/data/artifacts")
# → /mnt/data/artifacts/<agent_node_id>/AnalysisAction/
```

---

## Benchmarking

The framework ships with a complete benchmark suite in `benchmarks/`. Run it to measure
framework overhead on your target hardware.

`pip install -e ".[benchmarks]"` — enables psutil-based RSS measurement in memory_footprint and soak_test (also in `[all]`); without it, RSS columns render `nan` on platforms without `/proc`, latency numbers unaffected.

`pip install py-trees` — enables the py_trees row of the cross-framework comparison harness (`python -m baselines.compare`); there is no `baselines` extra. Jason and ROS 2 are not pip-installable and stay opt-in via JVM / sourced ROS distro respectively.

```bash
# Full suite (8 registered benchmarks, 30 runs each, JSON output)
python benchmarks/suite.py

# Quick run for development
python benchmarks/suite.py --runs 5

# Individual benchmarks
python benchmarks/tick_latency.py        # tick overhead (ms)
python benchmarks/reflex_latency.py      # safety response time (µs)
python benchmarks/memory_footprint.py    # RSS at steady state (MB)
python benchmarks/scalability_sweep.py   # tick latency vs node count
python benchmarks/scalability_extended.py # bus throughput, action dispatch, history depth
python benchmarks/stage_breakdown.py     # per-stage tick overhead via TickInstrumenter (§8.2.1)
python benchmarks/multistep_action_latency.py  # interrupt/rollback/mandatory-block latency (§8.2.7)
python benchmarks/soak_test.py            # 1M-tick stability soak; per-100k-bucket mean/P99/RSS + drift verdict (§8.2.8)
python benchmarks/transport_latency.py    # publish-to-wake latency across 4 transports × 3 payload sizes; env-gated brokers (§8.2.9)
python -m benchmarks.active_inference_comparison # decision strategy A/B (Greedy/Weighted/Random/AI)
python benchmarks/reflex_arbitration.py e9 --trials 200   # collision injected per stage of a running pick (ADR 0005)
python benchmarks/reflex_arbitration.py e10 --trials 200  # reflex latency under a long-running action
```

### Key metrics

| Benchmark | Definition | Unit |
|-----------|-----------|------|
| Tick latency | L_tick = t₁ − t₀ around `runtime.tick()` (action launch only, not execution — ADR 0005) | ms |
| Reflex latency | T_reflex = t_action − t_sense (sensor read to action entry) | µs |
| Memory footprint | Δ_RSS = RSS(config) − RSS(baseline) after 100 ticks | MB |
| Scalability factor | S(N) = median_tick(N) / median_tick(1) | dimensionless |

### Statistical rigour (`benchmarks/stats.py`)

- 95% bootstrap CI (10,000 resamples, seed=42) over per-run medians (also P95 and P99 via new `DescriptiveStats.p95_ci_lower/upper`, `p99_ci_lower/upper`)
- `bootstrap_ci(data, stat_fn=statistics.mean, ...)` accepts any `Callable[[Sequence[float]], float]`; empty input returns `(nan, nan)`
- `percentile(data, p)` — nearest-rank percentile primitive (`all_sorted[int(n * p/100)]`)
- `DescriptiveStats.from_runs(medians, samples, n_per_run, run_samples=None)` — when `run_samples` is supplied, P95/P99 CIs bootstrap over per-run P95/P99 estimates; else bootstrap the pooled array with a percentile statistic
- Wilcoxon signed-rank test (α=0.05) for paired comparisons
- Cliff's delta effect size: negligible (<0.147), small, medium, large (≥0.474)
- Bonferroni correction for multiple comparisons

### File map

```
benchmarks/
  suite.py               unified runner — device info + all benchmarks → JSON
  stats.py               bootstrap CI, Wilcoxon, Cliff's delta, DescriptiveStats
  tick_latency.py        per-tick wall-clock overhead
  reflex_latency.py      sensor-to-action reflex arc timing
  memory_footprint.py    RSS measurement at steady state
  scalability_sweep.py   tick latency × node count
  scalability_extended.py  bus throughput, concurrent actions, history depth
  stage_breakdown.py     per-stage tick overhead via TickInstrumenter (§8.2.1)
  multistep_action_latency.py  interrupt/rollback/mandatory-block latency (§8.2.7)
  soak_test.py           1M-tick stability soak: per-100k-bucket mean/P99/RSS + drift verdict (§8.2.8)
  transport_latency.py   publish-to-wake latency × 4 transports × 3 payload sizes; brokers env-gated (§8.2.9)
  active_inference_comparison.py  Greedy/Weighted/Random/ActiveInference A/B (latency + bias)
  reflex_arbitration.py  E9 stage-wise collision injection, E10 reflex latency under a running action
  results/               JSON output directory (gitignored)
```

## Baseline comparison

Cross-framework comparison using a shared pick-and-place robot arm scenario. All frameworks
use the same deterministic physics stub (`baselines/shared_sim.py`) — only the framework differs.

```bash
# Run comparison (Arachnite vs py_trees, 5 runs)
python -m baselines.compare

# Publication-grade (30 runs)
python -m baselines.compare --runs 30 --ticks 10000
```

### Compared frameworks

| Framework | Available | Safety features |
|-----------|-----------|----------------|
| Arachnite | Always | Reflex arc, mandatory blocks, rollback, distributed |
| py_trees | `pip install py-trees` | None (BT priority only) |
| Jason | LoC only (needs JVM) | None (BDI plan priority) |
| ROS 2 BT | LoC only (needs ROS 2) | None (DDS callback priority) |

### Key findings

- **py_trees ≈ 19× faster** (0.009 ms vs 0.170 ms median Arachnite) — lacks asyncio pipeline / SignalBus / reflex pass
- **Both well under 0.5% of budget at 10 Hz** — the difference is measurable but not operationally significant
- **Arachnite ≈ 2.5× more code than py_trees** (465 vs 187 LoC) — the extra lines buy 3 safety features absent from all baselines
- **Cost per safety feature ≈ 93 lines** — reflex arc, mandatory blocks, rollback

### Comparison metrics

| Metric | Formula |
|--------|---------|
| Overhead ratio | R = median_arachnite / median_baseline |
| Budget utilisation | U = median · tick_rate / 1000 |
| Feature-normalised LoC | (LoC_A − LoC_B) / N_features |

### File map

```
baselines/
  compare.py            main comparison harness
  shared_sim.py         ArmState physics stub, BenchmarkResult
  py_trees/robot_arm.py behaviour tree implementation
  jason/                AgentSpeak + Java environment (LoC only)
  ros2/                 ROS 2 BT reference (LoC only)
  results/              JSON output directory
```

---

## Web dashboard and runtime observers

`SignalDashboard` (requires `pip install "arachnite[web]"`) is a log sink and a `'*'` bus
subscriber that streams every signal and log event to a browser and to a plain-text log file:

```python
from arachnite import SignalDashboard, LogLevel

dashboard = SignalDashboard(bus, host="127.0.0.1", port=7070, log_file="run.log",
                            level=LogLevel.DEBUG, backlog=500)
rt = ArachniteRuntime(..., log_sinks=[dashboard],
                      context_observers=[dashboard.submit_context],     # per-tick Context
                      decision_observers=[dashboard.submit_decision])   # per-tick DecisionEvent
await dashboard.start()      # then open http://localhost:7070
...
await dashboard.stop()
```

- `/ws` refuses cross-origin WebSocket handshakes: only the dashboard's own origin and clients
  that send no `Origin` (scripts) are accepted; `allowed_origins=["https://ops.example:8443"]`
  adds exact origins (`"*"` allows all, not recommended).
- `auth_token=` requires a Bearer token / `?token=` / cookie on every request. Binding a
  non-loopback host without a token raises in `start()` unless `allow_unauthenticated=True`.
  `ssl_certfile` + `ssl_keyfile` serve HTTPS/WSS.
- Observers are plain callables, also added with `rt.add_context_observer()` /
  `rt.add_decision_observer()`. A raising observer is logged at WARNING and never stalls the
  tick. `DecisionEvent` carries `tick`, `strategy`, `considered`, `dispatched` (selected for
  launch this tick) and `interrupts`.

---

## Testing helpers (`arachnite.testing`)

Factory functions for building pipeline objects with sensible defaults.
Eliminates boilerplate when unit-testing instincts, actions, and decision strategies.

```python
from arachnite import make_signal, make_proposal, make_result, make_context, MockBus

# Signal with defaults (kind="test", value=0.0, source="TestSense", confidence=1.0)
sig = make_signal(kind="thermal", value=42.0)

# Proposal with defaults (action_id="TestAction", priority=50, urgency=0.5)
prop = make_proposal(action_id="CoolDown", priority=100, urgency=0.9)

# Result with defaults (action_id="TestAction", success=True)
res = make_result(success=False, error=RuntimeError("boom"))

# Context with defaults (tick=1, empty signals/state/history)
ctx = make_context(
    tick=5,
    signals=[make_signal(kind="thermal", value=90.0)],
    state={"mode": "alert"},
    last_result=make_result(),
)
```

### MockBus — record published signals for assertions

```python
bus = MockBus()
node = MyInstinct(bus=bus)

# After running the node...
await bus.publish(make_signal(kind="thermal"))

bus.published                       # list[Signal] — all recorded signals (copy)
bus.published_of_kind("thermal")    # list[Signal] — filtered by kind
bus.clear()                         # reset recorded signals and subscribers
```

`MockBus` extends `SignalBus` — subscribers still fire normally, so nodes that
subscribe to the bus during `setup()` work exactly as in production.

### Testing with the non-blocking runtime

`await rt.tick()` returns once the actions are *launched*, not finished. Wait for them
explicitly, then tick once more to see their Results in the context:

```python
await rt.pause()                          # stop the background loop racing manual ticks
await rt.tick()                           # launches the action
assert await rt.wait_idle(timeout=2.0)    # False on timeout
await rt.tick()                           # Results drained into this tick's context
assert rt.context.snapshot().last_results[0].success
```

Without a runtime, `await action_master.dispatch(proposal)` still awaits and returns the
Result directly. To test a preemption, use `action_master.launch(...)`, then
`launch_reflex(...)`, then `wait_idle()` and `drain_completed()`. The preempted owner's
Result has `preempted=True`.

---

## Rules — never violate

1. Nodes never hold references to each other — use SignalBus
2. ReflexInstinctNode and its target ActionNode must be on the same AgentNode
3. MultiStepActionNode mandatory blocks (interruptible=False) can never be interrupted by deliberation (a deliberative request is held until the block ends). Only a reflex with `ReflexPreemption.PREEMPT`, `emergency_stop()`/`cancel()` or the action timeout cuts into one, always through the owner's `on_preempted()` safe-stop.
4. execute() on any ActionNode must always return a Result — never raise
5. evaluate() on any InstinctNode must return a Proposal or None (None when not applicable) — never raise
6. All node I/O must be async — wrap blocking calls in asyncio.to_thread()
7. node_ids are unique per InstinctMasterNode across normal and reflex instincts

Concurrency obligations (ADR 0005):
- Declare `resources` on every ActionNode that commands an actuator. Exclusivity is only enforced for declared resources.
- Action code must be cancellation-safe. Preemption, `emergency_stop()`, shutdown and the action timeout arrive as `CancelledError` at an `await`.
- `on_preempted()` holds the actuators safe and does not undo work. It must finish within `safe_stop_timeout_s`.
- Never assume an action finished when `tick()` returns. Read `ctx.last_results` on a later tick, or `await wait_idle()`.

## Priority convention

| Range | Use |
|-------|-----|
| 200+  | Reflex instincts only (BaseReflexInstinctNode) |
| 100-199 | Normal — safety / survival |
| 50-99   | Normal — goal-directed |
| 1-49    | Normal — exploratory / maintenance |
| 0       | Reserved (inactive) |

## File map

```
arachnite/
  __init__.py       public API — import everything from here
  models.py         all dataclasses and enums (Signal.confidence rejects NaN/Inf)
  bus.py            SignalBus (transport bridge: start/stop_transport, add_remote_listener, is_remote)
  context.py        ContextNode (state persistence, StateUpdateSignal, max_state_keys eviction)
  runtime.py        ArachniteRuntime (tick loop, event-driven reflex lane, wait_idle, live reg/unreg, shutdown)
  builder.py        RuntimeBuilder (fluent construction API)
  supervisor.py     NodeSupervisor (cancel_restart_tasks(), restart_task_count property)
  health.py         HealthMonitor
  shutdown.py       ShutdownCoordinator
  logging.py        StructuredLogger, sinks
  codec.py          SignalCodec (network_safe attr), CodecRegistry (check_network_safety binds;
                    register() then refuses unsafe codecs; decode_network)
  config.py         NodeConfig
  media.py          MediaStore (on-disk storage for large signal payloads; kind/source validated against [a-zA-Z0-9_][a-zA-Z0-9_.\-]*, extension against '.name' segments, raises PathTraversalError; exclusive create, no overwrite)
  framework_config.py  FrameworkConfig (runtime, transport, logging settings)
  llm_provider.py   LLMProvider, Anthropic/Ollama/Local, ThreadSafeProvider, SharedModelRegistry
  web.py            SignalDashboard, FileLogSink
  exceptions.py     all framework exceptions (incl. UnsafeCodecError, PathTraversalError)
  safety_monitor.py runtime safety monitors and SafetyMonitorRegistry
  testing.py      make_signal, make_proposal, make_result, make_context, MockBus
  nodes/
    base.py         BaseNode ABC
    sense.py        BaseSenseNode (push), SenseMasterNode (get_node)
    instinct.py     BaseInstinctNode, BaseReflexInstinctNode (preemption), InstinctMasterNode (get_node)
    decision.py     BaseDecisionNode (decide_many delegates to decide), DecisionMasterNode (park / hand-off), built-in strategies
    action.py       BaseActionNode (resources, on_preempted), MultiStepActionNode, ActionMasterNode
                    (launch / launch_reflex / wait_idle, LaunchStatus, LaunchOutcome, get_node)
    llm.py          LLMInstinctNode (asyncio.Lock guards _cached_proposal)
    active_inference.py  ActiveInferenceDecisionNode
  transport/
    base.py         BaseTransport ABC (StructuredLogger for connect/disconnect events)
    local.py        LocalTransport (default, in-process)
    mqtt.py         MQTTTransport (calls check_network_safety on connect)
    nats.py         NATSTransport (calls check_network_safety on connect)
    redis.py        RedisTransport (calls check_network_safety on connect)
  distributed/
    agent_node.py   AgentNode (remote signals -> runtime.inject_remote_signal + mesh health)
    manifest.py     DeploymentManifest (validated on load; NodeAssignment.node_id = class node_id)
    mesh.py         MeshRuntime (shared LocalTransport for local agents; clean partial start)
    colocation.py   reflex co-location validator
    permissions.py  permission validation helpers
examples/
  minimal_agent.py          simplest complete pipeline
  temperature_monitor.py    realistic: reflex, multi-step action, disjoint resources (fan / heater)
  web_dashboard_demo.py     adds SignalDashboard to temperature_monitor
  robot_arm/                pick-and-place: resources, PREEMPT reflex + safe-stop, recovery, manifest
tests/
  conftest.py       shared fixtures — good reference implementations
```
