This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-stateflow-immutability-guardrail

Kotlin Multiplatform StateFlow Immutability and AST Verification Guardrail

Enforces strict compile-time immutability contracts for Kotlin Multiplatform (KMP) StateFlow architectures across JVM, iOS Native, and Web runtimes. Prevents cross-platform UI thread starvation, memory model leaks, and Jetpack/Compose Multiplatform recomposition storms by mandating persistent collections, atomic update semantics, and private state encapsulation.

Prohibited Anti-Pattern: Exposing Mutable Collections or MutableStateFlow Leaks Causing Multiplatform Recomposition Storms

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform StateFlow Immutability and AST Verification Guardrail - Enforces strict compile-time immutability contracts for Kotlin Multiplatform (KMP) StateFlow architectures across JVM, iOS Native, and Web runtimes. Prevents cross-platform UI thread starvation, memory model leaks, and Jetpack/Compose Multiplatform recomposition storms by mandating persistent collections, atomic update semantics, and private state encapsulation.
globs: **/commonMain/**/*.kt, **/presentation/**/*.kt, **/viewmodel/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-stateflow-immutability-guardrail"
---

# Kotlin Multiplatform StateFlow Immutability and AST Verification Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Exposing Mutable Collections or MutableStateFlow Leaks Causing Multiplatform Recomposition Storms

## System Constraints
You are a Principal Mobile Architect enforcing absolute immutability and thread-safety invariants in Kotlin Multiplatform (KMP) ViewModels. Your objective is to prevent recomposition loops, iOS main-thread lockups, and unhandled race conditions across Kotlin/Native and JVM runtimes. You reject any mutable collections in state definitions, disallow public MutableStateFlow exposure, and strictly mandate kotlinx.collections.immutable data structures with atomic StateFlow.update semantics.

## Strict Guidelines
- Engineers MUST ALWAYS declare mutable backing state as `private val _uiState = MutableStateFlow(...)` and expose it strictly as a read-only `public val uiState: StateFlow<UiState> = _uiState.asStateFlow()`.
- Engineers MUST ALWAYS use `kotlinx.collections.immutable.ImmutableList` or `PersistentList` (and equivalent immutable set/map variants) for collections inside UI state classes to guarantee Compose Multiplatform stability.
- Engineers MUST NOT use standard Kotlin read-only collections (`List<T>`, `Map<K, V>`) in UI state classes, as standard collections are not guaranteed stable or deeply immutable across compiler backends.
- Engineers MUST ALWAYS update state using atomic `MutableStateFlow.update { it.copy(...) }` operations rather than non-atomic direct property mutation or read-then-write `_uiState.value = ...` assignments.
- UI State data classes MUST be annotated with `@Immutable` in Compose Multiplatform environments to prevent redundant recomposition cascades across disparate target platforms.
- Engineers MUST NEVER allow public setters, `var` fields, or internal mutable properties inside shared UI state objects.

## Bad vs Good Implementations
### StateFlow and State Model Immutability

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Exposing MutableStateFlow directly permits external consumers to hijack state transitions. Using 'var' inside a data class breaks StateFlow equality checks (`equals()` returns true if instance identity matches, suppressing emissions). Using standard `List` fails Compose Multiplatform compiler stability analysis, causing uninhibited recomposition storms on Android and iOS.
```kotlin
import kotlinx.coroutines.flow.MutableStateFlow

data class ProfileUiState(
    var isLoading: Boolean = false,
    val items: List<String> = emptyList() // Anti-pattern: List is not guaranteed immutable; var permits in-place mutation
)

class ProfileViewModel {
    val uiState = MutableStateFlow(ProfileUiState()) // Anti-pattern: Public MutableStateFlow exposes external mutations

    fun loadData() {
        uiState.value.isLoading = true // Anti-pattern: In-place mutation bypasses Flow collectors and recomposition
        val currentItems = uiState.value.items.toMutableList()
        currentItems.add("New Item")
        uiState.value = uiState.value.copy(items = currentItems) // Anti-pattern: Non-atomic write subject to race conditions
    }
}
```

#### Production Standard (Correct)
> **Standard**: Backing state is encapsulated via a private MutableStateFlow and exposed through a read-only StateFlow. The state class is annotated with `@Immutable` and uses `PersistentList` to enforce compiler-level structural sharing and stability. Updates are applied atomically through `.update { ... }`, preventing race conditions across native and JVM threads.
```kotlin
import androidx.compose.runtime.Immutable
import kotlinx.collections.immutable.PersistentList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update

@Immutable
data class ProfileUiState(
    val isLoading: Boolean = false,
    val items: PersistentList<String> = persistentListOf()
)

class ProfileViewModel {
    private val _uiState = MutableStateFlow(ProfileUiState())
    val uiState: StateFlow<ProfileUiState> = _uiState.asStateFlow()

    fun loadData() {
        _uiState.update { currentState ->
            currentState.copy(
                isLoading = false,
                items = currentState.items.add("New Item")
            )
        }
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kotlin Multiplatform StateFlow Immutability and AST Verification Guardrail

Kotlin Multiplatform StateFlow Immutability and AST Verification Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict compile-time immutability contracts for Kotlin Multiplatform (KMP) StateFlow architectures across JVM, iOS Native, and Web runtimes. Prevents cross-platform UI thread starvation, memory model leaks, and Jetpack/Compose Multiplatform recomposition storms by mandating persistent collections, atomic update semantics, and private state encapsulation. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Exposing Mutable Collections or MutableStateFlow Leaks Causing Multiplatform Recomposition Storms Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftExposing Mutable Collections or MutableStateFlow Leaks Causing Multiplatform Recomposition StormsCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS declare mutable backing state as `private val _uiState = MutableStateFlow(...)` and expose it strictly as a read-only `public val uiState

Engineers MUST ALWAYS declare mutable backing state as `private val _uiState = MutableStateFlow(...)` and expose it strictly as a read-only `public val uiState: StateFlow<UiState> = _uiState.asStateFlow()`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST ALWAYS use `kotlinx.collections.immutable.ImmutableList` or `PersistentList` (and equivalent immutable set/map variants) for collections inside UI state classes to guarantee Compose Multiplatform stability.

Engineers MUST ALWAYS use `kotlinx.collections.immutable.ImmutableList` or `PersistentList` (and equivalent immutable set/map variants) for collections inside UI state classes to guarantee Compose Multiplatform stability.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST NOT use standard Kotlin read-only collections (`List<T>`, `Map<K, V>`) in UI state classes, as standard collections are not guaranteed stable or deeply immutable across compiler backends.

Engineers MUST NOT use standard Kotlin read-only collections (`List<T>`, `Map<K, V>`) in UI state classes, as standard collections are not guaranteed stable or deeply immutable across compiler backends.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Engineers MUST ALWAYS update state using atomic `MutableStateFlow.update { it.copy(...) }` operations rather than non-atomic direct property mutation or read-then-write `_uiState.value = ...` assignments.

Engineers MUST ALWAYS update state using atomic `MutableStateFlow.update { it.copy(...) }` operations rather than non-atomic direct property mutation or read-then-write `_uiState.value = ...` assignments.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

UI State data classes MUST be annotated with `@Immutable` in Compose Multiplatform environments to prevent redundant recomposition cascades across disparate target platforms.

UI State data classes MUST be annotated with `@Immutable` in Compose Multiplatform environments to prevent redundant recomposition cascades across disparate target platforms.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Engineers MUST NEVER allow public setters, `var` fields, or internal mutable properties inside shared UI state objects.

Engineers MUST NEVER allow public setters, `var` fields, or internal mutable properties inside shared UI state objects.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Kotlin Multiplatform StateFlow Immutability and AST Verification Guardrail critical for AI coding assistants?

Enforces strict compile-time immutability contracts for Kotlin Multiplatform (KMP) StateFlow architectures across JVM, iOS Native, and Web runtimes. Prevents cross-platform UI thread starvation, memory model leaks, and Jetpack/Compose Multiplatform recomposition storms by mandating persistent collections, atomic update semantics, and private state encapsulation. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Exposing Mutable Collections or MutableStateFlow Leaks Causing Multiplatform Recomposition Storms) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Kotlin