# Adapter contract: how adapters present external systems to DS rules

The contract an **adapter** signs when bridging an external system
into DS's fact model: what a rule author needs to know, and what any
adapter (HomeKit, Zigbee2MQTT, Matter, a custom REST adapter) must
honour to slot into the language without special-casing.

## What this is not

- Not a list of which specific adapters exist or what they each
  offer. Per-adapter content (schema catalogues, provider APIs,
  broker semantics) stays with each adapter doc.
- Not a wire-protocol spec. Wire formats, handshake mechanics,
  back-pressure policies belong with the runtime hosting each
  adapter; some relevant cross-tier bits live in
  [LFAC].
- Not a replacement for [LFAC] or
  [LEXP]. Those own the broader fact
  and expression surface. This doc is the narrower contract an
  adapter signs when bridging external systems into that surface.
- Not a blueprint for building an adapter. Adapter authors read
  this to know what DS expects; they build the rest per their
  own doc.

---

(LADP-1)=
## Terminology: adapter vs storage adapter [LADP.1]

(LADP-1-1)=
[LADP.1.1] The two words name different things — the test is whether DS
can run properly without it.

(LADP-1-2)=
- [LADP.1.2] **Storage adapter.** The one external process whose absence
  breaks DS itself. It provides runtime-essential services that
  cannot live inside the engine (durable storage, cross-restart
  state, long-term sample retention), across three planes:
  events, samples, cache. Nothing else is in this category; it
  is deliberately narrow.

(LADP-1-3)=
- [LADP.1.3] **Adapter.** Integrator code that bridges an external
  system's data model into DS's fact model **or** provides a
  compute/service role DS calls into. Adapters ship a `.ds`
  library file declaring their services and related schemas
  (consumed by the compiler per [LIMP]), and a
  binary that registers per-service callbacks against libds's C
  API at engine init ([LADP.8.1]). What is external is the
  system being bridged, not the adapter: there is no wire
  between an adapter and the engine. Typical adapters: Home
  Assistant bridge, MQTT bridge, weather-provider bridge, notify
  service, ML worker, tool server, another DS tier via
  cross-tier fact flow. DS runs properly with zero adapters —
  they are how rules touch the world, not how the engine itself
  stays up.

*see also:* [LADP.8.1](#LADP-8-1)

(LADP-1-4)=
[LADP.1.4] This doc concerns adapters only. Storage-adapter contracts live in
the storage-plane docs; they are not schema-contract-shaped.

---

(LADP-2)=
## Three schema-derivation modes [LADP.2]

(LADP-2-1)=
[LADP.2.1] The fundamental axis along which adapters differ: how the
schemas the adapter presents to DS come into being. Three modes
currently in use, each with a distinct author-visible contract.

(LADP-2-1-1)=
[LADP.2.1.1] Adapter-published schemas representing observed
state must declare `scope ambient` per [LSCP.2.5]. The compiler
rejects rule-side `emit` and `retract` actions targeting ambient
schemas, preventing rules from spoofing adapter-observed facts.
Rules wanting to trigger downstream effects emit a
non-ambient request schema (e.g. `LightRequest`) and let the
adapter respond.

*see also:* [LSCP.2.5](#LSCP-2-5)

(LADP-2-2)=
### Discovery-driven [LADP.2.2]

(LADP-2-2-1)=
[LADP.2.2.1] The adapter introspects the external system at connect, builds
schemas from what it finds, and extends them as the external
system changes.

(LADP-2-2-2)=
- [LADP.2.2.2] **Example:** a Home Assistant bridge that queries HA's state
  API at connect, emits one schema per observed entity domain
  (`Sensor`, `Light`, `BinarySensor`, …) with slots derived from
  observed attributes.

(LADP-2-2-3)=
- [LADP.2.2.3] **Schema evolution:** none while an engine runs. The engine
  refuses a schema registration once it has emitted its first stream event
  ([NFCT.1.1]), so the adapter's schemas are the ones it derived at connect. An
  attribute that first appears after that has no slot: the adapter must leave
  it out of the facts it asserts, and it reaches rules only through a schema
  that declares it, registered when an engine is next set up.

*see also:* [NFCT.1.1](#NFCT-1-1)

(LADP-2-2-4)=
- [LADP.2.2.4] **Entity registry:** adapter publishes the set of currently-
  known entity IDs for compile-time lint (warnings, not errors —
  entities can appear after compile time).

(LADP-2-2-5)=
- [LADP.2.2.5] **Typing:** each slot gets a concrete type — `String`,
  `Int`, `Float`, `Bool`, or `Json`. Where attributes vary
  in type across entities of the same domain, the adapter
  either stringifies, emits multiple narrow schemas, or
  falls back to `Json`. See [LADP.4].

*see also:* [LADP.4](#LADP-4)

(LADP-2-3)=
### Author-declared [LADP.2.3]

(LADP-2-3-1)=
[LADP.2.3.1] The external system has no discovery API or an unbounded
namespace. Site config declares which parts of the external
surface the adapter should subscribe to / ingest, and the
adapter generates schemas from the declarations.

(LADP-2-3-2)=
- [LADP.2.3.2] **Example:** an MQTT broker bridge where site config declares
  topic patterns, payload codecs, and extracted topic-variable
  bindings; the adapter subscribes to declared patterns only
  and generates one schema per declaration.

(LADP-2-3-3)=
- [LADP.2.3.3] **Schema evolution:** a new declared pattern requires a
  config change and an adapter restart.

(LADP-2-3-4)=
- [LADP.2.3.4] **Undeclared traffic:** undeclared traffic is ignored (or optionally
  surfaced via firehose-mode envelope facts — off by default).

(LADP-2-3-5)=
- [LADP.2.3.5] **Typing:** fully declared at config time.

(LADP-2-4)=
### Fixed [LADP.2.4]

(LADP-2-4-1)=
[LADP.2.4.1] Schemas are part of the adapter's implementation, hard-coded at
build time. Site config specifies which instances of the fixed
domain to fetch / track, but not what slots those instances
carry.

(LADP-2-4-2)=
- [LADP.2.4.2] **Example:** a weather-provider bridge where schemas
  (`WeatherCurrent`, `WeatherForecast`, `AirQuality`, `SunPhase`,
  `MoonPhase`) are part of the adapter. Site config declares
  which locations to fetch for; a `location` slot discriminates.

(LADP-2-4-3)=
- [LADP.2.4.3] **Schema evolution:** adapter version bumps only.

(LADP-2-4-4)=
- [LADP.2.4.4] **Authoritative surface:** the fixed schema.

(LADP-2-4-5)=
- [LADP.2.4.5] **Typing:** fully declared.

(LADP-2-5)=
### Mode selection is not user-visible [LADP.2.5]

(LADP-2-5-1)=
[LADP.2.5.1] Rule authors don't write "this is a discovery-driven adapter" in
their code. The mode is a property of how the adapter was built.
What authors see:

| Adapter mode | What the author writes |
|---|---|
| Discovery-driven | `Sensor t where t.entity_id == "sensor.kitchen_temp"`, `Sensor m where m.entity_id ~ /_motion$/` |
| Author-declared | `SensorTemp t where t.topic == "sensors/kitchen/temp"`, `SensorTemp t where t.topic ~ /…/` |
| Fixed | `WeatherCurrent w where w.location == "home"` |

(LADP-2-5-2)=
[LADP.2.5.2] **All three modes share one author shape** — name the schema, filter
its identity slot in `where` ([LADP.3.1]). The identity slot (`entity_id` / `topic`, [LADP.4]) is an ordinary slot
matched by `==` or a regex. The three forms coexist in the same rule; see
[LADP.9].

---

*see also:* [LADP.3.1](#LADP-3-1), [LADP.4](#LADP-4), [LADP.9](#LADP-9)

(LADP-3)=
## Adapter-entity matching [LADP.3]

(LADP-3-1)=
### Match by identity slot [LADP.3.1]

(LADP-3-1-1)=
[LADP.3.1.1] **An adapter entity is matched by its identity slot.** Name the
adapter's schema and constrain its **identity slot** (`entity_id` for flat-key
adapters, `topic` for segmented-key adapters — [LADP.4]) in the pattern's `where`
clause: `==` for an exact id, a regex (`~`, [LREG.2.1]) for a set.
The pattern grammar and the lexer treat an adapter's schema as any other
([LGRA.8], [LLEX.10.7]).

*ratified*  —  *see also:* [LADP.4](#LADP-4), [LGRA.8](#LGRA-8), [LLEX.10.7](#LLEX-10-7), [LREG.2.1](#LREG-2-1)

(LADP-3-1-2)=
[LADP.3.1.2] The schema (`Sensor`, `BinarySensor`, …) is the adapter's own type,
referenced bare when imported (`from ha import Sensor`) or library-qualified
(`ha.Sensor`) once `import ha` is in scope ([LGRA.22.4]).

*see also:* [LGRA.22.4](#LGRA-22-4)

(LADP-3-2)=
### Per-adapter key shape [LADP.3.2]

(LADP-3-2-1)=
[LADP.3.2.1] A flat `entity_id` (HA) and a `/`-segmented `topic` (MQTT) are both
ordinary `String` slots; the author writes the regex that fits the key — `[^.]*`
within an entity_id, `[^/]+` for one MQTT segment. An adapter registers no
wildcard recipe, so key-shape knowledge stays in the rule that needs it.

*ratified*

(LADP-3-3)=
### No glob sugar [LADP.3.3]

(LADP-3-3-1)=
[LADP.3.3.1] Dropping the sugar costs verbosity, not capability. Authors write
the identity-slot regex directly ([LADP.3.1]).

*see also:* [LADP.3.1](#LADP-3-1)

(LADP-3-4)=
### Multi-match activation [LADP.3.4]

(LADP-3-4-1)=
[LADP.3.4.1] For a regex-constrained pattern, the Rete engine fires one activation
per matching fact — the natural all-match semantic. A rule with
`Sensor t where t.entity_id ~ /_temp$/ and t.state > 75` activates independently
for each `Sensor` fact whose `entity_id` matches and whose state is
above 75. Bindings scope to each activation.

---

(LADP-4)=
## Common-slot contract [LADP.4]

(LADP-4-1)=
[LADP.4.1] Every adapter-emitted schema carries a minimum slot set. The
intent is twofold: (a) rule authors have a predictable surface
(`ts`, `dwell`, at least one discriminator), and (b) engine
concerns like meaningful-change filtering and logical-fact
stability can rely on consistent timestamp handling.

(LADP-4-2)=
### Required on every adapter schema [LADP.4.2]

(LADP-4-2-1)=
[LADP.4.2.1] Required slot on every adapter schema:

| Slot | Type | Purpose |
|---|---|---|
| `ts` | `Time` | The UTC instant at which the source observed the fact, supplied by the adapter ([LFAC.9.2]): source time, compared with `now()` by rules that need it. Load-bearing for series and `then` ordering; `t.dwell` and `within <dur>` do not read it ([LTIM.2.8.6]). |

*see also:* [LFAC.9.2](#LFAC-9-2), [LTIM.2.8.6](#LTIM-2-8-6)

(LADP-4-3)=
### Required when the adapter is discovery-driven [LADP.4.3]

(LADP-4-3-1)=
[LADP.4.3.1] Required slots when the adapter is discovery-driven:

| Slot | Type | Purpose |
|---|---|---|
| `entity_id` | STRING | The external system's entity identifier. Authors match it directly in `where` (`entity_id == …` / `~ /…/`, [LADP.3.1]). |
| `state` | concrete type | The entity's primary state. The adapter picks a concrete type (`String`, `Int`, `Float`, `Bool`, or `Json`) per schema when it declares the schema; the choice is fixed in the declaration and carried in the artefact (RARC.9.4.2), never negotiated at connect time. When attributes vary across entities of the same domain, the adapter either stringifies (`state: String`), emits multiple narrow schemas per observed type, or — last resort — declares `state: Json`. See [LADP.5]. |
| `last_changed` | FLOAT | Epoch when state last meaningfully changed, in source time. Usually equals `ts`; preserved across attribute-only updates, so `now()` minus `last_changed` is the time in the current state. `dwell` measures time since the fact last entered working memory instead ([LTIM.2.8.6]), which an attribute-only update resets. |
| `context_id` | STRING | Causality chain identifier from the external system. See [LADP.10]. |
| `friendly_name` | STRING | Human-readable label for operator logs. |

*see also:* [LTIM.2.8.6](#LTIM-2-8-6), [LADP.10](#LADP-10), [LADP.3.1](#LADP-3-1), [LADP.5](#LADP-5), [RARC.9.4.2](#RARC-9-4-2)

(LADP-4-4)=
### Required when the adapter is author-declared [LADP.4.4]

(LADP-4-4-1)=
[LADP.4.4.1] Required slots when the adapter is author-declared:

| Slot | Type | Purpose |
|---|---|---|
| `topic` (or per-adapter equivalent key) | STRING | The external system's identifier for this fact. Authors match it directly in `where` ([LADP.3.1]). |
| `retained` | BOOL | Whether this fact came from the source system's retention mechanism (MQTT retained message, etc.) vs a live publish. See [LADP.8]. |

*see also:* [LADP.3.1](#LADP-3-1), [LADP.8](#LADP-8)

(LADP-4-4-2)=
[LADP.4.4.2] For MQTT specifically, `qos` is also common; that's adapter-
specific and declared in the schema generated from the topic
declaration.

(LADP-4-5)=
### Fixed adapters [LADP.4.5]

(LADP-4-5-1)=
[LADP.4.5.1] The fixed-adapter schemas declare whatever discriminator makes
sense for their domain. `WeatherCurrent` uses `location`;
`MoonPhase` has no discriminator because it's effectively a
singleton. The `ts` requirement still applies.

(LADP-4-7)=
### Meaningful-change discipline [LADP.4.7]

(LADP-4-7-1)=
[LADP.4.7.1] An adapter **may** suppress a no-op reassertion at the source,
to make fewer calls into the engine. The engine's suppression is the
correctness contract ([LFAC.2.5.1]), so an adapter that passes every update
through conforms ([LFAC.2.5.2]).

*see also:* [LFAC.2.5.1](#LFAC-2-5-1), [LFAC.2.5.2](#LFAC-2-5-2)

(LADP-4-7-4)=
[LADP.4.7.4] An adapter that carries `last_changed` ([LADP.4.3.1]) **must**
keep its value across an attribute-only update, one that changes another slot
and leaves `state` unchanged, so `now()` minus `last_changed` is the time in
the current state.

*see also:* [LADP.4.3.1](#LADP-4-3-1)

(LADP-4-8)=
### Identity markers on generated `logical` schemas [LADP.4.8]

(LADP-4-8-1)=
[LADP.4.8.1] A `logical` schema an adapter generates carries
`key` / `mutable` markers on every slot like any other
`logical` schema (require-all, [LFAC.1.7.4]). The identity
slot — `entity_id` for discovery-driven
adapters ([LADP.4.3.1]), `topic` or the per-adapter equivalent
key for author-declared adapters ([LADP.4.4.1]) — must be among
the `key` slots: it is the external identifier, which is the
fact's identity.

*see also:* [LADP.4.3.1](#LADP-4-3-1), [LADP.4.4.1](#LADP-4-4-1), [LFAC.1.7.4](#LFAC-1-7-4)

(LADP-4-8-2)=
[LADP.4.8.2] Unless the contract declares otherwise, an adapter
marks the identity slot `key` and every other generated
slot `mutable`. This satisfies require-all for the generated
schema and reproduces the intended one-live-fact-per-external-
identifier behaviour.

(LADP-4-8-3)=
[LADP.4.8.3] `entity_id` retains its role as the discovery-driven
external-identifier slot ([LADP.4.3.1]) — required by name — but
has no identity-resolver privilege: identity is read from the
`key` markers ([LFAC.1.7.5]), not from the slot name.

*see also:* [LADP.4.3.1](#LADP-4-3-1), [LFAC.1.7.5](#LFAC-1-7-5)

(LADP-4-8-4)=
[LADP.4.8.4] A generated `scope logical ambient` schema follows the
generated-schema rule ([LADP.4.8.1] / [LADP.4.8.2]) unchanged — the
base is `logical`, so the adapter marks the identity slot `key`
and the rest `mutable`; the `ambient` modifier adds only the read-only
boundary ([LSCP.2.5.1]).

---

*see also:* [LADP.4.8.1](#LADP-4-8-1), [LADP.4.8.2](#LADP-4-8-2), [LSCP.2.5.1](#LSCP-2-5-1)

(LADP-5)=
## Handling multi-typed attributes [LADP.5]

(LADP-5-1)=
[LADP.5.1] Discovery-driven adapters often encounter attributes whose
runtime type varies across entities of the same domain. Home
Assistant's `state` attribute is the canonical case —
numeric on `sensor.temp`, string on `light.foo`, boolean-ish
string (`"on"`/`"off"`) on `binary_sensor.door`. A Matter
adapter sees similar variation across device clusters; a
Zigbee adapter sees it across device attributes.

(LADP-5-2)=
[LADP.5.2] **Every slot on every schema commits to one concrete type at
declaration**, and nothing later revises it ([RARC.9.4.2]). `Any` is not a type
name, so the compiler refuses a slot declared `Any` as it refuses any
type that does not resolve ([LGRA.5.7.1]). Adapters have
three strategies, picked per slot, in order of
preference:

*ratified*  —  *see also:* [LGRA.5.7.1](#LGRA-5-7-1), [RARC.9.4.2](#RARC-9-4-2)

(LADP-5-3)=
### 1. Stringify [LADP.5.3]

(LADP-5-3-1)=
[LADP.5.3.1] Declare the slot `String` and serialise whatever the source
system produced to its string form. `72.1` → `"72.1"`,
`true` → `"true"`, `"on"` → `"on"`. Rules that need numeric
access use `parse_float` / `parse_int` / `parse_bool`
explicitly (or upstream rules that parse and emit a narrower
schema).

(LADP-5-3-2)=
- [LADP.5.3.2] *Pro:* one schema, one type per slot, consistent across
  all entities. Simplest for adapters and authors alike.

(LADP-5-3-3)=
- [LADP.5.3.3] *Con:* authors opt into parsing at every use-site.

(LADP-5-3-4)=
[LADP.5.3.4] Preferred when the type variation is wide or unpredictable
and rule authors rarely need type-specific operations on the
slot.

(LADP-5-4)=
### 2. Multiple narrow schemas [LADP.5.4]

(LADP-5-4-1)=
[LADP.5.4.1] Emit a distinct schema per observed type — `HaNumericState`,
`HaStringState`, `HaBooleanState` — and route each entity to
the schema matching its observed type as the adapter emits.
Rules match the schema they care about.

(LADP-5-4-2)=
- [LADP.5.4.2] *Pro:* each schema is narrowly typed; numeric-valued
  entities support `t.state > 30` natively; no author-side
  parsing.

(LADP-5-4-3)=
- [LADP.5.4.3] *Con:* tripled (or more) schema surface area; rules that
  want "any state from any HA entity" must match all
  schemas.

(LADP-5-4-4)=
[LADP.5.4.4] Preferred when the type variation is bounded (2–3 observed
types) and authors frequently use type-specific operations.

(LADP-5-5)=
### 3. `Json` fallback [LADP.5.5]

(LADP-5-5-1)=
[LADP.5.5.1] Declare the slot `Json`. The adapter passes the value
through as a JSON-serialised blob; rules access via path
operators. Leaves are runtime-typed per the JSON decoder's
output.

(LADP-5-5-2)=
- [LADP.5.5.2] *Pro:* structural flexibility — nested objects and arrays
  pass through cleanly.

(LADP-5-5-3)=
- [LADP.5.5.3] *Con:* reintroduces runtime type surprises at the leaf,
  scoped to the Json slot. Author raises a `TypeError` on
  `m.body.foo > 30` if `foo` is not a number at runtime.

(LADP-5-5-4)=
[LADP.5.5.4] Preferred when the attribute carries genuinely structured
data (not just type-variant scalars) — webhook payloads,
MQTT JSON messages, arbitrary metadata blobs.

(LADP-5-6)=
### Runtime type mismatches [LADP.5.6]

(LADP-5-6-1)=
[LADP.5.6.1] If an entity reports a value that doesn't fit the adapter's
declared slot type (numeric entity shows up on a slot
declared `String`), the adapter has two choices — neither is
automatic widening:

(LADP-5-6-2)=
- [LADP.5.6.2] **Log and drop / coerce.** Adapter converts to declared
  type (lossy if wrong) or refuses to emit. Metric
  increments; operators see the mismatch.

(LADP-5-6-3)=
- [LADP.5.6.3] **Adapter author updates the schema.** If the mismatch is
  persistent (many entities, often), the adapter author
  changes the declared type at the adapter layer — switches
  the slot to `String` or `Json` and redeploys. This is a
  deliberate ops-level decision, not a runtime automatic.

(LADP-5-6-4)=
[LADP.5.6.4] A slot's type **must not** widen automatically: widening would
silently change which rules matched, a correctness-affecting change that
must not happen without operator intent.

(LADP-5-7)=
### Author-facing consequence [LADP.5.7]

(LADP-5-7-1)=
[LADP.5.7.1] Rules compile against concrete types. `t.state > 30` on a
`state: String` slot is a compile error (type mismatch) —
the author must write `parse_float(t.state) > 30` or match
against the numeric-typed schema if the adapter emits
multiple narrow schemas.

(LADP-5-7-2)=
[LADP.5.7.2] Only `Json`-typed slots have runtime type variation at the
leaf, and that variation is scoped: `m.body.foo > 30` raises a
`TypeError` at runtime if the leaf is a string, but `m.state > 30` on a
`String`-typed slot is caught at compile time.

(LADP-5-8)=
### Cross-adapter relevance [LADP.5.8]

(LADP-5-8-1)=
[LADP.5.8.1] The three-strategy pattern applies to any discovery-driven
adapter with multi-typed attribute surfaces (HA, Matter,
Zigbee, HomeKit, generic webhook payloads). Author-declared
adapters commit to types in config and skip the question;
fixed adapters hard-code types.

---

(LADP-6)=
## Lifecycle events [LADP.6]

(LADP-6-1)=
[LADP.6.1] Every adapter surfaces entity/topic lifecycle via the same
authoring patterns.

(LADP-6-2)=
### State changes [LADP.6.2]

(LADP-6-2-1)=
[LADP.6.2.1] Handled implicitly via retract-and-reassert. Rules pattern-match
on the current state as usual.

(LADP-6-3)=
### Becomes unavailable / unknown [LADP.6.3]

(LADP-6-3-1)=
[LADP.6.3.1] When the external system reports an entity as unavailable
(HA's `unavailable` / `unknown` states; MQTT device going
offline via LWT), the adapter **asserts `state = "unavailable"`
rather than retracting**. Rules that want to react match on
the value directly.

(LADP-6-3-2)=
[LADP.6.3.2] This preserves the invariant that every entity has a live fact;
authors don't have to guard for "is there a fact at all." Dwell
works across availability transitions.

(LADP-6-4)=
### Entity deletion (discovery-driven) [LADP.6.4]

(LADP-6-4-1)=
[LADP.6.4.1] When an entity is removed from the external system, the adapter
retracts its fact **without re-asserting**. Rules keyed on that
entity stop firing.

(LADP-6-5)=
### Entity rename (discovery-driven) [LADP.6.5]

(LADP-6-5-1)=
[LADP.6.5.1] The adapter retracts the old-entity_id fact and asserts a new
fact with the new entity_id. Rule patterns referencing the old
name stop matching; the author resolves it.

(LADP-6-7)=
### Broker disconnect (author-declared) [LADP.6.7]

(LADP-6-7-1)=
[LADP.6.7.1] For adapters connected to external brokers (MQTT), a transient
broker disconnect reconnects automatically with backoff. On
reconnect, retained messages re-deliver; facts re-assert per
meaningful-change discipline (identical values don't reset
dwell).

(LADP-6-7-2)=
[LADP.6.7.2] Site-ds can observe the reconnect event via operator log entries;
rules do not match on connection state.

(LADP-6-8)=
### Lifecycle events worth matching on [LADP.6.8]

(LADP-6-8-1)=
[LADP.6.8.1] Lifecycle events worth matching on:

| Event | Author writes |
|---|---|
| Entity unavailable | `where s.state == "unavailable"` |
| Entity unknown | `where s.state == "unknown"` |
| Fresh (not just-learned) | `where not t.retained` (MQTT) — see [LADP.8] |
| No entity present | `no <Schema> <binding>` ([LGRA.8.1]) — but see [LADP.7.4.1] |

---

*see also:* [LADP.8](#LADP-8), [LGRA.8.1](#LGRA-8-1), [LADP.7.4.1](#LADP-7-4-1)

(LADP-7)=
## Live vs snapshot [LADP.7]

(LADP-7-1)=
[LADP.7.1] Two parallel mechanisms by which facts enter working memory
not-as-live-events. One carries a slot convention rules can match on;
the other does not, and that is a property of the mechanism rather
than a missing feature ([LADP.7.3.1]). Fact hydration, a third, is deferred
([LHYD.1]).

| Mechanism | Slot convention | Source |
|---|---|---|
| MQTT retained | `retained = true` | broker's "last payload" replay on new subscriber |
| Discovery burst | none | a discovery-driven adapter's one-per-entity burst at connect — indistinguishable from live ([LADP.7.3.1]) |

*see also:* [LADP.7.3.1](#LADP-7-3-1), [LHYD.1](#LHYD-1)

(LADP-7-2)=
### Authoring convention [LADP.7.2]

(LADP-7-2-1)=
- [LADP.7.2.1] Unconstrained pattern matches both live and snapshot.

(LADP-7-2-2)=
- [LADP.7.2.2] `where not t.retained` / `where t.corr == ""` filters
  to live only.

(LADP-7-2-3)=
- [LADP.7.2.3] `where t.retained` filters to snapshot only.

(LADP-7-3)=
### Discovery-burst seeds are indistinguishable from live [LADP.7.3]

(LADP-7-3-1)=
[LADP.7.3.1] A discovery-driven adapter's connect-time seed is
indistinguishable from live updates: no slot marks it, so an
unconstrained pattern matches both ([LADP.7.2.1]).

*see also:* [LADP.7.2.1](#LADP-7-2-1)

(LADP-7-4)=
### Negation and snapshot [LADP.7.4]

(LADP-7-4-1)=
[LADP.7.4.1] `not <pattern>` matches when no fact matches — regardless of
live-vs-snapshot. An MQTT retained fact therefore defeats a `not` written
about live state; constrain `retained` inside the negation when that matters.

---

(LADP-8)=
## Service-dispatch resolution [LADP.8]

(LADP-8-1)=
[LADP.8.1] Adapters that host services (`call light.turn_on`,
`call mqtt.publish`, `call weather.get_forecasts`) declare
those services in the adapter's `.ds` library file. Rule
files reference an adapter's services by `import`ing the
adapter library per [LIMP]. At runtime,
the integrator's adapter binary registers per-service
callbacks against libds's C API; the compiled DSC carries
the service set the engine binds against.

(LADP-8-2)=
### Dispatch table is built at compile time [LADP.8.2]

(LADP-8-2-1)=
[LADP.8.2.1] The compiler builds a service-dispatch table
from the `service` declarations of every library in the
compilation's import closure plus the rule file's own
declarations. Each entry maps a service name, the one global
name a call uses ([LGRA.10.1.6]), to its declaration
(kwarg shape and response schema reference). The table is emitted into the DSC alongside schema and
rule atoms; libds reads it at DSC load.

*ratified*  —  *see also:* [LGRA.10.1.6](#LGRA-10-1-6)

(LADP-8-2-2)=
[LADP.8.2.2] **Unique match.** When the rule writes
`call light.turn_on` and exactly one declaration in the
compilation's import closure declares `light.turn_on`, the
compiler resolves the call to that declaration, whatever form
imported the declaring library ([LGRA.10.1.6]).

*ratified*  —  *see also:* [LGRA.10.1.6](#LGRA-10-1-6)

(LADP-8-2-3)=
[LADP.8.2.3] **No match.** When the rule writes
`call light.turn_on` and nothing in the compilation's import
closure declares it, the compiler emits
`DS_VALIDATE_UNKNOWN_SERVICE` naming the service path and the
services the closure declares.

*ratified*

(LADP-8-3)=
### Adapter library identifier and service domains [LADP.8.3]

(LADP-8-3-1)=
[LADP.8.3.1] Each imported library has a single lowercase
identifier per [LIMP.1.2]. Service
declarations within a library use dotted names
(`light.turn_on`, `mqtt.publish`); the dotted form is the
service's own identity, and a call names it bare, with no
library qualifier ([LGRA.10.1.6]).

*see also:* [LGRA.10.1.6](#LGRA-10-1-6), [LIMP.1.2](#LIMP-1-2)

(LADP-8-3-2)=
[LADP.8.3.2] Two libraries may declare services that share a
top-level domain (both `hub-bridge.ds` and a second adapter
declaring services in the `light` domain), provided no two
declarations share a service name ([LCRS.14.9]). A domain is
part of each service's name, not a namespace a library owns.

*see also:* [LCRS.14.9](#LCRS-14-9)

(LADP-8-3-3)=
[LADP.8.3.3] Library-name collisions are caught at import
time per [LIMP.3.1.3] — two `.ds` files resolving
to the same library identifier are
`DS_VALIDATE_AMBIGUOUS_LIBRARY` errors. The runtime never
sees a collision because the DSC carries one resolved
mapping; integrator-build pipelines configure the search
path to disambiguate before compile.

*see also:* [LIMP.3.1.3](#LIMP-3-1-3)

(LADP-8-4)=
### Response schemas [LADP.8.4]

(LADP-8-4-1)=
[LADP.8.4.1] A service declaring `response T` names, in `T`, a `schema`
declared in the same library. The declaration's header carries the service's
dotted name (`<domain>.<method>`); the library identifier is implicit in the
file. `T` is a response schema and meets [LCRS.4.3.2]; a call's response is a
fact of `T` ([LCRS.4.3.1]), and rules read it as they read any fact
([LCRS.5.5]).

*see also:* [LCRS.4.3.1](#LCRS-4-3-1), [LCRS.4.3.2](#LCRS-4-3-2), [LCRS.5.5](#LCRS-5-5)

(LADP-8-4-2)=
[LADP.8.4.2] **Every service declares its response** ([LGRA.23.1]), as one of:

| Declaration | A successful call | A failed call |
|---|---|---|
| `response T` | the adapter asserts one fact of `T` ([LCRS.4.3.1]) | a `CallError` ([LCRS.4.2.1]) |
| `no response` | nothing is asserted | a `CallError` |

A declaration with neither is a compile error
(`DS_VALIDATE_SERVICE_NO_RESPONSE_DECL`, [LGRA.23.2]): there is no untyped
response. A call to a `no response` service is [LCRS.17].

*ratified*  —  *see also:* [LCRS.17](#LCRS-17), [LCRS.4.2.1](#LCRS-4-2-1), [LCRS.4.3.1](#LCRS-4-3-1), [LGRA.23.1](#LGRA-23-1), [LGRA.23.2](#LGRA-23-2)

(LADP-8-4-3)=
[LADP.8.4.3] Response schemas use the same DS schema
grammar as any other schema. They can be re-exported
through `from B import HALightResponse` per [LIMP.4.4] if a higher-level library composes on top.

---

*ratified*  —  *see also:* [LIMP.4.4](#LIMP-4-4)

(LADP-8-5)=
### Kwarg modifiers [LADP.8.5]

(LADP-8-5-1)=
[LADP.8.5.1] A service declaration's kwarg modifiers ([LGRA.23.1]) constrain
every `call` to that service:

| Modifier | The compiler must |
|---|---|
| `required` | reject a call that omits the kwarg (`DS_VALIDATE_MISSING_KWARG`) |
| `literal` | reject a call that supplies the kwarg as anything but a literal ([LGRA.10.7], `DS_VALIDATE_DYNAMIC_IDENT_KWARG`) |
| `default <literal>` | lower a call that omits the kwarg exactly as if it supplied the literal, so the service receives it; such a kwarg is never missing |

A kwarg with none of the three is optional and may be computed. The modifiers
travel in the artefact's service manifest (`proto/service_def.proto#ServiceKwarg`).

*ratified*  —  *defined in:* [proto/service_def.proto#ServiceKwarg](#proto-service_def-proto-ServiceKwarg)  —  *see also:* [LGRA.10.7](#LGRA-10-7), [LGRA.23.1](#LGRA-23-1)

(LADP-8-5-2)=
[LADP.8.5.2] **A kwarg's declared type decides the number the service
receives.** A service sees a plain number, so the declaration is the contract.
The compiler must lower a quantity supplied by a kwarg's `default`
([LADP.8.5.1]), and a quantity written at the `call` on a kwarg whose declared
type is not a unit symbol, as follows:

| Declared type | The service receives |
|---|---|
| a unit symbol | the quantity expressed in that unit |
| a dimension or scalar-group name ([LUNI.7.1]) | the quantity in the dimension's base unit |
| `Float` or `Int` | the quantity in its dimension's base unit and storage type ([LUNI.7.2]) |

The compiler must reject a written quantity whose dimension is not the
kwarg's, on a unit-typed or dimension-typed kwarg (`DS_VALIDATE_DIM_MISMATCH`,
[LUNI.8.2]), unless exactly one `implicit` formula bridges the two dimensions,
which the compiler then applies ([LUNI.4.5.1]). A `default` of another
dimension is refused at the declaration ([LGRA.23.2]).

A written number with no unit, on a unit-typed or dimension-typed kwarg, is
taken as already in the kwarg's unit, or in the base unit for a dimension, as a
`let` annotation takes one ([LUNI.8.6]). The service receives it unchanged.

*ratified*  —  *see also:* [LADP.8.5.1](#LADP-8-5-1), [LGRA.23.2](#LGRA-23-2), [LUNI.4.5.1](#LUNI-4-5-1), [LUNI.7.1](#LUNI-7-1), [LUNI.7.2](#LUNI-7-2), [LUNI.8.2](#LUNI-8-2), [LUNI.8.6](#LUNI-8-6)

(LADP-8-5-3)=
[LADP.8.5.3] **A quantity written at the `call` on a unit-typed kwarg is
converted to the kwarg's unit.** The compiler must lower it so that the service
receives the quantity expressed in the kwarg's unit ([LADP.8.5.2]), never the
base-unit value a quantity is stored as ([LUNI.4.3]). This holds for every
quantity of the kwarg's dimension: a unit literal, a read of a unit-typed slot,
and any other expression of that dimension.

A value known at compile time is converted there, as the kwarg's `default` is.
Any other value is converted when the call is evaluated, by the unit's
conversion from the base unit, with the constants the compiler bakes
([LUNI.2.7.1]).

Where the kwarg's dimension declares `storage int64` ([LUNI.7.2]), the converted
quantity must be a whole number of the kwarg's unit. It is never truncated or
rounded:

- the compiler must refuse a value known at compile time that is not whole
  (`DS_VALIDATE_KWARG_QUANTITY_NOT_WHOLE`), as it refuses such a `default`
  ([LGRA.23.2]): `90_s` on a `min` kwarg is refused, and `120_s` is `2`;
- for a value that is not whole when the call is evaluated, the engine must
  raise a `ComputationError` of kind `NOT_REPRESENTABLE` ([LERR.1.4]) and must
  not issue the call.

*ratified*  —  *see also:* [LADP.8.5.2](#LADP-8-5-2), [LERR.1.4](#LERR-1-4), [LGRA.23.2](#LGRA-23-2), [LUNI.2.7.1](#LUNI-2-7-1), [LUNI.4.3](#LUNI-4-3), [LUNI.7.2](#LUNI-7-2)

(LADP-8-6)=
### Fact kwargs [LADP.8.6]

(LADP-8-6-1)=
[LADP.8.6.1] A kwarg declared with a schema, or with the kind `Schema`
([LGRA.23.2]), takes a **fact**: its argument must be a pattern binding, so
the fact is one working memory holds. A kwarg declared with a schema takes a
binding of that schema; one declared `Schema` takes a binding of any schema.
Any other argument is a compile error (`DS_VALIDATE_FACT_KWARG_NOT_BINDING`).
No form constructs a schema value inline: a fact that working memory never held
has no meaning.

The call carries the fact as a `FactExternal` ([RFCS.23]), so the adapter
receives the fact's value and none of the engine's state.

*ratified*  —  *see also:* [LGRA.23.2](#LGRA-23-2), [RFCS.23](#RFCS-23)

(LADP-9)=
## Cross-adapter composition [LADP.9]

(LADP-9-1)=
[LADP.9.1] A rule can pattern-match facts from multiple adapters — that's
the point of having one DS surface over many external systems.
Every pattern is `schema where …`, and each schema is owned by one
adapter, so nothing special is needed at the rule-author level.

(LADP-9-2)=
[LADP.9.2] Three adapters in one rule — a weather-provider bridge (fixed:
`SunPhase`, `WeatherForecast`), a Home Assistant bridge
(discovery-driven: `Sensor` matched on `entity_id`), and a `light.turn_on`
call routed through the same HA bridge. The rule doesn't know
which adapter owns which pattern; each schema is owned by one adapter and
the compiler's service-dispatch table routes the call.

(LADP-9-3)=
### Cross-adapter constraints and joins [LADP.9.3]

(LADP-9-3-1)=
[LADP.9.3.1] Ordinary `where` joins work across adapters.

(LADP-9-3-2)=
[LADP.9.3.2] No special composition rule. Adapters connected to the same
tier emit into the same working memory; their facts coexist
and can be joined freely.

---

(LADP-10)=
## Causality and `context_id` [LADP.10]

(LADP-10-1)=
[LADP.10.1] Discovery-driven adapters that receive causality chains from the
external system (HA's `context_id`) surface them on a standard
slot, documented here as a convention rather than a grammar
feature.

(LADP-10-2)=
### Uses in rules [LADP.10.2]

(LADP-10-2-1)=
- [LADP.10.2.1] **Debug logging.** Actions log the context_id they reacted to
  and the one they produced (if the adapter supports an
  out-context header on call requests), so causal chains trace.

(LADP-10-2-2)=
- [LADP.10.2.2] **Avoiding own-action feedback.** A rule that fires
  `call light.turn_on entity_id: ...` will see the resulting state
  change arrive as a fact, and usually should not react to it.
  Telling that fact apart from a genuine external change means
  comparing its `context_id` against the context the rule's own call
  produced.

  **DS cannot supply the second value.** A rule may compare
  `l.context_id` against anything it can name, but nothing in the
  language records the context id an outgoing `call` caused. That
  exists only if the adapter reports it back, which [LADP.10.2.1]
  treats as optional. So in v1 the pattern is open only to
  integrations whose adapter surfaces both directions — the inbound
  `context_id` and the context its own calls produce — and the test
  is then an ordinary comparison against a slot the adapter fills.
  Where an adapter does not, v1 offers no way to distinguish the two,
  and the rule has to be shaped so that reacting to its own effect is
  harmless.

*see also:* [LADP.10.2.1](#LADP-10-2-1)

(LADP-10-3)=
### Adapter support [LADP.10.3]

(LADP-10-3-1)=
- [LADP.10.3.1] **Discovery-driven adapters** that receive causality chains
  should surface `context_id` as a required common slot.

(LADP-10-3-2)=
- [LADP.10.3.2] **Author-declared adapters** (MQTT) have no equivalent; the
  slot is absent.

(LADP-10-3-3)=
- [LADP.10.3.3] **Fixed adapters** (Weather) have no causality; the slot is
  absent.

---

(LADP-8-5-4)=
[LADP.8.5.4] **A kwarg declared with a builtin type takes a value of that
type.** Each argument reaches the service as the kind its value has
([NCBK.6.10]), so the declaration is a contract only if the value matches it.
On a kwarg whose declared type is a builtin type ([LGRA.22.8]), the compiler
must refuse, with `DS_VALIDATE_TYPE_MISMATCH`, a value written at the `call`
whose leaf kind ([LUNI.8.7.3]) is not the declared type's:

- an `Int` given to a `String` kwarg is refused, and so is a `Json` value;
- an `Int` given to a `Float` kwarg is refused, not promoted, as at an `emit`
  slot ([LEXP.7.3b]).

The author writes the cast ([LCST.4.1]). A quantity given to an `Int` or
`Float` kwarg is not refused here: [LADP.8.5.2] converts it. A kwarg declared
with a unit, a dimension or a schema follows [LADP.8.5.2], [LADP.8.5.3] and
[LADP.8.6.1].

*ratified*  —  *see also:* [LADP.8.5.2](#LADP-8-5-2), [LADP.8.5.3](#LADP-8-5-3), [LADP.8.6.1](#LADP-8-6-1), [LCST.4.1](#LCST-4-1), [LEXP.7.3b](#LEXP-7-3b), [LGRA.22.8](#LGRA-22-8), [LUNI.8.7.3](#LUNI-8-7-3), [NCBK.6.10](#NCBK-6-10)

