Просмотр исходного кода

feat(host): add algorithm-facing HTH facade and simulation kit

Co-authored-by: Cursor <cursoragent@cursor.com>
root 3 месяцев назад
Родитель
Сommit
9538acf4aa
34 измененных файлов с 1691 добавлено и 119 удалено
  1. 5 0
      docs/advanced/README.md
  2. 25 0
      docs/simple/ALGORITHM_API.md
  3. 35 0
      docs/simple/README_10_MINUTES.md
  4. 7 0
      reviews/algorithm-01-external-simplicity.md
  5. 8 0
      reviews/algorithm-02-facade-honesty.md
  6. 4 0
      reviews/algorithm-03-internal-automation.md
  7. 7 0
      reviews/algorithm-04-mock-replay.md
  8. 6 0
      reviews/algorithm-05-packages.md
  9. 64 0
      sdk/python/examples/algorithm_quickstart.ipynb
  10. 1 1
      sdk/python/examples/capture.py
  11. 6 0
      sdk/python/examples/closed_loop_demo.py
  12. 2 2
      sdk/python/examples/control_mock.py
  13. 2 2
      sdk/python/examples/observe.py
  14. 18 0
      sdk/python/examples/offline_replay_demo.py
  15. 22 0
      sdk/python/examples/policy_template.py
  16. 11 0
      sdk/python/examples/quickstart.py
  17. 2 2
      sdk/python/examples/snapshot.py
  18. 6 86
      sdk/python/hth_sdk/__init__.py
  19. 73 0
      sdk/python/hth_sdk/advanced.py
  20. 19 1
      sdk/python/hth_sdk/exceptions.py
  21. 9 1
      sdk/python/hth_sdk/mock.py
  22. 220 0
      sdk/python/hth_sdk/replay.py
  23. 11 0
      sdk/python/hth_sdk/sim/__init__.py
  24. 62 0
      sdk/python/hth_sdk/sim/scenarios.py
  25. 89 0
      sdk/python/hth_sdk/sim/thermal.py
  26. 593 0
      sdk/python/hth_sdk/simple.py
  27. 9 6
      sdk/python/pyproject.toml
  28. 180 0
      sdk/python/tests/test_facade.py
  29. 6 12
      sdk/python/tests/test_import.py
  30. 1 1
      sdk/python/tests/test_mock_client.py
  31. 30 2
      tools/evaluate_gates.py
  32. 98 0
      tools/package_hth_algorithm_kit.py
  33. 9 3
      tools/rtl_uart_cosim/run_hthd_pty_rtl.py
  34. 51 0
      tools/run_algorithm_gates.sh

+ 5 - 0
docs/advanced/README.md

@@ -0,0 +1,5 @@
+# Advanced host SDK
+
+Maintainer surface: `from hth_sdk.advanced import HthClient, ControlLease, ActionBatch`.
+
+See `host/docs/python-sdk-guide.zh-CN.md`. Directors should use `docs/simple/` instead.

+ 25 - 0
docs/simple/ALGORITHM_API.md

@@ -0,0 +1,25 @@
+# 算法 API
+
+## 对象
+
+- `HTH`:同步连接。`mock()` / `replay()` / `connect()`
+- `State`:温度、百分比、`ready`、`fresh`、`faults`、`control`
+- `Control`:`fans` `heaters` `doors`(门 0=全开)
+- `Result`:`ok` `sent` `message` `warning`
+- `HTHError`:`code` `message` `recoverable`
+
+`state.meta` 和 `result.meta` 是内部细节,正常算法不要用。
+
+## 方法
+
+`read()` `watch()` `set()` `safe()` `resume()` `close()`
+
+`set()` 不会自动退出安全模式。安全后必须 `resume(control)`。
+
+`ok` 表示本机守护进程接受并完成了主机侧动作。`sent` 表示完整控制帧已派发。当前没有设备确认。
+
+## Mock 场景
+
+`normal` `coupled_4chamber` `sensor_invalid` `sensor_stale` `startup_delay` `disconnect_recover` `safe_mode` `actuator_clamp` `slow_consumer`
+
+热模型只用于接口测试,不是真实高温罩辨识结果。

+ 35 - 0
docs/simple/README_10_MINUTES.md

@@ -0,0 +1,35 @@
+# 10 分钟上手
+
+本包给算法人员用。不要阅读串口、gRPC 或设备协议文档。
+
+```text
+SIMULATION ONLY
+NOT IDENTIFIED FROM REAL HARDWARE
+NOT A PHYSICAL VALIDATION MODEL
+```
+
+## 安装
+
+```bash
+python -m venv venv
+venv\Scripts\pip install hth_sdk-*-py3-none-any.whl
+python quickstart.py
+```
+
+Linux / macOS 把 `venv\Scripts\pip` 换成 `venv/bin/pip`。
+
+## 你只需要这些对象
+
+`HTH` `State` `Control` `Result` `HTHError`
+
+## 三种连接
+
+```python
+HTH.mock()
+HTH.replay("sample_replay/sample.jsonl")
+HTH.connect()   # 仅在本机已有守护进程时使用
+```
+
+其余控制循环代码保持不变。
+
+当前范围不包括真实加热器、风扇或风门。

+ 7 - 0
reviews/algorithm-01-external-simplicity.md

@@ -0,0 +1,7 @@
+# Review 1 — 对外简洁性
+
+- 顶层 `__all__` 只有 `HTH State Control Result HTHError`。
+- Quick Start 不出现 lease / epoch / command id / gRPC。
+- 算法人员使用百分比,不使用 actuator ID。
+- 同步 API,调用方不写 asyncio。
+- 错误统一为 `HTHError(code, message, recoverable)`。

+ 8 - 0
reviews/algorithm-02-facade-honesty.md

@@ -0,0 +1,8 @@
+# Review 2 — Facade 真实性
+
+- `ready` 来自 lifecycle / 安全模式,不编造。
+- `fresh` 来自时间窗与 data_gap;`sensor_stale` 强制不新鲜。
+- 无效温度为 `None`,并带布尔掩码。
+- `control` 是主机已知命令目标,不是实际反馈。
+- `Result.ok` 只表示主机侧接受;`sent` 表示完整帧已派发。不把 UNCONFIRMED 推给总监主路径。
+- `set()` 不会偷偷退出 Safe。

+ 4 - 0
reviews/algorithm-03-internal-automation.md

@@ -0,0 +1,4 @@
+# Review 3 — 自动内部机制
+
+Facade 在 `set()` / `safe()` / `resume()` 中自动完成连接检查、Ready/Fresh、Lease 获取与续租、Command ID、TTL、Snapshot Seq、Control Revision、完整 ActionBatch、Latest-Wins/Epoch 后重新取租、关闭时释放。
+后台独立事件循环线程,`close()` 停止线程。

+ 7 - 0
reviews/algorithm-04-mock-replay.md

@@ -0,0 +1,7 @@
+# Review 4 — Mock / Replay / 仿真
+
+- 九个场景可按 seed 复现。
+- 热模型标明 SIMULATION ONLY,不是物理孪生。
+- Replay 只读,`set()` 返回 `READ_ONLY`。
+- Notebook 由测试执行代码单元。
+- RTL 单独成 `rtl_cosim_acceptance`,失败不挡住算法包。

+ 6 - 0
reviews/algorithm-05-packages.md

@@ -0,0 +1,6 @@
+# Review 5 — 算法包与工程包
+
+- 算法包根目录 `hth-algorithm-kit/`,无 Go / proto / RTL / 审查长文。
+- 解压后 `pip install` wheel 并运行 `quickstart.py`。
+- SHA 与 attestation 在 ZIP 外。
+- Hardware validation: NOT RUN,范围为本轮之外,不编码成 FAIL。

+ 64 - 0
sdk/python/examples/algorithm_quickstart.ipynb

@@ -0,0 +1,64 @@
+{
+  "cells": [
+    {
+      "cell_type": "markdown",
+      "metadata": {},
+      "source": [
+        "# Algorithm quickstart\n",
+        "\n",
+        "SIMULATION ONLY. NOT IDENTIFIED FROM REAL HARDWARE. NOT A PHYSICAL VALIDATION MODEL."
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "from hth_sdk import HTH, Control\n",
+        "\n",
+        "hth = HTH.mock(scenario=\"normal\", seed=1, speed=20)\n",
+        "state = hth.read()\n",
+        "temps = [t for t in state.temperatures_c if t is not None]\n",
+        "print(len(state.temperatures_c), max(temps))"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "curve = []\n",
+        "for st in hth.watch(period=0.02, count=5):\n",
+        "    r = hth.set(Control(fans=[20]*4, heaters=[20]*4, doors={\"x\":0,\"y\":0,\"z\":0}))\n",
+        "    curve.append(max(t for t in st.temperatures_c if t is not None))\n",
+        "    assert r.ok\n",
+        "print(curve)"
+      ]
+    },
+    {
+      "cell_type": "code",
+      "execution_count": null,
+      "metadata": {},
+      "outputs": [],
+      "source": [
+        "hth.close()\n",
+        "with HTH.mock(scenario=\"coupled_4chamber\", seed=1, speed=20) as other:\n",
+        "    print(other.read().ready)"
+      ]
+    }
+  ],
+  "metadata": {
+    "kernelspec": {
+      "display_name": "Python 3",
+      "language": "python",
+      "name": "python3"
+    },
+    "language_info": {
+      "name": "python"
+    }
+  },
+  "nbformat": 4,
+  "nbformat_minor": 5
+}

+ 1 - 1
sdk/python/examples/capture.py

@@ -15,7 +15,7 @@ from pathlib import Path
 
 
 async def _collect_mock(count: int) -> tuple[list[dict], dict]:
-    from hth_sdk import API_VERSION, MockClient
+    from hth_sdk.advanced import API_VERSION, MockClient
 
     records = []
     async with MockClient() as client:

+ 6 - 0
sdk/python/examples/closed_loop_demo.py

@@ -0,0 +1,6 @@
+from hth_sdk import HTH
+from policy_template import run
+
+if __name__ == "__main__":
+    with HTH.mock(scenario="normal", seed=1, speed=30) as hth:
+        run(hth, steps=6)

+ 2 - 2
sdk/python/examples/control_mock.py

@@ -17,7 +17,7 @@ import asyncio
 import sys
 from datetime import timedelta
 
-from hth_sdk import MockClient
+from hth_sdk.advanced import MockClient
 from hth_sdk.exceptions import ActionRejected, HthError
 
 
@@ -40,7 +40,7 @@ async def _run_mock() -> int:
 
 
 async def _run_real(observe: str, control: str) -> int:
-    from hth_sdk import connect_control
+    from hth_sdk.advanced import connect_control
 
     async with await connect_control(observe=observe, control=control) as client:
         devices = await client.list_devices()

+ 2 - 2
sdk/python/examples/observe.py

@@ -12,7 +12,7 @@ import sys
 
 
 async def _run_mock(count: int) -> None:
-    from hth_sdk import MockClient
+    from hth_sdk.advanced import MockClient
 
     async with MockClient() as client:
         devices = await client.list_devices()
@@ -31,7 +31,7 @@ async def _run_mock(count: int) -> None:
 
 
 async def _run_socket(socket: str, count: int) -> None:
-    from hth_sdk import connect_observe
+    from hth_sdk.advanced import connect_observe
 
     async with await connect_observe(socket) as client:
         devices = await client.list_devices()

+ 18 - 0
sdk/python/examples/offline_replay_demo.py

@@ -0,0 +1,18 @@
+from pathlib import Path
+
+from hth_sdk import HTH
+from hth_sdk.replay import write_sample_replay
+
+
+def main() -> None:
+    path = Path(__file__).resolve().parent.parent / "hth_sdk" / "data" / "sample_replay.jsonl"
+    if not path.is_file():
+        write_sample_replay(path)
+    with HTH.replay(path) as hth:
+        state = hth.read()
+        print("replay temps", [t for t in state.temperatures_c if t is not None][:4])
+        print("ready", state.ready, "fresh", state.fresh)
+
+
+if __name__ == "__main__":
+    main()

+ 22 - 0
sdk/python/examples/policy_template.py

@@ -0,0 +1,22 @@
+"""Minimal closed-loop policy. Change only the first line to switch backends."""
+
+from hth_sdk import Control, HTH
+
+
+def decide(state):
+    valid = [t for t in state.temperatures_c if t is not None]
+    heat = 25 if valid and max(valid) < 45 else 0
+    return Control(fans=[20] * 4, heaters=[heat] * 4, doors={"x": 0, "y": 0, "z": 0})
+
+
+def run(hth: HTH, steps: int = 8) -> None:
+    for state in hth.watch(period=0.05, count=steps):
+        if not state.ready or not state.fresh:
+            continue
+        result = hth.set(decide(state))
+        print(state.time, result.ok, state.temperatures_c[0])
+
+
+if __name__ == "__main__":
+    with HTH.mock(scenario="coupled_4chamber", seed=1, speed=20) as hth:
+        run(hth)

+ 11 - 0
sdk/python/examples/quickstart.py

@@ -0,0 +1,11 @@
+from hth_sdk import HTH, Control
+
+with HTH.mock() as hth:
+    for state in hth.watch(period=0.05, count=3):
+        action = Control(
+            fans=[20] * 4,
+            heaters=[30] * 4,
+            doors={"x": 0, "y": 0, "z": 0},
+        )
+        result = hth.set(action)
+        print(max(t for t in state.temperatures_c if t is not None), result.ok)

+ 2 - 2
sdk/python/examples/snapshot.py

@@ -65,13 +65,13 @@ async def main() -> int:
     p.add_argument("--socket", default="", help="empty = in-process mock")
     args = p.parse_args()
     if args.socket:
-        from hth_sdk import connect_observe
+        from hth_sdk.advanced import connect_observe
 
         async with await connect_observe(args.socket) as client:
             devices = await client.list_devices()
             snap = await client.get_snapshot(devices[0].device_id)
     else:
-        from hth_sdk import MockClient
+        from hth_sdk.advanced import MockClient
 
         async with MockClient() as client:
             devices = await client.list_devices()

+ 6 - 86
sdk/python/hth_sdk/__init__.py

@@ -1,92 +1,12 @@
-"""hth-sdk — Python client for the hth Linux userspace hood API.
+"""hth-sdk — algorithm-facing hood API.
 
-Public surface is async (`grpc.aio`) plus an in-process MockClient.
-This package does not open serial ports and does not implement models.
+Default public surface is the synchronous facade. Platform details live in
+`hth_sdk.advanced`.
 """
 
 from __future__ import annotations
 
-from hth_sdk.batch import ActionBatchBuilder
-from hth_sdk.client import HthClient, connect, connect_control, connect_observe
-from hth_sdk.constants import (
-    API_VERSION,
-    DEFAULT_CONTROL_SOCKET,
-    DEFAULT_OBSERVE_SOCKET,
-)
-from hth_sdk.exceptions import (
-    ActionRejected,
-    ApiVersionMismatch,
-    ConfirmationNotProven,
-    DataGap,
-    DeviceEpochChanged,
-    HthError,
-    InvalidResumePoint,
-    LeaseError,
-    LeaseExpired,
-    LeaseMismatch,
-    StubsNotGenerated,
-    TransportError,
-)
-from hth_sdk.lease import ControlLease
-from hth_sdk.mock import MockClient
-from hth_sdk.types import (
-    ActionBatch,
-    ActionRecord,
-    ActionResult,
-    ActionResultEvent,
-    Capabilities,
-    DeliveryGap,
-    DeviceInfo,
-    Event,
-    FaultEvent,
-    FieldAudit,
-    HeartbeatEvent,
-    Measurement,
-    SafetyModeEvent,
-    Snapshot,
-    SnapshotEvent,
-    TelemetryEvent,
-)
+from hth_sdk.simple import Control, HTH, HTHError, Result, State
 
-__all__ = [
-    "API_VERSION",
-    "DEFAULT_CONTROL_SOCKET",
-    "DEFAULT_OBSERVE_SOCKET",
-    "ActionBatch",
-    "ActionBatchBuilder",
-    "ActionRejected",
-    "ActionResult",
-    "ApiVersionMismatch",
-    "Capabilities",
-    "ConfirmationNotProven",
-    "ControlLease",
-    "DataGap",
-    "DeviceEpochChanged",
-    "DeviceInfo",
-    "HthClient",
-    "HthError",
-    "SnapshotEvent",
-    "SafetyModeEvent",
-    "InvalidResumePoint",
-    "HeartbeatEvent",
-    "FieldAudit",
-    "FaultEvent",
-    "Event",
-    "DeliveryGap",
-    "ActionResultEvent",
-    "ActionRecord",
-    "LeaseError",
-    "LeaseExpired",
-    "LeaseMismatch",
-    "Measurement",
-    "MockClient",
-    "Snapshot",
-    "StubsNotGenerated",
-    "TelemetryEvent",
-    "TransportError",
-    "connect",
-    "connect_control",
-    "connect_observe",
-]
-
-__version__ = "0.1.0"
+__all__ = ["HTH", "State", "Control", "Result", "HTHError"]
+__version__ = "0.2.0"

+ 73 - 0
sdk/python/hth_sdk/advanced.py

@@ -0,0 +1,73 @@
+"""Maintainer / advanced SDK surface.
+
+Algorithm code should import from `hth_sdk` only.
+"""
+
+from hth_sdk.batch import ActionBatchBuilder
+from hth_sdk.client import HthClient, connect, connect_control, connect_observe
+from hth_sdk.constants import API_VERSION, DEFAULT_CONTROL_SOCKET, DEFAULT_OBSERVE_SOCKET
+from hth_sdk.exceptions import (
+    ActionRejected,
+    ApiVersionMismatch,
+    ConfirmationNotProven,
+    DataGap,
+    DeviceEpochChanged,
+    HthError,
+    InvalidResumePoint,
+    LeaseError,
+    LeaseExpired,
+    LeaseMismatch,
+    StubsNotGenerated,
+    TransportError,
+)
+from hth_sdk.lease import ControlLease
+from hth_sdk.mock import MockClient
+from hth_sdk.replay import ReplayClient
+from hth_sdk.types import (
+    ActionBatch,
+    ActionRecord,
+    ActionResult,
+    Capabilities,
+    DeliveryGap,
+    DeviceInfo,
+    Event,
+    Measurement,
+    Snapshot,
+    TelemetryEvent,
+)
+
+__all__ = [
+    "API_VERSION",
+    "DEFAULT_CONTROL_SOCKET",
+    "DEFAULT_OBSERVE_SOCKET",
+    "ActionBatch",
+    "ActionBatchBuilder",
+    "ActionRecord",
+    "ActionRejected",
+    "ActionResult",
+    "ApiVersionMismatch",
+    "Capabilities",
+    "ConfirmationNotProven",
+    "ControlLease",
+    "DataGap",
+    "DeliveryGap",
+    "DeviceEpochChanged",
+    "DeviceInfo",
+    "Event",
+    "HthClient",
+    "HthError",
+    "InvalidResumePoint",
+    "LeaseError",
+    "LeaseExpired",
+    "LeaseMismatch",
+    "Measurement",
+    "MockClient",
+    "ReplayClient",
+    "Snapshot",
+    "StubsNotGenerated",
+    "TelemetryEvent",
+    "TransportError",
+    "connect",
+    "connect_control",
+    "connect_observe",
+]

+ 19 - 1
sdk/python/hth_sdk/exceptions.py

@@ -6,7 +6,25 @@ from typing import Any
 
 
 class HthError(Exception):
-    """Base class for all SDK errors."""
+    """Base class for all SDK errors.
+
+    Algorithm-facing code should catch this type only. Subclasses stay in
+    `hth_sdk.advanced` for maintainers.
+    """
+
+    def __init__(self, *args: object, code: str = "", recoverable: bool = False, **_: object) -> None:
+        super().__init__(*args)
+        self.code = code or type(self).__name__
+        self.recoverable = bool(recoverable)
+        self._msg = str(self) if args else ""
+
+    @property
+    def message(self) -> str:
+        return self._msg or str(self)
+
+    @message.setter
+    def message(self, value: str) -> None:
+        self._msg = value
 
 
 class StubsNotGenerated(HthError):

+ 9 - 1
sdk/python/hth_sdk/mock.py

@@ -242,6 +242,9 @@ class MockClient:
         self._command_cache: dict[str, ActionResult] = {}
         self._ticker: Optional[asyncio.Task] = None
         self._tick_period = 0.05
+        self._on_tick = None
+        self._ready_after = 0.0
+        self.seed = 1
         self.has_observe = True
         self.has_control = True
 
@@ -341,8 +344,12 @@ class MockClient:
         try:
             while True:
                 await asyncio.sleep(self._tick_period)
+                if self._on_tick is not None:
+                    self._on_tick(self)
                 if not self._waiters:
-                    return
+                    if self._on_tick is None:
+                        return
+                    continue
                 self._publish()
         except asyncio.CancelledError:
             return
@@ -626,6 +633,7 @@ class MockClient:
             wall_time=_utcnow(),
             monotonic_ns=self._event,
             lifecycle=self._lifecycle,
+            safety_control_mode="SAFE" if self._lifecycle == "SAFE" else "NORMAL",
             measurements=tuple(measurements),
             continuous_targets=targets,
             last_requested=None,

+ 220 - 0
sdk/python/hth_sdk/replay.py

@@ -0,0 +1,220 @@
+"""Read-only replay client with the same async surface as MockClient."""
+
+from __future__ import annotations
+
+import json
+from collections.abc import AsyncIterator
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from typing import Any, Optional
+
+from hth_sdk.exceptions import ActionRejected, HthError, InvalidResumePoint
+from hth_sdk.lease import ControlLease
+from hth_sdk.mock import default_capabilities
+from hth_sdk.profiles.prod2u import TEMPERATURE_IDS
+from hth_sdk.types import (
+    ActionBatch,
+    ActionResult,
+    Capabilities,
+    CommandedActuator,
+    DeviceInfo,
+    Event,
+    Measurement,
+    Snapshot,
+    SnapshotEvent,
+    TelemetryEvent,
+)
+
+
+def _utcnow() -> datetime:
+    return datetime.now(timezone.utc)
+
+
+class ReplayClient:
+    """Plays recorded snapshots. set()/safe()/resume() are READ_ONLY."""
+
+    def __init__(self, snapshots: list[Snapshot], *, device_id: str = "hood.0") -> None:
+        if not snapshots:
+            raise HthError("replay has no snapshots", code="EMPTY", recoverable=False)
+        self.device_id = device_id
+        self._snaps = list(snapshots)
+        self._i = 0
+        self.has_observe = True
+        self.has_control = False
+
+    @classmethod
+    def from_jsonl(cls, path: str | Path, *, device_id: str = "hood.0") -> "ReplayClient":
+        snaps = []
+        for line in Path(path).read_text(encoding="utf-8").splitlines():
+            line = line.strip()
+            if not line:
+                continue
+            snaps.append(snapshot_from_simple(json.loads(line), device_id=device_id))
+        return cls(snaps, device_id=device_id)
+
+    async def close(self) -> None:
+        return None
+
+    async def __aenter__(self) -> "ReplayClient":
+        return self
+
+    async def __aexit__(self, *exc: object) -> None:
+        await self.close()
+
+    def _require(self, device_id: str) -> None:
+        if device_id and device_id != self.device_id:
+            raise ActionRejected("UNKNOWN_ID", device_id)
+
+    async def list_devices(self) -> list[DeviceInfo]:
+        s = self._snaps[self._i]
+        return [
+            DeviceInfo(
+                device_id=self.device_id,
+                display_name="replay",
+                profile_id="replay",
+                profile_revision="1",
+                protocol_contract_hash="replay",
+                backend_kind="replay",
+                lifecycle=s.lifecycle,
+                device_epoch=s.device_epoch,
+            )
+        ]
+
+    async def get_capabilities(self, device_id: str) -> Capabilities:
+        self._require(device_id)
+        return default_capabilities(device_id)
+
+    async def get_snapshot(self, device_id: str) -> Snapshot:
+        self._require(device_id)
+        return self._snaps[min(self._i, len(self._snaps) - 1)]
+
+    async def get_faults(self, device_id: str, include_inactive: bool = False):
+        return []
+
+    async def subscribe_telemetry(
+        self, device_id: str, resume_after_event_id: int = 0
+    ) -> AsyncIterator[TelemetryEvent]:
+        self._require(device_id)
+        last = None
+        for snap in self._snaps:
+            if snap.event_id <= resume_after_event_id:
+                continue
+            ev = TelemetryEvent(snapshot=snap, previous_epoch=last)
+            last = snap.device_epoch
+            self._i = min(self._i + 1, len(self._snaps) - 1)
+            yield ev
+
+    async def subscribe_events(self, device_id: str, resume_after_event_id: int = 0):
+        self._require(device_id)
+        snap = await self.get_snapshot(device_id)
+        if resume_after_event_id > snap.event_id:
+            raise InvalidResumePoint(resume_after_event_id, snap.event_id)
+        yield SnapshotEvent(
+            event_id=snap.event_id,
+            kind="SNAPSHOT",
+            wall_time=snap.wall_time,
+            device_id=device_id,
+            snapshot=snap,
+        )
+
+    async def acquire_lease(self, *args: Any, **kwargs: Any) -> ControlLease:
+        raise HthError("replay is read-only", code="READ_ONLY", recoverable=False)
+
+    async def renew_lease(self, *args: Any, **kwargs: Any):
+        raise HthError("replay is read-only", code="READ_ONLY", recoverable=False)
+
+    async def release_lease(self, *args: Any, **kwargs: Any) -> None:
+        return None
+
+    async def validate(self, batch: ActionBatch) -> ActionResult:
+        raise HthError("replay is read-only", code="READ_ONLY", recoverable=False)
+
+    async def apply(self, batch: ActionBatch) -> ActionResult:
+        raise HthError("replay is read-only", code="READ_ONLY", recoverable=False)
+
+    async def enter_safe_mode(self, *args: Any, **kwargs: Any) -> ActionResult:
+        raise HthError("replay is read-only", code="READ_ONLY", recoverable=False)
+
+    async def resume_from_safe(self, *args: Any, **kwargs: Any) -> ActionResult:
+        raise HthError("replay is read-only", code="READ_ONLY", recoverable=False)
+
+
+def snapshot_from_simple(row: dict[str, Any], *, device_id: str) -> Snapshot:
+    temps = row.get("temperatures_c") or []
+    measurements = []
+    for i, sid in enumerate(TEMPERATURE_IDS):
+        raw = temps[i] if i < len(temps) else None
+        measurements.append(
+            Measurement(
+                id=sid,
+                value=None if raw is None else float(raw),
+                unit="degC",
+                quality="INVALID" if raw is None else "VALID",
+                host_time=_utcnow(),
+            )
+        )
+    fans = row.get("fans_percent") or [10, 10, 10, 10]
+    heaters = row.get("heaters_percent") or [0, 0, 0, 0]
+    doors = row.get("doors_close_percent") or {"x": 0, "y": 0, "z": 0}
+    targets = []
+    for i, v in enumerate(fans, start=1):
+        targets.append(CommandedActuator(id=f"fan.chamber.{i}", commanded_target=float(v)))
+    for i, v in enumerate(heaters, start=1):
+        targets.append(CommandedActuator(id=f"ptc.chamber.{i}", commanded_target=float(v)))
+    for axis in ("x", "y", "z"):
+        targets.append(
+            CommandedActuator(id=f"door.{axis}.close_percent", commanded_target=float(doors.get(axis, 0)))
+        )
+    wall = row.get("time")
+    wt = _utcnow()
+    if isinstance(wall, str):
+        try:
+            wt = datetime.fromisoformat(wall.replace("Z", "+00:00"))
+        except ValueError:
+            wt = _utcnow()
+    return Snapshot(
+        device_id=device_id,
+        daemon_instance_id="replay",
+        device_epoch=int(row.get("device_epoch") or 1),
+        snapshot_seq=int(row.get("snapshot_seq") or 1),
+        control_revision=int(row.get("control_revision") or 0),
+        event_id=int(row.get("event_id") or 1),
+        wall_time=wt,
+        monotonic_ns=int(row.get("event_id") or 1),
+        lifecycle=str(row.get("lifecycle") or "READY"),
+        measurements=tuple(measurements),
+        continuous_targets=tuple(targets),
+        last_requested=None,
+        last_accepted=None,
+        last_dispatched=None,
+        device_confirmation="UNCONFIRMED",
+        active_faults=(),
+        lease=None,
+        dropped_telemetry_count=0,
+        data_gap=bool(row.get("data_gap") or False),
+    )
+
+
+def write_sample_replay(path: Path, *, n: int = 8, seed: int = 1) -> Path:
+    path.parent.mkdir(parents=True, exist_ok=True)
+    lines = []
+    t0 = datetime(2026, 1, 1, tzinfo=timezone.utc)
+    for i in range(n):
+        temps = [25.0 + 0.1 * i + (ch % 4) * 0.05 for ch in range(27)]
+        if i % 3 == 2:
+            temps[26] = None
+        row = {
+            "time": (t0 + timedelta(seconds=i)).isoformat(),
+            "temperatures_c": temps,
+            "fans_percent": [20, 20, 20, 20],
+            "heaters_percent": [10, 10, 10, 10],
+            "doors_close_percent": {"x": 0, "y": 0, "z": 0},
+            "snapshot_seq": i + 1,
+            "event_id": i + 1,
+            "device_epoch": 1,
+            "control_revision": 1,
+            "lifecycle": "READY",
+        }
+        lines.append(json.dumps(row, separators=(",", ":")))
+    path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+    return path

+ 11 - 0
sdk/python/hth_sdk/sim/__init__.py

@@ -0,0 +1,11 @@
+"""Interface-test simulation helpers.
+
+SIMULATION ONLY
+NOT IDENTIFIED FROM REAL HARDWARE
+NOT A PHYSICAL VALIDATION MODEL
+"""
+
+from hth_sdk.sim.scenarios import SCENARIO_NAMES, ScenarioSpec, scenario_spec
+from hth_sdk.sim.thermal import ThermalModel
+
+__all__ = ["ThermalModel", "SCENARIO_NAMES", "ScenarioSpec", "scenario_spec"]

+ 62 - 0
sdk/python/hth_sdk/sim/scenarios.py

@@ -0,0 +1,62 @@
+"""Named Mock scenarios.
+
+SIMULATION ONLY
+NOT IDENTIFIED FROM REAL HARDWARE
+NOT A PHYSICAL VALIDATION MODEL
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+
+SCENARIO_NAMES = (
+    "normal",
+    "coupled_4chamber",
+    "sensor_invalid",
+    "sensor_stale",
+    "startup_delay",
+    "disconnect_recover",
+    "safe_mode",
+    "actuator_clamp",
+    "slow_consumer",
+)
+
+
+@dataclass(frozen=True)
+class ScenarioSpec:
+    name: str
+    coupling: float = 0.01
+    invalid_channels: tuple[int, ...] = (26,)
+    stale: bool = False
+    startup_delay_s: float = 0.0
+    disconnect_after_s: float = 0.0
+    recover_after_s: float = 0.0
+    start_safe: bool = False
+    clamp_heaters: float = 100.0
+    tick_s: float = 0.05
+    noise_c: float = 0.0
+    fresh_horizon_s: float = 3.0
+
+
+def scenario_spec(name: str) -> ScenarioSpec:
+    key = (name or "normal").strip().lower()
+    if key not in SCENARIO_NAMES:
+        raise ValueError(f"unknown scenario {name!r}; choose one of {SCENARIO_NAMES}")
+    if key == "coupled_4chamber":
+        return ScenarioSpec(name=key, coupling=0.06)
+    if key == "sensor_invalid":
+        return ScenarioSpec(name=key, invalid_channels=(3, 11, 26))
+    if key == "sensor_stale":
+        return ScenarioSpec(name=key, stale=True, fresh_horizon_s=0.0)
+    if key == "startup_delay":
+        return ScenarioSpec(name=key, startup_delay_s=0.4)
+    if key == "disconnect_recover":
+        return ScenarioSpec(name=key, disconnect_after_s=0.2, recover_after_s=0.5)
+    if key == "safe_mode":
+        return ScenarioSpec(name=key, start_safe=True)
+    if key == "actuator_clamp":
+        return ScenarioSpec(name=key, clamp_heaters=80.0)
+    if key == "slow_consumer":
+        return ScenarioSpec(name=key, tick_s=0.2)
+    return ScenarioSpec(name="normal")

+ 89 - 0
sdk/python/hth_sdk/sim/thermal.py

@@ -0,0 +1,89 @@
+"""Deterministic interface-test thermal model.
+
+SIMULATION ONLY
+NOT IDENTIFIED FROM REAL HARDWARE
+NOT A PHYSICAL VALIDATION MODEL
+
+The 27 channels are a convenience array, not a DIMM or chamber map.
+"""
+
+from __future__ import annotations
+
+import math
+import random
+from dataclasses import dataclass, field
+
+
+CHAMBERS = 4
+CHANNELS = 27
+
+
+@dataclass
+class ThermalModel:
+    """First-order 4-chamber coupled RC model for SDK/interface tests."""
+
+    seed: int = 1
+    ambient_c: float = 25.0
+    heat_gain: float = 0.08
+    fan_loss: float = 0.04
+    door_loss: float = 0.02
+    coupling: float = 0.01
+    inertia: float = 0.85
+    noise_c: float = 0.0
+    chamber_temps: list[float] = field(default_factory=lambda: [25.0] * CHAMBERS)
+
+    def __post_init__(self) -> None:
+        self._rng = random.Random(self.seed)
+        if len(self.chamber_temps) != CHAMBERS:
+            self.chamber_temps = [self.ambient_c] * CHAMBERS
+
+    def step(
+        self,
+        dt_s: float,
+        heaters: list[float],
+        fans: list[float],
+        doors: dict[str, float],
+    ) -> list[float | None]:
+        """Advance one step. Returns 27 channel values (None = invalid)."""
+        if dt_s <= 0:
+            return self.channels()
+        h = _pad4(heaters)
+        f = _pad4(fans)
+        door_open = 1.0 - (sum(float(doors.get(k, 0.0)) for k in ("x", "y", "z")) / 300.0)
+        nxt = list(self.chamber_temps)
+        for i in range(CHAMBERS):
+            heat = self.heat_gain * (h[i] / 100.0)
+            cool = self.fan_loss * (f[i] / 100.0) * (0.4 + 0.6 * door_open)
+            leak = self.door_loss * door_open
+            couple = 0.0
+            for j in range(CHAMBERS):
+                if i == j:
+                    continue
+                couple += self.coupling * (self.chamber_temps[j] - self.chamber_temps[i])
+            dT = heat - (cool + leak) * (self.chamber_temps[i] - self.ambient_c) + couple
+            nxt[i] = self.inertia * self.chamber_temps[i] + (1.0 - self.inertia) * (
+                self.chamber_temps[i] + dT * dt_s
+            )
+            if self.noise_c:
+                nxt[i] += self._rng.uniform(-self.noise_c, self.noise_c)
+            nxt[i] = max(-20.0, min(180.0, nxt[i]))
+        self.chamber_temps = nxt
+        return self.channels()
+
+    def channels(self) -> list[float | None]:
+        out: list[float | None] = []
+        for i in range(CHANNELS):
+            chamber = i % CHAMBERS
+            out.append(self.chamber_temps[chamber] + 0.05 * (i // CHAMBERS))
+        return out
+
+
+def _pad4(values: list[float]) -> list[float]:
+    xs = [float(v) for v in values[:CHAMBERS]]
+    while len(xs) < CHAMBERS:
+        xs.append(xs[-1] if xs else 0.0)
+    return xs
+
+
+def hash_seed(seed: int, name: str) -> int:
+    return (seed * 10007 + sum(ord(c) for c in name)) % 2_147_483_647

+ 593 - 0
sdk/python/hth_sdk/simple.py

@@ -0,0 +1,593 @@
+"""Synchronous algorithm-facing facade.
+
+Callers do not write asyncio, gRPC, lease, or actuator-id strings.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import threading
+import time
+import uuid
+from collections.abc import Iterator
+from dataclasses import dataclass, field
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+from typing import Any, Optional
+
+from hth_sdk.constants import DEFAULT_CONTROL_SOCKET, DEFAULT_OBSERVE_SOCKET
+from hth_sdk.exceptions import HthError, LeaseExpired, LeaseMismatch
+from hth_sdk.mock import MockClient
+from hth_sdk.profiles.prod2u import DOOR_IDS, FAN_IDS, PTC_IDS, TEMPERATURE_IDS
+from hth_sdk.replay import ReplayClient, write_sample_replay
+from hth_sdk.sim.scenarios import ScenarioSpec, scenario_spec
+from hth_sdk.sim.thermal import ThermalModel
+from hth_sdk.types import ActionResult, Snapshot
+
+
+def _utcnow() -> datetime:
+    return datetime.now(timezone.utc)
+
+
+class HTHError(HthError):
+    """Public exception alias. Catch this in algorithm code."""
+
+
+@dataclass(frozen=True)
+class Control:
+    fans: list[float]
+    heaters: list[float]
+    doors: dict[str, float]
+
+    @classmethod
+    def from_state(cls, state: "State") -> "Control":
+        return cls(
+            fans=list(state.fans_percent),
+            heaters=list(state.heaters_percent),
+            doors=dict(state.doors_close_percent),
+        )
+
+    def normalized(self) -> "Control":
+        fans = _four(self.fans, 10.0)
+        heaters = _four(self.heaters, 0.0)
+        doors = {
+            "x": _pct(self.doors.get("x", 0.0)),
+            "y": _pct(self.doors.get("y", 0.0)),
+            "z": _pct(self.doors.get("z", 0.0)),
+        }
+        return Control(fans=fans, heaters=heaters, doors=doors)
+
+
+@dataclass(frozen=True)
+class Result:
+    ok: bool
+    sent: bool
+    message: str = ""
+    warning: str = ""
+    meta: dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass(frozen=True)
+class State:
+    time: datetime
+    temperatures_c: list[float | None]
+    temperature_valid: list[bool]
+    fans_percent: list[float]
+    heaters_percent: list[float]
+    doors_close_percent: dict[str, float]
+    ready: bool
+    fresh: bool
+    faults: list[str]
+    control: Control
+    meta: dict[str, Any] = field(default_factory=dict)
+
+    def to_dict(self) -> dict[str, Any]:
+        return {
+            "time": self.time.isoformat(),
+            "temperatures_c": list(self.temperatures_c),
+            "temperature_valid": list(self.temperature_valid),
+            "fans_percent": list(self.fans_percent),
+            "heaters_percent": list(self.heaters_percent),
+            "doors_close_percent": dict(self.doors_close_percent),
+            "ready": self.ready,
+            "fresh": self.fresh,
+            "faults": list(self.faults),
+            "control": {
+                "fans": list(self.control.fans),
+                "heaters": list(self.control.heaters),
+                "doors": dict(self.control.doors),
+            },
+        }
+
+    def to_numpy(self):
+        try:
+            np = __import__("numpy")
+        except ImportError as exc:  # pragma: no cover
+            raise HTHError(
+                "numpy is optional; install it to use State.to_numpy()",
+                code="OPTIONAL_DEPENDENCY",
+                recoverable=True,
+            ) from exc
+        vals = [float("nan") if t is None else float(t) for t in self.temperatures_c]
+        return np.asarray(vals, dtype=float)
+
+
+class _Loop:
+    def __init__(self) -> None:
+        self.loop = asyncio.new_event_loop()
+        self.thread = threading.Thread(target=self._run, name="hth-facade-loop", daemon=True)
+        self._ready = threading.Event()
+        self.thread.start()
+        self._ready.wait(timeout=5)
+
+    def _run(self) -> None:
+        asyncio.set_event_loop(self.loop)
+        self._ready.set()
+        self.loop.run_forever()
+
+    def call(self, coro, timeout: float = 60.0):
+        if not self.thread.is_alive():
+            raise HTHError("background loop stopped", code="CLOSED", recoverable=False)
+        fut = asyncio.run_coroutine_threadsafe(coro, self.loop)
+        try:
+            return fut.result(timeout=timeout)
+        except HthError:
+            raise
+        except Exception as exc:
+            if isinstance(exc, HthError):
+                raise
+            raise HTHError(str(exc), code=type(exc).__name__, recoverable=False) from exc
+
+    def stop(self) -> None:
+        if self.loop.is_running():
+            self.loop.call_soon_threadsafe(self.loop.stop)
+        self.thread.join(timeout=3)
+        if not self.loop.is_closed():
+            self.loop.close()
+
+
+class HTH:
+    """Synchronous hood handle. Use mock(), replay(), or connect()."""
+
+    def __init__(
+        self,
+        backend: Any,
+        *,
+        kind: str,
+        device_id: str,
+        readonly: bool = False,
+        spec: Optional[ScenarioSpec] = None,
+        speed: float = 1.0,
+        mode: str = "real-time",
+        fresh_horizon_s: float = 3.0,
+    ) -> None:
+        self._backend = backend
+        self._kind = kind
+        self._device_id = device_id
+        self._readonly = readonly
+        self._spec = spec
+        self._speed = max(float(speed), 0.01)
+        self._mode = mode
+        self._fresh_horizon_s = fresh_horizon_s
+        self._loop = _Loop()
+        self._lease = None
+        self._caps = None
+        self._closed = False
+        self._sim: Optional[ThermalModel] = None
+        self._sim_t0 = time.monotonic()
+        self._last_sim = self._sim_t0
+        self._epoch_seen: Optional[int] = None
+        if spec is not None and kind == "mock":
+            self._sim = ThermalModel(seed=getattr(backend, "seed", 1), coupling=spec.coupling)
+            backend._tick_period = spec.tick_s / self._speed
+            if mode != "step":
+                backend._on_tick = self._on_mock_tick
+            if spec.start_safe:
+                backend._lifecycle = "SAFE"
+            if spec.startup_delay_s > 0:
+                backend._lifecycle = "PROBING"
+                backend._ready_after = time.monotonic() + spec.startup_delay_s / self._speed
+        self._call(self._prepare())
+
+    @classmethod
+    def mock(
+        cls,
+        scenario: str = "normal",
+        seed: int = 1,
+        speed: float = 1.0,
+        *,
+        device: str = "hood.0",
+        mode: str = "accelerated",
+    ) -> "HTH":
+        spec = scenario_spec(scenario)
+        client = MockClient(device_id=device)
+        client.seed = seed
+        return cls(
+            client,
+            kind="mock",
+            device_id=device,
+            spec=spec,
+            speed=speed,
+            mode=mode,
+            fresh_horizon_s=spec.fresh_horizon_s,
+        )
+
+    @classmethod
+    def replay(cls, path: str | Path | None = None, *, device: str = "hood.0") -> "HTH":
+        if path is None:
+            tmp = Path(__file__).resolve().parent / "data" / "sample_replay.jsonl"
+            if not tmp.is_file():
+                write_sample_replay(tmp)
+            path = tmp
+        client = ReplayClient.from_jsonl(path, device_id=device)
+        return cls(client, kind="replay", device_id=device, readonly=True, mode="step")
+
+    @classmethod
+    def connect(
+        cls,
+        device: int | str | None = None,
+        *,
+        device_id: str | None = None,
+        observe: str | None = None,
+        control: str | None = None,
+    ) -> "HTH":
+        from hth_sdk.client import connect
+
+        obs = observe or DEFAULT_OBSERVE_SOCKET
+        ctl = control or DEFAULT_CONTROL_SOCKET
+        loop = _Loop()
+        try:
+            client = loop.call(connect(observe=obs, control=ctl, role="control"))
+            devices = loop.call(client.list_devices())
+        except Exception:
+            loop.stop()
+            raise
+        chosen = _choose_device(devices, device=device, device_id=device_id)
+        hth = object.__new__(cls)
+        hth._backend = client
+        hth._kind = "connect"
+        hth._device_id = chosen
+        hth._readonly = False
+        hth._spec = None
+        hth._speed = 1.0
+        hth._mode = "real-time"
+        hth._fresh_horizon_s = 5.0
+        hth._loop = loop
+        hth._lease = None
+        hth._caps = None
+        hth._closed = False
+        hth._sim = None
+        hth._epoch_seen = None
+        hth._call(hth._prepare())
+        return hth
+
+    def __enter__(self) -> "HTH":
+        return self
+
+    def __exit__(self, *exc: object) -> None:
+        self.close()
+
+    def close(self) -> None:
+        if self._closed:
+            return
+        self._closed = True
+        try:
+            self._call(self._shutdown(), timeout=8.0)
+        except Exception:
+            pass
+        self._loop.stop()
+
+    def read(self) -> State:
+        self._ensure_open()
+        if self._sim is not None:
+            self._call(self._step_sim())
+        snap = self._call(self._backend.get_snapshot(self._device_id))
+        return self._state_from(snap)
+
+    async def _step_sim(self) -> None:
+        if self._sim is not None and isinstance(self._backend, MockClient):
+            self._on_mock_tick(self._backend)
+
+    def watch(self, period: float = 1.0, count: int | None = None) -> Iterator[State]:
+        self._ensure_open()
+        period = max(float(period), 0.02)
+        n = 0
+        while not self._closed:
+            yield self.read()
+            n += 1
+            if count is not None and n >= int(count):
+                return
+            time.sleep(period / self._speed if self._kind == "mock" else period)
+
+    def set(self, control: Control) -> Result:
+        self._ensure_open()
+        if self._readonly:
+            raise HTHError("replay is read-only", code="READ_ONLY", recoverable=False)
+        return self._call(self._set(control, resume=False))
+
+    def safe(self) -> Result:
+        self._ensure_open()
+        if self._readonly:
+            raise HTHError("replay is read-only", code="READ_ONLY", recoverable=False)
+        return self._call(self._safe())
+
+    def resume(self, control: Control) -> Result:
+        self._ensure_open()
+        if self._readonly:
+            raise HTHError("replay is read-only", code="READ_ONLY", recoverable=False)
+        return self._call(self._set(control, resume=True))
+
+    def _call(self, coro, timeout: float = 60.0):
+        try:
+            return self._loop.call(coro, timeout=timeout)
+        except HthError as exc:
+            raise HTHError(exc.message, code=getattr(exc, "code", type(exc).__name__), recoverable=getattr(exc, "recoverable", False)) from exc
+
+    def _ensure_open(self) -> None:
+        if self._closed:
+            raise HTHError("handle is closed", code="CLOSED", recoverable=False)
+
+    async def _prepare(self) -> None:
+        self._caps = await self._backend.get_capabilities(self._device_id)
+        ensure = getattr(self._backend, "_ensure_ticker", None)
+        if ensure is not None:
+            ensure()
+
+    async def _shutdown(self) -> None:
+        if self._lease is not None:
+            try:
+                await self._lease.release()
+            except Exception:
+                pass
+            self._lease = None
+        closer = getattr(self._backend, "close", None)
+        if closer is not None:
+            await closer()
+
+    async def _snapshot(self) -> Snapshot:
+        snap = await self._backend.get_snapshot(self._device_id)
+        if self._epoch_seen is None:
+            self._epoch_seen = snap.device_epoch
+        elif snap.device_epoch != self._epoch_seen:
+            self._lease = None
+            self._epoch_seen = snap.device_epoch
+            try:
+                await self._ensure_lease()
+            except Exception:
+                pass
+        return snap
+
+    def _state_from(self, snap: Snapshot) -> State:
+        temps: list[float | None] = []
+        valid: list[bool] = []
+        by_id = snap.measurements_by_id()
+        for sid in TEMPERATURE_IDS:
+            m = by_id.get(sid)
+            if m is None or m.value is None or m.quality not in {"VALID", "ESTIMATED"}:
+                temps.append(None)
+                valid.append(False)
+            else:
+                temps.append(float(m.value))
+                valid.append(True)
+        fans = [_target(snap, aid, 10.0) for aid in FAN_IDS]
+        heaters = [_target(snap, aid, 0.0) for aid in PTC_IDS]
+        doors = {
+            "x": _target(snap, "door.x.close_percent", 0.0),
+            "y": _target(snap, "door.y.close_percent", 0.0),
+            "z": _target(snap, "door.z.close_percent", 0.0),
+        }
+        commanded = Control(fans=fans, heaters=heaters, doors=doors)
+        ready = snap.lifecycle in {"READY"} and snap.safety_control_mode not in {"SAFE", "SAFE_PENDING"}
+        if getattr(self._backend, "_lifecycle", "") == "SAFE":
+            ready = False
+        if self._spec and self._spec.stale:
+            fresh = False
+        else:
+            age = 0.0
+            if snap.wall_time is not None:
+                wt = snap.wall_time
+                if wt.tzinfo is None:
+                    wt = wt.replace(tzinfo=timezone.utc)
+                age = max(0.0, (_utcnow() - wt).total_seconds())
+            fresh = (not snap.data_gap) and age <= self._fresh_horizon_s
+        faults = [f.type or f.human_reason or f.fault_id for f in snap.active_faults]
+        return State(
+            time=snap.wall_time or _utcnow(),
+            temperatures_c=temps,
+            temperature_valid=valid,
+            fans_percent=fans,
+            heaters_percent=heaters,
+            doors_close_percent=doors,
+            ready=ready,
+            fresh=fresh,
+            faults=faults,
+            control=commanded,
+            meta={
+                "device_epoch": snap.device_epoch,
+                "snapshot_seq": snap.snapshot_seq,
+                "control_revision": snap.control_revision,
+                "port_generation": snap.port_generation,
+                "lifecycle": snap.lifecycle,
+                "safety_control_mode": snap.safety_control_mode,
+                "device_confirmation": snap.device_confirmation,
+                "source_time": snap.wall_time.isoformat() if snap.wall_time else None,
+            },
+        )
+
+    async def _ensure_lease(self) -> None:
+        if self._lease is not None and not getattr(self._lease, "_closed", False):
+            return
+        ttl = timedelta(seconds=20)
+        if self._caps is not None and self._caps.timing is not None and self._caps.timing.recommended_action_ttl_ms:
+            ttl = timedelta(milliseconds=max(self._caps.timing.recommended_action_ttl_ms, 5000))
+        self._lease = await self._backend.acquire_lease(
+            self._device_id, "hth-facade", ttl, auto_renew=True
+        )
+        await self._lease.__aenter__()
+
+    async def _safe(self) -> Result:
+        await self._ensure_lease()
+        try:
+            raw = await self._lease.enter_safe_mode("facade")
+        except (LeaseExpired, LeaseMismatch):
+            self._lease = None
+            await self._ensure_lease()
+            raw = await self._lease.enter_safe_mode("facade")
+        return _result_from(raw)
+
+    async def _set(self, control: Control, *, resume: bool) -> Result:
+        snap = await self._snapshot()
+        state = self._state_from(snap)
+        if not state.fresh:
+            raise HTHError("state is not fresh", code="STALE", recoverable=True)
+        if resume:
+            if state.ready:
+                raise HTHError("not in safe mode", code="NOT_SAFE", recoverable=True)
+        elif not state.ready:
+            raise HTHError("device is not ready for control", code="NOT_READY", recoverable=True)
+        await self._ensure_lease()
+        if self._caps is None:
+            self._caps = await self._backend.get_capabilities(self._device_id)
+        ctrl = control.normalized()
+        if self._spec is not None and self._spec.clamp_heaters < 100:
+            ctrl = Control(
+                fans=ctrl.fans,
+                heaters=[min(v, self._spec.clamp_heaters) for v in ctrl.heaters],
+                doors=ctrl.doors,
+            )
+        batch = _batch_from_control(
+            self._device_id,
+            ctrl,
+            snap,
+            self._caps,
+            lease_id=self._lease.lease_id,
+            lease_epoch=self._lease.lease_epoch,
+        )
+        try:
+            if resume:
+                raw = await self._lease.resume_from_safe(batch)
+            else:
+                raw = await self._lease.apply(batch)
+        except (LeaseExpired, LeaseMismatch):
+            self._lease = None
+            await self._ensure_lease()
+            batch = _batch_from_control(
+                self._device_id,
+                ctrl,
+                await self._snapshot(),
+                self._caps,
+                lease_id=self._lease.lease_id,
+                lease_epoch=self._lease.lease_epoch,
+            )
+            raw = await self._lease.resume_from_safe(batch) if resume else await self._lease.apply(batch)
+        return _result_from(raw)
+
+    def _on_mock_tick(self, mock: MockClient) -> None:
+        now = time.monotonic()
+        if getattr(mock, "_ready_after", 0) and now >= mock._ready_after and mock._lifecycle == "PROBING":
+            mock._lifecycle = "READY"
+        spec = self._spec
+        if spec is None or self._sim is None:
+            return
+        dt = float(spec.tick_s)
+        self._last_sim = now
+        if spec.disconnect_after_s and (now - self._sim_t0) * self._speed >= spec.disconnect_after_s:
+            if spec.recover_after_s == 0 or (now - self._sim_t0) * self._speed < spec.recover_after_s:
+                mock.inject_data_gap(1)
+        fans = [_float(mock._targets.get(i), 10) for i in FAN_IDS]
+        heaters = [_float(mock._targets.get(i), 0) for i in PTC_IDS]
+        doors = {ax: _float(mock._targets.get(f"door.{ax}.close_percent"), 0) for ax in ("x", "y", "z")}
+        vals = self._sim.step(dt, heaters, fans, doors)
+        for i, sid in enumerate(TEMPERATURE_IDS):
+            if i in spec.invalid_channels:
+                mock._temps[sid] = None
+            else:
+                mock._temps[sid] = vals[i]
+
+
+def _four(values: list[float], default: float) -> list[float]:
+    xs = [_pct(v) for v in list(values)[:4]]
+    while len(xs) < 4:
+        xs.append(default if not xs else xs[-1])
+    return xs
+
+
+def _pct(value: float) -> float:
+    v = float(value)
+    if v < 0:
+        return 0.0
+    if v > 100:
+        return 100.0
+    return v
+
+
+def _float(value: Any, default: float) -> float:
+    try:
+        return float(value)
+    except (TypeError, ValueError):
+        return default
+
+
+def _target(snap: Snapshot, actuator_id: str, default: float) -> float:
+    t = snap.target(actuator_id)
+    if t is None:
+        return default
+    return float(t.commanded_target)
+
+
+def _batch_from_control(device_id, control: Control, snap: Snapshot, caps, *, lease_id: str, lease_epoch: int):
+    from hth_sdk.batch import ActionBatchBuilder
+
+    b = ActionBatchBuilder(device_id, client_id="hth-facade", capabilities=caps)
+    b.command_id(uuid.uuid4().hex)
+    b.lease(lease_id, lease_epoch)
+    b.based_on(snap.snapshot_seq, snap.control_revision)
+    for aid, val in zip(FAN_IDS, control.fans):
+        b.set(aid, val)
+    for aid, val in zip(PTC_IDS, control.heaters):
+        b.set(aid, val)
+    for aid, axis in zip(DOOR_IDS, ("x", "y", "z")):
+        b.set(aid, control.doors[axis])
+    return b.build()
+
+
+def _result_from(raw: ActionResult) -> Result:
+    sent = raw.accepted and raw.dispatched is not None
+    return Result(
+        ok=bool(raw.accepted),
+        sent=bool(sent),
+        message=raw.message or "",
+        warning="",
+        meta={
+            "command_id": raw.command_id,
+            "device_epoch": raw.device_epoch,
+            "confirmation": raw.confirmation,
+            "dispatch_state": raw.dispatch_state,
+            "control_revision": raw.control_revision,
+            "action_origin": raw.action_origin,
+            "clamps": [{"id": c.id, "original": c.original, "limited": c.limited} for c in raw.clamps],
+        },
+    )
+
+
+def _choose_device(devices, *, device, device_id: str | None) -> str:
+    if not devices:
+        raise HTHError("no devices", code="NO_DEVICE", recoverable=False)
+    if device_id:
+        for d in devices:
+            if d.device_id == device_id:
+                return d.device_id
+        raise HTHError(f"device {device_id!r} not found", code="NO_DEVICE", recoverable=False)
+    if device is None:
+        if len(devices) == 1:
+            return devices[0].device_id
+        raise HTHError(
+            "multiple devices; pass device=0 or device_id=...",
+            code="AMBIGUOUS_DEVICE",
+            recoverable=True,
+        )
+    if isinstance(device, int):
+        if device < 0 or device >= len(devices):
+            raise HTHError(f"device index {device} out of range", code="NO_DEVICE", recoverable=False)
+        return devices[device].device_id
+    return str(device)

+ 9 - 6
sdk/python/pyproject.toml

@@ -4,16 +4,13 @@ build-backend = "setuptools.build_meta"
 
 [project]
 name = "hth-sdk"
-version = "0.1.0"
-description = "Python SDK for the hth Linux userspace high-temperature-hood API (gRPC over Unix sockets)."
+version = "0.2.0"
+description = "Simple synchronous Python facade for the hth high-temperature-hood API."
 readme = "README.md"
 requires-python = ">=3.11"
 license = { text = "Proprietary" }
 authors = [{ name = "Prod2U host platform" }]
-dependencies = [
-  "grpcio>=1.83.0,<2",
-  "protobuf>=7.35.1,<8",
-]
+dependencies = []
 keywords = ["hth", "grpc", "hood", "telemetry"]
 classifiers = [
   "Programming Language :: Python :: 3",
@@ -24,8 +21,14 @@ classifiers = [
 ]
 
 [project.optional-dependencies]
+live = [
+  "grpcio>=1.83.0,<2",
+  "protobuf>=7.35.1,<8",
+]
 dev = [
   "grpcio-tools>=1.83.0,<2",
+  "grpcio>=1.83.0,<2",
+  "protobuf>=7.35.1,<8",
   "pytest>=8",
 ]
 gen = [

+ 180 - 0
sdk/python/tests/test_facade.py

@@ -0,0 +1,180 @@
+from __future__ import annotations
+
+import ast
+import threading
+from pathlib import Path
+
+import pytest
+
+from hth_sdk import Control, HTH, HTHError, Result, State
+from hth_sdk.replay import write_sample_replay
+from hth_sdk.sim import SCENARIO_NAMES
+
+
+def _ctrl(fans=20, heaters=10, doors=None) -> Control:
+    return Control(
+        fans=[fans] * 4,
+        heaters=[heaters] * 4,
+        doors=doors or {"x": 0, "y": 0, "z": 0},
+    )
+
+
+def test_public_surface_is_tiny():
+    import hth_sdk
+
+    assert len(hth_sdk.__all__) <= 6
+    assert set(hth_sdk.__all__) == {"HTH", "State", "Control", "Result", "HTHError"}
+
+
+def test_sync_read_and_set():
+    with HTH.mock(scenario="normal", seed=1, speed=50) as hth:
+        state = hth.read()
+        assert isinstance(state, State)
+        assert len(state.temperatures_c) == 27
+        assert len(state.temperature_valid) == 27
+        assert state.temperatures_c[26] is None
+        assert state.temperature_valid[26] is False
+        assert state.control.fans
+        result = hth.set(_ctrl())
+        assert isinstance(result, Result)
+        assert result.ok is True
+        assert result.sent is True
+        assert "UNCONFIRMED" not in (result.warning or "")
+        assert result.meta.get("command_id")
+        again = hth.read()
+        assert again.fans_percent[0] == 20
+        assert again.meta.get("snapshot_seq")
+
+
+def test_watch_and_auto_lease():
+    with HTH.mock(scenario="normal", seed=2, speed=40) as hth:
+        n = 0
+        for state in hth.watch(period=0.01, count=3):
+            n += 1
+            r = hth.set(_ctrl(fans=15 + n, heaters=5))
+            assert r.ok
+        assert n == 3
+
+
+def test_safe_and_resume():
+    with HTH.mock(scenario="normal", seed=1, speed=40) as hth:
+        safe = hth.safe()
+        assert safe.ok
+        state = hth.read()
+        assert state.ready is False
+        with pytest.raises(HTHError) as ei:
+            hth.set(_ctrl())
+        assert ei.value.code == "NOT_READY"
+        res = hth.resume(_ctrl(fans=12, heaters=0))
+        assert res.ok
+        assert hth.read().ready is True
+
+
+def test_replay_readonly(tmp_path):
+    path = write_sample_replay(tmp_path / "r.jsonl")
+    with HTH.replay(path) as hth:
+        state = hth.read()
+        assert len(state.temperatures_c) == 27
+        with pytest.raises(HTHError) as ei:
+            hth.set(_ctrl())
+        assert ei.value.code == "READ_ONLY"
+        assert ei.value.recoverable is False
+
+
+def test_scenarios_run():
+    for name in SCENARIO_NAMES:
+        with HTH.mock(scenario=name, seed=1, speed=80) as hth:
+            st = hth.read()
+            assert isinstance(st, State)
+            if name == "sensor_stale":
+                assert st.fresh is False
+            if name == "safe_mode":
+                assert st.ready is False
+
+
+def test_stale_fail_closed():
+    with HTH.mock(scenario="sensor_stale", seed=1, speed=20) as hth:
+        with pytest.raises(HTHError) as ei:
+            hth.set(_ctrl())
+        assert ei.value.code == "STALE"
+
+
+def test_same_policy_mock_and_replay(tmp_path):
+    def policy(hth: HTH) -> list[float | None]:
+        out = []
+        for state in hth.watch(period=0.01, count=2):
+            valid = [t for t in state.temperatures_c if t is not None]
+            heat = 20 if valid and max(valid) < 40 else 0
+            if state.ready and state.fresh:
+                hth.set(_ctrl(heaters=heat))
+            out.append(max(valid) if valid else None)
+        return out
+
+    with HTH.mock(scenario="normal", seed=1, speed=40) as mock:
+        mock_vals = policy(mock)
+    path = write_sample_replay(tmp_path / "p.jsonl")
+    with HTH.replay(path) as replay:
+        replay_state = replay.read()
+        assert len(replay_state.temperatures_c) == 27
+        with pytest.raises(HTHError):
+            replay.set(_ctrl())
+    assert mock_vals
+
+
+def test_error_model():
+    err = HTHError("x", code="STALE", recoverable=True)
+    assert err.code == "STALE"
+    assert err.message == "x"
+    assert err.recoverable is True
+
+
+def test_no_thread_leak():
+    before = {t.name for t in threading.enumerate()}
+    with HTH.mock(seed=1, speed=30) as hth:
+        hth.read()
+        hth.set(_ctrl())
+    leftover = [t for t in threading.enumerate() if t.name == "hth-facade-loop" and t.is_alive()]
+    assert leftover == []
+    _ = before
+
+
+def test_quickstart_is_clean():
+    root = Path(__file__).resolve().parents[1]
+    qs = (root / "examples" / "quickstart.py").read_text(encoding="utf-8")
+    banned = (
+        "grpc",
+        "protobuf",
+        "unix socket",
+        "lease",
+        "epoch",
+        "command id",
+        "snapshot seq",
+        "control revision",
+        "ttl",
+        "capability hash",
+        "unconfirmed",
+    )
+    low = qs.lower()
+    for word in banned:
+        assert word not in low, word
+    tree = ast.parse(qs)
+    for node in ast.walk(tree):
+        if isinstance(node, ast.ImportFrom) and node.module:
+            assert not node.module.startswith("hth_sdk.advanced")
+            assert "grpc" not in node.module
+            assert "generated" not in node.module
+    core = [ln for ln in qs.splitlines() if ln.strip() and not ln.strip().startswith("#")]
+    assert len(core) <= 15
+
+
+def test_thermal_repeatable():
+    def run():
+        with HTH.mock(scenario="coupled_4chamber", seed=7, speed=50, mode="step") as hth:
+            hth.set(_ctrl(heaters=40, fans=10))
+            for _ in hth.watch(period=0.01, count=4):
+                pass
+            return hth.read().temperatures_c[:4]
+
+    a = run()
+    b = run()
+    assert a == b

+ 6 - 12
sdk/python/tests/test_import.py

@@ -6,24 +6,18 @@ from __future__ import annotations
 def test_import_package():
     import hth_sdk
 
-    assert hth_sdk.API_VERSION == "hth.api.v1"
-    assert hth_sdk.__version__ == "0.1.0"
+    assert hth_sdk.__version__ == "0.2.0"
 
 
 def test_public_symbols():
     import hth_sdk
 
-    for name in (
-        "ActionBatch",
-        "ActionBatchBuilder",
-        "MockClient",
-        "HthClient",
-        "ControlLease",
-        "connect",
-        "DeviceEpochChanged",
-        "DataGap",
-    ):
+    assert hth_sdk.__all__ == ["HTH", "State", "Control", "Result", "HTHError"]
+    for name in hth_sdk.__all__:
         assert hasattr(hth_sdk, name)
+    assert "ActionBatch" not in hth_sdk.__all__
+    assert "HthClient" not in hth_sdk.__all__
+    assert "ControlLease" not in hth_sdk.__all__
 
 
 def test_sdk_does_not_import_heavy_deps():

+ 1 - 1
sdk/python/tests/test_mock_client.py

@@ -4,7 +4,7 @@ import asyncio
 from datetime import timedelta
 
 import pytest
-from hth_sdk import ActionBatch, MockClient
+from hth_sdk.advanced import ActionBatch, MockClient
 from hth_sdk.exceptions import ActionRejected, DataGap, DeviceEpochChanged, LeaseError, LeaseExpired
 from hth_sdk.profiles import prod2u
 

+ 30 - 2
tools/evaluate_gates.py

@@ -94,19 +94,45 @@ def evaluate(rows: list[dict], *, soak_24h: str = "NOT RUN", hardware: str = "NO
         if dirty and dirty not in {"clean", ""}:
             bind = "BLOCKED"
 
+    facade = _st(rows, "facade")
+    if facade == "NOT RUN":
+        facade = _st(rows, "algorithm-facade")
+    kit = _st(rows, "algorithm-kit")
+    if kit == "NOT RUN":
+        kit = _st(rows, "kit-quickstart")
+    scen = _st(rows, "scenario")
+    if scen == "NOT RUN":
+        scen = facade
+    replay = _st(rows, "replay")
+    if replay == "NOT RUN":
+        replay = facade
+    daemon = _st(rows, "daemon-mock")
+    if daemon == "NOT RUN":
+        daemon = _st(rows, "python-matrix")
+    algo_ready = all(s == "PASS" for s in (facade, kit, scen, replay)) and daemon in {"PASS", "NOT RUN"}
     p0 = all(s == "PASS" for s in (go, gofmt, race, vet, static, vuln, buf_lint, buf_break, py, pty, rtl, systemd, fuzz, soak2h, pkg)) and bind == "PASS"
     software = "PASS" if p0 else "BLOCKED"
     ready = "YES" if software == "PASS" else "NO"
-    rc_ready = "YES" if software == "PASS" and soak_24h == "PASS" and hardware == "PASS" else "NO"
-    prod = "NO"
+    rc_ready = "NOT ASSESSED"
+    prod = "NOT ASSESSED"
     return {
         "architecture_direction": "PASS",
+        "algorithm_facade_acceptance": facade,
+        "algorithm_kit_acceptance": kit,
+        "mock_scenario_acceptance": scen,
+        "replay_acceptance": replay,
+        "daemon_mock_uds_acceptance": daemon,
+        "pty_protocol_acceptance": pty,
+        "rtl_cosim_acceptance": rtl if rtl != "NOT RUN" else "NOT RUN",
+        "engineering_package_acceptance": pkg,
+        "ready_for_algorithm_development": "YES" if algo_ready else "NO",
         "software_simulation_integration_acceptance": software,
         "software_safety_acceptance": software,
         "ready_for_controlled_hardware_validation": ready,
         "release_candidate_readiness": rc_ready,
         "production_readiness": prod,
         "hardware_validation": hardware,
+        "hardware_validation_scope": "OUT OF CURRENT ROUND",
         "real_actuator_validation": "NOT RUN",
         "gates": {
             "go_test": go,
@@ -118,6 +144,8 @@ def evaluate(rows: list[dict], *, soak_24h: str = "NOT RUN", hardware: str = "NO
             "buf_lint": buf_lint,
             "buf_breaking": buf_break,
             "python": py,
+            "facade": facade,
+            "algorithm_kit": kit,
             "pty": pty,
             "rtl": rtl,
             "systemd": systemd,

+ 98 - 0
tools/package_hth_algorithm_kit.py

@@ -0,0 +1,98 @@
+#!/usr/bin/env python3
+"""Build the director-facing algorithm kit. No Go, proto, RTL, or review docs."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import sys
+import zipfile
+from datetime import datetime, timezone
+from pathlib import Path
+
+from package_hth_review import write_zip_file
+
+ROOT_NAME = "hth-algorithm-kit"
+
+
+def _sha(data: bytes) -> str:
+    return hashlib.sha256(data).hexdigest()
+
+
+def main() -> int:
+    host = Path(__file__).resolve().parents[1]
+    sdk = host / "sdk" / "python"
+    sys.path.insert(0, str(sdk))
+    commit = os.environ.get("HTH_GIT_COMMIT", "unknown")
+    short = commit[:7] if commit != "unknown" else "unknown"
+    version = "0.2.0"
+    out_dir = Path(os.environ.get("HTH_PACKAGE_DIR") or os.environ.get("TEMP") or "/tmp")
+    out_dir.mkdir(parents=True, exist_ok=True)
+    wheel = Path(os.environ.get("HTH_SDK_WHEEL") or "")
+    if not wheel.is_file():
+        dist = list((sdk / "dist").glob("hth_sdk-*.whl")) if (sdk / "dist").is_dir() else []
+        if not dist:
+            raise SystemExit("set HTH_SDK_WHEEL to a built wheel")
+        wheel = sorted(dist)[-1]
+    epoch = int(os.environ.get("SOURCE_DATE_EPOCH") or 0)
+    items: list[tuple[str, bytes, int]] = []
+
+    def add(name: str, data: bytes, mode: int = 0o644) -> None:
+        items.append((f"{ROOT_NAME}/{name}", data, mode))
+
+    add("README_10_MINUTES.md", (host / "docs" / "simple" / "README_10_MINUTES.md").read_bytes())
+    add("ALGORITHM_API.md", (host / "docs" / "simple" / "ALGORITHM_API.md").read_bytes())
+    add(wheel.name, wheel.read_bytes())
+    add("quickstart.py", (sdk / "examples" / "quickstart.py").read_bytes())
+    add("policy_template.py", (sdk / "examples" / "policy_template.py").read_bytes())
+    add("closed_loop_demo.py", (sdk / "examples" / "closed_loop_demo.py").read_bytes())
+    add("offline_replay_demo.py", (sdk / "examples" / "offline_replay_demo.py").read_bytes())
+    add("algorithm_quickstart.ipynb", (sdk / "examples" / "algorithm_quickstart.ipynb").read_bytes())
+    add(
+        "scenarios/README.md",
+        b"SIMULATION ONLY\nNOT IDENTIFIED FROM REAL HARDWARE\nNOT A PHYSICAL VALIDATION MODEL\n",
+    )
+    from hth_sdk.replay import write_sample_replay
+
+    replay = Path(os.environ.get("TMPDIR") or "/tmp") / "hth-sample-replay.jsonl"
+    write_sample_replay(replay)
+    add("sample_replay/sample.jsonl", replay.read_bytes())
+    manifest = {
+        "name": ROOT_NAME,
+        "version": version,
+        "git_commit": commit,
+        "created_utc": datetime.fromtimestamp(epoch or 0, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+        if epoch
+        else datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
+        "files": [n.split("/", 1)[1] for n, _, _ in items],
+        "note": "Director kit. Mock/Replay only. Hardware validation NOT RUN.",
+    }
+    add("MANIFEST.json", (json.dumps(manifest, indent=2, sort_keys=True) + "\n").encode())
+    items.sort(key=lambda x: x[0])
+    sums = []
+    for name, data, _ in items:
+        sums.append(f"{_sha(data)}  {name.split('/', 1)[1]}")
+    items.append((f"{ROOT_NAME}/SHA256SUMS", ("\n".join(sums) + "\n").encode(), 0o644))
+    items.sort(key=lambda x: x[0])
+    zip_path = out_dir / f"hth-algorithm-kit-{version}-{short}.zip"
+    with zipfile.ZipFile(zip_path, "w") as zf:
+        for name, data, mode in items:
+            write_zip_file(zf, name, data, mode)
+    digest = _sha(zip_path.read_bytes())
+    (out_dir / (zip_path.name + ".sha256")).write_text(f"{digest}  {zip_path.name}\n", encoding="utf-8")
+    att = {
+        "filename": zip_path.name,
+        "bytes": zip_path.stat().st_size,
+        "sha256": digest,
+        "git_commit": commit,
+        "packager": "host/tools/package_hth_algorithm_kit.py",
+        "kind": "algorithm-kit",
+    }
+    (out_dir / (zip_path.name + ".attestation.json")).write_text(json.dumps(att, indent=2) + "\n", encoding="utf-8")
+    print(zip_path)
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 9 - 3
tools/rtl_uart_cosim/run_hthd_pty_rtl.py

@@ -459,9 +459,15 @@ from hth_sdk.types import ActionBatch
 async def main():
     obs, ctl = os.environ["HTH_OBS"], os.environ["HTH_CTL"]
     async with await connect(observe=obs, control=ctl, role="control") as client:
-        snap = await client.get_snapshot("prod2u-0")
-        temps = [m for m in snap.measurements if m.id.startswith("temperature.channel.")]
-        if len(temps) < 27:
+        temps = []
+        snap = None
+        for _ in range(60):
+            snap = await client.get_snapshot("prod2u-0")
+            temps = [m for m in snap.measurements if m.id.startswith("temperature.channel.")]
+            if len(temps) >= 27:
+                break
+            await asyncio.sleep(0.5)
+        if snap is None or len(temps) < 27:
             raise SystemExit(f"expected 27 temperature channels after GET_TEMP, got {len(temps)}")
         print("TEMP_CHANNELS", len(temps), "EVENT_ID", snap.event_id, "QUALITY", sorted({m.quality for m in temps}))
         caps = await client.get_capabilities("prod2u-0")

+ 51 - 0
tools/run_algorithm_gates.sh

@@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+# Algorithm facade + kit gates. Does not require RTL, soak, or hardware.
+set -uo pipefail
+export PATH="/opt/python-3.12/bin:/opt/python-3.11/bin:/opt/python-3.13/bin:/usr/bin:/bin:${PATH}"
+SRC="${HTH_SRC:-$(cd "$(dirname "$0")/../.." && pwd)}"
+SDK="${SRC}/host/sdk/python"
+RUN="${HTH_RUN_DIR:-/tmp/hth-algo-run}"
+PKG="${HTH_PACKAGE_DIR:-/tmp}"
+mkdir -p "$RUN" "$PKG"
+export HTH_RUN_DIR="$RUN"
+export HTH_PACKAGE_DIR="$PKG"
+export HTH_GIT_COMMIT="${HTH_GIT_COMMIT:-unknown}"
+export SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH:-$(date -u +%s)}"
+REC="${SRC}/host/tools/record_cmd.sh"
+fail=0
+rec() { local n="$1"; shift; if ! "${REC}" "${n}" "$@"; then fail=1; fi; }
+
+cd "$SDK"
+rec algorithm-facade python3 -m pytest tests/test_facade.py tests/test_import.py tests/test_mock_client.py -q
+rec algorithm-notebook python3 - <<'PY'
+import json
+from pathlib import Path
+nb = json.loads(Path("examples/algorithm_quickstart.ipynb").read_text(encoding="utf-8"))
+g = {}
+for cell in nb["cells"]:
+    if cell.get("cell_type") != "code":
+        continue
+    exec("".join(cell.get("source") or []), g, g)
+print("NOTEBOOK_OK")
+PY
+python3 -m pip install -q -i https://mirrors.aliyun.com/pypi/simple build >/dev/null 2>&1 || true
+rec algorithm-wheel python3 -m build --wheel --outdir "${RUN}/dist" .
+WHEEL="$(ls -1t "${RUN}/dist"/hth_sdk-*.whl 2>/dev/null | head -n1 || true)"
+export HTH_SDK_WHEEL="$WHEEL"
+rec algorithm-kit python3 "${SRC}/host/tools/package_hth_algorithm_kit.py"
+ZIP="$(ls -1t "${PKG}"/hth-algorithm-kit-*.zip 2>/dev/null | head -n1 || true)"
+if [[ -n "$ZIP" ]]; then
+  STAGE="${RUN}/kit-stage"
+  rm -rf "$STAGE"
+  mkdir -p "$STAGE"
+  python3 - <<PY
+import zipfile
+zipfile.ZipFile(r"${ZIP}").extractall(r"${STAGE}")
+PY
+  rec kit-quickstart bash -lc "cd ${STAGE}/hth-algorithm-kit && python3 -m venv venv && ./venv/bin/pip install -q ${STAGE}/hth-algorithm-kit/hth_sdk-*.whl && ./venv/bin/python quickstart.py"
+fi
+if [[ -d /mnt/c/Users/Administrator/AppData/Local/Temp ]]; then
+  cp -a "${PKG}"/hth-algorithm-kit-*.zip* /mnt/c/Users/Administrator/AppData/Local/Temp/ 2>/dev/null || true
+fi
+echo "ALGO_GATES_DONE fail=${fail}" | tee "${RUN}/GATES_DONE"
+exit "${fail}"