This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-deterministic-state-engine-invariants

KMP Deterministic Unidirectional State Engine and Side-Effect Isolation

Cross-platform state divergence occurs when business logic, asynchronous side effects, and state mutations are intertwined with platform threading models. In Kotlin Multiplatform (KMP), all core domain state transitions must be strictly pure, mathematical reducers running over immutable state data structures, while asynchronous operations are modeled exclusively as declarative side-effect commands executed on isolated effect handlers.

Prohibited Anti-Pattern: Impure In-Reducer Side Effects and Mutable Platform-Specific Concurrency Divergence

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Deterministic Unidirectional State Engine and Side-Effect Isolation - Cross-platform state divergence occurs when business logic, asynchronous side effects, and state mutations are intertwined with platform threading models. In Kotlin Multiplatform (KMP), all core domain state transitions must be strictly pure, mathematical reducers running over immutable state data structures, while asynchronous operations are modeled exclusively as declarative side-effect commands executed on isolated effect handlers.
globs: **/commonMain/**/state/*.kt, **/commonMain/**/engine/*.kt, **/commonMain/**/reducer/*.kt, **/commonMain/**/domain/**/StateMachine.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-deterministic-state-engine-invariants"
---

# KMP Deterministic Unidirectional State Engine and Side-Effect Isolation

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Impure In-Reducer Side Effects and Mutable Platform-Specific Concurrency Divergence

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform (KMP) deterministic state architecture. Enforce absolute purity in state reducers, ban direct coroutine launches within state transitions, require immutable algebraic data types (ADTs) for State, Intent, and Effect, and guarantee reproducible state across Android (JVM), iOS (Kotlin/Native), and Desktop targets.

## Strict Guidelines
- Engineers MUST ALWAYS implement state transition functions as pure mathematical reducers `(State, Intent) -> Pair<State, Set<Effect>>` without any I/O, clock reads, random seeds, or dispatcher context shifts.
- Engineers MUST NEVER launch Kotlin Coroutines, execute network/database calls, or mutate external variables inside reducers or state transition blocks.
- Engineers MUST represent `State`, `Intent`/`Event`, and `Effect`/`Command` strictly as sealed interfaces or sealed classes with immutable properties (`val`) to guarantee exhaustive compiler pattern matching.
- Engineers MUST dispatch external side-effects (e.g., HTTP sync, disk writes, analytics) through a dedicated platform-agnostic `EffectHandler` using structured concurrency scoped to an explicit `CoroutineScope`.
- Engineers MUST enforce state distribution via read-only `StateFlow<State>` and distinct transient events via hot queues/channels (e.g., `SharedFlow` with `extraBufferCapacity = 0`) to prevent dropped or duplicated platform UI triggers.

## Bad vs Good Implementations
### State Reducer with Side-Effects vs Pure Deterministic State Engine

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Launching coroutines directly inside state transition methods introduces platform-specific race conditions, breaks test determinism, couples the state machine to network/threading I/O, and causes diverging memory states between Android (JVM) and iOS (Native).
```kotlin
class SyncStateManager(private val scope: CoroutineScope, private val api: SyncApi) {
    var currentState = SyncState.Idle
        private set

    fun handleIntent(intent: SyncIntent) {
        when (intent) {
            is SyncIntent.StartSync -> {
                currentState = SyncState.Syncing(progress = 0)
                // ANTI-PATTERN: Coroutine launched directly inside state handler
                // Causes race conditions across Kotlin/Native thread boundaries and non-deterministic tests
                scope.launch {
                    try {
                        val result = api.pushChanges()
                        currentState = SyncState.Success(result.timestamp)
                    } catch (e: Throwable) {
                        currentState = SyncState.Error(e.message ?: "Sync failed")
                    }
                }
            }
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: The reducer is 100% pure, synchronously predictable, fully testable without mock dispatchers or coroutines, and isolates execution instructions into immutable `SyncEffect` values handled by an asynchronous bridge outside the state machine.
```kotlin
sealed interface SyncState {
    data object Idle : SyncState
    data class Syncing(val progress: Int) : SyncState
    data class Success(val syncTimestamp: Long) : SyncState
    data class Failure(val reason: String) : SyncState
}

sealed interface SyncIntent {
    data object StartSync : SyncIntent
    data class SyncCompleted(val timestamp: Long) : SyncIntent
    data class SyncFailed(val message: String) : SyncIntent
}

sealed interface SyncEffect {
    data object ExecuteNetworkPush : SyncEffect
    data class LogMetric(val eventName: String) : SyncEffect
}

// PURE: Guaranteed deterministic evaluation on any platform target
fun syncReducer(
    state: SyncState,
    intent: SyncIntent
): Pair<SyncState, Set<SyncEffect>> = when (intent) {
    is SyncIntent.StartSync -> when (state) {
        is SyncState.Idle, is SyncState.Failure -> 
            SyncState.Syncing(progress = 0) to setOf(SyncEffect.ExecuteNetworkPush)
        is SyncState.Syncing, is SyncState.Success -> state to emptySet()
    }
    is SyncIntent.SyncCompleted -> 
        SyncState.Success(intent.timestamp) to setOf(SyncEffect.LogMetric("sync_success"))
    is SyncIntent.SyncFailed -> 
        SyncState.Failure(intent.message) to setOf(SyncEffect.LogMetric("sync_failure"))
}
```

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP Deterministic Unidirectional State Engine and Side-Effect Isolation

KMP Deterministic Unidirectional State Engine and Side-Effect Isolation defines an industrial-grade behavioral standard for mobile engineering. Cross-platform state divergence occurs when business logic, asynchronous side effects, and state mutations are intertwined with platform threading models. In Kotlin Multiplatform (KMP), all core domain state transitions must be strictly pure, mathematical reducers running over immutable state data structures, while asynchronous operations are modeled exclusively as declarative side-effect commands executed on isolated effect handlers. 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: Impure In-Reducer Side Effects and Mutable Platform-Specific Concurrency Divergence 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 DriftImpure In-Reducer Side Effects and Mutable Platform-Specific Concurrency DivergenceCritical
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 implement state transition functions as pure mathematical reducers `(State, Intent) -> Pair<State, Set<Effect>>` without any I/O, clock reads, random seeds, or dispatcher context shifts.

Engineers MUST ALWAYS implement state transition functions as pure mathematical reducers `(State, Intent) -> Pair<State, Set<Effect>>` without any I/O, clock reads, random seeds, or dispatcher context shifts.

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 NEVER launch Kotlin Coroutines, execute network/database calls, or mutate external variables inside reducers or state transition blocks.

Engineers MUST NEVER launch Kotlin Coroutines, execute network/database calls, or mutate external variables inside reducers or state transition blocks.

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 represent `State`, `Intent`/`Event`, and `Effect`/`Command` strictly as sealed interfaces or sealed classes with immutable properties (`val`) to guarantee exhaustive compiler pattern matching.

Engineers MUST represent `State`, `Intent`/`Event`, and `Effect`/`Command` strictly as sealed interfaces or sealed classes with immutable properties (`val`) to guarantee exhaustive compiler pattern matching.

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 dispatch external side-effects (e.g., HTTP sync, disk writes, analytics) through a dedicated platform-agnostic `EffectHandler` using structured concurrency scoped to an explicit `CoroutineScope`.

Engineers MUST dispatch external side-effects (e.g., HTTP sync, disk writes, analytics) through a dedicated platform-agnostic `EffectHandler` using structured concurrency scoped to an explicit `CoroutineScope`.

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

Engineers MUST enforce state distribution via read-only `StateFlow<State>` and distinct transient events via hot queues/channels (e.g., `SharedFlow` with `extraBufferCapacity = 0`) to prevent dropped or duplicated platform UI triggers.

Engineers MUST enforce state distribution via read-only `StateFlow<State>` and distinct transient events via hot queues/channels (e.g., `SharedFlow` with `extraBufferCapacity = 0`) to prevent dropped or duplicated platform UI triggers.

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 KMP Deterministic Unidirectional State Engine and Side-Effect Isolation critical for AI coding assistants?

Cross-platform state divergence occurs when business logic, asynchronous side effects, and state mutations are intertwined with platform threading models. In Kotlin Multiplatform (KMP), all core domain state transitions must be strictly pure, mathematical reducers running over immutable state data structures, while asynchronous operations are modeled exclusively as declarative side-effect commands executed on isolated effect handlers. 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 (Impure In-Reducer Side Effects and Mutable Platform-Specific Concurrency Divergence) 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

KMP