This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-compose-semantics-parity-barrier

KMP Compose Multiplatform Semantics Parity Barrier for Dual-Platform WCAG Compliance

Enforces deterministic accessibility semantics tree configuration in Kotlin Multiplatform (Compose Multiplatform) UI components. Bridges behavioral discrepancies between Android AccessibilityNodeInfo and iOS UIAccessibilityElement representations by enforcing descendant merging, explicit semantic roles, and unified state descriptions. Prevents silent screen reader regressions, fragmented accessibility focus rings, and WCAG 2.1/2.2 AA non-compliance across TalkBack and VoiceOver.

Prohibited Anti-Pattern: Fragmented Semantics Hierarchy and Implicit Platform Trait Mapping

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: KMP Compose Multiplatform Semantics Parity Barrier for Dual-Platform WCAG Compliance - Enforces deterministic accessibility semantics tree configuration in Kotlin Multiplatform (Compose Multiplatform) UI components. Bridges behavioral discrepancies between Android AccessibilityNodeInfo and iOS UIAccessibilityElement representations by enforcing descendant merging, explicit semantic roles, and unified state descriptions. Prevents silent screen reader regressions, fragmented accessibility focus rings, and WCAG 2.1/2.2 AA non-compliance across TalkBack and VoiceOver.
globs: **/commonMain/**/*.kt, **/shared/**/*.kt, **/composeApp/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-compose-semantics-parity-barrier"
---

# KMP Compose Multiplatform Semantics Parity Barrier for Dual-Platform WCAG Compliance

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Fragmented Semantics Hierarchy and Implicit Platform Trait Mapping

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform and Compose Multiplatform accessibility runtimes. Your mandate is to enforce structural semantic parity between Android AccessibilityNodeInfo and iOS UIAccessibilityElement hierarchies. Mandate strict semantic boundary encapsulation, explicit Role declarations, unified state descriptions, and descendant merging to eliminate VoiceOver and TalkBack navigation discrepancies across shared design system components.

## Strict Guidelines
- Engineers MUST ALWAYS set `mergeDescendants = true` on composite interactive components using `Modifier.semantics(mergeDescendants = true)` to avoid fragmented focus traversal on iOS VoiceOver.
- Engineers MUST ALWAYS assign an explicit `Role` (e.g., `Role.Button`, `Role.Switch`, `Role.Checkbox`, `Role.Tab`) inside the semantics block whenever custom pointer input or click handling is implemented.
- Engineers MUST NOT rely on implicit platform accessibility inference from basic composables like `Box` or `Row` with detached `clickable` modifiers.
- Code MUST provide unified `stateDescription` and `contentDescription` values that dynamically convey operational state changes without relying on visual text nodes.
- Components NEVER expose raw decorative iconography or supplemental visual indicators to the accessibility tree; these MUST be hidden using `Modifier.clearAndSetSemantics { }` or `contentDescription = null`.
- Engineers MUST declare explicit accessibility actions (`onClick`, `onLongClick`, `customActions`) inside the `semantics` block when custom gestures bypass standard high-level Compose interaction handlers.
- UI design system test suites MUST validate semantic trees using Compose UI test matchers (`assert(hasSemantics(...))` and `assertIsDisplayed()`) within commonMain tests to guarantee cross-runtime parity.

## Bad vs Good Implementations
### Accessible Compound Switch/Toggle Component

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omits mergeDescendants and semantic role definitions. On iOS, CMP maps this to fragmented UIAccessibilityElements without trait association. On TalkBack, AccessibilityNodeInfo fails to announce actionable state changes cohesively.
```kotlin
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier

// ANTI-PATTERN: Lacks semantic unification. In VoiceOver (iOS), the Text and Switch
// are announced as separate elements, causing duplicate focus and missing composite role state.
// In TalkBack, click actions fail to associate label semantics with the binary switch state.
@Composable
fun SettingToggleItem(
    title: String,
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit,
    modifier: Modifier = Modifier
) {
    Row(
        modifier = modifier.clickable { onCheckedChange(!checked) }
    ) {
        Text(text = title)
        Switch(
            checked = checked,
            onCheckedChange = null // Broken semantics linkage
        )
    }
}
```

#### Production Standard (Correct)
> **Standard**: Enforces semantic boundary via `mergeDescendants = true`, assigns `Role.Switch`, clears child switch semantics to prevent tree pollution, and supplies an explicit `stateDescription` ensuring equal VoiceOver trait mapping and TalkBack state parity.
```kotlin
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.stateDescription

// PRODUCTION INVARIANT: Uses toggleable with explicit Role, stateDescription,
// and merges descendants. Maps cleanly to UIAccessibilityTraitButton/TraitSelected
// on iOS and AccessibilityNodeInfo.ACTION_CLICK with ToggleableInfo on Android.
@Composable
fun SettingToggleItem(
    title: String,
    checked: Boolean,
    onCheckedChange: (Boolean) -> Unit,
    modifier: Modifier = Modifier
) {
    val stateLabel = if (checked) "Enabled" else "Disabled"

    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = modifier
            .semantics(mergeDescendants = true) {
                role = Role.Switch
                stateDescription = stateLabel
            }
            .toggleable(
                value = checked,
                role = Role.Switch,
                onValueChange = onCheckedChange
            )
    ) {
        Text(text = title)
        Switch(
            checked = checked,
            onCheckedChange = null,
            modifier = Modifier.clearAndSetSemantics { }
        )
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Recommended Agent Skills (askills.dev)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: KMP Compose Multiplatform Semantics Parity Barrier for Dual-Platform WCAG Compliance

KMP Compose Multiplatform Semantics Parity Barrier for Dual-Platform WCAG Compliance defines an industrial-grade behavioral standard for mobile engineering. Enforces deterministic accessibility semantics tree configuration in Kotlin Multiplatform (Compose Multiplatform) UI components. Bridges behavioral discrepancies between Android AccessibilityNodeInfo and iOS UIAccessibilityElement representations by enforcing descendant merging, explicit semantic roles, and unified state descriptions. Prevents silent screen reader regressions, fragmented accessibility focus rings, and WCAG 2.1/2.2 AA non-compliance across TalkBack and VoiceOver. 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: Fragmented Semantics Hierarchy and Implicit Platform Trait Mapping 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 DriftFragmented Semantics Hierarchy and Implicit Platform Trait MappingCritical
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 set `mergeDescendants = true` on composite interactive components using `Modifier.semantics(mergeDescendants = true)` to avoid fragmented focus traversal on iOS VoiceOver.

Engineers MUST ALWAYS set `mergeDescendants = true` on composite interactive components using `Modifier.semantics(mergeDescendants = true)` to avoid fragmented focus traversal on iOS VoiceOver.

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 assign an explicit `Role` (e.g., `Role.Button`, `Role.Switch`, `Role.Checkbox`, `Role.Tab`) inside the semantics block whenever custom pointer input or click handling is implemented.

Engineers MUST ALWAYS assign an explicit `Role` (e.g., `Role.Button`, `Role.Switch`, `Role.Checkbox`, `Role.Tab`) inside the semantics block whenever custom pointer input or click handling is implemented.

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 rely on implicit platform accessibility inference from basic composables like `Box` or `Row` with detached `clickable` modifiers.

Engineers MUST NOT rely on implicit platform accessibility inference from basic composables like `Box` or `Row` with detached `clickable` modifiers.

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

Code MUST provide unified `stateDescription` and `contentDescription` values that dynamically convey operational state changes without relying on visual text nodes.

Code MUST provide unified `stateDescription` and `contentDescription` values that dynamically convey operational state changes without relying on visual text nodes.

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 expose raw decorative iconography or supplemental visual indicators to the accessibility tree

Components NEVER expose raw decorative iconography or supplemental visual indicators to the accessibility tree; these MUST be hidden using `Modifier.clearAndSetSemantics { }` or `contentDescription = null`.

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 declare explicit accessibility actions (`onClick`, `onLongClick`, `customActions`) inside the `semantics` block when custom gestures bypass standard high-level Compose interaction handlers.

Engineers MUST declare explicit accessibility actions (`onClick`, `onLongClick`, `customActions`) inside the `semantics` block when custom gestures bypass standard high-level Compose interaction handlers.

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.
7

UI design system test suites MUST validate semantic trees using Compose UI test matchers (`assert(hasSemantics(...))` and `assertIsDisplayed()`) within commonMain tests to guarantee cross-runtime parity.

UI design system test suites MUST validate semantic trees using Compose UI test matchers (`assert(hasSemantics(...))` and `assertIsDisplayed()`) within commonMain tests to guarantee cross-runtime parity.

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 Compose Multiplatform Semantics Parity Barrier for Dual-Platform WCAG Compliance critical for AI coding assistants?

Enforces deterministic accessibility semantics tree configuration in Kotlin Multiplatform (Compose Multiplatform) UI components. Bridges behavioral discrepancies between Android AccessibilityNodeInfo and iOS UIAccessibilityElement representations by enforcing descendant merging, explicit semantic roles, and unified state descriptions. Prevents silent screen reader regressions, fragmented accessibility focus rings, and WCAG 2.1/2.2 AA non-compliance across TalkBack and VoiceOver. 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 (Fragmented Semantics Hierarchy and Implicit Platform Trait Mapping) 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