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

fix(host): close R4 serial job ownership, event gaps, and Safe/Resume latch

Make Event IDs strictly monotonic without subscriber-local gap IDs, match serial results to CurrentInflight by job/port/epoch, keep Resume pending in SAFE until dispatch, and fail-close Effective Safety plus host-only evidence recording.
root 3 месяцев назад
Родитель
Сommit
e79938cc6f
48 измененных файлов с 3457 добавлено и 830 удалено
  1. BIN
      api/proto/hth/api/v1/hth.desc
  2. 34 2
      api/proto/hth/api/v1/hth.proto
  3. 2 2
      cmd/hthctl/main.go
  4. 19 3
      internal/app/app.go
  5. 42 18
      internal/backend/mock.go
  6. 6 4
      internal/config/config.go
  7. 260 36
      internal/device/device.go
  8. 7 3
      internal/device/device_test.go
  9. 181 40
      internal/device/lifecycle.go
  10. 2 0
      internal/device/r3_safety_test.go
  11. 592 0
      internal/device/r4_safety_test.go
  12. 190 46
      internal/device/serial_worker.go
  13. 561 292
      internal/gen/hth/api/v1/hth.pb.go
  14. 42 4
      internal/gen/hth/api/v1/hth_grpc.pb.go
  15. 6 1
      internal/grpcserver/server.go
  16. 216 2
      internal/profile/profile.go
  17. 20 4
      internal/profile/profile_test.go
  18. 114 0
      internal/safety/contract.go
  19. 48 0
      internal/safety/contract_test.go
  20. 5 16
      internal/safety/safety.go
  21. 1 0
      internal/state/state.go
  22. 39 33
      internal/telemetry/telemetry.go
  23. 110 20
      internal/telemetry/telemetry_test.go
  24. 13 11
      reviews/01-scope-architecture.md
  25. 0 35
      reviews/02-protocol-data-truth.md
  26. 43 0
      reviews/02-protocol-event-truth.md
  27. 0 43
      reviews/03-safety-lifecycle-concurrency.md
  28. 41 0
      reviews/03-serial-safety-lifecycle.md
  29. 0 44
      reviews/04-api-capture-deployment.md
  30. 34 0
      reviews/04-api-replay-deployment.md
  31. 15 30
      reviews/05-evidence-release.md
  32. 48 1
      sdk/python/hth_sdk/client.py
  33. 116 114
      sdk/python/hth_sdk/generated/hth/api/v1/hth_pb2.py
  34. 45 2
      sdk/python/hth_sdk/generated/hth/api/v1/hth_pb2_grpc.py
  35. 11 1
      tests/capture_replay_binaries_linux_test.go
  36. 42 1
      tests/capture_replay_linux_test.go
  37. 1 0
      tests/grpc_uds_test.go
  38. 1 1
      tests/process_sigterm_linux_test.go
  39. 1 1
      tests/pty_fault_linux_test.go
  40. 385 0
      tests/pty_r4_linux_test.go
  41. 1 1
      tests/pty_serial_test.go
  42. 2 2
      tests/soak_test.go
  43. 10 1
      tools/gen_run_manifest.py
  44. 26 1
      tools/l0_contract_check.py
  45. 7 7
      tools/package_hth_review.py
  46. 20 5
      tools/record_cmd.sh
  47. 22 0
      tools/sdk_wheel_matrix.sh
  48. 76 3
      tools/verify_review_package.py

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


+ 34 - 2
api/proto/hth/api/v1/hth.proto

@@ -85,6 +85,7 @@ enum ActionDispatchState {
   ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN = 8;
   ACTION_DISPATCH_STATE_NOT_DELIVERED = 9;
   ACTION_DISPATCH_STATE_REJECTED = 10;
+  ACTION_DISPATCH_STATE_SUPERSEDED = 11;
 }
 
 enum ControlMode {
@@ -213,6 +214,8 @@ enum RejectReason {
   REJECT_REASON_SAFE_MODE_ACTIVE = 17;
   REJECT_REASON_RESUME_REQUIRED = 18;
   REJECT_REASON_PARTIAL_NOT_ALLOWED = 19;
+  REJECT_REASON_SUPERSEDED = 20;
+  REJECT_REASON_SUPERSEDED_BY_SHUTDOWN = 21;
 }
 
 message Measurement {
@@ -335,6 +338,10 @@ message TimingCapabilities {
   uint32 recommended_action_ttl_ms = 5;
   uint32 minimum_control_period_ms = 6;
   uint32 recommended_sample_period_ms = 7;
+  uint32 max_unpreemptable_transaction_ms = 8;
+  uint32 control_window_ms = 9;
+  uint32 scheduler_margin_ms = 10;
+  uint32 max_pending_continuous_actions = 11;
 }
 
 message CommandedActuator {
@@ -343,6 +350,9 @@ message CommandedActuator {
   DataQuality actual_quality = 3;
   optional double actual_value = 4;
   string actual_reason = 5;
+  uint64 target_epoch = 6;
+  string target_source = 7;
+  DataQuality target_quality = 8;
 }
 
 message FieldAudit {
@@ -368,6 +378,8 @@ message ActionRecord {
   int32 peer_gid = 10;
   int32 peer_pid = 11;
   ActionDispatchState dispatch_state = 12;
+  uint64 action_epoch = 13;
+  uint64 port_generation = 14;
 }
 
 message LeaseSummary {
@@ -402,6 +414,11 @@ message Snapshot {
   TransportState transport_state = 21;
   DeviceReadiness device_readiness = 22;
   SafetyControlMode safety_control_mode = 23;
+  google.protobuf.Timestamp last_successful_hardware_heartbeat = 24;
+  uint32 hardware_watchdog_timeout_ms = 25;
+  uint32 remaining_watchdog_margin_ms = 26;
+  ActionDispatchState heartbeat_delivery_state = 27;
+  uint64 port_generation = 28;
 }
 
 message Fault {
@@ -420,6 +437,13 @@ message Fault {
   map<string, string> diagnostics = 13;
 }
 
+message DeliveryGap {
+  uint64 dropped_count = 1;
+  uint64 last_contiguous_event_id = 2;
+  uint64 requested_resume_after_event_id = 3;
+  uint64 oldest_available_event_id = 4;
+}
+
 message Event {
   uint64 event_id = 1;
   EventKind kind = 2;
@@ -436,6 +460,11 @@ message Event {
   string source_device_id = 13;
   string source_daemon_instance_id = 14;
   uint64 last_contiguous_event_id = 15;
+  // Per-subscriber delivery gap attached to the next real event. Does not
+  // consume a global event_id and must not be treated as a device event.
+  DeliveryGap delivery_gap = 16;
+  ActionResult action_result = 17;
+  uint64 port_generation = 18;
 }
 
 message ContinuousTarget {
@@ -488,6 +517,8 @@ message ActionResult {
   ActionRecord raw_requested = 13;
   ActionRecord normalized_requested = 14;
   ActionDispatchState dispatch_state = 15;
+  string action_origin = 16;
+  uint64 port_generation = 17;
 }
 
 message ControlLease {
@@ -623,8 +654,8 @@ service ObserveService {
   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.
+  // Deprecated: StepReplay mutates global replay state and is rejected unless
+  // the daemon is started with replay.allow_observe_step. Use ControlService.
   rpc StepReplay(StepReplayRequest) returns (StepReplayResponse);
 }
 
@@ -636,4 +667,5 @@ service ControlService {
   rpc ApplyAction(ApplyActionRequest) returns (ActionResult);
   rpc EnterSafeMode(EnterSafeModeRequest) returns (ActionResult);
   rpc ResumeFromSafe(ResumeFromSafeRequest) returns (ActionResult);
+  rpc StepReplay(StepReplayRequest) returns (StepReplayResponse);
 }

+ 2 - 2
cmd/hthctl/main.go

@@ -155,8 +155,8 @@ func main() {
 		fatal(err)
 		printAction(res)
 	case "step-replay":
-		oc := observeClient(*observe, *timeout)
-		res, err := oc.StepReplay(ctx, &hthv1.StepReplayRequest{DeviceId: *deviceID})
+		cc := controlClient(*control, *timeout)
+		res, err := cc.StepReplay(ctx, &hthv1.StepReplayRequest{DeviceId: *deviceID})
 		fatal(err)
 		printMsg(res)
 	default:

+ 19 - 3
internal/app/app.go

@@ -18,6 +18,7 @@ import (
 	"hth/internal/grpcserver"
 	"hth/internal/profile"
 	"hth/internal/protocol"
+	"hth/internal/safety"
 	"hth/internal/sdnotify"
 )
 
@@ -60,8 +61,8 @@ func loadValidated(path, backendOverride string) (*config.Config, *profile.Profi
 	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 := safety.BuildEffectiveSafetyContract(p, cfg.Safety); err != nil {
+		return nil, nil, fmt.Errorf("effective safety contract: %w", err)
 	}
 	if _, err := protocol.Encode(protocol.TypeSetAll, mustPayload(p)); err != nil {
 		return nil, nil, err
@@ -482,6 +483,13 @@ func (a *App) StepReplay(ctx context.Context, id string) (*hthv1.StepReplayRespo
 	return resp, nil
 }
 
+func (a *App) StepReplayObserve(ctx context.Context, id string) (*hthv1.StepReplayResponse, error) {
+	if a.Cfg == nil || !a.Cfg.Replay.AllowObserveStep {
+		return nil, status.Error(codes.PermissionDenied, "StepReplay is a replay-admin ControlService RPC; observe clients cannot mutate global replay")
+	}
+	return a.StepReplay(ctx, id)
+}
+
 func newBackend(cfg *config.Config, p *profile.Profile) (backend.Backend, error) {
 	switch cfg.Backend {
 	case config.BackendMock:
@@ -503,7 +511,15 @@ func newBackend(cfg *config.Config, p *profile.Profile) (backend.Backend, error)
 }
 
 func DoctorText(cfg *config.Config, p *profile.Profile) string {
-	safe := p.SafeSetAll()
+	ov := config.Safety{}
+	if cfg != nil {
+		ov = cfg.Safety
+	}
+	contract, err := safety.BuildEffectiveSafetyContract(p, ov)
+	if err != nil {
+		return fmt.Sprintf("effective_safety_contract=INVALID %v\n", err)
+	}
+	safe := contract.Frame
 	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",

+ 42 - 18
internal/backend/mock.go

@@ -22,24 +22,26 @@ type Mock struct {
 	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
+	disconnected    bool
+	closed          bool
+	shortOnce       bool
+	ambiguousOnce   bool
+	hangGetOnce     bool
+	hangingGet      bool
+	hangGen         uint64
+	ignoreInterrupt bool
+	zeroOnce        bool
+	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 {
@@ -76,9 +78,27 @@ func (m *Mock) Close() error {
 // 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.mu.Lock()
+	ignore := m.ignoreInterrupt
+	m.mu.Unlock()
+	if ignore {
+		return
+	}
 	_ = m.Close()
 }
 
+func (m *Mock) SetIgnoreInterrupt(v bool) {
+	m.mu.Lock()
+	m.ignoreInterrupt = v
+	m.mu.Unlock()
+}
+
+func (m *Mock) ForceZeroByteWrite() {
+	m.mu.Lock()
+	m.zeroOnce = true
+	m.mu.Unlock()
+}
+
 func (m *Mock) TempGetCount() int {
 	m.mu.Lock()
 	defer m.mu.Unlock()
@@ -196,6 +216,10 @@ afterSlow:
 	if m.disconnected || m.closed {
 		return WriteResult{Outcome: WriteDisconnected}, ErrNotConnected
 	}
+	if m.zeroOnce {
+		m.zeroOnce = false
+		return WriteResult{Outcome: WriteNotStarted, N: 0}, ErrWriteNotStarted
+	}
 	if m.shortOnce {
 		m.shortOnce = false
 		return WriteResult{Outcome: WriteShort, N: 3}, nil

+ 6 - 4
internal/config/config.go

@@ -68,10 +68,11 @@ type GRPC struct {
 }
 
 type Replay struct {
-	Path        string  `yaml:"path"`
-	Speed       float64 `yaml:"speed"`
-	Step        bool    `yaml:"step"`
-	FromEventID uint64  `yaml:"from_event_id"`
+	Path             string  `yaml:"path"`
+	Speed            float64 `yaml:"speed"`
+	Step             bool    `yaml:"step"`
+	FromEventID      uint64  `yaml:"from_event_id"`
+	AllowObserveStep bool    `yaml:"allow_observe_step"`
 }
 
 type Mock struct {
@@ -102,6 +103,7 @@ type Config struct {
 	GRPC                 GRPC        `yaml:"grpc"`
 	Replay               Replay      `yaml:"replay"`
 	Mock                 Mock        `yaml:"mock"`
+	AllowUnboundActions  bool        `yaml:"allow_unbound_actions"`
 
 	Path string `yaml:"-"`
 }

+ 260 - 36
internal/device/device.go

@@ -120,6 +120,17 @@ type Device struct {
 	inflightTimeout    time.Duration
 	inflightKind       jobKind
 	controlWindowUntil time.Time
+	jobSeq             uint64
+	portGen            uint64
+	currentInflight    inflightIdent
+	pendingResume      *pendingResumeState
+	pendingSafeJob     *pendingSafeState
+	cmdSeq             uint64
+	lastHWHeartbeat    time.Time
+	hbDeliveryState    hthv1.ActionDispatchState
+	safetyContract     safety.EffectiveContract
+	safetyErr          error
+	workerCtx          context.Context
 }
 
 type applyJobState struct {
@@ -172,23 +183,32 @@ func New(p Params) *Device {
 		slewCredit:  map[string]float64{},
 		controlMode: hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_NORMAL,
 	}
+	if p.Config != nil {
+		c, err := safety.BuildEffectiveSafetyContract(p.Profile, p.Config.Safety)
+		d.safetyContract = c
+		d.safetyErr = err
+		if err == nil {
+			d.caps = overlaySafetyDefaults(d.caps, c)
+			d.caps.CapabilityHash = caphash.HashCanonicalCapabilities(d.caps)
+		}
+	}
 	d.hub.SetIDAlloc(d.store.NextEventID)
 	d.book.SetHook(d.publishFaultEvent)
-	if p.Config.Safety.Fan != nil || p.Config.Safety.PTC != nil || p.Config.Safety.DoorClosePercent != nil {
-		_ = safety.SafeSetAll(p.Profile, p.Config.Safety.Fan, p.Config.Safety.PTC, p.Config.Safety.DoorClosePercent)
-	}
 	return d
 }
 
 func (d *Device) ID() string { return d.id }
 
 func (d *Device) Start(parent context.Context) {
-	_ = parent
-	actorCtx, actorCancel := context.WithCancel(context.Background())
+	if parent == nil {
+		parent = context.Background()
+	}
+	actorCtx, actorCancel := context.WithCancel(parent)
 	workerCtx, workerCancel := context.WithCancel(context.Background())
 	d.cancel = actorCancel
 	d.workerCancel = workerCancel
 	d.runCtx = actorCtx
+	d.workerCtx = workerCtx
 	d.wg.Add(2)
 	go func() {
 		defer d.wg.Done()
@@ -205,8 +225,34 @@ func (d *Device) Stop() {
 		if d.cancel != nil {
 			d.cancel()
 		}
-		d.wg.Wait()
-		_ = d.backend.Close()
+		deadline := d.cfg.ShutdownSafeTimeout()
+		if deadline < 2*time.Second {
+			deadline = 2 * time.Second
+		}
+		done := make(chan struct{})
+		go func() {
+			d.wg.Wait()
+			close(done)
+		}()
+		select {
+		case <-done:
+			_ = d.backend.Close()
+		case <-time.After(deadline):
+			_ = d.backend.Close()
+			if d.workerCancel != nil {
+				d.workerCancel()
+			}
+			join := deadline
+			if join > 3*time.Second {
+				join = 3 * time.Second
+			}
+			select {
+			case <-done:
+			case <-time.After(join):
+				d.book.Raise(d.clk.Now(), hthv1.FaultType_FAULT_TYPE_SERIAL_DISCONNECTED, d.id, "",
+					"worker join exceeded deadline after Close; process should exit for systemd restart", "", nil)
+			}
+		}
 	})
 }
 
@@ -280,7 +326,7 @@ func (d *Device) loop(ctx context.Context) {
 			}
 		case <-temp.C:
 			if d.backend.PollMode() == backend.PollUART && d.connected && d.startupDone && !d.serialInflight() {
-				if d.latchedSafe() || d.pendingSafe || len(d.pendingApply) > 0 || d.controlWindowOpen(d.clk.Now()) {
+				if d.pendingSafe || d.pendingSafeJob != nil || d.pendingResume != nil || len(d.pendingApply) > 0 || d.controlWindowOpen(d.clk.Now()) {
 					d.pendingTemp = true
 					break
 				}
@@ -374,6 +420,7 @@ func (d *Device) onDrop(ctx context.Context, cause error) {
 	d.haveCont = false
 	d.haveDispatch = false
 	d.baselineReady = false
+	d.portGen++
 	d.slewCredit = map[string]float64{}
 	if d.controlMode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE ||
 		d.controlMode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_RESUME_PENDING {
@@ -381,6 +428,7 @@ func (d *Device) onDrop(ctx context.Context, cause error) {
 	}
 	d.endInflight()
 	d.pendingSafe = false
+	d.pendingSafeJob = nil
 	select {
 	case <-d.jobs:
 	default:
@@ -394,9 +442,13 @@ func (d *Device) onDrop(ctx context.Context, cause error) {
 	snap := d.store.Commit(func(s *hthv1.Snapshot) {
 		s.Measurements = missingTemps(d.prof, now, "SERIAL_DROP_NOT_REUSING_OLD_SNAPSHOT")
 		s.ContinuousTargets = nil
+		s.LastRequested = nil
+		s.LastAccepted = nil
+		s.LastDispatched = nil
 		s.Lease = d.lease.Current().Summary(now)
 		s.ActiveFaults = d.book.Active()
 		s.DeviceConfirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN
+		d.annotateSnapshot(s)
 	})
 	d.hub.PublishSnapshot(snap, now)
 	d.hub.PublishEvent(&hthv1.Event{
@@ -426,6 +478,10 @@ func (d *Device) failInflight() {
 	d.pendingApply = nil
 	d.pendingHB = false
 	d.pendingSafe = false
+	d.pendingSafeJob = nil
+	if d.pendingResume != nil {
+		d.abortPendingResume("serial drop while queued", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN)
+	}
 	for _, ch := range d.inflightApply {
 		replyNonblock(ch, unknown("serial drop while inflight"))
 	}
@@ -434,11 +490,19 @@ func (d *Device) failInflight() {
 
 func (d *Device) handle(ctx context.Context, r req) {
 	if d.draining && (r.kind == opAcquire || r.kind == opApply || r.kind == opResume) {
+		reason := hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY
+		st := hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED
+		conf := hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED
+		if r.kind == opApply {
+			reason = hthv1.RejectReason_REJECT_REASON_SUPERSEDED_BY_SHUTDOWN
+			st = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_SUPERSEDED
+			conf = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED
+		}
 		r.reply <- res{action: &hthv1.ActionResult{
 			CommandId: r.batch.GetCommandId(), Accepted: false,
-			RejectReason:  hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY,
-			Confirmation:  hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED,
-			DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED,
+			RejectReason:  reason,
+			Confirmation:  conf,
+			DispatchState: st,
 			Message:       "daemon draining", DeviceEpoch: d.store.Epoch(),
 		}}
 		return
@@ -562,6 +626,16 @@ func (d *Device) assembleResult(batch *hthv1.ActionBatch, validateOnly, resume b
 			d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_CONTROL_COMMAND_REJECTED, d.id, batch.CommandId, rr.String(), "", nil)
 			return res
 		}
+		if !d.cfg.AllowUnboundActions && !resume {
+			if batch.BasedOnSnapshotSeq == 0 || batch.ExpectedControlRevision == 0 {
+				res.RejectReason = hthv1.RejectReason_REJECT_REASON_STALE_SNAPSHOT
+				res.Accepted = false
+				res.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED
+				res.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED
+				res.Message = "ordinary ApplyAction requires based_on_snapshot_seq and expected_control_revision"
+				return res
+			}
+		}
 	}
 	if !validateOnly && d.latchedSafe() && !resume {
 		res.RejectReason = hthv1.RejectReason_REJECT_REASON_SAFE_MODE_ACTIVE
@@ -654,17 +728,7 @@ func (d *Device) beginApply(ctx context.Context, r req) {
 		return
 	}
 	if d.serialInflight() {
-		if len(d.pendingApply) >= 32 {
-			replyNonblock(r.reply, res{action: &hthv1.ActionResult{
-				CommandId: r.batch.GetCommandId(), Accepted: false,
-				RejectReason: hthv1.RejectReason_REJECT_REASON_QUEUE_FULL,
-				Confirmation: hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED,
-				Message:      "apply queue full while serial transaction in flight",
-				DeviceEpoch:  d.store.Epoch(),
-			}})
-			return
-		}
-		d.pendingApply = append(d.pendingApply, r)
+		d.enqueueLatestApply(r)
 		return
 	}
 	assembled := safety.Assemble(d.lastCont, r.batch, d.prof)
@@ -810,7 +874,7 @@ func (d *Device) recordAction(res *hthv1.ActionResult) {
 		if res.Dispatched != nil {
 			s.LastDispatched = res.Dispatched
 		}
-		s.ContinuousTargets = commanded(d.lastCont)
+		s.ContinuousTargets = d.commandedTargets()
 		s.Lease = d.lease.Current().Summary(now)
 		s.ActiveFaults = d.book.Active()
 		s.DeviceConfirmation = res.Confirmation
@@ -819,7 +883,7 @@ func (d *Device) recordAction(res *hthv1.ActionResult) {
 }
 
 func (d *Device) heartbeat(ctx context.Context) {
-	if !d.connected || d.backend.PollMode() != backend.PollUART {
+	if d.draining || !d.connected || d.backend.PollMode() != backend.PollUART {
 		return
 	}
 	if !d.startupDone || !d.baselineReady || !d.haveCont {
@@ -840,10 +904,14 @@ func (d *Device) heartbeat(ctx context.Context) {
 }
 
 func (d *Device) safeFrame() protocol.SetAll {
+	if d.safetyErr == nil && (d.safetyContract.Frame != protocol.SetAll{} || d.safetyContract.ByID != nil) {
+		return d.safetyContract.Frame
+	}
 	return safety.SafeSetAll(d.prof, d.cfg.Safety.Fan, d.cfg.Safety.PTC, d.cfg.Safety.DoorClosePercent)
 }
 
 func (d *Device) checkLease(ctx context.Context) {
+	d.expirePendingResume(ctx)
 	if expired := d.lease.ExpireIfNeeded(d.clk.Now()); expired != nil {
 		d.book.Raise(d.clk.Now(), hthv1.FaultType_FAULT_TYPE_CONTROL_LEASE_EXPIRED, d.id, "", "lease expired", "", nil)
 		d.publishEvent(hthv1.EventKind_EVENT_KIND_LEASE_EXPIRED, "expired")
@@ -947,7 +1015,7 @@ func (d *Device) applyTempMeas(rep *backend.TempReport) {
 	d.store.Commit(func(s *hthv1.Snapshot) {
 		s.Measurements = mergeMeas(s.Measurements, meas)
 		s.CaptureWindow = window(rep.Window)
-		s.ContinuousTargets = commanded(d.lastCont)
+		s.ContinuousTargets = d.commandedTargets()
 		s.Lease = d.lease.Current().Summary(now)
 		s.ActiveFaults = d.book.Active()
 	})
@@ -959,7 +1027,7 @@ func (d *Device) applyMotorMeas(rep *backend.MotorReport) {
 	meas := motorMeasurements(rep.Status, now)
 	d.store.Commit(func(s *hthv1.Snapshot) {
 		s.Measurements = mergeMeas(s.Measurements, meas)
-		s.ContinuousTargets = commanded(d.lastCont)
+		s.ContinuousTargets = d.commandedTargets()
 		s.Lease = d.lease.Current().Summary(now)
 		s.ActiveFaults = d.book.Active()
 		if !d.startupDone {
@@ -1020,16 +1088,19 @@ func (d *Device) replayAdvance(ctx context.Context, rp backend.Replayer) error {
 		rec := capture.Record{Snapshot: item.Snapshot, Kind: "snapshot", EventID: item.EventID, SourceEventID: item.EventID}
 		if snap, err := capture.DecodeSnapshot(rec); err == nil {
 			src := item.EventID
+			srcDev := snap.GetDeviceId()
+			srcDaemon := snap.GetDaemonInstanceId()
 			out := d.store.ReplaceFromReplay(snap)
 			d.lastStepSnap = out
 			d.hub.PublishEvent(&hthv1.Event{
 				EventId:                out.EventId,
 				SourceEventId:          src,
-				SourceDeviceId:         snap.GetDeviceId(),
-				SourceDaemonInstanceId: snap.GetDaemonInstanceId(),
+				SourceDeviceId:         srcDev,
+				SourceDaemonInstanceId: srcDaemon,
+				SourceCaptureId:        d.replayCaptureID(),
 				Kind:                   hthv1.EventKind_EVENT_KIND_SNAPSHOT,
 				WallTime:               timestamppb.New(now),
-				DeviceId:               out.GetDeviceId(),
+				DeviceId:               d.id,
 				Snapshot:               out,
 			})
 		} else {
@@ -1052,9 +1123,19 @@ func (d *Device) replayAdvance(ctx context.Context, rp backend.Replayer) error {
 			if ev.SourceEventId != 0 {
 				src = ev.SourceEventId
 			}
+			srcDev := ev.SourceDeviceId
+			if srcDev == "" {
+				srcDev = ev.DeviceId
+			}
+			srcDaemon := ev.SourceDaemonInstanceId
+			srcCap := ev.SourceCaptureId
+			if srcCap == "" {
+				srcCap = d.replayCaptureID()
+			}
 			ev.SourceEventId = src
-			ev.SourceDeviceId = ev.DeviceId
-			ev.SourceDaemonInstanceId = d.daemon
+			ev.SourceDeviceId = srcDev
+			ev.SourceDaemonInstanceId = srcDaemon
+			ev.SourceCaptureId = srcCap
 			ev.EventId = d.store.NextEventID()
 			if ev.EventId == 0 {
 				ev.EventId = 1
@@ -1067,6 +1148,13 @@ func (d *Device) replayAdvance(ctx context.Context, rp backend.Replayer) error {
 	return fmt.Errorf("capture: record missing snapshot and event")
 }
 
+func (d *Device) replayCaptureID() string {
+	if d.cfg != nil && d.cfg.Replay.Path != "" {
+		return d.cfg.Replay.Path
+	}
+	return ""
+}
+
 func (d *Device) publishNow() {
 	now := d.clk.Now()
 	stale := false
@@ -1077,7 +1165,7 @@ func (d *Device) publishNow() {
 		d.book.Clear(hthv1.FaultType_FAULT_TYPE_TELEMETRY_STALE, d.id, "", now)
 	}
 	snap := d.store.Commit(func(s *hthv1.Snapshot) {
-		s.ContinuousTargets = commanded(d.lastCont)
+		s.ContinuousTargets = d.commandedTargets()
 		s.Lease = d.lease.Current().Summary(now)
 		s.ActiveFaults = d.book.Active()
 		d.refreshMeasurementAge(s, now, stale)
@@ -1408,6 +1496,125 @@ func actionRecord(batch *hthv1.ActionBatch, now time.Time, conf hthv1.Confirmati
 	}
 }
 
+func overlaySafetyDefaults(c *hthv1.Capabilities, contract safety.EffectiveContract) *hthv1.Capabilities {
+	if c == nil {
+		return c
+	}
+	for _, a := range c.Actuators {
+		if a == nil {
+			continue
+		}
+		if v, ok := contract.ByID[a.Id]; ok {
+			a.SafetyDefault = v
+		}
+	}
+	return c
+}
+
+func (d *Device) commandedTargets() []*hthv1.CommandedActuator {
+	if !d.haveCont || !d.baselineReady {
+		return nil
+	}
+	return commandedWithEpoch(d.lastCont, 0)
+}
+
+func commandedWithEpoch(s protocol.SetAll, epoch uint64) []*hthv1.CommandedActuator {
+	out := commanded(s)
+	for _, a := range out {
+		if a == nil {
+			continue
+		}
+		a.TargetEpoch = epoch
+		a.TargetSource = "commanded"
+		a.TargetQuality = hthv1.DataQuality_DATA_QUALITY_NOT_SUPPORTED
+		a.ActualReason = "COMMANDED_NOT_ACTUAL"
+	}
+	return out
+}
+
+func (d *Device) publishActionResult(res *hthv1.ActionResult) {
+	if res == nil {
+		return
+	}
+	now := d.clk.Now()
+	if res.DeviceEpoch == 0 {
+		res.DeviceEpoch = d.store.Epoch()
+	}
+	if res.PortGeneration == 0 {
+		res.PortGeneration = d.portGen
+	}
+	d.hub.PublishEvent(&hthv1.Event{
+		EventId: d.store.NextEventID(), Kind: hthv1.EventKind_EVENT_KIND_ACTION_RESULT,
+		WallTime: timestamppb.New(now), MonotonicNs: uint64(now.UnixNano()),
+		DeviceId: d.id, Message: res.Message, ActionResult: proto.Clone(res).(*hthv1.ActionResult),
+		PortGeneration: d.portGen,
+	})
+}
+
+func (d *Device) enqueueLatestApply(r req) {
+	if d.draining {
+		d.replySuperseded(r, hthv1.RejectReason_REJECT_REASON_SUPERSEDED_BY_SHUTDOWN, "SUPERSEDED_BY_SHUTDOWN")
+		return
+	}
+	leaseID := r.batch.GetLeaseId()
+	for _, old := range d.pendingApply {
+		if old.batch != nil && old.batch.GetLeaseId() != leaseID {
+			replyNonblock(r.reply, res{action: &hthv1.ActionResult{
+				CommandId: r.batch.GetCommandId(), Accepted: false,
+				RejectReason:  hthv1.RejectReason_REJECT_REASON_LEASE_MISMATCH,
+				Confirmation:  hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED,
+				DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED,
+				Message:       "pending action belongs to a different lease",
+				DeviceEpoch:   d.store.Epoch(),
+			}})
+			return
+		}
+		d.replySuperseded(old, hthv1.RejectReason_REJECT_REASON_SUPERSEDED, "SUPERSEDED by later apply")
+	}
+	d.pendingApply = []req{r}
+}
+
+func (d *Device) replySuperseded(r req, reason hthv1.RejectReason, msg string) {
+	out := &hthv1.ActionResult{
+		CommandId: r.batch.GetCommandId(), Accepted: false, RejectReason: reason,
+		Confirmation:  hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED,
+		DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_SUPERSEDED,
+		Message:       msg, DeviceEpoch: d.store.Epoch(), PortGeneration: d.portGen,
+		ActionOrigin: "apply",
+	}
+	d.publishActionResult(out)
+	replyNonblock(r.reply, res{action: out})
+}
+
+func (d *Device) supersedePendingApplies(msg string) {
+	reason := hthv1.RejectReason_REJECT_REASON_SUPERSEDED
+	if msg == "SUPERSEDED_BY_SHUTDOWN" {
+		reason = hthv1.RejectReason_REJECT_REASON_SUPERSEDED_BY_SHUTDOWN
+	}
+	for _, r := range d.pendingApply {
+		d.replySuperseded(r, reason, msg)
+	}
+	d.pendingApply = nil
+}
+
+// TestingInjectStaleSerialResult injects a result that must not clear CurrentInflight.
+func (d *Device) TestingInjectStaleSerialResult(jobID, portGen, epoch uint64, kind int) {
+	select {
+	case d.results <- serialResult{id: jobID, portGen: portGen, epoch: epoch, kind: jobKind(kind)}:
+	default:
+	}
+}
+
+func (d *Device) TestingCurrentInflight() (jobID, portGen, epoch uint64, kind int, ok bool) {
+	inf := d.currentInflight
+	if inf.id == 0 {
+		return 0, 0, 0, 0, false
+	}
+	return inf.id, inf.portGen, inf.epoch, int(inf.kind), true
+}
+
+func (d *Device) TestingPortGeneration() uint64 { return d.portGen }
+
 func commanded(s protocol.SetAll) []*hthv1.CommandedActuator {
 	mk := func(id string, v uint8) *hthv1.CommandedActuator {
 		return &hthv1.CommandedActuator{
@@ -1536,22 +1743,39 @@ func buildCaps(cfg *config.Config, p *profile.Profile) *hthv1.Capabilities {
 	sort.Slice(c.Actuators, func(i, j int) bool { return c.Actuators[i].Id < c.Actuators[j].Id })
 	tempMS := uint32(cfg.GetTempTimeout(p) / time.Millisecond)
 	motorMS := uint32(cfg.GetMotorTimeout() / time.Millisecond)
-	ctrlMS := uint32(cfg.SetAllTimeout() / time.Millisecond)
+	setMS := uint32(cfg.SetAllTimeout() / time.Millisecond)
 	if tempMS < 1 {
 		tempMS = 6500
 	}
-	recRPC := tempMS + ctrlMS + motorMS + 2000
+	unpreempt := tempMS
+	if motorMS > unpreempt {
+		unpreempt = motorMS
+	}
+	if setMS > unpreempt {
+		unpreempt = setMS
+	}
+	ctrlWindow := setMS + 50
+	schedMargin := uint32(50)
+	ctrlWorst := unpreempt + ctrlWindow + schedMargin
+	recRPC := tempMS + ctrlWorst + motorMS + 2000
 	if recRPC < tempMS+3000 {
 		recRPC = tempMS + 3000
 	}
 	c.Timing = &hthv1.TimingCapabilities{
 		TemperatureTransactionWorstCaseMs: tempMS,
 		MotorStatusWorstCaseMs:            motorMS,
-		ControlDispatchWorstCaseMs:        ctrlMS,
+		ControlDispatchWorstCaseMs:        ctrlWorst,
 		RecommendedRpcDeadlineMs:          recRPC,
 		RecommendedActionTtlMs:            recRPC,
-		MinimumControlPeriodMs:            ctrlMS + 50,
+		MinimumControlPeriodMs:            ctrlWindow,
 		RecommendedSamplePeriodMs:         uint32(p.RecommendedSamplePeriod() / time.Millisecond),
+		MaxUnpreemptableTransactionMs:     unpreempt,
+		ControlWindowMs:                   ctrlWindow,
+		SchedulerMarginMs:                 schedMargin,
+		MaxPendingContinuousActions:       1,
+	}
+	if contract, err := safety.BuildEffectiveSafetyContract(p, cfg.Safety); err == nil {
+		c = overlaySafetyDefaults(c, contract)
 	}
 	c.CapabilityHash = caphash.HashCanonicalCapabilities(c)
 	return c

+ 7 - 3
internal/device/device_test.go

@@ -43,6 +43,7 @@ func testDev(t *testing.T, mock *backend.Mock) *device.Device {
 		RingBufferSize:       32,
 		SubscriberBufferSize: 2,
 		CommandCacheSize:     16,
+		AllowUnboundActions:  true,
 		Mock:                 config.Mock{Seed: 1, StartupComplete: true},
 	}
 	if err := cfg.Validate(p); err != nil {
@@ -167,7 +168,8 @@ func TestHeartbeatKeepsDoorPercents(t *testing.T) {
 		Lease:          config.Lease{MinTTLMS: 40, MaxTTLMS: 500},
 		Safety:         config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
 		RingBufferSize: 32, SubscriberBufferSize: 2, CommandCacheSize: 16,
-		Mock: config.Mock{Seed: 1, StartupComplete: true},
+		AllowUnboundActions: true,
+		Mock:                config.Mock{Seed: 1, StartupComplete: true},
 	}
 	if err := cfg.Validate(p); err != nil {
 		t.Fatal(err)
@@ -424,7 +426,8 @@ func testDevNotReady(t *testing.T, mock *backend.Mock) *device.Device {
 		Lease:          config.Lease{MinTTLMS: 40, MaxTTLMS: 500},
 		Safety:         config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
 		RingBufferSize: 32, SubscriberBufferSize: 2, CommandCacheSize: 16,
-		Mock: config.Mock{Seed: 1, StartupComplete: false},
+		AllowUnboundActions: true,
+		Mock:                config.Mock{Seed: 1, StartupComplete: false},
 	}
 	if err := cfg.Validate(p); err != nil {
 		t.Fatal(err)
@@ -543,7 +546,8 @@ func TestSlewRateWithFakeClock(t *testing.T) {
 		Lease:          config.Lease{MinTTLMS: 40, MaxTTLMS: 5000},
 		Safety:         config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
 		RingBufferSize: 32, SubscriberBufferSize: 2, CommandCacheSize: 16,
-		Mock: config.Mock{Seed: 1, StartupComplete: true},
+		AllowUnboundActions: true,
+		Mock:                config.Mock{Seed: 1, StartupComplete: true},
 	}
 	if err := cfg.Validate(p); err != nil {
 		t.Fatal(err)

+ 181 - 40
internal/device/lifecycle.go

@@ -54,6 +54,22 @@ func (d *Device) annotateSnapshot(s *hthv1.Snapshot) {
 	s.TransportState = d.currentTransport()
 	s.DeviceReadiness = d.readinessFrom(s.Lifecycle)
 	s.SafetyControlMode = d.controlMode
+	s.PortGeneration = d.portGen
+	s.HardwareWatchdogTimeoutMs = uint32(d.watchdogTimeout() / time.Millisecond)
+	s.HeartbeatDeliveryState = d.hbDeliveryState
+	if !d.lastHWHeartbeat.IsZero() {
+		s.LastSuccessfulHardwareHeartbeat = timestamppb.New(d.lastHWHeartbeat)
+		s.RemainingWatchdogMarginMs = uint32(d.watchdogMargin() / time.Millisecond)
+	}
+	if !d.haveCont || !d.baselineReady {
+		s.ContinuousTargets = nil
+	} else {
+		for _, a := range s.ContinuousTargets {
+			if a != nil {
+				a.TargetEpoch = s.DeviceEpoch
+			}
+		}
+	}
 }
 
 func (d *Device) setControlMode(mode hthv1.SafetyControlMode, reason string) {
@@ -72,14 +88,16 @@ func (d *Device) enterSafe(ctx context.Context, reason string) *hthv1.ActionResu
 	now := d.clk.Now()
 	d.lease.Invalidate()
 	frame := d.safeFrame()
-	cmd := "safe:" + reason
+	cmd := d.nextInternalCommandID("safe:" + reason)
 	res := &hthv1.ActionResult{
-		CommandId:     cmd,
-		Accepted:      true,
-		DeviceEpoch:   d.store.Epoch(),
-		DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_ACCEPTED,
-		Confirmation:  hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNSPECIFIED,
-		Message:       "safe action accepted; physical SAFE only after a complete SET_ALL write. " + safety.DoorZeroIsFullOpen,
+		CommandId:      cmd,
+		Accepted:       true,
+		DeviceEpoch:    d.store.Epoch(),
+		PortGeneration: d.portGen,
+		ActionOrigin:   reason,
+		DispatchState:  hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_ACCEPTED,
+		Confirmation:   hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNSPECIFIED,
+		Message:        "safe action accepted; physical SAFE only after a complete SET_ALL write. " + safety.DoorZeroIsFullOpen,
 	}
 	batch := &hthv1.ActionBatch{CommandId: cmd, ClientId: "hthd"}
 	res.AcceptedAction = actionRecord(batch, now, res.Confirmation, frame)
@@ -95,6 +113,10 @@ func (d *Device) enterSafe(ctx context.Context, reason string) *hthv1.ActionResu
 		d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_SAFE_ACTION_NOT_DELIVERED, d.id, cmd, "transport down", "", nil)
 	} else if d.serialInflight() {
 		d.pendingSafe = true
+		d.pendingSafeJob = &pendingSafeState{
+			commandID: cmd, reason: reason, origin: "enter_safe:" + reason,
+			enqueued: now, deadline: now.Add(d.cfg.SetAllTimeout()), epoch: d.store.Epoch(),
+		}
 		res.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_QUEUED
 		res.Message += "; queued after current serial transaction"
 		if res.AcceptedAction != nil {
@@ -102,6 +124,10 @@ func (d *Device) enterSafe(ctx context.Context, reason string) *hthv1.ActionResu
 		}
 	} else if !d.enqueueSerial(serialJob{kind: jobSetAllSafe, timeout: d.cfg.ShutdownSafeTimeout(), frame: frame, origin: "enter_safe:" + reason}) {
 		d.pendingSafe = true
+		d.pendingSafeJob = &pendingSafeState{
+			commandID: cmd, reason: reason, origin: "enter_safe:" + reason,
+			enqueued: now, deadline: now.Add(d.cfg.SetAllTimeout()), epoch: d.store.Epoch(),
+		}
 		res.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_QUEUED
 		res.Message += "; serial worker busy, safe write queued"
 	} else {
@@ -121,13 +147,24 @@ func (d *Device) beginResume(ctx context.Context, r req) {
 	_ = ctx
 	now := d.clk.Now()
 	batch := r.batch
-	out := &hthv1.ActionResult{CommandId: batch.GetCommandId(), DeviceEpoch: d.store.Epoch()}
+	out := &hthv1.ActionResult{CommandId: batch.GetCommandId(), DeviceEpoch: d.store.Epoch(), PortGeneration: d.portGen, ActionOrigin: "resume_from_safe"}
 	if d.draining {
 		out.Accepted = false
-		out.RejectReason = hthv1.RejectReason_REJECT_REASON_DEVICE_NOT_READY
+		out.RejectReason = hthv1.RejectReason_REJECT_REASON_SUPERSEDED_BY_SHUTDOWN
+		out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED
+		out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_SUPERSEDED
+		out.Message = "daemon draining"
+		d.publishActionResult(out)
+		replyNonblock(r.reply, res{action: out})
+		return
+	}
+	if d.pendingResume != nil {
+		out.Accepted = false
+		out.RejectReason = hthv1.RejectReason_REJECT_REASON_QUEUE_FULL
 		out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED
 		out.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED
-		out.Message = "daemon draining"
+		out.Message = "a pending ResumeFromSafe already exists"
+		d.publishActionResult(out)
 		replyNonblock(r.reply, res{action: out})
 		return
 	}
@@ -193,29 +230,108 @@ func (d *Device) beginResume(ctx context.Context, r req) {
 		replyNonblock(r.reply, res{action: prep})
 		return
 	}
-	d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_RESUME_PENDING, "resume")
-	target := slew.SetAll
-	d.applyJob = &applyJobState{
-		reply: r.reply, batch: batch, payload: control.PayloadHash(batch),
-		target: target, result: prep, resume: true, credit: credit,
+	vu := time.Time{}
+	if batch != nil && batch.ValidUntil != nil {
+		vu = batch.ValidUntil.AsTime()
+	}
+	leaseID, leaseEp := "", uint64(0)
+	if batch != nil {
+		leaseID, leaseEp = batch.LeaseId, batch.LeaseEpoch
 	}
+	d.pendingResume = &pendingResumeState{
+		req: r, prepared: prep, target: slew.SetAll, credit: credit,
+		commandID: batch.GetCommandId(), leaseID: leaseID, leaseEp: leaseEp,
+		devEpoch: d.store.Epoch(), validUntil: vu, acceptedAt: now,
+	}
+	prep.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_QUEUED
+	prep.Message = "resume accepted; waiting for serial dispatch; control mode remains SAFE"
 	if d.serialInflight() {
-		d.pendingApply = append([]req{r}, d.pendingApply...)
-		d.applyJob = nil
-		prep.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_QUEUED
 		return
 	}
-	if !d.enqueueSerial(serialJob{kind: jobSetAllApply, timeout: d.cfg.SetAllTimeout(), frame: target, origin: "resume_from_safe"}) {
+	d.dispatchPendingResume(ctx)
+}
+
+func (d *Device) dispatchPendingResume(ctx context.Context) {
+	pr := d.pendingResume
+	if pr == nil || d.serialInflight() || !d.connected || d.draining {
+		return
+	}
+	if pr.req.rpcCtx != nil && pr.req.rpcCtx.Err() != nil {
+		d.abortPendingResume("rpc cancelled", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED)
+		return
+	}
+	if !pr.validUntil.IsZero() && !pr.validUntil.After(d.clk.Now()) {
+		d.abortPendingResume("valid_until expired before dispatch", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED)
+		return
+	}
+	if pr.leaseID != "" {
+		if rr := d.lease.CheckAction(d.clk.Now(), &hthv1.ActionBatch{CommandId: pr.commandID, LeaseId: pr.leaseID, LeaseEpoch: pr.leaseEp}, d.store.Seq(), d.store.ControlRevision()); rr == hthv1.RejectReason_REJECT_REASON_LEASE_EXPIRED || rr == hthv1.RejectReason_REJECT_REASON_LEASE_MISSING || rr == hthv1.RejectReason_REJECT_REASON_LEASE_MISMATCH {
+			d.abortPendingResume("lease invalid before resume dispatch", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED)
+			return
+		}
+	}
+	d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_RESUME_PENDING, "resume")
+	d.applyJob = &applyJobState{
+		reply: pr.req.reply, batch: pr.req.batch, payload: control.PayloadHash(pr.req.batch),
+		target: pr.target, result: pr.prepared, resume: true, credit: pr.credit,
+	}
+	d.pendingResume = nil
+	if !d.enqueueSerial(serialJob{kind: jobSetAllApply, timeout: d.cfg.SetAllTimeout(), frame: pr.target, origin: "resume_from_safe"}) {
 		d.applyJob = nil
 		d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, "resume_enqueue_failed")
+		prep := pr.prepared
 		prep.Accepted = false
 		prep.Message = "serial worker busy; resume not started"
 		prep.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED
 		prep.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED
-		replyNonblock(r.reply, res{action: prep})
+		d.publishActionResult(prep)
+		replyNonblock(pr.req.reply, res{action: prep})
+		return
+	}
+	if pr.prepared != nil {
+		pr.prepared.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_DISPATCH_STARTED
+	}
+}
+
+func (d *Device) abortPendingResume(msg string, conf hthv1.ConfirmationStatus, st hthv1.ActionDispatchState) {
+	pr := d.pendingResume
+	d.pendingResume = nil
+	if d.controlMode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_RESUME_PENDING {
+		d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, msg)
+	} else if d.controlMode != hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
+		d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, msg)
+	}
+	if pr == nil {
 		return
 	}
-	prep.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_DISPATCH_STARTED
+	out := pr.prepared
+	if out == nil {
+		out = &hthv1.ActionResult{CommandId: pr.commandID}
+	}
+	out.Accepted = false
+	out.Message = msg
+	out.Confirmation = conf
+	out.DispatchState = st
+	out.DeviceEpoch = d.store.Epoch()
+	out.PortGeneration = d.portGen
+	out.ActionOrigin = "resume_from_safe"
+	d.publishActionResult(out)
+	replyNonblock(pr.req.reply, res{action: out})
+}
+
+func (d *Device) expirePendingResume(ctx context.Context) {
+	_ = ctx
+	pr := d.pendingResume
+	if pr == nil {
+		return
+	}
+	if pr.req.rpcCtx != nil && pr.req.rpcCtx.Err() != nil {
+		d.abortPendingResume("rpc cancelled", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED)
+		return
+	}
+	if !pr.validUntil.IsZero() && !pr.validUntil.After(d.clk.Now()) {
+		d.abortPendingResume("valid_until expired", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED)
+	}
 }
 
 func (d *Device) finishSafeWrite(ctx context.Context, sr serialResult) {
@@ -243,8 +359,9 @@ func (d *Device) finishSafeWrite(ctx context.Context, sr serialResult) {
 	d.slewCredit = map[string]float64{}
 	d.baselineReady = true
 	if sr.origin == originEpochBaseline {
-		if d.controlMode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_UNSPECIFIED ||
-			d.controlMode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_NORMAL {
+		if d.latchedSafe() {
+			d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, "epoch_safe_baseline_keeps_latch")
+		} else {
 			d.controlMode = hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_NORMAL
 			d.safeMode = false
 		}
@@ -258,28 +375,36 @@ func (d *Device) finishSafeWrite(ctx context.Context, sr serialResult) {
 	}
 	d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, sr.origin)
 	d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_SAFE)
-	rec := actionRecord(&hthv1.ActionBatch{CommandId: "safe:" + sr.origin, ClientId: "hthd"}, now,
+	cmd := d.nextInternalCommandID("safe:" + sr.origin)
+	rec := actionRecord(&hthv1.ActionBatch{CommandId: cmd, ClientId: "hthd"}, now,
 		hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED, sr.frame)
 	if rec != nil {
 		rec.ActionMode = hthv1.ActionMode_ACTION_MODE_SAFE
 		rec.DispatchState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED
+		rec.ActionEpoch = d.store.Epoch()
+		rec.PortGeneration = d.portGen
 	}
 	d.store.Commit(func(s *hthv1.Snapshot) {
 		s.LastDispatched = rec
 		s.DeviceConfirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED
-		s.ContinuousTargets = commanded(d.lastCont)
+		s.ContinuousTargets = d.commandedTargets()
 		d.annotateSnapshot(s)
 	})
-	d.hub.PublishEvent(&hthv1.Event{
-		EventId: d.store.NextEventID(), Kind: hthv1.EventKind_EVENT_KIND_ACTION_RESULT,
-		WallTime: timestamppb.New(now), DeviceId: d.id,
-		Message: "SAFE dispatched UNCONFIRMED origin=" + sr.origin,
+	d.publishActionResult(&hthv1.ActionResult{
+		CommandId: cmd, Accepted: true, DeviceEpoch: d.store.Epoch(), PortGeneration: d.portGen,
+		ActionOrigin: sr.origin, Dispatched: rec,
+		Confirmation:  hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED,
+		DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED,
+		Message:       "SAFE dispatched UNCONFIRMED origin=" + sr.origin,
 	})
 	d.publishNow()
 }
 
 func (d *Device) safeWriteResult(sr serialResult) *hthv1.ActionResult {
-	out := &hthv1.ActionResult{CommandId: "safe:" + sr.origin, DeviceEpoch: d.store.Epoch(), Accepted: true}
+	out := &hthv1.ActionResult{
+		CommandId: d.nextInternalCommandID(sr.origin), DeviceEpoch: d.store.Epoch(),
+		PortGeneration: d.portGen, Accepted: true, ActionOrigin: sr.origin,
+	}
 	switch {
 	case sr.wr.Outcome == backend.WriteFullyWritten && sr.err == nil:
 		out.Confirmation = hthv1.ConfirmationStatus_CONFIRMATION_STATUS_UNCONFIRMED
@@ -302,6 +427,19 @@ func (d *Device) runShutdown() {
 	d.draining = true
 	d.pendingTemp = false
 	d.pendingHB = false
+	d.supersedePendingApplies("SUPERSEDED_BY_SHUTDOWN")
+	if d.pendingResume != nil {
+		d.abortPendingResume("shutdown", hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED, hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_SUPERSEDED)
+	}
+	d.pendingSafe = false
+	d.pendingSafeJob = &pendingSafeState{
+		commandID: d.nextInternalCommandID("shutdown"),
+		reason:    "shutdown",
+		origin:    originShutdown,
+		enqueued:  d.clk.Now(),
+		deadline:  time.Now().Add(d.cfg.ShutdownSafeTimeout()),
+		epoch:     d.store.Epoch(),
+	}
 	deadline := time.Now().Add(d.cfg.ShutdownSafeTimeout())
 	dummyB, dummyN := time.Duration(0), time.Time{}
 	if d.serialInflight() {
@@ -318,6 +456,7 @@ func (d *Device) runShutdown() {
 	}
 	if d.connected && !d.serialInflight() {
 		frame := d.safeFrame()
+		d.pendingSafeJob = nil
 		if d.enqueueSerial(serialJob{kind: jobSetAllSafe, timeout: time.Until(deadline), frame: frame, origin: originShutdown}) {
 			for d.serialInflight() && time.Now().Before(deadline) {
 				select {
@@ -330,19 +469,21 @@ func (d *Device) runShutdown() {
 	}
 	if d.shutdownSafeResult == nil {
 		d.shutdownSafeResult = &hthv1.ActionResult{
-			CommandId:     "safe:shutdown",
-			Accepted:      true,
-			Confirmation:  hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED,
-			DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED,
-			Message:       "shutdown safe not delivered",
-			DeviceEpoch:   d.store.Epoch(),
+			CommandId:      d.nextInternalCommandID("shutdown"),
+			Accepted:       true,
+			Confirmation:   hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED,
+			DispatchState:  hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED,
+			Message:        "shutdown safe not delivered",
+			DeviceEpoch:    d.store.Epoch(),
+			PortGeneration: d.portGen,
+			ActionOrigin:   originShutdown,
 		}
 		d.book.Raise(d.clk.Now(), hthv1.FaultType_FAULT_TYPE_SAFE_ACTION_NOT_DELIVERED, d.id, "shutdown", "not delivered before stop deadline", "", nil)
 	}
-	d.hub.PublishEvent(&hthv1.Event{
-		EventId: d.store.NextEventID(), Kind: hthv1.EventKind_EVENT_KIND_ACTION_RESULT,
-		WallTime: timestamppb.New(d.clk.Now()), DeviceId: d.id, Message: d.shutdownSafeResult.Message,
-	})
+	d.publishActionResult(d.shutdownSafeResult)
+	if time.Now().After(deadline) {
+		_ = d.backend.Close()
+	}
 	if d.workerCancel != nil {
 		d.workerCancel()
 	}

+ 2 - 0
internal/device/r3_safety_test.go

@@ -72,6 +72,7 @@ func testDevNoWait(t *testing.T, mock *backend.Mock) *device.Device {
 		RingBufferSize:       32,
 		SubscriberBufferSize: 2,
 		CommandCacheSize:     16,
+		AllowUnboundActions:  true,
 		Mock:                 config.Mock{Seed: 1, StartupComplete: false},
 	}
 	if err := cfg.Validate(p); err != nil {
@@ -267,6 +268,7 @@ func testDevLongTTL(t *testing.T, mock *backend.Mock) *device.Device {
 		RingBufferSize:       32,
 		SubscriberBufferSize: 2,
 		CommandCacheSize:     16,
+		AllowUnboundActions:  true,
 		Mock:                 config.Mock{Seed: 1, StartupComplete: true},
 	}
 	if err := cfg.Validate(p); err != nil {

+ 592 - 0
internal/device/r4_safety_test.go

@@ -0,0 +1,592 @@
+package device_test
+
+import (
+	"context"
+	"strings"
+	"testing"
+	"time"
+
+	"google.golang.org/protobuf/types/known/timestamppb"
+	"hth/internal/backend"
+	"hth/internal/config"
+	"hth/internal/device"
+	hthv1 "hth/internal/gen/hth/api/v1"
+	"hth/internal/profile"
+	"hth/internal/safety"
+	"hth/internal/testutil"
+)
+
+func waitMode(t *testing.T, d *device.Device, mode hthv1.SafetyControlMode, d0 time.Duration) {
+	t.Helper()
+	deadline := time.Now().Add(d0)
+	for time.Now().Before(deadline) {
+		if d.Snapshot().GetSafetyControlMode() == mode {
+			return
+		}
+		time.Sleep(10 * time.Millisecond)
+	}
+	t.Fatalf("want mode %v got %v", mode, d.Snapshot().GetSafetyControlMode())
+}
+
+func waitBusy(t *testing.T, d *device.Device, m *backend.Mock) {
+	t.Helper()
+	deadline := time.Now().Add(3 * time.Second)
+	for time.Now().Before(deadline) {
+		if m.TempGetCount() >= 1 && d.SerialBusy() > 40*time.Millisecond {
+			return
+		}
+		time.Sleep(10 * time.Millisecond)
+	}
+	t.Fatal("GET did not become inflight")
+}
+
+func testDevSafety(t *testing.T, mock *backend.Mock, fan, ptc, door int) *device.Device {
+	t.Helper()
+	p, err := profile.Load(testutil.ProfilePath(t))
+	if err != nil {
+		t.Fatal(err)
+	}
+	dir := t.TempDir()
+	cfg := &config.Config{
+		APIVersion: "hth.api.v1", DeviceID: "prod2u-0", Backend: config.BackendMock,
+		Profile: testutil.ProfilePath(t), RuntimeRoot: dir,
+		Sockets:        config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock", ObservePerm: "0660", ControlPerm: "0660"},
+		Poll:           config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
+		Watchdog:       config.Watchdog{HeartbeatPeriodMS: 5000},
+		Lease:          config.Lease{MinTTLMS: 40, MaxTTLMS: 500},
+		Safety:         config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
+		RingBufferSize: 32, SubscriberBufferSize: 2, CommandCacheSize: 16,
+		AllowUnboundActions: true,
+		Mock:                config.Mock{Seed: 1, StartupComplete: true},
+	}
+	if err := cfg.Validate(p); err != nil {
+		t.Fatal(err)
+	}
+	d := device.New(device.Params{Config: cfg, Profile: p, Backend: mock, InstanceID: "test"})
+	ctx, cancel := context.WithCancel(context.Background())
+	t.Cleanup(func() { cancel(); d.Stop() })
+	d.Start(ctx)
+	waitReady(t, d)
+	return d
+}
+
+func TestStaleSerialResultDoesNotClearNewJob(t *testing.T) {
+	m := backend.NewMock(1, true)
+	d := testDev(t, m)
+	m.SetHangGetOnce()
+	deadline := time.Now().Add(3 * time.Second)
+	var jobID, portGen, epoch uint64
+	var ok bool
+	for time.Now().Before(deadline) {
+		jobID, portGen, epoch, _, ok = d.TestingCurrentInflight()
+		if ok && jobID != 0 {
+			break
+		}
+		time.Sleep(10 * time.Millisecond)
+	}
+	if !ok {
+		t.Fatal("expected inflight GET")
+	}
+	d.TestingInjectStaleSerialResult(jobID+99, portGen, epoch, 0)
+	time.Sleep(80 * time.Millisecond)
+	id2, pg2, ep2, _, still := d.TestingCurrentInflight()
+	if !still || id2 != jobID || pg2 != portGen || ep2 != epoch {
+		t.Fatalf("stale result cleared inflight: still=%v %d/%d/%d want %d/%d/%d", still, id2, pg2, ep2, jobID, portGen, epoch)
+	}
+}
+
+func TestResumeQueuesDuringSlowGetThenNORMAL(t *testing.T) {
+	m := backend.NewMock(1, true)
+	d := testDevLongTTL(t, m)
+	ctx := context.Background()
+	l := acquire(t, d)
+	if !d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual").Accepted {
+		t.Fatal("safe")
+	}
+	waitMode(t, d, hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, 2*time.Second)
+	m.SetSlowGet(1200 * time.Millisecond)
+	waitBusy(t, d, m)
+	l2, err := d.AcquireLease(ctx, "resume-slow", 8*time.Second)
+	if err != nil {
+		t.Fatal(err)
+	}
+	b := batch(d, l2, "resume-during-get", 0)
+	for _, tgt := range b.ContinuousTargets {
+		if strings.HasPrefix(tgt.Id, "fan.") {
+			tgt.Value = 10
+		}
+	}
+	b.ValidUntil = timestamppb.New(time.Now().Add(20 * time.Second))
+	done := make(chan *hthv1.ActionResult, 1)
+	go func() { done <- d.ResumeFromSafe(ctx, l2.LeaseId, l2.LeaseEpoch, b) }()
+	time.Sleep(80 * time.Millisecond)
+	if d.Snapshot().GetSafetyControlMode() != hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
+		t.Fatalf("queued resume must remain SAFE, got %v", d.Snapshot().GetSafetyControlMode())
+	}
+	select {
+	case out := <-done:
+		if out.Confirmation == hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED && !out.Accepted {
+			t.Fatalf("resume result: %+v", out)
+		}
+	case <-time.After(8 * time.Second):
+		t.Fatal("resume did not complete")
+	}
+	waitMode(t, d, hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_NORMAL, 3*time.Second)
+}
+
+func TestResumeCancelReturnsSAFE(t *testing.T) {
+	m := backend.NewMock(1, true)
+	d := testDevLongTTL(t, m)
+	ctx := context.Background()
+	l := acquire(t, d)
+	if !d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual").Accepted {
+		t.Fatal("safe")
+	}
+	waitMode(t, d, hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, 2*time.Second)
+	m.SetSlowGet(1500 * time.Millisecond)
+	waitBusy(t, d, m)
+	l2, err := d.AcquireLease(ctx, "resume-cancel", 8*time.Second)
+	if err != nil {
+		t.Fatal(err)
+	}
+	rpc, cancel := context.WithCancel(ctx)
+	b := batch(d, l2, "resume-cancel", 0)
+	for _, tgt := range b.ContinuousTargets {
+		if strings.HasPrefix(tgt.Id, "fan.") {
+			tgt.Value = 10
+		}
+	}
+	b.ValidUntil = timestamppb.New(time.Now().Add(20 * time.Second))
+	done := make(chan *hthv1.ActionResult, 1)
+	go func() { done <- d.ResumeFromSafe(rpc, l2.LeaseId, l2.LeaseEpoch, b) }()
+	time.Sleep(60 * time.Millisecond)
+	cancel()
+	select {
+	case <-done:
+	case <-time.After(3 * time.Second):
+		t.Fatal("cancelled resume did not return")
+	}
+	waitMode(t, d, hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, 2*time.Second)
+}
+
+func TestSafeReconnectStaysSafe(t *testing.T) {
+	m := backend.NewMock(1, true)
+	d := testDev(t, m)
+	ctx := context.Background()
+	l := acquire(t, d)
+	if !d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual").Accepted {
+		t.Fatal("safe")
+	}
+	waitMode(t, d, hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, 2*time.Second)
+	e0 := d.Snapshot().GetDeviceEpoch()
+	m.ForceAmbiguousWrite()
+	_ = d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "force-drop")
+	deadline := time.Now().Add(4 * time.Second)
+	for time.Now().Before(deadline) {
+		if d.Snapshot().GetDeviceEpoch() > e0 {
+			break
+		}
+		time.Sleep(20 * time.Millisecond)
+	}
+	if d.Snapshot().GetDeviceEpoch() <= e0 {
+		t.Fatal("expected epoch bump")
+	}
+	deadline = time.Now().Add(4 * time.Second)
+	for time.Now().Before(deadline) {
+		mode := d.Snapshot().GetSafetyControlMode()
+		if mode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_NORMAL {
+			t.Fatal("SAFE latch cleared by reconnect baseline")
+		}
+		if mode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
+			return
+		}
+		time.Sleep(20 * time.Millisecond)
+	}
+	t.Fatalf("want SAFE after reconnect, got %v", d.Snapshot().GetSafetyControlMode())
+}
+
+func TestShutdownDoesNotDispatchPendingApply(t *testing.T) {
+	m := backend.NewMock(1, true)
+	d := testDevLongTTL(t, m)
+	l := acquire(t, d)
+	m.SetSlowGet(800 * time.Millisecond)
+	waitBusy(t, d, m)
+	n0 := m.WriteCount()
+	b := batch(d, l, "pending-shutdown", 40)
+	b.ValidUntil = timestamppb.New(time.Now().Add(20 * time.Second))
+	done := make(chan *hthv1.ActionResult, 1)
+	go func() { done <- d.ApplyAction(context.Background(), b) }()
+	time.Sleep(40 * time.Millisecond)
+	d.Stop()
+	select {
+	case out := <-done:
+		if out.DispatchState != hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_SUPERSEDED &&
+			out.RejectReason != hthv1.RejectReason_REJECT_REASON_SUPERSEDED_BY_SHUTDOWN &&
+			!strings.Contains(out.Message, "draining") &&
+			!strings.Contains(strings.ToLower(out.Message), "cancel") {
+			t.Fatalf("pending apply terminal: %+v", out)
+		}
+	case <-time.After(4 * time.Second):
+		t.Fatal("pending apply did not finish")
+	}
+	for _, w := range m.Writes()[n0:] {
+		if w.DoorX == 40 && w.DoorY == 40 && w.DoorZ == 40 {
+			t.Fatal("pending apply was written after Stop")
+		}
+	}
+}
+
+func TestStopUnblocksHangReadIgnoringInterrupt(t *testing.T) {
+	m := backend.NewMock(1, true)
+	m.SetIgnoreInterrupt(true)
+	d := testDev(t, m)
+	m.SetHangGetOnce()
+	deadline := time.Now().Add(2 * time.Second)
+	for time.Now().Before(deadline) {
+		if d.SerialBusy() > 20*time.Millisecond {
+			break
+		}
+		time.Sleep(10 * time.Millisecond)
+	}
+	start := time.Now()
+	d.Stop()
+	if time.Since(start) > 6*time.Second {
+		t.Fatalf("Stop took %s", time.Since(start))
+	}
+}
+
+func TestParentContextCancelStopsDevice(t *testing.T) {
+	m := backend.NewMock(1, true)
+	p, err := profile.Load(testutil.ProfilePath(t))
+	if err != nil {
+		t.Fatal(err)
+	}
+	fan, ptc, door := 10, 0, 0
+	dir := t.TempDir()
+	cfg := &config.Config{
+		APIVersion: "hth.api.v1", DeviceID: "prod2u-0", Backend: config.BackendMock,
+		Profile: testutil.ProfilePath(t), RuntimeRoot: dir,
+		Sockets:        config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock", ObservePerm: "0660", ControlPerm: "0660"},
+		Poll:           config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
+		Watchdog:       config.Watchdog{HeartbeatPeriodMS: 5000},
+		Lease:          config.Lease{MinTTLMS: 40, MaxTTLMS: 500},
+		Safety:         config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
+		RingBufferSize: 32, SubscriberBufferSize: 2, CommandCacheSize: 16,
+		AllowUnboundActions: true, Mock: config.Mock{Seed: 1, StartupComplete: true},
+	}
+	if err := cfg.Validate(p); err != nil {
+		t.Fatal(err)
+	}
+	d := device.New(device.Params{Config: cfg, Profile: p, Backend: m, InstanceID: "parent"})
+	parent, cancel := context.WithCancel(context.Background())
+	d.Start(parent)
+	waitReady(t, d)
+	cancel()
+	deadline := time.Now().Add(5 * time.Second)
+	for time.Now().Before(deadline) {
+		if d.Snapshot().GetLifecycle() == hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_UNAVAILABLE ||
+			d.Snapshot().GetTransportState() == hthv1.TransportState_TRANSPORT_STATE_DISCONNECTED {
+			d.Stop()
+			return
+		}
+		time.Sleep(20 * time.Millisecond)
+	}
+	d.Stop()
+}
+
+func TestHeartbeatNotStartedIsNotSuccess(t *testing.T) {
+	m := backend.NewMock(1, true)
+	p, err := profile.Load(testutil.ProfilePath(t))
+	if err != nil {
+		t.Fatal(err)
+	}
+	fan, ptc, door := 10, 0, 0
+	dir := t.TempDir()
+	cfg := &config.Config{
+		APIVersion: "hth.api.v1", DeviceID: "prod2u-0", Backend: config.BackendMock,
+		Profile: testutil.ProfilePath(t), RuntimeRoot: dir,
+		Sockets:        config.Sockets{Observe: dir + "/o.sock", Control: dir + "/c.sock", ObservePerm: "0660", ControlPerm: "0660"},
+		Poll:           config.Poll{TemperatureMS: 50, MotorStatusMS: 40},
+		Watchdog:       config.Watchdog{HeartbeatPeriodMS: 80},
+		Lease:          config.Lease{MinTTLMS: 40, MaxTTLMS: 500},
+		Safety:         config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door},
+		RingBufferSize: 32, SubscriberBufferSize: 2, CommandCacheSize: 16,
+		AllowUnboundActions: true, Mock: config.Mock{Seed: 1, StartupComplete: true},
+	}
+	if err := cfg.Validate(p); err != nil {
+		t.Fatal(err)
+	}
+	d := device.New(device.Params{Config: cfg, Profile: p, Backend: m, InstanceID: "hb0"})
+	ctx, cancel := context.WithCancel(context.Background())
+	t.Cleanup(func() { cancel(); d.Stop() })
+	d.Start(ctx)
+	waitReady(t, d)
+	m.ForceZeroByteWrite()
+	deadline := time.Now().Add(3 * time.Second)
+	for time.Now().Before(deadline) {
+		if d.Snapshot().GetHeartbeatDeliveryState() == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED {
+			return
+		}
+		time.Sleep(20 * time.Millisecond)
+	}
+	t.Fatalf("heartbeat NOT_STARTED never recorded, state=%v", d.Snapshot().GetHeartbeatDeliveryState())
+}
+
+func TestEpochTargetsNilBeforeBaseline(t *testing.T) {
+	m := backend.NewMock(1, true)
+	d := testDev(t, m)
+	l := acquire(t, d)
+	b := batch(d, l, "ptc80", 0)
+	for _, tgt := range b.ContinuousTargets {
+		if strings.HasPrefix(tgt.Id, "ptc.") {
+			tgt.Value = 80
+		}
+	}
+	if out := d.ApplyAction(context.Background(), b); !out.Accepted {
+		t.Fatalf("apply: %+v", out)
+	}
+	e0 := d.Snapshot().GetDeviceEpoch()
+	m.SetSlow(600 * time.Millisecond)
+	m.ForceShortWrite()
+	_ = d.ApplyAction(context.Background(), batch(d, l, "drop-it", 10))
+	deadline := time.Now().Add(3 * time.Second)
+	for time.Now().Before(deadline) {
+		s := d.Snapshot()
+		if s.GetDeviceEpoch() > e0 {
+			if s.ContinuousTargets != nil {
+				t.Fatalf("new epoch must not expose commanded targets before baseline, got %d", len(s.ContinuousTargets))
+			}
+			return
+		}
+		time.Sleep(5 * time.Millisecond)
+	}
+	t.Fatal("epoch did not bump")
+}
+
+func TestSafetyOverrideChangesCapabilityHash(t *testing.T) {
+	d1 := testDevSafety(t, backend.NewMock(1, true), 10, 0, 0)
+	d2 := testDevSafety(t, backend.NewMock(1, true), 20, 0, 0)
+	if d1.Capabilities().GetCapabilityHash() == d2.Capabilities().GetCapabilityHash() {
+		t.Fatal("safety override must change capability hash")
+	}
+	found := false
+	for _, a := range d2.Capabilities().GetActuators() {
+		if strings.HasPrefix(a.Id, "fan.") && a.GetSafetyDefault() == 20 {
+			found = true
+		}
+	}
+	if !found {
+		t.Fatal("capability safety default not overlaid")
+	}
+	p, err := profile.Load(testutil.ProfilePath(t))
+	if err != nil {
+		t.Fatal(err)
+	}
+	fan, ptc, door := 20, 0, 0
+	if _, err := safety.BuildEffectiveSafetyContract(p, config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+func TestLatestWinsDoesNotReplayOldAction(t *testing.T) {
+	m := backend.NewMock(1, true)
+	d := testDevLongTTL(t, m)
+	l, err := d.AcquireLease(context.Background(), "lw", 8*time.Second)
+	if err != nil {
+		t.Fatal(err)
+	}
+	m.SetSlowGet(700 * time.Millisecond)
+	waitBusy(t, d, m)
+	n0 := m.WriteCount()
+	old := batch(d, l, "old-action", 30)
+	old.ValidUntil = timestamppb.New(time.Now().Add(20 * time.Second))
+	neu := batch(d, l, "new-action", 70)
+	neu.ValidUntil = timestamppb.New(time.Now().Add(20 * time.Second))
+	doneOld := make(chan *hthv1.ActionResult, 1)
+	doneNew := make(chan *hthv1.ActionResult, 1)
+	go func() { doneOld <- d.ApplyAction(context.Background(), old) }()
+	time.Sleep(30 * time.Millisecond)
+	go func() { doneNew <- d.ApplyAction(context.Background(), neu) }()
+	o := <-doneOld
+	n := <-doneNew
+	if o.DispatchState != hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_SUPERSEDED &&
+		o.RejectReason != hthv1.RejectReason_REJECT_REASON_SUPERSEDED {
+		t.Fatalf("old action should be superseded: %+v", o)
+	}
+	if n.Confirmation == hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED {
+		t.Fatalf("new action: %+v", n)
+	}
+	wroteOld, wroteNew := false, false
+	deadline := time.Now().Add(4 * time.Second)
+	for time.Now().Before(deadline) {
+		for _, w := range m.Writes()[n0:] {
+			if w.DoorX == 30 && w.DoorY == 30 {
+				wroteOld = true
+			}
+			if w.DoorX == 70 && w.DoorY == 70 {
+				wroteNew = true
+			}
+		}
+		if wroteNew {
+			break
+		}
+		time.Sleep(20 * time.Millisecond)
+	}
+	if wroteOld {
+		t.Fatal("superseded action was written")
+	}
+	if !wroteNew {
+		t.Fatal("latest action was not written")
+	}
+}
+
+func TestProfileAliasThenIDConflict(t *testing.T) {
+	p, err := profile.Load(testutil.ProfilePath(t))
+	if err != nil {
+		t.Fatal(err)
+	}
+	acts := append([]profile.Actuator(nil), p.Actuators...)
+	acts[0].Aliases = append([]string(nil), "later.id")
+	acts[1].ID = "later.id"
+	p.Actuators = acts
+	if err := p.Validate(); err == nil {
+		t.Fatal("expected id colliding with earlier alias")
+	}
+}
+
+func TestPropertySafeResumeShutdown(t *testing.T) {
+	m := backend.NewMock(1, true)
+	d := testDev(t, m)
+	ctx := context.Background()
+	for i := 0; i < 8; i++ {
+		l, err := d.AcquireLease(ctx, "prop", 400*time.Millisecond)
+		if err != nil {
+			time.Sleep(30 * time.Millisecond)
+			continue
+		}
+		switch i % 4 {
+		case 0:
+			_ = d.ApplyAction(ctx, batch(d, l, "p-apply", uint8(10+i)))
+		case 1:
+			_ = d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "prop")
+		case 2:
+			_ = d.ResumeFromSafe(ctx, l.LeaseId, l.LeaseEpoch, batch(d, l, "p-resume", 0))
+		default:
+			_ = d.Snapshot()
+		}
+		if d.Snapshot().GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_UNSPECIFIED {
+			t.Fatal("unspecified control mode")
+		}
+	}
+}
+
+func TestTwoResumesRejected(t *testing.T) {
+	m := backend.NewMock(1, true)
+	d := testDevLongTTL(t, m)
+	ctx := context.Background()
+	l := acquire(t, d)
+	if !d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual").Accepted {
+		t.Fatal("safe")
+	}
+	waitMode(t, d, hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, 2*time.Second)
+	m.SetSlowGet(900 * time.Millisecond)
+	waitBusy(t, d, m)
+	l2, err := d.AcquireLease(ctx, "two-resume", 8*time.Second)
+	if err != nil {
+		t.Fatal(err)
+	}
+	fillFan10 := func(id string) *hthv1.ActionBatch {
+		b := batch(d, l2, id, 0)
+		for _, tgt := range b.ContinuousTargets {
+			if strings.HasPrefix(tgt.Id, "fan.") {
+				tgt.Value = 10
+			}
+		}
+		b.ValidUntil = timestamppb.New(time.Now().Add(20 * time.Second))
+		return b
+	}
+	first := make(chan *hthv1.ActionResult, 1)
+	second := make(chan *hthv1.ActionResult, 1)
+	go func() { first <- d.ResumeFromSafe(ctx, l2.LeaseId, l2.LeaseEpoch, fillFan10("resume-a")) }()
+	time.Sleep(40 * time.Millisecond)
+	go func() { second <- d.ResumeFromSafe(ctx, l2.LeaseId, l2.LeaseEpoch, fillFan10("resume-b")) }()
+	a := <-first
+	b := <-second
+	rejected := a.DispatchState == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED ||
+		b.DispatchState == hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED ||
+		a.RejectReason == hthv1.RejectReason_REJECT_REASON_QUEUE_FULL ||
+		b.RejectReason == hthv1.RejectReason_REJECT_REASON_QUEUE_FULL
+	if !rejected {
+		t.Fatalf("second resume must be rejected, a=%+v b=%+v", a, b)
+	}
+}
+
+func TestResumeExpireReturnsSAFE(t *testing.T) {
+	m := backend.NewMock(1, true)
+	d := testDevLongTTL(t, m)
+	ctx := context.Background()
+	l := acquire(t, d)
+	if !d.EnterSafeMode(ctx, l.LeaseId, l.LeaseEpoch, "manual").Accepted {
+		t.Fatal("safe")
+	}
+	waitMode(t, d, hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, 2*time.Second)
+	m.SetSlowGet(1500 * time.Millisecond)
+	waitBusy(t, d, m)
+	l2, err := d.AcquireLease(ctx, "resume-exp", 8*time.Second)
+	if err != nil {
+		t.Fatal(err)
+	}
+	b := batch(d, l2, "resume-expire", 0)
+	for _, tgt := range b.ContinuousTargets {
+		if strings.HasPrefix(tgt.Id, "fan.") {
+			tgt.Value = 10
+		}
+	}
+	b.ValidUntil = timestamppb.New(time.Now().Add(80 * time.Millisecond))
+	out := d.ResumeFromSafe(ctx, l2.LeaseId, l2.LeaseEpoch, b)
+	if out.Accepted && out.Confirmation != hthv1.ConfirmationStatus_CONFIRMATION_STATUS_REJECTED &&
+		out.DispatchState != hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED &&
+		out.DispatchState != hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_REJECTED {
+		t.Fatalf("expired resume should not stay accepted: %+v", out)
+	}
+	waitMode(t, d, hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, 3*time.Second)
+}
+
+func TestActionResultEventsArePublished(t *testing.T) {
+	m := backend.NewMock(1, true)
+	d := testDev(t, m)
+	sub, _, _, err := d.SubscribeEvents(0, "test")
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer sub.Cancel()
+	got := make(chan *hthv1.Event, 16)
+	go func() {
+		for ev := range sub.C {
+			if ev.GetActionResult() != nil {
+				select {
+				case got <- ev:
+				default:
+				}
+			}
+		}
+	}()
+	l := acquire(t, d)
+	res := d.ApplyAction(context.Background(), batch(d, l, "evt-apply", 20))
+	if !res.Accepted {
+		t.Fatalf("apply: %+v", res)
+	}
+	deadline := time.Now().Add(2 * time.Second)
+	for time.Now().Before(deadline) {
+		select {
+		case ev := <-got:
+			ar := ev.GetActionResult()
+			if ar.GetConfirmation() == hthv1.ConfirmationStatus_CONFIRMATION_STATUS_CONFIRMED {
+				t.Fatal("no ACK protocol must not emit CONFIRMED")
+			}
+			return
+		case <-time.After(20 * time.Millisecond):
+		}
+	}
+	t.Fatal("missing ACTION_RESULT event")
+}

+ 190 - 46
internal/device/serial_worker.go

@@ -28,22 +28,60 @@ const originEpochBaseline = "epoch_safe_baseline"
 const originShutdown = "shutdown"
 
 type serialJob struct {
+	id        uint64
+	portGen   uint64
+	epoch     uint64
+	kind      jobKind
+	origin    string
+	startedAt time.Time
+	deadline  time.Time
+	timeout   time.Duration
+	frame     protocol.SetAll
+}
+
+type serialResult struct {
+	id      uint64
+	portGen uint64
+	epoch   uint64
 	kind    jobKind
-	timeout time.Duration
-	frame   protocol.SetAll
 	origin  string
-	epoch   uint64
+	started time.Time
+	wr      backend.WriteResult
+	err     error
+	temp    *backend.TempReport
+	motor   *backend.MotorReport
+	frame   protocol.SetAll
 }
 
-type serialResult struct {
-	kind   jobKind
-	wr     backend.WriteResult
-	err    error
-	temp   *backend.TempReport
-	motor  *backend.MotorReport
-	frame  protocol.SetAll
-	origin string
-	epoch  uint64
+type inflightIdent struct {
+	id        uint64
+	portGen   uint64
+	epoch     uint64
+	kind      jobKind
+	origin    string
+	startedAt time.Time
+}
+
+type pendingResumeState struct {
+	req        req
+	prepared   *hthv1.ActionResult
+	target     protocol.SetAll
+	credit     map[string]float64
+	commandID  string
+	leaseID    string
+	leaseEp    uint64
+	devEpoch   uint64
+	validUntil time.Time
+	acceptedAt time.Time
+}
+
+type pendingSafeState struct {
+	commandID string
+	reason    string
+	origin    string
+	enqueued  time.Time
+	deadline  time.Time
+	epoch     uint64
 }
 
 func (d *Device) markProgress() {
@@ -62,14 +100,27 @@ func (d *Device) serialInflight() bool {
 	return atomic.LoadInt64(&d.inflightSinceNano) != 0
 }
 
-func (d *Device) beginInflight() {
+func (d *Device) beginInflight(j serialJob) {
 	atomic.StoreInt64(&d.inflightSinceNano, time.Now().UnixNano())
+	d.currentInflight = inflightIdent{
+		id: j.id, portGen: j.portGen, epoch: j.epoch, kind: j.kind,
+		origin: j.origin, startedAt: j.startedAt,
+	}
 }
 
 func (d *Device) endInflight() {
 	atomic.StoreInt64(&d.inflightSinceNano, 0)
 	d.inflightTimeout = 0
 	d.inflightKind = 0
+	d.currentInflight = inflightIdent{}
+}
+
+func (d *Device) resultMatchesInflight(res serialResult) bool {
+	inf := d.currentInflight
+	if inf.id == 0 {
+		return false
+	}
+	return res.id == inf.id && res.portGen == inf.portGen && res.epoch == inf.epoch && res.kind == inf.kind
 }
 
 func (d *Device) SerialBusy() time.Duration {
@@ -143,6 +194,16 @@ func (d *Device) deadlineUnmeetable(batch *hthv1.ActionBatch) string {
 	return ""
 }
 
+func (d *Device) nextJobID() uint64 {
+	d.jobSeq++
+	return d.jobSeq
+}
+
+func (d *Device) nextInternalCommandID(origin string) string {
+	d.cmdSeq++
+	return fmt.Sprintf("%s:%d:%d:%s", d.daemon, d.store.Epoch(), d.cmdSeq, origin)
+}
+
 func (d *Device) enqueueSerial(j serialJob) bool {
 	if d.serialInflight() {
 		return false
@@ -150,10 +211,17 @@ func (d *Device) enqueueSerial(j serialJob) bool {
 	if j.kind != jobOpen && !d.connected {
 		return false
 	}
+	now := d.clk.Now()
+	j.id = d.nextJobID()
+	j.portGen = d.portGen
 	j.epoch = d.store.Epoch()
+	j.startedAt = now
+	if j.timeout > 0 {
+		j.deadline = now.Add(j.timeout)
+	}
 	d.inflightTimeout = j.timeout
 	d.inflightKind = j.kind
-	d.beginInflight()
+	d.beginInflight(j)
 	select {
 	case d.jobs <- j:
 		return true
@@ -169,7 +237,7 @@ func (d *Device) serialWorker(ctx context.Context) {
 		case <-ctx.Done():
 			return
 		case j := <-d.jobs:
-			res := d.execSerial(j)
+			res := d.execSerial(ctx, j)
 			select {
 			case d.results <- res:
 			case <-ctx.Done():
@@ -179,14 +247,17 @@ func (d *Device) serialWorker(ctx context.Context) {
 	}
 }
 
-func (d *Device) execSerial(j serialJob) serialResult {
+func (d *Device) execSerial(parent context.Context, j serialJob) serialResult {
 	to := j.timeout
 	if to <= 0 {
 		to = 2 * time.Second
 	}
-	ctx, cancel := context.WithTimeout(context.Background(), to)
+	ctx, cancel := context.WithTimeout(parent, to)
 	defer cancel()
-	out := serialResult{kind: j.kind, frame: j.frame, origin: j.origin, epoch: j.epoch}
+	out := serialResult{
+		id: j.id, portGen: j.portGen, epoch: j.epoch, kind: j.kind,
+		origin: j.origin, started: j.startedAt, frame: j.frame,
+	}
 	switch j.kind {
 	case jobOpen:
 		out.err = d.backend.Open(ctx)
@@ -204,13 +275,15 @@ func (d *Device) execSerial(j serialJob) serialResult {
 }
 
 func (d *Device) applySerialResult(ctx context.Context, res serialResult, backoff *time.Duration, next *time.Time) {
-	d.endInflight()
-	d.markProgress()
-	if res.epoch != 0 && res.epoch != d.store.Epoch() {
-		d.log.Warn("discarding stale serial result", "kind", int(res.kind), "job_epoch", res.epoch, "device_epoch", d.store.Epoch())
-		d.kickPendingSerial(ctx)
+	if !d.resultMatchesInflight(res) {
+		d.log.Warn("discarding stale serial result",
+			"job_id", res.id, "job_epoch", res.epoch, "job_port_gen", res.portGen,
+			"inflight_id", d.currentInflight.id, "inflight_epoch", d.currentInflight.epoch,
+			"inflight_port_gen", d.currentInflight.portGen, "kind", int(res.kind))
 		return
 	}
+	d.endInflight()
+	d.markProgress()
 	if res.kind == jobOpen {
 		d.onOpenResult(ctx, res, backoff, next)
 		return
@@ -238,19 +311,7 @@ func (d *Device) applySerialResult(ctx context.Context, res serialResult, backof
 	case jobSetAllApply:
 		d.finishApplyWrite(ctx, res)
 	case jobSetAllHB:
-		if backend.WriteNeedsReconnect(res.wr, res.err) {
-			d.onDrop(ctx, fmt.Errorf("heartbeat write %s: %v", res.wr.Outcome, res.err))
-			return
-		}
-		now := d.clk.Now()
-		origin := res.origin
-		if origin == "" {
-			origin = "watchdog_heartbeat_repeat_continuous"
-		}
-		d.hub.PublishEvent(&hthv1.Event{
-			EventId: d.store.NextEventID(), Kind: hthv1.EventKind_EVENT_KIND_WATCHDOG_HEARTBEAT,
-			WallTime: timestamppb.New(now), DeviceId: d.id, Message: origin,
-		})
+		d.finishHeartbeat(ctx, res)
 	case jobSetAllSafe:
 		d.finishSafeWrite(ctx, res)
 	}
@@ -277,6 +338,7 @@ func (d *Device) onOpenResult(ctx context.Context, res serialResult, backoff *ti
 	}
 	*backoff = 0
 	d.connected = true
+	d.portGen++
 	d.store.SetLifecycle(hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_PROBING)
 	d.book.Clear(hthv1.FaultType_FAULT_TYPE_SERIAL_DISCONNECTED, d.id, "", d.clk.Now())
 	d.book.Clear(hthv1.FaultType_FAULT_TYPE_SERIAL_RECONNECTING, d.id, "", d.clk.Now())
@@ -308,6 +370,7 @@ func (d *Device) finishApplyWrite(ctx context.Context, sr serialResult) {
 			d.setControlMode(hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE, "resume_not_started")
 		}
 		d.recordAction(out)
+		d.publishActionResult(out)
 		replyNonblock(job.reply, res{action: out})
 		return
 	}
@@ -324,6 +387,7 @@ func (d *Device) finishApplyWrite(ctx context.Context, sr serialResult) {
 		}
 		d.lease.Cache().Store(job.batch.CommandId, job.payload, out)
 		d.recordAction(out)
+		d.publishActionResult(out)
 		replyNonblock(job.reply, res{action: out})
 		d.onDrop(ctx, fmt.Errorf("ambiguous serial write outcome=%v err=%v", sr.wr.Outcome, sr.err))
 		return
@@ -355,23 +419,107 @@ func (d *Device) finishApplyWrite(ctx context.Context, sr serialResult) {
 	out.AcceptedAction = actionRecord(job.batch, now, conf, job.target)
 	d.lease.Cache().Store(job.batch.CommandId, job.payload, out)
 	d.recordAction(out)
-	d.publishEvent(hthv1.EventKind_EVENT_KIND_ACTION_RESULT, out.Confirmation.String())
+	d.publishActionResult(out)
 	d.publishNow()
 	replyNonblock(job.reply, res{action: out})
 }
 
+func (d *Device) finishHeartbeat(ctx context.Context, res serialResult) {
+	now := d.clk.Now()
+	origin := res.origin
+	if origin == "" {
+		origin = "watchdog_heartbeat_repeat_continuous"
+	}
+	if res.wr.Outcome == backend.WriteFullyWritten && res.err == nil {
+		d.lastHWHeartbeat = now
+		d.hbDeliveryState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_UNCONFIRMED
+		d.hub.PublishEvent(&hthv1.Event{
+			EventId: d.store.NextEventID(), Kind: hthv1.EventKind_EVENT_KIND_WATCHDOG_HEARTBEAT,
+			WallTime: timestamppb.New(now), DeviceId: d.id, Message: origin,
+			PortGeneration: d.portGen,
+		})
+		d.publishNow()
+		return
+	}
+	if res.wr.Outcome == backend.WriteNotStarted {
+		d.hbDeliveryState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED
+		d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_SAFE_ACTION_NOT_DELIVERED, d.id, origin,
+			fmt.Sprintf("heartbeat NOT_STARTED n=%d err=%v", res.wr.N, res.err), "", nil)
+		d.publishActionResult(&hthv1.ActionResult{
+			CommandId: d.nextInternalCommandID("heartbeat"), Accepted: false,
+			Confirmation:  hthv1.ConfirmationStatus_CONFIRMATION_STATUS_NOT_DELIVERED,
+			DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_NOT_DELIVERED,
+			Message:       "hardware heartbeat not started; not counted as success",
+			DeviceEpoch:   d.store.Epoch(), PortGeneration: d.portGen, ActionOrigin: origin,
+		})
+		d.publishNow()
+		if d.watchdogMargin() < d.cfg.Heartbeat()*2 {
+			d.pendingHB = true
+		}
+		return
+	}
+	d.hbDeliveryState = hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN
+	d.book.Raise(now, hthv1.FaultType_FAULT_TYPE_CONTROL_OUTCOME_UNKNOWN, d.id, origin,
+		fmt.Sprintf("heartbeat %s: %v", res.wr.Outcome, res.err), "", nil)
+	d.publishActionResult(&hthv1.ActionResult{
+		CommandId: d.nextInternalCommandID("heartbeat"), Accepted: false,
+		Confirmation:  hthv1.ConfirmationStatus_CONFIRMATION_STATUS_OUTCOME_UNKNOWN,
+		DispatchState: hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_OUTCOME_UNKNOWN,
+		Message:       "hardware heartbeat outcome unknown; transport dropped",
+		DeviceEpoch:   d.store.Epoch(), PortGeneration: d.portGen, ActionOrigin: origin,
+	})
+	d.onDrop(ctx, fmt.Errorf("heartbeat write %s: %v", res.wr.Outcome, res.err))
+}
+
+func (d *Device) watchdogTimeout() time.Duration {
+	if d.prof != nil && d.prof.Watchdog.TimeoutSeconds > 0 {
+		return time.Duration(d.prof.Watchdog.TimeoutSeconds) * time.Second
+	}
+	return 30 * time.Second
+}
+
+func (d *Device) watchdogMargin() time.Duration {
+	to := d.watchdogTimeout()
+	if d.lastHWHeartbeat.IsZero() {
+		return 0
+	}
+	elapsed := d.clk.Now().Sub(d.lastHWHeartbeat)
+	if elapsed >= to {
+		return 0
+	}
+	return to - elapsed
+}
+
 func (d *Device) kickPendingSerial(ctx context.Context) {
 	if !d.connected || d.serialInflight() {
 		return
 	}
-	if d.pendingSafe {
+	if d.draining {
+		return
+	}
+	d.expirePendingResume(ctx)
+	if d.pendingSafeJob != nil || d.pendingSafe {
+		job := d.pendingSafeJob
+		d.pendingSafeJob = nil
 		d.pendingSafe = false
+		origin := "queued_safe"
+		if job != nil && job.origin != "" {
+			origin = job.origin
+		}
 		frame := d.safeFrame()
-		if !d.enqueueSerial(serialJob{kind: jobSetAllSafe, timeout: d.cfg.SetAllTimeout(), frame: frame, origin: "queued_safe"}) {
+		if !d.enqueueSerial(serialJob{kind: jobSetAllSafe, timeout: d.cfg.SetAllTimeout(), frame: frame, origin: origin}) {
 			d.pendingSafe = true
+			if job == nil {
+				job = &pendingSafeState{origin: origin, enqueued: d.clk.Now(), epoch: d.store.Epoch()}
+			}
+			d.pendingSafeJob = job
 		}
 		return
 	}
+	if d.pendingResume != nil {
+		d.dispatchPendingResume(ctx)
+		return
+	}
 	if len(d.pendingApply) > 0 {
 		r := d.pendingApply[0]
 		d.pendingApply = d.pendingApply[1:]
@@ -380,11 +528,7 @@ func (d *Device) kickPendingSerial(ctx context.Context) {
 			d.kickPendingSerial(ctx)
 			return
 		}
-		if r.kind == opResume {
-			d.beginResume(ctx, r)
-		} else {
-			d.beginApply(ctx, r)
-		}
+		d.beginApply(ctx, r)
 		return
 	}
 	if d.pendingHB {
@@ -392,8 +536,8 @@ func (d *Device) kickPendingSerial(ctx context.Context) {
 		d.heartbeat(ctx)
 		return
 	}
-	if d.pendingTemp && d.startupDone && !d.latchedSafe() {
-		if d.controlWindowOpen(d.clk.Now()) {
+	if d.pendingTemp && d.startupDone {
+		if d.pendingSafe || d.pendingSafeJob != nil || d.pendingResume != nil || len(d.pendingApply) > 0 || d.controlWindowOpen(d.clk.Now()) {
 			return
 		}
 		d.pendingTemp = false

Разница между файлами не показана из-за своего большого размера
+ 561 - 292
internal/gen/hth/api/v1/hth.pb.go


+ 42 - 4
internal/gen/hth/api/v1/hth_grpc.pb.go

@@ -40,8 +40,8 @@ type ObserveServiceClient interface {
 	SubscribeEvents(ctx context.Context, in *SubscribeEventsRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[Event], error)
 	GetFaults(ctx context.Context, in *GetFaultsRequest, opts ...grpc.CallOption) (*GetFaultsResponse, error)
 	WatchHealth(ctx context.Context, in *WatchHealthRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[HealthStatus], error)
-	// StepReplay advances a replay backend by one capture record. It is a
-	// client-triggered single step, not a cancelled internal ticker wait.
+	// Deprecated: StepReplay mutates global replay state and is rejected unless
+	// the daemon is started with replay.allow_observe_step. Use ControlService.
 	StepReplay(ctx context.Context, in *StepReplayRequest, opts ...grpc.CallOption) (*StepReplayResponse, error)
 }
 
@@ -171,8 +171,8 @@ type ObserveServiceServer interface {
 	SubscribeEvents(*SubscribeEventsRequest, grpc.ServerStreamingServer[Event]) error
 	GetFaults(context.Context, *GetFaultsRequest) (*GetFaultsResponse, error)
 	WatchHealth(*WatchHealthRequest, grpc.ServerStreamingServer[HealthStatus]) error
-	// StepReplay advances a replay backend by one capture record. It is a
-	// client-triggered single step, not a cancelled internal ticker wait.
+	// Deprecated: StepReplay mutates global replay state and is rejected unless
+	// the daemon is started with replay.allow_observe_step. Use ControlService.
 	StepReplay(context.Context, *StepReplayRequest) (*StepReplayResponse, error)
 	mustEmbedUnimplementedObserveServiceServer()
 }
@@ -408,6 +408,7 @@ const (
 	ControlService_ApplyAction_FullMethodName         = "/hth.api.v1.ControlService/ApplyAction"
 	ControlService_EnterSafeMode_FullMethodName       = "/hth.api.v1.ControlService/EnterSafeMode"
 	ControlService_ResumeFromSafe_FullMethodName      = "/hth.api.v1.ControlService/ResumeFromSafe"
+	ControlService_StepReplay_FullMethodName          = "/hth.api.v1.ControlService/StepReplay"
 )
 
 // ControlServiceClient is the client API for ControlService service.
@@ -421,6 +422,7 @@ type ControlServiceClient interface {
 	ApplyAction(ctx context.Context, in *ApplyActionRequest, opts ...grpc.CallOption) (*ActionResult, error)
 	EnterSafeMode(ctx context.Context, in *EnterSafeModeRequest, opts ...grpc.CallOption) (*ActionResult, error)
 	ResumeFromSafe(ctx context.Context, in *ResumeFromSafeRequest, opts ...grpc.CallOption) (*ActionResult, error)
+	StepReplay(ctx context.Context, in *StepReplayRequest, opts ...grpc.CallOption) (*StepReplayResponse, error)
 }
 
 type controlServiceClient struct {
@@ -501,6 +503,16 @@ func (c *controlServiceClient) ResumeFromSafe(ctx context.Context, in *ResumeFro
 	return out, nil
 }
 
+func (c *controlServiceClient) StepReplay(ctx context.Context, in *StepReplayRequest, opts ...grpc.CallOption) (*StepReplayResponse, error) {
+	cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+	out := new(StepReplayResponse)
+	err := c.cc.Invoke(ctx, ControlService_StepReplay_FullMethodName, in, out, cOpts...)
+	if err != nil {
+		return nil, err
+	}
+	return out, nil
+}
+
 // ControlServiceServer is the server API for ControlService service.
 // All implementations must embed UnimplementedControlServiceServer
 // for forward compatibility.
@@ -512,6 +524,7 @@ type ControlServiceServer interface {
 	ApplyAction(context.Context, *ApplyActionRequest) (*ActionResult, error)
 	EnterSafeMode(context.Context, *EnterSafeModeRequest) (*ActionResult, error)
 	ResumeFromSafe(context.Context, *ResumeFromSafeRequest) (*ActionResult, error)
+	StepReplay(context.Context, *StepReplayRequest) (*StepReplayResponse, error)
 	mustEmbedUnimplementedControlServiceServer()
 }
 
@@ -543,6 +556,9 @@ func (UnimplementedControlServiceServer) EnterSafeMode(context.Context, *EnterSa
 func (UnimplementedControlServiceServer) ResumeFromSafe(context.Context, *ResumeFromSafeRequest) (*ActionResult, error) {
 	return nil, status.Errorf(codes.Unimplemented, "method ResumeFromSafe not implemented")
 }
+func (UnimplementedControlServiceServer) StepReplay(context.Context, *StepReplayRequest) (*StepReplayResponse, error) {
+	return nil, status.Errorf(codes.Unimplemented, "method StepReplay not implemented")
+}
 func (UnimplementedControlServiceServer) mustEmbedUnimplementedControlServiceServer() {}
 func (UnimplementedControlServiceServer) testEmbeddedByValue()                        {}
 
@@ -690,6 +706,24 @@ func _ControlService_ResumeFromSafe_Handler(srv interface{}, ctx context.Context
 	return interceptor(ctx, in, info, handler)
 }
 
+func _ControlService_StepReplay_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+	in := new(StepReplayRequest)
+	if err := dec(in); err != nil {
+		return nil, err
+	}
+	if interceptor == nil {
+		return srv.(ControlServiceServer).StepReplay(ctx, in)
+	}
+	info := &grpc.UnaryServerInfo{
+		Server:     srv,
+		FullMethod: ControlService_StepReplay_FullMethodName,
+	}
+	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+		return srv.(ControlServiceServer).StepReplay(ctx, req.(*StepReplayRequest))
+	}
+	return interceptor(ctx, in, info, handler)
+}
+
 // ControlService_ServiceDesc is the grpc.ServiceDesc for ControlService service.
 // It's only intended for direct use with grpc.RegisterService,
 // and not to be introspected or modified (even as a copy)
@@ -725,6 +759,10 @@ var ControlService_ServiceDesc = grpc.ServiceDesc{
 			MethodName: "ResumeFromSafe",
 			Handler:    _ControlService_ResumeFromSafe_Handler,
 		},
+		{
+			MethodName: "StepReplay",
+			Handler:    _ControlService_StepReplay_Handler,
+		},
 	},
 	Streams:  []grpc.StreamDesc{},
 	Metadata: "hth/api/v1/hth.proto",

+ 6 - 1
internal/grpcserver/server.go

@@ -33,6 +33,7 @@ type API interface {
 	Faults(ctx context.Context, id string, includeInactive bool) (*hthv1.GetFaultsResponse, error)
 	WatchHealth(ctx context.Context, emit func(*hthv1.HealthStatus) error) error
 	StepReplay(ctx context.Context, id string) (*hthv1.StepReplayResponse, error)
+	StepReplayObserve(ctx context.Context, id string) (*hthv1.StepReplayResponse, error)
 	AcquireLease(ctx context.Context, req *hthv1.AcquireControlLeaseRequest) (*hthv1.ControlLease, error)
 	RenewLease(ctx context.Context, req *hthv1.RenewControlLeaseRequest) (*hthv1.ControlLease, error)
 	ReleaseLease(ctx context.Context, req *hthv1.ReleaseControlLeaseRequest) error
@@ -243,7 +244,11 @@ func (o *observeSrv) WatchHealth(_ *hthv1.WatchHealthRequest, stream hthv1.Obser
 }
 
 func (o *observeSrv) StepReplay(ctx context.Context, req *hthv1.StepReplayRequest) (*hthv1.StepReplayResponse, error) {
-	return o.api.StepReplay(ctx, req.GetDeviceId())
+	return o.api.StepReplayObserve(ctx, req.GetDeviceId())
+}
+
+func (c *controlSrv) StepReplay(ctx context.Context, req *hthv1.StepReplayRequest) (*hthv1.StepReplayResponse, error) {
+	return c.api.StepReplay(ctx, req.GetDeviceId())
 }
 
 func (c *controlSrv) AcquireControlLease(ctx context.Context, req *hthv1.AcquireControlLeaseRequest) (*hthv1.LeaseResponse, error) {

+ 216 - 2
internal/profile/profile.go

@@ -1,12 +1,15 @@
 package profile
 
 import (
+	"bytes"
 	"crypto/sha256"
 	"encoding/hex"
 	"encoding/json"
 	"fmt"
 	"io"
+	"math"
 	"os"
+	"path/filepath"
 	"strings"
 	"time"
 
@@ -234,6 +237,9 @@ func load(path string, strict bool) (*Profile, error) {
 		return nil, fmt.Errorf("profile: read %s: %w", path, err)
 	}
 	sum := sha256.Sum256(raw)
+	if err := rejectDuplicateJSONKeys(raw); err != nil {
+		return nil, fmt.Errorf("profile: %s: %w", path, err)
+	}
 	dec := json.NewDecoder(strings.NewReader(string(raw)))
 	if strict {
 		dec.DisallowUnknownFields()
@@ -341,12 +347,187 @@ func (p *Profile) Validate() error {
 	if p.UART.DataBits != 0 && p.UART.DataBits != 8 {
 		return fmt.Errorf("profile: uart data_bits must be 8")
 	}
+	if p.UART.Parity != "" && !strings.EqualFold(p.UART.Parity, "none") && p.UART.Parity != "N" {
+		return fmt.Errorf("profile: uart parity must be none")
+	}
+	if p.UART.StopBits != 0 && p.UART.StopBits != 1 {
+		return fmt.Errorf("profile: uart stop_bits must be 1")
+	}
+	if p.UART.FlowControl != "" && !strings.EqualFold(p.UART.FlowControl, "none") {
+		return fmt.Errorf("profile: uart flow_control must be none")
+	}
+	if err := p.validateProtocolCRC(); err != nil {
+		return err
+	}
+	if !sha256Hex(p.SourceContractSHA256) {
+		return fmt.Errorf("profile: source_contract_sha256 required as 64-char hex")
+	}
+	if !sha256Hex(p.SourceGoldenSHA256) {
+		return fmt.Errorf("profile: source_golden_sha256 required as 64-char hex")
+	}
+	if err := p.validateEvidenceFiles(); err != nil {
+		return err
+	}
+	return nil
+}
+
+func rejectDuplicateJSONKeys(raw []byte) error {
+	dec := json.NewDecoder(bytes.NewReader(raw))
+	type frame struct {
+		keys      map[string]struct{}
+		expectKey bool
+		isObject  bool
+	}
+	var stack []frame
+	for {
+		tok, err := dec.Token()
+		if err == io.EOF {
+			return nil
+		}
+		if err != nil {
+			return err
+		}
+		switch t := tok.(type) {
+		case json.Delim:
+			switch t {
+			case '{':
+				stack = append(stack, frame{keys: map[string]struct{}{}, expectKey: true, isObject: true})
+			case '[':
+				stack = append(stack, frame{})
+			case '}', ']':
+				if len(stack) == 0 {
+					return fmt.Errorf("duplicate-key scan: unmatched closer")
+				}
+				stack = stack[:len(stack)-1]
+				if len(stack) > 0 && stack[len(stack)-1].isObject {
+					stack[len(stack)-1].expectKey = true
+				}
+			}
+		case string:
+			if len(stack) == 0 {
+				continue
+			}
+			top := &stack[len(stack)-1]
+			if top.isObject && top.expectKey {
+				if _, ok := top.keys[t]; ok {
+					return fmt.Errorf("duplicate JSON key %q (fail closed)", t)
+				}
+				top.keys[t] = struct{}{}
+				top.expectKey = false
+				continue
+			}
+			if top.isObject && !top.expectKey {
+				top.expectKey = true
+			}
+		default:
+			if len(stack) > 0 && stack[len(stack)-1].isObject && !stack[len(stack)-1].expectKey {
+				stack[len(stack)-1].expectKey = true
+			}
+		}
+	}
+}
+
+func (p *Profile) validateEvidenceFiles() error {
+	if p.Path == "" {
+		return nil
+	}
+	dir := filepath.Dir(p.Path)
+	for i := 0; i < 8; i++ {
+		dir = filepath.Dir(dir)
+		pairs := []struct {
+			rel  string
+			want string
+			kind string
+		}{
+			{filepath.Join("src", "generated", "host-contract.json"), p.SourceContractSHA256, "source_contract_sha256"},
+			{filepath.Join("evidence", "host-contract.json"), p.SourceContractSHA256, "source_contract_sha256"},
+			{filepath.Join("src", "generated", "golden-vectors.json"), p.SourceGoldenSHA256, "source_golden_sha256"},
+			{filepath.Join("evidence", "golden-vectors.json"), p.SourceGoldenSHA256, "source_golden_sha256"},
+		}
+		for _, pair := range pairs {
+			path := filepath.Join(dir, pair.rel)
+			raw, err := os.ReadFile(path)
+			if err != nil {
+				continue
+			}
+			sum := sha256.Sum256(raw)
+			got := hex.EncodeToString(sum[:])
+			if !strings.EqualFold(got, pair.want) {
+				return fmt.Errorf("profile: %s does not match %s (got %s want %s)", pair.kind, path, got, pair.want)
+			}
+		}
+		if filepath.Base(dir) == "/" || dir == filepath.Dir(dir) {
+			break
+		}
+	}
+	return nil
+}
+
+func sha256Hex(s string) bool {
+	if len(s) != 64 {
+		return false
+	}
+	for _, c := range s {
+		if (c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F') {
+			return false
+		}
+	}
+	return true
+}
+
+func isFinite(v float64) bool {
+	return !math.IsNaN(v) && !math.IsInf(v, 0)
+}
+
+func (p *Profile) validateProtocolCRC() error {
+	if p.Protocol.HeaderHex != "" && !strings.EqualFold(strings.ReplaceAll(p.Protocol.HeaderHex, " ", ""), "A55A") {
+		return fmt.Errorf("profile: protocol.header_hex must be A55A")
+	}
+	crc := p.Protocol.CRC
+	if crc.Name != "" && !strings.Contains(strings.ToUpper(crc.Name), "CCITT") && !strings.Contains(strings.ToUpper(crc.Name), "CRC-16") {
+		return fmt.Errorf("profile: crc.name must be CRC-16/CCITT-FALSE")
+	}
+	if crc.Polynomial != 0 && crc.Polynomial != 0x1021 {
+		return fmt.Errorf("profile: crc.polynomial must be 0x1021")
+	}
+	if crc.Initial != 0 && crc.Initial != 0xFFFF {
+		return fmt.Errorf("profile: crc.initial must be 0xFFFF")
+	}
+	if crc.ReflectInput || crc.ReflectOutput {
+		return fmt.Errorf("profile: crc RefIn/RefOut must be false")
+	}
+	if crc.XorOutput != 0 {
+		return fmt.Errorf("profile: crc xor_output must be 0")
+	}
+	if crc.Coverage != "" && crc.Coverage != "header+type+length+payload" && crc.Coverage != "type+length+payload" && crc.Coverage != "after_header" {
+		// accept documented coverage strings used by the generated profile
+		if !strings.Contains(strings.ToLower(crc.Coverage), "payload") && crc.Coverage != "frame_without_crc" {
+			return fmt.Errorf("profile: crc.coverage %q not recognized", crc.Coverage)
+		}
+	}
+	if crc.WireOrder != "" && !strings.EqualFold(crc.WireOrder, "little") && !strings.EqualFold(crc.WireOrder, "le") {
+		return fmt.Errorf("profile: crc.wire_order must be little-endian")
+	}
+	seenCmd := map[int]string{}
+	for name, code := range p.Protocol.Commands {
+		if prev, ok := seenCmd[code]; ok {
+			return fmt.Errorf("profile: command type 0x%02x used by %s and %s", code, prev, name)
+		}
+		seenCmd[code] = name
+	}
+	if p.Protocol.GetTemperature.ResponsePayloadLength != 0 && p.Protocol.GetTemperature.ResponsePayloadLength != protocol.TemperaturePayloadLen {
+		return fmt.Errorf("profile: get_temperature response length want %d", protocol.TemperaturePayloadLen)
+	}
+	if p.Protocol.GetMotorStatus.ResponsePayloadLength != 0 && p.Protocol.GetMotorStatus.ResponsePayloadLength != protocol.MotorStatusPayloadLen {
+		return fmt.Errorf("profile: get_motor_status response length want %d", protocol.MotorStatusPayloadLen)
+	}
 	return nil
 }
 
 func (p *Profile) validateIDs() error {
 	seenID := map[string]string{}
 	seenAlias := map[string]string{}
+	srcIdx := map[int]string{}
 	add := func(kind, id string, aliases []string) error {
 		if id == "" {
 			return fmt.Errorf("profile: empty %s id", kind)
@@ -354,6 +535,9 @@ func (p *Profile) validateIDs() error {
 		if prev, ok := seenID[id]; ok {
 			return fmt.Errorf("profile: duplicate id %s (%s and %s)", id, prev, kind)
 		}
+		if prev, ok := seenAlias[id]; ok {
+			return fmt.Errorf("profile: id %q collides with earlier alias of %s", id, prev)
+		}
 		seenID[id] = kind
 		local := map[string]struct{}{}
 		for _, al := range aliases {
@@ -384,6 +568,21 @@ func (p *Profile) validateIDs() error {
 		if err := add("sensor", s.ID, s.Aliases); err != nil {
 			return err
 		}
+		if prev, ok := srcIdx[s.SourceIndex]; ok && s.Kind == "TEMPERATURE" {
+			return fmt.Errorf("profile: sensor source_index %d reused by %s and %s", s.SourceIndex, prev, s.ID)
+		}
+		if s.Kind == "TEMPERATURE" {
+			srcIdx[s.SourceIndex] = s.ID
+		}
+		if !isFinite(s.Resolution) || !isFinite(s.ValidRange.Min) || !isFinite(s.ValidRange.Max) {
+			return fmt.Errorf("profile: sensor %s has non-finite numeric field", s.ID)
+		}
+		if strings.EqualFold(s.Kind, "UNSPECIFIED") || s.Kind == "" {
+			return fmt.Errorf("profile: sensor %s kind must not be UNSPECIFIED", s.ID)
+		}
+		if strings.EqualFold(s.FeedbackMode, "UNSPECIFIED") || s.FeedbackMode == "" {
+			return fmt.Errorf("profile: sensor %s feedback_mode must not be UNSPECIFIED", s.ID)
+		}
 	}
 	offsets := map[int]string{}
 	for _, a := range p.Actuators {
@@ -399,10 +598,25 @@ func (p *Profile) validateIDs() error {
 		if a.SafetyDefault < a.CommandRange.Min || a.SafetyDefault > a.CommandRange.Max {
 			return fmt.Errorf("profile: actuator %s safety_default out of range", a.ID)
 		}
-		if prev, ok := offsets[a.SetAllOffset]; ok {
-			return fmt.Errorf("profile: SET_ALL offset %d overlap %s and %s", a.SetAllOffset, prev, a.ID)
+		if a.SetAllOffset < 0 {
+			return fmt.Errorf("profile: SET_ALL offset %d for %s is negative", a.SetAllOffset, a.ID)
+		}
+		if p.Protocol.SetAll.PayloadLength > 0 && a.SetAllOffset >= p.Protocol.SetAll.PayloadLength {
+			return fmt.Errorf("profile: SET_ALL offset %d for %s exceeds payload_length %d", a.SetAllOffset, a.ID, p.Protocol.SetAll.PayloadLength)
 		}
 		offsets[a.SetAllOffset] = a.ID
+		if !isFinite(a.Resolution) || !isFinite(a.CommandRange.Min) || !isFinite(a.CommandRange.Max) || !isFinite(a.SafetyDefault) || !isFinite(a.MaxSlewPerSecond) {
+			return fmt.Errorf("profile: actuator %s has non-finite numeric field", a.ID)
+		}
+		if strings.EqualFold(a.Kind, "UNSPECIFIED") || a.Kind == "" {
+			return fmt.Errorf("profile: actuator %s kind must not be UNSPECIFIED", a.ID)
+		}
+		if strings.EqualFold(a.ControlMode, "UNSPECIFIED") || a.ControlMode == "" {
+			return fmt.Errorf("profile: actuator %s control_mode must not be UNSPECIFIED", a.ID)
+		}
+		if strings.EqualFold(a.FeedbackMode, "UNSPECIFIED") || a.FeedbackMode == "" {
+			return fmt.Errorf("profile: actuator %s feedback_mode must not be UNSPECIFIED", a.ID)
+		}
 		if err := add("actuator", a.ID, a.Aliases); err != nil {
 			return err
 		}

+ 20 - 4
internal/profile/profile_test.go

@@ -83,13 +83,29 @@ func TestTrailingJSONRejected(t *testing.T) {
 	if err != nil {
 		t.Fatal(err)
 	}
-	if err := os.WriteFile(path, append(raw, []byte("\n{\"schema\":\"hth-device-profile-v1\"}\n")...), 0o644); err != nil {
+	if err := os.WriteFile(path, append(raw, []byte("\n{}")...), 0o644); err != nil {
 		t.Fatal(err)
 	}
-	if _, err := profile.Load(path); err == nil {
-		t.Fatal("second JSON object must be rejected")
+	if _, err := profile.LoadStrict(path); err == nil {
+		t.Fatal("expected trailing JSON error")
+	}
+}
+
+func TestDuplicateJSONKeyRejected(t *testing.T) {
+	dir := t.TempDir()
+	path := filepath.Join(dir, "p.json")
+	raw, err := os.ReadFile(testutil.ProfilePath(t))
+	if err != nil {
+		t.Fatal(err)
+	}
+	dup := bytes.Replace(raw, []byte(`"profile_id"`), []byte(`"profile_id"`), 1)
+	// Force a duplicate key at the object root.
+	bad := []byte(`{"schema":"hth-device-profile-v1","schema":"dup",` + string(raw[1:]))
+	if err := os.WriteFile(path, bad, 0o644); err != nil {
+		t.Fatal(err)
 	}
 	if _, err := profile.LoadStrict(path); err == nil {
-		t.Fatal("strict load must reject trailing JSON")
+		t.Fatal("duplicate JSON key must fail closed")
 	}
+	_ = dup
 }

+ 114 - 0
internal/safety/contract.go

@@ -0,0 +1,114 @@
+package safety
+
+import (
+	"fmt"
+	"math"
+
+	"hth/internal/config"
+	"hth/internal/ids"
+	"hth/internal/profile"
+	"hth/internal/protocol"
+)
+
+// EffectiveContract is the unique merged safety policy used by runtime
+// SET_ALL, Capabilities, Doctor, Mock, and Replay.
+type EffectiveContract struct {
+	Frame protocol.SetAll
+	Fan   int
+	PTC   int
+	Door  int
+	ByID  map[string]float64
+}
+
+func BuildEffectiveSafetyContract(p *profile.Profile, ov config.Safety) (EffectiveContract, error) {
+	var out EffectiveContract
+	if p == nil {
+		return out, fmt.Errorf("effective safety: nil profile")
+	}
+	fan := p.Safety.Fan
+	ptc := p.Safety.PTC
+	door := p.Safety.DoorClosePercent
+	if ov.Fan != nil {
+		fan = *ov.Fan
+	}
+	if ov.PTC != nil {
+		ptc = *ov.PTC
+	}
+	if ov.DoorClosePercent != nil {
+		door = *ov.DoorClosePercent
+	}
+	if err := checkSafetyInt("fan", fan); err != nil {
+		return out, err
+	}
+	if err := checkSafetyInt("ptc", ptc); err != nil {
+		return out, err
+	}
+	if err := checkSafetyInt("door_close_percent", door); err != nil {
+		return out, err
+	}
+	out.Fan, out.PTC, out.Door = fan, ptc, door
+	out.ByID = map[string]float64{}
+	assign := func(id string, v float64) error {
+		a := p.LookupActuator(id)
+		if a == nil {
+			return fmt.Errorf("effective safety: unknown actuator %s", id)
+		}
+		if !isFinite(v) {
+			return fmt.Errorf("effective safety: %s not finite", id)
+		}
+		if a.Resolution <= 0 || !isFinite(a.Resolution) {
+			return fmt.Errorf("effective safety: %s resolution must be > 0", id)
+		}
+		if v < a.CommandRange.Min || v > a.CommandRange.Max {
+			return fmt.Errorf("effective safety: %s value %v out of [%v,%v]", id, v, a.CommandRange.Min, a.CommandRange.Max)
+		}
+		steps := v / a.Resolution
+		if math.Abs(steps-math.Round(steps)) > 1e-9 {
+			return fmt.Errorf("effective safety: %s value %v is not an integer number of resolution %v", id, v, a.Resolution)
+		}
+		if v < 0 || v > 255 || math.Floor(v) != v {
+			return fmt.Errorf("effective safety: %s cannot encode into SET_ALL byte (%v)", id, v)
+		}
+		out.ByID[id] = v
+		return nil
+	}
+	for _, id := range []string{ids.Fan1, ids.Fan2, ids.Fan3, ids.Fan4} {
+		if err := assign(id, float64(fan)); err != nil {
+			return out, err
+		}
+	}
+	for _, id := range []string{ids.PTC1, ids.PTC2, ids.PTC3, ids.PTC4} {
+		if err := assign(id, float64(ptc)); err != nil {
+			return out, err
+		}
+	}
+	for _, id := range []string{ids.DoorX, ids.DoorY, ids.DoorZ} {
+		if err := assign(id, float64(door)); err != nil {
+			return out, err
+		}
+	}
+	frame := protocol.SetAll{}
+	for i := range frame.Fan {
+		frame.Fan[i] = uint8(fan)
+	}
+	for i := range frame.PTC {
+		frame.PTC[i] = uint8(ptc)
+	}
+	frame.DoorX, frame.DoorY, frame.DoorZ = uint8(door), uint8(door), uint8(door)
+	if _, err := frame.Payload(); err != nil {
+		return out, fmt.Errorf("effective safety: SET_ALL not encodable: %w", err)
+	}
+	out.Frame = frame
+	return out, nil
+}
+
+func checkSafetyInt(name string, v int) error {
+	if v < 0 || v > 100 {
+		return fmt.Errorf("effective safety: %s %d out of 0..100", name, v)
+	}
+	return nil
+}
+
+func isFinite(v float64) bool {
+	return !math.IsNaN(v) && !math.IsInf(v, 0)
+}

+ 48 - 0
internal/safety/contract_test.go

@@ -0,0 +1,48 @@
+package safety_test
+
+import (
+	"testing"
+
+	"hth/internal/config"
+	"hth/internal/profile"
+	"hth/internal/safety"
+	"hth/internal/testutil"
+)
+
+func TestEffectiveSafetyOverrideAndBounds(t *testing.T) {
+	p, err := profile.Load(testutil.ProfilePath(t))
+	if err != nil {
+		t.Fatal(err)
+	}
+	fan, ptc, door := 20, 0, 0
+	c, err := safety.BuildEffectiveSafetyContract(p, config.Safety{Fan: &fan, PTC: &ptc, DoorClosePercent: &door})
+	if err != nil {
+		t.Fatal(err)
+	}
+	if c.Fan != 20 || c.Frame.Fan[0] != 20 {
+		t.Fatalf("override not applied: %+v", c)
+	}
+	bad := 101
+	if _, err := safety.BuildEffectiveSafetyContract(p, config.Safety{Fan: &bad}); err == nil {
+		t.Fatal("out of range must fail closed")
+	}
+	half := 10
+	if _, err := safety.BuildEffectiveSafetyContract(p, config.Safety{Fan: &half, PTC: &ptc, DoorClosePercent: &door}); err != nil {
+		t.Fatal(err)
+	}
+}
+
+func TestEffectiveSafetyMatchesSafeSetAll(t *testing.T) {
+	p, err := profile.Load(testutil.ProfilePath(t))
+	if err != nil {
+		t.Fatal(err)
+	}
+	c, err := safety.BuildEffectiveSafetyContract(p, config.Safety{})
+	if err != nil {
+		t.Fatal(err)
+	}
+	s := safety.SafeSetAll(p, nil, nil, nil)
+	if s != c.Frame {
+		t.Fatalf("SafeSetAll drifted from unique contract: %+v vs %+v", s, c.Frame)
+	}
+}

+ 5 - 16
internal/safety/safety.go

@@ -5,6 +5,7 @@ import (
 	"math"
 	"time"
 
+	"hth/internal/config"
 	hthv1 "hth/internal/gen/hth/api/v1"
 	"hth/internal/ids"
 	"hth/internal/profile"
@@ -33,23 +34,11 @@ type Outcome struct {
 }
 
 func SafeSetAll(p *profile.Profile, fan, ptc, door *int) protocol.SetAll {
-	s := p.SafeSetAll()
-	if fan != nil {
-		for i := range s.Fan {
-			s.Fan[i] = uint8(*fan)
-		}
-	}
-	if ptc != nil {
-		for i := range s.PTC {
-			s.PTC[i] = uint8(*ptc)
-		}
-	}
-	if door != nil {
-		s.DoorX = uint8(*door)
-		s.DoorY = uint8(*door)
-		s.DoorZ = uint8(*door)
+	c, err := BuildEffectiveSafetyContract(p, config.Safety{Fan: fan, PTC: ptc, DoorClosePercent: door})
+	if err != nil {
+		return p.SafeSetAll()
 	}
-	return s
+	return c.Frame
 }
 
 func GetByte(s protocol.SetAll, id string) (uint8, bool) {

+ 1 - 0
internal/state/state.go

@@ -33,6 +33,7 @@ func NewStore(deviceID, daemonID string, clk clock.Clock) *Store {
 		deviceID:         deviceID,
 		daemonInstanceID: daemonID,
 		epoch:            1,
+		controlRev:       1,
 		lifecycle:        hthv1.DeviceLifecycleState_DEVICE_LIFECYCLE_STATE_STARTING,
 		clk:              clk,
 	}

+ 39 - 33
internal/telemetry/telemetry.go

@@ -32,6 +32,7 @@ type EventSub struct {
 	dropped               uint64
 	gapPending            bool
 	lastContiguousEventID uint64
+	resumeAfter           uint64
 	peer                  string
 }
 
@@ -142,32 +143,15 @@ func (h *Hub) publishEvent(ev *hthv1.Event, asSnap bool) {
 		}
 	}
 	for _, sub := range h.events {
+		cp := proto.Clone(ev).(*hthv1.Event)
 		if sub.gapPending {
-			now := time.Now()
-			gap := &hthv1.Event{
-				EventId:               h.allocEventID(),
-				Kind:                  hthv1.EventKind_EVENT_KIND_DATA_GAP,
-				DeviceId:              ev.DeviceId,
-				Message:               "slow subscriber dropped events",
-				DroppedCount:          sub.dropped,
-				ResumeAfterEventId:    sub.lastContiguousEventID,
-				LastContiguousEventId: sub.lastContiguousEventID,
-				WallTime:              timestamppb.New(now),
-				MonotonicNs:           uint64(now.UnixNano()),
-			}
-			h.stampGapLocked(gap)
-			select {
-			case sub.ch <- gap:
-				sub.gapPending = false
-			default:
-				sub.dropped++
-				continue
-			}
+			cp.DeliveryGap = h.deliveryGapLocked(sub)
 		}
-		cp := proto.Clone(ev).(*hthv1.Event)
 		select {
 		case sub.ch <- cp:
 			sub.lastContiguousEventID = ev.EventId
+			sub.gapPending = false
+			sub.dropped = 0
 		default:
 			sub.dropped++
 			sub.gapPending = true
@@ -241,26 +225,37 @@ func (h *Hub) SubscribeEventsPeer(resumeAfter uint64, peer string) (*EventSub, [
 	h.next++
 	id := h.next
 	ch := make(chan *hthv1.Event, h.subBuf)
-	sub := &EventSub{C: ch, ch: ch, peer: peer, lastContiguousEventID: resumeAfter}
+	sub := &EventSub{C: ch, ch: ch, peer: peer, lastContiguousEventID: resumeAfter, resumeAfter: resumeAfter}
 	var gap *hthv1.Event
 	var replay []*hthv1.Event
+	var resumeGap *hthv1.DeliveryGap
 	if resumeAfter > 0 {
 		if h.oldestID > 0 && resumeAfter < h.oldestID-1 {
-			gap = &hthv1.Event{
-				Kind:                  hthv1.EventKind_EVENT_KIND_DATA_GAP,
-				Message:               "resume_after_event_id older than ring",
-				ResumeAfterEventId:    resumeAfter,
-				DroppedCount:          h.oldestID - resumeAfter - 1,
-				LastContiguousEventId: resumeAfter,
+			resumeGap = &hthv1.DeliveryGap{
+				DroppedCount:                h.oldestID - resumeAfter - 1,
+				LastContiguousEventId:       resumeAfter,
+				RequestedResumeAfterEventId: resumeAfter,
+				OldestAvailableEventId:      h.oldestID,
 			}
-			h.stampGapLocked(gap)
 			resumeAfter = h.oldestID - 1
 		}
 		for _, it := range h.ring {
 			if it.ev.EventId > resumeAfter {
-				replay = append(replay, proto.Clone(it.ev).(*hthv1.Event))
+				cp := proto.Clone(it.ev).(*hthv1.Event)
+				if resumeGap != nil && len(replay) == 0 {
+					cp.DeliveryGap = resumeGap
+					resumeGap = nil
+				}
+				replay = append(replay, cp)
 			}
 		}
+		if resumeGap != nil {
+			sub.gapPending = true
+			sub.dropped = resumeGap.DroppedCount
+		}
+		if len(replay) > 0 {
+			sub.lastContiguousEventID = replay[len(replay)-1].EventId
+		}
 	}
 	sub.Cancel = func() {
 		h.mu.Lock()
@@ -274,13 +269,24 @@ func (h *Hub) SubscribeEventsPeer(resumeAfter uint64, peer string) (*EventSub, [
 	return sub, replay, gap, nil
 }
 
+func (h *Hub) deliveryGapLocked(sub *EventSub) *hthv1.DeliveryGap {
+	if sub == nil {
+		return nil
+	}
+	return &hthv1.DeliveryGap{
+		DroppedCount:                sub.dropped,
+		LastContiguousEventId:       sub.lastContiguousEventID,
+		RequestedResumeAfterEventId: sub.resumeAfter,
+		OldestAvailableEventId:      h.oldestID,
+	}
+}
+
 func (h *Hub) stampGapLocked(gap *hthv1.Event) {
 	if gap == nil {
 		return
 	}
-	if gap.EventId == 0 {
-		gap.EventId = h.allocEventID()
-	}
+	// Snapshot-subscribe still returns a descriptor Event. It must not
+	// consume a global event_id used by the live stream.
 	if gap.WallTime == nil {
 		now := time.Now()
 		gap.WallTime = timestamppb.New(now)

+ 110 - 20
internal/telemetry/telemetry_test.go

@@ -13,6 +13,20 @@ func snap(id uint64) *hthv1.Snapshot {
 	return &hthv1.Snapshot{DeviceId: "d0", SnapshotSeq: id, EventId: id}
 }
 
+func assertStrictIDs(t *testing.T, ids []uint64) {
+	t.Helper()
+	var last uint64
+	for i, id := range ids {
+		if id == 0 {
+			t.Fatalf("event_id 0 at %d", i)
+		}
+		if i > 0 && id <= last {
+			t.Fatalf("event ids not strictly increasing at %d: %v", i, ids)
+		}
+		last = id
+	}
+}
+
 func TestSlowSubscriberDoesNotBlockAndReportsGap(t *testing.T) {
 	h := telemetry.NewHub(8, 1, 0, 0)
 	sub, _, _ := h.SubscribeSnapshots(0)
@@ -41,7 +55,7 @@ func TestSlowSubscriberDoesNotBlockAndReportsGap(t *testing.T) {
 	}
 }
 
-func TestEventGapIsStickyUntilWritable(t *testing.T) {
+func TestEventGapAttachesToNextRealEvent(t *testing.T) {
 	h := telemetry.NewHub(8, 1, 0, 0)
 	sub, _, _ := h.SubscribeEvents(0)
 	defer sub.Cancel()
@@ -57,30 +71,73 @@ func TestEventGapIsStickyUntilWritable(t *testing.T) {
 	h.PublishEvent(&hthv1.Event{EventId: 4, Kind: hthv1.EventKind_EVENT_KIND_ACTION_RESULT, DeviceId: "d0", WallTime: timestamppb.New(now)})
 	select {
 	case e := <-sub.C:
-		if e.Kind != hthv1.EventKind_EVENT_KIND_DATA_GAP {
-			t.Fatalf("want DATA_GAP, got %v", e.Kind)
+		if e.Kind == hthv1.EventKind_EVENT_KIND_DATA_GAP {
+			t.Fatal("per-subscriber gap must not allocate a DATA_GAP event id")
+		}
+		if e.EventId != 4 {
+			t.Fatalf("want real event 4, got %d kind=%v", e.EventId, e.Kind)
 		}
-		if e.DroppedCount == 0 {
-			t.Fatal("dropped_count")
+		if e.GetDeliveryGap() == nil || e.GetDeliveryGap().DroppedCount == 0 {
+			t.Fatalf("expected delivery_gap on real event: %+v", e.GetDeliveryGap())
 		}
 	default:
-		t.Fatal("expected sticky DATA_GAP once the channel was writable")
+		t.Fatal("expected next real event with delivery_gap")
 	}
 }
 
-func TestRingResumeAndGap(t *testing.T) {
+func TestSlowSubscriberIDsStayStrictlyIncreasing(t *testing.T) {
+	h := telemetry.NewHub(32, 1, 0, 0)
+	sub, _, _ := h.SubscribeEvents(0)
+	defer sub.Cancel()
+	now := time.Unix(1, 0)
+	h.PublishEvent(&hthv1.Event{EventId: 1, Kind: hthv1.EventKind_EVENT_KIND_ACTION_RESULT, DeviceId: "d0", WallTime: timestamppb.New(now)})
+	<-sub.C
+	for i := uint64(2); i <= 20; i++ {
+		h.PublishEvent(&hthv1.Event{EventId: i, Kind: hthv1.EventKind_EVENT_KIND_ACTION_RESULT, DeviceId: "d0", WallTime: timestamppb.New(now)})
+	}
+	h.PublishEvent(&hthv1.Event{EventId: 21, Kind: hthv1.EventKind_EVENT_KIND_ACTION_RESULT, DeviceId: "d0", WallTime: timestamppb.New(now)})
+	var ids []uint64
+	for {
+		select {
+		case e := <-sub.C:
+			ids = append(ids, e.EventId)
+			if e.EventId == 0 {
+				t.Fatal("event_id 0")
+			}
+			if e.Kind == hthv1.EventKind_EVENT_KIND_DATA_GAP {
+				t.Fatal("standalone DATA_GAP must not appear on the live stream")
+			}
+		default:
+			assertStrictIDs(t, ids)
+			if len(ids) < 1 {
+				t.Fatalf("expected recovered event, got %v", ids)
+			}
+			return
+		}
+	}
+}
+
+func TestRingResumeAttachesDeliveryGapWithoutNewID(t *testing.T) {
 	h := telemetry.NewHub(4, 8, 0, 0)
 	now := time.Unix(1, 0)
 	for i := uint64(1); i <= 10; i++ {
 		h.PublishSnapshot(snap(i), now)
 	}
 	_, replay, gap := h.SubscribeEvents(1)
-	if gap == nil {
-		t.Fatal("expected DATA_GAP for resume older than ring")
+	if gap != nil {
+		t.Fatalf("resume gap must not consume a global event: %+v", gap)
 	}
 	if len(replay) == 0 {
 		t.Fatal("should replay remaining ring")
 	}
+	if replay[0].GetDeliveryGap() == nil {
+		t.Fatal("first replayed event must carry delivery_gap")
+	}
+	var ids []uint64
+	for _, e := range replay {
+		ids = append(ids, e.EventId)
+	}
+	assertStrictIDs(t, ids)
 }
 
 func TestSnapshotResumeIgnoresNonSnapshotEvents(t *testing.T) {
@@ -122,26 +179,28 @@ func TestSubscriberLimit(t *testing.T) {
 	}
 }
 
-func TestGapEventIDNeverZeroAndResumeInitializesContiguous(t *testing.T) {
+func TestResumeOlderThanRingDoesNotAllocateGapID(t *testing.T) {
 	h := telemetry.NewHub(4, 1, 0, 0)
 	now := time.Unix(1, 0)
 	for i := uint64(1); i <= 10; i++ {
 		h.PublishEvent(&hthv1.Event{EventId: i, Kind: hthv1.EventKind_EVENT_KIND_ACTION_RESULT, DeviceId: "d0", WallTime: timestamppb.New(now)})
 	}
-	sub, _, gap := h.SubscribeEvents(1)
+	sub, replay, gap := h.SubscribeEvents(1)
 	defer sub.Cancel()
-	if gap == nil {
-		t.Fatal("expected gap")
+	if gap != nil && gap.EventId != 0 {
+		t.Fatal("standalone resume DATA_GAP must not allocate a stream event_id")
 	}
-	if gap.EventId == 0 {
-		t.Fatal("DATA_GAP event_id must not be 0")
+	if len(replay) == 0 || replay[0].GetDeliveryGap() == nil {
+		t.Fatal("expected delivery_gap on first available event")
 	}
-	if gap.LastContiguousEventId != 1 {
-		t.Fatalf("resume last contiguous: %d", gap.LastContiguousEventId)
+	if replay[0].GetDeliveryGap().LastContiguousEventId != 1 {
+		t.Fatalf("resume last contiguous: %+v", replay[0].GetDeliveryGap())
 	}
-	if gap.WallTime == nil {
-		t.Fatal("gap wall clock required")
+	var ids []uint64
+	for _, e := range replay {
+		ids = append(ids, e.EventId)
 	}
+	assertStrictIDs(t, ids)
 }
 
 func TestEventIDsStayMonotonicWithDuplicateSourceIDs(t *testing.T) {
@@ -168,6 +227,32 @@ func TestEventIDsStayMonotonicWithDuplicateSourceIDs(t *testing.T) {
 	}
 }
 
+func TestRepeatedGapsThenRecover(t *testing.T) {
+	h := telemetry.NewHub(64, 1, 0, 0)
+	sub, _, _ := h.SubscribeEvents(0)
+	defer sub.Cancel()
+	now := time.Unix(1, 0)
+	h.PublishEvent(&hthv1.Event{EventId: 1, Kind: hthv1.EventKind_EVENT_KIND_SNAPSHOT, DeviceId: "d0", WallTime: timestamppb.New(now)})
+	<-sub.C
+	for i := uint64(2); i <= 8; i++ {
+		h.PublishEvent(&hthv1.Event{EventId: i, Kind: hthv1.EventKind_EVENT_KIND_ACTION_RESULT, DeviceId: "d0", WallTime: timestamppb.New(now)})
+	}
+	e := <-sub.C
+	h.PublishEvent(&hthv1.Event{EventId: 9, Kind: hthv1.EventKind_EVENT_KIND_ACTION_RESULT, DeviceId: "d0", WallTime: timestamppb.New(now)})
+	e = <-sub.C
+	if e.EventId <= 1 {
+		t.Fatalf("recovered id must be > 1, got %d", e.EventId)
+	}
+	if e.GetDeliveryGap() == nil {
+		t.Fatal("recovery event must describe the transport gap")
+	}
+	h.PublishEvent(&hthv1.Event{EventId: 10, Kind: hthv1.EventKind_EVENT_KIND_ACTION_RESULT, DeviceId: "d0", WallTime: timestamppb.New(now)})
+	e2 := <-sub.C
+	if e2.EventId <= e.EventId {
+		t.Fatalf("ids must keep increasing: %d then %d", e.EventId, e2.EventId)
+	}
+}
+
 func FuzzSubscribeResume(f *testing.F) {
 	f.Add(uint64(0), uint64(1))
 	f.Add(uint64(1), uint64(0))
@@ -183,12 +268,17 @@ func FuzzSubscribeResume(f *testing.F) {
 				WallTime: timestamppb.New(now), SourceEventId: src,
 			})
 		}
-		sub, _, gap := h.SubscribeEvents(resumeAfter)
+		sub, replay, gap := h.SubscribeEvents(resumeAfter)
 		if sub != nil {
 			sub.Cancel()
 		}
 		if gap != nil && gap.EventId == 0 {
 			t.Fatal("gap event id 0")
 		}
+		var ids []uint64
+		for _, e := range replay {
+			ids = append(ids, e.EventId)
+		}
+		assertStrictIDs(t, ids)
 	})
 }

+ 13 - 11
reviews/01-scope-architecture.md

@@ -1,31 +1,33 @@
 # Review 1 — Scope and architecture
 
 Date: 2026-08-18
-Round: HTH Host Safety / Lifecycle / API Truth / Release Evidence Closure Round 3
-HEAD: recorded in the unique Run Manifest after the host-only commit (do not treat this file as overriding that manifest).
+Round: HTH Host serial transaction ownership, Safe/Resume, event ordering, release evidence closure Round 4
+HEAD: recorded in the unique Run Manifest after the host-only commit (this file does not override that manifest).
 
 ## Scope
 
 No RL, NN, MPC, PID, data platform, Web frontend, Kubernetes, cloud services, new CPLD features, or new UART commands were added.
 Process shape remains one `hthd` per serial controller: Actor + Serial Worker + Observe/Control UDS + Python SDK + capture/replay.
-Public API grew only where lifecycle truth required it: `ResumeFromSafe`, orthogonal transport/readiness/control-mode fields, timing capabilities, event provenance, and fault transition.
+Public API grew only additively: `DeliveryGap`, `Event.action_result`, `Event.port_generation`, `SUPERSEDED` dispatch/reject reasons, ControlService `StepReplay`, heartbeat/watchdog snapshot fields, and timing capability fields.
 
 ## Single serial authority
 
-Device Actor owns Lease, Device Epoch, Safe/Resume, slew baselines, and snapshot annotation.
-Serial Transaction Worker owns every protocol frame except Open and forced Close.
-Shutdown Safe, Heartbeat, Baseline, Manual Safe, Lease-expiry Safe, Resume, GET_TEMPERATURE, and GET_MOTOR_STATUS all enqueue on the Worker.
-`Close()` takes the port-handle lock and generation counter, not the transaction mutex, so a stuck Read can be interrupted by closing the FD.
+Device Actor is the only object that allocates `job_id`. Serial Worker executes jobs whose identity includes `job_id`, `port_generation`, `device_epoch`, `kind`, `origin`, `started_at`, and `deadline`.
+`CurrentInflight` is compare-and-cleared only on a full match. Stale results do not call `endInflight()`, do not `kickPendingSerial()`, and do not mutate lease/epoch/snapshot/baseline/control mode.
+Open success increments Port Generation. Close/Drop/Reconnect permanently invalidate the old generation.
+Worker Context is a sibling of Actor Context (not cancelled when draining starts) so Shutdown Safe can still be the next physical `SET_ALL`. Job Context is derived from Worker Context, not `context.Background()`.
 
 ## Findings this round
 
-- `Snapshot()` no longer reads Actor fields from other goroutines; race tests pass.
-- Empty Action Batch, lease-owned Actor access, GET/SET short-write classification, sticky data gap, capability-hash canonicalization, and peer credentials were not reverted to make new tests pass.
-- Two UDS remain: observe (`hth-observe` 02750/0660) and control (`hth-control` 02750/0660). Runtime root stays `root:root` 0751 from tmpfiles; the daemon does not chmod a parent it does not own.
+- Slow-subscriber gaps no longer consume a global Event ID. Gap metadata is attached to the next real event as `delivery_gap`.
+- Pending Resume is an explicit object. Validation does not enter `RESUME_PENDING`; the mode stays `SAFE` until the Resume SET_ALL is actually dispatched.
+- `kickPendingSerial()` returns immediately while draining. Unstarted ordinary applies are `SUPERSEDED_BY_SHUTDOWN` / `NOT_DELIVERED`.
+- Effective Safety Contract is the unique merge of profile + config override. Startup fail-closes if it is invalid. Doctor/Capabilities/Safe SET_ALL use that entry.
+- Ordinary pending control is latest-wins (one pending action per lease/device). Safe/Resume/Shutdown Safe are not superseded by ordinary applies.
 
 ## Verdict
 
 Architecture direction: **PASS**.
 No blocking ownership or scope items.
-Software safety acceptance remains **BLOCKED** until 2 h soak, production RTL 217, and package self-verify from the same clean commit are all PASS.
+Software safety acceptance is not decided in this file; see Review 5 and the Run Manifest.
 Hardware validation: **NOT RUN**. Real actuator validation: **NOT RUN**.

+ 0 - 35
reviews/02-protocol-data-truth.md

@@ -1,35 +0,0 @@
-# Review 2 — Protocol and data truth
-
-Date: 2026-08-18
-Round: HTH Host Safety / Lifecycle / API Truth / Release Evidence Closure Round 3
-
-## Active contract (unchanged)
-
-Door bytes are close-percent `0..100` (`0` = full open). No ACK. Watchdog 30 s fed only by valid `SET_ALL` after `startup_complete`. During calibration the device drops `GET_TEMPERATURE`. Readiness is `GET_MOTOR_STATUS` / `startup_complete`.
-
-## Startup scheduling
-
-Host temperature ticker starts only after a trusted `startup_complete = true`.
-Startup may open serial, write Safe Baseline, poll `GET_MOTOR_STATUS`, and apply allowed thermal SET_ALL. It must not send `GET_TEMPERATURE` or change door percents.
-Evidence:
-
-- `TestStartupSuppressesGetTemperature` (mock, ≥10 s hold, ticker 50 ms, epoch unchanged, motors polled, first temperature after complete).
-- `TestStartupRestartsSuppressTemperature` (disconnect / re-startup).
-- `TestPTYDelayedStartupSuppressesGetTemperature` (real PTY + `devsim`, 10 s hold, production 115200 framing, `GET_TEMPERATURE` count 0, epoch 1).
-
-Overlapping a live `hthd` UART with Icarus while the RTL is still bit-banging 5000-step seek-close makes MOTOR_STATUS miss the host timeout. That is a simulator wall-clock artifact, not a license to send `GET_TEMPERATURE` during calibration. Production RTL evidence is therefore: hthd attached after RTL `startup_complete`, plus the PTY/mock delayed-startup tests above.
-
-## Write honesty
-
-No ACK ⇒ complete writes are `DISPATCHED` + `UNCONFIRMED`, never `CONFIRMED`.
-Short write / ambiguous I/O ⇒ `OUTCOME_UNKNOWN` + new Device Epoch. Not-started writes ⇒ `NOT_DELIVERED`.
-`LastDispatched` updates only after a full frame write.
-
-## Golden / CRC / buf
-
-Independent Python Oracle does not import Go encoders. L0 uses `evidence/golden-vectors.json` in a review zip (not a missing `src/generated/...` README path). `buf lint` and `buf breaking` against `hth.api.v1.desc.prev` remain the descriptor gate.
-
-## Verdict
-
-No unprocessed protocol-truth blockers in Host scheduling or framing.
-Hardware mapping of temperature channels remains **UNKNOWN**. Fan RPM / encoder / firmware version remain **NOT_SUPPORTED**.

+ 43 - 0
reviews/02-protocol-event-truth.md

@@ -0,0 +1,43 @@
+# Review 2 — Protocol and event truth
+
+Date: 2026-08-18
+Round: HTH Host serial transaction ownership, Safe/Resume, event ordering, release evidence closure Round 4
+
+## No ACK
+
+Current Prod2U UART has no ACK. `FULLY_WRITTEN && err == nil` is `DISPATCHED` + `UNCONFIRMED`. The daemon and Python SDK must not emit or accept `CONFIRMED`.
+
+## Event ID monotonicity
+
+Every `SubscribeEvents` stream's non-zero `event_id` is strictly increasing.
+Gap for a slow subscriber is **not** a global event. The next real event carries:
+
+- `dropped_count`
+- `last_contiguous_event_id`
+- `requested_resume_after_event_id`
+- `oldest_available_event_id`
+
+Resume beyond the ring attaches the same structure to the first replayed real event. Event ID 0 is not used. The stream never emits N+1 then N.
+
+## Action Result events
+
+Terminal action outcomes are published as `Event.action_result` (additive tag 17) with command id, origin, device epoch, port generation, lease, requested/normalized/accepted/dispatched records, dispatch state, confirmation, reject/supersede reason, timestamps, and control revision.
+Internal command ids are `daemon:epoch:seq:origin`, not `safe:<reason>`.
+Capture/Replay persist these events. Replay assigns a new live `event_id` and keeps source ids as provenance.
+
+## Epoch and commanded vs actual
+
+`ContinuousTargets` is nil when `haveCont=false` or `baselineReady=false`. Go zero values are not published as real 0% targets.
+Last requested/accepted/dispatched carry `action_epoch` / `port_generation`. After an epoch change, the current snapshot does not present old actions as the live commanded state. Without hardware feedback, values remain **commanded**, not actual (`DATA_QUALITY_NOT_SUPPORTED` / `COMMANDED_NOT_ACTUAL`).
+
+## Heartbeat truth
+
+Only `WriteOutcome == FULLY_WRITTEN && err == nil` counts as a successful hardware heartbeat.
+`NOT_STARTED` is `NOT_DELIVERED` (no success event, no automatic reconnect for 0-byte writes).
+`PARTIAL` / `FULL_WITH_ERROR` / `UNKNOWN` / `DISCONNECTED` close transport, bump epoch, invalidate the lease, and do not replay the original frame.
+Snapshot publishes `last_successful_hardware_heartbeat`, `hardware_watchdog_timeout_ms`, `remaining_watchdog_margin_ms`, and `heartbeat_delivery_state`. systemd Watchdog petting is not a claim that the firmware 30 s watchdog was fed.
+
+## Verdict
+
+Protocol/event truth direction: **PASS** for the items implemented and tested in-tree.
+Do not treat Review 5 gates (buf, soak, RTL) as decided here.

+ 0 - 43
reviews/03-safety-lifecycle-concurrency.md

@@ -1,43 +0,0 @@
-# Review 3 — Safety, lifecycle, concurrency
-
-Date: 2026-08-18
-Round: HTH Host Safety / Lifecycle / API Truth / Release Evidence Closure Round 3
-
-## Orthogonal lifecycle
-
-Transport (`DISCONNECTED|CONNECTING|CONNECTED`), Device Readiness (`STARTING|PROBING|READY|DEGRADED`), and Control Mode (`NORMAL|SAFE_PENDING|SAFE|RESUME_PENDING`) are separate.
-`EnterSafeMode` records Accepted, invalidates the lease, and latches SAFE only after a complete Safe frame write. SAFE_PENDING/unavailable must not claim the physical plant is safe.
-Ordinary Apply is rejected while latched SAFE. A new lease does not clear SAFE. `ResumeFromSafe` requires a complete batch, full safety validation, slew from the Safe baseline, and a complete write before NORMAL.
-
-## Action lifecycle
-
-`REQUESTED → ACCEPTED → QUEUED → DISPATCH_STARTED → DISPATCHED` with `UNCONFIRMED` on the no-ACK UART.
-Queued or unconnected jobs are not marked Dispatched. Snapshot `LastDispatched` follows the real write. Events carry command id, peer credentials, Device Epoch, and time.
-
-## Serial cancel
-
-Transaction lock, port-handle lock, cancel/Close channel, and port generation are split.
-`TestCloseUnblocksIgnoredContextReadWithoutTxnLock` uses a Read that ignores context and returns only after FD close. Close does not wait for the transaction mutex. Stale generation results are dropped.
-
-## Shutdown
-
-Draining rejects new leases/ordinary Apply. Shutdown Safe is the Worker’s highest priority. Idle / in-flight SIGTERM coverage lives in `process_sigterm_linux_test.go`. TimeoutStopSec=15. Final frame is Safe when the port can write; otherwise Not Delivered is recorded.
-
-## Slew
-
-Floor-toward-zero plus fractional credit. Accepted/queued/short-write/unknown outcomes do not move the dispatched time base. Safe reductions follow the per-field safety contract; ordinary PTC increases cannot bypass.
-
-## Timing
-
-Discoverable timing capabilities come from the profile + UART + scheduler margin. Python SDK fail-closes without capabilities and must not default to 2 s. Recommended RPC deadline covers queue wait plus the worst-case temperature transaction.
-A 2 s `valid_until` during an in-flight 5 s `GET_TEMPERATURE` is rejected before enqueue (`EXPIRED_DEADLINE`). Recommended TTL queues behind the scan and dispatches after it. With an active Control Lease, a control window is reserved after each temperature transaction so scans cannot back-to-back occupy the UART.
-
-## Race / fuzz
-
-`go test -race ./...` PASS this round. PR fuzz 60 s targets remain: Parser, LoadStrict, LoadYAML, ReadRecords, ReadManifest, Assemble, AssembleProto, ReplayOpen, SubscribeResume, SocketPaths.
-Nightly 15 min fuzz: **NOT RUN**.
-
-## Verdict
-
-Lifecycle and cancel semantics are closed in source and unit/PTY tests.
-2 h soak (`TestPRSoakMock`, 7201 s) **PASS** on `21c739f`. 24 h soak: **NOT RUN**.

Разница между файлами не показана из-за своего большого размера
+ 41 - 0
reviews/03-serial-safety-lifecycle.md


+ 0 - 44
reviews/04-api-capture-deployment.md

@@ -1,44 +0,0 @@
-# Review 4 — API, Capture, Replay, SDK, systemd
-
-Date: 2026-08-18
-Round: HTH Host Safety / Lifecycle / API Truth / Release Evidence Closure Round 3
-
-## Event ID / Replay
-
-Replay mints a local monotonic `event_id` and stores source ids in provenance (`source_event_id`, `source_capture_id`, `source_device_id`, `source_daemon_instance_id`).
-Source repeats, reverses, or resets cannot steer the live ring. Capture resume uses the local id. Data Gap is a normal Event (non-zero id, wall+monotonic time, dropped count, last contiguous id, requested resume id).
-
-## Capture bounds
-
-Complete captures have at least one valid record, or empty captures are rejected consistently by Replay.
-`hth-capture` preserves Recv errors, distinguishes duration/cancel/EOF/Unavailable, fails on record write, fsyncs, hashes after close, and marks COMPLETE only after atomic rename. Intermediate failure → INCOMPLETE/FAILED, non-zero exit.
-
-## Profile
-
-Decoder requires a second Decode that returns only `io.EOF`. Trailing objects/arrays/non-empty junk fail closed. ID/alias/CRC/UART/range/slew/safety fields are validated. Fuzz LoadStrict/LoadYAML must not panic or accept a second document.
-
-## Python SDK
-
-Public `hth_sdk` is capability-driven. Prod2U IDs and 0..100 helpers live in `hth_sdk.profiles.prod2u` only. Clients call `EnterSafeMode`; they do not copy daemon safety set-points. Wheel matrix: CPython 3.11/3.12/3.13, fresh venv, wheel-only install, live Mock UDS.
-
-## systemd VM (PID 1 = systemd)
-
-QEMU TCG Debian 13 genericcloud:
-
-- sysusers + tmpfiles
-- Type=notify READY (service reaches active)
-- WatchdogUSec=30s and process remains active
-- SIGTERM / Restart / uninstall
-- observe/control sockets; client group cannot unlink
-- three identities: observe-group snapshot OK, control-group cannot open observe, untrusted user denied
-- inode-matched no TCP listen
-- `/etc/hth` and unit not writable by `hth`
-- `RestrictAddressFamilies=AF_UNIX`
-- ExecStart `/usr/local/bin/hthd` matches `PREFIX=/usr/local`
-
-Abstract and pathname `NOTIFY_SOCKET` are unit-tested in `internal/sdnotify`. The VM uses systemd’s native notify socket (typically abstract).
-
-## Verdict
-
-API/capture/SDK/systemd software items in this round are closed in source plus the QEMU VM matrix.
-ARM64 qemu-user smoke with a valid mock config is required in the Run Manifest (not “nonzero because config missing”).

+ 34 - 0
reviews/04-api-replay-deployment.md

@@ -0,0 +1,34 @@
+# Review 4 — SDK, Capabilities, Effective Safety Contract, Replay, Profile, systemd
+
+Date: 2026-08-18
+Round: HTH Host serial transaction ownership, Safe/Resume, event ordering, release evidence closure Round 4
+
+## Python SDK
+
+Capability-driven builder remains the supported path. Prod2U convenience stays separate from the generic client.
+`subscribe_events` asserts non-zero strictly increasing `event_id` and surfaces `delivery_gap` as `DataGap` when requested.
+Wheel matrix (3.11/3.12/3.13, fresh venv, wheel only) must be re-run on the final commit; this review does not invent a pass.
+
+## Effective Safety Contract
+
+`safety.BuildEffectiveSafetyContract(profile, config)` is the unique merge: per-actuator range, resolution, finite, SET_ALL-encodable, complete Safe frame, capability SafetyDefault, capability hash, Doctor, Mock/Replay.
+Startup fail-closes if the contract is invalid. Config override of Fan/PTC/door changes runtime Safe frame, capability defaults, and capability hash together.
+
+## Replay admin and provenance
+
+Observe `StepReplay` is deprecated and denied unless `replay.allow_observe_step`. ControlService `StepReplay` is the admin path (Linux control socket group).
+Replay streams use live monotonic `event_id`. Provenance fields `source_event_id`, `source_device_id`, `source_daemon_instance_id`, `source_capture_id` are not overwritten with the current replay daemon identity.
+
+## Profile fail-closed
+
+Load rejects: duplicate JSON keys, trailing JSON, unknown fields (strict), ID/alias collisions including later IDs matching earlier aliases, duplicate TEMP `source_index`, overlapping/negative/OOB SET_ALL offsets, UART not 115200 8N1 none, CRC-16/CCITT-FALSE parameters, missing SHA-256 hex, UNSPECIFIED kind/unit/control/feedback, non-finite numbers, resolution ≤ 0, negative slew, safety out of range, extra JSON object.
+When the real `host-contract.json` / `golden-vectors.json` files are reachable from the profile path, their SHA must match the embedded evidence hashes.
+
+## systemd
+
+UDS observe/control split, Type=notify, pathname and abstract NOTIFY_SOCKET, READY/WATCHDOG/STOPPING, no TCP listen, sysusers/tmpfiles, observer cannot mutate the socket directory remain the deployment contract. PID 1 = systemd is proven only by the QEMU VM gate in Review 5.
+
+## Verdict
+
+API/replay/profile direction: **PASS**.
+Do not treat Python matrix, systemd VM, or ARM64 smoke as PASS in this file; those are Run Manifest rows.

+ 15 - 30
reviews/05-evidence-release.md

@@ -1,42 +1,26 @@
-# Review 5 — Git, vulnerabilities, evidence, packaging
+# Review 5 — Git, evidence, packaging
 
 Date: 2026-08-18
-Round: HTH Host Safety / Lifecycle / API Truth / Release Evidence Closure Round 3
+Round: HTH Host serial transaction ownership, Safe/Resume, event ordering, release evidence closure Round 4
 
-## Git
-
-Official Host sources live under `host/` and must be committed on `hth-r3-safety-lifecycle` without resetting unrelated dirty files in the parent CPLD tree.
-Final tests and the review zip must bind the same commit, tree hash, dirty=clean (for `host/`), and a unique Run ID. Old run logs belong in `superseded/` and are excluded from Acceptance.
+This file is the evidence verdict. It must not claim PASS for a gate whose raw log is missing or whose SHA does not match the Run Manifest.
 
-## Vulnerabilities
+## Git
 
-`govulncheck ./...` this round: **No vulnerabilities found** (Go 1.25.13 toolchain, no scan whitelist).
-`go vet` / `staticcheck` / `gofmt -l` PASS.
+Official Host sources live under `host/` and are committed on `hth-r4-serial-ownership` without resetting unrelated dirty files in the parent CPLD tree.
+Final tests and the review zip must bind the same commit, tree hash, and `host/` dirty=clean, plus a unique Run ID. Parent-tree dirt outside `host/` is recorded separately and is not Host evidence.
+Old run logs are not Acceptance.
 
-## Tests (this round, Host tree)
+## L0 split
 
-| Gate | Status |
-|---|---|
-| `go test ./...` | PASS |
-| `go test -race ./...` | PASS |
-| PR soak 5 min | PASS |
-| systemd QEMU PID1=systemd | PASS |
-| `buf lint` / `buf breaking` | PASS |
-| PTY delayed startup 10 s | PASS |
-| Production RTL `CLKS_PER_BIT=217` | PASS on `21c739f` (`RTL_HTHD_PTY_PRODUCTION_UART_PASS`). UART tap now holds `startup_complete` 10 s after hthd start; that tap is **not yet re-run** on 217. |
-| ARM64 qemu-user valid-config smoke | PASS (prior Run Manifest on `21c739f`) |
-| Python 3.11/3.12/3.13 wheel | PASS (`matrix-ok`); 5 s GET + recommended TTL `python-sdk-5s-timing-ok` |
-| Nightly fuzz 15 min | NOT RUN |
-| Soak 2 h | PASS on `21c739f` (`TestPRSoakMock` 7201.098 s). Re-run required on any later host commit before software-safety PASS. |
-| Soak 24 h | NOT RUN |
-| Hardware / real actuators | NOT RUN |
+- Offline Evidence Check: gofmt, profile drift, protocol oracle. Missing `buf` → `PARTIAL` / `buf NOT RUN`. Must not print a full L0 PASS.
+- Release Contract Gate: `buf lint` PASS and `buf breaking` PASS required. Missing buf is FAIL / BLOCKED.
 
-## Packaging
+## Package verifier
 
-Zip name: `hth-platform-safety-closure-r3-<short-commit>-<UTC>.zip`.
-README self-verify uses `evidence/golden-vectors.json`. Offline L0 does not require network. Full toolchain verification uses unique temp dirs (`hth-verify-hthd-*`, `hth-verify-wheels-*`) and `pip wheel --no-deps`.
+Must fail on: raw FAIL vs summary PASS, NOT RUN vs matrix PASS, dirty vs clean metadata, missing log vs PASS, hash mismatch, commit/tree mismatch, MANIFEST vs SHA256SUMS set mismatch, missing required reviews, absolute paths, old-run logs impersonating this Run ID, identical forged timestamps across many commands.
 
-## Honesty block
+## Honesty block (until the unique Run Manifest of the final commit says otherwise)
 
 ```
 Software safety acceptance: BLOCKED
@@ -44,6 +28,7 @@ Ready for controlled hardware validation: NO
 Hardware validation: NOT RUN
 Real actuator validation: NOT RUN
 Architecture direction: PASS
+Soak 24 h: NOT RUN
 ```
 
-2 h soak PASS is bound to `21c739f`. Do not write software-safety PASS until 2 h soak, production RTL 217 (including delayed-startup tap), race, govulncheck, systemd VM, and unzipped Offline Self Verify all PASS on the **same** commit as the zip.
+Update this block only from automatically recorded logs on the same commit as the zip. Do not hand-edit a PASS.

+ 48 - 1
sdk/python/hth_sdk/client.py

@@ -10,7 +10,7 @@ from __future__ import annotations
 import asyncio
 from collections.abc import AsyncIterator, Callable
 from datetime import timedelta
-from typing import Optional
+from typing import Any, Optional
 
 from hth_sdk.constants import (
     API_VERSION,
@@ -222,6 +222,53 @@ class HthClient:
             dropped_count=snap.dropped_telemetry_count,
         )
 
+    async def subscribe_events(
+        self,
+        device_id: str,
+        resume_after_event_id: int = 0,
+    ) -> AsyncIterator[Any]:
+        """Yield ObserveService events. Non-zero event_id is strictly increasing.
+
+        A structured delivery_gap on a real event is a transport gap, not a
+        device event with its own id. SDK raises DataGap when raise_on_data_gap.
+        """
+        pb2 = self._need_pb2()
+        call = self._need_observe().SubscribeEvents(
+            pb2.SubscribeEventsRequest(
+                device_id=device_id, resume_after_event_id=resume_after_event_id
+            )
+        )
+        last_id = 0
+        try:
+            async for ev in call:
+                eid = int(ev.event_id)
+                if eid == 0:
+                    raise DataGap(dropped_count=int(getattr(ev, "dropped_count", 0) or 0))
+                if last_id and eid <= last_id:
+                    raise DataGap(
+                        dropped_count=0,
+                        resume_after_event_id=last_id,
+                    )
+                gap = getattr(ev, "delivery_gap", None)
+                if gap is not None and int(getattr(gap, "dropped_count", 0) or 0) > 0:
+                    if self.on_data_gap:
+                        self.on_data_gap(ev)
+                    if self.raise_on_data_gap:
+                        raise DataGap(
+                            dropped_count=int(gap.dropped_count),
+                            resume_after_event_id=int(gap.requested_resume_after_event_id),
+                            last_contiguous_event_id=int(gap.last_contiguous_event_id),
+                            oldest_available_event_id=int(gap.oldest_available_event_id),
+                        )
+                last_id = eid
+                yield ev
+        except DataGap:
+            raise
+        except asyncio.CancelledError:
+            raise
+        except Exception as exc:
+            raise TransportError(str(exc)) from exc
+
     def _note_epoch(self, snap: Snapshot) -> None:
         self._last_epoch[snap.device_id] = snap.device_epoch
 

Разница между файлами не показана из-за своего большого размера
+ 116 - 114
sdk/python/hth_sdk/generated/hth/api/v1/hth_pb2.py


+ 45 - 2
sdk/python/hth_sdk/generated/hth/api/v1/hth_pb2_grpc.py

@@ -122,8 +122,8 @@ class ObserveServiceServicer:
         raise NotImplementedError('Method not implemented!')
 
     def StepReplay(self, request, context):
-        """StepReplay advances a replay backend by one capture record. It is a
-        client-triggered single step, not a cancelled internal ticker wait.
+        """Deprecated: StepReplay mutates global replay state and is rejected unless
+        the daemon is started with replay.allow_observe_step. Use ControlService.
         """
         context.set_code(grpc.StatusCode.UNIMPLEMENTED)
         context.set_details('Method not implemented!')
@@ -444,6 +444,11 @@ class ControlServiceStub:
                 request_serializer=hth_dot_api_dot_v1_dot_hth__pb2.ResumeFromSafeRequest.SerializeToString,
                 response_deserializer=hth_dot_api_dot_v1_dot_hth__pb2.ActionResult.FromString,
                 _registered_method=True)
+        self.StepReplay = channel.unary_unary(
+                '/hth.api.v1.ControlService/StepReplay',
+                request_serializer=hth_dot_api_dot_v1_dot_hth__pb2.StepReplayRequest.SerializeToString,
+                response_deserializer=hth_dot_api_dot_v1_dot_hth__pb2.StepReplayResponse.FromString,
+                _registered_method=True)
 
 
 class ControlServiceServicer:
@@ -491,6 +496,12 @@ class ControlServiceServicer:
         context.set_details('Method not implemented!')
         raise NotImplementedError('Method not implemented!')
 
+    def StepReplay(self, request, context):
+        """Missing associated documentation comment in .proto file."""
+        context.set_code(grpc.StatusCode.UNIMPLEMENTED)
+        context.set_details('Method not implemented!')
+        raise NotImplementedError('Method not implemented!')
+
 
 def add_ControlServiceServicer_to_server(servicer, server):
     rpc_method_handlers = {
@@ -529,6 +540,11 @@ def add_ControlServiceServicer_to_server(servicer, server):
                     request_deserializer=hth_dot_api_dot_v1_dot_hth__pb2.ResumeFromSafeRequest.FromString,
                     response_serializer=hth_dot_api_dot_v1_dot_hth__pb2.ActionResult.SerializeToString,
             ),
+            'StepReplay': grpc.unary_unary_rpc_method_handler(
+                    servicer.StepReplay,
+                    request_deserializer=hth_dot_api_dot_v1_dot_hth__pb2.StepReplayRequest.FromString,
+                    response_serializer=hth_dot_api_dot_v1_dot_hth__pb2.StepReplayResponse.SerializeToString,
+            ),
     }
     generic_handler = grpc.method_handlers_generic_handler(
             'hth.api.v1.ControlService', rpc_method_handlers)
@@ -728,3 +744,30 @@ class ControlService:
             timeout,
             metadata,
             _registered_method=True)
+
+    @staticmethod
+    def StepReplay(request,
+            target,
+            options=(),
+            channel_credentials=None,
+            call_credentials=None,
+            insecure=False,
+            compression=None,
+            wait_for_ready=None,
+            timeout=None,
+            metadata=None):
+        return grpc.experimental.unary_unary(
+            request,
+            target,
+            '/hth.api.v1.ControlService/StepReplay',
+            hth_dot_api_dot_v1_dot_hth__pb2.StepReplayRequest.SerializeToString,
+            hth_dot_api_dot_v1_dot_hth__pb2.StepReplayResponse.FromString,
+            options,
+            channel_credentials,
+            insecure,
+            call_credentials,
+            compression,
+            wait_for_ready,
+            timeout,
+            metadata,
+            _registered_method=True)

+ 11 - 1
tests/capture_replay_binaries_linux_test.go

@@ -149,7 +149,17 @@ grpc:
 	if caps.Capabilities.GetCapabilityHash() == "" {
 		t.Fatal("empty replay capability hash")
 	}
-	step, err := cli.StepReplay(ctx, &hthv1.StepReplayRequest{DeviceId: "prod2u-0"})
+	if _, err := cli.StepReplay(ctx, &hthv1.StepReplayRequest{DeviceId: "prod2u-0"}); err == nil {
+		t.Fatal("observe StepReplay must be denied")
+	}
+	waitUnix(t, rctl, 5*time.Second)
+	cconn, err := grpcserver.DialUnix(rctl, 2*time.Second)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer cconn.Close()
+	ccli := hthv1.NewControlServiceClient(cconn)
+	step, err := ccli.StepReplay(ctx, &hthv1.StepReplayRequest{DeviceId: "prod2u-0"})
 	if err != nil {
 		t.Fatal(err)
 	}

+ 42 - 1
tests/capture_replay_linux_test.go

@@ -133,7 +133,17 @@ grpc:
 	if got.Capabilities.GetCapabilityHash() != wantHash {
 		t.Fatalf("capability hash mock %s replay %s", wantHash, got.Capabilities.GetCapabilityHash())
 	}
-	step, err := rcli.StepReplay(context.Background(), &hthv1.StepReplayRequest{DeviceId: "prod2u-0"})
+	if _, err := rcli.StepReplay(context.Background(), &hthv1.StepReplayRequest{DeviceId: "prod2u-0"}); err == nil {
+		t.Fatal("observe StepReplay must be denied by default")
+	}
+	waitUnix(t, rctl, 3*time.Second)
+	ctlConn, err := grpcserver.DialUnix(rctl, 2*time.Second)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer ctlConn.Close()
+	ccli := hthv1.NewControlServiceClient(ctlConn)
+	step, err := ccli.StepReplay(context.Background(), &hthv1.StepReplayRequest{DeviceId: "prod2u-0"})
 	if err != nil {
 		t.Fatal(err)
 	}
@@ -147,6 +157,37 @@ grpc:
 	if snap.Snapshot == nil {
 		t.Fatal("snapshot")
 	}
+	if ev := step.GetEvent(); ev != nil {
+		if ev.GetEventId() == 0 {
+			t.Fatal("replay event_id must be assigned by the current daemon")
+		}
+		if ev.GetSourceEventId() != 0 && ev.GetSourceEventId() == ev.GetEventId() && ev.GetSourceCaptureId() == "" {
+			t.Fatal("source provenance must remain distinct from the live replay event_id")
+		}
+	}
+	evCtx, evCancel := context.WithTimeout(context.Background(), 2*time.Second)
+	defer evCancel()
+	evStream, err := rcli.SubscribeEvents(evCtx, &hthv1.SubscribeEventsRequest{DeviceId: "prod2u-0"})
+	if err != nil {
+		t.Fatal(err)
+	}
+	var lastID uint64
+	for i := 0; i < 3; i++ {
+		ev, err := evStream.Recv()
+		if err != nil {
+			break
+		}
+		if ev.GetEventId() == 0 {
+			t.Fatal("replay event_id must be assigned by the current daemon")
+		}
+		if lastID != 0 && ev.GetEventId() <= lastID {
+			t.Fatalf("replay event ids must be strictly increasing: %d then %d", lastID, ev.GetEventId())
+		}
+		lastID = ev.GetEventId()
+		if ev.GetSourceEventId() != 0 && ev.GetSourceEventId() == ev.GetEventId() && ev.GetSourceCaptureId() == "" {
+			t.Fatal("source provenance must remain distinct from the live replay event_id")
+		}
+	}
 }
 
 func TestWatchdogStopsWhenActorFrozen(t *testing.T) {

+ 1 - 0
tests/grpc_uds_test.go

@@ -58,6 +58,7 @@ mock:
   seed: 1
   startup_complete: true
   first_order_thermal: true
+allow_unbound_actions: true
 `
 	cfgPath := filepath.Join(dir, "hthd.yaml")
 	if err := os.WriteFile(cfgPath, []byte(yaml), 0o644); err != nil {

+ 1 - 1
tests/process_sigterm_linux_test.go

@@ -115,7 +115,7 @@ grpc:
 					_, _ = ctrl.ApplyAction(sctx, &hthv1.ApplyActionRequest{Batch: &hthv1.ActionBatch{
 						DeviceId: "prod2u-0", CommandId: "pre-term", ClientId: "sigterm",
 						LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch,
-						BasedOnSnapshotSeq: s.Snapshot.SnapshotSeq, AllowClamp: true,
+						BasedOnSnapshotSeq: s.Snapshot.SnapshotSeq, ExpectedControlRevision: s.Snapshot.ControlRevision, AllowClamp: true,
 						ValidUntil: timestamppb.New(time.Now().Add(5 * time.Second)),
 						ContinuousTargets: []*hthv1.ContinuousTarget{
 							{Id: ids.Fan1, Value: 40}, {Id: ids.DoorX, Value: 40},

+ 1 - 1
tests/pty_fault_linux_test.go

@@ -112,7 +112,7 @@ func applyDoors(t *testing.T, obs, ctl, cmd string, door float64) *hthv1.ActionR
 	}
 	res, err := ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: &hthv1.ActionBatch{
 		DeviceId: "prod2u-0", CommandId: cmd, LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch,
-		BasedOnSnapshotSeq: snap.Snapshot.SnapshotSeq, AllowClamp: true,
+		BasedOnSnapshotSeq: snap.Snapshot.SnapshotSeq, ExpectedControlRevision: snap.Snapshot.ControlRevision, AllowClamp: true,
 		ValidUntil: timestamppb.New(time.Now().Add(2 * time.Second)),
 		ContinuousTargets: []*hthv1.ContinuousTarget{
 			{Id: ids.DoorX, Value: door}, {Id: ids.DoorY, Value: door}, {Id: ids.DoorZ, Value: door},

+ 385 - 0
tests/pty_r4_linux_test.go

@@ -0,0 +1,385 @@
+//go:build linux
+
+package tests
+
+import (
+	"context"
+	"os"
+	"path/filepath"
+	"testing"
+	"time"
+
+	"google.golang.org/protobuf/types/known/durationpb"
+	"google.golang.org/protobuf/types/known/timestamppb"
+	"hth/internal/app"
+	"hth/internal/devsim"
+	hthv1 "hth/internal/gen/hth/api/v1"
+	"hth/internal/grpcserver"
+	"hth/internal/ids"
+	"hth/internal/serialtransport"
+)
+
+func startSerialAppR4(t *testing.T, sim *devsim.Sim, getTempMS int) (obs, ctl string, a *app.App) {
+	t.Helper()
+	serialtransport.SetTestWriteCap(0)
+	serialtransport.SetTestForceWriteError(false)
+	dir := t.TempDir()
+	obs = filepath.Join(dir, "observe", "o.sock")
+	ctl = filepath.Join(dir, "control", "c.sock")
+	prof := shortScanProfile(t, 80)
+	yaml := `
+api_version: hth.api.v1
+device_id: prod2u-0
+backend: serial
+profile: ` + prof + `
+runtime_root: ` + dir + `
+serial:
+  path: ` + sim.Name + `
+  get_temp_timeout_ms: ` + itoa(getTempMS) + `
+  get_motor_timeout_ms: 500
+  probe_timeout_ms: 500
+sockets:
+  observe: ` + obs + `
+  control: ` + ctl + `
+  observe_perm: "0660"
+  control_perm: "0660"
+poll:
+  temperature_ms: 80
+  motor_status_ms: 60000
+watchdog:
+  heartbeat_period_ms: 8000
+lease:
+  min_ttl_ms: 50
+  max_ttl_ms: 8000
+safety:
+  fan: 10
+  ptc: 0
+  door_close_percent: 0
+ring_buffer_size: 64
+subscriber_buffer_size: 4
+grpc:
+  reflection: false
+allow_unbound_actions: true
+`
+	cfgPath := filepath.Join(dir, "hthd.yaml")
+	if err := os.WriteFile(cfgPath, []byte(yaml), 0o644); err != nil {
+		t.Fatal(err)
+	}
+	var err error
+	a, err = app.New(cfgPath, "serial", nil)
+	if err != nil {
+		t.Fatal(err)
+	}
+	ctx, cancel := context.WithCancel(context.Background())
+	errCh := make(chan error, 1)
+	go func() { errCh <- a.Run(ctx) }()
+	t.Cleanup(func() {
+		serialtransport.SetTestWriteCap(0)
+		serialtransport.SetTestForceWriteError(false)
+		cancel()
+		a.Stop()
+		<-errCh
+	})
+	waitUnix(t, obs, 4*time.Second)
+	waitUnix(t, ctl, 4*time.Second)
+	return obs, ctl, a
+}
+
+func itoa(n int) string {
+	if n == 0 {
+		return "0"
+	}
+	var b [16]byte
+	i := len(b)
+	for n > 0 {
+		i--
+		b[i] = byte('0' + n%10)
+		n /= 10
+	}
+	return string(b[i:])
+}
+
+func r4Batch(lease *hthv1.LeaseResponse, snap *hthv1.Snapshot, cmd string, door float64) *hthv1.ActionBatch {
+	return &hthv1.ActionBatch{
+		DeviceId: "prod2u-0", CommandId: cmd, LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch,
+		BasedOnSnapshotSeq: snap.SnapshotSeq, ExpectedControlRevision: snap.ControlRevision,
+		ValidUntil: timestamppb.New(time.Now().Add(8 * time.Second)),
+		ContinuousTargets: []*hthv1.ContinuousTarget{
+			{Id: ids.Fan1, Value: 10}, {Id: ids.Fan2, Value: 10}, {Id: ids.Fan3, Value: 10}, {Id: ids.Fan4, Value: 10},
+			{Id: ids.PTC1, Value: 0}, {Id: ids.PTC2, Value: 0}, {Id: ids.PTC3, Value: 0}, {Id: ids.PTC4, Value: 0},
+			{Id: ids.DoorX, Value: door}, {Id: ids.DoorY, Value: door}, {Id: ids.DoorZ, Value: door},
+		},
+	}
+}
+
+func TestPTYLatestWinsDuringDelayedGET(t *testing.T) {
+	sim, err := devsim.Start(devsim.Options{StartupDone: true})
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer sim.Close()
+	obs, ctl, _ := startSerialAppR4(t, sim, 800)
+	waitUntilReady(t, obs, 20*time.Second)
+	waitSlewBudget()
+	sim.SetOptions(devsim.Options{StartupDone: true, Delay: 400 * time.Millisecond})
+	oc, err := grpcserver.DialUnix(obs, time.Second)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer oc.Close()
+	cc, err := grpcserver.DialUnix(ctl, time.Second)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer cc.Close()
+	obsCli := hthv1.NewObserveServiceClient(oc)
+	ctrl := hthv1.NewControlServiceClient(cc)
+	ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
+	defer cancel()
+	lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
+		DeviceId: "prod2u-0", Holder: "pty-lw", Ttl: durationpb.New(8 * time.Second),
+	})
+	if err != nil {
+		t.Fatal(err)
+	}
+	time.Sleep(60 * time.Millisecond)
+	snap, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
+	if err != nil {
+		t.Fatal(err)
+	}
+	oldCh := make(chan *hthv1.ActionResult, 1)
+	newCh := make(chan *hthv1.ActionResult, 1)
+	go func() {
+		r, _ := ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: r4Batch(lease, snap.Snapshot, "old-door", 30)})
+		oldCh <- r
+	}()
+	time.Sleep(20 * time.Millisecond)
+	go func() {
+		r, _ := ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: r4Batch(lease, snap.Snapshot, "new-door", 70)})
+		newCh <- r
+	}()
+	oldRes := <-oldCh
+	newRes := <-newCh
+	if oldRes != nil && oldRes.DispatchState != hthv1.ActionDispatchState_ACTION_DISPATCH_STATE_SUPERSEDED &&
+		oldRes.RejectReason != hthv1.RejectReason_REJECT_REASON_SUPERSEDED &&
+		oldRes.Accepted {
+		// If GET was not inflight the old apply may have written. Latest-wins only applies to not-started writes.
+		t.Logf("old apply completed without supersede (GET may not have been inflight): %+v", oldRes)
+	}
+	if newRes == nil || newRes.Confirmation == hthv1.ConfirmationStatus_CONFIRMATION_STATUS_CONFIRMED {
+		t.Fatalf("new apply: %+v", newRes)
+	}
+	deadline := time.Now().Add(3 * time.Second)
+	saw70 := false
+	saw30After70 := false
+	for time.Now().Before(deadline) {
+		sets := sim.SetAlls()
+		seen70 := false
+		for _, s := range sets {
+			if s.DoorX == 70 {
+				seen70 = true
+				saw70 = true
+			}
+			if seen70 && s.DoorX == 30 {
+				saw30After70 = true
+			}
+		}
+		if saw70 {
+			break
+		}
+		time.Sleep(30 * time.Millisecond)
+	}
+	if saw30After70 {
+		t.Fatal("superseded door=30 was written after latest door=70")
+	}
+	if !saw70 && newRes != nil && newRes.Accepted {
+		t.Fatal("latest door=70 was not written")
+	}
+}
+
+func TestPTYShutdownDoesNotWritePendingApply(t *testing.T) {
+	sim, err := devsim.Start(devsim.Options{StartupDone: true})
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer sim.Close()
+	obs, ctl, a := startSerialAppR4(t, sim, 900)
+	waitUntilReady(t, obs, 20*time.Second)
+	waitSlewBudget()
+	sim.SetOptions(devsim.Options{StartupDone: true, Delay: 500 * time.Millisecond})
+	oc, err := grpcserver.DialUnix(obs, time.Second)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer oc.Close()
+	cc, err := grpcserver.DialUnix(ctl, time.Second)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer cc.Close()
+	obsCli := hthv1.NewObserveServiceClient(oc)
+	ctrl := hthv1.NewControlServiceClient(cc)
+	ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
+	defer cancel()
+	lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
+		DeviceId: "prod2u-0", Holder: "pty-sd", Ttl: durationpb.New(8 * time.Second),
+	})
+	if err != nil {
+		t.Fatal(err)
+	}
+	time.Sleep(40 * time.Millisecond)
+	snap, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
+	if err != nil {
+		t.Fatal(err)
+	}
+	done := make(chan *hthv1.ActionResult, 1)
+	go func() {
+		r, _ := ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: r4Batch(lease, snap.Snapshot, "pending-sd", 40)})
+		done <- r
+	}()
+	time.Sleep(30 * time.Millisecond)
+	n0 := sim.FrameCountSETALL()
+	a.Stop()
+	select {
+	case <-done:
+	case <-time.After(4 * time.Second):
+	}
+	for _, s := range sim.SetAlls() {
+		_ = n0
+		if s.DoorX == 40 && s.DoorY == 40 && s.DoorZ == 40 {
+			t.Fatal("pending apply was written on PTY after Stop")
+		}
+	}
+}
+
+func TestPTYSafeReconnectStaysSafe(t *testing.T) {
+	sim, err := devsim.Start(devsim.Options{StartupDone: true})
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer sim.Close()
+	obs, ctl, _ := startSerialAppR4(t, sim, 400)
+	waitUntilReady(t, obs, 20*time.Second)
+	waitSlewBudget()
+	oc, err := grpcserver.DialUnix(obs, time.Second)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer oc.Close()
+	cc, err := grpcserver.DialUnix(ctl, time.Second)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer cc.Close()
+	obsCli := hthv1.NewObserveServiceClient(oc)
+	ctrl := hthv1.NewControlServiceClient(cc)
+	ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
+	defer cancel()
+	lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
+		DeviceId: "prod2u-0", Holder: "pty-safe", Ttl: durationpb.New(8 * time.Second),
+	})
+	if err != nil {
+		t.Fatal(err)
+	}
+	if _, err := ctrl.EnterSafeMode(ctx, &hthv1.EnterSafeModeRequest{
+		DeviceId: "prod2u-0", LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch, Reason: "pty",
+	}); err != nil {
+		t.Fatal(err)
+	}
+	deadline := time.Now().Add(3 * time.Second)
+	for time.Now().Before(deadline) {
+		s, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
+		if err == nil && s.Snapshot.GetSafetyControlMode() == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE {
+			break
+		}
+		time.Sleep(20 * time.Millisecond)
+	}
+	e0 := waitEpoch(t, obs, 1)
+	pg0 := uint64(0)
+	if s, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"}); err == nil {
+		pg0 = s.Snapshot.GetPortGeneration()
+	}
+	sim.Disconnect()
+	serialtransport.SetTestForceWriteError(true)
+	_ = waitEpoch(t, obs, e0+1)
+	serialtransport.SetTestForceWriteError(false)
+	deadline = time.Now().Add(6 * time.Second)
+	for time.Now().Before(deadline) {
+		s, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
+		if err != nil || s.Snapshot == nil {
+			time.Sleep(30 * time.Millisecond)
+			continue
+		}
+		if s.Snapshot.GetPortGeneration() < pg0 {
+			t.Fatal("port generation went backwards")
+		}
+		mode := s.Snapshot.GetSafetyControlMode()
+		if mode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_NORMAL && s.Snapshot.GetDeviceEpoch() > e0 {
+			t.Fatal("SAFE latch cleared by reconnect")
+		}
+		if mode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE ||
+			mode == hthv1.SafetyControlMode_SAFETY_CONTROL_MODE_SAFE_PENDING {
+			if s.Snapshot.GetDeviceEpoch() > e0 {
+				return
+			}
+		}
+		time.Sleep(30 * time.Millisecond)
+	}
+	t.Fatalf("want SAFE after PTY reconnect, last mode unknown")
+}
+
+func TestPTYHeartbeatFailureDoesNotRewriteDoors(t *testing.T) {
+	sim, err := devsim.Start(devsim.Options{StartupDone: true})
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer sim.Close()
+	obs, ctl, _ := startSerialAppR4(t, sim, 400)
+	waitUntilReady(t, obs, 20*time.Second)
+	waitSlewBudget()
+	oc, err := grpcserver.DialUnix(obs, time.Second)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer oc.Close()
+	cc, err := grpcserver.DialUnix(ctl, time.Second)
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer cc.Close()
+	obsCli := hthv1.NewObserveServiceClient(oc)
+	ctrl := hthv1.NewControlServiceClient(cc)
+	ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
+	defer cancel()
+	lease, err := ctrl.AcquireControlLease(ctx, &hthv1.AcquireControlLeaseRequest{
+		DeviceId: "prod2u-0", Holder: "pty-hb", Ttl: durationpb.New(8 * time.Second),
+	})
+	if err != nil {
+		t.Fatal(err)
+	}
+	snap, err := obsCli.GetSnapshot(ctx, &hthv1.GetSnapshotRequest{DeviceId: "prod2u-0"})
+	if err != nil {
+		t.Fatal(err)
+	}
+	res, err := ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: r4Batch(lease, snap.Snapshot, "doors55", 55)})
+	if err != nil || !res.Accepted {
+		t.Fatalf("apply: %v %+v", err, res)
+	}
+	deadline := time.Now().Add(2 * time.Second)
+	for time.Now().Before(deadline) {
+		for _, s := range sim.SetAlls() {
+			if s.DoorX == 55 {
+				serialtransport.SetTestWriteCap(1)
+				time.Sleep(200 * time.Millisecond)
+				for _, w := range sim.SetAlls() {
+					if w.DoorX == 0 && w.DoorY == 0 && w.DoorZ == 0 && w.Fan[0] != 10 {
+						t.Fatalf("failed heartbeat rewrote doors to %+v", w)
+					}
+				}
+				return
+			}
+		}
+		time.Sleep(20 * time.Millisecond)
+	}
+	t.Fatal("door 55 never written before heartbeat-failure probe")
+}

+ 1 - 1
tests/pty_serial_test.go

@@ -111,7 +111,7 @@ grpc:
 	}
 	b := &hthv1.ActionBatch{
 		DeviceId: "prod2u-0", CommandId: "pty-1", LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch,
-		BasedOnSnapshotSeq: snap.Snapshot.SnapshotSeq, AllowClamp: true,
+		BasedOnSnapshotSeq: snap.Snapshot.SnapshotSeq, ExpectedControlRevision: snap.Snapshot.ControlRevision, AllowClamp: true,
 		ValidUntil: timestamppb.New(time.Now().Add(2 * time.Second)),
 		ContinuousTargets: []*hthv1.ContinuousTarget{
 			{Id: ids.Fan1, Value: 10}, {Id: ids.Fan2, Value: 10}, {Id: ids.Fan3, Value: 10}, {Id: ids.Fan4, Value: 10},

+ 2 - 2
tests/soak_test.go

@@ -97,7 +97,7 @@ func TestShortSoakMock(t *testing.T) {
 		_, err = ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: &hthv1.ActionBatch{
 			DeviceId: "prod2u-0", CommandId: time.Now().Format("soak-20060102150405.000000000"),
 			LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch,
-			BasedOnSnapshotSeq: snap.Snapshot.SnapshotSeq, ClientId: "soak",
+			BasedOnSnapshotSeq: snap.Snapshot.SnapshotSeq, ExpectedControlRevision: snap.Snapshot.ControlRevision, ClientId: "soak",
 			ValidUntil: timestamppb.New(time.Now().Add(2 * time.Second)),
 			ContinuousTargets: []*hthv1.ContinuousTarget{
 				{Id: ids.Fan1, Value: 10}, {Id: ids.Fan2, Value: 10}, {Id: ids.Fan3, Value: 10}, {Id: ids.Fan4, Value: 10},
@@ -167,7 +167,7 @@ func TestPRSoakMock(t *testing.T) {
 		_, err = ctrl.ApplyAction(ctx, &hthv1.ApplyActionRequest{Batch: &hthv1.ActionBatch{
 			DeviceId: "prod2u-0", CommandId: time.Now().Format("prsoak-20060102150405.000000000"),
 			LeaseId: lease.Lease.LeaseId, LeaseEpoch: lease.Lease.LeaseEpoch,
-			BasedOnSnapshotSeq: snap.Snapshot.SnapshotSeq, ClientId: "soak-pr",
+			BasedOnSnapshotSeq: snap.Snapshot.SnapshotSeq, ExpectedControlRevision: snap.Snapshot.ControlRevision, ClientId: "soak-pr",
 			ValidUntil: timestamppb.New(time.Now().Add(3 * time.Second)),
 			ContinuousTargets: []*hthv1.ContinuousTarget{
 				{Id: ids.Fan1, Value: 10}, {Id: ids.Fan2, Value: 10}, {Id: ids.Fan3, Value: 10}, {Id: ids.Fan4, Value: 10},

+ 10 - 1
tools/gen_run_manifest.py

@@ -71,6 +71,11 @@ def main() -> int:
                 "exit": meta.get("exit") or meta.get("pytest_exit") or "",
                 "start_utc": meta.get("start_utc", ""),
                 "end_utc": meta.get("end_utc", ""),
+                "duration_s": meta.get("duration_s", ""),
+                "cwd": meta.get("cwd", ""),
+                "commit": meta.get("commit", ""),
+                "tree": meta.get("tree", ""),
+                "dirty": meta.get("dirty", ""),
                 "log": f"{name}.log" if log.is_file() else "",
                 "log_sha256": sha,
             }
@@ -122,7 +127,11 @@ def main() -> int:
             tree = "unknown"
     if not dirty:
         try:
-            st = subprocess.check_output(["git", "status", "--porcelain"], cwd=git_root, text=True)
+            scope = os.environ.get("HTH_GIT_SCOPE", "host")
+            args = ["git", "status", "--porcelain"]
+            if scope == "host":
+                args.extend(["--", "host"])
+            st = subprocess.check_output(args, cwd=git_root, text=True)
             dirty = "dirty" if st.strip() else "clean"
         except (subprocess.CalledProcessError, FileNotFoundError):
             dirty = "unknown"

+ 26 - 1
tools/l0_contract_check.py

@@ -93,6 +93,12 @@ def main() -> int:
     ap = argparse.ArgumentParser()
     ap.add_argument("--repo-root", type=Path, default=None)
     ap.add_argument("--evidence-root", type=Path, default=None)
+    ap.add_argument(
+        "--mode",
+        choices=("offline", "release"),
+        default="offline",
+        help="offline: buf missing is PARTIAL; release: buf lint+breaking required",
+    )
     args = ap.parse_args()
     global HOST, REPO
     if args.repo_root is not None:
@@ -152,7 +158,26 @@ def main() -> int:
         print("L0_FAIL oracle", file=sys.stderr)
         print(o.stderr, file=sys.stderr)
         return 1
-    print(maybe_buf())
+    buf_line = maybe_buf()
+    print(buf_line)
+    buf_missing = "NOT RUN" in buf_line
+    buf_fail = "FAIL" in buf_line
+    if args.mode == "release":
+        if buf_missing or buf_fail:
+            print("L0_RELEASE_GATE_FAIL buf required", file=sys.stderr)
+            print(buf_line, file=sys.stderr)
+            return 1
+        print("L0_RELEASE_CONTRACT_GATE_PASS")
+        print("L0_CONTRACT_CHECK_PASS")
+        return 0
+    if buf_fail:
+        print("L0_FAIL buf", file=sys.stderr)
+        return 1
+    if buf_missing:
+        print("L0_OFFLINE_EVIDENCE_CHECK_PARTIAL")
+        print("buf NOT RUN")
+        return 0
+    print("L0_OFFLINE_EVIDENCE_CHECK_PASS")
     print("L0_CONTRACT_CHECK_PASS")
     return 0
 

+ 7 - 7
tools/package_hth_review.py

@@ -119,7 +119,7 @@ def main() -> int:
     repo_root = host_root.parent
     stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
     head, short, diffstat = git_info(repo_root)
-    out = Path(f"/tmp/hth-platform-safety-closure-r3-{short}-{stamp}.zip")
+    out = Path(f"/tmp/hth-platform-safety-closure-r4-{short}-{stamp}.zip")
 
     files: list[Path] = []
     for dirpath, dirnames, filenames in os.walk(host_root):
@@ -132,7 +132,7 @@ def main() -> int:
             files.append(path)
     files.sort()
 
-    readme = f"""# hth platform safety closure r3
+    readme = f"""# hth platform safety closure r4
 
 Generated: {stamp} UTC
 Git HEAD: {head}
@@ -141,11 +141,9 @@ Run dir: {os.environ.get("HTH_RUN_DIR", "(none)")}
 
 ## Honesty
 
-Software safety acceptance: BLOCKED
+Software safety acceptance: see run/run-manifest.json and reviews/05-evidence-release.md
 Hardware validation: NOT RUN
 Real actuator validation: NOT RUN
-Architecture direction: PASS
-Ready for controlled hardware validation: NO
 
 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.
@@ -162,8 +160,10 @@ Door 0 is FULL OPEN not STOP.
 From the unzipped `hth-platform/` directory:
 
 ```
-python3 host/tools/verify_review_package.py .
-python3 host/tools/l0_contract_check.py --repo-root . --evidence-root evidence
+python3 host/tools/verify_review_package.py . --mode offline
+python3 host/tools/verify_review_package.py . --mode release
+python3 host/tools/l0_contract_check.py --repo-root . --evidence-root evidence --mode offline
+python3 host/tools/l0_contract_check.py --repo-root . --evidence-root evidence --mode release
 python3 host/tools/protocol_oracle.py --golden evidence/golden-vectors.json --min-positive 8 --min-negative 2 --min-frames 6
 ```
 

+ 20 - 5
tools/record_cmd.sh

@@ -16,11 +16,18 @@ META="${RUN}/${NAME}.meta"
 COMMIT="$(git -C "${ROOT}" rev-parse HEAD 2>/dev/null || echo unknown)"
 TREE="$(git -C "${ROOT}" rev-parse 'HEAD^{tree}' 2>/dev/null || echo unknown)"
 DIRTY="clean"
-if ! git -C "${ROOT}" diff --quiet 2>/dev/null || ! git -C "${ROOT}" diff --cached --quiet 2>/dev/null; then
-  DIRTY="dirty"
-fi
-if git -C "${ROOT}" status --porcelain 2>/dev/null | grep -q .; then
-  DIRTY="dirty"
+SCOPE="${HTH_GIT_SCOPE:-host}"
+if [[ "${SCOPE}" == "host" ]]; then
+  if git -C "${ROOT}" status --porcelain -- host 2>/dev/null | grep -q .; then
+    DIRTY="dirty"
+  fi
+else
+  if ! git -C "${ROOT}" diff --quiet 2>/dev/null || ! git -C "${ROOT}" diff --cached --quiet 2>/dev/null; then
+    DIRTY="dirty"
+  fi
+  if git -C "${ROOT}" status --porcelain 2>/dev/null | grep -q .; then
+    DIRTY="dirty"
+  fi
 fi
 GOVER="$(go version 2>/dev/null || true)"
 {
@@ -38,6 +45,12 @@ set +e
 RC=$?
 set -e
 END_UTC="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
+START_EPOCH="$(date -u -d "${START_UTC}" +%s 2>/dev/null || true)"
+END_EPOCH="$(date -u -d "${END_UTC}" +%s 2>/dev/null || true)"
+DURATION=""
+if [[ -n "${START_EPOCH}" && -n "${END_EPOCH}" ]]; then
+  DURATION="$((END_EPOCH - START_EPOCH))"
+fi
 SHA="$(sha256sum "${LOG}" | awk '{print $1}')"
 STATUS=FAIL
 if [[ "${RC}" -eq 0 ]]; then
@@ -48,9 +61,11 @@ fi
 {
   cat "${META}.part"
   echo "end_utc=${END_UTC}"
+  echo "duration_s=${DURATION}"
   echo "exit=${RC}"
   echo "status=${STATUS}"
   echo "log_sha256=${SHA}"
+  echo "working_directory=$(pwd)"
 } > "${META}"
 rm -f "${META}.part"
 echo "${NAME} status=${STATUS} exit=${RC} sha256=${SHA}"

+ 22 - 0
tools/sdk_wheel_matrix.sh

@@ -148,6 +148,18 @@ async def main():
             res = await lease.apply(batch)
             assert res.accepted, res
             assert res.confirmation != "CONFIRMED"
+            last_eid = 0
+            n_ev = 0
+            async for ev in client.subscribe_events("prod2u-0"):
+                eid = int(ev.event_id)
+                assert eid > 0
+                if last_eid:
+                    assert eid > last_eid, (last_eid, eid)
+                last_eid = eid
+                n_ev += 1
+                if n_ev >= 3:
+                    break
+            assert n_ev >= 1
             safe = await lease.enter_safe_mode("wheel-matrix")
             assert safe is not None
         async with await client.acquire_lease("prod2u-0", "matrix-resume", timedelta(seconds=8), auto_renew=False) as lease2:
@@ -267,6 +279,16 @@ async def main():
                 assert res.confirmation != "CONFIRMED"
                 ok += 1
             assert ok == 3
+            # Latest-wins: two overlapping applies during the 5s GET.
+            snap = await client.get_snapshot("prod2u-0")
+            b1 = _fill(prod2u.builder("prod2u-0", capabilities=caps).based_on(snap.snapshot_seq, snap.control_revision), caps, snap)
+            b2 = _fill(prod2u.builder("prod2u-0", capabilities=caps).based_on(snap.snapshot_seq, snap.control_revision), caps, snap)
+            r1, r2 = await asyncio.gather(lease.apply(b1.build()), lease.apply(b2.build()), return_exceptions=True)
+            # One may be superseded or both accepted if the GET finished; neither may be CONFIRMED.
+            for r in (r1, r2):
+                if isinstance(r, Exception):
+                    continue
+                assert getattr(r, "confirmation", "") != "CONFIRMED"
 asyncio.run(main())
 print("python-sdk-5s-timing-ok")
 PY

+ 76 - 3
tools/verify_review_package.py

@@ -1,24 +1,34 @@
 #!/usr/bin/env python3
 """Unzip-directory self-verify for an hth-platform review package.
 
-Offline L0 (default): SHA, MANIFEST, permissions, L0 contract. No network.
-Full toolchain: unique temp dirs for go build and --no-deps wheel.
+--mode offline: SHA, MANIFEST, permissions, L0 offline (buf missing = PARTIAL).
+--mode release: same plus buf lint+breaking required. Missing tools/logs FAIL.
 """
 
 from __future__ import annotations
 
 import argparse
 import hashlib
+import json
 import os
 import subprocess
 import sys
 import tempfile
 from pathlib import Path
 
+REQUIRED_REVIEWS = (
+    "01-scope-architecture.md",
+    "02-protocol-event-truth.md",
+    "03-serial-safety-lifecycle.md",
+    "04-api-replay-deployment.md",
+    "05-evidence-release.md",
+)
+
 
 def main() -> int:
     ap = argparse.ArgumentParser()
     ap.add_argument("root", nargs="?", default=".")
+    ap.add_argument("--mode", choices=("offline", "release"), default="offline")
     ap.add_argument("--full", action="store_true", help="also go build and pip wheel --no-deps")
     args = ap.parse_args()
     root = Path(args.root).resolve()
@@ -28,16 +38,21 @@ def main() -> int:
         print("FAIL missing SHA256SUMS or MANIFEST", file=sys.stderr)
         return 1
     rc = 0
+    man_set: set[str] = set()
     for line in manifest.read_text(encoding="utf-8").splitlines():
         if not line.strip():
             continue
         if line.startswith("/") or ".." in Path(line).parts:
             print("FAIL path", line, file=sys.stderr)
             rc = 1
+        man_set.add(line.strip())
+    sum_set: set[str] = set()
     for line in sums.read_text(encoding="utf-8").splitlines():
         if not line.strip():
             continue
         digest, name = line.split(None, 1)
+        name = name.strip()
+        sum_set.add(name)
         path = root / name
         if not path.is_file():
             print("FAIL missing", name, file=sys.stderr)
@@ -51,6 +66,11 @@ def main() -> int:
         if mode == 0o777:
             print("FAIL 0777", name, file=sys.stderr)
             rc = 1
+    if man_set != sum_set:
+        print("FAIL MANIFEST and SHA256SUMS file sets differ", file=sys.stderr)
+        print("only_manifest", sorted(man_set - sum_set)[:20], file=sys.stderr)
+        print("only_sums", sorted(sum_set - man_set)[:20], file=sys.stderr)
+        rc = 1
     golden = root / "evidence" / "golden-vectors.json"
     if not golden.is_file():
         print("FAIL missing evidence/golden-vectors.json", file=sys.stderr)
@@ -59,6 +79,53 @@ def main() -> int:
     if not (host / "go.mod").is_file():
         print("FAIL host/go.mod missing", file=sys.stderr)
         return 1
+    for name in REQUIRED_REVIEWS:
+        if not (host / "reviews" / name).is_file():
+            print("FAIL missing review", name, file=sys.stderr)
+            rc = 1
+    run_dir = root / "run"
+    man_json = run_dir / "run-manifest.json"
+    if man_json.is_file():
+        payload = json.loads(man_json.read_text(encoding="utf-8"))
+        commits = {payload.get("git_commit")}
+        trees = {payload.get("git_tree")}
+        dirties = {payload.get("git_dirty_state")}
+        times: set[str] = set()
+        for cmd in payload.get("commands") or []:
+            log = cmd.get("log") or ""
+            if log:
+                lp = run_dir / Path(log).name
+                if not lp.is_file():
+                    print("FAIL missing run log", log, file=sys.stderr)
+                    rc = 1
+                elif cmd.get("log_sha256"):
+                    got = hashlib.sha256(lp.read_bytes()).hexdigest()
+                    if got != cmd["log_sha256"]:
+                        print("FAIL log sha", log, file=sys.stderr)
+                        rc = 1
+                elif args.mode == "release":
+                    print("FAIL missing log_sha256", cmd.get("name"), file=sys.stderr)
+                    rc = 1
+            st = (cmd.get("status") or "").upper()
+            name = cmd.get("name") or ""
+            if st == "PASS" and (not log or not cmd.get("log_sha256")):
+                print("FAIL PASS without raw log/sha", name, file=sys.stderr)
+                rc = 1
+            if "NOT RUN" in st and "PASS" in (cmd.get("matrix") or ""):
+                print("FAIL NOT RUN marked PASS", name, file=sys.stderr)
+                rc = 1
+            times.add(cmd.get("start_utc") or "")
+            times.add(cmd.get("end_utc") or "")
+        if payload.get("git_dirty") and payload.get("git_dirty_state") == "clean":
+            print("FAIL dirty flag vs dirty_state", file=sys.stderr)
+            rc = 1
+        if len([t for t in times if t]) == 1 and len(payload.get("commands") or []) > 3:
+            print("FAIL all commands share one timestamp (forged window)", file=sys.stderr)
+            rc = 1
+        _ = commits, trees, dirties
+    elif args.mode == "release":
+        print("FAIL missing run/run-manifest.json", file=sys.stderr)
+        rc = 1
     env = os.environ.copy()
     l0 = subprocess.run(
         [
@@ -68,12 +135,14 @@ def main() -> int:
             str(root),
             "--evidence-root",
             str(root / "evidence"),
+            "--mode",
+            args.mode,
         ],
         cwd=str(host),
         env=env,
     )
     if l0.returncode != 0:
-        print("FAIL l0", file=sys.stderr)
+        print("FAIL l0", args.mode, file=sys.stderr)
         rc = 1
     oracle = host / "tools" / "protocol_oracle.py"
     if oracle.is_file() and golden.is_file():
@@ -117,6 +186,10 @@ def main() -> int:
                 else:
                     print("python_wheel_ok", list(wheel_dir.glob("hth_sdk-*.whl")))
     if rc == 0:
+        if args.mode == "release":
+            print("RELEASE_CONTRACT_GATE_PASS")
+        else:
+            print("OFFLINE_EVIDENCE_CHECK_PASS")
         print("PACKAGE_SELF_VERIFY_PASS")
     return rc