# State Manager (STM) Component Specification

**Component ID:** COMP-STM  
**Version:** 1.0  
**Date:** 2025-01-19  
**Location:** `application_layer/business_stack/STM/`

## 1. Purpose

The State Manager (STM) component implements the system finite state machine (FSM) as defined in the System State Machine Specification. It manages system operational states, enforces valid state transitions, coordinates teardown sequences, and notifies components of state changes.

## 2. Responsibilities

### 2.1 Primary Responsibilities

- Implement system FSM with 11 states (INIT, BOOT_FAILURE, RUNNING, WARNING, FAULT, OTA_PREP, OTA_UPDATE, MC_UPDATE, TEARDOWN, SERVICE, SD_DEGRADED)
- Enforce valid state transitions according to transition table
- Coordinate controlled teardown sequences
- Notify registered components of state changes via Event System
- Provide state query interface for components

### 2.2 Non-Responsibilities

- Feature logic (sensor acquisition, communication, etc.)
- Hardware access (delegated to drivers)
- Fault detection (delegated to Error Handler)
- Diagnostic logging (delegated to Diagnostics Task)

## 3. Public API

### 3.1 State Query Functions

```c
/**
 * @brief Get current system state
 * @return Current system state
 */
system_state_t stm_getCurrentState(void);

/**
 * @brief Check if a state is valid
 * @param state State to validate
 * @return true if state is valid, false otherwise
 */
bool stm_isStateValid(system_state_t state);

/**
 * @brief Check if system is in a specific state
 * @param state State to check
 * @return true if current state matches, false otherwise
 */
bool stm_isInState(system_state_t state);
```

### 3.2 State Transition Functions

```c
/**
 * @brief Request a state transition
 * @param target_state Target state
 * @param reason Transition reason
 * @return true if transition initiated, false if rejected
 */
bool stm_requestTransition(system_state_t target_state, transition_reason_t reason);

/**
 * @brief Validate if a state transition is allowed
 * @param from Source state
 * @param to Target state
 * @return true if transition is valid, false otherwise
 */
bool stm_validateTransition(system_state_t target_state, transition_reason_t reason);

/**
 * @brief Get transition reason for last transition
 * @return Transition reason
 */
transition_reason_t stm_getLastTransitionReason(void);
```

### 3.3 Teardown Functions

```c
/**
 * @brief Initiate controlled teardown sequence
 * @param reason Teardown reason
 * @return true if teardown initiated, false if rejected
 */
bool stm_initiateTeardown(teardown_reason_t reason);

/**
 * @brief Check if teardown is complete
 * @return true if teardown complete, false otherwise
 */
bool stm_isTeardownComplete(void);

/**
 * @brief Get teardown progress (0-100%)
 * @return Teardown progress percentage
 */
uint8_t stm_getTeardownProgress(void);
```

### 3.4 Component Registration

```c
/**
 * @brief State listener callback type
 * @param old_state Previous state
 * @param new_state New state
 * @param reason Transition reason
 */
typedef void (*state_listener_t)(system_state_t old_state, system_state_t new_state, transition_reason_t reason);

/**
 * @brief Register a state change listener
 * @param listener Callback function
 * @return true if registered, false on error
 */
bool stm_registerStateListener(state_listener_t listener);

/**
 * @brief Unregister a state change listener
 * @param listener Callback function to remove
 * @return true if unregistered, false if not found
 */
bool stm_unregisterStateListener(state_listener_t listener);
```

## 4. Data Types

### 4.1 System States

```c
typedef enum {
    SYSTEM_STATE_INIT = 0,
    SYSTEM_STATE_BOOT_FAILURE,
    SYSTEM_STATE_RUNNING,
    SYSTEM_STATE_WARNING,
    SYSTEM_STATE_FAULT,
    SYSTEM_STATE_OTA_PREP,
    SYSTEM_STATE_OTA_UPDATE,
    SYSTEM_STATE_MC_UPDATE,
    SYSTEM_STATE_TEARDOWN,
    SYSTEM_STATE_SERVICE,
    SYSTEM_STATE_SD_DEGRADED,
    SYSTEM_STATE_COUNT
} system_state_t;
```

### 4.2 Transition Reasons

```c
typedef enum {
    TRANSITION_REASON_INIT_SUCCESS,
    TRANSITION_REASON_SECURE_BOOT_FAIL,
    TRANSITION_REASON_NON_FATAL_FAULT,
    TRANSITION_REASON_FATAL_FAULT,
    TRANSITION_REASON_FAULT_CLEARED,
    TRANSITION_REASON_FAULT_ESCALATED,
    TRANSITION_REASON_OTA_REQUEST,
    TRANSITION_REASON_MC_UPDATE_REQUEST,
    TRANSITION_REASON_DEBUG_SESSION,
    TRANSITION_REASON_SD_FAILURE,
    TRANSITION_REASON_SD_RECOVERED,
    TRANSITION_REASON_RECOVERY_ATTEMPT,
    TRANSITION_REASON_MANUAL_RESET,
    TRANSITION_REASON_OTA_READY,
    TRANSITION_REASON_OTA_REJECTED,
    TRANSITION_REASON_TEARDOWN_COMPLETE,
    TRANSITION_REASON_OTA_SUCCESS,
    TRANSITION_REASON_OTA_FAILURE,
    TRANSITION_REASON_MC_UPDATE_COMPLETE,
    TRANSITION_REASON_SESSION_CLOSED,
    TRANSITION_REASON_MANUAL_INTERVENTION
} transition_reason_t;
```

### 4.3 Teardown Reasons

```c
typedef enum {
    TEARDOWN_REASON_OTA,
    TEARDOWN_REASON_MC_UPDATE,
    TEARDOWN_REASON_FATAL_FAULT,
    TEARDOWN_REASON_MANUAL_COMMAND,
    TEARDOWN_REASON_SYSTEM_RESET
} teardown_reason_t;
```

## 5. Threading Model

- **Owner Task:** System Management Task (HIGH priority)
- **Thread Safety:** Thread-safe (protected by mutex for state transitions)
- **Blocking Operations:** None (all operations are non-blocking)
- **ISR Access:** State queries allowed from ISR (read-only, lock-free)

## 6. Resource Ownership

- **State Machine State:** Owned exclusively by STM component
- **State Transition Lock:** Mutex-protected (prevents concurrent transitions)
- **State Listeners:** List maintained by STM (protected by mutex)

## 7. Error Model

### 7.1 Error Conditions

| Error | Condition | Response |
|-------|-----------|----------|
| `STM_ERR_INVALID_STATE` | Invalid state parameter | Return false, log warning |
| `STM_ERR_INVALID_TRANSITION` | Invalid transition requested | Return false, log warning |
| `STM_ERR_TEARDOWN_IN_PROGRESS` | Teardown already in progress | Return false, log info |
| `STM_ERR_LISTENER_FULL` | Too many listeners registered | Return false, log error |

### 7.2 Diagnostics Emitted

- `DIAG-SY-STM-0001`: Invalid state transition attempted (WARNING)
- `DIAG-SY-STM-0002`: State transition timeout (ERROR)
- `DIAG-SY-STM-0003`: Teardown sequence failure (FATAL)

## 8. State-Dependent Behavior

### 8.1 INIT State

- **Allowed Operations:** State queries, listener registration
- **Forbidden Operations:** State transitions (except to RUNNING or BOOT_FAILURE)
- **Duration:** Bounded (max 5 seconds)

### 8.2 RUNNING State

- **Allowed Operations:** All operations
- **Forbidden Operations:** None
- **Duration:** Indefinite (normal operation)

### 8.3 TEARDOWN State

- **Allowed Operations:** State queries, teardown progress queries
- **Forbidden Operations:** New state transitions (except completion transitions)
- **Duration:** Bounded (max 500ms)

## 9. Dependencies

### 9.1 Required Components

- **Event System:** For state change notifications
- **Error Handler:** For fault-triggered transitions
- **Persistence:** For data flush during teardown
- **Logger:** For diagnostic logging

### 9.2 Required Interfaces

- Event System publish interface
- Persistence flush interface
- Logger interface

## 10. Acceptance Tests

### 10.1 State Transition Tests

- **T-STM-001:** Valid state transitions succeed
- **T-STM-002:** Invalid state transitions are rejected
- **T-STM-003:** State transition timing meets requirements (≤50ms)

### 10.2 Teardown Tests

- **T-STM-004:** Teardown sequence completes within 500ms
- **T-STM-005:** Teardown coordinates data flush
- **T-STM-006:** Teardown prevents new transitions

### 10.3 Notification Tests

- **T-STM-007:** State change notifications are sent to all listeners
- **T-STM-008:** State change notifications are non-blocking

## 11. Traceability

- **SWR-SYS-001:** FSM implementation
- **SWR-SYS-002:** State transition enforcement
- **SWR-SYS-003:** State-based operation restriction
- **SWR-SYS-004:** State transition notification
- **SWR-SYS-005:** Controlled teardown execution
- **SWR-SYS-006:** Critical data persistence before teardown
- **SWR-SYS-007:** Data integrity protection during shutdown

## 12. Implementation Notes

- State machine SHALL be implemented as a table-driven FSM
- State transitions SHALL be atomic (protected by mutex)
- State listeners SHALL be called asynchronously via Event System
- Teardown sequence SHALL coordinate with Persistence component for data flush
- State queries SHALL be lock-free for ISR access (read-only)
