This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: cmp-predictive-back-gesture-state-isolation-standard

Compose Multiplatform Predictive Back Gesture State Isolation Standard

Enforces complete decoupling between predictive back gesture animation progress and persistent navigation/ViewModel state across Compose Multiplatform targets (Android, iOS). Prevents speculative transition gestures from mutating business models, firing lifecycle teardowns, or desynchronizing stack entries when users cancel mid-gesture.

Prohibited Anti-Pattern: Premature ViewModel Mutation or Lifecycle Destruction During Speculative Gesture Tracking

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform Predictive Back Gesture State Isolation Standard - Enforces complete decoupling between predictive back gesture animation progress and persistent navigation/ViewModel state across Compose Multiplatform targets (Android, iOS). Prevents speculative transition gestures from mutating business models, firing lifecycle teardowns, or desynchronizing stack entries when users cancel mid-gesture.
globs: **/*Screen.kt, **/*NavHost.kt, **/*Destination.kt, **/*ViewModel.kt, **/navigation/**
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/cmp-predictive-back-gesture-state-isolation-standard"
---

# Compose Multiplatform Predictive Back Gesture State Isolation Standard

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Premature ViewModel Mutation or Lifecycle Destruction During Speculative Gesture Tracking

## System Constraints
You are a Principal Mobile Architect enforcing Compose Multiplatform Predictive Back Gesture State Preservation standards. Speculative transitions (such as predictive back gestures on Android 14+ and iOS edge-swipe parity) emit continuous progress values that represent potential, not committed, navigation events. You must strictly forbid any mutation of ViewModels, Navigation back stacks, network jobs, or business state inside gesture progress observers. State commits must only occur when a gesture completes and confirms navigation.

## Strict Guidelines
- Engineers MUST ALWAYS isolate predictive back progress interpolation to transient UI transition state (e.g., GraphicsLayer, Animatable, or SeekableTransitionState) without modifying ViewModels.
- Engineers MUST NOT execute popBackStack(), state cleanup, or dispatch completion actions during the collection of predictive back progress updates.
- Code MUST strictly distinguish between gesture cancellation (rollback) and gesture completion (commit) inside PredictiveBackHandler or platform-agnostic gesture detectors.
- ViewModels MUST NEVER observe or store raw gesture progress values; ViewModels only respond to discrete domain events dispatched upon committed completion.
- Components NEVER trigger disposable effects, cancel coroutines, or alter shared stack parameters until the destination transition is finalized.

## Bad vs Good Implementations
### Predictive Back Gesture Handling in Compose Multiplatform

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Mutating ViewModel domain state or releasing resources during predictive back progress assumes the transition will finish. If the user cancels the swipe, the screen returns to the foreground with partially destroyed resources or corrupted business draft states.
```kotlin
// BAD: Mutating ViewModel and Navigation state during progress collection
@Composable
fun DetailScreen(
    viewModel: DetailViewModel,
    navController: NavController
) {
    PredictiveBackHandler(enabled = true) { progressFlow ->
        try {
            progressFlow.collect { backEvent ->
                // Anti-pattern: Mutating business state and triggering navigation work speculative to the gesture
                viewModel.updateDraftProgress(backEvent.progress)
                if (backEvent.progress > 0.5f) {
                    viewModel.persistDraftAndReleaseResources() // Corrupts state if user cancels swipe!
                }
            }
            // Gesture completed
            navController.popBackStack()
        } catch (e: CancellationException) {
            // Canceled: But draft state is already corrupted and resources were prematurely released!
        }
    }
    DetailContent(viewModel = viewModel)
}
```

#### Production Standard (Correct)
> **Standard**: Progress updates exclusively drive local `graphicsLayer` rendering. The ViewModel's lifecycle and domain state remain intact if the user aborts the gesture. State mutation and navigation commits occur strictly after the progress flow finishes normally.
```kotlin
// GOOD: Speculative UI isolation using transient animation states; state commit deferred to completion
@Composable
fun DetailScreen(
    viewModel: DetailViewModel,
    navController: NavController
) {
    // Transient animation progress isolated strictly to the local UI layer
    var gestureProgress by remember { mutableFloatStateOf(0f) }

    PredictiveBackHandler(enabled = true) { progressFlow ->
        try {
            progressFlow.collect { backEvent ->
                // Only drive ephemeral UI transformation
                gestureProgress = backEvent.progress
            }
            // GESTURE COMMITTED: Perform atomic teardown and navigation
            viewModel.onNavigationConfirmed()
            navController.popBackStack()
        } catch (e: CancellationException) {
            // GESTURE CANCELED: Reset ephemeral UI without touching business logic
            gestureProgress = 0f
        }
    }

    DetailContent(
        modifier = Modifier.graphicsLayer {
            scaleX = 1f - (gestureProgress * 0.1f)
            scaleY = 1f - (gestureProgress * 0.1f)
            alpha = 1f - (gestureProgress * 0.2f)
        },
        viewModel = viewModel
    )
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Compose Multiplatform Predictive Back Gesture State Isolation Standard

Compose Multiplatform Predictive Back Gesture State Isolation Standard defines an industrial-grade behavioral standard for mobile engineering. Enforces complete decoupling between predictive back gesture animation progress and persistent navigation/ViewModel state across Compose Multiplatform targets (Android, iOS). Prevents speculative transition gestures from mutating business models, firing lifecycle teardowns, or desynchronizing stack entries when users cancel mid-gesture. 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: Premature ViewModel Mutation or Lifecycle Destruction During Speculative Gesture Tracking 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 DriftPremature ViewModel Mutation or Lifecycle Destruction During Speculative Gesture TrackingCritical
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 isolate predictive back progress interpolation to transient UI transition state (e.g., GraphicsLayer, Animatable, or SeekableTransitionState) without modifying ViewModels.

Engineers MUST ALWAYS isolate predictive back progress interpolation to transient UI transition state (e.g., GraphicsLayer, Animatable, or SeekableTransitionState) without modifying ViewModels.

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 NOT execute popBackStack(), state cleanup, or dispatch completion actions during the collection of predictive back progress updates.

Engineers MUST NOT execute popBackStack(), state cleanup, or dispatch completion actions during the collection of predictive back progress updates.

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

Code MUST strictly distinguish between gesture cancellation (rollback) and gesture completion (commit) inside PredictiveBackHandler or platform-agnostic gesture detectors.

Code MUST strictly distinguish between gesture cancellation (rollback) and gesture completion (commit) inside PredictiveBackHandler or platform-agnostic gesture detectors.

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

ViewModels MUST NEVER observe or store raw gesture progress values

ViewModels MUST NEVER observe or store raw gesture progress values; ViewModels only respond to discrete domain events dispatched upon committed completion.

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

Components NEVER trigger disposable effects, cancel coroutines, or alter shared stack parameters until the destination transition is finalized.

Components NEVER trigger disposable effects, cancel coroutines, or alter shared stack parameters until the destination transition is finalized.

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 Compose Multiplatform Predictive Back Gesture State Isolation Standard critical for AI coding assistants?

Enforces complete decoupling between predictive back gesture animation progress and persistent navigation/ViewModel state across Compose Multiplatform targets (Android, iOS). Prevents speculative transition gestures from mutating business models, firing lifecycle teardowns, or desynchronizing stack entries when users cancel mid-gesture. 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 (Premature ViewModel Mutation or Lifecycle Destruction During Speculative Gesture Tracking) 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

Compose