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

fix(host): close R3 safety lifecycle, serial cancel, and evidence gates

Latch SAFE only after a complete write, interrupt stuck UART reads without the transaction mutex, and start GET_TEMPERATURE only after startup_complete. Bind systemd VM, production UART 217, and capability-driven SDK evidence to the host tree.

Co-authored-by: Cursor <cursoragent@cursor.com>
root 3 месяцев назад
Сommit
0c53ba1d9f
100 измененных файлов с 6598 добавлено и 0 удалено
  1. 20 0
      .gitignore
  2. 68 0
      ACCEPTANCE_MATRIX.md
  3. 84 0
      Makefile
  4. 113 0
      README.zh-CN.md
  5. 1 0
      api/proto/google/protobuf/README.md
  6. 115 0
      api/proto/google/protobuf/duration.proto
  7. 145 0
      api/proto/google/protobuf/timestamp.proto
  8. BIN
      api/proto/hth.api.v1.desc.prev
  9. BIN
      api/proto/hth/api/v1/hth.desc
  10. 639 0
      api/proto/hth/api/v1/hth.proto
  11. 22 0
      buf.yaml
  12. 176 0
      cmd/hth-capture/main.go
  13. 274 0
      cmd/hthctl/main.go
  14. 44 0
      cmd/hthd/main.go
  15. 2 0
      contracts/evidence/RTL_REF.txt
  16. 3 0
      contracts/evidence/SHA256SUMS
  17. 17 0
      contracts/evidence/golden-vectors.json
  18. 547 0
      contracts/evidence/host-contract.json
  19. 32 0
      deploy/examples/hthd.mock.yaml
  20. 32 0
      deploy/examples/hthd.serial.yaml
  21. 23 0
      deploy/examples/podman-socket-only.sh
  22. 116 0
      deploy/install.sh
  23. 8 0
      deploy/systemd/hth.conf
  24. 45 0
      deploy/systemd/hthd.service
  25. 44 0
      deploy/systemd/hthd@.service
  26. 7 0
      deploy/sysusers.d/hth.conf
  27. 12 0
      deploy/tmpfiles/hth.conf
  28. 29 0
      deploy/udev/99-hth-controller.rules.template
  29. 24 0
      deploy/uninstall.sh
  30. 103 0
      docs/api-contract.zh-CN.md
  31. 133 0
      docs/architecture.zh-CN.md
  32. 42 0
      docs/compatibility-policy.zh-CN.md
  33. 117 0
      docs/deployment.zh-CN.md
  34. 65 0
      docs/failure-semantics.zh-CN.md
  35. 78 0
      docs/known-gaps.zh-CN.md
  36. 62 0
      docs/model-data-integration.zh-CN.md
  37. 79 0
      docs/operations.zh-CN.md
  38. 232 0
      docs/protocol-source-audit.zh-CN.md
  39. 119 0
      docs/python-sdk-guide.zh-CN.md
  40. 86 0
      docs/safety-contract.zh-CN.md
  41. 78 0
      docs/signal-dictionary.zh-CN.md
  42. 18 0
      go.mod
  43. 56 0
      go.sum
  44. 527 0
      internal/app/app.go
  45. 23 0
      internal/app/backend_linux.go
  46. 131 0
      internal/backend/backend.go
  47. 104 0
      internal/backend/backend_test.go
  48. 22 0
      internal/backend/classify.go
  49. 369 0
      internal/backend/mock.go
  50. 207 0
      internal/backend/replay.go
  51. 34 0
      internal/backend/replay_fuzz_test.go
  52. 145 0
      internal/backend/replay_strict_test.go
  53. 56 0
      internal/backend/serial_close_linux_test.go
  54. 208 0
      internal/backend/serial_get_linux_test.go
  55. 227 0
      internal/backend/serial_linux.go
  56. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/0255ca613fd7c6a1
  57. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/0938b7fa705ec552
  58. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/0cbd8c395f234c73
  59. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/0ce8924336b00a4a
  60. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/10668f0c64d180ee
  61. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/1e4976294bffeaa6
  62. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/247c677b3d2ee7d7
  63. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/2940cad0e1b165c5
  64. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/2eafed28f42a799b
  65. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/2fa28f4c3423d42d
  66. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/406a65375d9339a3
  67. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/446e2c92d43d091a
  68. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/4a20de1c3de0db84
  69. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/4ca045b77ed1c5e0
  70. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/4d8dad06d4f7a904
  71. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/577e3b8b16e7366a
  72. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/598eaef9b893cb72
  73. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/6bb50660bc5d12ab
  74. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/70a32a8bd28f5c4e
  75. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/72306381974229ff
  76. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/7537b76aadc6bd46
  77. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/7d4070133ca6e65e
  78. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/8341f2427830db12
  79. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/88fec89d12adc077
  80. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/94b3d7c043393667
  81. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/a0bf1046919c14c8
  82. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/a2433a0d4562ac7a
  83. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/a87b74a6e18e12db
  84. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/b34c6fd7ba700fac
  85. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/b54de5a6d7420d30
  86. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/b9cde15548b004f6
  87. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/bb625e6c5fa614a3
  88. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/bc5279be026b445b
  89. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/c359a835dadd58b1
  90. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/c6c45768ecf32742
  91. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/c9c99350dd9b9413
  92. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/d2795509f824b36c
  93. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/dbd5d95c0469560d
  94. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/e2eece8a41c4840c
  95. 3 0
      internal/backend/testdata/fuzz/FuzzReplayOpen/f50212ecab9304df
  96. 26 0
      internal/caphash/caphash.go
  97. 22 0
      internal/caphash/caphash_test.go
  98. 438 0
      internal/capture/capture.go
  99. 29 0
      internal/capture/capture_test.go
  100. 0 0
      internal/capture/disk_test.go

+ 20 - 0
.gitignore

@@ -0,0 +1,20 @@
+# Local SDK venv (oss-cad-suite prefix layout). Never commit.
+.venv-sdk/
+
+# Build outputs
+bin/
+
+# Python caches / packaging
+**/__pycache__/
+**/.pytest_cache/
+**/*.egg-info/
+.mypy_cache/
+.ruff_cache/
+dist/
+build/
+
+# Local captures / runtime
+*.sock
+
+# This-run logs (authoritative copies live in $HTH_RUN_DIR / the review zip)
+reviews/artifacts/

+ 68 - 0
ACCEPTANCE_MATRIX.md

@@ -0,0 +1,68 @@
+# ACCEPTANCE_MATRIX
+
+Evidence classes: `source` (this `host/` tree), `sim` (pytest / Go tests), `formal` (none for host), `TD` (N/A), `package` (review zip), `hardware` (**NOT RUN**).
+
+`fail` / `blocked` / `not_run` / placeholder is never a pass.
+
+| ID | Requirement | Evidence | Status |
+| --- | --- | --- | --- |
+| P1 | Current protocol is percent-close 0..100, not jog 00/01/02 | `docs/protocol-source-audit.zh-CN.md`, profile.json, SDK door IDs | source pass |
+| P2 | Door 0 = FULL OPEN, not STOP | safety-contract, signal-dictionary, `ActionBatchBuilder.set_door_close_percent`, tests | source+sim pass (SDK) |
+| P3 | GET_MOTOR_STATUS exists | audit, proto Capabilities, profile protocol.commands | source pass |
+| P4 | No ACK; SET_ALL never CONFIRMED | audit, SDK apply guard, MockClient confirmation, docs | source+sim pass (SDK/mock) |
+| P5 | Watchdog 30s; fed only by valid SET_ALL after startup | audit, profile watchdog.*, docs | source pass; serial path = Go daemon |
+| P6 | GET_TEMP dropped during startup; readiness = startup_complete | audit, profile startup.*, docs | source pass |
+| P7 | Heartbeat repeats real percents; must not rewrite doors to 0 as no-op | safety-contract, architecture | source pass; runtime = Go |
+| P8 | temperature.channel.00..26 mapping UNKNOWN | signal-dictionary, MockClient notes, profile sensors | source pass |
+| P9 | Fan RPM / encoder / firmware version NOT_SUPPORTED | Capabilities flags, docs, mock | source+sim pass (SDK) |
+| P10 | Hardware validation NOT RUN | README, known-gaps, this matrix | declared |
+| A1 | Domain API vs gRPC distinction | architecture, api-contract | source pass |
+| A2 | hthd owns serial; clients do not | architecture, deployment, SDK never opens serial | source pass (SDK); daemon = Go |
+| A3 | observe.sock vs control.sock; groups hth-observe / hth-control | deployment, systemd comments | source pass |
+| A4 | requested/accepted/dispatched/confirmed | api-contract, failure-semantics, control_mock.py printout | source+sim pass (mock) |
+| A5 | Lease vs grpc keepalive vs systemd wd vs FPGA wd | architecture, safety-contract, unit omits WatchdogSec | source pass |
+| S1 | Python package hth-sdk importable | `sdk/python/pyproject.toml`, `tests/test_import.py` | sim (run locally) |
+| S2 | Unix socket connect observe/control | `hth_sdk.client.connect*` | source; live UDS needs daemon |
+| S3 | grpc.aio wrappers | `hth_sdk/client.py` | source; needs stubs |
+| S4 | Typed exceptions | `hth_sdk/exceptions.py`, tests | sim |
+| S5 | Capabilities / Snapshot objects | `hth_sdk/types.py` | sim |
+| S6 | Telemetry async iter + epoch/gap notifications | MockClient + `test_mock_client.py` | sim |
+| S7 | ControlLease context manager | `hth_sdk/lease.py` | sim (mock) |
+| S8 | ActionBatch builder + validate/apply | batch + mock tests | sim |
+| S9 | API version check | constants + client `_maybe_check_api` | source |
+| S10 | control example defaults to mock; no dangerous real actions | `examples/control_mock.py`, `test_control_example.py` | sim |
+| S11 | pytest without daemon | `sdk/python/tests/*` | sim |
+| D1 | Chinese docs complete (listed in README) | `host/docs/*.zh-CN.md`, README, this file | source |
+| D2 | protocol-source-audit not overwritten | git/worktree | constraint |
+| D3 | systemd unit Restart/RuntimeDirectory/NoNewPrivileges/User=hth; no lying WatchdogSec | `deploy/systemd/hthd.service` | source |
+| D4 | udev template placeholders only | `deploy/udev/99-hth-controller.rules.template` | source |
+| D5 | tmpfiles + example yaml mock/serial | `deploy/tmpfiles`, `deploy/examples` | source |
+| D6 | Thin podman/docker socket-only example; no k8s/helm | deployment.zh-CN.md | source |
+| C1 | hth.api.v1, reserved-tag policy, enum 0 UNSPECIFIED, split versions | proto + compatibility-policy | source |
+| Z1 | review zip packager | `tools/package_hth_review.py` | source (0644/0755 modes; contract evidence snapshot) |
+| G1 | Go daemon compile/test | `go test ./...`, amd64/arm64 build logs | sim pass (this environment) |
+| G2 | `go test -race` | CGO + gcc 14.2.0 this host | **sim pass** (2026-08-17) |
+| G9 | Python pin matches gencode 7.35.1 / grpcio 1.83.0 | pyproject.toml; fresh venv+wheel+UDS on 3.11/3.12/3.13 | **sim pass** (CPython 3.11.13 / 3.12.11 / 3.13.5) |
+| G11 | observer/controller/untrusted UDS | `TestRealUsersSocketIsolation` | sim pass (root useradd) |
+| G12 | RTL SET_ALL byte oracle | `rtl_uart_cosim/run_setall_oracle.py` | sim pass |
+| G13 | UART-bit Prod2U top cocotb | `run_uart_bit_e2e.py` | **sim pass** (Icarus; no hthd) |
+| G14 | hthd + PTY + UART-bit + top | `run_hthd_pty_rtl.py` | **sim pass** (`RTL_HTHD_PTY_UART_BIT_PASS`; sim-only CLKS_PER_BIT=8). Production 217: **FAIL** this run |
+| G15 | systemd-nspawn Debian | `tools/nspawn_hthd_smoke.sh` | **blocked** (overlay container, PID1=sshd, cannot mount) |
+| G16 | `sd_notify` READY/STOPPING | `TestHthdSdNotifyReadyAndStopping` | sim pass |
+| G17 | PR soak 3 min | `HTH_SOAK_SECONDS=180 TestPRSoakMock` | sim pass |
+| G19 | `staticcheck ./...` | staticcheck 2025.1.1 | **sim pass** this run |
+| G20 | PR fuzz 60s | parser/profile/config/capture | **sim pass** this run |
+| G21 | `govulncheck ./...` | v1.1.4 / Go 1.24.6 | **fail** stdlib GO-2025-4007/4008 |
+| G3 | Nil/empty Apply/Validate no panic | device + gRPC UDS tests | sim pass |
+| G4 | Raw requested vs normalized | `TestRawRequestedKeepsOriginalFloat` | sim pass |
+| G5 | Slew rate Fake clock | safety + device tests | sim pass |
+| G6 | Startup door batch Plan A | `TestStartupRejectsDoorChange` | sim pass |
+| G7 | Short write reconnect/epoch | `TestShortWriteBumpsEpochAndKillsLease` | sim pass |
+| G8 | Sticky event DATA_GAP | telemetry test | sim pass |
+| G10 | ZIP 0644 / gofmt | packager + gofmt -l | source pass this tree |
+| G18 | `buf lint` + `buf breaking` | `host/buf.yaml`, `tools/l0_contract_check.py` | **sim pass** (buf 1.47.2; FILE breaking vs `hth.api.v1.desc.prev`) |
+| H1 | Physical serial / PTC / motors / JTAG | forbidden unless authorized | **NOT RUN** |
+
+## Protocol honesty block (copy)
+
+Current hardware protocol: percent-close doors 0..100, GET_MOTOR_STATUS exists, NO ACK, watchdog 30s fed only by SET_ALL after startup, GET_TEMP dropped during startup. Door 0 is FULL OPEN not STOP. Heartbeat repeats real percents. Temperature channel IDs `temperature.channel.00..26` mapping UNKNOWN. Fan RPM / encoder / firmware version NOT_SUPPORTED. Hardware validation NOT RUN. Never claim production-ready hardware.

+ 84 - 0
Makefile

@@ -0,0 +1,84 @@
+MODULE := hth
+GO ?= go
+PYTHON ?= python3
+PROTOC ?= protoc
+GOPROXY ?= https://goproxy.cn,direct
+export GOPROXY
+export CGO_ENABLED ?= 0
+export GOTOOLCHAIN ?= local
+
+HOST_ROOT := $(abspath $(dir $(lastword $(MAKEFILE_LIST))))
+REPO_ROOT := $(abspath $(HOST_ROOT)/..)
+PROTO := $(HOST_ROOT)/api/proto/hth/api/v1/hth.proto
+GEN_DIR := $(HOST_ROOT)/internal/gen/hth/api/v1
+PROFILE := $(HOST_ROOT)/profiles/prod2u-door-temp/profile.json
+BIN_DIR := $(HOST_ROOT)/bin
+API_VERSION := hth.api.v1
+
+.PHONY: all generate profile proto tidy build build-amd64 build-arm64 test test-race vet fuzz python-sdk check-config doctor-bin gofmt-check clean
+
+all: generate build test
+
+generate: profile proto
+
+profile:
+	$(PYTHON) $(HOST_ROOT)/tools/gen_profile.py --repo-root $(REPO_ROOT) --out $(PROFILE)
+
+proto:
+	@mkdir -p $(GEN_DIR)
+	$(PROTOC) --version
+	$(PROTOC) -I $(HOST_ROOT)/api/proto \
+		--go_out=$(HOST_ROOT)/internal/gen --go_opt=module=hth/internal/gen \
+		--go-grpc_out=$(HOST_ROOT)/internal/gen --go-grpc_opt=module=hth/internal/gen \
+		$(PROTO)
+	$(PYTHON) $(HOST_ROOT)/tools/gen_python_stubs.py || $(PYTHON) -m grpc_tools.protoc -I $(HOST_ROOT)/api/proto \
+		--python_out=$(HOST_ROOT)/sdk/python/hth_sdk/generated \
+		--grpc_python_out=$(HOST_ROOT)/sdk/python/hth_sdk/generated \
+		$(PROTO)
+	$(PROTOC) -I $(HOST_ROOT)/api/proto --include_imports --descriptor_set_out=$(HOST_ROOT)/api/proto/hth/api/v1/hth.desc $(PROTO)
+
+tidy:
+	cd $(HOST_ROOT) && $(GO) mod tidy
+
+build: generate
+	mkdir -p $(BIN_DIR)
+	cd $(HOST_ROOT) && $(GO) build -trimpath -ldflags '-s -w -X hth/internal/app.APIVersion=$(API_VERSION)' -o $(BIN_DIR)/hthd ./cmd/hthd
+	cd $(HOST_ROOT) && $(GO) build -trimpath -ldflags '-s -w -X hth/internal/app.APIVersion=$(API_VERSION)' -o $(BIN_DIR)/hthctl ./cmd/hthctl
+	cd $(HOST_ROOT) && $(GO) build -trimpath -ldflags '-s -w -X hth/internal/app.APIVersion=$(API_VERSION)' -o $(BIN_DIR)/hth-capture ./cmd/hth-capture
+
+build-amd64: generate
+	mkdir -p $(BIN_DIR)
+	cd $(HOST_ROOT) && GOOS=linux GOARCH=amd64 CGO_ENABLED=0 $(GO) build -trimpath -o $(BIN_DIR)/hthd-linux-amd64 ./cmd/hthd
+	cd $(HOST_ROOT) && GOOS=linux GOARCH=amd64 CGO_ENABLED=0 $(GO) build -trimpath -o $(BIN_DIR)/hthctl-linux-amd64 ./cmd/hthctl
+	cd $(HOST_ROOT) && GOOS=linux GOARCH=amd64 CGO_ENABLED=0 $(GO) build -trimpath -o $(BIN_DIR)/hth-capture-linux-amd64 ./cmd/hth-capture
+
+build-arm64: generate
+	mkdir -p $(BIN_DIR)
+	cd $(HOST_ROOT) && GOOS=linux GOARCH=arm64 CGO_ENABLED=0 $(GO) build -trimpath -o $(BIN_DIR)/hthd-linux-arm64 ./cmd/hthd
+	cd $(HOST_ROOT) && GOOS=linux GOARCH=arm64 CGO_ENABLED=0 $(GO) build -trimpath -o $(BIN_DIR)/hthctl-linux-arm64 ./cmd/hthctl
+	cd $(HOST_ROOT) && GOOS=linux GOARCH=arm64 CGO_ENABLED=0 $(GO) build -trimpath -o $(BIN_DIR)/hth-capture-linux-arm64 ./cmd/hth-capture
+
+test: generate
+	cd $(HOST_ROOT) && $(GO) test ./...
+
+test-race:
+	cd $(HOST_ROOT) && CGO_ENABLED=1 $(GO) test -race ./...
+
+vet:
+	cd $(HOST_ROOT) && $(GO) vet ./...
+
+gofmt-check:
+	@test -z "$$(cd $(HOST_ROOT) && gofmt -l $(shell cd $(HOST_ROOT) && find . -name '*.go' ! -path './internal/gen/*'))"
+
+fuzz:
+	cd $(HOST_ROOT) && $(GO) test ./internal/protocol -fuzz=FuzzParser -fuzztime=8s
+
+python-sdk:
+	$(PYTHON) -m pip install -e $(HOST_ROOT)/sdk/python -q
+	$(PYTHON) -m pytest -q $(HOST_ROOT)/sdk/python/tests
+
+check-config: build
+	$(BIN_DIR)/hthd --check-config --config $(HOST_ROOT)/deploy/examples/hthd.mock.yaml
+
+clean:
+	rm -rf $(BIN_DIR)

+ 113 - 0
README.zh-CN.md

@@ -0,0 +1,113 @@
+# hth Linux 用户空间平台
+
+`hth` 是高温罩设备在 **Linux 宿主机用户空间** 的访问与控制平台。它的目标不是训练模型,而是让后续的数据人员、控制算法人员和模型人员 **不必理解串口帧、CRC、Command Type、FPGA 球位、PWM 或 STEP/DIR**。
+
+当前活动硬件协议来自 Prod2U 门百分比合同(见 `docs/protocol-source-audit.zh-CN.md`)。本文与所有 `host/docs/*` 均按该审计撰写。
+
+## 一句话架构
+
+```text
+CPLD/FPGA 控制板  --UART-->  hthd(唯一串口所有者)  --gRPC/UDS-->  observe.sock / control.sock
+```
+
+- **领域 API**:高温罩语义(温度、风扇占空比、PTC 占空比、门闭合百分比、Lease、故障)。
+- **gRPC**:该 API 的一种本地传输。第一版只走 Unix Domain Socket,不监听 TCP。
+- **Python SDK**(`hth-sdk` / `import hth_sdk`):给数据/模型程序用的客户端。
+- **hthctl / hth-capture**:运维与短时采集,不打开串口。
+
+## 协议诚实性(必须先读)
+
+当前真实 UART 合同:
+
+| 事实 | 含义 |
+| --- | --- |
+| 门字节 `0..100` | **闭合百分比**。`0` = **全开**,`100` = **全关**。`0` **不是** STOP / HOLD / 心跳空操作 |
+| `GET_MOTOR_STATUS` (`0x03`) | 存在;返回 31 字节 `MOTOR_STATUS_DATA` |
+| **无 ACK** | 串口 `write` 成功只表示字节交给了 OS。`confirmation` 最多是 `UNCONFIRMED`,**永不**把 SET_ALL 标成 `CONFIRMED` |
+| Watchdog **30 s** | 仅 `startup_complete` 之后,由**合法 SET_ALL commit** 喂狗。GET **不喂** |
+| 启动期 `GET_TEMPERATURE` | **静默丢弃,无响应**。Readiness = `startup_complete` 位 |
+| 心跳 | 必须**重发真实连续目标(含三个门百分比)**。禁止把门改写成 `0` 当空操作 |
+| 温度 ID | `temperature.channel.00` … `26`。物理 DIMM/腔体映射 = **UNKNOWN** |
+| 风扇 RPM / 编码器 / 固件版本 | **NOT_SUPPORTED** |
+| 硬件验证 | **NOT RUN**。本仓库 **不得**声称生产可用硬件 |
+
+旧 jog 合同(`00`=不启动 jog / `01` 开 / `02` 关,watchdog 10 s → FAN 20)**已破坏性迁移,禁止复活**。
+
+## 为什么 hthd 独占串口
+
+多个进程同时打开同一 UART 会导致:
+
+- 帧被拆碎、CRC 失败、半帧互相污染;
+- 两个控制者同时写 SET_ALL,latest-wins 在总线上变成竞态;
+- Watchdog 心跳与用户动作互相覆盖;
+- 无 ACK 时无法判断“谁写成功了”。
+
+因此 **只有 `hthd` 允许打开串口**。Python 模型、Jupyter、容器、hthctl、采集程序都只连 Unix Socket。
+
+## 仓库布局
+
+```text
+host/
+  api/proto/hth/api/v1/hth.proto   # 稳定 API 合同(hth.api.v1)
+  cmd/                             # hthd / hthctl / hth-capture(Go 守护进程)
+  internal/                        # 协议、后端、Lease、安全、gRPC
+  profiles/prod2u-door-temp/       # 由 host-contract + golden 生成的 Profile
+  sdk/python/                      # hth-sdk
+  deploy/                          # systemd / udev 模板 / tmpfiles / 示例配置
+  docs/                            # 中文文档
+```
+
+## 快速开始(Mock,不碰硬件)
+
+```bash
+# 守护进程(Go 侧;后端 mock,不打开串口)
+hthd --backend=mock --config host/deploy/examples/hthd.mock.yaml
+
+# Python SDK(可在无守护进程时用 in-process MockClient)
+cd host/sdk/python
+python3 -m pip install -e .
+python3 examples/observe.py
+python3 examples/snapshot.py
+python3 examples/control_mock.py    # 默认 mock;拒绝危险真机动作
+python3 examples/capture.py
+python3 -m pytest -q tests
+```
+
+生成 Python protobuf stubs(真实 UDS 客户端需要):
+
+```bash
+python3 host/tools/gen_python_stubs.py
+```
+
+## 给两类后续人员
+
+- **数据人员**:只加入 `hth-observe` 组,挂载 `observe.sock`,调用 `GetSnapshot` / `SubscribeTelemetry`。不要申请 Lease。
+- **模型/控制人员**:加入 `hth-control` 组,先 `AcquireControlLease`,再用 `ActionBatch` 一次提交风扇+PTC+门百分比。用 `ValidateAction` 做干跑。
+
+详见 `docs/model-data-integration.zh-CN.md` 与 `docs/python-sdk-guide.zh-CN.md`。
+
+## 文档索引
+
+| 文档 | 内容 |
+| --- | --- |
+| [protocol-source-audit.zh-CN.md](docs/protocol-source-audit.zh-CN.md) | 协议证据链(已写,勿覆盖) |
+| [architecture.zh-CN.md](docs/architecture.zh-CN.md) | 运行架构与职责边界 |
+| [api-contract.zh-CN.md](docs/api-contract.zh-CN.md) | 领域 API 与 gRPC 服务 |
+| [signal-dictionary.zh-CN.md](docs/signal-dictionary.zh-CN.md) | 稳定 ID、实测/估计/不支持 |
+| [safety-contract.zh-CN.md](docs/safety-contract.zh-CN.md) | Lease、心跳、门 0、无 ACK |
+| [failure-semantics.zh-CN.md](docs/failure-semantics.zh-CN.md) | 故障与确认语义 |
+| [python-sdk-guide.zh-CN.md](docs/python-sdk-guide.zh-CN.md) | SDK 安装与示例 |
+| [model-data-integration.zh-CN.md](docs/model-data-integration.zh-CN.md) | 数据订阅 / 模型 Lease |
+| [deployment.zh-CN.md](docs/deployment.zh-CN.md) | systemd、udev 模板、容器挂 socket |
+| [operations.zh-CN.md](docs/operations.zh-CN.md) | 运维、doctor、日志 |
+| [compatibility-policy.zh-CN.md](docs/compatibility-policy.zh-CN.md) | `hth.api.v1`、保留 tag、版本拆分 |
+| [known-gaps.zh-CN.md](docs/known-gaps.zh-CN.md) | 已知缺口 |
+| [ACCEPTANCE_MATRIX.md](ACCEPTANCE_MATRIX.md) | 验收矩阵 |
+
+## 明确不在本仓库范围
+
+神经网络、RL、MPC、PID、Kafka、数据湖、Kubernetes/Helm、Web 前端、公网 REST、直接操作真机 PTC/风扇/电机(除非未来任务明确授权)。
+
+```text
+Hardware validation: NOT RUN
+```

+ 1 - 0
api/proto/google/protobuf/README.md

@@ -0,0 +1 @@
+These well-known types are vendored so `protoc -I api/proto` resolves google/protobuf/{timestamp,duration}.proto without a system protobuf include path.

+ 115 - 0
api/proto/google/protobuf/duration.proto

@@ -0,0 +1,115 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc.  All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option cc_enable_arenas = true;
+option go_package = "google.golang.org/protobuf/types/known/durationpb";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "DurationProto";
+option java_multiple_files = true;
+option objc_class_prefix = "GPB";
+option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+
+// A Duration represents a signed, fixed-length span of time represented
+// as a count of seconds and fractions of seconds at nanosecond
+// resolution. It is independent of any calendar and concepts like "day"
+// or "month". It is related to Timestamp in that the difference between
+// two Timestamp values is a Duration and it can be added or subtracted
+// from a Timestamp. Range is approximately +-10,000 years.
+//
+// # Examples
+//
+// Example 1: Compute Duration from two Timestamps in pseudo code.
+//
+//     Timestamp start = ...;
+//     Timestamp end = ...;
+//     Duration duration = ...;
+//
+//     duration.seconds = end.seconds - start.seconds;
+//     duration.nanos = end.nanos - start.nanos;
+//
+//     if (duration.seconds < 0 && duration.nanos > 0) {
+//       duration.seconds += 1;
+//       duration.nanos -= 1000000000;
+//     } else if (duration.seconds > 0 && duration.nanos < 0) {
+//       duration.seconds -= 1;
+//       duration.nanos += 1000000000;
+//     }
+//
+// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
+//
+//     Timestamp start = ...;
+//     Duration duration = ...;
+//     Timestamp end = ...;
+//
+//     end.seconds = start.seconds + duration.seconds;
+//     end.nanos = start.nanos + duration.nanos;
+//
+//     if (end.nanos < 0) {
+//       end.seconds -= 1;
+//       end.nanos += 1000000000;
+//     } else if (end.nanos >= 1000000000) {
+//       end.seconds += 1;
+//       end.nanos -= 1000000000;
+//     }
+//
+// Example 3: Compute Duration from datetime.timedelta in Python.
+//
+//     td = datetime.timedelta(days=3, minutes=10)
+//     duration = Duration()
+//     duration.FromTimedelta(td)
+//
+// # JSON Mapping
+//
+// In JSON format, the Duration type is encoded as a string rather than an
+// object, where the string ends in the suffix "s" (indicating seconds) and
+// is preceded by the number of seconds, with nanoseconds expressed as
+// fractional seconds. For example, 3 seconds with 0 nanoseconds should be
+// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
+// be expressed in JSON format as "3.000000001s", and 3 seconds and 1
+// microsecond should be expressed in JSON format as "3.000001s".
+//
+message Duration {
+  // Signed seconds of the span of time. Must be from -315,576,000,000
+  // to +315,576,000,000 inclusive. Note: these bounds are computed from:
+  // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
+  int64 seconds = 1;
+
+  // Signed fractions of a second at nanosecond resolution of the span
+  // of time. Durations less than one second are represented with a 0
+  // `seconds` field and a positive or negative `nanos` field. For durations
+  // of one second or more, a non-zero value for the `nanos` field must be
+  // of the same sign as the `seconds` field. Must be from -999,999,999
+  // to +999,999,999 inclusive.
+  int32 nanos = 2;
+}

+ 145 - 0
api/proto/google/protobuf/timestamp.proto

@@ -0,0 +1,145 @@
+// Protocol Buffers - Google's data interchange format
+// Copyright 2008 Google Inc.  All rights reserved.
+// https://developers.google.com/protocol-buffers/
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option cc_enable_arenas = true;
+option go_package = "google.golang.org/protobuf/types/known/timestamppb";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "TimestampProto";
+option java_multiple_files = true;
+option objc_class_prefix = "GPB";
+option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+
+// A Timestamp represents a point in time independent of any time zone or local
+// calendar, encoded as a count of seconds and fractions of seconds at
+// nanosecond resolution. The count is relative to an epoch at UTC midnight on
+// January 1, 1970, in the proleptic Gregorian calendar which extends the
+// Gregorian calendar backwards to year one.
+//
+// All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap
+// second table is needed for interpretation, using a [24-hour linear
+// smear](https://developers.google.com/time/smear).
+//
+// The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By
+// restricting to that range, we ensure that we can convert to and from [RFC
+// 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings.
+//
+// # Examples
+//
+// Example 1: Compute Timestamp from POSIX `time()`.
+//
+//     Timestamp timestamp;
+//     timestamp.set_seconds(time(NULL));
+//     timestamp.set_nanos(0);
+//
+// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
+//
+//     struct timeval tv;
+//     gettimeofday(&tv, NULL);
+//
+//     Timestamp timestamp;
+//     timestamp.set_seconds(tv.tv_sec);
+//     timestamp.set_nanos(tv.tv_usec * 1000);
+//
+// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
+//
+//     FILETIME ft;
+//     GetSystemTimeAsFileTime(&ft);
+//     UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
+//
+//     // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
+//     // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
+//     Timestamp timestamp;
+//     timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
+//     timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
+//
+// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
+//
+//     long millis = System.currentTimeMillis();
+//
+//     Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
+//         .setNanos((int) ((millis % 1000) * 1000000)).build();
+//
+// Example 5: Compute Timestamp from Java `Instant.now()`.
+//
+//     Instant now = Instant.now();
+//
+//     Timestamp timestamp =
+//         Timestamp.newBuilder().setSeconds(now.getEpochSecond())
+//             .setNanos(now.getNano()).build();
+//
+// Example 6: Compute Timestamp from current time in Python.
+//
+//     timestamp = Timestamp()
+//     timestamp.GetCurrentTime()
+//
+// # JSON Mapping
+//
+// In JSON format, the Timestamp type is encoded as a string in the
+// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
+// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
+// where {year} is always expressed using four digits while {month}, {day},
+// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
+// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
+// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
+// is required. A ProtoJSON serializer should always use UTC (as indicated by
+// "Z") when printing the Timestamp type and a ProtoJSON parser should be
+// able to accept both UTC and other timezones (as indicated by an offset).
+//
+// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
+// 01:30 UTC on January 15, 2017.
+//
+// In JavaScript, one can convert a Date object to this format using the
+// standard
+// [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)
+// method. In Python, a standard `datetime.datetime` object can be converted
+// to this format using
+// [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with
+// the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use
+// the Joda Time's [`ISODateTimeFormat.dateTime()`](
+// http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime()
+// ) to obtain a formatter capable of generating timestamps in this format.
+//
+message Timestamp {
+  // Represents seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. Must
+  // be between -62135596800 and 253402300799 inclusive (which corresponds to
+  // 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z).
+  int64 seconds = 1;
+
+  // Non-negative fractions of a second at nanosecond resolution. This field is
+  // the nanosecond portion of the duration, not an alternative to seconds.
+  // Negative second values with fractions must still have non-negative nanos
+  // values that count forward in time. Must be between 0 and 999,999,999
+  // inclusive.
+  int32 nanos = 2;
+}

BIN
api/proto/hth.api.v1.desc.prev


BIN
api/proto/hth/api/v1/hth.desc


+ 639 - 0
api/proto/hth/api/v1/hth.proto

@@ -0,0 +1,639 @@
+syntax = "proto3";
+
+package hth.api.v1;
+
+option go_package = "hth/internal/gen/hth/api/v1;hthv1";
+
+import "google/protobuf/duration.proto";
+import "google/protobuf/timestamp.proto";
+
+// API, protocol, profile, firmware and capability versions are separate.
+// Do not reuse a single "version" field for all of them.
+
+enum DeviceLifecycleState {
+  DEVICE_LIFECYCLE_STATE_UNSPECIFIED = 0;
+  DEVICE_LIFECYCLE_STATE_STARTING = 1;
+  DEVICE_LIFECYCLE_STATE_CONNECTING = 2;
+  DEVICE_LIFECYCLE_STATE_PROBING = 3;
+  DEVICE_LIFECYCLE_STATE_READY = 4;
+  DEVICE_LIFECYCLE_STATE_DEGRADED = 5;
+  DEVICE_LIFECYCLE_STATE_SAFE = 6;
+  DEVICE_LIFECYCLE_STATE_UNAVAILABLE = 7;
+  DEVICE_LIFECYCLE_STATE_UNKNOWN = 8;
+}
+
+enum DataQuality {
+  DATA_QUALITY_UNSPECIFIED = 0;
+  DATA_QUALITY_VALID = 1;
+  DATA_QUALITY_STALE = 2;
+  DATA_QUALITY_MISSING = 3;
+  DATA_QUALITY_INVALID = 4;
+  DATA_QUALITY_ESTIMATED = 5;
+  DATA_QUALITY_NOT_SUPPORTED = 6;
+  DATA_QUALITY_UNKNOWN = 7;
+}
+
+enum ConfirmationStatus {
+  CONFIRMATION_STATUS_UNSPECIFIED = 0;
+  // Hardware returned a proven execution result. Never used for SET_ALL on the
+  // current Prod2U UART contract (no ACK).
+  CONFIRMATION_STATUS_CONFIRMED = 1;
+  // Host fully wrote the frame; device did not acknowledge.
+  CONFIRMATION_STATUS_UNCONFIRMED = 2;
+  // Short write, disconnect, or crash window; device may or may not have executed.
+  CONFIRMATION_STATUS_OUTCOME_UNKNOWN = 3;
+  CONFIRMATION_STATUS_REJECTED = 4;
+  CONFIRMATION_STATUS_NOT_SUPPORTED = 5;
+  // Write never started (no FD, cancelled before first byte).
+  CONFIRMATION_STATUS_NOT_DELIVERED = 6;
+}
+
+// Orthogonal to DeviceLifecycleState. Process may be SERVING while device is STARTING.
+enum TransportState {
+  TRANSPORT_STATE_UNSPECIFIED = 0;
+  TRANSPORT_STATE_DISCONNECTED = 1;
+  TRANSPORT_STATE_CONNECTING = 2;
+  TRANSPORT_STATE_CONNECTED = 3;
+}
+
+enum DeviceReadiness {
+  DEVICE_READINESS_UNSPECIFIED = 0;
+  DEVICE_READINESS_STARTING = 1;
+  DEVICE_READINESS_PROBING = 2;
+  DEVICE_READINESS_READY = 3;
+  DEVICE_READINESS_DEGRADED = 4;
+}
+
+// Latchable host control mode. Ordinary Apply cannot exit SAFE.
+enum SafetyControlMode {
+  SAFETY_CONTROL_MODE_UNSPECIFIED = 0;
+  SAFETY_CONTROL_MODE_NORMAL = 1;
+  SAFETY_CONTROL_MODE_SAFE_PENDING = 2;
+  SAFETY_CONTROL_MODE_SAFE = 3;
+  SAFETY_CONTROL_MODE_RESUME_PENDING = 4;
+}
+
+enum ActionDispatchState {
+  ACTION_DISPATCH_STATE_UNSPECIFIED = 0;
+  ACTION_DISPATCH_STATE_REQUESTED = 1;
+  ACTION_DISPATCH_STATE_ACCEPTED = 2;
+  ACTION_DISPATCH_STATE_QUEUED = 3;
+  ACTION_DISPATCH_STATE_DISPATCH_STARTED = 4;
+  ACTION_DISPATCH_STATE_DISPATCHED = 5;
+  ACTION_DISPATCH_STATE_UNCONFIRMED = 6;
+  ACTION_DISPATCH_STATE_CONFIRMED = 7;
+  ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN = 8;
+  ACTION_DISPATCH_STATE_NOT_DELIVERED = 9;
+  ACTION_DISPATCH_STATE_REJECTED = 10;
+}
+
+enum ControlMode {
+  CONTROL_MODE_UNSPECIFIED = 0;
+  CONTROL_MODE_JOG_ONLY = 1;
+  CONTROL_MODE_PERCENT_CLOSE = 2;
+  CONTROL_MODE_CONTINUOUS_DUTY = 3;
+}
+
+enum FeedbackMode {
+  FEEDBACK_MODE_UNSPECIFIED = 0;
+  FEEDBACK_MODE_NONE = 1;
+  FEEDBACK_MODE_ESTIMATED_OPEN_LOOP = 2;
+  FEEDBACK_MODE_LIMIT_SWITCH = 3;
+  FEEDBACK_MODE_ENCODER = 4;
+}
+
+enum ActuatorKind {
+  ACTUATOR_KIND_UNSPECIFIED = 0;
+  ACTUATOR_KIND_FAN = 1;
+  ACTUATOR_KIND_HEATER = 2;
+  ACTUATOR_KIND_DOOR = 3;
+}
+
+enum SensorKind {
+  SENSOR_KIND_UNSPECIFIED = 0;
+  SENSOR_KIND_TEMPERATURE = 1;
+  SENSOR_KIND_LIMIT_SWITCH = 2;
+  SENSOR_KIND_ESTIMATED_POSITION = 3;
+}
+
+enum FaultSeverity {
+  FAULT_SEVERITY_UNSPECIFIED = 0;
+  FAULT_SEVERITY_INFO = 1;
+  FAULT_SEVERITY_WARNING = 2;
+  FAULT_SEVERITY_ERROR = 3;
+  FAULT_SEVERITY_CRITICAL = 4;
+}
+
+enum FaultClass {
+  FAULT_CLASS_UNSPECIFIED = 0;
+  FAULT_CLASS_DEVICE_REPORTED = 1;
+  FAULT_CLASS_HOST_INFERRED = 2;
+  FAULT_CLASS_CONFIG = 3;
+  FAULT_CLASS_COMMUNICATION = 4;
+  FAULT_CLASS_DATA_QUALITY = 5;
+}
+
+enum FaultType {
+  FAULT_TYPE_UNSPECIFIED = 0;
+  FAULT_TYPE_CONFIG_INVALID = 1;
+  FAULT_TYPE_PROFILE_INVALID = 2;
+  FAULT_TYPE_PROFILE_CONTRACT_MISMATCH = 3;
+  FAULT_TYPE_SERIAL_DEVICE_NOT_FOUND = 4;
+  FAULT_TYPE_SERIAL_PERMISSION_DENIED = 5;
+  FAULT_TYPE_SERIAL_DISCONNECTED = 6;
+  FAULT_TYPE_SERIAL_RECONNECTING = 7;
+  FAULT_TYPE_FRAME_LENGTH_INVALID = 8;
+  FAULT_TYPE_FRAME_CRC_INVALID = 9;
+  FAULT_TYPE_FRAME_TYPE_UNKNOWN = 10;
+  FAULT_TYPE_RESPONSE_TIMEOUT = 11;
+  FAULT_TYPE_TEMPERATURE_DATA_INVALID = 12;
+  FAULT_TYPE_TELEMETRY_STALE = 13;
+  FAULT_TYPE_CONTROL_LEASE_EXPIRED = 14;
+  FAULT_TYPE_CONTROL_COMMAND_REJECTED = 15;
+  FAULT_TYPE_CONTROL_OUTCOME_UNKNOWN = 16;
+  FAULT_TYPE_SAFE_ACTION_NOT_DELIVERED = 17;
+  FAULT_TYPE_SUBSCRIBER_DATA_GAP = 18;
+  FAULT_TYPE_DEVICE_AXIS_FAULT = 19;
+  FAULT_TYPE_WATCHDOG_TRIPPED = 20;
+}
+
+enum EventKind {
+  EVENT_KIND_UNSPECIFIED = 0;
+  EVENT_KIND_SNAPSHOT = 1;
+  EVENT_KIND_FAULT_RAISED = 2;
+  EVENT_KIND_FAULT_CLEARED = 3;
+  EVENT_KIND_LEASE_ACQUIRED = 4;
+  EVENT_KIND_LEASE_RENEWED = 5;
+  EVENT_KIND_LEASE_RELEASED = 6;
+  EVENT_KIND_LEASE_EXPIRED = 7;
+  EVENT_KIND_DEVICE_EPOCH_CHANGED = 8;
+  EVENT_KIND_DATA_GAP = 9;
+  EVENT_KIND_SAFE_MODE_ENTERED = 10;
+  EVENT_KIND_WATCHDOG_HEARTBEAT = 11;
+  EVENT_KIND_ACTION_RESULT = 12;
+  EVENT_KIND_BACKEND_STATE = 13;
+  EVENT_KIND_FAULT_UPDATED = 14;
+  EVENT_KIND_FAULT_ACKNOWLEDGED = 15;
+  EVENT_KIND_SAFETY_MODE_CHANGED = 16;
+  EVENT_KIND_RESUME_FROM_SAFE = 17;
+}
+
+enum HostHealth {
+  HOST_HEALTH_UNSPECIFIED = 0;
+  HOST_HEALTH_SERVING = 1;
+  HOST_HEALTH_NOT_SERVING = 2;
+  HOST_HEALTH_DEGRADED = 3;
+}
+
+enum ActionMode {
+  ACTION_MODE_UNSPECIFIED = 0;
+  ACTION_MODE_NORMAL = 1;
+  ACTION_MODE_SAFE = 2;
+  ACTION_MODE_HEARTBEAT = 3;
+}
+
+enum RejectReason {
+  REJECT_REASON_UNSPECIFIED = 0;
+  REJECT_REASON_INVALID_ARGUMENT = 1;
+  REJECT_REASON_UNKNOWN_ID = 2;
+  REJECT_REASON_NOT_SUPPORTED = 3;
+  REJECT_REASON_OUT_OF_RANGE = 4;
+  REJECT_REASON_CLAMP_REQUIRED = 5;
+  REJECT_REASON_LEASE_MISSING = 6;
+  REJECT_REASON_LEASE_MISMATCH = 7;
+  REJECT_REASON_LEASE_EXPIRED = 8;
+  REJECT_REASON_STALE_SNAPSHOT = 9;
+  REJECT_REASON_STALE_CONTROL_REVISION = 10;
+  REJECT_REASON_EXPIRED_DEADLINE = 11;
+  REJECT_REASON_IDEMPOTENCY_CONFLICT = 12;
+  REJECT_REASON_DEVICE_NOT_READY = 13;
+  REJECT_REASON_QUEUE_FULL = 14;
+  REJECT_REASON_ATOMIC_BATCH_FAILED = 15;
+  REJECT_REASON_SLEW_LIMITED = 16;
+  REJECT_REASON_SAFE_MODE_ACTIVE = 17;
+  REJECT_REASON_RESUME_REQUIRED = 18;
+  REJECT_REASON_PARTIAL_NOT_ALLOWED = 19;
+}
+
+message Measurement {
+  string id = 1;
+  double value = 2;
+  string unit = 3;
+  DataQuality quality = 4;
+  string quality_reason = 5;
+  google.protobuf.Duration age = 6;
+  google.protobuf.Timestamp host_time = 7;
+  bool source_timestamp_available = 8;
+  google.protobuf.Timestamp source_time = 9;
+  optional int32 raw_code = 10;
+}
+
+message TimeWindow {
+  google.protobuf.Timestamp request_sent = 1;
+  google.protobuf.Timestamp response_start = 2;
+  google.protobuf.Timestamp response_complete = 3;
+  google.protobuf.Timestamp host_receive = 4;
+  google.protobuf.Timestamp approx_acquire_start = 5;
+  google.protobuf.Timestamp approx_acquire_end = 6;
+  bool source_timestamp_available = 7;
+}
+
+message DeviceIdentity {
+  string device_id = 1;
+  string display_name = 2;
+  string profile_id = 3;
+  string profile_revision = 4;
+  string protocol_contract_hash = 5;
+  string backend_kind = 6;
+}
+
+message DeviceInfo {
+  DeviceIdentity identity = 1;
+  DeviceLifecycleState lifecycle = 2;
+  uint64 device_epoch = 3;
+}
+
+message Range {
+  double min = 1;
+  double max = 2;
+}
+
+message SensorCapability {
+  string id = 1;
+  repeated string aliases = 2;
+  string display_name = 3;
+  SensorKind kind = 4;
+  string unit = 5;
+  Range valid_range = 6;
+  double resolution = 7;
+  bool source_timestamp = 8;
+  string mapping_confidence = 9;
+  string hood_id = 10;
+  string chamber_id = 11;
+  string dimm_id = 12;
+  string connector = 13;
+  int32 source_index = 14;
+  google.protobuf.Duration update_period = 15;
+  string calibration_version = 16;
+  FeedbackMode feedback_mode = 17;
+}
+
+message ActuatorCapability {
+  string id = 1;
+  repeated string aliases = 2;
+  string display_name = 3;
+  ActuatorKind kind = 4;
+  string unit = 5;
+  Range command_range = 6;
+  double resolution = 7;
+  ControlMode control_mode = 8;
+  FeedbackMode feedback_mode = 9;
+  bool idempotent = 10;
+  bool one_shot = 11;
+  double safety_default = 12;
+  double max_slew_per_second = 13;
+  bool actual_feedback = 14;
+  string hood_id = 15;
+  string chamber_id = 16;
+  string connector = 17;
+  string notes = 18;
+}
+
+message Capabilities {
+  string device_id = 1;
+  string profile_id = 2;
+  string profile_revision = 3;
+  string protocol_contract_hash = 4;
+  string capability_hash = 5;
+  string api_version = 6;
+  string firmware_version = 7;
+  DataQuality firmware_version_quality = 8;
+  int32 hood_count = 9;
+  int32 chamber_count = 10;
+  repeated SensorCapability sensors = 11;
+  repeated ActuatorCapability actuators = 12;
+  google.protobuf.Duration recommended_sample_period = 13;
+  bool ack_supported = 14;
+  bool status_query_supported = 15;
+  bool position_feedback_supported = 16;
+  bool rpm_feedback_supported = 17;
+  bool device_fault_query_supported = 18;
+  bool limit_readback_supported = 19;
+  string readiness_probe = 20;
+  string notes = 21;
+  TimingCapabilities timing = 22;
+  bool host_fault_reporting_supported = 23;
+  bool device_native_fault_query_supported = 24;
+  string device_fault_source = 25;
+}
+
+message TimingCapabilities {
+  uint32 temperature_transaction_worst_case_ms = 1;
+  uint32 motor_status_worst_case_ms = 2;
+  uint32 control_dispatch_worst_case_ms = 3;
+  uint32 recommended_rpc_deadline_ms = 4;
+  uint32 recommended_action_ttl_ms = 5;
+  uint32 minimum_control_period_ms = 6;
+  uint32 recommended_sample_period_ms = 7;
+}
+
+message CommandedActuator {
+  string id = 1;
+  double commanded_target = 2;
+  DataQuality actual_quality = 3;
+  optional double actual_value = 4;
+  string actual_reason = 5;
+}
+
+message FieldAudit {
+  string id = 1;
+  bool explicit = 2;
+  double raw_value = 3;
+  double before_clamp = 4;
+  double after_clamp = 5;
+  bool clamped = 6;
+  string clamp_reason = 7;
+}
+
+message ActionRecord {
+  string command_id = 1;
+  string client_id = 2;
+  google.protobuf.Timestamp time = 3;
+  ConfirmationStatus confirmation = 4;
+  repeated CommandedActuator actuators = 5;
+  string origin = 6;
+  repeated FieldAudit field_audits = 7;
+  ActionMode action_mode = 8;
+  int32 peer_uid = 9;
+  int32 peer_gid = 10;
+  int32 peer_pid = 11;
+  ActionDispatchState dispatch_state = 12;
+}
+
+message LeaseSummary {
+  string lease_id = 1;
+  uint64 lease_epoch = 2;
+  string holder = 3;
+  google.protobuf.Timestamp expires_at = 4;
+  bool active = 5;
+}
+
+message Snapshot {
+  string device_id = 1;
+  string daemon_instance_id = 2;
+  uint64 device_epoch = 3;
+  uint64 snapshot_seq = 4;
+  uint64 control_revision = 5;
+  uint64 event_id = 6;
+  google.protobuf.Timestamp wall_time = 7;
+  uint64 monotonic_ns = 8;
+  TimeWindow capture_window = 9;
+  DeviceLifecycleState lifecycle = 10;
+  repeated Measurement measurements = 11;
+  repeated CommandedActuator continuous_targets = 12;
+  ActionRecord last_requested = 13;
+  ActionRecord last_accepted = 14;
+  ActionRecord last_dispatched = 15;
+  ConfirmationStatus device_confirmation = 16;
+  repeated Fault active_faults = 17;
+  LeaseSummary lease = 18;
+  uint64 dropped_telemetry_count = 19;
+  bool data_gap = 20;
+  TransportState transport_state = 21;
+  DeviceReadiness device_readiness = 22;
+  SafetyControlMode safety_control_mode = 23;
+}
+
+message Fault {
+  string fault_id = 1;
+  FaultType type = 2;
+  FaultSeverity severity = 3;
+  FaultClass class = 4;
+  google.protobuf.Timestamp first_time = 5;
+  google.protobuf.Timestamp last_time = 6;
+  bool active = 7;
+  bool latched = 8;
+  uint64 count = 9;
+  string device_id = 10;
+  string command_id = 11;
+  string human_reason = 12;
+  map<string, string> diagnostics = 13;
+}
+
+message Event {
+  uint64 event_id = 1;
+  EventKind kind = 2;
+  google.protobuf.Timestamp wall_time = 3;
+  uint64 monotonic_ns = 4;
+  string device_id = 5;
+  Snapshot snapshot = 6;
+  Fault fault = 7;
+  string message = 8;
+  uint64 resume_after_event_id = 9;
+  uint64 dropped_count = 10;
+  uint64 source_event_id = 11;
+  string source_capture_id = 12;
+  string source_device_id = 13;
+  string source_daemon_instance_id = 14;
+  uint64 last_contiguous_event_id = 15;
+}
+
+message ContinuousTarget {
+  string id = 1;
+  double value = 2;
+}
+
+message DiscreteCommand {
+  string id = 1;
+  string name = 2;
+  double value = 3;
+}
+
+message ClampRecord {
+  string id = 1;
+  double original = 2;
+  double limited = 3;
+  string reason = 4;
+}
+
+message ActionBatch {
+  string device_id = 1;
+  string command_id = 2;
+  string lease_id = 3;
+  uint64 lease_epoch = 4;
+  uint64 based_on_snapshot_seq = 5;
+  uint64 expected_control_revision = 6;
+  google.protobuf.Timestamp valid_until = 7;
+  repeated ContinuousTarget continuous_targets = 8;
+  repeated DiscreteCommand discrete_commands = 9;
+  bool allow_clamp = 10;
+  string client_id = 11;
+  string policy_version = 12;
+}
+
+message ActionResult {
+  string command_id = 1;
+  bool accepted = 2;
+  RejectReason reject_reason = 3;
+  string message = 4;
+  repeated ClampRecord clamps = 5;
+  // requested is the raw client fields (original floats, only explicit IDs).
+  ActionRecord requested = 6;
+  ActionRecord accepted_action = 7;
+  ActionRecord dispatched = 8;
+  ConfirmationStatus confirmation = 9;
+  uint64 control_revision = 10;
+  uint64 device_epoch = 11;
+  bool replayed_from_cache = 12;
+  ActionRecord raw_requested = 13;
+  ActionRecord normalized_requested = 14;
+  ActionDispatchState dispatch_state = 15;
+}
+
+message ControlLease {
+  string lease_id = 1;
+  uint64 lease_epoch = 2;
+  string device_id = 3;
+  string holder = 4;
+  google.protobuf.Timestamp created_at = 5;
+  google.protobuf.Timestamp expires_at = 6;
+  google.protobuf.Duration max_ttl = 7;
+  bool active = 8;
+}
+
+message ListDevicesRequest {}
+
+message ListDevicesResponse {
+  repeated DeviceInfo devices = 1;
+}
+
+message GetCapabilitiesRequest {
+  string device_id = 1;
+}
+
+message GetCapabilitiesResponse {
+  Capabilities capabilities = 1;
+}
+
+message GetSnapshotRequest {
+  string device_id = 1;
+}
+
+message GetSnapshotResponse {
+  Snapshot snapshot = 1;
+}
+
+message SubscribeTelemetryRequest {
+  string device_id = 1;
+  uint64 resume_after_event_id = 2;
+}
+
+message SubscribeEventsRequest {
+  string device_id = 1;
+  uint64 resume_after_event_id = 2;
+}
+
+message GetFaultsRequest {
+  string device_id = 1;
+  bool include_inactive = 2;
+}
+
+message GetFaultsResponse {
+  repeated Fault faults = 1;
+  bool device_fault_query_supported = 2;
+  bool host_fault_reporting_supported = 3;
+  bool device_native_fault_query_supported = 4;
+  string device_fault_source = 5;
+}
+
+message WatchHealthRequest {}
+
+message HealthStatus {
+  HostHealth host = 1;
+  repeated DeviceInfo devices = 2;
+  string message = 3;
+  HostHealth observe_service = 4;
+  HostHealth control_service = 5;
+  TransportState transport_state = 6;
+  DeviceReadiness device_readiness = 7;
+  SafetyControlMode safety_control_mode = 8;
+}
+
+message AcquireControlLeaseRequest {
+  string device_id = 1;
+  string holder = 2;
+  google.protobuf.Duration ttl = 3;
+}
+
+message RenewControlLeaseRequest {
+  string device_id = 1;
+  string lease_id = 2;
+  uint64 lease_epoch = 3;
+  google.protobuf.Duration ttl = 4;
+}
+
+message ReleaseControlLeaseRequest {
+  string device_id = 1;
+  string lease_id = 2;
+  uint64 lease_epoch = 3;
+}
+
+message LeaseResponse {
+  ControlLease lease = 1;
+}
+
+message ValidateActionRequest {
+  ActionBatch batch = 1;
+}
+
+message ApplyActionRequest {
+  ActionBatch batch = 1;
+}
+
+message EnterSafeModeRequest {
+  string device_id = 1;
+  string lease_id = 2;
+  uint64 lease_epoch = 3;
+  string reason = 4;
+}
+
+message ResumeFromSafeRequest {
+  string device_id = 1;
+  string lease_id = 2;
+  uint64 lease_epoch = 3;
+  ActionBatch batch = 4;
+}
+
+message StepReplayRequest {
+  string device_id = 1;
+}
+
+message StepReplayResponse {
+  bool advanced = 1;
+  Event event = 2;
+  Snapshot snapshot = 3;
+  string message = 4;
+}
+
+service ObserveService {
+  rpc ListDevices(ListDevicesRequest) returns (ListDevicesResponse);
+  rpc GetCapabilities(GetCapabilitiesRequest) returns (GetCapabilitiesResponse);
+  rpc GetSnapshot(GetSnapshotRequest) returns (GetSnapshotResponse);
+  rpc SubscribeTelemetry(SubscribeTelemetryRequest) returns (stream Snapshot);
+  rpc SubscribeEvents(SubscribeEventsRequest) returns (stream Event);
+  rpc GetFaults(GetFaultsRequest) returns (GetFaultsResponse);
+  rpc WatchHealth(WatchHealthRequest) returns (stream HealthStatus);
+  // StepReplay advances a replay backend by one capture record. It is a
+  // client-triggered single step, not a cancelled internal ticker wait.
+  rpc StepReplay(StepReplayRequest) returns (StepReplayResponse);
+}
+
+service ControlService {
+  rpc AcquireControlLease(AcquireControlLeaseRequest) returns (LeaseResponse);
+  rpc RenewControlLease(RenewControlLeaseRequest) returns (LeaseResponse);
+  rpc ReleaseControlLease(ReleaseControlLeaseRequest) returns (LeaseResponse);
+  rpc ValidateAction(ValidateActionRequest) returns (ActionResult);
+  rpc ApplyAction(ApplyActionRequest) returns (ActionResult);
+  rpc EnterSafeMode(EnterSafeModeRequest) returns (ActionResult);
+  rpc ResumeFromSafe(ResumeFromSafeRequest) returns (ActionResult);
+}

+ 22 - 0
buf.yaml

@@ -0,0 +1,22 @@
+# L0 proto lint/breaking. Vendored google/protobuf copies are excluded;
+# buf resolves well-known types. Do not treat this file as a product runtime dep.
+version: v2
+modules:
+  - path: api/proto
+    excludes:
+      - api/proto/google
+      - api/proto/hth.api.v1.desc.prev
+lint:
+  use:
+    - STANDARD
+  except:
+    # Style-only; keep published hth.api.v1 names. Syntax/package/import stay on.
+    - ENUM_VALUE_PREFIX
+    - ENUM_ZERO_VALUE_SUFFIX
+    - PACKAGE_DIRECTORY_MATCH
+    - RPC_REQUEST_STANDARD_NAME
+    - RPC_RESPONSE_STANDARD_NAME
+    - RPC_REQUEST_RESPONSE_UNIQUE
+breaking:
+  use:
+    - FILE

+ 176 - 0
cmd/hth-capture/main.go

@@ -0,0 +1,176 @@
+package main
+
+import (
+	"context"
+	"flag"
+	"fmt"
+	"os"
+	"os/signal"
+	"syscall"
+	"time"
+
+	"hth/internal/app"
+	"hth/internal/capture"
+	hthv1 "hth/internal/gen/hth/api/v1"
+	"hth/internal/grpcserver"
+)
+
+func main() {
+	fs := flag.NewFlagSet("hth-capture", flag.ExitOnError)
+	observe := fs.String("observe-sock", "/tmp/hth-mock/observe.sock", "observe unix socket")
+	deviceID := fs.String("device", "prod2u-0", "device id")
+	out := fs.String("out", "", "output directory")
+	dur := fs.Duration("duration", 3*time.Second, "capture duration")
+	_ = fs.Parse(os.Args[1:])
+	if *out == "" {
+		fmt.Fprintln(os.Stderr, "hth-capture: --out required")
+		os.Exit(2)
+	}
+	if err := os.MkdirAll(*out, 0o755); err != nil {
+		fmt.Fprintln(os.Stderr, err)
+		os.Exit(1)
+	}
+	conn, err := grpcserver.DialUnix(*observe, 5*time.Second)
+	if err != nil {
+		fmt.Fprintln(os.Stderr, err)
+		os.Exit(1)
+	}
+	defer conn.Close()
+	cli := hthv1.NewObserveServiceClient(conn)
+	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
+	defer stop()
+	ctx, cancel := context.WithTimeout(ctx, *dur)
+	defer cancel()
+
+	caps, err := cli.GetCapabilities(ctx, &hthv1.GetCapabilitiesRequest{DeviceId: *deviceID})
+	if err != nil {
+		fmt.Fprintln(os.Stderr, err)
+		os.Exit(1)
+	}
+	man := capture.Manifest{
+		APIVersion:          app.APIVersion,
+		APISchemaVersion:    app.APIVersion,
+		ProfileHash:         caps.Capabilities.GetProtocolContractHash(),
+		ProfileContractHash: caps.Capabilities.GetProtocolContractHash(),
+		ProfileID:           caps.Capabilities.GetProfileId(),
+		ProfileRevision:     caps.Capabilities.GetProfileRevision(),
+		CapabilityHash:      caps.Capabilities.GetCapabilityHash(),
+		DeviceID:            *deviceID,
+		StartedAt:           time.Now().UTC(),
+		StartTime:           time.Now().UTC(),
+		Status:              capture.StatusIncomplete,
+		CompletionStatus:    capture.StatusIncomplete,
+	}
+	if err := capture.WriteManifest(*out, man); err != nil {
+		fmt.Fprintln(os.Stderr, err)
+		os.Exit(1)
+	}
+	f, err := os.Create(capture.RecordsPath(*out))
+	if err != nil {
+		fmt.Fprintln(os.Stderr, err)
+		os.Exit(1)
+	}
+	defer func() { _ = f.Close() }()
+
+	ev, err := cli.SubscribeEvents(ctx, &hthv1.SubscribeEventsRequest{DeviceId: *deviceID})
+	if err != nil {
+		fmt.Fprintln(os.Stderr, err)
+		os.Exit(1)
+	}
+	n := 0
+	firstID, lastID := uint64(0), uint64(0)
+	writeErr := error(nil)
+	recvErr := error(nil)
+	userCancel := false
+	durationElapsed := false
+	for {
+		e, err := ev.Recv()
+		if err != nil {
+			recvErr = err
+			switch {
+			case ctx.Err() == context.DeadlineExceeded:
+				durationElapsed = true
+			case ctx.Err() == context.Canceled:
+				userCancel = true
+			}
+			break
+		}
+		rec, err := capture.EventRecord(e)
+		if err != nil {
+			writeErr = err
+			break
+		}
+		if err := capture.AppendRecord(f, rec); err != nil {
+			writeErr = err
+			break
+		}
+		sid := rec.SourceID()
+		if n == 0 {
+			firstID = sid
+		}
+		lastID = sid
+		n++
+	}
+	closeErr := f.Close()
+	syncErr := error(nil)
+	if closeErr == nil {
+		// Hash only after a successful close.
+		if sum, err := capture.HashFile(capture.RecordsPath(*out)); err == nil {
+			man.RecordsSHA256 = sum
+		} else {
+			syncErr = err
+		}
+	} else {
+		syncErr = closeErr
+	}
+	man.EndedAt = time.Now().UTC()
+	man.EndTime = man.EndedAt
+	man.StartTime = man.StartedAt
+	man.APISchemaVersion = man.APIVersion
+	man.RecordCount = n
+	man.FirstSourceEventID = firstID
+	man.LastSourceEventID = lastID
+	switch {
+	case writeErr != nil || syncErr != nil:
+		man.Status = capture.StatusIncomplete
+		man.CompletionStatus = capture.StatusIncomplete
+		if writeErr != nil {
+			man.IncompleteReason = writeErr.Error()
+		} else {
+			man.IncompleteReason = syncErr.Error()
+		}
+		man.CompletionReason = man.IncompleteReason
+	case durationElapsed && n > 0:
+		man.Status = capture.StatusComplete
+		man.CompletionStatus = capture.StatusComplete
+		man.CompletionReason = "duration elapsed"
+	case userCancel:
+		man.Status = capture.StatusIncomplete
+		man.CompletionStatus = capture.StatusIncomplete
+		man.IncompleteReason = "user cancel"
+		man.CompletionReason = man.IncompleteReason
+	case n == 0:
+		man.Status = capture.StatusIncomplete
+		man.CompletionStatus = capture.StatusIncomplete
+		man.IncompleteReason = "zero records"
+		man.CompletionReason = man.IncompleteReason
+	default:
+		man.Status = capture.StatusIncomplete
+		man.CompletionStatus = capture.StatusIncomplete
+		if recvErr != nil {
+			man.IncompleteReason = "stream ended: " + recvErr.Error()
+		} else {
+			man.IncompleteReason = "unexpected stream end"
+		}
+		man.CompletionReason = man.IncompleteReason
+	}
+	if err := capture.WriteManifest(*out, man); err != nil {
+		fmt.Fprintf(os.Stderr, "hth-capture manifest failed after %d records: %v\n", n, err)
+		os.Exit(1)
+	}
+	if writeErr != nil || syncErr != nil || man.Status != capture.StatusComplete {
+		fmt.Fprintf(os.Stderr, "hth-capture incomplete after %d records status=%s recv=%v write=%v close=%v\n", n, man.Status, recvErr, writeErr, syncErr)
+		os.Exit(1)
+	}
+	fmt.Printf("wrote %d records to %s status=%s\n", n, *out, man.Status)
+}

+ 274 - 0
cmd/hthctl/main.go

@@ -0,0 +1,274 @@
+package main
+
+import (
+	"context"
+	"flag"
+	"fmt"
+	"os"
+	"strings"
+	"time"
+
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/health/grpc_health_v1"
+	"google.golang.org/protobuf/encoding/protojson"
+	"google.golang.org/protobuf/proto"
+	"google.golang.org/protobuf/types/known/durationpb"
+	"google.golang.org/protobuf/types/known/timestamppb"
+	"hth/internal/app"
+	"hth/internal/config"
+	hthv1 "hth/internal/gen/hth/api/v1"
+	"hth/internal/grpcserver"
+	"hth/internal/ids"
+	"hth/internal/profile"
+)
+
+func main() {
+	fs := flag.NewFlagSet("hthctl", flag.ExitOnError)
+	observe := fs.String("observe-sock", "/tmp/hth-mock/observe.sock", "observe unix socket")
+	control := fs.String("control-sock", "/tmp/hth-mock/control.sock", "control unix socket")
+	deviceID := fs.String("device", "prod2u-0", "device id")
+	cfgPath := fs.String("config", "", "optional local config for doctor")
+	realHW := fs.Bool("i-understand-this-is-real-hardware", false, "required for non-mock endpoints")
+	timeout := fs.Duration("timeout", 5*time.Second, "rpc timeout")
+	count := fs.Int("count", 0, "watch/events count (0=until interrupt)")
+	holder := fs.String("holder", "hthctl", "lease holder")
+	ttl := fs.Duration("ttl", 10*time.Second, "lease ttl")
+	file := fs.String("file", "", "JSON ActionBatch for validate-action")
+	allowClamp := fs.Bool("allow-clamp", false, "allow clamp on validate/apply")
+	_ = fs.Parse(os.Args[1:])
+	args := fs.Args()
+	if len(args) < 1 {
+		fmt.Fprintln(os.Stderr, "usage: hthctl [flags] doctor|devices|capabilities|snapshot|watch|events|faults|health|validate-action|apply-action|enter-safe-mode|step-replay")
+		os.Exit(2)
+	}
+	cmd := args[0]
+	if cmd != "doctor" || *cfgPath == "" {
+		if err := requireRealAck(*observe, *control, *realHW); err != nil {
+			fmt.Fprintln(os.Stderr, err)
+			os.Exit(2)
+		}
+	}
+	ctx, cancel := context.WithTimeout(context.Background(), *timeout)
+	defer cancel()
+	switch cmd {
+	case "doctor":
+		fatal(runDoctor(ctx, *cfgPath, *observe))
+	case "devices":
+		c := observeClient(*observe, *timeout)
+		resp, err := c.ListDevices(ctx, &hthv1.ListDevicesRequest{})
+		fatal(err)
+		printMsg(resp)
+	case "capabilities":
+		c := observeClient(*observe, *timeout)
+		resp, err := c.GetCapabilities(ctx, &hthv1.GetCapabilitiesRequest{DeviceId: *deviceID})
+		fatal(err)
+		printMsg(resp)
+	case "snapshot":
+		c := observeClient(*observe, *timeout)
+		resp, err := c.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: *deviceID})
+		fatal(err)
+		printMsg(resp)
+	case "watch":
+		c := observeClient(*observe, *timeout)
+		st, err := c.SubscribeTelemetry(context.Background(), &hthv1.SubscribeTelemetryRequest{DeviceId: *deviceID})
+		fatal(err)
+		n := 0
+		for {
+			s, err := st.Recv()
+			fatal(err)
+			printMsg(s)
+			n++
+			if *count > 0 && n >= *count {
+				return
+			}
+		}
+	case "events":
+		c := observeClient(*observe, *timeout)
+		st, err := c.SubscribeEvents(context.Background(), &hthv1.SubscribeEventsRequest{DeviceId: *deviceID})
+		fatal(err)
+		n := 0
+		for {
+			e, err := st.Recv()
+			fatal(err)
+			printMsg(e)
+			n++
+			if *count > 0 && n >= *count {
+				return
+			}
+		}
+	case "faults":
+		c := observeClient(*observe, *timeout)
+		resp, err := c.GetFaults(ctx, &hthv1.GetFaultsRequest{DeviceId: *deviceID, IncludeInactive: true})
+		fatal(err)
+		printMsg(resp)
+	case "health":
+		conn := mustDial(*observe, *timeout)
+		defer conn.Close()
+		hc := grpc_health_v1.NewHealthClient(conn)
+		resp, err := hc.Check(ctx, &grpc_health_v1.HealthCheckRequest{})
+		fatal(err)
+		fmt.Println(resp.Status.String())
+		oc := hthv1.NewObserveServiceClient(conn)
+		st, err := oc.WatchHealth(ctx, &hthv1.WatchHealthRequest{})
+		fatal(err)
+		msg, err := st.Recv()
+		fatal(err)
+		printMsg(msg)
+	case "validate-action":
+		batch := loadBatch(*file, *deviceID, *allowClamp)
+		c := controlClient(*control, *timeout)
+		res, err := c.ValidateAction(ctx, &hthv1.ValidateActionRequest{Batch: batch})
+		fatal(err)
+		printAction(res)
+	case "apply-action":
+		cc := controlClient(*control, *timeout)
+		oc := observeClient(*observe, *timeout)
+		lease, err := cc.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
+			DeviceId: *deviceID, Holder: *holder, Ttl: durationpb.New(*ttl),
+		})
+		fatal(err)
+		snap, err := oc.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: *deviceID})
+		fatal(err)
+		batch := loadBatch(*file, *deviceID, *allowClamp)
+		batch.LeaseId = lease.Lease.LeaseId
+		batch.LeaseEpoch = lease.Lease.LeaseEpoch
+		batch.BasedOnSnapshotSeq = snap.Snapshot.GetSnapshotSeq()
+		batch.ExpectedControlRevision = snap.Snapshot.GetControlRevision()
+		if batch.ValidUntil == nil {
+			batch.ValidUntil = timestamppb.New(time.Now().Add(*timeout))
+		}
+		if batch.CommandId == "" || batch.CommandId == "hthctl-validate" {
+			batch.CommandId = fmt.Sprintf("hthctl-%d", time.Now().UnixNano())
+		}
+		res, err := cc.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: batch})
+		fatal(err)
+		printAction(res)
+	case "enter-safe-mode":
+		cc := controlClient(*control, *timeout)
+		lease, err := cc.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
+			DeviceId: *deviceID, Holder: *holder, Ttl: durationpb.New(*ttl),
+		})
+		fatal(err)
+		res, err := cc.EnterSafeMode(ctx, &hthv1.EnterSafeModeRequest{
+			DeviceId: *deviceID, LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch, Reason: "hthctl",
+		})
+		fatal(err)
+		printAction(res)
+	case "step-replay":
+		oc := observeClient(*observe, *timeout)
+		res, err := oc.StepReplay(ctx, &hthv1.StepReplayRequest{DeviceId: *deviceID})
+		fatal(err)
+		printMsg(res)
+	default:
+		fmt.Fprintln(os.Stderr, "unknown command", cmd)
+		os.Exit(2)
+	}
+}
+
+func requireRealAck(observe, control string, ack bool) error {
+	if isMock(observe) && isMock(control) {
+		return nil
+	}
+	if ack {
+		return nil
+	}
+	return fmt.Errorf("refusing non-mock endpoint %s / %s without --i-understand-this-is-real-hardware; hthctl never opens serial", observe, control)
+}
+
+func isMock(path string) bool {
+	p := strings.ToLower(path)
+	return strings.Contains(p, "mock") || strings.Contains(p, "/tmp/")
+}
+
+func runDoctor(ctx context.Context, cfgPath, observe string) error {
+	if cfgPath != "" {
+		cfg, err := config.Load(cfgPath)
+		if err != nil {
+			return err
+		}
+		p, err := profile.LoadStrict(cfg.Profile)
+		if err != nil {
+			return err
+		}
+		if err := cfg.Validate(p); err != nil {
+			return err
+		}
+		fmt.Print(app.DoctorText(cfg, p))
+	}
+	conn, err := grpcserver.DialUnix(observe, 2*time.Second)
+	if err != nil {
+		if cfgPath != "" {
+			fmt.Println("live observe socket: not connected (", err, ")")
+			return nil
+		}
+		return err
+	}
+	defer conn.Close()
+	hc := grpc_health_v1.NewHealthClient(conn)
+	st, err := hc.Check(ctx, &grpc_health_v1.HealthCheckRequest{})
+	if err != nil {
+		return err
+	}
+	fmt.Println("grpc_health", st.Status.String())
+	return nil
+}
+
+func observeClient(path string, d time.Duration) hthv1.ObserveServiceClient {
+	return hthv1.NewObserveServiceClient(mustDial(path, d))
+}
+
+func controlClient(path string, d time.Duration) hthv1.ControlServiceClient {
+	return hthv1.NewControlServiceClient(mustDial(path, d))
+}
+
+func mustDial(path string, d time.Duration) *grpc.ClientConn {
+	c, err := grpcserver.DialUnix(path, d)
+	fatal(err)
+	return c
+}
+
+func printMsg(m proto.Message) {
+	b, err := protojson.MarshalOptions{Multiline: true, UseProtoNames: true}.Marshal(m)
+	if err != nil {
+		fmt.Println(err)
+		return
+	}
+	fmt.Println(string(b))
+}
+
+func printAction(res *hthv1.ActionResult) {
+	fmt.Println("accepted", res.Accepted, "confirmation", res.Confirmation.String(), "reject", res.RejectReason.String())
+	fmt.Println("message", res.Message)
+	fmt.Println("replayed_from_cache", res.ReplayedFromCache)
+	printNamed("requested", res.Requested)
+	printNamed("accepted", res.AcceptedAction)
+	printNamed("dispatched", res.Dispatched)
+}
+
+func printNamed(name string, rec *hthv1.ActionRecord) {
+	if rec == nil {
+		fmt.Println(name, "(none)")
+		return
+	}
+	b, _ := protojson.MarshalOptions{UseProtoNames: true}.Marshal(rec)
+	fmt.Println(name, string(b))
+}
+
+func loadBatch(path, deviceID string, clamp bool) *hthv1.ActionBatch {
+	b := &hthv1.ActionBatch{DeviceId: deviceID, CommandId: "hthctl-validate", AllowClamp: clamp, ClientId: "hthctl"}
+	if path == "" {
+		b.ContinuousTargets = []*hthv1.ContinuousTarget{{Id: ids.Fan1, Value: 10}}
+		return b
+	}
+	raw, err := os.ReadFile(path)
+	fatal(err)
+	fatal(protojson.Unmarshal(raw, b))
+	return b
+}
+
+func fatal(err error) {
+	if err != nil {
+		fmt.Fprintln(os.Stderr, err)
+		os.Exit(1)
+	}
+}

+ 44 - 0
cmd/hthd/main.go

@@ -0,0 +1,44 @@
+package main
+
+import (
+	"context"
+	"flag"
+	"fmt"
+	"log/slog"
+	"os"
+	"os/signal"
+	"syscall"
+
+	"hth/internal/app"
+)
+
+func main() {
+	fs := flag.NewFlagSet("hthd", flag.ExitOnError)
+	cfgPath := fs.String("config", "", "path to hthd YAML config")
+	backend := fs.String("backend", "", "override backend: mock|serial|replay")
+	check := fs.Bool("check-config", false, "validate config and profile then exit")
+	_ = fs.Parse(os.Args[1:])
+	if *cfgPath == "" {
+		fmt.Fprintln(os.Stderr, "hthd: --config is required")
+		os.Exit(2)
+	}
+	if *check {
+		if err := app.CheckConfig(*cfgPath, *backend); err != nil {
+			fmt.Fprintln(os.Stderr, err)
+			os.Exit(1)
+		}
+		return
+	}
+	log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelInfo}))
+	a, err := app.New(*cfgPath, *backend, log)
+	if err != nil {
+		fmt.Fprintln(os.Stderr, err)
+		os.Exit(1)
+	}
+	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
+	defer stop()
+	if err := a.Run(ctx); err != nil {
+		fmt.Fprintln(os.Stderr, err)
+		os.Exit(1)
+	}
+}

+ 2 - 0
contracts/evidence/RTL_REF.txt

@@ -0,0 +1,2 @@
+copied=2026-08-17T14:45:29Z
+unknown

+ 3 - 0
contracts/evidence/SHA256SUMS

@@ -0,0 +1,3 @@
+cf98d173860b42bbd1ad18d96ff5d257850ced262fb5eb501c352fc0ab4fc03b  host-contract.json
+35df83761f5e7b4c9dd24709e02d57ee119e6f8fd3b65f13e7a19ada8c689926  golden-vectors.json
+320bc6bccc943d183e374db0665b8530ac573198bc15fbc8f514af4a00f3cfd7  RTL_REF.txt

+ 17 - 0
contracts/evidence/golden-vectors.json

@@ -0,0 +1,17 @@
+{
+  "all_invalid_temperature": "A55A821BFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA745",
+  "get_motor_status": "A55A03005C48",
+  "get_temperature": "A55A02006D7B",
+  "motor_status_data_example": "A55A831F4702250000000000E8030002250000000000E8030002250000000000E803005226",
+  "notes": {
+    "get_motor_status": "Exact request frame A55A03005C48.",
+    "set_all_all_zero_full_open": "Legal SET_ALL: FAN/PTC 0 and doors 0/0/0 = full open; not a jog heartbeat no-op.",
+    "set_all_door_0x65_rejected": "Door percent 0x65 (101) is out of 0..100 and must be rejected."
+  },
+  "set_all_all_zero_full_open": "A55A010B00000000000000000000005873",
+  "set_all_door_0x65_rejected": "65",
+  "set_all_doors_0_percent": "A55A010B0A141E2800193264000000D584",
+  "set_all_doors_100_percent": "A55A010B0A141E2800193264646464B228",
+  "set_all_doors_50_percent": "A55A010B0A141E2800193264323232F65A",
+  "set_all_legacy_14_rejected": "0E"
+}

+ 547 - 0
contracts/evidence/host-contract.json

@@ -0,0 +1,547 @@
+{
+  "axis_count": 3,
+  "commands": {
+    "get_motor_status": {
+      "payload_length": 0,
+      "response": "MOTOR_STATUS_DATA",
+      "type": "0x03"
+    },
+    "get_temperature": {
+      "payload_length": 0,
+      "response": "TEMPERATURE_DATA",
+      "type": "0x02"
+    },
+    "motor_status_data": {
+      "frame_length": 37,
+      "layout": {
+        "axis_fields": [
+          "state",
+          "flags",
+          "requested_percent",
+          "current_position_le16",
+          "target_position_le16",
+          "travel_steps_le16",
+          "fault_code"
+        ],
+        "axis_order": [
+          "x",
+          "y",
+          "z"
+        ],
+        "byte0_global": {
+          "bit0_2": "calibrated_mask_xyz",
+          "bit3_5": "fault_mask_xyz",
+          "bit6": "startup_complete",
+          "bit7": "watchdog_tripped"
+        },
+        "fault_codes": {
+          "BOTH_LIMITS_ACTIVE": 1,
+          "CAL_CLOSE_TIMEOUT": 2,
+          "CAL_OPEN_TIMEOUT": 3,
+          "ENDPOINT_TIMEOUT": 5,
+          "INVALID_ZERO_OR_TINY_TRAVEL": 4,
+          "NONE": 0
+        },
+        "flags": {
+          "calibrated": 2,
+          "close_limit": 1,
+          "endpoint_mode": 4,
+          "moving": 3,
+          "open_limit": 0,
+          "replan_pending": 6,
+          "reserved": 7,
+          "target_valid": 5
+        },
+        "per_axis_bytes": 10,
+        "states": {
+          "CAL_MEASURE_OPEN": 1,
+          "CAL_SEEK_CLOSE": 0,
+          "FAULT": 6,
+          "IDLE": 2,
+          "MOVE_CLOSE": 4,
+          "MOVE_OPEN": 3,
+          "WAIT_REPLAN": 5
+        }
+      },
+      "payload_length": 31,
+      "type": "0x83"
+    },
+    "set_all": {
+      "door_percent_range": [
+        0,
+        100
+      ],
+      "door_percent_semantics": {
+        "0": "full_open_endpoint",
+        "0x65": "rejected_out_of_range",
+        "100": "full_close_endpoint",
+        "1_to_99": "mid_percent_close",
+        "all_zero_frame": "fan_ptc_zero_and_all_doors_full_open_not_heartbeat"
+      },
+      "duty_range": [
+        0,
+        100
+      ],
+      "field_order": [
+        "fan_chamber_1",
+        "fan_chamber_2",
+        "fan_chamber_3",
+        "fan_chamber_4",
+        "ptc_chamber_1",
+        "ptc_chamber_2",
+        "ptc_chamber_3",
+        "ptc_chamber_4",
+        "door_z_percent",
+        "door_x_percent",
+        "door_y_percent"
+      ],
+      "payload_length": 11,
+      "response": "none",
+      "type": "0x01"
+    },
+    "temperature_data": {
+      "frame_length": 33,
+      "payload_length": 27,
+      "type": "0x82"
+    }
+  },
+  "limit_count": 6,
+  "limits": {
+    "active_level": "high",
+    "channels": [
+      {
+        "ball": "A5",
+        "connector": "CON12",
+        "connector_pin": 1,
+        "name": "x_limit_ls",
+        "side": "low"
+      },
+      {
+        "ball": "B6",
+        "connector": "CON12",
+        "connector_pin": 2,
+        "name": "x_limit_hs",
+        "side": "high"
+      },
+      {
+        "ball": "C8",
+        "connector": "CON12",
+        "connector_pin": 3,
+        "name": "y_limit_ls",
+        "side": "low"
+      },
+      {
+        "ball": "A8",
+        "connector": "CON12",
+        "connector_pin": 4,
+        "name": "y_limit_hs",
+        "side": "high"
+      },
+      {
+        "ball": "K16",
+        "connector": "CON129",
+        "connector_pin": 1,
+        "name": "z_limit_ls",
+        "side": "low"
+      },
+      {
+        "ball": "J15",
+        "connector": "CON129",
+        "connector_pin": 2,
+        "name": "z_limit_hs",
+        "side": "high"
+      }
+    ],
+    "close_limit_is_ls": [
+      true,
+      true,
+      true
+    ],
+    "functional_use": true,
+    "limit_active_high": [
+      true,
+      true,
+      true
+    ],
+    "limit_count": 6,
+    "runtime_use": true,
+    "startup": {
+      "additional_rising_edges_after_synchronized_limit": 0,
+      "axis_order": [
+        "x",
+        "y",
+        "z"
+      ],
+      "enabled": true,
+      "fault_lock_until_reset": true,
+      "final_position": "open",
+      "limit_stop_during_move": true,
+      "max_steps": 5000,
+      "min_travel_steps": 2,
+      "mode": "seek_close_then_measure_open",
+      "partial_axis_failure_allowed": true,
+      "runtime_limit_use": true,
+      "step_rate_hz": 1000,
+      "stop_semantics": "truncate_current_high_pulse_immediately_after_synchronized_limit"
+    }
+  },
+  "motors": {
+    "close_dir_value": 1,
+    "count": 3,
+    "dir_close_level": [
+      1,
+      1,
+      1
+    ],
+    "dir_setup_cycles": 25000,
+    "enable_n": {
+      "active_level": "low",
+      "ball": "C11",
+      "connector": "CON120",
+      "connector_pin": 2,
+      "notes": "NPN open-collector invert at board; FPGA drives constant 1 so connector EN is permanently asserted.",
+      "policy": "permanent_high"
+    },
+    "execution": "overlap",
+    "mapping": {
+      "x": {
+        "axis": "x",
+        "dir_ball": "J6",
+        "dir_connector": "CON142",
+        "dir_connector_pin": 3,
+        "role": "door",
+        "step_ball": "H4",
+        "step_connector": "CON142",
+        "step_connector_pin": 2
+      },
+      "y": {
+        "axis": "y",
+        "dir_ball": "A4",
+        "dir_connector": "CON126",
+        "dir_connector_pin": 3,
+        "role": "door",
+        "step_ball": "E7",
+        "step_connector": "CON126",
+        "step_connector_pin": 2
+      },
+      "z": {
+        "axis": "z",
+        "dir_ball": "A12",
+        "dir_connector": "CON127",
+        "dir_connector_pin": 3,
+        "role": "door",
+        "step_ball": "B4",
+        "step_connector": "CON127",
+        "step_connector_pin": 2
+      }
+    },
+    "open_dir_value": 0,
+    "order": [
+      "x",
+      "y",
+      "z"
+    ],
+    "positioning": {
+      "close_endpoint_percent": 100,
+      "command_interrupt": "finish_current_high_pulse_then_replan",
+      "endpoint_guard_extra_steps": 500,
+      "idempotent_same_target": true,
+      "latest_wins": true,
+      "mid_clamp": "1_to_travel_minus_1",
+      "mid_percent_max": 99,
+      "mid_percent_min": 1,
+      "mode": "percent_close",
+      "open_endpoint_percent": 0,
+      "percent_max": 100,
+      "percent_min": 0,
+      "planner_count": 1,
+      "rounding": "half_up",
+      "shared_percent_planner": true
+    },
+    "role": "door",
+    "step_half_cycles": 12500,
+    "step_rate_hz": 1000
+  },
+  "outputs": {
+    "boot_targets": {
+      "fan": 10,
+      "ptc": 0
+    },
+    "chamber_ptc_count": 4,
+    "chamber_ptc_pairs": [
+      {
+        "chamber": 1,
+        "ptc_indices": [
+          0,
+          1
+        ]
+      },
+      {
+        "chamber": 2,
+        "ptc_indices": [
+          2,
+          3
+        ]
+      },
+      {
+        "chamber": 3,
+        "ptc_indices": [
+          4,
+          5
+        ]
+      },
+      {
+        "chamber": 4,
+        "ptc_indices": [
+          6,
+          7
+        ]
+      }
+    ],
+    "fan_board_inverts": true,
+    "fan_channels": [
+      {
+        "ball": "B1",
+        "board_signal": "FAN_PWM3",
+        "connector": "CON25",
+        "connector_pin": 7,
+        "index": 0,
+        "name": "fan1",
+        "polarity": "active_low",
+        "signal": "fan_pwm_out[0]"
+      },
+      {
+        "ball": "C4",
+        "board_signal": "FAN_PWM1",
+        "connector": "CON8",
+        "connector_pin": 7,
+        "index": 1,
+        "name": "fan2",
+        "polarity": "active_low",
+        "signal": "fan_pwm_out[1]"
+      },
+      {
+        "ball": "B5",
+        "board_signal": "FAN_PWM2",
+        "connector": "CON24",
+        "connector_pin": 7,
+        "index": 2,
+        "name": "fan3",
+        "polarity": "active_low",
+        "signal": "fan_pwm_out[2]"
+      },
+      {
+        "ball": "A14",
+        "board_signal": "FAN_PWM4",
+        "connector": "CON26",
+        "connector_pin": 7,
+        "index": 3,
+        "name": "fan4",
+        "polarity": "active_low",
+        "signal": "fan_pwm_out[3]"
+      }
+    ],
+    "fan_connector_active_level": "high",
+    "fan_count": 4,
+    "fan_default": 10,
+    "fan_polarity": "active_low",
+    "ptc_channels": [
+      {
+        "ball": "G16",
+        "board_signal": "HEAT2",
+        "connector": "CON18",
+        "connector_pin": 3,
+        "index": 0,
+        "name": "ptc1",
+        "polarity": "active_high",
+        "signal": "ptc_pwm_out[0]"
+      },
+      {
+        "ball": "F16",
+        "board_signal": "HEAT1",
+        "connector": "CON18",
+        "connector_pin": 1,
+        "index": 1,
+        "name": "ptc2",
+        "polarity": "active_high",
+        "signal": "ptc_pwm_out[1]"
+      },
+      {
+        "ball": "N1",
+        "board_signal": "HEAT8",
+        "connector": "CON27",
+        "connector_pin": 3,
+        "index": 2,
+        "name": "ptc3",
+        "polarity": "active_high",
+        "signal": "ptc_pwm_out[2]"
+      },
+      {
+        "ball": "M1",
+        "board_signal": "HEAT7",
+        "connector": "CON27",
+        "connector_pin": 1,
+        "index": 3,
+        "name": "ptc4",
+        "polarity": "active_high",
+        "signal": "ptc_pwm_out[3]"
+      },
+      {
+        "ball": "R16",
+        "board_signal": "HEAT14",
+        "connector": "CON28",
+        "connector_pin": 3,
+        "index": 4,
+        "name": "ptc5",
+        "polarity": "active_high",
+        "signal": "ptc_pwm_out[4]"
+      },
+      {
+        "ball": "P16",
+        "board_signal": "HEAT13",
+        "connector": "CON28",
+        "connector_pin": 1,
+        "index": 5,
+        "name": "ptc6",
+        "polarity": "active_high",
+        "signal": "ptc_pwm_out[5]"
+      },
+      {
+        "ball": "P9",
+        "board_signal": "HEAT20",
+        "connector": "CON29",
+        "connector_pin": 3,
+        "index": 6,
+        "name": "ptc7",
+        "polarity": "active_high",
+        "signal": "ptc_pwm_out[6]"
+      },
+      {
+        "ball": "T9",
+        "board_signal": "HEAT19",
+        "connector": "CON29",
+        "connector_pin": 1,
+        "index": 7,
+        "name": "ptc8",
+        "polarity": "active_high",
+        "signal": "ptc_pwm_out[7]"
+      }
+    ],
+    "ptc_count": 8,
+    "ptc_default": 0,
+    "ptc_polarity": "active_high",
+    "pwm_actual_frequency_hz": 19.993602047,
+    "pwm_bits": 8,
+    "pwm_frequency_hz": 20,
+    "pwm_internal_width": 7,
+    "pwm_max_duty": 100,
+    "pwm_phase_count": 100,
+    "pwm_slot_clks": 1042
+  },
+  "profile": "prod2u-normal-multiproject-115200-v1",
+  "project_id": "prod2u-door-temp",
+  "protocol": {
+    "commands": {
+      "get_motor_status": 3,
+      "get_temperature": 2,
+      "motor_status_data": 131,
+      "set_all": 1,
+      "temperature_data": 130
+    },
+    "crc": {
+      "coverage": "type_length_payload",
+      "initial": 65535,
+      "name": "CRC-16/CCITT-FALSE",
+      "polynomial": 4129,
+      "reflect_input": false,
+      "reflect_output": false,
+      "wire_order": "little",
+      "xor_output": 0
+    },
+    "get_motor_status": {
+      "payload_length": 0,
+      "response": "motor_status_data"
+    },
+    "header_hex": "A55A",
+    "motor_status_data": {
+      "frame_length": 37,
+      "layout": "host-contract",
+      "payload_length": 31
+    },
+    "set_all": {
+      "chamber_ptc_count": 4,
+      "chamber_ptc_offset": 4,
+      "door_percent_max": 100,
+      "door_percent_min": 0,
+      "door_percent_rejected_example": 101,
+      "duty_max": 100,
+      "duty_min": 0,
+      "exhaust_x_offset": 9,
+      "exhaust_y_offset": 10,
+      "fan_offset": 0,
+      "legacy_payload_length_rejected": 14,
+      "payload_length": 11,
+      "response": "none",
+      "z_door_offset": 8
+    },
+    "temperature_data": {
+      "frame_length": 33,
+      "payload_length": 27
+    }
+  },
+  "runtime_limit_use": true,
+  "schema": "prod2u-simple-host-contract-v1",
+  "temperature": {
+    "bus": "i2c",
+    "conversion": {
+      "profile": "ct7428-msb-integer",
+      "raw_shift": 7,
+      "raw_width": 9,
+      "reject_sign_bit": true
+    },
+    "device": "CT7428",
+    "device_addresses": [
+      73,
+      72,
+      75
+    ],
+    "invalid_value": 255,
+    "maximum_celsius": 150,
+    "registers": [
+      0,
+      1,
+      2,
+      3,
+      4,
+      5,
+      6,
+      7,
+      8
+    ],
+    "scl_ball": "M8",
+    "sda_ball": "N9",
+    "value_count": 27
+  },
+  "uart": {
+    "baud": 115200,
+    "clks_per_bit": 217,
+    "data_bits": 8,
+    "flow_control": "none",
+    "inter_byte_timeout_ms": 10,
+    "parity": "N",
+    "rx_ball": "N11",
+    "stop_bits": 1,
+    "tx_ball": "M10"
+  },
+  "watchdog": {
+    "enable_after_startup_complete": true,
+    "target": {
+      "fan": 10,
+      "ptc": 0
+    },
+    "tick_clks": 12500,
+    "tick_us": 500,
+    "timeout_seconds": 30,
+    "timeout_ticks": 60000
+  }
+}

+ 32 - 0
deploy/examples/hthd.mock.yaml

@@ -0,0 +1,32 @@
+api_version: hth.api.v1
+device_id: prod2u-0
+display_name: Prod2U mock
+backend: mock
+profile: ../../profiles/prod2u-door-temp/profile.json
+runtime_root: /tmp/hth-mock
+sockets:
+  observe: /tmp/hth-mock/observe.sock
+  control: /tmp/hth-mock/control.sock
+  observe_perm: "0660"
+  control_perm: "0660"
+poll:
+  temperature_ms: 200
+  motor_status_ms: 100
+watchdog:
+  heartbeat_period_ms: 5000
+lease:
+  min_ttl_ms: 1000
+  max_ttl_ms: 30000
+safety:
+  fan: 10
+  ptc: 0
+  door_close_percent: 0
+ring_buffer_size: 1024
+subscriber_buffer_size: 8
+command_cache_size: 256
+grpc:
+  reflection: true
+mock:
+  seed: 1
+  startup_complete: true
+  first_order_thermal: true

+ 32 - 0
deploy/examples/hthd.serial.yaml

@@ -0,0 +1,32 @@
+api_version: hth.api.v1
+device_id: prod2u-0
+display_name: Prod2U serial
+backend: serial
+profile: ../../profiles/prod2u-door-temp/profile.json
+serial:
+  path: /dev/hth/controller0
+runtime_root: /run/hth
+sockets:
+  observe: /run/hth/observe/observe.sock
+  control: /run/hth/control/control.sock
+  observe_perm: "0660"
+  control_perm: "0660"
+  observe_group: hth-observe
+  control_group: hth-control
+poll:
+  temperature_ms: 200
+  motor_status_ms: 100
+watchdog:
+  heartbeat_period_ms: 5000
+lease:
+  min_ttl_ms: 1000
+  max_ttl_ms: 30000
+safety:
+  fan: 10
+  ptc: 0
+  door_close_percent: 0
+ring_buffer_size: 1024
+subscriber_buffer_size: 8
+command_cache_size: 256
+grpc:
+  reflection: false

+ 23 - 0
deploy/examples/podman-socket-only.sh

@@ -0,0 +1,23 @@
+#!/usr/bin/env bash
+# Thin example: model/data container talks to host hthd via bind-mounted sockets only.
+# Do NOT map serial devices. Do NOT use --privileged.
+set -euo pipefail
+IMAGE="${1:-localhost/hth-client:dev}"
+
+# Observe-only (data people)
+podman run --rm -it \
+  --network=none \
+  --user 1000:1000 \
+  --security-opt no-new-privileges \
+  --volume /run/hth/observe.sock:/run/hth/observe.sock:ro \
+  "$IMAGE" \
+  python3 -c 'print("mount observe.sock only; never /dev/ttyUSB*")'
+
+# Control (model people) — still requires a Lease inside the app
+# podman run --rm -it \
+#   --network=none \
+#   --user 1000:1000 \
+#   --security-opt no-new-privileges \
+#   --volume /run/hth/observe.sock:/run/hth/observe.sock:ro \
+#   --volume /run/hth/control.sock:/run/hth/control.sock \
+#   "$IMAGE" python3 /app/control.py

+ 116 - 0
deploy/install.sh

@@ -0,0 +1,116 @@
+#!/usr/bin/env bash
+# Install hthd binaries, systemd unit, sysusers, tmpfiles, profile, and example config.
+#
+# Binaries default to PREFIX=/usr/local (matches ExecStart=/usr/local/bin/hthd).
+# sysusers/tmpfiles stay at /usr/lib on Debian even when PREFIX is /usr/local.
+# Do not use PREFIX=/usr with ExecStart=/usr/local/bin/hthd.
+set -euo pipefail
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+DESTDIR="${DESTDIR:-}"
+PREFIX="${PREFIX:-/usr/local}"
+BINDIR="${BINDIR:-${PREFIX}/bin}"
+LIBDIR="${LIBDIR:-/usr/lib}"
+SYSCONFDIR="${SYSCONFDIR:-/etc}"
+UNITDIR="${UNITDIR:-${SYSCONFDIR}/systemd/system}"
+ETCDIR="${ETCDIR:-${SYSCONFDIR}/hth}"
+UDEVDIR="${UDEVDIR:-${SYSCONFDIR}/udev/rules.d}"
+
+export PATH="/data/prod2u/opt/go1.25.13/bin:/root/go/bin:/usr/bin:/bin:${PATH}"
+export GOTOOLCHAIN="${GOTOOLCHAIN:-local}"
+if [[ -d /data/prod2u/opt/go1.25.13 ]]; then
+  export GOROOT=/data/prod2u/opt/go1.25.13
+fi
+
+echo "install: PREFIX=${PREFIX} BINDIR=${BINDIR} LIBDIR=${LIBDIR} DESTDIR=${DESTDIR:-/}"
+if [[ "${PREFIX}" == "/usr" && "${BINDIR}" == "/usr/bin" ]]; then
+  echo "error: systemd unit ExecStart is /usr/local/bin/hthd; use PREFIX=/usr/local (default)" >&2
+  echo "       or set BINDIR and ship a matching unit." >&2
+  exit 2
+fi
+
+build_one() {
+  local name="$1"
+  local dest="${ROOT}/bin/${name}"
+  if [[ -x "${dest}" ]]; then
+    return 0
+  fi
+  mkdir -p "${ROOT}/bin"
+  (cd "${ROOT}" && CGO_ENABLED=0 go build -trimpath -o "${dest}" "./cmd/${name}")
+}
+
+build_one hthd
+build_one hthctl
+build_one hth-capture
+
+install -d -m 0755 "${DESTDIR}${BINDIR}"
+install -m 0755 "${ROOT}/bin/hthd" "${DESTDIR}${BINDIR}/hthd"
+install -m 0755 "${ROOT}/bin/hthctl" "${DESTDIR}${BINDIR}/hthctl"
+install -m 0755 "${ROOT}/bin/hth-capture" "${DESTDIR}${BINDIR}/hth-capture"
+
+install -d -m 0755 "${DESTDIR}${LIBDIR}/sysusers.d" "${DESTDIR}${LIBDIR}/tmpfiles.d" "${DESTDIR}${UNITDIR}"
+install -m 0644 "${ROOT}/deploy/sysusers.d/hth.conf" "${DESTDIR}${LIBDIR}/sysusers.d/hth.conf"
+install -m 0644 "${ROOT}/deploy/tmpfiles/hth.conf" "${DESTDIR}${LIBDIR}/tmpfiles.d/hth.conf"
+install -m 0644 "${ROOT}/deploy/systemd/hthd.service" "${DESTDIR}${UNITDIR}/hthd.service"
+install -m 0644 "${ROOT}/deploy/systemd/hthd@.service" "${DESTDIR}${UNITDIR}/hthd@.service"
+
+install -d -m 0750 "${DESTDIR}${ETCDIR}" "${DESTDIR}${ETCDIR}/profiles" "${DESTDIR}${ETCDIR}/profiles/prod2u-door-temp"
+install -m 0640 "${ROOT}/deploy/examples/hthd.mock.yaml" "${DESTDIR}${ETCDIR}/hthd.yaml.example"
+if [[ ! -e "${DESTDIR}${ETCDIR}/hthd.yaml" ]]; then
+  cat > "${DESTDIR}${ETCDIR}/hthd.yaml" <<EOF
+api_version: hth.api.v1
+device_id: prod2u-0
+display_name: Prod2U mock
+backend: mock
+profile: ${ETCDIR}/profiles/prod2u-door-temp/profile.json
+runtime_root: /run/hth
+sockets:
+  observe: /run/hth/observe/observe.sock
+  control: /run/hth/control/control.sock
+  observe_perm: "0660"
+  control_perm: "0660"
+  observe_group: hth-observe
+  control_group: hth-control
+poll:
+  temperature_ms: 200
+  motor_status_ms: 100
+watchdog:
+  heartbeat_period_ms: 5000
+lease:
+  min_ttl_ms: 1000
+  max_ttl_ms: 30000
+safety:
+  fan: 10
+  ptc: 0
+  door_close_percent: 0
+ring_buffer_size: 1024
+subscriber_buffer_size: 8
+command_cache_size: 256
+grpc:
+  reflection: false
+mock:
+  seed: 1
+  startup_complete: true
+EOF
+  chmod 0640 "${DESTDIR}${ETCDIR}/hthd.yaml"
+fi
+install -m 0640 "${ROOT}/profiles/prod2u-door-temp/profile.json" "${DESTDIR}${ETCDIR}/profiles/prod2u-door-temp/profile.json"
+
+install -d -m 0755 "${DESTDIR}${UDEVDIR}"
+install -m 0644 "${ROOT}/deploy/udev/99-hth-controller.rules.template" \
+  "${DESTDIR}${UDEVDIR}/99-hth-controller.rules.template"
+
+install -d -m 0750 "${DESTDIR}/var/lib/hth" "${DESTDIR}/var/lib/hth/captures" "${DESTDIR}/var/lib/hth/replay"
+if [[ -z "${DESTDIR}" ]] && getent group hth >/dev/null 2>&1; then
+  chown -R root:hth "${ETCDIR}"
+  chmod 0750 "${ETCDIR}" "${ETCDIR}/profiles" "${ETCDIR}/profiles/prod2u-door-temp"
+  chmod 0640 "${ETCDIR}/hthd.yaml" "${ETCDIR}/profiles/prod2u-door-temp/profile.json" 2>/dev/null || true
+  if id hth >/dev/null 2>&1; then
+    chown -R hth:hth "${DESTDIR}/var/lib/hth"
+  fi
+fi
+
+echo "installed binaries=${DESTDIR}${BINDIR}/{hthd,hthctl,hth-capture}"
+echo "installed unit=${DESTDIR}${UNITDIR}/hthd.service (ExecStart=/usr/local/bin/hthd)"
+echo "installed profile=${DESTDIR}${ETCDIR}/profiles/prod2u-door-temp/profile.json"
+echo "next: systemd-sysusers && systemd-tmpfiles --create && systemctl daemon-reload"
+echo "python SDK: pip install ${ROOT}/sdk/python (or the release wheel); not copied into PREFIX"

+ 8 - 0
deploy/systemd/hth.conf

@@ -0,0 +1,8 @@
+# NOT a tmpfiles fragment.
+# Authoritative tmpfiles.d fragment is:
+#   host/deploy/tmpfiles/hth.conf
+# Install with:
+#   install -m 0644 deploy/tmpfiles/hth.conf /usr/lib/tmpfiles.d/hth.conf
+# or: host/deploy/install.sh
+#
+# Do not copy this comment file into /usr/lib/tmpfiles.d/.

+ 45 - 0
deploy/systemd/hthd.service

@@ -0,0 +1,45 @@
+[Unit]
+Description=hth high-temperature hood device daemon
+Documentation=file:///etc/hth/hthd.yaml
+After=systemd-tmpfiles-setup.service
+Wants=systemd-tmpfiles-setup.service
+
+[Service]
+Type=notify
+NotifyAccess=main
+User=hth
+Group=hth
+SupplementaryGroups=dialout hth-observe hth-control
+Restart=on-failure
+RestartSec=2s
+WatchdogSec=30
+# systemd WatchdogSec is process liveness only. hthd sends sd_notify
+# READY=1 and WATCHDOG=1. It does not replace Control Lease or FPGA SET_ALL watchdog.
+# Runtime directories come from tmpfiles.d/hth.conf (setgid observe/control).
+# Do not use RuntimeDirectory=hth 0750 hth:hth: that blocks hth-observe.
+UMask=0007
+NoNewPrivileges=true
+PrivateTmp=true
+ProtectHome=true
+ProtectSystem=strict
+ReadWritePaths=/run/hth /var/lib/hth
+ReadOnlyPaths=/etc/hth
+WorkingDirectory=/var/lib/hth
+ExecStartPre=/usr/local/bin/hthd --check-config --config /etc/hth/hthd.yaml
+ExecStart=/usr/local/bin/hthd --config /etc/hth/hthd.yaml
+TimeoutStopSec=15
+LimitNOFILE=4096
+LockPersonality=true
+RestrictSUIDSGID=true
+RestrictNamespaces=true
+SystemCallArchitectures=native
+ProtectClock=true
+ProtectKernelTunables=true
+ProtectKernelModules=true
+ProtectControlGroups=true
+# Do not set PrivateDevices=true: it hides the serial node.
+# RestrictAddressFamilies=AF_UNIX: gRPC UDS + sd_notify only. No TCP.
+RestrictAddressFamilies=AF_UNIX
+
+[Install]
+WantedBy=multi-user.target

+ 44 - 0
deploy/systemd/hthd@.service

@@ -0,0 +1,44 @@
+# hthd instance unit: one serial controller = one process.
+# Usage: systemctl enable --now hthd@controller0.service
+# Config: /etc/hth/hthd@%i.yaml
+
+[Unit]
+Description=hth high-temperature hood daemon (%i)
+Documentation=file:///etc/hth/hthd@%i.yaml
+After=systemd-tmpfiles-setup.service
+Requires=systemd-tmpfiles-setup.service
+
+[Service]
+Type=notify
+NotifyAccess=main
+User=hth
+Group=hth
+SupplementaryGroups=dialout hth-observe hth-control
+Restart=on-failure
+RestartSec=2s
+WatchdogSec=30
+UMask=0007
+NoNewPrivileges=true
+PrivateTmp=true
+ProtectHome=true
+ProtectSystem=strict
+ReadWritePaths=/run/hth /var/lib/hth
+ReadOnlyPaths=/etc/hth
+WorkingDirectory=/var/lib/hth
+ExecStartPre=/usr/local/bin/hthd --check-config --config /etc/hth/hthd@%i.yaml
+ExecStart=/usr/local/bin/hthd --config /etc/hth/hthd@%i.yaml
+TimeoutStopSec=15
+LimitNOFILE=4096
+LockPersonality=true
+RestrictSUIDSGID=true
+RestrictNamespaces=true
+SystemCallArchitectures=native
+ProtectClock=true
+ProtectKernelTunables=true
+ProtectKernelModules=true
+ProtectControlGroups=true
+# Do not set PrivateDevices=true: it hides the serial node.
+RestrictAddressFamilies=AF_UNIX
+
+[Install]
+WantedBy=multi-user.target

+ 7 - 0
deploy/sysusers.d/hth.conf

@@ -0,0 +1,7 @@
+# Type Path                 Mode User Group
+# sysusers.d — daemon user plus observe/control client users (and matching groups).
+u hth          - "hth device daemon" /var/lib/hth /usr/sbin/nologin
+u hth-observe  - "hth observe clients" - /usr/sbin/nologin
+u hth-control  - "hth control clients" - /usr/sbin/nologin
+m hth hth-observe
+m hth hth-control

+ 12 - 0
deploy/tmpfiles/hth.conf

@@ -0,0 +1,12 @@
+# Type Path Mode User Group Age Argument
+# Parent must be traversable by hth-observe / hth-control.
+# Child dirs are owned by the daemon so it can bind sockets; setgid so
+# sockets inherit the client group. Group has no write, so clients cannot unlink.
+d /run/hth 0751 root root -
+d /run/hth/observe 02750 hth hth-observe -
+d /run/hth/control 02750 hth hth-control -
+d /var/lib/hth 0750 hth hth -
+d /var/lib/hth/captures 0750 hth hth -
+d /var/lib/hth/replay 0750 hth hth -
+d /etc/hth 0750 root hth -
+d /etc/hth/profiles 0750 root hth -

+ 29 - 0
deploy/udev/99-hth-controller.rules.template

@@ -0,0 +1,29 @@
+# 99-hth-controller.rules.template
+#
+# Do NOT invent USB idVendor / idProduct / serial.
+# This repository has no captured hardware IDs.
+#
+# On a machine with the real USB-UART adapter plugged in:
+#
+#   udevadm info -a -n /dev/ttyUSB0
+#   udevadm info -q property -n /dev/ttyUSB0
+#
+# Copy ATTRS{idVendor}, ATTRS{idProduct}, and ATTRS{serial} (if present)
+# into the rule below. Prefer serial + VID/PID over "the first ttyUSB".
+# Optionally match ATTRS{devpath} / kernel USB port path for stable seating.
+#
+# Install the filled file as:
+#   /etc/udev/rules.d/99-hth-controller.rules
+# Then:
+#   sudo udevadm control --reload-rules
+#   sudo udevadm trigger
+#
+# Expected symlink: /dev/hth/controller0
+# Production hthd.serial.yaml should use that path, not /dev/ttyUSB0.
+
+# ACTION=="add", SUBSYSTEM=="tty", \
+#   ATTRS{idVendor}=="XXXX", ATTRS{idProduct}=="YYYY", ATTRS{serial}=="ZZZZ", \
+#   SYMLINK+="hth/controller0", GROUP="hth", MODE="0660", TAG+="uaccess"
+
+# Placeholder line kept commented so an unfinished copy cannot match every tty:
+# KERNEL=="ttyUSB*", ATTRS{idVendor}=="REPLACE_VID", ATTRS{idProduct}=="REPLACE_PID", SYMLINK+="hth/controller0"

+ 24 - 0
deploy/uninstall.sh

@@ -0,0 +1,24 @@
+#!/usr/bin/env bash
+# Remove hthd units and binaries. Does not delete /var/lib/hth captures unless --purge.
+set -euo pipefail
+PREFIX="${PREFIX:-/usr/local}"
+BINDIR="${BINDIR:-${PREFIX}/bin}"
+LIBDIR="${LIBDIR:-/usr/lib}"
+SYSCONFDIR="${SYSCONFDIR:-/etc}"
+UNITDIR="${UNITDIR:-${SYSCONFDIR}/systemd/system}"
+ETCDIR="${ETCDIR:-${SYSCONFDIR}/hth}"
+PURGE=0
+if [[ "${1:-}" == "--purge" ]]; then
+  PURGE=1
+fi
+if command -v systemctl >/dev/null 2>&1 && [[ "$(cat /proc/1/comm 2>/dev/null)" == systemd ]]; then
+  systemctl disable --now hthd.service 2>/dev/null || true
+  systemctl daemon-reload || true
+fi
+rm -f "${BINDIR}/hthd" "${BINDIR}/hthctl" "${BINDIR}/hth-capture"
+rm -f "${UNITDIR}/hthd.service" "${UNITDIR}/hthd@.service"
+rm -f "${LIBDIR}/sysusers.d/hth.conf" "${LIBDIR}/tmpfiles.d/hth.conf"
+if [[ "${PURGE}" -eq 1 ]]; then
+  rm -rf "${ETCDIR}" /var/lib/hth /run/hth
+fi
+echo "uninstalled hthd binaries and units (purge=${PURGE})"

+ 103 - 0
docs/api-contract.zh-CN.md

@@ -0,0 +1,103 @@
+# API 合同(hth.api.v1)
+
+权威 IDL:`host/api/proto/hth/api/v1/hth.proto`。  
+本文解释领域语义。传输是 gRPC over UDS,但 **API ≠ gRPC**:换传输不应改 ID 与质量枚举。
+
+包名:`hth.api.v1`。枚举 0 值均为 `*_UNSPECIFIED`。版本字段拆分,见兼容性政策。
+
+## 服务与套接字
+
+| 服务 | Socket | 谁能调用 |
+| --- | --- | --- |
+| `ObserveService` | `/run/hth/observe.sock` | `hth-observe`(及 control 组) |
+| `ControlService` | `/run/hth/control.sock` | 仅 `hth-control` |
+
+Observe **不得**暴露 `ApplyAction`。第一版无 TCP。
+
+### ObserveService
+
+- `ListDevices`
+- `GetCapabilities`
+- `GetSnapshot` — 读缓存
+- `SubscribeTelemetry` — `stream Snapshot`
+- `SubscribeEvents` — `stream Event`
+- `GetFaults`
+- `WatchHealth` — `stream HealthStatus`
+
+可另开标准 gRPC Health。Reflection 仅开发配置开启。
+
+### ControlService
+
+- `AcquireControlLease` / `RenewControlLease` / `ReleaseControlLease`
+- `ValidateAction` — 不访问硬件
+- `ApplyAction` — 需有效 Lease;组装完整 SET_ALL
+- `EnterSafeMode`
+
+## Capabilities(必须诚实)
+
+`GetCapabilities` 至少包含:device/profile/revision、protocol contract hash、capability hash、**api_version**、firmware_version **及其 quality**、罩/腔数量、传感器与执行器列表、ACK/状态查询/位置/RPM/故障查询标志、readiness probe。
+
+当前 Prod2U 期望:
+
+| 字段 | 值 |
+| --- | --- |
+| `api_version` | `hth.api.v1` |
+| `ack_supported` | `false` |
+| `status_query_supported` | `true`(`GET_MOTOR_STATUS`) |
+| `position_feedback_supported` | 无编码器;开环估计另见传感器 `ESTIMATED` |
+| `rpm_feedback_supported` | `false` |
+| `firmware_version_quality` | `NOT_SUPPORTED` |
+| `readiness_probe` | `motor_status_startup_complete` |
+| 温度 `mapping_confidence` | `UNKNOWN` |
+
+限位:协议在 MOTOR_STATUS 中回报 open/close flag,Host readback = 支持(来自状态帧,不是独立 GPIO 轮询)。原理图上协议不返回的限位 = `NOT_SUPPORTED`。
+
+## Snapshot
+
+相对一致的一帧状态:`device_epoch`、`snapshot_seq`(单调)、`control_revision`、墙钟与单调时钟、采集窗口、全部测量(带 `DataQuality`)、连续目标、`last_requested` / `last_accepted` / `last_dispatched`、`device_confirmation`、故障、Lease 摘要、`data_gap` / `dropped_telemetry_count`。
+
+没有实际反馈的执行器:
+
+```text
+commanded_target = 40
+actual_value     不出现或忽略
+actual_quality   = NOT_SUPPORTED
+```
+
+禁止把风扇 commanded duty 写成 RPM。
+
+## ActionBatch
+
+一次原子提交。当前 Profile 下风扇/PTC/门都是 **连续目标**(门为 close-percent,不是 jog 一次性事件)。
+
+必填语义:
+
+- `device_id` `command_id` `lease_id` `lease_epoch`
+- `based_on_snapshot_seq` `expected_control_revision`(过旧则拒绝)
+- `valid_until`
+- `continuous_targets` / (预留)`discrete_commands`
+- `allow_clamp`:false 时需 clamp 则整批拒绝
+- 未知 ID / 越界 / 不支持 → **整批失败**,禁止部分成功
+
+`ValidateAction` 与 `ApplyAction` 返回 `ActionResult`,必须带 requested/accepted/dispatched/confirmation。SET_ALL 的 confirmation **不是** `CONFIRMED`。
+
+## 遥测续接与 DATA_GAP
+
+`SubscribeTelemetry(resume_after_event_id)` 从内存 ring 续接。超出 ring → 明确 `data_gap`,禁止假装连续。慢订阅者不得阻塞控制路径。
+
+`device_epoch` 变化时旧 resume id 无效,客户端必须当新设备会话处理。
+
+## 启动期(对 API 的影响)
+
+标定期间:
+
+- SET_ALL:可改 FAN/PTC,**忽略门百分比且不缓存**;不喂运行期 watchdog(尚未 enable)
+- GET_MOTOR_STATUS:允许
+- GET_TEMPERATURE:设备丢弃 → Host 不得用温度超时判死
+- 合法 SET_ALL **不**当作运行期门目标
+
+`startup_complete` 之后 Host 必须让上位机 **重发** 期望百分比。
+
+## 与 UART 的关系(适配器内部,不进入公共 ID)
+
+公共 API 禁止以 payload offset、command type、CRC、球位作为主键。那些只存在于 Profile / 诊断 metadata。

+ 133 - 0
docs/architecture.zh-CN.md

@@ -0,0 +1,133 @@
+# 架构说明
+
+面向有 Linux / DevOps 背景、但不熟悉嵌入式协议的读者。标识符保持英文。
+
+## 1. 运行形态
+
+```text
+CPLD / FPGA
+    UART 115200 8N1   (仅 hthd 打开)
+        │
+        ▼
+┌──────────────────────────────────────────┐
+│ hthd  (systemd 用户 hth,非 root)        │
+│  Device Actor × N                         │
+│  Profile / 协议编解码 / 状态缓存            │
+│  Lease 仲裁 / 安全层 / Watchdog 心跳        │
+│  故障 / Snapshot seq / device_epoch        │
+└───────────────┬──────────────────────────┘
+                │ gRPC over Unix Domain Socket
+        ┌───────┴────────┐
+        ▼                ▼
+ /run/hth/observe.sock   /run/hth/control.sock
+ 组 hth-observe           组 hth-control
+ 只读                     需 Lease 才能 Apply
+```
+
+第一版 **不监听 TCP**、不做 TLS、不做 REST Gateway。权限 = Unix 文件权限 + 两个 Linux 组。
+
+## 2. 为什么 hthd 必须独占串口
+
+串口是字节流,不是消息总线。分帧、CRC、半帧恢复、字节间超时、SET_ALL 组装、Watchdog 心跳,都必须在 **同一个 Device Actor** 里串行完成。
+
+若模型容器、Jupyter 或第二个 Python 进程直接 `open("/dev/ttyUSB0")`:
+
+- 与心跳抢写,门百分比会被旧上位机习惯改成 `00`(全开);
+- 无 ACK,无法证明谁的帧到达了 FPGA;
+- 启动期丢温度 GET 会被误判为设备死亡。
+
+**容器禁止映射串口。** 只 bind-mount Unix Socket。`hthd` 留在宿主机 systemd。
+
+## 3. API 与 gRPC 的区别
+
+| | 领域 API | gRPC |
+| --- | --- | --- |
+| 是什么 | 高温罩语义合同:Capabilities、Snapshot、ActionBatch、Lease | 该合同的一种 RPC 编码与传输 |
+| 稳定名 | `hth.api.v1` 消息与服务 | 同一套 `.proto`,本地 `unix://` |
+| 不是什么 | 不是 UART 帧,不是 REST,不是“已经执行” | 不是控制心跳,不是硬件 Watchdog |
+
+以后若 Backend 从 UART 换成 AXI/UIO,**领域 API 与 SDK 原则上不改**;变化的是 `hthd` 内部 backend。
+
+## 4. 内部并发
+
+推荐(Go 守护进程):
+
+```text
+gRPC handler  →  有界命令队列  →  Device Actor  →  backend (mock|serial|replay)
+遥测订阅者     →  每订阅者有界缓冲;慢客户端丢弃并标记 DATA_GAP
+```
+
+优先级(合同):
+
+1. 进入安全态
+2. 正式 ApplyAction
+3. Watchdog 安全心跳(重复连续目标,**不改写门为 0**)
+4. 马达状态轮询
+5. 温度轮询(有待发控制时不要开长 GET_TEMP)
+
+`GetSnapshot()` **只读缓存**,不每次打串口。
+
+## 5. Backend 三种
+
+| kind | 串口 | 用途 |
+| --- | --- | --- |
+| `mock` | 永不打开 | SDK / 控制流程测试。一阶热数字仅供接口测试,**不是物理模型** |
+| `replay` | 拒绝打开真串口 | 播放 `hth-capture` 记录 |
+| `serial` | 独占真实设备 | 当前 Prod2U Profile;**Hardware validation: NOT RUN** |
+
+## 6. 四种“看门狗 / 心跳”,不要混用
+
+| 机制 | 监视谁 | 不能替代什么 |
+| --- | --- | --- |
+| **Control Lease** | 正式控制客户端是否还活着、是否仍持有写入权 | 不能替代 FPGA Watchdog |
+| **gRPC keepalive** | HTTP/2 ping,连接还在 | **不是**控制心跳,**不能**代替 `RenewControlLease` |
+| **systemd Watchdog** | `hthd` 进程是否 `sd_notify` | 已实现:`READY=1` + 周期 `WATCHDOG=1`。只监控进程,不替代 Lease / FPGA watchdog |
+| **FPGA Watchdog** | 30 s 内是否有合法 SET_ALL commit(仅 startup 后) | 最终硬件安全网。Host 心跳必须重发真实门百分比 |
+
+## 7. requested / accepted / dispatched / confirmed
+
+对无 ACK 的 SET_ALL:
+
+```text
+requested   客户端想要什么(ActionBatch)
+accepted    hthd 校验通过、准备编码的规范化目标
+dispatched  已完整写入 OS 串口缓冲的帧(仍不知 FPGA 是否执行)
+confirmed   硬件证明执行结果 —— 当前协议下 SET_ALL 永不进入此态
+```
+
+`confirmation_status`:
+
+- 完整写出:`UNCONFIRMED`
+- 短写 / 断开:`OUTCOME_UNKNOWN`
+- 校验失败:`REJECTED`
+- `CONFIRMED`:当前合同禁止用于 SET_ALL
+
+后续可用 `GET_MOTOR_STATUS` 观察 `requested_percent` / `moving` / 限位,这是 **独立观测**,仍不把 SET_ALL 标成 CONFIRMED。
+
+## 8. 门 0 不是 STOP
+
+当前控制模式是 `PERCENT_CLOSE`,不是 `JOG_ONLY`。
+
+- `door.*.close_percent = 0` → 规划到 **全开端点**(完成只认真实 open_limit)
+- `= 100` → 全关端点
+- `1..99` → 开环步数估计,质量 `ESTIMATED`
+- 旧文档里的 `NO_NEW_JOG` 是历史 jog 语义,**不是**当前默认 API
+
+把三门填 `00` 当心跳,会把三轴开到全开限位。
+
+## 9. 路径与用户组
+
+| 路径 | 用途 |
+| --- | --- |
+| `/etc/hth/hthd.yaml` | 主配置 |
+| `/etc/hth/profiles/` | 已校验 Profile |
+| `/run/hth/observe.sock` | 只读 |
+| `/run/hth/control.sock` | 控制 |
+| `/var/lib/hth/captures/` | 短时采集 |
+| `/var/lib/hth/replay/` | Replay 输入 |
+
+组:`hth-observe`、`hth-control`。服务用户 `hth`(非 root),串口补充组通常为 `dialout`(以发行版为准)。
+
+## 10. 设备 Epoch
+
+串口断开/重连、守护进程重启、Profile 更换 → `device_epoch` 增加,Lease 全部作废,不得把旧 Snapshot 当新真相。SDK 在遥测流上发出 `DEVICE_EPOCH_CHANGED` 通知。

+ 42 - 0
docs/compatibility-policy.zh-CN.md

@@ -0,0 +1,42 @@
+# 兼容性政策
+
+## 版本拆分(禁止一个模糊的 version 字段包打天下)
+
+| 名称 | 当前值 | 何时变 |
+| --- | --- | --- |
+| API | `hth.api.v1` | 破坏性公共消息/服务变更 |
+| 协议合同 / Profile | `prod2u-normal-multiproject-115200-v1` + `profile_revision` + contract sha256 | UART/语义变更 |
+| Capability hash | 由 Profile/能力表计算 | 传感器/执行器集合或标志变化 |
+| 固件版本 | 协议 **不可读** → quality `NOT_SUPPORTED` | 不能用 API version 冒充 |
+| Capture 磁盘格式 | 与在线 protobuf **解耦** | 允许独立加 magic/version |
+
+SDK 在 `GetCapabilities.api_version` 上做检查,不匹配则 `ApiVersionMismatch`。
+
+## Protobuf 纪律(hth.api.v1)
+
+- 包名保持 `hth.api.v1` 直到破坏性变更。
+- **新字段用新 tag**。不要插入到已发布字段中间靠“碰巧兼容”。
+- **删除字段后必须 `reserved` 原 tag 与名称**。禁止 reuse tag。
+- 枚举 **0 = `UNSPECIFIED`**。不要把可扩展状态做成单纯 bool(将来会出现第三态时无法演进)。
+- 不要复用一个 `version` string 表示 API+协议+固件。
+- Descriptor set 可由 `protoc --descriptor_set_out` 生成,供兼容性测试比对(见 Makefile `proto` 目标)。
+
+当前 proto 已遵循:各枚举均有 `*_UNSPECIFIED = 0`。
+
+## 领域 ID 稳定性
+
+- `temperature.channel.00`…`26` 一旦发布,只能增加 alias,不能改主键。
+- 门执行器 ID 为 `door.{x,y,z}.close_percent`,语义是闭合百分比,不是 jog opcode。
+- 旧 14 字节 SET_ALL、旧 `00/01/02` jog **拒绝/不实现**,不提供兼容转换器把心跳 `00` 翻译成“不动”。
+
+## 行为兼容
+
+- 无 ACK:不得在小版本里突然把 SET_ALL 标成 `CONFIRMED` 而不改 API 主版本并写清硬件证据。
+- Watchdog 30 s / FAN 10 / PTC 0:若固件合同变更,必须改 Profile 并 bump protocol/profile 标识,而不是只改守护进程魔法数。
+- Mock、Replay、serial 三个 backend 共用同一套 gRPC 合同。Mock 也不得返回 SET_ALL `CONFIRMED`。
+
+## 客户端建议
+
+- 忽略未知字段(protobuf 默认)但不要忽略 `DataQuality`。
+- 遇到未知 `FaultType` / `EventKind` 当 `UNSPECIFIED` 同类处理并记日志,不要崩溃。
+- `device_epoch` 变化视为会话边界。

+ 117 - 0
docs/deployment.zh-CN.md

@@ -0,0 +1,117 @@
+# 部署
+
+`hthd` 作为 **宿主机原生 systemd 服务** 运行。容器只用来跑模型/采集客户端。  
+不提供 Kubernetes、Helm、Operator。
+
+## 用户、组、路径
+
+```text
+用户:  hth          (NoNewPrivileges,非 root)
+组:    hth
+附加:  dialout      (或发行版上的串口组,按 udev 实际为准)
+组:    hth-observe  (读 observe.sock)
+组:    hth-control  (读/写 control.sock)
+
+/etc/hth/hthd.yaml
+/etc/hth/profiles/prod2u-door-temp/profile.json
+/run/hth/                  0751 root:root(可遍历)
+/run/hth/observe/          02750 hth:hth-observe
+/run/hth/control/          02750 hth:hth-control
+/run/hth/observe/observe.sock
+/run/hth/control/control.sock
+/var/lib/hth/captures/
+/var/lib/hth/replay/
+```
+
+创建:
+
+```bash
+sudo useradd --system --home /var/lib/hth --shell /usr/sbin/nologin hth
+sudo groupadd --system hth-observe
+sudo groupadd --system hth-control
+sudo usermod -aG hth-observe,hth-control,dialout hth
+# 数据人员: sudo usermod -aG hth-observe <user>
+# 控制人员: sudo usermod -aG hth-observe,hth-control <user>
+sudo systemd-tmpfiles --create host/deploy/tmpfiles/hth.conf
+```
+
+安装二进制与配置(路径按实际 prefix 调整):
+
+```bash
+sudo install -m 0755 bin/hthd bin/hthctl bin/hth-capture /usr/local/bin/
+sudo install -d -m 0750 -o hth -g hth /etc/hth /etc/hth/profiles /var/lib/hth /var/lib/hth/captures /var/lib/hth/replay
+sudo install -m 0640 -o hth -g hth deploy/examples/hthd.mock.yaml /etc/hth/hthd.yaml
+sudo install -m 0644 profiles/prod2u-door-temp/profile.json /etc/hth/profiles/prod2u-door-temp/profile.json
+sudo install -m 0644 deploy/systemd/hthd.service /etc/systemd/system/hthd.service
+sudo systemctl daemon-reload
+sudo hthd --check-config --config /etc/hth/hthd.yaml
+sudo systemctl enable --now hthd.service
+```
+
+生产串口:把 `hthd.yaml` 换成 `deploy/examples/hthd.serial.yaml` 填好的副本。**安全块必须显式写出**,serial 模式不允许“缺省就当 FAN 10”。
+
+卸载:`systemctl disable --now hthd`;删除 unit、`/etc/hth`、`/var/lib/hth`(注意保留采集文件若还需要);`userdel hth` 仅在确认无残留设备时。
+
+## systemd
+
+文件:`deploy/systemd/hthd.service`。
+
+- `Restart=on-failure`
+- 运行目录由 **tmpfiles** 创建(不要 `RuntimeDirectory=hth 0750 hth:hth`,那会挡住 `hth-observe` 遍历 `/run/hth`)
+- `NoNewPrivileges=true`
+- `User=hth`
+- 设置 `Type=notify` 与 `WatchdogSec=30`。`hthd` 通过 `NOTIFY_SOCKET` 发送 `READY=1` 与 `WATCHDOG=1`。systemd Watchdog 只说明进程还活着,不是 Control Lease,也不是 FPGA 看门狗。
+- systemd Watchdog ≠ Control Lease ≠ FPGA Watchdog。
+
+语法检查(环境允许时):`systemd-analyze verify deploy/systemd/hthd.service`。
+
+## udev 稳定名(不要编造 VID/PID)
+
+仓库 **没有** 真机采集的 USB `idVendor` / `idProduct` / `serial`。  
+模板:`deploy/udev/99-hth-controller.rules.template`。
+
+在插上真实转换器的机器上:
+
+```bash
+# 找到当前 tty
+ls /dev/ttyUSB* /dev/ttyACM* 2>/dev/null
+udevadm info -a -n /dev/ttyUSB0
+# 记录 ATTRS{idVendor} ATTRS{idProduct} ATTRS{serial} 以及内核 DEVPATH
+```
+
+填入模板后安装到 `/etc/udev/rules.d/99-hth-controller.rules`,期望 symlink:`/dev/hth/controller0`。  
+正式配置 **不要**长期写死 `/dev/ttyUSB0`。
+
+## 示例配置
+
+- `deploy/examples/hthd.mock.yaml` — `backend: mock`,不打开串口。字段名与 `internal/config/config.go` 一致(未知键报错)。
+- `deploy/examples/hthd.serial.yaml` — `backend: serial`,`serial.path: /dev/hth/controller0`,必须显式写出 `safety.fan` / `safety.ptc` / `safety.door_close_percent`。
+
+Socket 组权限由 systemd/tmpfiles 与 `chgrp` 承担。心跳 `watchdog.heartbeat_period_ms` 必须 **小于** FPGA 30 s。
+
+## 薄容器示例(仅 bind-mount sockets)
+
+数据容器(只读 observe):
+
+```bash
+podman run --rm -it \
+  --network=none \
+  --user 1000:1000 \
+  --security-opt no-new-privileges \
+  --volume /run/hth/observe.sock:/run/hth/observe.sock:ro \
+  localhost/hth-model:dev \
+  python3 /app/observe.py --socket /run/hth/observe.sock
+```
+
+Docker 同样:**不要** `--privileged`,**不要** `--device /dev/ttyUSB0`。
+
+控制容器额外挂载 `control.sock`(可读写),仍须在应用内 AcquireLease。  
+容器运行时崩溃 **不得** 影响宿主机 `hthd` 的硬件心跳职责。
+
+## 日志
+
+普通日志进 **journald**:`journalctl -u hthd -f`。不要无上限写 `/var/log`。
+
+## 交叉编译说明
+
+Go 守护进程可 `make build-amd64` / `make build-arm64`。arm64 只要求交叉编译成功,不要求本机运行。当前不包含 SoC-FPGA bring-up。

+ 65 - 0
docs/failure-semantics.zh-CN.md

@@ -0,0 +1,65 @@
+# 故障与失败语义
+
+## 1. 确认语义(无 ACK)
+
+公共字段 `confirmation_status` / Snapshot `device_confirmation`:
+
+| 值 | 何时 |
+| --- | --- |
+| `UNSPECIFIED` | 未填;客户端应视为未知 |
+| `CONFIRMED` | 仅当硬件返回可证明执行结果。**当前 SET_ALL 不得使用** |
+| `UNCONFIRMED` | 帧已完整写出;设备无 ACK |
+| `OUTCOME_UNKNOWN` | 短写、断开、进程崩溃窗口;设备可能已执行 |
+| `REJECTED` | Host 未下发 |
+| `NOT_SUPPORTED` | 该动作类型无确认通道 |
+
+SDK 若看到 SET_ALL 路径返回 `CONFIRMED`,视为守护进程 bug(`ConfirmationNotProven`),不是硬件证据。
+
+`OUTCOME_UNKNOWN` 且门目标相对上次 **有变化**:禁止自动重发。操作员/模型必须基于新 Snapshot + 新 `command_id` 显式决策。
+
+## 2. requested / accepted / dispatched
+
+即使 `accepted=true` 且 `dispatched` 非空,仍可能 `UNCONFIRMED`。  
+`replayed_from_cache=true` 表示相同 `command_id` 未再次写串口。
+
+同 `command_id` 不同 payload → `IDEMPOTENCY_CONFLICT`。
+
+## 3. 故障分类
+
+`FaultClass`:`DEVICE_REPORTED` / `HOST_INFERRED` / `CONFIG` / `COMMUNICATION` / `DATA_QUALITY`。
+
+没有设备故障队列时,**不得**输出“设备无故障”的假结论;只能说“无 Host 推断故障”或“设备故障查询能力有限(轴 fault_code 在 MOTOR_STATUS 快照中)”。
+
+`FaultType` 含配置/Profile、串口、帧、超时、温度无效、遥测过期、Lease、命令拒绝、结果未知、安全动作未送达、订阅 DATA_GAP、轴故障、watchdog tripped。
+
+轴 `fault_code`(设备报告):`NONE` `BOTH_LIMITS_ACTIVE` `CAL_CLOSE_TIMEOUT` `CAL_OPEN_TIMEOUT` `INVALID_ZERO_OR_TINY_TRAVEL` `ENDPOINT_TIMEOUT`。失败轴 FAULT-lock 直到 FPGA 复位。允许部分轴成功。
+
+## 4. 生命周期
+
+`STARTING` `CONNECTING` `PROBING` `READY` `DEGRADED` `SAFE` `UNAVAILABLE` `UNKNOWN`。
+
+Readiness:**不要**用“第一次温度成功”。启动期温度 GET 被丢弃。以 `GET_MOTOR_STATUS.startup_complete=1` 为准。
+
+## 5. 数据缺口与 Epoch
+
+| 事件 | 客户端必须 |
+| --- | --- |
+| `data_gap=true` / `EVENT_KIND_DATA_GAP` | 不得插值填洞;从新 Snapshot 重建状态 |
+| `device_epoch` 变化 | 丢弃旧 Lease 与旧 seq;重新 GetCapabilities/GetSnapshot;重新 AcquireLease |
+| 订阅落后 ring | 明确 gap,而不是静默跳号 |
+
+## 6. 温度无效
+
+`0xFF` → 不得变成 255℃。`quality=INVALID`。缺失/不支持的 RPM 等用 `NOT_SUPPORTED`,不要用 0 RPM 冒充停转实测。
+
+## 7. Host 推断 vs 设备报告
+
+| 例子 | 类别 |
+| --- | --- |
+| CRC 错、超时、串口消失 | Host 推断 / 通信 |
+| `watchdog_tripped` 位、轴 FAULT | 设备报告(经 MOTOR_STATUS) |
+| 温度映射未知 | 不是故障;是能力缺口 |
+
+## 8. 安全动作未送达
+
+串口断开时 Host 不能保证安全帧到达。必须保留 `SAFE_ACTION_NOT_DELIVERED`。最终依赖 FPGA 30 s watchdog。进程 `ExecStop` 的 best-effort 写串口 **不是**安全保证。

+ 78 - 0
docs/known-gaps.zh-CN.md

@@ -0,0 +1,78 @@
+# 已知缺口
+
+诚实清单。未完成项不是“即将默认可用”。
+
+## 协议与数据
+
+| 缺口 | 状态 |
+| --- | --- |
+| 27 路温度 ↔ DIMM/腔体物理位置 | **UNKNOWN**,不虚构 |
+| 风扇实际 RPM | **NOT_SUPPORTED** |
+| PTC 实际功率/电流 | **NOT_SUPPORTED** |
+| 编码器 / 真实机械百分比闭环 | **NOT_SUPPORTED** |
+| 固件版本字符串 | **NOT_SUPPORTED** |
+| 设备源时间戳 | 不可用 |
+| ACK / 命令序号 | 无。SET_ALL 不能 CONFIRMED |
+| 设备主动故障队列 | 无;仅 MOTOR_STATUS 快照中的轴故障 |
+| 旧 jog 上位机心跳 `门=00` | 会把轴开到全开;无兼容层 |
+| USB VID/PID/serial | 仓库无真机值;udev **仅模板** |
+| Hardware validation | **NOT RUN** |
+
+## 产品范围外(有意不做)
+
+神经网络、RL、MPC、PID、Kafka、数据湖、MLflow、Kubernetes/Helm、Web 控制台、公网 REST、在 SDK 内做 observation 归一化。
+
+## 实现依赖(并行 Go 守护进程)
+
+Python SDK、文档、deploy 文件可独立审阅。`hthd` / `hthctl` / serial actor 由 Go 侧落地。若 `cmd/hthd` 尚未编译通过:
+
+- `MockClient` 仍可单测
+- 真实 UDS 集成测试标记为未跑
+- `hthd --check-config` 可能不可用
+
+## systemd Watchdog
+
+unit 使用 `Type=notify` 与 `WatchdogSec=30`。`hthd` 在监听就绪后发送 `READY=1`,并周期性发送 `WATCHDOG=1`。这只监控 **hthd 进程存活**,不能替代 Control Lease,也不能替代 FPGA 30s SET_ALL 看门狗。
+
+## 安全心跳与 jog 文档陷阱
+
+合同要求心跳重复连续目标且 **不把门改写为 0**。旧任务书曾写“心跳清零门 jog”。当前实现必须按 **百分比合同**,不能按 jog 清零。审查时若发现心跳把三门写成 0,视为缺陷(除非当时安全策略 **故意全开** 且文档如此——无 Lease 安全态可以是全开,那是政策,不是“空操作”)。
+
+## 本机 SDK 环境
+
+- 权威解释器 `/data/prod2u/bin/python3` 是 OSS CAD Suite 包装脚本,标准 `venv` 会链到 `libexec/python3.11` 并因缺少 `libpython` 崩溃。
+- 未提交的 `host/.venv-sdk` 使用 `--prefix` 布局 + 包装器,依赖装在该目录的 `site-packages`。
+- 清华 PyPI 镜像对 grpcio wheel 返回 403;阿里云镜像可用。
+- 曾误用 `pip install --prefix` 卸载 OSS CAD 的 setuptools,已恢复 `65.5.0`。后续安装必须 `--target` / 包装器,禁止改 OSS CAD site-packages。
+
+## 生成物
+
+- Python stubs 需 `grpcio-tools`;生成脚本:`host/tools/gen_python_stubs.py`
+- Profile 需仓库内 `src/generated/host-contract.json`(`tools/gen_profile.py`);L0 漂移检查:`host/tools/l0_contract_check.py`
+- 评审打包:`host/tools/package_hth_review.py`
+
+## 本轮验证
+
+| 项 | 状态 |
+| --- | --- |
+| `go test -race ./...` | **PASS**(gcc 14.2.0) |
+| Python 3.13 干净 venv + 仅 Wheel + Mock UDS | **PASS** |
+| Python 3.12 干净 venv + 仅 Wheel + Mock UDS | **PASS**(CPython 3.12.11) |
+| Python 3.11 干净 venv + 仅 Wheel + Mock UDS | **PASS**(CPython 3.11.13,非 OSS CAD) |
+| observer/controller/untrusted 真实账户 | **PASS** |
+| RTL `frame_rx` 字节级 SET_ALL oracle | **PASS** |
+| UART-bit Prod2U top cocotb(无 hthd) | **PASS** |
+| hthd + PTY + UART-bit + top | **PASS**(`RTL_HTHD_PTY_UART_BIT_PASS`;仿真专用 `CLKS_PER_BIT=8` wrapper,生产 RTL 未改) |
+| systemd-nspawn / QEMU Debian 部署 | **BLOCKED**(本 overlay 容器 PID1=sshd,无法 mount) |
+| `buf lint` / `buf breaking` | **PASS**(buf 1.47.2) |
+| Hardware validation | **NOT RUN** |
+
+总体软件验收在可 mount 的 systemd VM、24h soak、以及真机授权验证闭合前保持 **BLOCKED**。P0-1~P0-12 与本环境可证明的 L3 hthd-in-loop 已闭合。
+
+```text
+Hardware validation: NOT RUN
+Overall software acceptance: BLOCKED
+Architecture direction: PASS
+```
+
+不得使用“生产可用”“硬件验证通过”等措辞。

+ 62 - 0
docs/model-data-integration.zh-CN.md

@@ -0,0 +1,62 @@
+# 数据人员与模型人员如何接入
+
+本平台 **不是** 训练框架。这里只保证:能拿到带质量位的一致 Snapshot,以及在 Lease 下发原子 ActionBatch。
+
+## 数据人员(只读)
+
+1. 账号加入组 `hth-observe`(不要给 `hth-control`,除非职责需要)。
+2. 确认能访问 `/run/hth/observe.sock`(`srw-rw----`,组 `hth-observe`)。
+3. 安装 `hth-sdk`,**不要**打开 `/dev/ttyUSB*` 或 `/dev/hth/controller0`。
+4. 调用:
+
+```python
+devices = await client.list_devices()
+caps = await client.get_capabilities(devices[0].device_id)
+# caps.sensors[*].mapping_confidence 对温度是 UNKNOWN
+async for event in client.subscribe_telemetry(devices[0].device_id):
+    snap = event.snapshot
+```
+
+5. 使用稳定 ID `temperature.channel.00`…`26`。不要在自己的表里改名为 `dimm.7` 除非有 **额外的、本仓库以外的** 安装证据。
+6. 丢弃 `quality=INVALID` 的样本;不要把 255 当摄氏度。
+7. `source_timestamp_available=false`:用 Host 采集窗口,不要假装 27 路同时刻。
+8. `event.data_gap` 或 `device_epoch` 变化:从这一帧起重新对齐,不要做无说明插值。
+9. 风扇/PTC 的 `actual_quality=NOT_SUPPORTED`:只能记录 **命令目标**,不能当实测 RPM/功率训练标签,除非另有传感器。
+10. 门中间位置是 `ESTIMATED`。限位 bool 来自 MOTOR_STATUS,不是独立编码器。
+
+容器:只挂 observe socket,见部署文档。容器运行时挂了不能让你们“顺便”拿串口。
+
+## 模型 / 控制人员(写入)
+
+1. 组 `hth-control`,socket `/run/hth/control.sock`。仍 **禁止** 映射串口。
+2. `AcquireControlLease`。同一设备同时只有一个正式 holder。
+3. 每个控制周期:`GetSnapshot`(或订阅最新一帧)→ 组 `ActionBatch`(风扇+PTC+三门百分比一次提交)→ `ValidateAction` → `ApplyAction`。
+4. 填写 `based_on_snapshot_seq` 与 `expected_control_revision`,避免基于过期状态写门。
+5. 看返回的 requested / accepted / dispatched / **confirmation**。当前 confirmation 应为 `UNCONFIRMED`。不要在训练日志里写成 `executed=true`。
+6. `door.*.close_percent=0` 是命令 **全开**。若算法想“保持当前门”,应回写 **当前目标百分比**,而不是写 0。
+7. Lease 到期前 `Renew`。进程退出要 `Release`(SDK context manager 会做)。过期后守护进程转安全目标(FAN 10、PTC 0、门全开)。
+8. 先在 `hthd --backend=mock` 或 `MockClient` 上把闭环跑通。真机需要运维显式配置 serial backend,且 **Hardware validation: NOT RUN**。
+9. SDK 不提供 Reward、归一化向量、Replay Buffer。那些留在你们的训练代码里,并从 Snapshot 自己抽取。
+
+## 推荐最小循环(伪代码)
+
+```text
+lease = acquire(ttl=8s)
+loop:
+    snap = latest_snapshot()
+    if snap.lifecycle != READY: wait / safe
+    if snap.device_epoch != epoch: reacquire lease
+    batch = policy(snap)          # 连续目标,门为 close-percent
+    validate(batch)
+    result = apply(batch)
+    log(result.confirmation)      # UNCONFIRMED
+    sleep(sample_period)          # 不得低于 Profile 最小周期
+release(lease)
+```
+
+## 不要做的事
+
+- 多进程抢 Lease 当负载均衡
+- 用 GET_TEMPERATURE 当应用层 API(应由 hthd 采样)
+- 在 Jupyter 里 `pyserial` 直连
+- 把 mock 一阶温度曲线当成真实热模型辨识结果

+ 79 - 0
docs/operations.zh-CN.md

@@ -0,0 +1,79 @@
+# 运维
+
+## doctor
+
+```bash
+hthctl doctor
+```
+
+应检查:配置能否解析、Profile 能否解析、contract hash、API 版本 `hth.api.v1`、串口路径(serial 模式)、socket 路径、安全动作能否编码、心跳周期是否小于 30 s、Profile 与安装是否匹配。doctor **不**打开串口写危险动作。
+
+其它:
+
+```bash
+hthctl devices
+hthctl capabilities --device hood.0
+hthctl snapshot --device hood.0
+hthctl watch
+hthctl events
+hthctl faults
+hthctl health
+hthctl validate-action --file batch.json
+hthctl enter-safe-mode --device hood.0
+```
+
+`hthctl` 默认连接 mock/本地 socket 策略以实现安全:对真实 control endpoint 需要显式确认参数(与 SDK 示例相同精神)。它 **从不** 直接 open 串口。
+
+## 配置检查
+
+```bash
+hthd --check-config --config /etc/hth/hthd.yaml
+```
+
+未知字段报错。serial 模式缺安全值不得静默填默认。改安全合同通过 **重启** 生效,不做半热更新。
+
+## 日常观察
+
+```bash
+systemctl status hthd
+journalctl -u hthd -o short-iso --no-pager | tail
+ls -l /run/hth/*.sock
+# 不应出现 TCP 监听
+ss -lntp | grep hthd || true
+```
+
+生命周期卡在 `PROBING`:启动期温度无响应是 **合同行为**。看 `GET_MOTOR_STATUS` 的 `startup_complete`,不要用温度超时判死。
+
+`watchdog_tripped=1`:FPGA 已把 PTC 0 / FAN 10。恢复靠下一帧合法 SET_ALL。Host 应记录故障并避免把门心跳写成 0 以外的“创意值”。
+
+## 采集与 Replay
+
+```bash
+hth-capture --out /var/lib/hth/captures/run1
+# Replay 配置 backend.kind=replay,且必须拒绝打开真串口
+```
+
+Capture 是诊断工具,不是数据湖。Manifest 应含 api_version、profile hash、capability hash、起止时间。
+
+## 权限问题
+
+- `SERIAL_PERMISSION_DENIED`:`hth` 是否在串口组、udev MODE/GROUP 是否生效
+- 客户端 `Permission denied` on socket:用户是否在 `hth-observe` / `hth-control`,是否重新登录使组生效
+
+## 升级
+
+1. `hthd --check-config` 新配置  
+2. 安装新二进制与 Profile(hash 应与生成合同一致)  
+3. `systemctl restart hthd` — 旧 Lease 全部作废,控制客户端必须重拿  
+4. 核对 `api_version` 仍为 `hth.api.v1` 或按兼容性政策 bump
+
+## 明确禁止
+
+- 用 `kill -9` 当日常停止手段还指望安全帧一定发出  
+- 把 journal 关掉改无限写磁盘  
+- 在生产把 Reflection 开到不可信用户  
+- 声称“已经硬件验证通过”
+
+```text
+Hardware validation: NOT RUN
+```

+ 232 - 0
docs/protocol-source-audit.zh-CN.md

@@ -0,0 +1,232 @@
+# 协议来源审计(Host 实现依据)
+
+本文是 Linux 用户空间 `hthd` 实现真实串口 Profile **之前**的证据链审计。  
+权威顺序:当前活动项目配置与产品合同 → 与当前提交一致的生成 Host Contract / Golden Vectors → 活动需求与协议文档 → 当前 RTL 与测试所证明的行为。历史 jog 合同只用于识别“不要复活什么”,**不得作为实现依据**。
+
+## 1. 仓库与提交
+
+| 项 | 值 |
+| --- | --- |
+| 仓库 | `CPLD_temperature_control_board`(当前工作树;原 Cursor 工作区 `yocto-soc-fpga` 无 Prod2U 协议) |
+| 检出 | detached `HEAD` = `8fa4dcfbaaa4b049bca675fa4567c0a1b315f339` |
+| `dev` 指针 | `d4f3df2549efeb1e9227f62d1d71c6179c9f9160`(落后于当前 HEAD) |
+| HEAD 说明 | `docs(activity): bind Round-10 tip ff480c0 TD bitstream 299ef1cf` |
+| 工作树 | **脏**:大量已跟踪文件有未提交修改;存在无关未跟踪文件。Host 实现只新增 `host/`,不改 RTL、不覆盖用户未提交改动 |
+| 其它 worktree | `preview/door-percent-positioning`、若干历史 jog/motor worktree。不作为活动协议 |
+
+当前活动合同文件(工作树版本,含未提交修订):
+
+- `projects/prod2u-door-temp/project.json`
+- `projects/prod2u-door-temp/requirements.zh-CN.md`
+- `docs/prod2u-door-temp-protocol.zh-CN.md`
+- `AGENTS.md`
+- `src/generated/host-contract.json`
+- `src/generated/golden-vectors.json`
+- `src/generated/project-summary.json`
+- 参考模型:`tools/prod2u_simple_protocol.py`
+- RTL:`src/project/command_controller.v`、`src/modules/host_watchdog.v`、`src/modules/temperature_reader.v`
+
+**冲突结论(已选择证据链最完整的当前活动来源,未静默猜测):**
+
+任务合同第十一节仍按**旧 jog 语义**举例(`00=NO_NEW_JOG` / `01=OPEN_JOG` / `02=CLOSE_JOG`)。  
+当前活动合同、生成 Host Contract、Golden Vectors、RTL 与协议文档**一致地**声明这是一次**破坏性迁移**:门字节为闭合百分比 `0..100`,并新增 `GET_MOTOR_STATUS`。  
+Host **采用新合同**。旧 14 字节 SET_ALL、旧 `00/01/02` jog、旧 watchdog `10s→FAN20` **全部拒绝/不实现**。
+
+## 2. 采用的协议来源
+
+Profile ID 来自 `project.json`:`prod2u-normal-multiproject-115200-v1`。  
+Schema:`prod2u-simple-host-contract-v1`。  
+项目 ID:`prod2u-door-temp`。
+
+## 3. 帧格式
+
+```text
+A5 5A | type | payload_length | payload | crc16_low | crc16_high
+```
+
+- UART:115200 8N1,无流控;FPGA 侧 25 MHz、217 clocks/bit。
+- 帧头:`A5 5A`(`header_hex=A55A`)。
+- CRC:CRC-16/CCITT-FALSE;多项式 `0x1021`;初值 `0xFFFF`;不反射;xorout `0`;覆盖 **type + length + payload**;线上 **小端**。
+- 长度字段是 payload 字节数,不是整帧长度。整帧 = `6 + payload_length`。
+- 最大合法 payload:当前合同最长为 MOTOR_STATUS_DATA 的 31 字节。Host 解析器另设可配置硬上限(默认 64),拒绝攻击者给出的超大 length。
+- 旧 14 字节 SET_ALL:`legacy_payload_length_rejected=14`,整帧拒绝。
+
+## 4. 命令列表
+
+| Type | 名称 | 请求 payload | 响应 |
+| ---: | --- | ---: | --- |
+| `0x01` | SET_ALL | 11 | **无**(无 ACK) |
+| `0x02` | GET_TEMPERATURE | 0 | `0x82` TEMPERATURE_DATA(27 字节,整帧 33) |
+| `0x03` | GET_MOTOR_STATUS | 0 | `0x83` MOTOR_STATUS_DATA(31 字节,整帧 37) |
+| `0x82` | TEMPERATURE_DATA | 27 | 设备→Host |
+| `0x83` | MOTOR_STATUS_DATA | 31 | 设备→Host |
+
+Golden Vectors(`src/generated/golden-vectors.json`):
+
+| 键 | 十六进制 |
+| --- | --- |
+| `get_temperature` | `A55A02006D7B` |
+| `get_motor_status` | `A55A03005C48` |
+| `set_all_all_zero_full_open` | `A55A010B00000000000000000000005873` |
+| `set_all_doors_0_percent` | `A55A010B0A141E2800193264000000D584` |
+| `set_all_doors_50_percent` | `A55A010B0A141E2800193264323232F65A` |
+| `set_all_doors_100_percent` | `A55A010B0A141E2800193264646464B228` |
+| `all_invalid_temperature` | `A55A821B` + 27×`FF` + `A745` |
+| `set_all_legacy_14_rejected` | 长度标记 `0E`(不是合法帧) |
+| `set_all_door_0x65_rejected` | 门值 `65`(101)非法 |
+
+## 5. SET_ALL payload 语义(11 字节)
+
+| Offset | 字段 | 范围 |
+| ---: | --- | --- |
+| 0..3 | FAN 腔体 1..4 占空比 | 0..100 |
+| 4..7 | Chamber PTC 1..4 占空比 | 0..100(各复制到 2 路物理 PTC PWM) |
+| 8 | Z 门闭合百分比 | 0..100 |
+| 9 | X 门闭合百分比 | 0..100 |
+| 10 | Y 门闭合百分比 | 0..100 |
+
+任一 FAN/PTC/门越界、长度错误或 CRC 错误:**整帧拒绝**(不改热控、不改马达、不喂狗)。
+
+门百分比:
+
+| 值 | 领域语义 | 禁止命名 |
+| --- | --- | --- |
+| `0` | 全开端点;正常完成只认真实 open_limit | 不是 STOP / HOLD / 心跳空操作 |
+| `1..99` | 中间闭合百分比;开环步数估计 | 不是编码器绝对位置 |
+| `100` | 全关端点;正常完成只认真实 close_limit | — |
+| `101..255` | 非法,整帧拒绝 | — |
+
+合同明确:`all_zero_frame` = FAN/PTC=0 **且三门全开**,**不是** jog 心跳空操作。  
+旧上位机若把三门填 `00` 当心跳,会把三轴开到全开限位。
+
+控制模式:`PERCENT_CLOSE` + `latest-wins`。不是 `JOG_ONLY`。
+
+## 6. 温度值语义
+
+- 27 个无符号字节,FPGA 已把 CT7428 转成整数摄氏度(`ct7428-msb-integer`,`raw_shift=7`,拒绝符号位)。
+- `0xFF`(255)= 设备报告无效,**不得输出 255℃**。Host:`quality=INVALID`,`reason=DEVICE_REPORTED_INVALID`。
+- `maximum_celsius=150`:合法有效值应在 0..150;超过该范围且不是 0xFF 时标 `INVALID`(合同未给专用原因码,Host 用 `OUT_OF_DECLARED_RANGE`)。
+- 27 个值来自 3 个 I2C 地址 × 9 个寄存器的**依次采集**,不是同一纳秒。Host 记录请求发送、响应开始/完成、近似采集窗口;`source_timestamp` = **不可用**。
+- 稳定 ID:`temperature.channel.00` … `temperature.channel.26`。  
+  **不能证明**它们对应哪个 DIMM/腔体物理位置。Alias 映射 = `UNKNOWN`,不虚构 `hood.x.chamber.y.dimm.z`。
+
+## 7. Watchdog 如何被喂
+
+来源:`project.json` `watchdog.*`、协议文档、`command_controller.v` 的 `valid_set_all_commit`、`AGENTS.md`。
+
+| 项 | 当前合同 |
+| --- | --- |
+| 超时 | **30 s**(500 µs × 60000 tick) |
+| 使能 | 仅 `startup_complete` 之后 |
+| 喂狗事件 | **仅合法 SET_ALL commit**(含相同百分比重复帧) |
+| 不喂狗 | 任何 GET、非法帧、CRC 错误、越界 SET_ALL |
+| 超时动作 | PTC=0,FAN=10;禁止新 STEP 上升沿;保留 travel/current/requested;`watchdog_tripped=1` |
+| 恢复 | 下一帧合法 SET_ALL 清 tripped,并按该帧百分比重新规划运动 |
+| 门 | watchdog 优雅停(不截断当前 STEP 高脉冲);**不会**把门字节改写成 jog 空操作 |
+
+Host 安全心跳必须**重发当前真实连续目标(含三个门百分比)**,周期明显短于 30 s。  
+**禁止**把门填 0 当作“不动作心跳”。
+
+## 8. 启动期间是否接收命令
+
+标定(seek-close → measure-open,每轴 ≤5000 gated STEP):
+
+| 命令 | 启动期行为 |
+| --- | --- |
+| SET_ALL | 可更新 FAN/PTC;**忽略门百分比且不缓存**;合法帧仍 commit(RTL `valid_set_all_commit`),但 `motor_request_valid` 仅在 `startup_complete` 时置位。启动期 watchdog **未使能**,因此该 commit **不喂运行期 watchdog** |
+| GET_MOTOR_STATUS | **允许**,有 `0x83` 响应 |
+| GET_TEMPERATURE | **静默丢弃,无响应** |
+
+`startup_complete` 粘性置位直到 FPGA 上电/全局复位/重配置。  
+Host Readiness:以 `GET_MOTOR_STATUS` 返回 `startup_complete=1` 为可证明的通信/标定完成证据。首次合法温度响应只能作为“温度通道就绪”的附加证据,不能在启动期用温度超时判定设备死亡。
+
+## 9. 是否有 ACK
+
+**无 ACK / 无命令队列 / 无 ERROR 帧。**  
+`serial write` 成功只表示字节交给 OS/驱动。公共 API 的 `confirmation_status`:
+
+- 完整写出 SET_ALL:`UNCONFIRMED`(不是 `CONFIRMED`)
+- 短写或断开:`OUTCOME_UNKNOWN`
+- 不得把无 ACK 协议假装成 Exactly Once
+
+后续可用 `GET_MOTOR_STATUS` 观察 `requested_percent` / `moving` / 限位,作为**独立观测**,仍不把 SET_ALL 标成 `CONFIRMED`。
+
+## 10. 是否有设备状态查询
+
+有:`GET_MOTOR_STATUS` → 全局 byte0:
+
+- bit0..2:X/Y/Z calibrated mask
+- bit3..5:X/Y/Z fault mask
+- bit6:`startup_complete`
+- bit7:`watchdog_tripped`
+
+固件版本字符串:**协议不可读** → `NOT_SUPPORTED`。
+
+## 11. 是否有马达状态查询
+
+有。每轴 10 字节 × X,Y,Z:
+
+- state:`CAL_SEEK_CLOSE=0` … `FAULT=6`
+- flags:open_limit / close_limit / calibrated / moving / endpoint_mode / target_valid / replan_pending
+- `requested_percent`
+- `current_position` LE16(0=全开端,`travel_steps`=全关端)
+- `target_position` LE16
+- `travel_steps` LE16
+- `fault_code`:NONE / BOTH_LIMITS_ACTIVE / CAL_CLOSE_TIMEOUT / CAL_OPEN_TIMEOUT / INVALID_ZERO_OR_TINY_TRAVEL / ENDPOINT_TIMEOUT
+
+中间位置是开环 STEP 估计,质量必须是 `ESTIMATED`。  
+端点 0/100 在对应限位 flag 为真时,端点到达可标 `VALID`(限位是固件回报的真实开关量)。  
+**没有编码器。** 不暴露虚假的独立“实际百分比传感器”冒充闭环。可提供由 `current_position/travel_steps` 推导的估计闭合百分比,质量 `ESTIMATED`。
+
+限位:协议**回报** open/close limit flags,因此 Host readback = **SUPPORTED**(来自 MOTOR_STATUS,不是独立 GPIO 轮询)。原理图上的其它限位(如 LS4/HS4 inventory)若协议不返回,标 `NOT_SUPPORTED`。
+
+## 12. 是否有执行器实际反馈
+
+| 执行器 | 命令目标 | 实际反馈 |
+| --- | --- | --- |
+| FAN duty | SET_ALL 写入 | **无** RPM / 无读回 PWM。`actual_quality=NOT_SUPPORTED` |
+| PTC duty | SET_ALL 写入 | **无** 温度闭环确认(腔体温度是 27 通道,映射未知)。`actual_quality=NOT_SUPPORTED` |
+| 门百分比 | SET_ALL 写入 | MOTOR_STATUS 提供 requested / estimated position / limits / moving。位置 = 开环估计 |
+
+## 13. 能力证明分层
+
+### 能够证明(合同 + Golden + RTL)
+
+- 帧头、CRC、五种帧类型、11 字节 SET_ALL、27 温度、31 马达状态
+- 门百分比 0..100;越界整帧拒绝;旧 14 字节拒绝
+- 无 ACK
+- GET 不喂狗;合法 SET_ALL 在 `startup_complete` 后喂狗
+- watchdog 30 s → PTC 0 / FAN 10
+- 启动期丢温度 GET、允许马达状态 GET
+- 温度 0xFF 无效
+- 马达状态字段布局与 fault/state 枚举
+- 四腔 FAN/PTC 与腔体 1 三门的**逻辑**拓扑(来自 project.json,不是猜测 DIMM)
+
+### 只能静态配置(不能运行时从串口读出)
+
+- Profile / 连接器 / FPGA 球位 / PWM 极性 / 步频 / 限位球位
+- USB VID/PID / 串口序列号(仓库无真机采集值 → udev **模板**,不编造)
+- 安全心跳周期、Lease TTL、采样周期(Host 配置,受 Profile 约束)
+- 27 温度通道的物理安装位置
+
+### 完全无法取得
+
+- 固件版本字符串
+- 风扇实际 RPM
+- PTC 实际功率/电流
+- 编码器位置、真实机械百分比闭环
+- 设备主动上送的故障队列(只有马达状态快照里的轴故障码)
+- ACK / 命令序号
+- 传感器源时间戳
+- 硬件验证(**Hardware validation: NOT RUN**)
+
+## 14. Host 实现约束(本审计的直接后果)
+
+1. 领域 API 使用 `door.close_percent`,**禁止** `NO_NEW_JOG` 作为当前 Prod2U 的默认门语义。
+2. Watchdog 心跳 = 重发最新连续目标;门百分比保持用户/安全目标,**绝不改写为 0 当作空操作**。
+3. `CONFIRMED` 永不用于 SET_ALL。
+4. 含门目标变化的帧在结果不明时**不自动重发**;纯重复相同连续目标(幂等)由 Profile 声明允许作为心跳。
+5. 温度无效值不得变成 255℃。
+6. 温度稳定 ID 使用 channel 编号,不虚构 DIMM 映射。
+7. Readiness Probe = `startup_complete` 位,而不是“第一次温度成功”(启动期本来就不应答温度)。
+8. 真实串口 Profile 从 `host-contract.json` + `golden-vectors.json` **生成**,禁止手抄易漂移常量。

+ 119 - 0
docs/python-sdk-guide.zh-CN.md

@@ -0,0 +1,119 @@
+# Python SDK 指南
+
+包名:`hth-sdk`。导入:`import hth_sdk`。  
+依赖:**仅** `grpcio`、`protobuf`。不要把 NumPy / pandas / torch 加进该包。
+
+本 SDK **不打开串口**。真连接只走 Unix Socket。无 stubs / 无守护进程时,用 `MockClient` 做流程测试。
+
+## 安装
+
+```bash
+cd host/sdk/python
+python3 -m pip install -e .
+python3 -m pytest -q tests
+```
+
+生成 gRPC stubs(真实 `HthClient` 需要;Mock 不需要):
+
+```bash
+# 从 host/
+python3 tools/gen_python_stubs.py
+```
+
+`grpc_tools.protoc` 示例(脚本已封装 include 路径与 import 改写):
+
+```bash
+python3 -m grpc_tools.protoc \
+  -I api/proto \
+  -I "$(python3 -c 'import grpc_tools,pathlib; print(pathlib.Path(grpc_tools.__file__).parent/"_proto")')" \
+  --python_out=sdk/python/hth_sdk/generated \
+  --grpc_python_out=sdk/python/hth_sdk/generated \
+  api/proto/hth/api/v1/hth.proto
+```
+
+生成失败时:builders / exceptions / MockClient 仍可单测;`connect()` 会抛 `StubsNotGenerated`。
+
+## 连接
+
+```python
+from hth_sdk import connect_observe, connect_control, MockClient, API_VERSION
+
+# 1) 进程内 mock(默认教学路径)
+async with MockClient() as c:
+    snap = await c.get_snapshot("hood.0")
+
+# 2) 只读 UDS
+async with await connect_observe("/run/hth/observe.sock") as c:
+    caps = await c.get_capabilities("hood.0")
+    assert caps.api_version == API_VERSION
+
+# 3) 观察 + 控制
+async with await connect_control(
+    observe="/run/hth/observe.sock",
+    control="/run/hth/control.sock",
+) as c:
+    ...
+```
+
+`GetCapabilities.api_version` 必须等于 `hth.api.v1`,否则 `ApiVersionMismatch`。
+
+## 数据人员:订阅
+
+```python
+async for event in client.subscribe_telemetry("hood.0"):
+    snap = event.snapshot
+    if event.epoch_changed:
+        # 重连/重启:旧 seq 与旧 Lease 作废
+        ...
+    if event.data_gap:
+        # 有丢失,不要当连续采样
+        ...
+    t = snap.measurement("temperature.channel.00")
+    # t.quality 可能是 VALID / INVALID / STALE / ...
+```
+
+`GetSnapshot` 只读守护进程缓存。不要在客户端狂打 GET 温度。
+
+回调:`on_device_epoch_changed`、`on_data_gap`;或 `raise_on_epoch_change=True`。
+
+## 模型人员:Lease + ActionBatch
+
+```python
+from datetime import timedelta
+from hth_sdk import ActionBatch
+
+async with await client.acquire_lease("hood.0", "model-a", timedelta(seconds=8)) as lease:
+    batch = (
+        ActionBatch.builder("hood.0")
+        .based_on(snap.snapshot_seq, snap.control_revision)
+        .valid_for(timedelta(seconds=3))
+        .set_fan(1, 20)
+        .set_ptc(1, 0)
+        .set_door_close_percent("x", 0)  # 0 = 全开,不是 STOP
+        .build()
+    )
+    await lease.validate(batch)
+    result = await lease.apply(batch)
+    print(result.confirmation)  # 期望 UNCONFIRMED
+```
+
+- gRPC keepalive **不会**续 Lease;context manager 按 TTL/3 调用 `RenewControlLease`。
+- 不要把 `confirmation==UNCONFIRMED` 当成失败;那是当前协议的诚实结果。
+- 不要实现 Observation Vector / Reward / 训练循环(不属于 SDK)。
+
+## 示例
+
+| 文件 | 默认行为 |
+| --- | --- |
+| `examples/observe.py` | mock 订阅;`--socket` 才连守护进程 |
+| `examples/snapshot.py` | 打印实测/估计/不支持分类 |
+| `examples/control_mock.py` | **强制默认 mock**;真实 socket 需要 `--i-understand-this-is-real-hardware` 且即使启用也只发安全默认 |
+| `examples/capture.py` | 短 JSONL,不是数据平台 |
+
+## 异常
+
+`HthError`、`TransportError`、`ApiVersionMismatch`、`LeaseExpired` / `LeaseMismatch`、`ActionRejected`、`DeviceEpochChanged`、`DataGap`、`StubsNotGenerated`、`ConfirmationNotProven`。
+
+## 本地已知 ID
+
+SDK 默认校验 `fan.chamber.1..4`、`ptc.chamber.1..4`、`door.{x,y,z}.close_percent`,范围整数 0..100。未知 ID 本地拒绝。守护进程仍是权威。

+ 86 - 0
docs/safety-contract.zh-CN.md

@@ -0,0 +1,86 @@
+# 安全合同
+
+本文约束 Host 用户空间行为。FPGA 内部限位硬停仍由固件执行。  
+**Hardware validation: NOT RUN。**
+
+## 1. 门 0 不是 STOP
+
+当前活动合同是 `PERCENT_CLOSE`:
+
+| 值 | 安全含义 |
+| --- | --- |
+| 0 | **全开**。用户空间安全门默认。会驱动轴走向 open_limit |
+| 1..99 | 开环中间点 |
+| 100 | 全关 |
+
+禁止:
+
+- 把 `0` 叫做 STOP / HOLD / BRAKE / `NO_NEW_JOG`
+- 心跳时把三门改写成 `00`“空操作”
+- 在结果 `OUTCOME_UNKNOWN` 时自动重发 **门目标发生变化** 的帧
+
+心跳必须重复 **当前真实连续目标**(含门百分比),周期明显短于 30 s(Profile 默认 Host 5 s)。
+
+历史 jog 的 `NO_NEW_JOG` 不是当前默认语义。文档提及它只为防止旧上位机习惯回流。
+
+## 2. 无 ACK 不得声称已执行
+
+`serial write` 成功 ≠ 设备执行。
+
+| 写出结果 | confirmation |
+| --- | --- |
+| 完整 11 字节 SET_ALL 交给 OS | `UNCONFIRMED` |
+| 短写、断开、崩溃窗口 | `OUTCOME_UNKNOWN` |
+| 本地/守护进程拒绝 | `REJECTED` |
+| 硬件证明 | `CONFIRMED` — **当前 SET_ALL 禁用** |
+
+相同连续目标可作幂等心跳(Profile `idempotent_same_target`)。  
+`command_id` 缓存只防止重复 RPC 再写串口,**不能**把无 ACK 变成 Exactly Once。
+
+## 3. 用户空间安全目标
+
+与 FPGA watchdog 超时动作对齐,并明确门策略:
+
+| 执行器 | 安全值 | 来源 |
+| --- | --- | --- |
+| FAN | 10 | 合同 watchdog target;不是旧版 FAN 20 |
+| PTC | 0 | 合同 |
+| 门 close-percent | 0 | **全开政策**,不是 jog 空操作 |
+
+Lease 过期 / 无 Lease:尝试下发该安全 Action,随后只发安全心跳。串口已断开则记录 `SAFE_ACTION_NOT_DELIVERED`,最终靠 FPGA Watchdog(PTC 0 / FAN 10,停新 STEP 上升沿)。
+
+启动标定期间:PTC 0%、FAN 10%;门由标定 FSM 运动,SET_ALL 的门字节被忽略。
+
+## 4. Lease vs 其它心跳
+
+| 机制 | 作用 |
+| --- | --- |
+| Control Lease | 同一设备同一时刻一个正式写入者。过期 → 撤销控制权并转安全策略 |
+| gRPC keepalive | 仅保活 HTTP/2。**不能**代替 `RenewControlLease` |
+| systemd Watchdog | `hthd` 发送 `sd_notify` READY/WATCHDOG;只表示进程存活 |
+| FPGA Watchdog | 30 s;仅 startup 后合法 SET_ALL 喂狗。GET 不喂 |
+
+Daemon 重启、串口重连、Profile 变更 → 全部 Lease 作废。
+
+## 5. Clamp 与原子批
+
+- 默认:非法 ID / 越界 / 不支持 → **整批拒绝**
+- `allow_clamp=true`:必须在结果中列出原值、限制值、原因
+- `allow_clamp=false`:需要 clamp 则整批拒绝
+- 不要提供 `set_fan(); set_door();` 这种会夹在中间状态的分 API 作为正式控制路径
+
+## 6. 调度优先级
+
+安全态 > ApplyAction > 喂狗心跳 > 马达状态 GET > 温度 GET。  
+有待发控制时不要启动可能长达数秒的温度扫描。
+
+## 7. 容器与权限
+
+- 模型/数据容器:**不** `--device` 串口,**不** `--privileged`
+- 数据容器只挂 `observe.sock`
+- 控制容器才挂 `control.sock`,且仍须 Lease
+- 容器崩溃不影响 `hthd` 继续心跳(只要进程还在)
+
+## 8. 真机
+
+未经明确授权,示例与 SDK **默认 mock**。`control_mock.py` 拒绝未确认的真实 endpoint,即使确认也只发安全默认值(FAN 10 / PTC 0 / 门全开)。

+ 78 - 0
docs/signal-dictionary.zh-CN.md

@@ -0,0 +1,78 @@
+# 信号词典
+
+稳定 ID 来自 `profiles/prod2u-door-temp/profile.json`(由活动 `host-contract.json` + `golden-vectors.json` 生成)。  
+**禁止**为了“看起来完整”而虚构 DIMM 映射或 RPM。
+
+质量枚举:`VALID` `STALE` `MISSING` `INVALID` `ESTIMATED` `NOT_SUPPORTED` `UNKNOWN`。
+
+## 分类总表
+
+| 类别 | 含义 |
+| --- | --- |
+| **实测 (measured)** | 设备协议返回、Host 未改写语义的量 |
+| **估计 (estimated)** | Host 或开环 STEP 推导,必须带 `ESTIMATED` |
+| **不支持 (unsupported)** | 协议无法取得,quality=`NOT_SUPPORTED`,不得填假值 |
+
+## 温度 — 实测(值);映射 — UNKNOWN
+
+| ID | 单位 | 质量规则 |
+| --- | --- | --- |
+| `temperature.channel.00` … `temperature.channel.26` | degC | `0xFF` → `INVALID` + `DEVICE_REPORTED_INVALID`,**禁止输出 255℃**;超过声明 150℃ 且非 0xFF → `INVALID` / `OUT_OF_DECLARED_RANGE` |
+
+- 27 通道来自 3×I2C×9 寄存器**依次扫描**,不是同一纳秒。`source_timestamp_available=false`。
+- `hood_id`/`chamber_id`/`dimm_id` 当前为空或仅 `hood.0`。`mapping_confidence=UNKNOWN`。
+- 将来真实映射只能 **加 alias**,不能改掉 `temperature.channel.NN`。
+
+## 门位置 — 估计;端点限位 — 实测 flag
+
+| ID | 类别 | 说明 |
+| --- | --- | --- |
+| `door.{x,y,z}.close_percent` | 执行器目标 | 命令,不是传感器 |
+| `door.{x,y,z}.estimated_close_percent` | **估计** | `current_position/travel_steps`;中间点开环 |
+| `door.{x,y,z}.open_limit` | **实测 flag** | 来自 MOTOR_STATUS,非 Host GPIO |
+| `door.{x,y,z}.close_limit` | **实测 flag** | 同上 |
+
+端点 0/100 仅当对应限位 flag 为真时,端点到达可标 `VALID`。中间百分比不得冒充闭环编码器。
+
+**没有编码器。** `encoder_position = NOT_SUPPORTED`。
+
+## 执行器命令(无实际反馈)
+
+| ID | 范围 | 控制模式 | actual |
+| --- | --- | --- | --- |
+| `fan.chamber.1` … `4` | 0..100 % | `CONTINUOUS_DUTY` | RPM **NOT_SUPPORTED**;FPGA 输出风扇为 active-low |
+| `ptc.chamber.1` … `4` | 0..100 % | `CONTINUOUS_DUTY` | 功率/电流 **NOT_SUPPORTED**;一腔命令复制到 2 路物理 PTC PWM |
+| `door.x.close_percent` | 0..100 | `PERCENT_CLOSE` | 见上;SET_ALL offset X=9 |
+| `door.y.close_percent` | 0..100 | `PERCENT_CLOSE` | offset Y=10 |
+| `door.z.close_percent` | 0..100 | `PERCENT_CLOSE` | offset Z=8 |
+
+门:`0` = **全开**,不是 STOP。`101..255` 整帧拒绝。
+
+别名(诊断,不是新主键):`fan1`…、`heater.chamber.N`、`hood.0.chamber.1.door.{x,y,z}`。
+
+## 设备级状态(来自 GET_MOTOR_STATUS)
+
+全局 byte0:X/Y/Z calibrated、fault mask、`startup_complete`、`watchdog_tripped`。  
+每轴:state 枚举、flags、`requested_percent`、current/target/travel、fault_code。
+
+固件版本字符串:**不可读** → `NOT_SUPPORTED`。
+
+## 时间戳
+
+| 字段 | 状态 |
+| --- | --- |
+| Host `wall_time` / `monotonic_ns` | 有 |
+| 采集窗口 request/response/approx | Host 记录 |
+| 设备源时间戳 | **不可用** |
+
+## 明确不存在的信号
+
+- `fan.*.rpm`
+- `ptc.*.watts` / current
+- `door.*.encoder_counts`
+- `firmware.version` 字符串
+- 传感器安装位置(DIMM/腔体)—— UNKNOWN,不是“暂空字符串当已知”
+
+```text
+Hardware validation: NOT RUN
+```

+ 18 - 0
go.mod

@@ -0,0 +1,18 @@
+module hth
+
+go 1.25.0
+
+require (
+	go.uber.org/goleak v1.3.0
+	golang.org/x/sys v0.47.0
+	google.golang.org/grpc v1.82.1
+	google.golang.org/protobuf v1.36.12
+	gopkg.in/yaml.v3 v3.0.1
+)
+
+require (
+	github.com/kr/text v0.2.0 // indirect
+	golang.org/x/net v0.58.0 // indirect
+	golang.org/x/text v0.41.0 // indirect
+	google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 // indirect
+)

+ 56 - 0
go.sum

@@ -0,0 +1,56 @@
+github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
+github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
+github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
+github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
+github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
+github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
+github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
+github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
+github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
+github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
+github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
+go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
+go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
+go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
+go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
+go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
+go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
+go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
+go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
+go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=
+go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
+go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
+go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
+go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
+go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
+golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
+golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
+golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
+golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
+golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
+gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
+gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 h1:RmoJA1ujG+/lRGNfUnOMfhCy5EipVMyvUE+KNbPbTlw=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
+google.golang.org/grpc v1.82.1 h1:NnAxzGRA0677vCa4BUkOAnO5+FfQqVl9iUXeD0IqcGE=
+google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA=
+google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
+google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
+gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

+ 527 - 0
internal/app/app.go

@@ -0,0 +1,527 @@
+package app
+
+import (
+	"context"
+	"fmt"
+	"log/slog"
+	"os"
+	"sync"
+	"time"
+
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+	"google.golang.org/protobuf/types/known/durationpb"
+	"hth/internal/backend"
+	"hth/internal/config"
+	"hth/internal/device"
+	hthv1 "hth/internal/gen/hth/api/v1"
+	"hth/internal/grpcserver"
+	"hth/internal/profile"
+	"hth/internal/protocol"
+	"hth/internal/sdnotify"
+)
+
+var APIVersion = "hth.api.v1"
+
+type App struct {
+	Cfg      *config.Config
+	Profile  *profile.Profile
+	Dev      *device.Device
+	srv      *grpcserver.Servers
+	log      *slog.Logger
+	inst     string
+	stopOnce sync.Once
+}
+
+func CheckConfig(path, backendOverride string) error {
+	_, _, err := loadValidated(path, backendOverride)
+	if err != nil {
+		return err
+	}
+	fmt.Println("config: OK")
+	return nil
+}
+
+func loadValidated(path, backendOverride string) (*config.Config, *profile.Profile, error) {
+	if path == "" {
+		return nil, nil, fmt.Errorf("config path required")
+	}
+	cfg, err := config.Load(path)
+	if err != nil {
+		return nil, nil, err
+	}
+	if err := cfg.ApplyBackendOverride(backendOverride); err != nil {
+		return nil, nil, err
+	}
+	p, err := profile.LoadStrict(cfg.Profile)
+	if err != nil {
+		return nil, nil, err
+	}
+	if err := cfg.Validate(p); err != nil {
+		return nil, nil, err
+	}
+	if _, err := p.SafeSetAll().Payload(); err != nil {
+		return nil, nil, fmt.Errorf("safety SET_ALL not encodable: %w", err)
+	}
+	if _, err := protocol.Encode(protocol.TypeSetAll, mustPayload(p)); err != nil {
+		return nil, nil, err
+	}
+	return cfg, p, nil
+}
+
+func mustPayload(p *profile.Profile) []byte {
+	b, _ := p.SafeSetAll().Payload()
+	return b
+}
+
+func New(path, backendOverride string, log *slog.Logger) (*App, error) {
+	cfg, p, err := loadValidated(path, backendOverride)
+	if err != nil {
+		return nil, err
+	}
+	if log == nil {
+		log = slog.New(slog.NewTextHandler(os.Stderr, nil))
+	}
+	b, err := newBackend(cfg, p)
+	if err != nil {
+		return nil, err
+	}
+	inst := fmt.Sprintf("hthd-%d", time.Now().UnixNano())
+	dev := device.New(device.Params{Config: cfg, Profile: p, Backend: b, Logger: log, InstanceID: inst})
+	return &App{Cfg: cfg, Profile: p, Dev: dev, log: log, inst: inst}, nil
+}
+
+func (a *App) Run(ctx context.Context) error {
+	a.Dev.Start(ctx)
+	srv, err := grpcserver.Start(a.Cfg, a)
+	if err != nil {
+		a.Dev.Stop()
+		return err
+	}
+	a.srv = srv
+	a.log.Info("hthd listening", "observe", a.Cfg.Sockets.Observe, "control", a.Cfg.Sockets.Control, "backend", a.Cfg.Backend, "api", APIVersion)
+	if err := sdnotify.Ready(); err != nil {
+		a.log.Warn("sd_notify READY failed", "err", err)
+	}
+	var wdStop chan struct{}
+	if sdnotify.WatchdogEnabled() {
+		wdStop = make(chan struct{})
+		iv := sdnotify.WatchdogInterval()
+		if iv <= 0 {
+			iv = 10 * time.Second
+		}
+		go func() {
+			t := time.NewTicker(iv)
+			defer t.Stop()
+			for {
+				select {
+				case <-wdStop:
+					return
+				case <-t.C:
+					if a.watchdogOK() {
+						_ = sdnotify.Watchdog()
+					}
+				}
+			}
+		}()
+	}
+	select {
+	case <-ctx.Done():
+	case err := <-srv.ErrC:
+		a.log.Error("grpc server exited", "err", err)
+		if wdStop != nil {
+			close(wdStop)
+		}
+		a.shutdown()
+		_ = sdnotify.Stopping()
+		sdnotify.Close()
+		return err
+	}
+	if wdStop != nil {
+		close(wdStop)
+	}
+	a.shutdown()
+	_ = sdnotify.Stopping()
+	sdnotify.Close()
+	return nil
+}
+
+func (a *App) WatchdogShouldPet() bool {
+	return a.watchdogOK()
+}
+
+func (a *App) watchdogOK() bool {
+	if a.Dev == nil || a.srv == nil {
+		return false
+	}
+	if !a.srv.ObserveAlive() || !a.srv.ControlAlive() {
+		return false
+	}
+	maxTxn := a.Dev.MaxSerialTxn()
+	if a.Dev.SerialBusy() > maxTxn {
+		return false
+	}
+	prog := a.Dev.ActorProgress()
+	if prog.IsZero() || time.Since(prog) > maxTxn+2*time.Second {
+		return false
+	}
+	return true
+}
+
+func (a *App) shutdown() {
+	a.stopOnce.Do(func() {
+		if a.Dev != nil {
+			a.Dev.Stop()
+		}
+		if a.srv != nil {
+			a.srv.Stop()
+		}
+	})
+}
+
+func (a *App) Stop() {
+	a.shutdown()
+}
+
+func (a *App) device(id string) (*device.Device, error) {
+	if id == "" {
+		id = a.Cfg.DeviceID
+	}
+	if a.Dev == nil || a.Dev.ID() != id {
+		return nil, status.Errorf(codes.NotFound, "device %s", id)
+	}
+	return a.Dev, nil
+}
+
+func (a *App) ListDevices(context.Context) (*hthv1.ListDevicesResponse, error) {
+	return &hthv1.ListDevicesResponse{Devices: []*hthv1.DeviceInfo{a.Dev.Info()}}, nil
+}
+
+func (a *App) Capabilities(ctx context.Context, id string) (*hthv1.Capabilities, error) {
+	d, err := a.device(id)
+	if err != nil {
+		return nil, err
+	}
+	return d.Capabilities(), nil
+}
+
+func (a *App) Snapshot(ctx context.Context, id string) (*hthv1.Snapshot, error) {
+	d, err := a.device(id)
+	if err != nil {
+		return nil, err
+	}
+	return d.Snapshot(), nil
+}
+
+func (a *App) SubscribeTelemetry(ctx context.Context, id string, resume uint64, emit func(*hthv1.Snapshot) error) error {
+	d, err := a.device(id)
+	if err != nil {
+		return err
+	}
+	peer := peerKey(ctx)
+	sub, replay, gap, err := d.SubscribeTelemetry(resume, peer)
+	if err != nil {
+		return status.Error(codes.ResourceExhausted, err.Error())
+	}
+	defer sub.Cancel()
+	if gap != nil {
+		s := d.Snapshot()
+		if s != nil {
+			s.DataGap = true
+			s.DroppedTelemetryCount = gap.DroppedCount
+			if err := emit(s); err != nil {
+				return err
+			}
+		}
+	}
+	for _, s := range replay {
+		if err := emit(s); err != nil {
+			return err
+		}
+	}
+	for {
+		select {
+		case <-ctx.Done():
+			return nil
+		case s, ok := <-sub.C:
+			if !ok {
+				return nil
+			}
+			if err := emit(s); err != nil {
+				return err
+			}
+		}
+	}
+}
+
+func (a *App) SubscribeEvents(ctx context.Context, id string, resume uint64, emit func(*hthv1.Event) error) error {
+	d, err := a.device(id)
+	if err != nil {
+		return err
+	}
+	peer := peerKey(ctx)
+	sub, replay, gap, err := d.SubscribeEvents(resume, peer)
+	if err != nil {
+		return status.Error(codes.ResourceExhausted, err.Error())
+	}
+	defer sub.Cancel()
+	if gap != nil {
+		if err := emit(gap); err != nil {
+			return err
+		}
+	}
+	for _, e := range replay {
+		if err := emit(e); err != nil {
+			return err
+		}
+	}
+	for {
+		select {
+		case <-ctx.Done():
+			return nil
+		case e, ok := <-sub.C:
+			if !ok {
+				return nil
+			}
+			if err := emit(e); err != nil {
+				return err
+			}
+		}
+	}
+}
+
+func (a *App) Faults(ctx context.Context, id string, include bool) (*hthv1.GetFaultsResponse, error) {
+	d, err := a.device(id)
+	if err != nil {
+		return nil, err
+	}
+	return &hthv1.GetFaultsResponse{
+		Faults:                          d.Faults(include),
+		DeviceFaultQuerySupported:       false,
+		HostFaultReportingSupported:     true,
+		DeviceNativeFaultQuerySupported: false,
+		DeviceFaultSource:               "host_inferred; MOTOR_STATUS axis flags only; no device fault queue",
+	}, nil
+}
+
+func (a *App) WatchHealth(ctx context.Context, emit func(*hthv1.HealthStatus) error) error {
+	t := time.NewTicker(500 * time.Millisecond)
+	defer t.Stop()
+	send := func() error {
+		host := hthv1.HostHealth_HOST_HEALTH_SERVING
+		if a.srv != nil && (!a.srv.ObserveAlive() || !a.srv.ControlAlive()) {
+			host = hthv1.HostHealth_HOST_HEALTH_NOT_SERVING
+		}
+		msg := "process=SERVING"
+		if a.Dev != nil {
+			lc := a.Dev.Snapshot().GetLifecycle()
+			msg += fmt.Sprintf(" device_lifecycle=%s", lc.String())
+			switch a.Cfg.Backend {
+			case config.BackendReplay:
+				if a.Dev.ReplayComplete() {
+					msg += " replay_completion=COMPLETE device_readiness=REPLAY_COMPLETE control_availability=READ_ONLY"
+				} else {
+					msg += " replay_completion=IN_PROGRESS control_availability=READ_ONLY"
+				}
+			case config.BackendSerial, config.BackendMock:
+				snap := a.Dev.Snapshot()
+				if snap.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE ||
+					snap.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING ||
+					snap.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_RESUME_PENDING {
+					msg += " device_readiness=" + snap.GetDeviceReadiness().String() + " control_availability=SAFE_LATCHED"
+				} else if lc == hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_READY {
+					msg += " device_readiness=READY control_availability=AVAILABLE"
+				} else {
+					msg += " device_readiness=NOT_READY control_availability=UNAVAILABLE"
+				}
+			}
+		}
+		if a.srv != nil {
+			if a.srv.ObserveAlive() {
+				msg += " observe_server=ALIVE"
+			} else {
+				msg += " observe_server=DOWN"
+			}
+			if a.srv.ControlAlive() {
+				msg += " control_server=ALIVE"
+			} else {
+				msg += " control_server=DOWN"
+			}
+		}
+		hs := &hthv1.HealthStatus{
+			Host:    host,
+			Devices: []*hthv1.DeviceInfo{a.Dev.Info()},
+			Message: msg,
+		}
+		if a.srv != nil {
+			if a.srv.ObserveAlive() {
+				hs.ObserveService = hthv1.HostHealth_HOST_HEALTH_SERVING
+			} else {
+				hs.ObserveService = hthv1.HostHealth_HOST_HEALTH_NOT_SERVING
+			}
+			if a.srv.ControlAlive() {
+				hs.ControlService = hthv1.HostHealth_HOST_HEALTH_SERVING
+			} else {
+				hs.ControlService = hthv1.HostHealth_HOST_HEALTH_NOT_SERVING
+			}
+		}
+		if a.Dev != nil {
+			snap := a.Dev.Snapshot()
+			hs.TransportState = snap.GetTransportState()
+			hs.DeviceReadiness = snap.GetDeviceReadiness()
+			hs.SafetyControlMode = snap.GetSafetyControlMode()
+		}
+		return emit(hs)
+	}
+	if err := send(); err != nil {
+		return err
+	}
+	for {
+		select {
+		case <-ctx.Done():
+			return nil
+		case <-t.C:
+			if err := send(); err != nil {
+				return err
+			}
+		}
+	}
+}
+
+func (a *App) AcquireLease(ctx context.Context, req *hthv1.AcquireControlLeaseRequest) (*hthv1.ControlLease, error) {
+	d, err := a.device(req.DeviceId)
+	if err != nil {
+		return nil, err
+	}
+	ttl := time.Duration(0)
+	if req.Ttl != nil {
+		ttl = req.Ttl.AsDuration()
+	}
+	return d.AcquireLease(ctx, req.Holder, ttl)
+}
+
+func (a *App) RenewLease(ctx context.Context, req *hthv1.RenewControlLeaseRequest) (*hthv1.ControlLease, error) {
+	d, err := a.device(req.DeviceId)
+	if err != nil {
+		return nil, err
+	}
+	ttl := time.Duration(0)
+	if req.Ttl != nil {
+		ttl = req.Ttl.AsDuration()
+	}
+	return d.RenewLease(ctx, req.LeaseId, req.LeaseEpoch, ttl)
+}
+
+func (a *App) ReleaseLease(ctx context.Context, req *hthv1.ReleaseControlLeaseRequest) error {
+	d, err := a.device(req.DeviceId)
+	if err != nil {
+		return err
+	}
+	return d.ReleaseLease(ctx, req.LeaseId, req.LeaseEpoch)
+}
+
+func (a *App) ValidateAction(ctx context.Context, batch *hthv1.ActionBatch) (*hthv1.ActionResult, error) {
+	id := ""
+	if batch != nil {
+		id = batch.DeviceId
+	}
+	d, err := a.device(id)
+	if err != nil {
+		return nil, err
+	}
+	return d.ValidateAction(ctx, batch), nil
+}
+
+func (a *App) ApplyAction(ctx context.Context, batch *hthv1.ActionBatch) (*hthv1.ActionResult, error) {
+	id := ""
+	if batch != nil {
+		id = batch.DeviceId
+	}
+	d, err := a.device(id)
+	if err != nil {
+		return nil, err
+	}
+	return d.ApplyAction(ctx, batch), nil
+}
+
+func (a *App) EnterSafeMode(ctx context.Context, req *hthv1.EnterSafeModeRequest) (*hthv1.ActionResult, error) {
+	d, err := a.device(req.DeviceId)
+	if err != nil {
+		return nil, err
+	}
+	return d.EnterSafeMode(ctx, req.LeaseId, req.LeaseEpoch, req.Reason), nil
+}
+
+func (a *App) ResumeFromSafe(ctx context.Context, req *hthv1.ResumeFromSafeRequest) (*hthv1.ActionResult, error) {
+	d, err := a.device(req.DeviceId)
+	if err != nil {
+		return nil, err
+	}
+	return d.ResumeFromSafe(ctx, req.LeaseId, req.LeaseEpoch, req.Batch), nil
+}
+
+func (a *App) StepReplay(ctx context.Context, id string) (*hthv1.StepReplayResponse, error) {
+	d, err := a.device(id)
+	if err != nil {
+		return nil, err
+	}
+	res := d.StepReplay(ctx)
+	resp := &hthv1.StepReplayResponse{
+		Advanced: res.GetAccepted(),
+		Message:  res.GetMessage(),
+		Snapshot: d.LastStepSnapshot(),
+		Event:    d.LastStepEvent(),
+	}
+	if resp.Snapshot == nil {
+		resp.Snapshot = d.Snapshot()
+	}
+	if res.GetMessage() == "EOF" {
+		resp.Advanced = false
+		resp.Message = "EOF replay_completion=COMPLETE"
+	}
+	return resp, nil
+}
+
+func newBackend(cfg *config.Config, p *profile.Profile) (backend.Backend, error) {
+	switch cfg.Backend {
+	case config.BackendMock:
+		m := backend.NewMock(cfg.Mock.Seed, cfg.Mock.StartupComplete)
+		m.FirstOrderThermal = cfg.Mock.FirstOrderThermal
+		return m, nil
+	case config.BackendReplay:
+		rp := backend.NewReplay(cfg.Replay.Path, cfg.Replay.Speed, cfg.Replay.Step, cfg.Replay.FromEventID)
+		rp.SetContract(p.APIVersion, device.CapabilityHashOf(cfg, p))
+		return rp, nil
+	case config.BackendSerial:
+		return newSerialBackend(cfg, p)
+	default:
+		return nil, fmt.Errorf("unknown backend %s", cfg.Backend)
+	}
+}
+
+func DoctorText(cfg *config.Config, p *profile.Profile) string {
+	safe := p.SafeSetAll()
+	raw, _ := safe.Encode()
+	return fmt.Sprintf(
+		"api_version=%s\nprofile_id=%s rev=%s\nprofile_sha256=%s\ncontract_sha256=%s\ncapability_hash=%s\nbackend=%s\nserial_path=%s\nobserve=%s\ncontrol=%s\nheartbeat=%dms firmware_watchdog=%ds\nsafety_fan=%d safety_ptc=%d safety_door=%d (door 0=FULL OPEN)\nsafe_frame=%x\n",
+		APIVersion, p.ProfileID, p.ProfileRevision, p.FileSHA256, p.SourceContractSHA256, device.CapabilityHashOf(cfg, p),
+		cfg.Backend, cfg.Serial.Path, cfg.Sockets.Observe, cfg.Sockets.Control,
+		cfg.Watchdog.HeartbeatPeriodMS, p.Watchdog.TimeoutSeconds,
+		safe.Fan[0], safe.PTC[0], safe.DoorX, raw,
+	)
+}
+
+func TTL(d *durationpb.Duration) time.Duration {
+	if d == nil {
+		return 0
+	}
+	return d.AsDuration()
+}
+
+func peerKey(ctx context.Context) string {
+	cred, ok := grpcserver.PeerFromContext(ctx)
+	if !ok || cred.PID == 0 {
+		return ""
+	}
+	return fmt.Sprintf("uid=%d,gid=%d,pid=%d", cred.UID, cred.GID, cred.PID)
+}

+ 23 - 0
internal/app/backend_linux.go

@@ -0,0 +1,23 @@
+//go:build linux
+
+package app
+
+import (
+	"time"
+
+	"hth/internal/backend"
+	"hth/internal/config"
+	"hth/internal/profile"
+)
+
+func newSerialBackend(cfg *config.Config, p *profile.Profile) (backend.Backend, error) {
+	inter := p.InterByteTimeout()
+	if cfg.Serial.InterByteTimeoutMS > 0 {
+		inter = time.Duration(cfg.Serial.InterByteTimeoutMS) * time.Millisecond
+	}
+	resp := p.GetResponseTimeout()
+	if cfg.Serial.ResponseTimeoutMS > 0 {
+		resp = time.Duration(cfg.Serial.ResponseTimeoutMS) * time.Millisecond
+	}
+	return backend.NewSerial(cfg.Serial.Path, inter, resp), nil
+}

+ 131 - 0
internal/backend/backend.go

@@ -0,0 +1,131 @@
+package backend
+
+import (
+	"context"
+	"errors"
+	"time"
+
+	"hth/internal/protocol"
+)
+
+var (
+	ErrReadOnly        = errors.New("backend is read-only")
+	ErrNotConnected    = errors.New("backend not connected")
+	ErrReplaySerial    = errors.New("replay backend refuses to open a real serial device")
+	ErrStreamUntrusted = errors.New("uart stream untrusted; reconnect required")
+	ErrWriteNotStarted = errors.New("serial write not started")
+)
+
+type WriteOutcome int
+
+const (
+	WriteNotStarted WriteOutcome = iota
+	WriteFullyWritten
+	WritePartiallyWritten
+	WriteFullyWrittenWithError
+	WriteOutcomeUnknown
+	WriteDisconnected
+)
+
+// Historical aliases used by existing tests.
+const (
+	WriteFull      = WriteFullyWritten
+	WriteShort     = WritePartiallyWritten
+	WriteAmbiguous = WriteFullyWrittenWithError
+)
+
+func (o WriteOutcome) String() string {
+	switch o {
+	case WriteNotStarted:
+		return "NOT_STARTED"
+	case WriteFullyWritten:
+		return "FULLY_WRITTEN"
+	case WritePartiallyWritten:
+		return "PARTIALLY_WRITTEN"
+	case WriteFullyWrittenWithError:
+		return "FULLY_WRITTEN_WITH_ERROR"
+	case WriteDisconnected:
+		return "DISCONNECTED"
+	default:
+		return "OUTCOME_UNKNOWN"
+	}
+}
+
+// WriteNeedsReconnect reports outcomes that may have left the UART parser
+// misaligned. The transport must be closed; the original action is never
+// auto-replayed.
+func WriteNeedsReconnect(wr WriteResult, err error) bool {
+	if wr.Outcome == WriteNotStarted {
+		return false
+	}
+	if err != nil && wr.Outcome == WriteFullyWritten {
+		return true
+	}
+	switch wr.Outcome {
+	case WritePartiallyWritten, WriteFullyWrittenWithError, WriteDisconnected, WriteOutcomeUnknown:
+		return true
+	default:
+		return err != nil
+	}
+}
+
+type WriteResult struct {
+	Outcome WriteOutcome
+	N       int
+}
+
+type TimeWindow struct {
+	RequestSent      time.Time
+	RequestComplete  time.Time
+	ResponseStart    time.Time
+	ResponseComplete time.Time
+	HostReceive      time.Time
+}
+
+type TempReport struct {
+	Samples []protocol.TemperatureSample
+	Window  TimeWindow
+	Raw     []byte
+}
+
+type MotorReport struct {
+	Status protocol.MotorStatus
+	Window TimeWindow
+	Raw    []byte
+}
+
+type PollMode int
+
+const (
+	PollUART PollMode = iota
+	PollReplay
+)
+
+type Backend interface {
+	Kind() string
+	PollMode() PollMode
+	Open(ctx context.Context) error
+	Close() error
+	WriteSetAll(ctx context.Context, s protocol.SetAll) (WriteResult, error)
+	GetTemperature(ctx context.Context) (*TempReport, error)
+	GetMotorStatus(ctx context.Context) (*MotorReport, error)
+}
+
+// Interrupter unblocks an in-flight Read without requiring the caller to hold
+// the transaction mutex. Serial Close/Interrupt must not wait for txnMu.
+type Interrupter interface {
+	Interrupt()
+}
+
+type ReplayItem struct {
+	Kind     string
+	EventID  uint64
+	WallTime time.Time
+	Snapshot []byte
+	Event    []byte
+}
+
+type Replayer interface {
+	Backend
+	Next(ctx context.Context) (ReplayItem, error)
+}

+ 104 - 0
internal/backend/backend_test.go

@@ -0,0 +1,104 @@
+package backend_test
+
+import (
+	"context"
+	"os"
+	"path/filepath"
+	"testing"
+	"time"
+
+	"google.golang.org/protobuf/types/known/timestamppb"
+	"hth/internal/backend"
+	"hth/internal/capture"
+	hthv1 "hth/internal/gen/hth/api/v1"
+	"hth/internal/protocol"
+)
+
+func TestMockDeterministicInvalidAndThermal(t *testing.T) {
+	m := backend.NewMock(1, true)
+	ctx := context.Background()
+	a, err := m.GetTemperature(ctx)
+	if err != nil {
+		t.Fatal(err)
+	}
+	m2 := backend.NewMock(1, true)
+	b, err := m2.GetTemperature(ctx)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if a.Samples[0].Raw != b.Samples[0].Raw {
+		t.Fatal("deterministic")
+	}
+	if a.Window.ResponseStart.Equal(a.Window.RequestComplete) || a.Window.ResponseStart.Before(a.Window.RequestComplete) && !a.Window.RequestComplete.After(a.Window.RequestSent) {
+		if !a.Window.ResponseStart.After(a.Window.RequestComplete) {
+			t.Fatalf("response start must be after request complete: %+v", a.Window)
+		}
+	}
+	m.SetInvalidChannel(3, true)
+	c, err := m.GetTemperature(ctx)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if c.Samples[3].Quality != protocol.TempDeviceInvalid || c.Samples[3].Celsius != 0 {
+		t.Fatalf("invalid must not be 255C: %+v", c.Samples[3])
+	}
+	_, err = m.WriteSetAll(ctx, protocol.SetAll{PTC: [4]uint8{100, 100, 100, 100}, Fan: [4]uint8{0, 0, 0, 0}})
+	if err != nil {
+		t.Fatal(err)
+	}
+	before := c.Samples[0].Celsius
+	var later float64
+	for i := 0; i < 20; i++ {
+		r, err := m.GetTemperature(ctx)
+		if err != nil {
+			t.Fatal(err)
+		}
+		later = r.Samples[0].Celsius
+	}
+	if later <= before {
+		t.Fatalf("first-order thermal should rise (test fixture, not physics): %v -> %v", before, later)
+	}
+}
+
+func TestReplayRefusesSerialPath(t *testing.T) {
+	r := backend.NewReplay("/dev/ttyUSB0", 1, true, 0)
+	if err := r.Open(context.Background()); err == nil {
+		t.Fatal("must refuse serial")
+	}
+}
+
+func TestReplayReadsCapture(t *testing.T) {
+	dir := t.TempDir()
+	f, err := os.Create(capture.RecordsPath(dir))
+	if err != nil {
+		t.Fatal(err)
+	}
+	s := &hthv1.Snapshot{DeviceId: "d0", SnapshotSeq: 1, EventId: 5, DeviceEpoch: 2, WallTime: timestamppb.New(time.Unix(10, 0))}
+	rec, err := capture.SnapshotRecord(s)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if err := capture.AppendRecord(f, rec); err != nil {
+		t.Fatal(err)
+	}
+	f.Close()
+	man := capture.Manifest{
+		APIVersion: "hth.api.v1", DeviceID: "d0", Status: capture.StatusComplete,
+		ProfileHash: "profile-test", CapabilityHash: "cap-test",
+	}
+	if err := capture.Seal(dir, man); err != nil {
+		t.Fatal(err)
+	}
+	r := backend.NewReplay(dir, 1000, true, 0)
+	if err := r.Open(context.Background()); err != nil {
+		t.Fatal(err)
+	}
+	item, err := r.Next(context.Background())
+	if err != nil {
+		t.Fatal(err)
+	}
+	if item.EventID != 5 {
+		t.Fatalf("event %d", item.EventID)
+	}
+	_ = filepath.Separator
+}

+ 22 - 0
internal/backend/classify.go

@@ -0,0 +1,22 @@
+package backend
+
+import (
+	"errors"
+	"os"
+)
+
+func ClassifyOpen(err error) string {
+	if err == nil {
+		return ""
+	}
+	if os.IsNotExist(err) {
+		return "not_found"
+	}
+	if os.IsPermission(err) {
+		return "permission"
+	}
+	if errors.Is(err, ErrNotConnected) {
+		return "disconnected"
+	}
+	return "other"
+}

+ 369 - 0
internal/backend/mock.go

@@ -0,0 +1,369 @@
+package backend
+
+import (
+	"context"
+	"errors"
+	"math"
+	"sync"
+	"time"
+
+	"hth/internal/protocol"
+)
+
+// Mock is a deterministic UART-equivalent backend.
+// The optional first-order thermal update is NOT a physics model; it exists
+// only for interface and control-loop tests.
+type Mock struct {
+	mu sync.Mutex
+
+	Seed              int64
+	StartupComplete   bool
+	FirstOrderThermal bool
+	Slow              time.Duration
+	SlowGet           time.Duration
+
+	disconnected  bool
+	closed        bool
+	shortOnce     bool
+	ambiguousOnce bool
+	hangGetOnce   bool
+	hangingGet    bool
+	hangGen       uint64
+	invalid       [protocol.TemperaturePayloadLen]bool
+	temps         [protocol.TemperaturePayloadLen]float64
+	setAll        protocol.SetAll
+	writes        []protocol.SetAll
+	ticks         int
+	tempGets      int
+	motorGets     int
+	openedAt      time.Time
+	StartupDelay  time.Duration
+	travel        uint16
+	pos           [3]uint16 // x,y,z current
+}
+
+func NewMock(seed int64, startupComplete bool) *Mock {
+	m := &Mock{Seed: seed, StartupComplete: startupComplete, travel: 1000, FirstOrderThermal: true}
+	for i := range m.temps {
+		m.temps[i] = 25
+	}
+	for i := range m.setAll.Fan {
+		m.setAll.Fan[i] = 10
+	}
+	return m
+}
+
+func (m *Mock) Kind() string       { return "mock" }
+func (m *Mock) PollMode() PollMode { return PollUART }
+
+func (m *Mock) Open(context.Context) error {
+	m.mu.Lock()
+	m.openedAt = time.Now()
+	m.closed = false
+	m.disconnected = false
+	m.mu.Unlock()
+	return nil
+}
+
+func (m *Mock) Close() error {
+	m.mu.Lock()
+	m.closed = true
+	m.hangGen++
+	m.mu.Unlock()
+	return nil
+}
+
+// Interrupt unblocks a hung Get that ignores context. Close and Interrupt
+// must not wait for an in-flight protocol mutex.
+func (m *Mock) Interrupt() {
+	_ = m.Close()
+}
+
+func (m *Mock) TempGetCount() int {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	return m.tempGets
+}
+
+func (m *Mock) MotorGetCount() int {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	return m.motorGets
+}
+
+func (m *Mock) SetDisconnected(v bool) {
+	m.mu.Lock()
+	m.disconnected = v
+	m.mu.Unlock()
+}
+
+func (m *Mock) ForceShortWrite() {
+	m.mu.Lock()
+	m.shortOnce = true
+	m.mu.Unlock()
+}
+
+func (m *Mock) ForceAmbiguousWrite() {
+	m.mu.Lock()
+	m.ambiguousOnce = true
+	m.mu.Unlock()
+}
+
+func (m *Mock) SetInvalidChannel(i int, inv bool) {
+	m.mu.Lock()
+	if i >= 0 && i < len(m.invalid) {
+		m.invalid[i] = inv
+	}
+	m.mu.Unlock()
+}
+
+func (m *Mock) SetSlow(d time.Duration) {
+	m.mu.Lock()
+	m.Slow = d
+	m.mu.Unlock()
+}
+
+func (m *Mock) SetSlowGet(d time.Duration) {
+	m.mu.Lock()
+	m.SlowGet = d
+	m.mu.Unlock()
+}
+
+func (m *Mock) SetStartupComplete(v bool) {
+	m.mu.Lock()
+	m.StartupComplete = v
+	m.mu.Unlock()
+}
+
+// SetHangGetOnce makes the next GetTemperature ignore context until Close/Interrupt.
+func (m *Mock) SetHangGetOnce() {
+	m.mu.Lock()
+	m.hangGetOnce = true
+	m.mu.Unlock()
+}
+
+func (m *Mock) Writes() []protocol.SetAll {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	out := make([]protocol.SetAll, len(m.writes))
+	copy(out, m.writes)
+	return out
+}
+
+func (m *Mock) LastSetAll() protocol.SetAll {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	return m.setAll
+}
+
+func (m *Mock) WriteCount() int {
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	return len(m.writes)
+}
+
+func (m *Mock) WriteSetAll(ctx context.Context, s protocol.SetAll) (WriteResult, error) {
+	m.mu.Lock()
+	slow := m.Slow
+	m.mu.Unlock()
+	if slow > 0 {
+		deadline := time.NewTimer(slow)
+		defer deadline.Stop()
+		ticker := time.NewTicker(5 * time.Millisecond)
+		defer ticker.Stop()
+		for {
+			m.mu.Lock()
+			closed := m.closed
+			m.mu.Unlock()
+			if closed {
+				return WriteResult{Outcome: WriteDisconnected}, ErrNotConnected
+			}
+			select {
+			case <-ctx.Done():
+				return WriteResult{Outcome: WriteNotStarted}, ctx.Err()
+			case <-deadline.C:
+				goto afterSlow
+			case <-ticker.C:
+			}
+		}
+	}
+afterSlow:
+	if err := ctx.Err(); err != nil {
+		return WriteResult{Outcome: WriteNotStarted}, err
+	}
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	if m.disconnected || m.closed {
+		return WriteResult{Outcome: WriteDisconnected}, ErrNotConnected
+	}
+	if m.shortOnce {
+		m.shortOnce = false
+		return WriteResult{Outcome: WriteShort, N: 3}, nil
+	}
+	if m.ambiguousOnce {
+		m.ambiguousOnce = false
+		n := protocol.MinFrameLen + protocol.SetAllPayloadLen
+		return WriteResult{Outcome: WriteAmbiguous, N: n}, errors.New("injected full write error")
+	}
+	m.setAll = s
+	m.writes = append(m.writes, s)
+	m.pos[0] = uint16(float64(m.travel) * float64(s.DoorX) / 100)
+	m.pos[1] = uint16(float64(m.travel) * float64(s.DoorY) / 100)
+	m.pos[2] = uint16(float64(m.travel) * float64(s.DoorZ) / 100)
+	return WriteResult{Outcome: WriteFull, N: protocol.MinFrameLen + protocol.SetAllPayloadLen}, nil
+}
+
+func (m *Mock) GetTemperature(ctx context.Context) (*TempReport, error) {
+	sent := time.Now()
+	m.mu.Lock()
+	if m.hangGetOnce {
+		m.hangGetOnce = false
+		m.hangingGet = true
+	}
+	hang := m.hangingGet
+	slow := m.SlowGet
+	if slow == 0 {
+		slow = m.Slow
+	}
+	m.mu.Unlock()
+	if hang {
+		m.mu.Lock()
+		gen := m.hangGen
+		m.mu.Unlock()
+		for {
+			m.mu.Lock()
+			moved := m.hangGen != gen
+			m.mu.Unlock()
+			if moved {
+				m.mu.Lock()
+				m.hangingGet = false
+				m.mu.Unlock()
+				return nil, ErrNotConnected
+			}
+			time.Sleep(5 * time.Millisecond)
+		}
+	}
+	if slow > 0 {
+		select {
+		case <-ctx.Done():
+			return nil, ctx.Err()
+		case <-time.After(slow):
+		}
+	}
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	if m.disconnected || m.closed {
+		return nil, ErrNotConnected
+	}
+	m.tempGets++
+	m.ticks++
+	if m.FirstOrderThermal {
+		m.stepThermal(1.0)
+	}
+	raw := make([]byte, protocol.TemperaturePayloadLen)
+	for i := range raw {
+		if m.invalid[i] {
+			raw[i] = protocol.TempInvalid
+		} else {
+			v := int(math.Round(m.temps[i]))
+			if v < 0 {
+				v = 0
+			}
+			if v > 150 {
+				v = 150
+			}
+			raw[i] = byte(v)
+		}
+	}
+	frame, err := protocol.EncodeTemperature(raw)
+	if err != nil {
+		return nil, err
+	}
+	dec, err := protocol.Decode(frame)
+	if err != nil {
+		return nil, err
+	}
+	samples, err := protocol.DecodeTemperature(dec)
+	if err != nil {
+		return nil, err
+	}
+	done := time.Now()
+	return &TempReport{Samples: samples, Raw: frame, Window: TimeWindow{
+		RequestSent: sent, RequestComplete: sent.Add(200 * time.Microsecond),
+		ResponseStart:    sent.Add(time.Millisecond),
+		ResponseComplete: done, HostReceive: done,
+	}}, nil
+}
+
+func (m *Mock) GetMotorStatus(ctx context.Context) (*MotorReport, error) {
+	if err := ctx.Err(); err != nil {
+		return nil, err
+	}
+	sent := time.Now()
+	m.mu.Lock()
+	defer m.mu.Unlock()
+	if m.disconnected || m.closed {
+		return nil, ErrNotConnected
+	}
+	m.motorGets++
+	startup := m.StartupComplete
+	if !startup && m.StartupDelay > 0 && !m.openedAt.IsZero() && time.Since(m.openedAt) >= m.StartupDelay {
+		startup = true
+	}
+	st := protocol.MotorStatus{StartupComplete: startup, CalibratedMask: 0x07}
+	st.X = m.axis(m.setAll.DoorX, m.pos[0])
+	st.Y = m.axis(m.setAll.DoorY, m.pos[1])
+	st.Z = m.axis(m.setAll.DoorZ, m.pos[2])
+	raw, err := protocol.EncodeMotorStatus(st)
+	if err != nil {
+		return nil, err
+	}
+	f, err := protocol.Decode(raw)
+	if err != nil {
+		return nil, err
+	}
+	ms, err := protocol.DecodeMotorStatus(f)
+	if err != nil {
+		return nil, err
+	}
+	done := time.Now()
+	return &MotorReport{Status: ms, Raw: raw, Window: TimeWindow{
+		RequestSent: sent, RequestComplete: sent.Add(200 * time.Microsecond),
+		ResponseStart: sent.Add(time.Millisecond), ResponseComplete: done, HostReceive: done,
+	}}, nil
+}
+
+func (m *Mock) axis(req uint8, pos uint16) protocol.AxisStatus {
+	flags := protocol.FlagCalibrated | protocol.FlagTargetValid
+	if req == 0 {
+		flags |= protocol.FlagOpenLimit
+	}
+	if req == 100 {
+		flags |= protocol.FlagCloseLimit
+	}
+	return protocol.AxisStatus{
+		State:            protocol.AxisIdle,
+		Flags:            flags,
+		RequestedPercent: req,
+		CurrentPosition:  pos,
+		TargetPosition:   pos,
+		TravelSteps:      m.travel,
+	}
+}
+
+func (m *Mock) stepThermal(dt float64) {
+	var heat, cool float64
+	for _, v := range m.setAll.PTC {
+		heat += float64(v)
+	}
+	for _, v := range m.setAll.Fan {
+		cool += float64(v)
+	}
+	heat /= 400
+	cool /= 400
+	target := 25 + 80*heat - 30*cool
+	alpha := 1 - math.Exp(-dt/30)
+	for i := range m.temps {
+		m.temps[i] += (target - m.temps[i]) * alpha
+	}
+}

+ 207 - 0
internal/backend/replay.go

@@ -0,0 +1,207 @@
+package backend
+
+import (
+	"context"
+	"fmt"
+	"os"
+	"path/filepath"
+	"strings"
+	"sync"
+	"time"
+
+	"hth/internal/capture"
+	"hth/internal/protocol"
+)
+
+var ErrReplayEOF = fmt.Errorf("replay: end of capture")
+
+const maxReplayRecords = 1_000_000
+
+type Replay struct {
+	path            string
+	speed           float64
+	step            bool
+	fromEventID     uint64
+	requireComplete bool
+	apiVersion      string
+	capHash         string
+
+	mu       sync.Mutex
+	items    []ReplayItem
+	idx      int
+	lastWall time.Time
+	haveLast bool
+	stepCh   chan struct{}
+}
+
+func NewReplay(path string, speed float64, step bool, fromEventID uint64) *Replay {
+	if speed <= 0 {
+		speed = 1
+	}
+	return &Replay{
+		path: path, speed: speed, step: step, fromEventID: fromEventID,
+		requireComplete: true,
+		stepCh:          make(chan struct{}, 1),
+	}
+}
+
+func (r *Replay) SetContract(apiVersion, capHash string) {
+	r.apiVersion = apiVersion
+	r.capHash = capHash
+}
+
+func (r *Replay) Kind() string       { return "replay" }
+func (r *Replay) PollMode() PollMode { return PollReplay }
+func (r *Replay) Stepping() bool     { return r.step }
+
+func looksLikeSerial(path string) bool {
+	p := strings.ToLower(path)
+	return strings.HasPrefix(p, "/dev/tty") ||
+		strings.HasPrefix(p, "/dev/hth") ||
+		strings.HasPrefix(p, "/dev/serial") ||
+		strings.Contains(p, "ttyusb") ||
+		strings.Contains(p, "ttyacm")
+}
+
+func (r *Replay) Open(context.Context) error {
+	if looksLikeSerial(r.path) {
+		return fmt.Errorf("%w: %s", ErrReplaySerial, r.path)
+	}
+	fi, err := os.Stat(r.path)
+	if err != nil {
+		return err
+	}
+	if fi.Mode()&os.ModeDevice != 0 || fi.Mode()&os.ModeCharDevice != 0 {
+		return fmt.Errorf("%w: %s is a device node", ErrReplaySerial, r.path)
+	}
+	dir := r.path
+	recPath := r.path
+	if fi.IsDir() {
+		recPath = capture.RecordsPath(r.path)
+	} else {
+		dir = filepath.Dir(r.path)
+	}
+	man, err := capture.ReadManifest(dir)
+	if err != nil {
+		return fmt.Errorf("capture: manifest required: %w", err)
+	}
+	if err := capture.ValidateManifest(man, r.apiVersion, r.capHash, r.requireComplete); err != nil {
+		return err
+	}
+	rfi, err := os.Stat(recPath)
+	if err != nil {
+		return err
+	}
+	if rfi.Size() > capture.MaxRecordsBytes {
+		return fmt.Errorf("capture: records size %d exceeds %d", rfi.Size(), capture.MaxRecordsBytes)
+	}
+	if rfi.Size() == 0 {
+		return fmt.Errorf("capture: empty records")
+	}
+	raw, err := os.ReadFile(recPath)
+	if err != nil {
+		return err
+	}
+	if raw[len(raw)-1] != '\n' {
+		return fmt.Errorf("capture: truncated records.jsonl (missing trailing newline)")
+	}
+	recSHA, err := capture.HashFile(recPath)
+	if err != nil {
+		return err
+	}
+	recs, err := capture.ReadRecords(recPath)
+	if err != nil {
+		return fmt.Errorf("capture: records: %w", err)
+	}
+	if err := capture.ValidateRecordsAgainstManifest(man, recs, recSHA); err != nil {
+		return err
+	}
+	if len(recs) > maxReplayRecords {
+		return fmt.Errorf("capture: %d records exceeds limit %d", len(recs), maxReplayRecords)
+	}
+	r.mu.Lock()
+	defer r.mu.Unlock()
+	r.items = r.items[:0]
+	for _, rec := range recs {
+		if rec.V != 0 && rec.V != capture.Version {
+			return fmt.Errorf("capture: unsupported record version %d", rec.V)
+		}
+		if rec.Kind != "snapshot" && rec.Kind != "event" {
+			return fmt.Errorf("capture: unknown record kind %q", rec.Kind)
+		}
+		src := rec.SourceID()
+		if src < r.fromEventID {
+			continue
+		}
+		r.items = append(r.items, ReplayItem{
+			Kind:     rec.Kind,
+			EventID:  src,
+			WallTime: rec.WallTime,
+			Snapshot: rec.Snapshot,
+			Event:    rec.Event,
+		})
+	}
+	r.idx = 0
+	r.haveLast = false
+	return nil
+}
+
+func (r *Replay) Close() error { return nil }
+
+func (r *Replay) WriteSetAll(context.Context, protocol.SetAll) (WriteResult, error) {
+	return WriteResult{}, ErrReadOnly
+}
+
+func (r *Replay) GetTemperature(context.Context) (*TempReport, error) {
+	return nil, ErrReadOnly
+}
+
+func (r *Replay) GetMotorStatus(context.Context) (*MotorReport, error) {
+	return nil, ErrReadOnly
+}
+
+func (r *Replay) RequestStep() {
+	select {
+	case r.stepCh <- struct{}{}:
+	default:
+	}
+}
+
+func (r *Replay) Next(ctx context.Context) (ReplayItem, error) {
+	r.mu.Lock()
+	if r.idx >= len(r.items) {
+		r.mu.Unlock()
+		return ReplayItem{}, ErrReplayEOF
+	}
+	item := r.items[r.idx]
+	last := r.lastWall
+	have := r.haveLast
+	step := r.step
+	speed := r.speed
+	r.mu.Unlock()
+	if !step && have && !item.WallTime.IsZero() && !last.IsZero() && speed < 1000 {
+		dt := item.WallTime.Sub(last)
+		if dt > 0 {
+			wait := time.Duration(float64(dt) / speed)
+			select {
+			case <-ctx.Done():
+				return ReplayItem{}, ctx.Err()
+			case <-time.After(wait):
+			}
+		}
+	}
+	r.mu.Lock()
+	defer r.mu.Unlock()
+	if r.idx >= len(r.items) {
+		return ReplayItem{}, ErrReplayEOF
+	}
+	item = r.items[r.idx]
+	r.idx++
+	if !item.WallTime.IsZero() {
+		r.lastWall = item.WallTime
+		r.haveLast = true
+	}
+	return item, nil
+}
+
+func CaptureFile(dir string) string { return filepath.Join(dir, "records.jsonl") }

+ 34 - 0
internal/backend/replay_fuzz_test.go

@@ -0,0 +1,34 @@
+package backend_test
+
+import (
+	"context"
+	"os"
+	"path/filepath"
+	"testing"
+
+	"hth/internal/backend"
+	"hth/internal/capture"
+)
+
+func FuzzReplayOpen(f *testing.F) {
+	f.Add([]byte(`{"v":1,"kind":"manifest"}`), []byte("{\"v\":1,\"kind\":\"event\"}\n"))
+	f.Add([]byte(`{}`), []byte("{"))
+	f.Add([]byte(`{"v":1,"kind":"manifest","status":"COMPLETE"}`), []byte(""))
+	f.Fuzz(func(t *testing.T, man, recs []byte) {
+		if len(man) > 1<<20 || len(recs) > 1<<20 {
+			t.Skip()
+		}
+		dir := t.TempDir()
+		if err := os.WriteFile(filepath.Join(dir, "manifest.json"), man, 0o644); err != nil {
+			t.Fatal(err)
+		}
+		if err := os.WriteFile(capture.RecordsPath(dir), recs, 0o644); err != nil {
+			t.Fatal(err)
+		}
+		r := backend.NewReplay(dir, 1, true, 0)
+		_ = r.Open(context.Background())
+		_, _ = r.Next(context.Background())
+		r.RequestStep()
+		_ = r.Close()
+	})
+}

+ 145 - 0
internal/backend/replay_strict_test.go

@@ -0,0 +1,145 @@
+package backend_test
+
+import (
+	"context"
+	"errors"
+	"os"
+	"path/filepath"
+	"testing"
+	"time"
+
+	"google.golang.org/protobuf/types/known/timestamppb"
+	"hth/internal/backend"
+	"hth/internal/capture"
+	hthv1 "hth/internal/gen/hth/api/v1"
+)
+
+func writeCapture(t *testing.T, dir string, recs []capture.Record, capHash string) {
+	t.Helper()
+	f, err := os.Create(capture.RecordsPath(dir))
+	if err != nil {
+		t.Fatal(err)
+	}
+	for _, rec := range recs {
+		if err := capture.AppendRecord(f, rec); err != nil {
+			t.Fatal(err)
+		}
+	}
+	f.Close()
+	man := capture.Manifest{
+		APIVersion: "hth.api.v1", DeviceID: "d0", Status: capture.StatusComplete,
+		ProfileHash: "profile-test", CapabilityHash: capHash,
+	}
+	if err := capture.Seal(dir, man); err != nil {
+		t.Fatal(err)
+	}
+}
+
+func TestReplayEmptyCaptureRejected(t *testing.T) {
+	dir := t.TempDir()
+	if err := os.WriteFile(capture.RecordsPath(dir), []byte(""), 0o644); err != nil {
+		t.Fatal(err)
+	}
+	_ = capture.WriteManifest(dir, capture.Manifest{
+		APIVersion: "hth.api.v1", Status: capture.StatusComplete,
+		ProfileHash: "p", CapabilityHash: "c", RecordCount: 0, RecordsSHA256: "x",
+	})
+	r := backend.NewReplay(dir, 1, true, 0)
+	if err := r.Open(context.Background()); err == nil {
+		t.Fatal("empty records must fail")
+	}
+}
+
+func TestReplayCapabilityMismatch(t *testing.T) {
+	dir := t.TempDir()
+	s := &hthv1.Snapshot{DeviceId: "d0", EventId: 1, WallTime: timestamppb.New(time.Unix(1, 0))}
+	rec, _ := capture.SnapshotRecord(s)
+	writeCapture(t, dir, []capture.Record{rec}, "cap-a")
+	r := backend.NewReplay(dir, 1, true, 0)
+	r.SetContract("hth.api.v1", "cap-b")
+	if err := r.Open(context.Background()); err == nil {
+		t.Fatal("cap mismatch must fail")
+	}
+}
+
+func TestReplayContextCancelDoesNotAdvance(t *testing.T) {
+	dir := t.TempDir()
+	s1 := &hthv1.Snapshot{DeviceId: "d0", EventId: 1, WallTime: timestamppb.New(time.Unix(1, 0))}
+	s2 := &hthv1.Snapshot{DeviceId: "d0", EventId: 2, WallTime: timestamppb.New(time.Unix(1, 0).Add(80 * time.Millisecond))}
+	r1, _ := capture.SnapshotRecord(s1)
+	r2, _ := capture.SnapshotRecord(s2)
+	writeCapture(t, dir, []capture.Record{r1, r2}, "cap-test")
+	rp := backend.NewReplay(dir, 1, false, 0)
+	if err := rp.Open(context.Background()); err != nil {
+		t.Fatal(err)
+	}
+	item, err := rp.Next(context.Background())
+	if err != nil || item.EventID != 1 {
+		t.Fatalf("first %v %v", item.EventID, err)
+	}
+	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
+	defer cancel()
+	_, err = rp.Next(ctx)
+	if !errors.Is(err, context.DeadlineExceeded) && !errors.Is(err, context.Canceled) {
+		t.Fatalf("want cancel during wait, got %v", err)
+	}
+	item, err = rp.Next(context.Background())
+	if err != nil {
+		t.Fatal(err)
+	}
+	if item.EventID != 2 {
+		t.Fatalf("cancel must not skip record, got %d", item.EventID)
+	}
+}
+
+func TestReplayEOF(t *testing.T) {
+	dir := t.TempDir()
+	s := &hthv1.Snapshot{DeviceId: "d0", EventId: 9, WallTime: timestamppb.New(time.Unix(1, 0))}
+	rec, _ := capture.SnapshotRecord(s)
+	writeCapture(t, dir, []capture.Record{rec}, "cap-test")
+	rp := backend.NewReplay(dir, 1000, true, 0)
+	if err := rp.Open(context.Background()); err != nil {
+		t.Fatal(err)
+	}
+	if _, err := rp.Next(context.Background()); err != nil {
+		t.Fatal(err)
+	}
+	_, err := rp.Next(context.Background())
+	if !errors.Is(err, backend.ErrReplayEOF) {
+		t.Fatalf("EOF: %v", err)
+	}
+}
+
+func TestReplayTruncatedRejected(t *testing.T) {
+	dir := t.TempDir()
+	p := capture.RecordsPath(dir)
+	if err := os.WriteFile(p, []byte("{\"v\":1,\"kind\":\"event\"}"), 0o644); err != nil {
+		t.Fatal(err)
+	}
+	_ = capture.WriteManifest(dir, capture.Manifest{
+		APIVersion: "hth.api.v1", Status: capture.StatusComplete,
+		ProfileHash: "p", CapabilityHash: "c", RecordCount: 1, RecordsSHA256: "x",
+	})
+	r := backend.NewReplay(dir, 1, true, 0)
+	if err := r.Open(context.Background()); err == nil {
+		t.Fatal("truncated jsonl must fail")
+	}
+}
+
+func TestReplayLargeFileLimit(t *testing.T) {
+	dir := t.TempDir()
+	p := capture.RecordsPath(dir)
+	// Stat size check uses MaxRecordsBytes; write a small file and monkey via Open path
+	if err := os.WriteFile(p, []byte("{}\n"), 0o644); err != nil {
+		t.Fatal(err)
+	}
+	_ = capture.WriteManifest(dir, capture.Manifest{
+		APIVersion: "hth.api.v1", Status: capture.StatusComplete,
+		ProfileHash: "p", CapabilityHash: "c", RecordCount: 1, RecordsSHA256: "x",
+	})
+	r := backend.NewReplay(dir, 1, true, 0)
+	if err := r.Open(context.Background()); err == nil {
+		t.Fatal("bad record/hash must fail")
+	}
+	_ = filepath.Separator
+}

+ 56 - 0
internal/backend/serial_close_linux_test.go

@@ -0,0 +1,56 @@
+//go:build linux
+
+package backend_test
+
+import (
+	"context"
+	"testing"
+	"time"
+
+	"hth/internal/serialtransport"
+)
+
+func TestCloseUnblocksIgnoredContextReadWithoutTxnLock(t *testing.T) {
+	serialtransport.SetTestIgnoreContext(true)
+	t.Cleanup(func() { serialtransport.SetTestIgnoreContext(false) })
+	s, _ := openSerialPair(t)
+	// Short deadline must not unblock this Read; only closing the FD does.
+	ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
+	defer cancel()
+	done := make(chan error, 1)
+	go func() {
+		_, err := s.GetTemperature(ctx)
+		done <- err
+	}()
+	time.Sleep(300 * time.Millisecond)
+	select {
+	case err := <-done:
+		t.Fatalf("Read returned on context deadline without Close: %v", err)
+	default:
+	}
+	start := time.Now()
+	if err := s.Close(); err != nil {
+		t.Fatal(err)
+	}
+	if time.Since(start) > 300*time.Millisecond {
+		t.Fatalf("Close waited for the transaction mutex: %s", time.Since(start))
+	}
+	select {
+	case err := <-done:
+		if err == nil {
+			t.Fatal("hung GET must fail after Close")
+		}
+	case <-time.After(2 * time.Second):
+		t.Fatal("Read did not unblock after Close")
+	}
+}
+
+func TestDoubleCloseIsSafe(t *testing.T) {
+	s, _ := openSerialPair(t)
+	if err := s.Close(); err != nil {
+		t.Fatal(err)
+	}
+	if err := s.Close(); err != nil {
+		t.Fatal(err)
+	}
+}

+ 208 - 0
internal/backend/serial_get_linux_test.go

@@ -0,0 +1,208 @@
+//go:build linux
+
+package backend_test
+
+import (
+	"context"
+	"errors"
+	"testing"
+	"time"
+
+	"golang.org/x/sys/unix"
+	"hth/internal/backend"
+	"hth/internal/devsim"
+	"hth/internal/protocol"
+	"hth/internal/serialtransport"
+)
+
+func TestClassifyWriteOutcomes(t *testing.T) {
+	cases := []struct {
+		n, want int
+		err     error
+		out     backend.WriteOutcome
+	}{
+		{0, 6, context.Canceled, backend.WriteNotStarted},
+		{1, 6, serialtransport.ErrShortWrite, backend.WritePartiallyWritten},
+		{6, 6, errors.New("injected"), backend.WriteFullyWrittenWithError},
+		{6, 6, nil, backend.WriteFullyWritten},
+		{0, 6, serialtransport.ErrDisconnected, backend.WriteDisconnected},
+	}
+	for _, tc := range cases {
+		// exercise via a tiny helper in this package by opening a PTY is overkill;
+		// WriteNeedsReconnect covers reconnect policy.
+		wr := backend.WriteResult{Outcome: tc.out, N: tc.n}
+		need := backend.WriteNeedsReconnect(wr, tc.err)
+		if tc.out == backend.WriteFullyWritten && tc.err == nil && need {
+			t.Fatalf("%v should not reconnect", tc.out)
+		}
+		if tc.out == backend.WritePartiallyWritten && !need {
+			t.Fatalf("%v must reconnect", tc.out)
+		}
+		if tc.out == backend.WriteFullyWrittenWithError && !need {
+			t.Fatalf("%v must reconnect", tc.out)
+		}
+	}
+}
+
+func openSerialPair(t *testing.T) (*backend.Serial, *unixMaster) {
+	t.Helper()
+	serialtransport.SetTestWriteCap(0)
+	serialtransport.SetTestForceWriteError(false)
+	t.Cleanup(func() {
+		serialtransport.SetTestWriteCap(0)
+		serialtransport.SetTestForceWriteError(false)
+		serialtransport.SetTestIgnoreContext(false)
+	})
+	m, hold, name, err := serialtransport.OpenPTY()
+	if err != nil {
+		t.Fatal(err)
+	}
+	t.Cleanup(func() { m.Close(); unix.Close(hold) })
+	s := backend.NewSerial(name, 20*time.Millisecond, time.Second)
+	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+	t.Cleanup(cancel)
+	if err := s.Open(ctx); err != nil {
+		t.Fatal(err)
+	}
+	t.Cleanup(func() { _ = s.Close() })
+	return s, &unixMaster{f: m}
+}
+
+type unixMaster struct {
+	f interface {
+		Read([]byte) (int, error)
+		Write([]byte) (int, error)
+		SetReadDeadline(time.Time) error
+		SetWriteDeadline(time.Time) error
+		Close() error
+	}
+}
+
+func replyTemp(t *testing.T, m *unixMaster) {
+	t.Helper()
+	raw := make([]byte, protocol.TemperaturePayloadLen)
+	frame, err := protocol.EncodeTemperature(raw)
+	if err != nil {
+		t.Fatal(err)
+	}
+	if _, err := m.f.Write(frame); err != nil {
+		t.Fatal(err)
+	}
+}
+
+func TestGETShortWriteUntrusted(t *testing.T) {
+	s, m := openSerialPair(t)
+	go drain(m)
+	serialtransport.SetTestWriteCap(1)
+	t.Cleanup(func() { serialtransport.SetTestWriteCap(0) })
+	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+	defer cancel()
+	_, err := s.GetTemperature(ctx)
+	if !errors.Is(err, backend.ErrStreamUntrusted) {
+		t.Fatalf("short GET write: %v", err)
+	}
+}
+
+func TestGETHalfFrameWriteUntrusted(t *testing.T) {
+	s, m := openSerialPair(t)
+	go drain(m)
+	req := protocol.GetTemperatureRequest()
+	serialtransport.SetTestWriteCap(len(req) / 2)
+	t.Cleanup(func() { serialtransport.SetTestWriteCap(0) })
+	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+	defer cancel()
+	_, err := s.GetTemperature(ctx)
+	if !errors.Is(err, backend.ErrStreamUntrusted) {
+		t.Fatalf("half GET write: %v", err)
+	}
+}
+
+func TestGETFullWriteErrorUntrusted(t *testing.T) {
+	s, m := openSerialPair(t)
+	go drain(m)
+	serialtransport.SetTestForceWriteError(true)
+	t.Cleanup(func() { serialtransport.SetTestForceWriteError(false) })
+	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+	defer cancel()
+	_, err := s.GetTemperature(ctx)
+	if !errors.Is(err, backend.ErrStreamUntrusted) {
+		t.Fatalf("full write+err: %v", err)
+	}
+}
+
+func TestGETUnexpectedTypeUntrusted(t *testing.T) {
+	s, m := openSerialPair(t)
+	go func() {
+		buf := make([]byte, 64)
+		_ = m.f.SetReadDeadline(time.Now().Add(2 * time.Second))
+		_, _ = m.f.Read(buf)
+		ms := protocol.MotorStatus{StartupComplete: true}
+		frame, _ := protocol.EncodeMotorStatus(ms)
+		_, _ = m.f.Write(frame)
+	}()
+	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+	defer cancel()
+	_, err := s.GetTemperature(ctx)
+	if !errors.Is(err, backend.ErrStreamUntrusted) {
+		t.Fatalf("wrong type: %v", err)
+	}
+}
+
+func TestDevsimCRCErrorUntrusted(t *testing.T) {
+	sim, err := devsim.Start(devsim.Options{StartupDone: true, CRCError: true})
+	if err != nil {
+		t.Fatal(err)
+	}
+	t.Cleanup(sim.Close)
+	s := backend.NewSerial(sim.Name, 10*time.Millisecond, time.Second)
+	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+	defer cancel()
+	if err := s.Open(ctx); err != nil {
+		t.Fatal(err)
+	}
+	t.Cleanup(func() { _ = s.Close() })
+	_, err = s.GetTemperature(ctx)
+	if !errors.Is(err, backend.ErrStreamUntrusted) {
+		t.Fatalf("devsim CRCError GET: %v", err)
+	}
+}
+
+func TestGETCRCErrorUntrusted(t *testing.T) {
+	s, m := openSerialPair(t)
+	go func() {
+		buf := make([]byte, 64)
+		_ = m.f.SetReadDeadline(time.Now().Add(2 * time.Second))
+		_, _ = m.f.Read(buf)
+		raw := make([]byte, protocol.TemperaturePayloadLen)
+		frame, err := protocol.EncodeTemperature(raw)
+		if err != nil {
+			return
+		}
+		frame[len(frame)-1] ^= 0xFF
+		_, _ = m.f.Write(frame)
+	}()
+	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+	defer cancel()
+	_, err := s.GetTemperature(ctx)
+	if !errors.Is(err, backend.ErrStreamUntrusted) {
+		t.Fatalf("CRC GET: %v", err)
+	}
+}
+
+func TestGETLeftoverBeforeWriteUntrusted(t *testing.T) {
+	s, m := openSerialPair(t)
+	replyTemp(t, m)
+	time.Sleep(20 * time.Millisecond)
+	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+	defer cancel()
+	_, err := s.GetTemperature(ctx)
+	if !errors.Is(err, backend.ErrStreamUntrusted) {
+		t.Fatalf("leftover late response must untrust: %v", err)
+	}
+}
+
+func drain(m *unixMaster) {
+	buf := make([]byte, 256)
+	_ = m.f.SetReadDeadline(time.Now().Add(2 * time.Second))
+	_, _ = m.f.Read(buf)
+}

+ 227 - 0
internal/backend/serial_linux.go

@@ -0,0 +1,227 @@
+//go:build linux
+
+package backend
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"os"
+	"sync"
+	"sync/atomic"
+	"time"
+
+	"hth/internal/protocol"
+	"hth/internal/serialtransport"
+)
+
+var ErrGenerationChanged = errors.New("serial port generation changed")
+
+type Serial struct {
+	txnMu     sync.Mutex
+	portMu    sync.Mutex
+	gen       atomic.Uint64
+	path      string
+	interByte time.Duration
+	respTO    time.Duration
+	port      *serialtransport.Port
+}
+
+func NewSerial(path string, interByte, respTimeout time.Duration) *Serial {
+	return &Serial{path: path, interByte: interByte, respTO: respTimeout}
+}
+
+func (s *Serial) Kind() string       { return "serial" }
+func (s *Serial) PollMode() PollMode { return PollUART }
+
+func (s *Serial) snapshot() (uint64, *serialtransport.Port) {
+	s.portMu.Lock()
+	defer s.portMu.Unlock()
+	return s.gen.Load(), s.port
+}
+
+func (s *Serial) Open(ctx context.Context) error {
+	if err := ctx.Err(); err != nil {
+		return err
+	}
+	p, err := serialtransport.Open(s.path, s.interByte)
+	if err != nil {
+		return err
+	}
+	if err := ctx.Err(); err != nil {
+		_ = p.Close()
+		return err
+	}
+	s.portMu.Lock()
+	old := s.port
+	s.port = p
+	token := s.gen.Add(1)
+	s.portMu.Unlock()
+	if old != nil {
+		_ = old.Close()
+	}
+	s.portMu.Lock()
+	if s.gen.Load() != token || s.port != p {
+		s.portMu.Unlock()
+		_ = p.Close()
+		return ErrGenerationChanged
+	}
+	s.portMu.Unlock()
+	return nil
+}
+
+func (s *Serial) Interrupt() {
+	_, port := s.snapshot()
+	if port != nil {
+		port.Interrupt()
+	}
+}
+
+func (s *Serial) Close() error {
+	s.portMu.Lock()
+	p := s.port
+	s.port = nil
+	s.gen.Add(1)
+	s.portMu.Unlock()
+	if p == nil {
+		return nil
+	}
+	return p.Close()
+}
+
+func (s *Serial) live(gen uint64, port *serialtransport.Port) bool {
+	return port != nil && s.gen.Load() == gen
+}
+
+func classifyWrite(n, want int, err error) WriteResult {
+	if n == 0 && err != nil && !errors.Is(err, serialtransport.ErrShortWrite) {
+		if errors.Is(err, serialtransport.ErrDisconnected) {
+			return WriteResult{Outcome: WriteDisconnected, N: n}
+		}
+		if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
+			return WriteResult{Outcome: WriteNotStarted, N: 0}
+		}
+		return WriteResult{Outcome: WriteOutcomeUnknown, N: n}
+	}
+	if errors.Is(err, serialtransport.ErrDisconnected) {
+		return WriteResult{Outcome: WriteDisconnected, N: n}
+	}
+	if n < want {
+		return WriteResult{Outcome: WritePartiallyWritten, N: n}
+	}
+	if err != nil {
+		return WriteResult{Outcome: WriteFullyWrittenWithError, N: n}
+	}
+	return WriteResult{Outcome: WriteFullyWritten, N: n}
+}
+
+func (s *Serial) WriteSetAll(ctx context.Context, st protocol.SetAll) (WriteResult, error) {
+	s.txnMu.Lock()
+	defer s.txnMu.Unlock()
+	gen, port := s.snapshot()
+	if port == nil {
+		return WriteResult{Outcome: WriteDisconnected}, ErrNotConnected
+	}
+	raw, err := st.Encode()
+	if err != nil {
+		return WriteResult{Outcome: WriteNotStarted}, err
+	}
+	n, err := port.Write(ctx, raw)
+	if !s.live(gen, port) {
+		return WriteResult{Outcome: WriteOutcomeUnknown, N: n}, ErrGenerationChanged
+	}
+	wr := classifyWrite(n, len(raw), err)
+	if wr.Outcome == WriteFullyWritten {
+		return wr, nil
+	}
+	if wr.Outcome == WriteNotStarted {
+		return wr, err
+	}
+	if err == nil {
+		err = serialtransport.ErrShortWrite
+	}
+	return wr, err
+}
+
+func (s *Serial) transact(ctx context.Context, req []byte, want byte) (protocol.Frame, []byte, TimeWindow, error) {
+	s.txnMu.Lock()
+	defer s.txnMu.Unlock()
+	win := TimeWindow{}
+	gen, port := s.snapshot()
+	if port == nil {
+		return protocol.Frame{}, nil, win, ErrNotConnected
+	}
+	if err := port.RejectUnexpected(); err != nil {
+		return protocol.Frame{}, nil, win, fmt.Errorf("%w: %v", ErrStreamUntrusted, err)
+	}
+	win.RequestSent = time.Now()
+	n, err := port.Write(ctx, req)
+	if !s.live(gen, port) {
+		return protocol.Frame{}, nil, win, fmt.Errorf("%w: %v", ErrStreamUntrusted, ErrGenerationChanged)
+	}
+	wr := classifyWrite(n, len(req), err)
+	if wr.Outcome == WriteFullyWritten {
+		win.RequestComplete = time.Now()
+	}
+	if WriteNeedsReconnect(wr, err) || wr.Outcome != WriteFullyWritten {
+		return protocol.Frame{}, nil, win, fmt.Errorf("%w: GET write %s n=%d: %v", ErrStreamUntrusted, wr.Outcome, wr.N, err)
+	}
+	frame, raw, first, last, err := port.ReadFrameTimed(ctx)
+	if !s.live(gen, port) {
+		return protocol.Frame{}, raw, win, fmt.Errorf("%w: %v", ErrStreamUntrusted, ErrGenerationChanged)
+	}
+	if !first.IsZero() {
+		win.ResponseStart = first
+	}
+	if !last.IsZero() {
+		win.ResponseComplete = last
+	}
+	win.HostReceive = time.Now()
+	if err != nil {
+		return protocol.Frame{}, raw, win, fmt.Errorf("%w: %v", ErrStreamUntrusted, err)
+	}
+	if frame.Type != want {
+		return frame, raw, win, fmt.Errorf("%w: unexpected frame type 0x%02x want 0x%02x", ErrStreamUntrusted, frame.Type, want)
+	}
+	return frame, raw, win, nil
+}
+
+func (s *Serial) GetTemperature(ctx context.Context) (*TempReport, error) {
+	frame, raw, win, err := s.transact(ctx, protocol.GetTemperatureRequest(), protocol.TypeTemperatureData)
+	if err != nil {
+		return nil, err
+	}
+	samples, err := protocol.DecodeTemperature(frame)
+	if err != nil {
+		return nil, err
+	}
+	return &TempReport{Samples: samples, Window: win, Raw: raw}, nil
+}
+
+func (s *Serial) GetMotorStatus(ctx context.Context) (*MotorReport, error) {
+	frame, raw, win, err := s.transact(ctx, protocol.GetMotorStatusRequest(), protocol.TypeMotorStatusData)
+	if err != nil {
+		return nil, err
+	}
+	ms, err := protocol.DecodeMotorStatus(frame)
+	if err != nil {
+		return nil, err
+	}
+	return &MotorReport{Status: ms, Window: win, Raw: raw}, nil
+}
+
+func ClassifySerialOpen(err error) string {
+	if err == nil {
+		return ""
+	}
+	if errors.Is(err, serialtransport.ErrAlreadyLocked) {
+		return "permission"
+	}
+	if os.IsNotExist(err) {
+		return "not_found"
+	}
+	if os.IsPermission(err) {
+		return "permission"
+	}
+	return serialtransport.ClassifyOpenError(err)
+}

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/0255ca613fd7c6a1

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("{\"\"0")
+[]byte("")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/0938b7fa705ec552

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("\a")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/0cbd8c395f234c73

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("{\"\":1A")
+[]byte("")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/0ce8924336b00a4a

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("A")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/10668f0c64d180ee

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("{}{}")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/1e4976294bffeaa6

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("10000000")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/247c677b3d2ee7d7

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("{\"\xd9\xc8\xc8\xc8\":\"\"}")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/2940cad0e1b165c5

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("{\"\"")
+[]byte("")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/2eafed28f42a799b

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("\t\t0")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/2fa28f4c3423d42d

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("{\"\xf8\xf8\xf8\xf8\xf8\xff\xff\xff\xf8\xf8\xf8\":\"\"}")
+[]byte("")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/406a65375d9339a3

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("{\x7f")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/446e2c92d43d091a

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("    0")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/4a20de1c3de0db84

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("\"\xeb\xb80\xf2\xb4\xf1\xaf00\"")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/4ca045b77ed1c5e0

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("-1")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/4d8dad06d4f7a904

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("\t0")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/577e3b8b16e7366a

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("    ")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/598eaef9b893cb72

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("{\"ѲȲ\xc8\":\"\"}")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/6bb50660bc5d12ab

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("        ")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/70a32a8bd28f5c4e

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("")
+[]byte("")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/72306381974229ff

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("10")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/7537b76aadc6bd46

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("{}A")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/7d4070133ca6e65e

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("\"\x91\xd90\"")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/8341f2427830db12

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("{ ")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/88fec89d12adc077

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("\t\t\t\t\t\t\t\t00000000")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/94b3d7c043393667

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("10000000000000000")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/a0bf1046919c14c8

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("6")
+[]byte("X")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/a2433a0d4562ac7a

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("\n\n")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/a87b74a6e18e12db

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("\"\\")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/b34c6fd7ba700fac

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("{\"\xff\xff\xff\xff\":\"\"}")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/b54de5a6d7420d30

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("{\"\x93\":0,\"0\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf8\xf800\":\"00000000\",\"000000\":\"00000000\"}")
+[]byte("")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/b9cde15548b004f6

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("[[0")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/bb625e6c5fa614a3

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("{\"aaaaaaaa\":\"\"}")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/bc5279be026b445b

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("nu")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/c359a835dadd58b1

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("{\"ζ\":\"\"}")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/c6c45768ecf32742

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("{\"\xd900\":0,\"kind\":\"\xff\xff\xff\xff000\"}")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/c9c99350dd9b9413

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("\"\xd0\xe8\x850\"")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/d2795509f824b36c

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("0.")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/dbd5d95c0469560d

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("-0")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/e2eece8a41c4840c

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("\r0")
+[]byte("0")

+ 3 - 0
internal/backend/testdata/fuzz/FuzzReplayOpen/f50212ecab9304df

@@ -0,0 +1,3 @@
+go test fuzz v1
+[]byte("\n")
+[]byte("0")

+ 26 - 0
internal/caphash/caphash.go

@@ -0,0 +1,26 @@
+package caphash
+
+import (
+	"crypto/sha256"
+	"encoding/hex"
+
+	"google.golang.org/protobuf/proto"
+	hthv1 "hth/internal/gen/hth/api/v1"
+)
+
+// HashCanonicalCapabilities is the unique Capability Hash algorithm.
+// Callers: GetCapabilities, hthctl doctor, hth-capture, Replay, acceptance, manifests.
+// It is NOT profile.ProfileIdentityDigest (a profile-file digest).
+func HashCanonicalCapabilities(c *hthv1.Capabilities) string {
+	if c == nil {
+		return ""
+	}
+	cp := proto.Clone(c).(*hthv1.Capabilities)
+	cp.CapabilityHash = ""
+	b, err := proto.MarshalOptions{Deterministic: true}.Marshal(cp)
+	if err != nil {
+		return ""
+	}
+	sum := sha256.Sum256(b)
+	return hex.EncodeToString(sum[:])
+}

+ 22 - 0
internal/caphash/caphash_test.go

@@ -0,0 +1,22 @@
+package caphash_test
+
+import (
+	"testing"
+
+	"hth/internal/caphash"
+	hthv1 "hth/internal/gen/hth/api/v1"
+)
+
+func TestHashIgnoresCapabilityHashFieldAndIsDeterministic(t *testing.T) {
+	a := &hthv1.Capabilities{ProfileId: "p", ProfileRevision: "1", ApiVersion: "hth.api.v1", CapabilityHash: "aaa"}
+	b := &hthv1.Capabilities{ProfileId: "p", ProfileRevision: "1", ApiVersion: "hth.api.v1", CapabilityHash: "bbb"}
+	ha := caphash.HashCanonicalCapabilities(a)
+	hb := caphash.HashCanonicalCapabilities(b)
+	if ha == "" || ha != hb {
+		t.Fatalf("hash %q vs %q", ha, hb)
+	}
+	a.AckSupported = true
+	if caphash.HashCanonicalCapabilities(a) == ha {
+		t.Fatal("capability change must change hash")
+	}
+}

+ 438 - 0
internal/capture/capture.go

@@ -0,0 +1,438 @@
+package capture
+
+import (
+	"bufio"
+	"crypto/sha256"
+	"encoding/hex"
+	"encoding/json"
+	"fmt"
+	"io"
+	"os"
+	"path/filepath"
+	"time"
+
+	"google.golang.org/protobuf/encoding/protojson"
+	hthv1 "hth/internal/gen/hth/api/v1"
+)
+
+const Version = 1
+
+const (
+	StatusIncomplete = "incomplete"
+	StatusComplete   = "complete"
+)
+
+const (
+	MaxRecordsBytes = 64 << 20
+	MaxRecordLine   = 4 << 20
+	MaxRecordCount  = 1_000_000
+)
+
+type Manifest struct {
+	V                   int       `json:"v"`
+	Kind                string    `json:"kind"`
+	APIVersion          string    `json:"api_version"`
+	APISchemaVersion    string    `json:"api_schema_version"`
+	ProfileHash         string    `json:"profile_hash"`
+	ProfileID           string    `json:"profile_id,omitempty"`
+	ProfileRevision     string    `json:"profile_revision,omitempty"`
+	ProfileContractHash string    `json:"profile_contract_hash"`
+	CapabilityHash      string    `json:"capability_hash"`
+	DeviceID            string    `json:"device_id"`
+	StartedAt           time.Time `json:"started_at"`
+	StartTime           time.Time `json:"start_time"`
+	EndedAt             time.Time `json:"ended_at,omitempty"`
+	EndTime             time.Time `json:"end_time,omitempty"`
+	RecordCount         int       `json:"record_count"`
+	RecordsSHA256       string    `json:"records_sha256"`
+	FirstSourceEventID  uint64    `json:"first_source_event_id"`
+	LastSourceEventID   uint64    `json:"last_source_event_id"`
+	Status              string    `json:"status"`
+	CompletionStatus    string    `json:"completion_status"`
+	IncompleteReason    string    `json:"incomplete_reason,omitempty"`
+	CompletionReason    string    `json:"completion_reason,omitempty"`
+}
+
+type Record struct {
+	V             int             `json:"v"`
+	Kind          string          `json:"kind"`
+	EventID       uint64          `json:"event_id,omitempty"`
+	SourceEventID uint64          `json:"source_event_id,omitempty"`
+	WallTime      time.Time       `json:"wall_time,omitempty"`
+	Snapshot      json.RawMessage `json:"snapshot,omitempty"`
+	Event         json.RawMessage `json:"event,omitempty"`
+}
+
+var marshal = protojson.MarshalOptions{UseProtoNames: true, EmitUnpopulated: false}
+
+func (m *Manifest) Normalize() {
+	if m == nil {
+		return
+	}
+	if m.APISchemaVersion == "" {
+		m.APISchemaVersion = m.APIVersion
+	}
+	if m.APIVersion == "" {
+		m.APIVersion = m.APISchemaVersion
+	}
+	if m.ProfileContractHash == "" {
+		m.ProfileContractHash = m.ProfileHash
+	}
+	if m.ProfileHash == "" {
+		m.ProfileHash = m.ProfileContractHash
+	}
+	if m.StartTime.IsZero() {
+		m.StartTime = m.StartedAt
+	}
+	if m.StartedAt.IsZero() {
+		m.StartedAt = m.StartTime
+	}
+	if m.EndTime.IsZero() {
+		m.EndTime = m.EndedAt
+	}
+	if m.EndedAt.IsZero() {
+		m.EndedAt = m.EndTime
+	}
+	if m.CompletionStatus == "" {
+		m.CompletionStatus = m.Status
+	}
+	if m.Status == "" {
+		m.Status = m.CompletionStatus
+	}
+	if m.CompletionReason == "" {
+		m.CompletionReason = m.IncompleteReason
+	}
+	if m.IncompleteReason == "" {
+		m.IncompleteReason = m.CompletionReason
+	}
+	if m.Kind == "" {
+		m.Kind = "manifest"
+	}
+	if m.V == 0 {
+		m.V = Version
+	}
+}
+
+func WriteManifest(dir string, m Manifest) error {
+	return writeManifestAtomic(dir, m)
+}
+
+func writeManifestAtomic(dir string, m Manifest) error {
+	m.Normalize()
+	m.V = Version
+	m.Kind = "manifest"
+	if m.Status == "" {
+		m.Status = StatusIncomplete
+		m.CompletionStatus = StatusIncomplete
+	}
+	b, err := json.MarshalIndent(m, "", "  ")
+	if err != nil {
+		return err
+	}
+	b = append(b, '\n')
+	final := filepath.Join(dir, "manifest.json")
+	tmp := final + ".tmp"
+	f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)
+	if err != nil {
+		return err
+	}
+	if _, err := f.Write(b); err != nil {
+		f.Close()
+		_ = os.Remove(tmp)
+		return err
+	}
+	if err := f.Sync(); err != nil {
+		f.Close()
+		_ = os.Remove(tmp)
+		return fmt.Errorf("capture: manifest fsync: %w", err)
+	}
+	if err := f.Close(); err != nil {
+		_ = os.Remove(tmp)
+		return err
+	}
+	if err := os.Rename(tmp, final); err != nil {
+		_ = os.Remove(tmp)
+		return err
+	}
+	return syncDir(dir)
+}
+
+func syncDir(dir string) error {
+	d, err := os.Open(dir)
+	if err != nil {
+		return fmt.Errorf("capture: dir fsync open: %w", err)
+	}
+	defer d.Close()
+	if err := d.Sync(); err != nil {
+		return fmt.Errorf("capture: dir fsync: %w", err)
+	}
+	return nil
+}
+
+func AppendRecord(f *os.File, rec Record) error {
+	rec.V = Version
+	if rec.SourceEventID == 0 {
+		rec.SourceEventID = rec.EventID
+	}
+	b, err := json.Marshal(rec)
+	if err != nil {
+		return err
+	}
+	n, err := f.Write(append(b, '\n'))
+	if err != nil {
+		return err
+	}
+	if n < len(b)+1 {
+		return fmt.Errorf("capture: short write %d/%d", n, len(b)+1)
+	}
+	return nil
+}
+
+func SyncFile(f *os.File) error {
+	if f == nil {
+		return fmt.Errorf("capture: nil file")
+	}
+	if err := f.Sync(); err != nil {
+		return fmt.Errorf("capture: fsync: %w", err)
+	}
+	return nil
+}
+
+func HashFile(path string) (string, error) {
+	f, err := os.Open(path)
+	if err != nil {
+		return "", err
+	}
+	defer f.Close()
+	h := sha256.New()
+	if _, err := io.Copy(h, f); err != nil {
+		return "", err
+	}
+	return hex.EncodeToString(h.Sum(nil)), nil
+}
+
+func Seal(dir string, m Manifest) error {
+	recPath := RecordsPath(dir)
+	fi, err := os.Stat(recPath)
+	if err != nil {
+		return err
+	}
+	if fi.Size() > MaxRecordsBytes {
+		return fmt.Errorf("capture: records size %d exceeds %d", fi.Size(), MaxRecordsBytes)
+	}
+	recs, err := ReadRecords(recPath)
+	if err != nil {
+		return err
+	}
+	sum, err := HashFile(recPath)
+	if err != nil {
+		return err
+	}
+	m.RecordCount = len(recs)
+	m.RecordsSHA256 = sum
+	if len(recs) > 0 {
+		m.FirstSourceEventID = recs[0].SourceID()
+		m.LastSourceEventID = recs[len(recs)-1].SourceID()
+	} else if m.Status == StatusComplete || m.CompletionStatus == StatusComplete {
+		return fmt.Errorf("capture: refusing to seal complete capture with zero records")
+	}
+	m.EndedAt = time.Now().UTC()
+	m.EndTime = m.EndedAt
+	return WriteManifest(dir, m)
+}
+
+func (r Record) SourceID() uint64 {
+	if r.SourceEventID != 0 {
+		return r.SourceEventID
+	}
+	return r.EventID
+}
+
+func ValidateManifest(m Manifest, apiVersion, capHash string, requireComplete bool) error {
+	m.Normalize()
+	if m.V != 0 && m.V != Version {
+		return fmt.Errorf("capture: unsupported manifest version %d", m.V)
+	}
+	if m.Kind != "" && m.Kind != "manifest" {
+		return fmt.Errorf("capture: unexpected kind %q", m.Kind)
+	}
+	if requireComplete {
+		if m.Status != StatusComplete {
+			return fmt.Errorf("capture: manifest status %q is not complete", m.Status)
+		}
+		if m.RecordCount == 0 {
+			return fmt.Errorf("capture: complete capture requires at least one record")
+		}
+		if m.CapabilityHash == "" {
+			return fmt.Errorf("capture: empty capability_hash is not valid")
+		}
+		if m.RecordsSHA256 == "" {
+			return fmt.Errorf("capture: empty records_sha256 is not valid")
+		}
+		if m.APIVersion == "" {
+			return fmt.Errorf("capture: api_schema_version required")
+		}
+		if m.ProfileHash == "" {
+			return fmt.Errorf("capture: empty profile_hash is not valid")
+		}
+	}
+	if apiVersion != "" && m.APIVersion != "" && m.APIVersion != apiVersion {
+		return fmt.Errorf("capture: api_version %q != %q", m.APIVersion, apiVersion)
+	}
+	if capHash != "" {
+		if m.CapabilityHash == "" {
+			return fmt.Errorf("capture: empty capability_hash is not valid")
+		}
+		if m.CapabilityHash != capHash {
+			return fmt.Errorf("capture: capability_hash mismatch")
+		}
+	}
+	return nil
+}
+
+func ValidateRecordsAgainstManifest(m Manifest, recs []Record, recSHA string) error {
+	m.Normalize()
+	if m.RecordCount != len(recs) {
+		return fmt.Errorf("capture: record_count %d != %d records", m.RecordCount, len(recs))
+	}
+	if m.RecordsSHA256 != "" && recSHA != "" && m.RecordsSHA256 != recSHA {
+		return fmt.Errorf("capture: records_sha256 mismatch")
+	}
+	if len(recs) == 0 {
+		if m.Status == StatusComplete || m.CompletionStatus == StatusComplete {
+			return fmt.Errorf("capture: complete capture with zero records is not valid")
+		}
+		if m.FirstSourceEventID != 0 || m.LastSourceEventID != 0 {
+			return fmt.Errorf("capture: empty records but event ids set")
+		}
+		return nil
+	}
+	var prev uint64
+	for i, rec := range recs {
+		if rec.V != 0 && rec.V != Version {
+			return fmt.Errorf("capture: record %d unsupported version %d", i, rec.V)
+		}
+		id := rec.SourceID()
+		if i > 0 && id != 0 && prev != 0 && id < prev {
+			return fmt.Errorf("capture: source event id not monotonic at %d: %d < %d", i, id, prev)
+		}
+		if id != 0 {
+			prev = id
+		}
+	}
+	first := recs[0].SourceID()
+	last := recs[len(recs)-1].SourceID()
+	if m.FirstSourceEventID != 0 && m.FirstSourceEventID != first {
+		return fmt.Errorf("capture: first_source_event_id %d != %d", m.FirstSourceEventID, first)
+	}
+	if m.LastSourceEventID != 0 && m.LastSourceEventID != last {
+		return fmt.Errorf("capture: last_source_event_id %d != %d", m.LastSourceEventID, last)
+	}
+	return nil
+}
+
+func SnapshotRecord(s *hthv1.Snapshot) (Record, error) {
+	b, err := marshal.Marshal(s)
+	if err != nil {
+		return Record{}, err
+	}
+	wt := time.Time{}
+	if s.WallTime != nil {
+		wt = s.WallTime.AsTime()
+	}
+	return Record{Kind: "snapshot", EventID: s.EventId, SourceEventID: s.EventId, WallTime: wt, Snapshot: b}, nil
+}
+
+func EventRecord(e *hthv1.Event) (Record, error) {
+	b, err := marshal.Marshal(e)
+	if err != nil {
+		return Record{}, err
+	}
+	wt := time.Time{}
+	if e.WallTime != nil {
+		wt = e.WallTime.AsTime()
+	}
+	return Record{Kind: "event", EventID: e.EventId, SourceEventID: e.EventId, WallTime: wt, Event: b}, nil
+}
+
+func ReadManifest(dir string) (Manifest, error) {
+	var m Manifest
+	f, err := os.Open(filepath.Join(dir, "manifest.json"))
+	if err != nil {
+		return m, err
+	}
+	defer f.Close()
+	dec := json.NewDecoder(f)
+	dec.DisallowUnknownFields()
+	if err := dec.Decode(&m); err != nil {
+		return m, fmt.Errorf("capture: manifest: %w", err)
+	}
+	var extra json.RawMessage
+	if err := dec.Decode(&extra); err != io.EOF {
+		if err == nil {
+			return m, fmt.Errorf("capture: trailing data after manifest")
+		}
+		return m, fmt.Errorf("capture: manifest trailing: %w", err)
+	}
+	m.Normalize()
+	return m, nil
+}
+
+func ReadRecords(path string) ([]Record, error) {
+	fi, err := os.Stat(path)
+	if err != nil {
+		return nil, err
+	}
+	if fi.Size() > MaxRecordsBytes {
+		return nil, fmt.Errorf("capture: records size %d exceeds %d", fi.Size(), MaxRecordsBytes)
+	}
+	f, err := os.Open(path)
+	if err != nil {
+		return nil, err
+	}
+	defer f.Close()
+	var out []Record
+	sc := bufio.NewScanner(f)
+	sc.Buffer(make([]byte, 0, 64*1024), MaxRecordLine)
+	for sc.Scan() {
+		line := sc.Bytes()
+		if len(line) == 0 {
+			continue
+		}
+		var rec Record
+		if err := json.Unmarshal(line, &rec); err != nil {
+			return nil, fmt.Errorf("capture: bad record: %w", err)
+		}
+		if rec.Kind != "snapshot" && rec.Kind != "event" {
+			return nil, fmt.Errorf("capture: unknown record kind %q", rec.Kind)
+		}
+		out = append(out, rec)
+		if len(out) > MaxRecordCount {
+			return nil, fmt.Errorf("capture: %d records exceeds limit %d", len(out), MaxRecordCount)
+		}
+	}
+	if err := sc.Err(); err != nil {
+		return nil, err
+	}
+	return out, nil
+}
+
+func DecodeSnapshot(rec Record) (*hthv1.Snapshot, error) {
+	if len(rec.Snapshot) == 0 {
+		return nil, fmt.Errorf("no snapshot")
+	}
+	s := &hthv1.Snapshot{}
+	return s, protojson.Unmarshal(rec.Snapshot, s)
+}
+
+func DecodeEvent(rec Record) (*hthv1.Event, error) {
+	if len(rec.Event) == 0 {
+		return nil, fmt.Errorf("no event")
+	}
+	e := &hthv1.Event{}
+	return e, protojson.Unmarshal(rec.Event, e)
+}
+
+func RecordsPath(dir string) string {
+	return filepath.Join(dir, "records.jsonl")
+}

+ 29 - 0
internal/capture/capture_test.go

@@ -0,0 +1,29 @@
+package capture_test
+
+import (
+	"os"
+	"path/filepath"
+	"testing"
+
+	"hth/internal/capture"
+)
+
+func TestTruncatedRecordsRejected(t *testing.T) {
+	dir := t.TempDir()
+	p := capture.RecordsPath(dir)
+	if err := os.WriteFile(p, []byte(`{"v":1,"kind":"event"`), 0o644); err != nil {
+		t.Fatal(err)
+	}
+	r := filepath.Join(dir, "x")
+	_ = r
+	if _, err := capture.ReadRecords(p); err == nil {
+		t.Fatal("truncated jsonl must fail")
+	}
+}
+
+func TestManifestIncompleteRejectedByValidator(t *testing.T) {
+	err := capture.ValidateManifest(capture.Manifest{Status: capture.StatusIncomplete}, "hth.api.v1", "", true)
+	if err == nil {
+		t.Fatal("incomplete must fail when requireComplete")
+	}
+}

+ 0 - 0
internal/capture/disk_test.go


Некоторые файлы не были показаны из-за большого количества измененных файлов