Skip to main content

ftui_layout/
pane.rs

1//! Canonical pane split-tree schema and validation.
2//!
3//! This module defines a host-agnostic pane tree model intended to be shared
4//! by terminal and web adapters. It focuses on:
5//!
6//! - Deterministic node identifiers suitable for replay/diff.
7//! - Explicit parent/child relationships for split trees.
8//! - Canonical serialization snapshots with forward-compatible extension bags.
9//! - Strict validation that rejects malformed trees.
10
11use std::collections::{BTreeMap, BTreeSet};
12use std::fmt;
13
14use ftui_core::geometry::{Rect, Sides};
15use serde::{Deserialize, Serialize};
16use smallvec::{SmallVec, smallvec};
17
18/// Current pane tree schema version.
19pub const PANE_TREE_SCHEMA_VERSION: u16 = 1;
20
21/// Current schema version for semantic pane interaction events.
22///
23/// Versioning policy:
24/// - Additive metadata can be carried in `extensions` without a version bump.
25/// - Breaking field/semantic changes must bump this version.
26pub const PANE_SEMANTIC_INPUT_EVENT_SCHEMA_VERSION: u16 = 1;
27
28/// Current schema version for semantic pane replay traces.
29pub const PANE_SEMANTIC_INPUT_TRACE_SCHEMA_VERSION: u16 = 1;
30
31/// Stable identifier for pane nodes.
32///
33/// `0` is reserved/invalid so IDs are always non-zero.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
35#[serde(transparent)]
36pub struct PaneId(u64);
37
38impl PaneId {
39    /// Lowest valid pane ID.
40    pub const MIN: Self = Self(1);
41
42    /// Create a new pane ID, rejecting 0.
43    pub fn new(raw: u64) -> Result<Self, PaneModelError> {
44        if raw == 0 {
45            return Err(PaneModelError::ZeroPaneId);
46        }
47        Ok(Self(raw))
48    }
49
50    /// Get the raw numeric value.
51    #[must_use]
52    pub const fn get(self) -> u64 {
53        self.0
54    }
55
56    /// Return the next ID, or an error on overflow.
57    pub fn checked_next(self) -> Result<Self, PaneModelError> {
58        let Some(next) = self.0.checked_add(1) else {
59            return Err(PaneModelError::PaneIdOverflow { current: self });
60        };
61        Self::new(next)
62    }
63}
64
65impl Default for PaneId {
66    fn default() -> Self {
67        Self::MIN
68    }
69}
70
71/// Orientation of a split node.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
73#[serde(rename_all = "snake_case")]
74pub enum SplitAxis {
75    Horizontal,
76    Vertical,
77}
78
79/// Ratio between split children, stored in reduced form.
80///
81/// Interpreted as weight pair `first:second` (not a direct fraction).
82/// Example: `3:2` assigns `3 / (3 + 2)` of available space to the first child.
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
84pub struct PaneSplitRatio {
85    numerator: u32,
86    denominator: u32,
87}
88
89impl PaneSplitRatio {
90    /// Create and normalize a ratio.
91    pub fn new(numerator: u32, denominator: u32) -> Result<Self, PaneModelError> {
92        if numerator == 0 || denominator == 0 {
93            return Err(PaneModelError::InvalidSplitRatio {
94                numerator,
95                denominator,
96            });
97        }
98        let gcd = gcd_u32(numerator, denominator);
99        Ok(Self {
100            numerator: numerator / gcd,
101            denominator: denominator / gcd,
102        })
103    }
104
105    /// Numerator (always > 0).
106    #[must_use]
107    pub const fn numerator(self) -> u32 {
108        if self.numerator == 0 {
109            1
110        } else {
111            self.numerator
112        }
113    }
114
115    /// Denominator (always > 0).
116    #[must_use]
117    pub const fn denominator(self) -> u32 {
118        if self.denominator == 0 {
119            1
120        } else {
121            self.denominator
122        }
123    }
124}
125
126impl Default for PaneSplitRatio {
127    fn default() -> Self {
128        Self {
129            numerator: 1,
130            denominator: 1,
131        }
132    }
133}
134
135/// Per-node size bounds.
136#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
137pub struct PaneConstraints {
138    pub min_width: u16,
139    pub min_height: u16,
140    pub max_width: Option<u16>,
141    pub max_height: Option<u16>,
142    pub collapsible: bool,
143    #[serde(default)]
144    pub margin: Option<u16>,
145    #[serde(default)]
146    pub padding: Option<u16>,
147}
148
149impl PaneConstraints {
150    /// Validate constraints for a given node.
151    pub fn validate(self, node_id: PaneId) -> Result<(), PaneModelError> {
152        if let Some(max_width) = self.max_width
153            && max_width < self.min_width
154        {
155            return Err(PaneModelError::InvalidConstraint {
156                node_id,
157                axis: "width",
158                min: self.min_width,
159                max: max_width,
160            });
161        }
162        if let Some(max_height) = self.max_height
163            && max_height < self.min_height
164        {
165            return Err(PaneModelError::InvalidConstraint {
166                node_id,
167                axis: "height",
168                min: self.min_height,
169                max: max_height,
170            });
171        }
172        Ok(())
173    }
174}
175
176impl Default for PaneConstraints {
177    fn default() -> Self {
178        Self {
179            min_width: 1,
180            min_height: 1,
181            max_width: None,
182            max_height: None,
183            collapsible: false,
184            margin: Some(PANE_DEFAULT_MARGIN_CELLS),
185            padding: Some(PANE_DEFAULT_PADDING_CELLS),
186        }
187    }
188}
189
190/// Leaf payload for pane content identity.
191#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
192pub struct PaneLeaf {
193    /// Host-provided stable surface key (for replay/diff mapping).
194    pub surface_key: String,
195    /// Forward-compatible extension bag.
196    #[serde(
197        default,
198        rename = "leaf_extensions",
199        skip_serializing_if = "BTreeMap::is_empty"
200    )]
201    pub extensions: BTreeMap<String, String>,
202}
203
204impl PaneLeaf {
205    /// Build a leaf with a stable surface key.
206    #[must_use]
207    pub fn new(surface_key: impl Into<String>) -> Self {
208        Self {
209            surface_key: surface_key.into(),
210            extensions: BTreeMap::new(),
211        }
212    }
213}
214
215/// Split payload with child references.
216#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
217pub struct PaneSplit {
218    pub axis: SplitAxis,
219    pub ratio: PaneSplitRatio,
220    pub first: PaneId,
221    pub second: PaneId,
222}
223
224/// Node payload variant.
225#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
226#[serde(tag = "kind", rename_all = "snake_case")]
227pub enum PaneNodeKind {
228    Leaf(PaneLeaf),
229    Split(PaneSplit),
230}
231
232/// Serializable node record in the canonical schema.
233#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
234pub struct PaneNodeRecord {
235    pub id: PaneId,
236    #[serde(default)]
237    pub parent: Option<PaneId>,
238    #[serde(default)]
239    pub constraints: PaneConstraints,
240    #[serde(flatten)]
241    pub kind: PaneNodeKind,
242    /// Forward-compatible extension bag.
243    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
244    pub extensions: BTreeMap<String, String>,
245}
246
247impl PaneNodeRecord {
248    /// Construct a leaf node record.
249    #[must_use]
250    pub fn leaf(id: PaneId, parent: Option<PaneId>, leaf: PaneLeaf) -> Self {
251        Self {
252            id,
253            parent,
254            constraints: PaneConstraints::default(),
255            kind: PaneNodeKind::Leaf(leaf),
256            extensions: BTreeMap::new(),
257        }
258    }
259
260    /// Construct a split node record.
261    #[must_use]
262    pub fn split(id: PaneId, parent: Option<PaneId>, split: PaneSplit) -> Self {
263        Self {
264            id,
265            parent,
266            constraints: PaneConstraints::default(),
267            kind: PaneNodeKind::Split(split),
268            extensions: BTreeMap::new(),
269        }
270    }
271}
272
273/// Canonical serialized pane tree shape.
274///
275/// The extension maps are reserved for forward-compatible fields.
276#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
277pub struct PaneTreeSnapshot {
278    #[serde(default = "default_schema_version")]
279    pub schema_version: u16,
280    pub root: PaneId,
281    pub next_id: PaneId,
282    pub nodes: Vec<PaneNodeRecord>,
283    #[serde(default)]
284    pub extensions: BTreeMap<String, String>,
285}
286
287fn default_schema_version() -> u16 {
288    PANE_TREE_SCHEMA_VERSION
289}
290
291impl PaneTreeSnapshot {
292    /// Canonicalize node ordering by ID for deterministic serialization.
293    pub fn canonicalize(&mut self) {
294        self.nodes.sort_by_key(|node| node.id);
295    }
296
297    /// Deterministic hash for diagnostics over serialized tree state.
298    #[must_use]
299    pub fn state_hash(&self) -> u64 {
300        snapshot_state_hash(self)
301    }
302
303    /// Inspect invariants and emit a structured diagnostics report.
304    #[must_use]
305    pub fn invariant_report(&self) -> PaneInvariantReport {
306        build_invariant_report(self)
307    }
308
309    /// Attempt deterministic safe repairs for recoverable invariant issues.
310    ///
311    /// Safety guardrail: any unrepairable error in the pre-repair report causes
312    /// this method to fail without modifying topology.
313    pub fn repair_safe(self) -> Result<PaneRepairOutcome, PaneRepairError> {
314        repair_snapshot_safe(self)
315    }
316}
317
318/// Severity for one invariant finding.
319#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
320#[serde(rename_all = "snake_case")]
321pub enum PaneInvariantSeverity {
322    Error,
323    Warning,
324}
325
326/// Stable code for invariant findings.
327#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
328#[serde(rename_all = "snake_case")]
329pub enum PaneInvariantCode {
330    UnsupportedSchemaVersion,
331    DuplicateNodeId,
332    MissingRoot,
333    RootHasParent,
334    MissingParent,
335    MissingChild,
336    MultipleParents,
337    ParentMismatch,
338    SelfReferentialSplit,
339    DuplicateSplitChildren,
340    InvalidSplitRatio,
341    InvalidConstraint,
342    CycleDetected,
343    UnreachableNode,
344    NextIdNotGreaterThanExisting,
345}
346
347/// One actionable invariant finding.
348#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
349pub struct PaneInvariantIssue {
350    pub code: PaneInvariantCode,
351    pub severity: PaneInvariantSeverity,
352    pub repairable: bool,
353    pub node_id: Option<PaneId>,
354    pub related_node: Option<PaneId>,
355    pub message: String,
356}
357
358/// Structured invariant report over a pane tree snapshot.
359#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
360pub struct PaneInvariantReport {
361    pub snapshot_hash: u64,
362    pub issues: Vec<PaneInvariantIssue>,
363}
364
365impl PaneInvariantReport {
366    /// Return true if any error-level finding exists.
367    #[must_use]
368    pub fn has_errors(&self) -> bool {
369        self.issues
370            .iter()
371            .any(|issue| issue.severity == PaneInvariantSeverity::Error)
372    }
373
374    /// Return true if any unrepairable error-level finding exists.
375    #[must_use]
376    pub fn has_unrepairable_errors(&self) -> bool {
377        self.issues
378            .iter()
379            .any(|issue| issue.severity == PaneInvariantSeverity::Error && !issue.repairable)
380    }
381}
382
383/// One deterministic repair action.
384#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
385#[serde(tag = "action", rename_all = "snake_case")]
386pub enum PaneRepairAction {
387    ReparentNode {
388        node_id: PaneId,
389        before_parent: Option<PaneId>,
390        after_parent: Option<PaneId>,
391    },
392    NormalizeRatio {
393        node_id: PaneId,
394        before_numerator: u32,
395        before_denominator: u32,
396        after_numerator: u32,
397        after_denominator: u32,
398    },
399    RemoveOrphanNode {
400        node_id: PaneId,
401    },
402    BumpNextId {
403        before: PaneId,
404        after: PaneId,
405    },
406}
407
408/// Outcome from successful safe repair pass.
409#[derive(Debug, Clone, PartialEq, Eq)]
410pub struct PaneRepairOutcome {
411    pub before_hash: u64,
412    pub after_hash: u64,
413    pub report_before: PaneInvariantReport,
414    pub report_after: PaneInvariantReport,
415    pub actions: Vec<PaneRepairAction>,
416    pub tree: PaneTree,
417}
418
419/// Failure reason for safe repair.
420#[derive(Debug, Clone, PartialEq, Eq)]
421pub enum PaneRepairFailure {
422    UnsafeIssuesPresent { codes: Vec<PaneInvariantCode> },
423    ValidationFailed { error: PaneModelError },
424}
425
426impl fmt::Display for PaneRepairFailure {
427    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
428        match self {
429            Self::UnsafeIssuesPresent { codes } => {
430                write!(f, "snapshot contains unsafe invariant issues: {codes:?}")
431            }
432            Self::ValidationFailed { error } => {
433                write!(f, "repaired snapshot failed validation: {error}")
434            }
435        }
436    }
437}
438
439impl std::error::Error for PaneRepairFailure {
440    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
441        if let Self::ValidationFailed { error } = self {
442            return Some(error);
443        }
444        None
445    }
446}
447
448/// Error payload for repair attempts.
449#[derive(Debug, Clone, PartialEq, Eq)]
450pub struct PaneRepairError {
451    pub before_hash: u64,
452    pub report: PaneInvariantReport,
453    pub reason: PaneRepairFailure,
454}
455
456impl fmt::Display for PaneRepairError {
457    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
458        write!(
459            f,
460            "pane repair failed: {} (before_hash={:#x}, issues={})",
461            self.reason,
462            self.before_hash,
463            self.report.issues.len()
464        )
465    }
466}
467
468impl std::error::Error for PaneRepairError {
469    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
470        Some(&self.reason)
471    }
472}
473
474/// Concrete layout result for a solved pane tree.
475#[derive(Debug, Clone, PartialEq, Eq)]
476pub struct PaneLayout {
477    pub area: Rect,
478    rects: BTreeMap<PaneId, Rect>,
479}
480
481impl PaneLayout {
482    /// Lookup rectangle for a specific pane node.
483    #[must_use]
484    pub fn rect(&self, node_id: PaneId) -> Option<Rect> {
485        self.rects.get(&node_id).copied()
486    }
487
488    /// Iterate all solved rectangles in deterministic ID order.
489    pub fn iter(&self) -> impl Iterator<Item = (PaneId, Rect)> + '_ {
490        self.rects.iter().map(|(node_id, rect)| (*node_id, *rect))
491    }
492
493    /// Classify pointer hit-test against any edge/corner grip for a pane rect.
494    #[must_use]
495    pub fn classify_resize_grip(
496        &self,
497        node_id: PaneId,
498        pointer: PanePointerPosition,
499        inset_cells: f64,
500    ) -> Option<PaneResizeGrip> {
501        let rect = self.rect(node_id)?;
502        classify_resize_grip(rect, pointer, inset_cells)
503    }
504
505    /// Default visual pane rectangle with baseline margin and padding applied.
506    ///
507    /// This provides Tailwind-like breathing room around pane content by
508    /// default while remaining deterministic and constraint-safe.
509    #[must_use]
510    pub fn visual_rect(&self, node_id: PaneId) -> Option<Rect> {
511        let rect = self.rect(node_id)?;
512        let with_margin = rect.inner(Sides::all(PANE_DEFAULT_MARGIN_CELLS));
513        let with_padding = with_margin.inner(Sides::all(PANE_DEFAULT_PADDING_CELLS));
514        if with_padding.width == 0 || with_padding.height == 0 {
515            Some(with_margin)
516        } else {
517            Some(with_padding)
518        }
519    }
520
521    /// Visual pane rectangle with custom margin/padding from constraints.
522    #[must_use]
523    pub fn visual_rect_with_constraints(
524        &self,
525        node_id: PaneId,
526        constraints: &PaneConstraints,
527    ) -> Option<Rect> {
528        let rect = self.rect(node_id)?;
529        let margin = constraints.margin.unwrap_or(PANE_DEFAULT_MARGIN_CELLS);
530        let padding = constraints.padding.unwrap_or(PANE_DEFAULT_PADDING_CELLS);
531        let with_margin = rect.inner(Sides::all(margin));
532        let with_padding = with_margin.inner(Sides::all(padding));
533        if with_padding.width == 0 || with_padding.height == 0 {
534            Some(with_margin)
535        } else {
536            Some(with_padding)
537        }
538    }
539
540    /// Compute the outer bounding box of a pane cluster in layout space.
541    #[must_use]
542    pub fn cluster_bounds(&self, nodes: &BTreeSet<PaneId>) -> Option<Rect> {
543        if nodes.is_empty() {
544            return None;
545        }
546        let mut min_x: Option<u16> = None;
547        let mut min_y: Option<u16> = None;
548        let mut max_x: Option<u16> = None;
549        let mut max_y: Option<u16> = None;
550
551        for node_id in nodes {
552            let rect = self.rect(*node_id)?;
553            min_x = Some(min_x.map_or(rect.x, |v| v.min(rect.x)));
554            min_y = Some(min_y.map_or(rect.y, |v| v.min(rect.y)));
555            let right = rect.x.saturating_add(rect.width);
556            let bottom = rect.y.saturating_add(rect.height);
557            max_x = Some(max_x.map_or(right, |v| v.max(right)));
558            max_y = Some(max_y.map_or(bottom, |v| v.max(bottom)));
559        }
560
561        let left = min_x?;
562        let top = min_y?;
563        let right = max_x?;
564        let bottom = max_y?;
565        Some(Rect::new(
566            left,
567            top,
568            right.saturating_sub(left).max(1),
569            bottom.saturating_sub(top).max(1),
570        ))
571    }
572}
573
574/// Default radius for magnetic docking attraction in cell units.
575pub const PANE_MAGNETIC_FIELD_CELLS: f64 = 6.0;
576
577/// Default inset from pane edges used to classify edge/corner grips.
578pub const PANE_EDGE_GRIP_INSET_CELLS: f64 = 1.5;
579
580/// Default pane margin in cell units.
581pub const PANE_DEFAULT_MARGIN_CELLS: u16 = 1;
582
583/// Default pane padding in cell units.
584pub const PANE_DEFAULT_PADDING_CELLS: u16 = 1;
585
586/// Docking zones for magnetic insertion previews.
587#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
588#[serde(rename_all = "snake_case")]
589pub enum PaneDockZone {
590    Left,
591    Right,
592    Top,
593    Bottom,
594    Center,
595}
596
597/// One magnetic docking preview candidate.
598#[derive(Debug, Clone, Copy, PartialEq)]
599pub struct PaneDockPreview {
600    pub target: PaneId,
601    pub zone: PaneDockZone,
602    /// Distance-weighted score; higher means stronger attraction.
603    pub score: f64,
604    /// Ghost rectangle to visualize the insertion/drop target.
605    pub ghost_rect: Rect,
606}
607
608/// Resize grip classification for any-edge / any-corner interaction.
609#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
610#[serde(rename_all = "snake_case")]
611pub enum PaneResizeGrip {
612    Left,
613    Right,
614    Top,
615    Bottom,
616    TopLeft,
617    TopRight,
618    BottomLeft,
619    BottomRight,
620}
621
622impl PaneResizeGrip {
623    #[must_use]
624    const fn horizontal_edge(self) -> Option<bool> {
625        match self {
626            Self::Left | Self::TopLeft | Self::BottomLeft => Some(false),
627            Self::Right | Self::TopRight | Self::BottomRight => Some(true),
628            Self::Top | Self::Bottom => None,
629        }
630    }
631
632    #[must_use]
633    const fn vertical_edge(self) -> Option<bool> {
634        match self {
635            Self::Top | Self::TopLeft | Self::TopRight => Some(false),
636            Self::Bottom | Self::BottomLeft | Self::BottomRight => Some(true),
637            Self::Left | Self::Right => None,
638        }
639    }
640}
641
642/// Pointer motion summary used by pressure-sensitive policies.
643#[derive(Debug, Clone, Copy, PartialEq)]
644pub struct PaneMotionVector {
645    pub delta_x: i32,
646    pub delta_y: i32,
647    /// Cells per second.
648    pub speed: f64,
649    /// Number of direction sign flips observed in this gesture window.
650    pub direction_changes: u16,
651}
652
653impl PaneMotionVector {
654    #[must_use]
655    pub fn from_delta(delta_x: i32, delta_y: i32, elapsed_ms: u32, direction_changes: u16) -> Self {
656        let elapsed = f64::from(elapsed_ms.max(1)) / 1_000.0;
657        let dx = f64::from(delta_x);
658        let dy = f64::from(delta_y);
659        let distance = (dx * dx + dy * dy).sqrt();
660        Self {
661            delta_x,
662            delta_y,
663            speed: distance / elapsed,
664            direction_changes,
665        }
666    }
667}
668
669/// Inertial throw profile used after drag release.
670#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
671pub struct PaneInertialThrow {
672    pub velocity_x: f64,
673    pub velocity_y: f64,
674    /// Exponential velocity damping per second. Higher means quicker settle.
675    pub damping: f64,
676    /// Projection horizon used for target preview/landing selection.
677    pub horizon_ms: u16,
678}
679
680impl PaneInertialThrow {
681    #[must_use]
682    pub fn from_motion(motion: PaneMotionVector) -> Self {
683        let dx = f64::from(motion.delta_x);
684        let dy = f64::from(motion.delta_y);
685        let magnitude = (dx * dx + dy * dy).sqrt();
686        let direction_x = if magnitude <= f64::EPSILON {
687            0.0
688        } else {
689            dx / magnitude
690        };
691        let direction_y = if magnitude <= f64::EPSILON {
692            0.0
693        } else {
694            dy / magnitude
695        };
696        let speed = motion.speed.clamp(0.0, 220.0);
697        let speed_curve = (speed / 220.0).clamp(0.0, 1.0).powf(0.72);
698        let noise_penalty = (f64::from(motion.direction_changes) / 10.0).clamp(0.0, 1.0);
699        let coherence = (1.0 - 0.55 * noise_penalty).clamp(0.35, 1.0);
700        let projected_velocity = (10.0 + speed * 0.55) * coherence;
701        Self {
702            velocity_x: direction_x * projected_velocity,
703            velocity_y: direction_y * projected_velocity,
704            damping: (9.2 - speed_curve * 4.0 + noise_penalty * 2.4).clamp(4.8, 10.5),
705            horizon_ms: (140.0 + speed_curve * 220.0).round().clamp(120.0, 380.0) as u16,
706        }
707    }
708
709    #[must_use]
710    pub fn projected_pointer(self, start: PanePointerPosition) -> PanePointerPosition {
711        let dt = f64::from(self.horizon_ms) / 1_000.0;
712        let attenuation = (-self.damping * dt).exp();
713        let gain = if self.damping <= f64::EPSILON {
714            dt
715        } else {
716            (1.0 - attenuation) / self.damping
717        };
718        let projected_x = f64::from(start.x) + self.velocity_x * gain;
719        let projected_y = f64::from(start.y) + self.velocity_y * gain;
720        PanePointerPosition::new(round_f64_to_i32(projected_x), round_f64_to_i32(projected_y))
721    }
722}
723
724/// Full affordance emphasis, in basis points (10_000 = 100%).
725pub const PANE_AFFORDANCE_EMPHASIS_FULL_BPS: u16 = 10_000;
726
727/// Deterministic micro-animation policy for pane affordances (bd-18yus).
728///
729/// Pane affordances (splitter handles, focus emphasis, snap previews) gain a
730/// subtle emphasis ramp when they activate — a hover fade-in, a slow active
731/// pulse — so a state change reads as motion rather than a hard cut. The policy
732/// is host-agnostic and reports only a bounded emphasis weight in basis points
733/// (`[0, 10_000]`); hosts map that to blend weight / brightness themselves.
734///
735/// Design properties:
736///
737/// - **Deterministic.** Emphasis is a pure function of an integer phase tick
738///   supplied by the caller (a frame counter / animation clock), never a wall
739///   clock, and uses integer-only math — so replays and snapshots are
740///   byte-stable across platforms with no floating-point drift.
741/// - **Reduced-motion safe.** When [`reduced_motion`](Self::reduced_motion) is
742///   set, every ramp collapses to a step function: emphasis jumps to its
743///   terminal value on the first frame. No semantic cue is lost — the affordance
744///   still changes state — only the in-between motion is removed, satisfying the
745///   reduced-motion behavior-parity requirement.
746/// - **Bounded & cheap.** Each query is constant-time, allocation-free integer
747///   arithmetic (a couple of multiplies and a divide), so per-affordance,
748///   per-frame overhead is negligible even with many splitters on screen.
749#[derive(Debug, Clone, Copy, PartialEq, Eq)]
750pub struct PaneAffordanceMotion {
751    /// When set, all ramps collapse to instantaneous steps (no in-between
752    /// frames), preserving the state change without motion.
753    pub reduced_motion: bool,
754    /// Frames over which a hover emphasis fades in (≈100 ms at 60 fps by
755    /// default). Zero means "instant".
756    pub fade_in_frames: u16,
757    /// Period of the active-state pulse in frames (≈0.8 s at 60 fps by
758    /// default). Zero disables the pulse (steady full emphasis).
759    pub pulse_period_frames: u16,
760    /// Low point of the active pulse in basis points; the pulse oscillates
761    /// between this floor and full emphasis.
762    pub pulse_floor_bps: u16,
763}
764
765impl Default for PaneAffordanceMotion {
766    fn default() -> Self {
767        Self {
768            reduced_motion: false,
769            fade_in_frames: 6,
770            pulse_period_frames: 48,
771            pulse_floor_bps: 8_000,
772        }
773    }
774}
775
776impl PaneAffordanceMotion {
777    /// The reduced-motion preset: identical timing fields, but every ramp is
778    /// stepped. Use this when the host reports a reduced-motion preference.
779    #[must_use]
780    pub fn reduced() -> Self {
781        Self {
782            reduced_motion: true,
783            ..Self::default()
784        }
785    }
786
787    /// Apply a reduced-motion preference to this policy, returning the adjusted
788    /// copy. Lets a host derive the effective policy from a preference flag.
789    #[must_use]
790    pub fn with_reduced_motion(mut self, reduced_motion: bool) -> Self {
791        self.reduced_motion = reduced_motion;
792        self
793    }
794
795    /// Hover emphasis ramp in basis points.
796    ///
797    /// `elapsed_frames` counts frames since the affordance entered the hovered
798    /// state. The ramp is a quadratic ease-out from 0 to full over
799    /// [`fade_in_frames`](Self::fade_in_frames). Under reduced motion (or a zero
800    /// fade) it returns full emphasis immediately.
801    #[must_use]
802    pub fn hover_emphasis_bps(&self, elapsed_frames: u16) -> u16 {
803        if self.reduced_motion || self.fade_in_frames == 0 {
804            return PANE_AFFORDANCE_EMPHASIS_FULL_BPS;
805        }
806        affordance_ease_out_bps(elapsed_frames.min(self.fade_in_frames), self.fade_in_frames)
807    }
808
809    /// Active (dragging) emphasis pulse in basis points.
810    ///
811    /// `phase_frames` is a free-running frame counter; the pulse smoothly
812    /// ping-pongs between [`pulse_floor_bps`](Self::pulse_floor_bps) and full
813    /// emphasis over [`pulse_period_frames`](Self::pulse_period_frames). Under
814    /// reduced motion (or a zero period) it returns steady full emphasis.
815    #[must_use]
816    pub fn active_pulse_bps(&self, phase_frames: u64) -> u16 {
817        if self.reduced_motion || self.pulse_period_frames == 0 {
818            return PANE_AFFORDANCE_EMPHASIS_FULL_BPS;
819        }
820        let period = self.pulse_period_frames;
821        let half = period / 2;
822        let p = (phase_frames % u64::from(period)) as u16;
823        // Smooth ping-pong: ease up to the peak at the midpoint, then back down.
824        let ramp = if p < half {
825            affordance_ease_out_bps(p, half)
826        } else {
827            affordance_ease_out_bps(period - p, period - half)
828        };
829        let span = PANE_AFFORDANCE_EMPHASIS_FULL_BPS - self.pulse_floor_bps;
830        self.pulse_floor_bps + ((u32::from(ramp) * u32::from(span)) / 10_000) as u16
831    }
832}
833
834/// Integer quadratic ease-out from 0 to 10_000 bps over `total` frames.
835///
836/// `ease_out(x) = 1 - (1 - x)^2` with `x = t / total`, evaluated in integer
837/// space so results are identical on every platform.
838fn affordance_ease_out_bps(t: u16, total: u16) -> u16 {
839    if total == 0 {
840        return PANE_AFFORDANCE_EMPHASIS_FULL_BPS;
841    }
842    let t = t.min(total);
843    let remaining = u64::from(total - t);
844    let total2 = u64::from(total) * u64::from(total);
845    let drop = (10_000u64 * remaining * remaining) / total2;
846    (10_000 - drop) as u16
847}
848
849/// Dynamic snap aggressiveness derived from drag pressure cues.
850#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
851pub struct PanePressureSnapProfile {
852    /// Relative snap strength (0..=10_000). Higher means stronger canonical snap.
853    pub strength_bps: u16,
854    /// Effective hysteresis window used for sticky docking/snap.
855    pub hysteresis_bps: u16,
856}
857
858impl PanePressureSnapProfile {
859    /// Compute pressure profile from gesture speed and direction noise.
860    ///
861    /// Slow/stable drags reduce snap force for precision; fast drags with
862    /// consistent direction increase snap force for canonical layouts.
863    #[must_use]
864    pub fn from_motion(motion: PaneMotionVector) -> Self {
865        let abs_dx = f64::from(motion.delta_x.unsigned_abs());
866        let abs_dy = f64::from(motion.delta_y.unsigned_abs());
867        let axis_dominance = (abs_dx.max(abs_dy) / (abs_dx + abs_dy).max(1.0)).clamp(0.5, 1.0);
868        let speed_factor = (motion.speed / 70.0).clamp(0.0, 1.0).powf(0.78);
869        let noise_penalty = (f64::from(motion.direction_changes) / 7.0).clamp(0.0, 1.0);
870        let confidence =
871            (speed_factor * (0.65 + axis_dominance * 0.35) * (1.0 - noise_penalty * 0.72))
872                .clamp(0.0, 1.0);
873        let strength = (1_500.0 + confidence.powf(0.85) * 8_500.0).round() as u16;
874        let hysteresis = (60.0 + confidence * 500.0).round() as u16;
875        Self {
876            strength_bps: strength.min(10_000),
877            hysteresis_bps: hysteresis.min(2_000),
878        }
879    }
880
881    #[must_use]
882    pub fn apply_to_tuning(self, base: PaneSnapTuning) -> PaneSnapTuning {
883        let scaled_step = ((u32::from(base.step_bps) * (11_000 - u32::from(self.strength_bps)))
884            / 10_000)
885            .clamp(100, 10_000);
886        PaneSnapTuning {
887            step_bps: scaled_step as u16,
888            hysteresis_bps: self.hysteresis_bps.max(base.hysteresis_bps),
889        }
890    }
891}
892
893/// Result of planning a side/corner resize from one pointer sample.
894#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
895pub struct PaneEdgeResizePlan {
896    pub leaf: PaneId,
897    pub grip: PaneResizeGrip,
898    pub operations: Vec<PaneOperation>,
899}
900
901/// Planned pane move with organic reflow semantics.
902#[derive(Debug, Clone, PartialEq)]
903pub struct PaneReflowMovePlan {
904    pub source: PaneId,
905    pub pointer: PanePointerPosition,
906    pub projected_pointer: PanePointerPosition,
907    pub preview: PaneDockPreview,
908    pub snap_profile: PanePressureSnapProfile,
909    pub operations: Vec<PaneOperation>,
910}
911
912/// Errors while deriving edge/corner resize plans.
913#[derive(Debug, Clone, PartialEq, Eq)]
914pub enum PaneEdgeResizePlanError {
915    MissingLeaf { leaf: PaneId },
916    NodeNotLeaf { node: PaneId },
917    MissingLayoutRect { node: PaneId },
918    NoAxisSplit { leaf: PaneId, axis: SplitAxis },
919    InvalidRatio { numerator: u32, denominator: u32 },
920}
921
922impl fmt::Display for PaneEdgeResizePlanError {
923    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
924        match self {
925            Self::MissingLeaf { leaf } => write!(f, "pane leaf {} not found", leaf.get()),
926            Self::NodeNotLeaf { node } => write!(f, "node {} is not a leaf", node.get()),
927            Self::MissingLayoutRect { node } => {
928                write!(f, "layout missing rectangle for node {}", node.get())
929            }
930            Self::NoAxisSplit { leaf, axis } => {
931                write!(
932                    f,
933                    "no ancestor split on {axis:?} axis for leaf {}",
934                    leaf.get()
935                )
936            }
937            Self::InvalidRatio {
938                numerator,
939                denominator,
940            } => write!(
941                f,
942                "invalid planned ratio {numerator}/{denominator} for edge resize"
943            ),
944        }
945    }
946}
947
948impl std::error::Error for PaneEdgeResizePlanError {}
949
950/// Errors while planning a directly-addressed splitter resize/nudge.
951///
952/// Unlike [`PaneEdgeResizePlanError`] (which is keyed by a leaf and walks to its
953/// nearest ancestor split), these errors describe a [`PaneResizeTarget`] that
954/// names a split node directly — the form produced by host splitter hit-testing
955/// and the [`PaneDragResizeMachine`].
956#[derive(Debug, Clone, Copy, PartialEq, Eq)]
957pub enum PaneSplitterResizePlanError {
958    /// The target split id is absent from the tree.
959    MissingSplit { split: PaneId },
960    /// The target node exists but is a leaf, not a split.
961    NotASplit { node: PaneId },
962    /// The split exists but its axis disagrees with the target axis.
963    AxisMismatch {
964        split: PaneId,
965        expected: SplitAxis,
966        actual: SplitAxis,
967    },
968    /// The current layout has no rectangle for the target split.
969    MissingLayoutRect { node: PaneId },
970    /// The derived ratio could not be constructed.
971    InvalidRatio { numerator: u32, denominator: u32 },
972}
973
974impl fmt::Display for PaneSplitterResizePlanError {
975    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
976        match self {
977            Self::MissingSplit { split } => {
978                write!(f, "splitter target {} not found", split.get())
979            }
980            Self::NotASplit { node } => write!(f, "node {} is a leaf, not a split", node.get()),
981            Self::AxisMismatch {
982                split,
983                expected,
984                actual,
985            } => write!(
986                f,
987                "split {} has axis {actual:?} but target requested {expected:?}",
988                split.get()
989            ),
990            Self::MissingLayoutRect { node } => {
991                write!(f, "layout missing rectangle for split {}", node.get())
992            }
993            Self::InvalidRatio {
994                numerator,
995                denominator,
996            } => write!(
997                f,
998                "invalid planned ratio {numerator}/{denominator} for splitter resize"
999            ),
1000        }
1001    }
1002}
1003
1004impl std::error::Error for PaneSplitterResizePlanError {}
1005
1006/// Errors while planning reflow moves and docking previews.
1007#[derive(Debug, Clone, PartialEq, Eq)]
1008pub enum PaneReflowPlanError {
1009    MissingSource { source: PaneId },
1010    NoDockTarget,
1011    SourceCannotMoveRoot { source: PaneId },
1012    InvalidRatio { numerator: u32, denominator: u32 },
1013}
1014
1015impl fmt::Display for PaneReflowPlanError {
1016    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1017        match self {
1018            Self::MissingSource { source } => write!(f, "source node {} not found", source.get()),
1019            Self::NoDockTarget => write!(f, "no magnetic docking target available"),
1020            Self::SourceCannotMoveRoot { source } => {
1021                write!(
1022                    f,
1023                    "source node {} is root and cannot be reflow-moved",
1024                    source.get()
1025                )
1026            }
1027            Self::InvalidRatio {
1028                numerator,
1029                denominator,
1030            } => write!(f, "invalid reflow ratio {numerator}/{denominator}"),
1031        }
1032    }
1033}
1034
1035impl std::error::Error for PaneReflowPlanError {}
1036
1037/// Multi-pane selection state for group interactions.
1038#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
1039pub struct PaneSelectionState {
1040    pub anchor: Option<PaneId>,
1041    pub selected: BTreeSet<PaneId>,
1042}
1043
1044/// Planned group transform preserving the internal cluster.
1045#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1046pub struct PaneGroupTransformPlan {
1047    pub members: Vec<PaneId>,
1048    pub operations: Vec<PaneOperation>,
1049}
1050
1051impl PaneSelectionState {
1052    /// Toggle selection with shift-like additive semantics.
1053    pub fn shift_toggle(&mut self, pane_id: PaneId) {
1054        if self.selected.contains(&pane_id) {
1055            let _ = self.selected.remove(&pane_id);
1056            if self.anchor == Some(pane_id) {
1057                self.anchor = self.selected.iter().next().copied();
1058            }
1059        } else {
1060            let _ = self.selected.insert(pane_id);
1061            if self.anchor.is_none() {
1062                self.anchor = Some(pane_id);
1063            }
1064        }
1065    }
1066
1067    #[must_use]
1068    pub fn as_sorted_vec(&self) -> Vec<PaneId> {
1069        self.selected.iter().copied().collect()
1070    }
1071
1072    #[must_use]
1073    pub fn is_empty(&self) -> bool {
1074        self.selected.is_empty()
1075    }
1076}
1077
1078/// High-level adaptive layout topology modes.
1079#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1080#[serde(rename_all = "snake_case")]
1081pub enum PaneLayoutIntelligenceMode {
1082    Focus,
1083    Compare,
1084    Monitor,
1085    Compact,
1086}
1087
1088/// One persistent timeline event for deterministic undo/redo/replay.
1089#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1090pub struct PaneInteractionTimelineEntry {
1091    pub sequence: u64,
1092    pub operation_id: u64,
1093    pub operation: PaneOperation,
1094    pub before_hash: u64,
1095    pub after_hash: u64,
1096}
1097
1098/// One replay checkpoint in the interaction timeline.
1099#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1100pub struct PaneInteractionTimelineCheckpoint {
1101    pub applied_len: usize,
1102    pub snapshot: PaneTreeSnapshot,
1103}
1104
1105/// Replay diagnostics for the currently selected timeline cursor.
1106#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1107pub struct PaneInteractionTimelineReplayDiagnostics {
1108    pub entry_count: usize,
1109    pub cursor: usize,
1110    pub checkpoint_count: usize,
1111    pub checkpoint_interval: usize,
1112    pub checkpoint_hit: bool,
1113    pub replay_start_idx: usize,
1114    pub replay_depth: usize,
1115}
1116
1117/// Auditable checkpoint-spacing decision derived from measured replay costs.
1118#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1119pub struct PaneInteractionTimelineCheckpointDecision {
1120    pub checkpoint_interval: usize,
1121    pub estimated_snapshot_cost_ns: u128,
1122    pub estimated_replay_step_cost_ns: u128,
1123    pub estimated_replay_depth_ns: u128,
1124}
1125
1126/// Deterministic retained-state telemetry for pane timeline memory analysis.
1127///
1128/// Byte counts are conservative shallow estimates plus explicitly tracked
1129/// payload bytes. They are intended for comparing timeline strategies and
1130/// retention policies, not for replacing allocator-level profiling.
1131#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1132pub struct PaneInteractionTimelineRetentionDiagnostics {
1133    pub entry_count: usize,
1134    pub cursor: usize,
1135    pub redo_entry_count: usize,
1136    pub checkpoint_count: usize,
1137    pub checkpoint_interval: usize,
1138    pub max_entries: usize,
1139    pub baseline_present: bool,
1140    pub retained_snapshot_count: usize,
1141    pub baseline_node_count: usize,
1142    pub checkpoint_node_count: usize,
1143    pub retained_snapshot_node_count: usize,
1144    pub retained_leaf_payload_bytes: usize,
1145    pub retained_extension_entry_count: usize,
1146    pub retained_extension_payload_bytes: usize,
1147    pub retained_operation_payload_bytes: usize,
1148    pub estimated_entry_struct_bytes: usize,
1149    pub estimated_checkpoint_struct_bytes: usize,
1150    pub estimated_snapshot_struct_bytes: usize,
1151    pub estimated_total_retained_bytes: usize,
1152}
1153
1154/// Persistent interaction timeline with undo/redo cursor.
1155#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1156pub struct PaneInteractionTimeline {
1157    /// Baseline tree before first recorded mutation.
1158    pub baseline: Option<PaneTreeSnapshot>,
1159    /// Full operation history in deterministic order.
1160    pub entries: Vec<PaneInteractionTimelineEntry>,
1161    /// Number of entries currently applied (<= entries.len()).
1162    pub cursor: usize,
1163    /// Deterministic replay checkpoints keyed by applied_len.
1164    pub checkpoints: Vec<PaneInteractionTimelineCheckpoint>,
1165    /// Entry spacing used when materializing checkpoints.
1166    pub checkpoint_interval: usize,
1167    /// Maximum retained history entries. A value of 0 disables pruning.
1168    #[serde(default = "default_pane_timeline_max_entries")]
1169    pub max_entries: usize,
1170}
1171
1172const DEFAULT_PANE_TIMELINE_CHECKPOINT_INTERVAL: usize = 16;
1173const DEFAULT_PANE_TIMELINE_MAX_ENTRIES: usize = 4096;
1174
1175fn default_pane_timeline_max_entries() -> usize {
1176    DEFAULT_PANE_TIMELINE_MAX_ENTRIES
1177}
1178
1179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1180enum PaneValidationStrategy {
1181    FullTree,
1182    LocalClosure,
1183}
1184
1185/// Validation mode for pane operation application.
1186///
1187/// `Adaptive` lets each operation's [`PaneOperationFamily`] pick the cheapest
1188/// sound validator (local-closure for `Local`, whole-tree for `Structural`).
1189/// `AlwaysFull` forces the conservative whole-tree validator regardless of
1190/// family, which is the easy-to-force baseline used for diagnosis, rollback,
1191/// rollout, and as the differential oracle for the certified fast paths.
1192#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1193enum PaneValidationMode {
1194    #[default]
1195    Adaptive,
1196    AlwaysFull,
1197}
1198
1199impl Default for PaneInteractionTimeline {
1200    fn default() -> Self {
1201        Self {
1202            baseline: None,
1203            entries: Vec::new(),
1204            cursor: 0,
1205            checkpoints: Vec::new(),
1206            checkpoint_interval: DEFAULT_PANE_TIMELINE_CHECKPOINT_INTERVAL,
1207            max_entries: DEFAULT_PANE_TIMELINE_MAX_ENTRIES,
1208        }
1209    }
1210}
1211
1212/// Timeline replay/undo/redo failures.
1213#[derive(Debug, Clone, PartialEq, Eq)]
1214pub enum PaneInteractionTimelineError {
1215    MissingBaseline,
1216    BaselineInvalid { source: PaneModelError },
1217    ApplyFailed { source: PaneOperationError },
1218}
1219
1220impl fmt::Display for PaneInteractionTimelineError {
1221    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1222        match self {
1223            Self::MissingBaseline => write!(f, "timeline baseline is not set"),
1224            Self::BaselineInvalid { source } => {
1225                write!(f, "failed to restore timeline baseline: {source}")
1226            }
1227            Self::ApplyFailed { source } => write!(f, "timeline replay operation failed: {source}"),
1228        }
1229    }
1230}
1231
1232impl std::error::Error for PaneInteractionTimelineError {
1233    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1234        match self {
1235            Self::BaselineInvalid { source } => Some(source),
1236            Self::ApplyFailed { source } => Some(source),
1237            Self::MissingBaseline => None,
1238        }
1239    }
1240}
1241
1242/// Placement of an incoming node relative to an existing node inside a split.
1243#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1244#[serde(rename_all = "snake_case")]
1245pub enum PanePlacement {
1246    ExistingFirst,
1247    IncomingFirst,
1248}
1249
1250impl PanePlacement {
1251    fn ordered(self, existing: PaneId, incoming: PaneId) -> (PaneId, PaneId) {
1252        match self {
1253            Self::ExistingFirst => (existing, incoming),
1254            Self::IncomingFirst => (incoming, existing),
1255        }
1256    }
1257}
1258
1259/// Pointer button for pane interaction events.
1260#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1261#[serde(rename_all = "snake_case")]
1262pub enum PanePointerButton {
1263    Primary,
1264    Secondary,
1265    Middle,
1266}
1267
1268/// Normalized interaction position in pane-local coordinates.
1269#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1270pub struct PanePointerPosition {
1271    pub x: i32,
1272    pub y: i32,
1273}
1274
1275impl PanePointerPosition {
1276    #[must_use]
1277    pub const fn new(x: i32, y: i32) -> Self {
1278        Self { x, y }
1279    }
1280}
1281
1282/// Snapshot of active modifiers captured with one semantic event.
1283#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1284pub struct PaneModifierSnapshot {
1285    pub shift: bool,
1286    pub alt: bool,
1287    pub ctrl: bool,
1288    pub meta: bool,
1289}
1290
1291impl PaneModifierSnapshot {
1292    #[must_use]
1293    pub const fn none() -> Self {
1294        Self {
1295            shift: false,
1296            alt: false,
1297            ctrl: false,
1298            meta: false,
1299        }
1300    }
1301}
1302
1303impl Default for PaneModifierSnapshot {
1304    fn default() -> Self {
1305        Self::none()
1306    }
1307}
1308
1309/// Canonical resize target for semantic pane input events.
1310#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1311pub struct PaneResizeTarget {
1312    pub split_id: PaneId,
1313    pub axis: SplitAxis,
1314}
1315
1316/// Direction for semantic resize commands.
1317#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1318#[serde(rename_all = "snake_case")]
1319pub enum PaneResizeDirection {
1320    Increase,
1321    Decrease,
1322}
1323
1324/// Canonical cancel reasons for pane interaction state machines.
1325#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1326#[serde(rename_all = "snake_case")]
1327pub enum PaneCancelReason {
1328    EscapeKey,
1329    PointerCancel,
1330    FocusLost,
1331    Blur,
1332    Programmatic,
1333    ContextLost,
1334    RenderStalled,
1335}
1336
1337/// Versioned semantic pane interaction event kind.
1338#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1339#[serde(tag = "event", rename_all = "snake_case")]
1340pub enum PaneSemanticInputEventKind {
1341    PointerDown {
1342        target: PaneResizeTarget,
1343        pointer_id: u32,
1344        button: PanePointerButton,
1345        position: PanePointerPosition,
1346    },
1347    PointerMove {
1348        target: PaneResizeTarget,
1349        pointer_id: u32,
1350        position: PanePointerPosition,
1351        delta_x: i32,
1352        delta_y: i32,
1353    },
1354    PointerUp {
1355        target: PaneResizeTarget,
1356        pointer_id: u32,
1357        button: PanePointerButton,
1358        position: PanePointerPosition,
1359    },
1360    WheelNudge {
1361        target: PaneResizeTarget,
1362        lines: i16,
1363    },
1364    KeyboardResize {
1365        target: PaneResizeTarget,
1366        direction: PaneResizeDirection,
1367        units: u16,
1368    },
1369    Cancel {
1370        target: Option<PaneResizeTarget>,
1371        reason: PaneCancelReason,
1372    },
1373    Blur {
1374        target: Option<PaneResizeTarget>,
1375    },
1376}
1377
1378/// Versioned semantic pane interaction event consumed by pane-core and emitted
1379/// by host adapters.
1380#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1381pub struct PaneSemanticInputEvent {
1382    #[serde(default = "default_pane_semantic_input_event_schema_version")]
1383    pub schema_version: u16,
1384    pub sequence: u64,
1385    #[serde(default)]
1386    pub modifiers: PaneModifierSnapshot,
1387    #[serde(flatten)]
1388    pub kind: PaneSemanticInputEventKind,
1389    #[serde(default)]
1390    pub extensions: BTreeMap<String, String>,
1391}
1392
1393fn default_pane_semantic_input_event_schema_version() -> u16 {
1394    PANE_SEMANTIC_INPUT_EVENT_SCHEMA_VERSION
1395}
1396
1397impl PaneSemanticInputEvent {
1398    /// Build a schema-versioned semantic pane input event.
1399    #[must_use]
1400    pub fn new(sequence: u64, kind: PaneSemanticInputEventKind) -> Self {
1401        Self {
1402            schema_version: PANE_SEMANTIC_INPUT_EVENT_SCHEMA_VERSION,
1403            sequence,
1404            modifiers: PaneModifierSnapshot::default(),
1405            kind,
1406            extensions: BTreeMap::new(),
1407        }
1408    }
1409
1410    /// Validate event invariants required for deterministic replay.
1411    pub fn validate(&self) -> Result<(), PaneSemanticInputEventError> {
1412        if self.schema_version != PANE_SEMANTIC_INPUT_EVENT_SCHEMA_VERSION {
1413            return Err(PaneSemanticInputEventError::UnsupportedSchemaVersion {
1414                version: self.schema_version,
1415                expected: PANE_SEMANTIC_INPUT_EVENT_SCHEMA_VERSION,
1416            });
1417        }
1418        if self.sequence == 0 {
1419            return Err(PaneSemanticInputEventError::ZeroSequence);
1420        }
1421
1422        match self.kind {
1423            PaneSemanticInputEventKind::PointerDown { pointer_id, .. }
1424            | PaneSemanticInputEventKind::PointerMove { pointer_id, .. }
1425            | PaneSemanticInputEventKind::PointerUp { pointer_id, .. } => {
1426                if pointer_id == 0 {
1427                    return Err(PaneSemanticInputEventError::ZeroPointerId);
1428                }
1429            }
1430            PaneSemanticInputEventKind::WheelNudge { lines, .. } => {
1431                if lines == 0 {
1432                    return Err(PaneSemanticInputEventError::ZeroWheelLines);
1433                }
1434            }
1435            PaneSemanticInputEventKind::KeyboardResize { units, .. } => {
1436                if units == 0 {
1437                    return Err(PaneSemanticInputEventError::ZeroResizeUnits);
1438                }
1439            }
1440            PaneSemanticInputEventKind::Cancel { .. } | PaneSemanticInputEventKind::Blur { .. } => {
1441            }
1442        }
1443
1444        Ok(())
1445    }
1446}
1447
1448/// Validation failures for semantic pane input events.
1449#[derive(Debug, Clone, PartialEq, Eq)]
1450pub enum PaneSemanticInputEventError {
1451    UnsupportedSchemaVersion { version: u16, expected: u16 },
1452    ZeroSequence,
1453    ZeroPointerId,
1454    ZeroWheelLines,
1455    ZeroResizeUnits,
1456}
1457
1458impl fmt::Display for PaneSemanticInputEventError {
1459    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1460        match self {
1461            Self::UnsupportedSchemaVersion { version, expected } => write!(
1462                f,
1463                "unsupported pane semantic input schema version {version} (expected {expected})"
1464            ),
1465            Self::ZeroSequence => write!(f, "semantic pane input event sequence must be non-zero"),
1466            Self::ZeroPointerId => {
1467                write!(
1468                    f,
1469                    "semantic pane pointer events require non-zero pointer_id"
1470                )
1471            }
1472            Self::ZeroWheelLines => write!(f, "semantic pane wheel nudge must be non-zero"),
1473            Self::ZeroResizeUnits => {
1474                write!(f, "semantic pane keyboard resize units must be non-zero")
1475            }
1476        }
1477    }
1478}
1479
1480impl std::error::Error for PaneSemanticInputEventError {}
1481
1482/// Metadata carried alongside semantic replay traces.
1483#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1484pub struct PaneSemanticInputTraceMetadata {
1485    #[serde(default = "default_pane_semantic_input_trace_schema_version")]
1486    pub schema_version: u16,
1487    pub seed: u64,
1488    pub start_unix_ms: u64,
1489    #[serde(default)]
1490    pub host: String,
1491    pub checksum: u64,
1492}
1493
1494fn default_pane_semantic_input_trace_schema_version() -> u16 {
1495    PANE_SEMANTIC_INPUT_TRACE_SCHEMA_VERSION
1496}
1497
1498/// Canonical replay trace for semantic pane input streams.
1499#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1500pub struct PaneSemanticInputTrace {
1501    pub metadata: PaneSemanticInputTraceMetadata,
1502    #[serde(default)]
1503    pub events: Vec<PaneSemanticInputEvent>,
1504}
1505
1506impl PaneSemanticInputTrace {
1507    /// Build a canonical semantic input trace and compute its checksum.
1508    pub fn new(
1509        seed: u64,
1510        start_unix_ms: u64,
1511        host: impl Into<String>,
1512        events: Vec<PaneSemanticInputEvent>,
1513    ) -> Result<Self, PaneSemanticInputTraceError> {
1514        let mut trace = Self {
1515            metadata: PaneSemanticInputTraceMetadata {
1516                schema_version: PANE_SEMANTIC_INPUT_TRACE_SCHEMA_VERSION,
1517                seed,
1518                start_unix_ms,
1519                host: host.into(),
1520                checksum: 0,
1521            },
1522            events,
1523        };
1524        trace.metadata.checksum = trace.recompute_checksum();
1525        trace.validate()?;
1526        Ok(trace)
1527    }
1528
1529    /// Deterministically recompute the checksum over trace payload fields.
1530    #[must_use]
1531    pub fn recompute_checksum(&self) -> u64 {
1532        pane_semantic_input_trace_checksum_payload(&self.metadata, &self.events)
1533    }
1534
1535    /// Validate schema/version, event ordering, and checksum invariants.
1536    pub fn validate(&self) -> Result<(), PaneSemanticInputTraceError> {
1537        if self.metadata.schema_version != PANE_SEMANTIC_INPUT_TRACE_SCHEMA_VERSION {
1538            return Err(PaneSemanticInputTraceError::UnsupportedSchemaVersion {
1539                version: self.metadata.schema_version,
1540                expected: PANE_SEMANTIC_INPUT_TRACE_SCHEMA_VERSION,
1541            });
1542        }
1543        if self.events.is_empty() {
1544            return Err(PaneSemanticInputTraceError::EmptyEvents);
1545        }
1546
1547        let mut previous_sequence = 0_u64;
1548        for (index, event) in self.events.iter().enumerate() {
1549            event
1550                .validate()
1551                .map_err(|source| PaneSemanticInputTraceError::InvalidEvent { index, source })?;
1552
1553            if index > 0 && event.sequence <= previous_sequence {
1554                return Err(PaneSemanticInputTraceError::SequenceOutOfOrder {
1555                    index,
1556                    previous: previous_sequence,
1557                    current: event.sequence,
1558                });
1559            }
1560            previous_sequence = event.sequence;
1561        }
1562
1563        let computed = self.recompute_checksum();
1564        if self.metadata.checksum != computed {
1565            return Err(PaneSemanticInputTraceError::ChecksumMismatch {
1566                recorded: self.metadata.checksum,
1567                computed,
1568            });
1569        }
1570
1571        Ok(())
1572    }
1573
1574    /// Replay a semantic trace through a drag/resize machine.
1575    pub fn replay(
1576        &self,
1577        machine: &mut PaneDragResizeMachine,
1578    ) -> Result<PaneSemanticReplayOutcome, PaneSemanticReplayError> {
1579        self.validate()
1580            .map_err(PaneSemanticReplayError::InvalidTrace)?;
1581
1582        let mut transitions = Vec::with_capacity(self.events.len());
1583        for event in &self.events {
1584            let transition = machine
1585                .apply_event(event)
1586                .map_err(PaneSemanticReplayError::Machine)?;
1587            transitions.push(transition);
1588        }
1589
1590        Ok(PaneSemanticReplayOutcome {
1591            trace_checksum: self.metadata.checksum,
1592            transitions,
1593            final_state: machine.state(),
1594        })
1595    }
1596}
1597
1598/// Validation failures for semantic replay trace payloads.
1599#[derive(Debug, Clone, PartialEq, Eq)]
1600pub enum PaneSemanticInputTraceError {
1601    UnsupportedSchemaVersion {
1602        version: u16,
1603        expected: u16,
1604    },
1605    EmptyEvents,
1606    SequenceOutOfOrder {
1607        index: usize,
1608        previous: u64,
1609        current: u64,
1610    },
1611    InvalidEvent {
1612        index: usize,
1613        source: PaneSemanticInputEventError,
1614    },
1615    ChecksumMismatch {
1616        recorded: u64,
1617        computed: u64,
1618    },
1619}
1620
1621impl fmt::Display for PaneSemanticInputTraceError {
1622    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1623        match self {
1624            Self::UnsupportedSchemaVersion { version, expected } => write!(
1625                f,
1626                "unsupported pane semantic input trace schema version {version} (expected {expected})"
1627            ),
1628            Self::EmptyEvents => write!(
1629                f,
1630                "semantic pane input trace must contain at least one event"
1631            ),
1632            Self::SequenceOutOfOrder {
1633                index,
1634                previous,
1635                current,
1636            } => write!(
1637                f,
1638                "semantic pane input trace sequence out of order at index {index} ({current} <= {previous})"
1639            ),
1640            Self::InvalidEvent { index, source } => {
1641                write!(
1642                    f,
1643                    "semantic pane input trace contains invalid event at index {index}: {source}"
1644                )
1645            }
1646            Self::ChecksumMismatch { recorded, computed } => write!(
1647                f,
1648                "semantic pane input trace checksum mismatch (recorded={recorded:#x}, computed={computed:#x})"
1649            ),
1650        }
1651    }
1652}
1653
1654impl std::error::Error for PaneSemanticInputTraceError {}
1655
1656/// Replay output from running one trace through a pane interaction machine.
1657#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1658pub struct PaneSemanticReplayOutcome {
1659    pub trace_checksum: u64,
1660    pub transitions: Vec<PaneDragResizeTransition>,
1661    pub final_state: PaneDragResizeState,
1662}
1663
1664/// Classification for replay conformance differences.
1665#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1666#[serde(rename_all = "snake_case")]
1667pub enum PaneSemanticReplayDiffKind {
1668    TransitionMismatch,
1669    MissingExpectedTransition,
1670    UnexpectedTransition,
1671    FinalStateMismatch,
1672}
1673
1674/// One structured replay conformance difference artifact.
1675#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1676pub struct PaneSemanticReplayDiffArtifact {
1677    pub kind: PaneSemanticReplayDiffKind,
1678    pub index: Option<usize>,
1679    pub expected_transition: Option<PaneDragResizeTransition>,
1680    pub actual_transition: Option<PaneDragResizeTransition>,
1681    pub expected_final_state: Option<PaneDragResizeState>,
1682    pub actual_final_state: Option<PaneDragResizeState>,
1683}
1684
1685/// Conformance comparison output for replay fixtures.
1686#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1687pub struct PaneSemanticReplayConformanceArtifact {
1688    pub trace_checksum: u64,
1689    pub passed: bool,
1690    pub diffs: Vec<PaneSemanticReplayDiffArtifact>,
1691}
1692
1693impl PaneSemanticReplayConformanceArtifact {
1694    /// Compare replay output against expected transitions/final state.
1695    #[must_use]
1696    pub fn compare(
1697        outcome: &PaneSemanticReplayOutcome,
1698        expected_transitions: &[PaneDragResizeTransition],
1699        expected_final_state: PaneDragResizeState,
1700    ) -> Self {
1701        let mut diffs = Vec::new();
1702        let max_len = expected_transitions.len().max(outcome.transitions.len());
1703
1704        for index in 0..max_len {
1705            let expected = expected_transitions.get(index);
1706            let actual = outcome.transitions.get(index);
1707
1708            match (expected, actual) {
1709                (Some(expected_transition), Some(actual_transition))
1710                    if expected_transition != actual_transition =>
1711                {
1712                    diffs.push(PaneSemanticReplayDiffArtifact {
1713                        kind: PaneSemanticReplayDiffKind::TransitionMismatch,
1714                        index: Some(index),
1715                        expected_transition: Some(expected_transition.clone()),
1716                        actual_transition: Some(actual_transition.clone()),
1717                        expected_final_state: None,
1718                        actual_final_state: None,
1719                    });
1720                }
1721                (Some(expected_transition), None) => {
1722                    diffs.push(PaneSemanticReplayDiffArtifact {
1723                        kind: PaneSemanticReplayDiffKind::MissingExpectedTransition,
1724                        index: Some(index),
1725                        expected_transition: Some(expected_transition.clone()),
1726                        actual_transition: None,
1727                        expected_final_state: None,
1728                        actual_final_state: None,
1729                    });
1730                }
1731                (None, Some(actual_transition)) => {
1732                    diffs.push(PaneSemanticReplayDiffArtifact {
1733                        kind: PaneSemanticReplayDiffKind::UnexpectedTransition,
1734                        index: Some(index),
1735                        expected_transition: None,
1736                        actual_transition: Some(actual_transition.clone()),
1737                        expected_final_state: None,
1738                        actual_final_state: None,
1739                    });
1740                }
1741                (Some(_), Some(_)) | (None, None) => {}
1742            }
1743        }
1744
1745        if outcome.final_state != expected_final_state {
1746            diffs.push(PaneSemanticReplayDiffArtifact {
1747                kind: PaneSemanticReplayDiffKind::FinalStateMismatch,
1748                index: None,
1749                expected_transition: None,
1750                actual_transition: None,
1751                expected_final_state: Some(expected_final_state),
1752                actual_final_state: Some(outcome.final_state),
1753            });
1754        }
1755
1756        Self {
1757            trace_checksum: outcome.trace_checksum,
1758            passed: diffs.is_empty(),
1759            diffs,
1760        }
1761    }
1762}
1763
1764/// Golden fixture shape for replay conformance runs.
1765#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1766pub struct PaneSemanticReplayFixture {
1767    pub trace: PaneSemanticInputTrace,
1768    #[serde(default)]
1769    pub expected_transitions: Vec<PaneDragResizeTransition>,
1770    pub expected_final_state: PaneDragResizeState,
1771}
1772
1773impl PaneSemanticReplayFixture {
1774    /// Run one replay fixture and emit structured conformance artifacts.
1775    pub fn run(
1776        &self,
1777        machine: &mut PaneDragResizeMachine,
1778    ) -> Result<PaneSemanticReplayConformanceArtifact, PaneSemanticReplayError> {
1779        let outcome = self.trace.replay(machine)?;
1780        Ok(PaneSemanticReplayConformanceArtifact::compare(
1781            &outcome,
1782            &self.expected_transitions,
1783            self.expected_final_state,
1784        ))
1785    }
1786}
1787
1788/// Replay runner failures.
1789#[derive(Debug, Clone, PartialEq, Eq)]
1790pub enum PaneSemanticReplayError {
1791    InvalidTrace(PaneSemanticInputTraceError),
1792    Machine(PaneDragResizeMachineError),
1793}
1794
1795impl fmt::Display for PaneSemanticReplayError {
1796    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1797        match self {
1798            Self::InvalidTrace(source) => write!(f, "invalid semantic replay trace: {source}"),
1799            Self::Machine(source) => write!(f, "pane drag/resize machine replay failed: {source}"),
1800        }
1801    }
1802}
1803
1804impl std::error::Error for PaneSemanticReplayError {}
1805
1806fn pane_semantic_input_trace_checksum_payload(
1807    metadata: &PaneSemanticInputTraceMetadata,
1808    events: &[PaneSemanticInputEvent],
1809) -> u64 {
1810    const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
1811    const PRIME: u64 = 0x0000_0001_0000_01b3;
1812
1813    fn mix(hash: &mut u64, byte: u8) {
1814        *hash ^= u64::from(byte);
1815        *hash = hash.wrapping_mul(PRIME);
1816    }
1817
1818    fn mix_bytes(hash: &mut u64, bytes: &[u8]) {
1819        for byte in bytes {
1820            mix(hash, *byte);
1821        }
1822    }
1823
1824    fn mix_u16(hash: &mut u64, value: u16) {
1825        mix_bytes(hash, &value.to_le_bytes());
1826    }
1827
1828    fn mix_u32(hash: &mut u64, value: u32) {
1829        mix_bytes(hash, &value.to_le_bytes());
1830    }
1831
1832    fn mix_i32(hash: &mut u64, value: i32) {
1833        mix_bytes(hash, &value.to_le_bytes());
1834    }
1835
1836    fn mix_u64(hash: &mut u64, value: u64) {
1837        mix_bytes(hash, &value.to_le_bytes());
1838    }
1839
1840    fn mix_i16(hash: &mut u64, value: i16) {
1841        mix_bytes(hash, &value.to_le_bytes());
1842    }
1843
1844    fn mix_bool(hash: &mut u64, value: bool) {
1845        mix(hash, u8::from(value));
1846    }
1847
1848    fn mix_str(hash: &mut u64, value: &str) {
1849        mix_u64(hash, value.len() as u64);
1850        mix_bytes(hash, value.as_bytes());
1851    }
1852
1853    fn mix_extensions(hash: &mut u64, extensions: &BTreeMap<String, String>) {
1854        mix_u64(hash, extensions.len() as u64);
1855        for (key, value) in extensions {
1856            mix_str(hash, key);
1857            mix_str(hash, value);
1858        }
1859    }
1860
1861    fn mix_target(hash: &mut u64, target: PaneResizeTarget) {
1862        mix_u64(hash, target.split_id.get());
1863        let axis = match target.axis {
1864            SplitAxis::Horizontal => 1,
1865            SplitAxis::Vertical => 2,
1866        };
1867        mix(hash, axis);
1868    }
1869
1870    fn mix_position(hash: &mut u64, position: PanePointerPosition) {
1871        mix_i32(hash, position.x);
1872        mix_i32(hash, position.y);
1873    }
1874
1875    fn mix_optional_target(hash: &mut u64, target: Option<PaneResizeTarget>) {
1876        match target {
1877            Some(target) => {
1878                mix(hash, 1);
1879                mix_target(hash, target);
1880            }
1881            None => mix(hash, 0),
1882        }
1883    }
1884
1885    fn mix_pointer_button(hash: &mut u64, button: PanePointerButton) {
1886        let value = match button {
1887            PanePointerButton::Primary => 1,
1888            PanePointerButton::Secondary => 2,
1889            PanePointerButton::Middle => 3,
1890        };
1891        mix(hash, value);
1892    }
1893
1894    fn mix_resize_direction(hash: &mut u64, direction: PaneResizeDirection) {
1895        let value = match direction {
1896            PaneResizeDirection::Increase => 1,
1897            PaneResizeDirection::Decrease => 2,
1898        };
1899        mix(hash, value);
1900    }
1901
1902    fn mix_cancel_reason(hash: &mut u64, reason: PaneCancelReason) {
1903        let value = match reason {
1904            PaneCancelReason::EscapeKey => 1,
1905            PaneCancelReason::PointerCancel => 2,
1906            PaneCancelReason::FocusLost => 3,
1907            PaneCancelReason::Blur => 4,
1908            PaneCancelReason::Programmatic => 5,
1909            PaneCancelReason::ContextLost => 6,
1910            PaneCancelReason::RenderStalled => 7,
1911        };
1912        mix(hash, value);
1913    }
1914
1915    let mut hash = OFFSET_BASIS;
1916    mix_u16(&mut hash, metadata.schema_version);
1917    mix_u64(&mut hash, metadata.seed);
1918    mix_u64(&mut hash, metadata.start_unix_ms);
1919    mix_str(&mut hash, &metadata.host);
1920    mix_u64(&mut hash, events.len() as u64);
1921
1922    for event in events {
1923        mix_u16(&mut hash, event.schema_version);
1924        mix_u64(&mut hash, event.sequence);
1925        mix_bool(&mut hash, event.modifiers.shift);
1926        mix_bool(&mut hash, event.modifiers.alt);
1927        mix_bool(&mut hash, event.modifiers.ctrl);
1928        mix_bool(&mut hash, event.modifiers.meta);
1929        mix_extensions(&mut hash, &event.extensions);
1930
1931        match event.kind {
1932            PaneSemanticInputEventKind::PointerDown {
1933                target,
1934                pointer_id,
1935                button,
1936                position,
1937            } => {
1938                mix(&mut hash, 1);
1939                mix_target(&mut hash, target);
1940                mix_u32(&mut hash, pointer_id);
1941                mix_pointer_button(&mut hash, button);
1942                mix_position(&mut hash, position);
1943            }
1944            PaneSemanticInputEventKind::PointerMove {
1945                target,
1946                pointer_id,
1947                position,
1948                delta_x,
1949                delta_y,
1950            } => {
1951                mix(&mut hash, 2);
1952                mix_target(&mut hash, target);
1953                mix_u32(&mut hash, pointer_id);
1954                mix_position(&mut hash, position);
1955                mix_i32(&mut hash, delta_x);
1956                mix_i32(&mut hash, delta_y);
1957            }
1958            PaneSemanticInputEventKind::PointerUp {
1959                target,
1960                pointer_id,
1961                button,
1962                position,
1963            } => {
1964                mix(&mut hash, 3);
1965                mix_target(&mut hash, target);
1966                mix_u32(&mut hash, pointer_id);
1967                mix_pointer_button(&mut hash, button);
1968                mix_position(&mut hash, position);
1969            }
1970            PaneSemanticInputEventKind::WheelNudge { target, lines } => {
1971                mix(&mut hash, 4);
1972                mix_target(&mut hash, target);
1973                mix_i16(&mut hash, lines);
1974            }
1975            PaneSemanticInputEventKind::KeyboardResize {
1976                target,
1977                direction,
1978                units,
1979            } => {
1980                mix(&mut hash, 5);
1981                mix_target(&mut hash, target);
1982                mix_resize_direction(&mut hash, direction);
1983                mix_u16(&mut hash, units);
1984            }
1985            PaneSemanticInputEventKind::Cancel { target, reason } => {
1986                mix(&mut hash, 6);
1987                mix_optional_target(&mut hash, target);
1988                mix_cancel_reason(&mut hash, reason);
1989            }
1990            PaneSemanticInputEventKind::Blur { target } => {
1991                mix(&mut hash, 7);
1992                mix_optional_target(&mut hash, target);
1993            }
1994        }
1995    }
1996
1997    hash
1998}
1999
2000/// Rational scale factor used for deterministic coordinate transforms.
2001#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2002pub struct PaneScaleFactor {
2003    numerator: u32,
2004    denominator: u32,
2005}
2006
2007impl PaneScaleFactor {
2008    /// Identity scale (`1/1`).
2009    pub const ONE: Self = Self {
2010        numerator: 1,
2011        denominator: 1,
2012    };
2013
2014    /// Build and normalize a rational scale factor.
2015    pub fn new(numerator: u32, denominator: u32) -> Result<Self, PaneCoordinateNormalizationError> {
2016        if numerator == 0 || denominator == 0 {
2017            return Err(PaneCoordinateNormalizationError::InvalidScaleFactor {
2018                field: "scale_factor",
2019                numerator,
2020                denominator,
2021            });
2022        }
2023        let gcd = gcd_u32(numerator, denominator);
2024        Ok(Self {
2025            numerator: numerator / gcd,
2026            denominator: denominator / gcd,
2027        })
2028    }
2029
2030    fn validate(self, field: &'static str) -> Result<(), PaneCoordinateNormalizationError> {
2031        if self.numerator == 0 || self.denominator == 0 {
2032            return Err(PaneCoordinateNormalizationError::InvalidScaleFactor {
2033                field,
2034                numerator: self.numerator,
2035                denominator: self.denominator,
2036            });
2037        }
2038        Ok(())
2039    }
2040
2041    #[must_use]
2042    pub const fn numerator(self) -> u32 {
2043        if self.numerator == 0 {
2044            1
2045        } else {
2046            self.numerator
2047        }
2048    }
2049
2050    #[must_use]
2051    pub const fn denominator(self) -> u32 {
2052        if self.denominator == 0 {
2053            1
2054        } else {
2055            self.denominator
2056        }
2057    }
2058}
2059
2060impl Default for PaneScaleFactor {
2061    fn default() -> Self {
2062        Self::ONE
2063    }
2064}
2065
2066/// Deterministic rounding policy for coordinate normalization.
2067#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
2068#[serde(rename_all = "snake_case")]
2069pub enum PaneCoordinateRoundingPolicy {
2070    /// Round toward negative infinity (`floor`).
2071    #[default]
2072    TowardNegativeInfinity,
2073    /// Round to nearest value; exact half-way ties resolve toward negative infinity.
2074    NearestHalfTowardNegativeInfinity,
2075}
2076
2077/// Input coordinate source variants accepted by pane normalization.
2078#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2079#[serde(tag = "source", rename_all = "snake_case")]
2080pub enum PaneInputCoordinate {
2081    /// Absolute CSS pixel coordinates.
2082    CssPixels { position: PanePointerPosition },
2083    /// Absolute device pixel coordinates.
2084    DevicePixels { position: PanePointerPosition },
2085    /// Viewport-local cell coordinates.
2086    Cell { position: PanePointerPosition },
2087}
2088
2089/// Deterministic normalized coordinate payload used by pane interaction layers.
2090#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2091pub struct PaneNormalizedCoordinate {
2092    /// Canonical global cell coordinate (viewport offset applied).
2093    pub global_cell: PanePointerPosition,
2094    /// Viewport-local cell coordinate.
2095    pub local_cell: PanePointerPosition,
2096    /// Normalized viewport-local CSS coordinate after DPR/zoom conversion.
2097    pub local_css: PanePointerPosition,
2098}
2099
2100/// Coordinate normalization configuration and transform pipeline.
2101#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2102pub struct PaneCoordinateNormalizer {
2103    pub viewport_origin_css: PanePointerPosition,
2104    pub viewport_origin_cells: PanePointerPosition,
2105    pub cell_width_css: u16,
2106    pub cell_height_css: u16,
2107    pub dpr: PaneScaleFactor,
2108    pub zoom: PaneScaleFactor,
2109    #[serde(default)]
2110    pub rounding: PaneCoordinateRoundingPolicy,
2111}
2112
2113impl PaneCoordinateNormalizer {
2114    /// Construct a validated coordinate normalizer.
2115    pub fn new(
2116        viewport_origin_css: PanePointerPosition,
2117        viewport_origin_cells: PanePointerPosition,
2118        cell_width_css: u16,
2119        cell_height_css: u16,
2120        dpr: PaneScaleFactor,
2121        zoom: PaneScaleFactor,
2122        rounding: PaneCoordinateRoundingPolicy,
2123    ) -> Result<Self, PaneCoordinateNormalizationError> {
2124        if cell_width_css == 0 || cell_height_css == 0 {
2125            return Err(PaneCoordinateNormalizationError::InvalidCellSize {
2126                width: cell_width_css,
2127                height: cell_height_css,
2128            });
2129        }
2130        dpr.validate("dpr")?;
2131        zoom.validate("zoom")?;
2132
2133        Ok(Self {
2134            viewport_origin_css,
2135            viewport_origin_cells,
2136            cell_width_css,
2137            cell_height_css,
2138            dpr,
2139            zoom,
2140            rounding,
2141        })
2142    }
2143
2144    /// Convert one raw coordinate into canonical pane cell space.
2145    pub fn normalize(
2146        &self,
2147        input: PaneInputCoordinate,
2148    ) -> Result<PaneNormalizedCoordinate, PaneCoordinateNormalizationError> {
2149        let (local_css_x, local_css_y) = match input {
2150            PaneInputCoordinate::CssPixels { position } => (
2151                i64::from(position.x) - i64::from(self.viewport_origin_css.x),
2152                i64::from(position.y) - i64::from(self.viewport_origin_css.y),
2153            ),
2154            PaneInputCoordinate::DevicePixels { position } => {
2155                let css_x = scale_div_round(
2156                    i64::from(position.x),
2157                    i64::from(self.dpr.denominator()),
2158                    i64::from(self.dpr.numerator()),
2159                    self.rounding,
2160                )?;
2161                let css_y = scale_div_round(
2162                    i64::from(position.y),
2163                    i64::from(self.dpr.denominator()),
2164                    i64::from(self.dpr.numerator()),
2165                    self.rounding,
2166                )?;
2167                (
2168                    css_x - i64::from(self.viewport_origin_css.x),
2169                    css_y - i64::from(self.viewport_origin_css.y),
2170                )
2171            }
2172            PaneInputCoordinate::Cell { position } => {
2173                let local_css_x = i64::from(position.x)
2174                    .checked_mul(i64::from(self.cell_width_css))
2175                    .ok_or(PaneCoordinateNormalizationError::CoordinateOverflow)?;
2176                let local_css_y = i64::from(position.y)
2177                    .checked_mul(i64::from(self.cell_height_css))
2178                    .ok_or(PaneCoordinateNormalizationError::CoordinateOverflow)?;
2179                let global_cell_x = i64::from(position.x) + i64::from(self.viewport_origin_cells.x);
2180                let global_cell_y = i64::from(position.y) + i64::from(self.viewport_origin_cells.y);
2181
2182                return Ok(PaneNormalizedCoordinate {
2183                    global_cell: PanePointerPosition::new(
2184                        to_i32(global_cell_x)?,
2185                        to_i32(global_cell_y)?,
2186                    ),
2187                    local_cell: position,
2188                    local_css: PanePointerPosition::new(to_i32(local_css_x)?, to_i32(local_css_y)?),
2189                });
2190            }
2191        };
2192
2193        let unzoomed_css_x = scale_div_round(
2194            local_css_x,
2195            i64::from(self.zoom.denominator()),
2196            i64::from(self.zoom.numerator()),
2197            self.rounding,
2198        )?;
2199        let unzoomed_css_y = scale_div_round(
2200            local_css_y,
2201            i64::from(self.zoom.denominator()),
2202            i64::from(self.zoom.numerator()),
2203            self.rounding,
2204        )?;
2205
2206        let local_cell_x = div_round(
2207            unzoomed_css_x,
2208            i64::from(self.cell_width_css),
2209            self.rounding,
2210        )?;
2211        let local_cell_y = div_round(
2212            unzoomed_css_y,
2213            i64::from(self.cell_height_css),
2214            self.rounding,
2215        )?;
2216
2217        let global_cell_x = local_cell_x + i64::from(self.viewport_origin_cells.x);
2218        let global_cell_y = local_cell_y + i64::from(self.viewport_origin_cells.y);
2219
2220        Ok(PaneNormalizedCoordinate {
2221            global_cell: PanePointerPosition::new(to_i32(global_cell_x)?, to_i32(global_cell_y)?),
2222            local_cell: PanePointerPosition::new(to_i32(local_cell_x)?, to_i32(local_cell_y)?),
2223            local_css: PanePointerPosition::new(to_i32(unzoomed_css_x)?, to_i32(unzoomed_css_y)?),
2224        })
2225    }
2226}
2227
2228/// Coordinate normalization failures.
2229#[derive(Debug, Clone, PartialEq, Eq)]
2230pub enum PaneCoordinateNormalizationError {
2231    InvalidCellSize {
2232        width: u16,
2233        height: u16,
2234    },
2235    InvalidScaleFactor {
2236        field: &'static str,
2237        numerator: u32,
2238        denominator: u32,
2239    },
2240    CoordinateOverflow,
2241}
2242
2243impl fmt::Display for PaneCoordinateNormalizationError {
2244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2245        match self {
2246            Self::InvalidCellSize { width, height } => {
2247                write!(
2248                    f,
2249                    "invalid pane cell dimensions width={width} height={height} (must be > 0)"
2250                )
2251            }
2252            Self::InvalidScaleFactor {
2253                field,
2254                numerator,
2255                denominator,
2256            } => {
2257                write!(
2258                    f,
2259                    "invalid pane scale factor for {field}: {numerator}/{denominator} (must be > 0)"
2260                )
2261            }
2262            Self::CoordinateOverflow => {
2263                write!(f, "coordinate conversion overflowed representable range")
2264            }
2265        }
2266    }
2267}
2268
2269impl std::error::Error for PaneCoordinateNormalizationError {}
2270
2271fn scale_div_round(
2272    value: i64,
2273    numerator: i64,
2274    denominator: i64,
2275    rounding: PaneCoordinateRoundingPolicy,
2276) -> Result<i64, PaneCoordinateNormalizationError> {
2277    if denominator <= 0 {
2278        return Err(PaneCoordinateNormalizationError::CoordinateOverflow);
2279    }
2280
2281    let scaled = (value as i128) * (numerator as i128);
2282    let den = denominator as i128;
2283
2284    let floor = scaled.div_euclid(den);
2285    let remainder = scaled.rem_euclid(den);
2286
2287    let mut result = floor;
2288
2289    if remainder != 0 {
2290        match rounding {
2291            PaneCoordinateRoundingPolicy::TowardNegativeInfinity => {}
2292            PaneCoordinateRoundingPolicy::NearestHalfTowardNegativeInfinity => {
2293                let twice_remainder = remainder * 2;
2294                if twice_remainder > den {
2295                    result += 1;
2296                }
2297                // Exact half-way ties deliberately keep the Euclidean floor,
2298                // which corresponds to rounding toward negative infinity.
2299            }
2300        }
2301    }
2302
2303    result
2304        .try_into()
2305        .map_err(|_| PaneCoordinateNormalizationError::CoordinateOverflow)
2306}
2307
2308fn div_round(
2309    value: i64,
2310    denominator: i64,
2311    rounding: PaneCoordinateRoundingPolicy,
2312) -> Result<i64, PaneCoordinateNormalizationError> {
2313    scale_div_round(value, 1, denominator, rounding)
2314}
2315
2316fn to_i32(value: i64) -> Result<i32, PaneCoordinateNormalizationError> {
2317    i32::try_from(value).map_err(|_| PaneCoordinateNormalizationError::CoordinateOverflow)
2318}
2319
2320/// Default move threshold (in coordinate units) for transitioning from
2321/// `Armed` to `Dragging`.
2322pub const PANE_DRAG_RESIZE_DEFAULT_THRESHOLD: u16 = 2;
2323
2324/// Default minimum move distance (in coordinate units) required to emit a
2325/// `DragUpdated` transition while dragging.
2326pub const PANE_DRAG_RESIZE_DEFAULT_HYSTERESIS: u16 = 2;
2327
2328/// Default snapping interval expressed in basis points (0..=10_000).
2329pub const PANE_SNAP_DEFAULT_STEP_BPS: u16 = 500;
2330
2331/// Default snap stickiness window in basis points.
2332pub const PANE_SNAP_DEFAULT_HYSTERESIS_BPS: u16 = 125;
2333
2334/// Precision mode derived from modifier snapshots.
2335#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2336#[serde(rename_all = "snake_case")]
2337pub enum PanePrecisionMode {
2338    Normal,
2339    Fine,
2340    Coarse,
2341}
2342
2343/// Modifier-derived precision/axis-lock policy for drag updates.
2344#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2345pub struct PanePrecisionPolicy {
2346    pub mode: PanePrecisionMode,
2347    pub axis_lock: Option<SplitAxis>,
2348    pub scale: PaneScaleFactor,
2349}
2350
2351impl PanePrecisionPolicy {
2352    /// Build precision policy from modifiers for a target split axis.
2353    #[must_use]
2354    pub fn from_modifiers(modifiers: PaneModifierSnapshot, target_axis: SplitAxis) -> Self {
2355        let mode = if modifiers.alt {
2356            PanePrecisionMode::Fine
2357        } else if modifiers.ctrl {
2358            PanePrecisionMode::Coarse
2359        } else {
2360            PanePrecisionMode::Normal
2361        };
2362        let axis_lock = modifiers.shift.then_some(target_axis);
2363        let scale = match mode {
2364            PanePrecisionMode::Normal => PaneScaleFactor::ONE,
2365            PanePrecisionMode::Fine => PaneScaleFactor {
2366                numerator: 1,
2367                denominator: 2,
2368            },
2369            PanePrecisionMode::Coarse => PaneScaleFactor {
2370                numerator: 2,
2371                denominator: 1,
2372            },
2373        };
2374        Self {
2375            mode,
2376            axis_lock,
2377            scale,
2378        }
2379    }
2380
2381    /// Apply precision mode and optional axis-lock to an interaction delta.
2382    pub fn apply_delta(
2383        &self,
2384        raw_delta_x: i32,
2385        raw_delta_y: i32,
2386    ) -> Result<(i32, i32), PaneInteractionPolicyError> {
2387        let (locked_x, locked_y) = match self.axis_lock {
2388            Some(SplitAxis::Horizontal) => (raw_delta_x, 0),
2389            Some(SplitAxis::Vertical) => (0, raw_delta_y),
2390            None => (raw_delta_x, raw_delta_y),
2391        };
2392
2393        let scaled_x = scale_delta_by_factor(locked_x, self.scale)?;
2394        let scaled_y = scale_delta_by_factor(locked_y, self.scale)?;
2395        Ok((scaled_x, scaled_y))
2396    }
2397}
2398
2399/// Deterministic snapping policy for pane split ratios.
2400#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2401pub struct PaneSnapTuning {
2402    pub step_bps: u16,
2403    pub hysteresis_bps: u16,
2404}
2405
2406impl PaneSnapTuning {
2407    pub fn new(step_bps: u16, hysteresis_bps: u16) -> Result<Self, PaneInteractionPolicyError> {
2408        let tuning = Self {
2409            step_bps,
2410            hysteresis_bps,
2411        };
2412        tuning.validate()?;
2413        Ok(tuning)
2414    }
2415
2416    pub fn validate(self) -> Result<(), PaneInteractionPolicyError> {
2417        if self.step_bps == 0 || self.step_bps > 10_000 {
2418            return Err(PaneInteractionPolicyError::InvalidSnapTuning {
2419                step_bps: self.step_bps,
2420                hysteresis_bps: self.hysteresis_bps,
2421            });
2422        }
2423        Ok(())
2424    }
2425
2426    /// Decide whether to snap an input ratio using deterministic tie-breaking.
2427    #[must_use]
2428    pub fn decide(self, ratio_bps: u16, previous_snap: Option<u16>) -> PaneSnapDecision {
2429        let step = u32::from(self.step_bps).max(1);
2430        let ratio = u32::from(ratio_bps).min(10_000);
2431        let low = ((ratio / step) * step).min(10_000);
2432        let high = (low + step).min(10_000);
2433
2434        let distance_low = ratio.abs_diff(low);
2435        let distance_high = ratio.abs_diff(high);
2436
2437        let (nearest, nearest_distance) = if distance_low <= distance_high {
2438            (low as u16, distance_low as u16)
2439        } else {
2440            (high as u16, distance_high as u16)
2441        };
2442
2443        if let Some(previous) = previous_snap {
2444            let distance_previous = ratio.abs_diff(u32::from(previous));
2445            if distance_previous <= u32::from(self.hysteresis_bps) {
2446                return PaneSnapDecision {
2447                    input_ratio_bps: ratio_bps,
2448                    snapped_ratio_bps: Some(previous),
2449                    nearest_ratio_bps: nearest,
2450                    nearest_distance_bps: nearest_distance,
2451                    reason: PaneSnapReason::RetainedPrevious,
2452                };
2453            }
2454        }
2455
2456        if nearest_distance <= self.hysteresis_bps {
2457            PaneSnapDecision {
2458                input_ratio_bps: ratio_bps,
2459                snapped_ratio_bps: Some(nearest),
2460                nearest_ratio_bps: nearest,
2461                nearest_distance_bps: nearest_distance,
2462                reason: PaneSnapReason::SnappedNearest,
2463            }
2464        } else {
2465            PaneSnapDecision {
2466                input_ratio_bps: ratio_bps,
2467                snapped_ratio_bps: None,
2468                nearest_ratio_bps: nearest,
2469                nearest_distance_bps: nearest_distance,
2470                reason: PaneSnapReason::UnsnapOutsideWindow,
2471            }
2472        }
2473    }
2474}
2475
2476impl Default for PaneSnapTuning {
2477    fn default() -> Self {
2478        Self {
2479            step_bps: PANE_SNAP_DEFAULT_STEP_BPS,
2480            hysteresis_bps: PANE_SNAP_DEFAULT_HYSTERESIS_BPS,
2481        }
2482    }
2483}
2484
2485/// Combined drag behavior tuning constants.
2486#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2487pub struct PaneDragBehaviorTuning {
2488    pub activation_threshold: u16,
2489    pub update_hysteresis: u16,
2490    pub snap: PaneSnapTuning,
2491}
2492
2493impl PaneDragBehaviorTuning {
2494    pub fn new(
2495        activation_threshold: u16,
2496        update_hysteresis: u16,
2497        snap: PaneSnapTuning,
2498    ) -> Result<Self, PaneInteractionPolicyError> {
2499        if activation_threshold == 0 {
2500            return Err(PaneInteractionPolicyError::InvalidThreshold {
2501                field: "activation_threshold",
2502                value: activation_threshold,
2503            });
2504        }
2505        if update_hysteresis == 0 {
2506            return Err(PaneInteractionPolicyError::InvalidThreshold {
2507                field: "update_hysteresis",
2508                value: update_hysteresis,
2509            });
2510        }
2511        snap.validate()?;
2512        Ok(Self {
2513            activation_threshold,
2514            update_hysteresis,
2515            snap,
2516        })
2517    }
2518
2519    #[must_use]
2520    pub fn should_start_drag(
2521        self,
2522        origin: PanePointerPosition,
2523        current: PanePointerPosition,
2524    ) -> bool {
2525        crossed_drag_threshold(origin, current, self.activation_threshold)
2526    }
2527
2528    #[must_use]
2529    pub fn should_emit_drag_update(
2530        self,
2531        previous: PanePointerPosition,
2532        current: PanePointerPosition,
2533    ) -> bool {
2534        crossed_drag_threshold(previous, current, self.update_hysteresis)
2535    }
2536}
2537
2538impl Default for PaneDragBehaviorTuning {
2539    fn default() -> Self {
2540        Self {
2541            activation_threshold: PANE_DRAG_RESIZE_DEFAULT_THRESHOLD,
2542            update_hysteresis: PANE_DRAG_RESIZE_DEFAULT_HYSTERESIS,
2543            snap: PaneSnapTuning::default(),
2544        }
2545    }
2546}
2547
2548/// Deterministic snap decision categories.
2549#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2550#[serde(rename_all = "snake_case")]
2551pub enum PaneSnapReason {
2552    RetainedPrevious,
2553    SnappedNearest,
2554    UnsnapOutsideWindow,
2555}
2556
2557/// Output of snap-decision evaluation.
2558#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2559pub struct PaneSnapDecision {
2560    pub input_ratio_bps: u16,
2561    pub snapped_ratio_bps: Option<u16>,
2562    pub nearest_ratio_bps: u16,
2563    pub nearest_distance_bps: u16,
2564    pub reason: PaneSnapReason,
2565}
2566
2567/// Tuning/policy validation errors for pane interaction behavior controls.
2568#[derive(Debug, Clone, PartialEq, Eq)]
2569pub enum PaneInteractionPolicyError {
2570    InvalidThreshold { field: &'static str, value: u16 },
2571    InvalidSnapTuning { step_bps: u16, hysteresis_bps: u16 },
2572    DeltaOverflow,
2573}
2574
2575impl fmt::Display for PaneInteractionPolicyError {
2576    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2577        match self {
2578            Self::InvalidThreshold { field, value } => {
2579                write!(f, "invalid {field} value {value} (must be > 0)")
2580            }
2581            Self::InvalidSnapTuning {
2582                step_bps,
2583                hysteresis_bps,
2584            } => {
2585                write!(
2586                    f,
2587                    "invalid snap tuning step_bps={step_bps} hysteresis_bps={hysteresis_bps}"
2588                )
2589            }
2590            Self::DeltaOverflow => write!(f, "delta scaling overflow"),
2591        }
2592    }
2593}
2594
2595impl std::error::Error for PaneInteractionPolicyError {}
2596
2597fn scale_delta_by_factor(
2598    delta: i32,
2599    factor: PaneScaleFactor,
2600) -> Result<i32, PaneInteractionPolicyError> {
2601    let scaled = i64::from(delta)
2602        .checked_mul(i64::from(factor.numerator()))
2603        .ok_or(PaneInteractionPolicyError::DeltaOverflow)?;
2604    let normalized = scaled / i64::from(factor.denominator());
2605    i32::try_from(normalized).map_err(|_| PaneInteractionPolicyError::DeltaOverflow)
2606}
2607
2608/// Deterministic pane drag/resize lifecycle state.
2609///
2610/// ```text
2611/// Idle -> Armed -> Dragging -> Idle
2612///    \------> Idle (commit/cancel from Armed)
2613/// ```
2614#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2615#[serde(tag = "state", rename_all = "snake_case")]
2616pub enum PaneDragResizeState {
2617    Idle,
2618    Armed {
2619        target: PaneResizeTarget,
2620        pointer_id: u32,
2621        origin: PanePointerPosition,
2622        current: PanePointerPosition,
2623        started_sequence: u64,
2624    },
2625    Dragging {
2626        target: PaneResizeTarget,
2627        pointer_id: u32,
2628        origin: PanePointerPosition,
2629        current: PanePointerPosition,
2630        started_sequence: u64,
2631        drag_started_sequence: u64,
2632    },
2633}
2634
2635/// Explicit no-op diagnostics for lifecycle events that are safely ignored.
2636#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2637#[serde(rename_all = "snake_case")]
2638pub enum PaneDragResizeNoopReason {
2639    IdleWithoutActiveDrag,
2640    ActiveDragAlreadyInProgress,
2641    PointerMismatch,
2642    TargetMismatch,
2643    ActiveStateDisallowsDiscreteInput,
2644    ThresholdNotReached,
2645    BelowHysteresis,
2646}
2647
2648/// Transition effect emitted by one lifecycle step.
2649#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2650#[serde(tag = "effect", rename_all = "snake_case")]
2651pub enum PaneDragResizeEffect {
2652    Armed {
2653        target: PaneResizeTarget,
2654        pointer_id: u32,
2655        origin: PanePointerPosition,
2656    },
2657    DragStarted {
2658        target: PaneResizeTarget,
2659        pointer_id: u32,
2660        origin: PanePointerPosition,
2661        current: PanePointerPosition,
2662        total_delta_x: i32,
2663        total_delta_y: i32,
2664    },
2665    DragUpdated {
2666        target: PaneResizeTarget,
2667        pointer_id: u32,
2668        previous: PanePointerPosition,
2669        current: PanePointerPosition,
2670        delta_x: i32,
2671        delta_y: i32,
2672        total_delta_x: i32,
2673        total_delta_y: i32,
2674    },
2675    Committed {
2676        target: PaneResizeTarget,
2677        pointer_id: u32,
2678        origin: PanePointerPosition,
2679        end: PanePointerPosition,
2680        total_delta_x: i32,
2681        total_delta_y: i32,
2682    },
2683    Canceled {
2684        target: Option<PaneResizeTarget>,
2685        pointer_id: Option<u32>,
2686        reason: PaneCancelReason,
2687    },
2688    KeyboardApplied {
2689        target: PaneResizeTarget,
2690        direction: PaneResizeDirection,
2691        units: u16,
2692    },
2693    WheelApplied {
2694        target: PaneResizeTarget,
2695        lines: i16,
2696    },
2697    Noop {
2698        reason: PaneDragResizeNoopReason,
2699    },
2700}
2701
2702/// One state-machine transition with deterministic telemetry fields.
2703#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2704pub struct PaneDragResizeTransition {
2705    pub transition_id: u64,
2706    pub sequence: u64,
2707    pub from: PaneDragResizeState,
2708    pub to: PaneDragResizeState,
2709    pub effect: PaneDragResizeEffect,
2710}
2711
2712/// Runtime lifecycle machine for pane drag/resize interactions.
2713#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2714pub struct PaneDragResizeMachine {
2715    state: PaneDragResizeState,
2716    drag_threshold: u16,
2717    update_hysteresis: u16,
2718    transition_counter: u64,
2719}
2720
2721impl Default for PaneDragResizeMachine {
2722    fn default() -> Self {
2723        Self {
2724            state: PaneDragResizeState::Idle,
2725            drag_threshold: PANE_DRAG_RESIZE_DEFAULT_THRESHOLD,
2726            update_hysteresis: PANE_DRAG_RESIZE_DEFAULT_HYSTERESIS,
2727            transition_counter: 0,
2728        }
2729    }
2730}
2731
2732impl PaneDragResizeMachine {
2733    /// Construct a drag/resize lifecycle machine with explicit threshold.
2734    pub fn new(drag_threshold: u16) -> Result<Self, PaneDragResizeMachineError> {
2735        Self::new_with_hysteresis(drag_threshold, PANE_DRAG_RESIZE_DEFAULT_HYSTERESIS)
2736    }
2737
2738    /// Construct a drag/resize lifecycle machine with explicit threshold and
2739    /// drag-update hysteresis.
2740    pub fn new_with_hysteresis(
2741        drag_threshold: u16,
2742        update_hysteresis: u16,
2743    ) -> Result<Self, PaneDragResizeMachineError> {
2744        if drag_threshold == 0 {
2745            return Err(PaneDragResizeMachineError::InvalidDragThreshold {
2746                threshold: drag_threshold,
2747            });
2748        }
2749        if update_hysteresis == 0 {
2750            return Err(PaneDragResizeMachineError::InvalidUpdateHysteresis {
2751                hysteresis: update_hysteresis,
2752            });
2753        }
2754        Ok(Self {
2755            state: PaneDragResizeState::Idle,
2756            drag_threshold,
2757            update_hysteresis,
2758            transition_counter: 0,
2759        })
2760    }
2761
2762    /// Current lifecycle state.
2763    #[must_use]
2764    pub const fn state(&self) -> PaneDragResizeState {
2765        self.state
2766    }
2767
2768    /// Configured drag-start threshold.
2769    #[must_use]
2770    pub const fn drag_threshold(&self) -> u16 {
2771        self.drag_threshold
2772    }
2773
2774    /// Configured drag-update hysteresis threshold.
2775    #[must_use]
2776    pub const fn update_hysteresis(&self) -> u16 {
2777        self.update_hysteresis
2778    }
2779
2780    /// Whether the machine is in a non-idle state (Armed or Dragging).
2781    #[must_use]
2782    pub const fn is_active(&self) -> bool {
2783        !matches!(self.state, PaneDragResizeState::Idle)
2784    }
2785
2786    /// Unconditionally reset the machine to Idle, returning a diagnostic
2787    /// transition if the machine was in an active state.
2788    ///
2789    /// This is a safety valve for RAII cleanup paths (panic, signal, guard
2790    /// drop) where constructing a valid `PaneSemanticInputEvent` is not
2791    /// possible. The returned transition carries `PaneCancelReason::Programmatic`
2792    /// and a `Canceled` effect.
2793    ///
2794    /// If the machine is already Idle, returns `None` (no-op).
2795    pub fn force_cancel(&mut self) -> Option<PaneDragResizeTransition> {
2796        let from = self.state;
2797        match from {
2798            PaneDragResizeState::Idle => None,
2799            PaneDragResizeState::Armed {
2800                target, pointer_id, ..
2801            }
2802            | PaneDragResizeState::Dragging {
2803                target, pointer_id, ..
2804            } => {
2805                self.state = PaneDragResizeState::Idle;
2806                self.transition_counter = self.transition_counter.saturating_add(1);
2807                Some(PaneDragResizeTransition {
2808                    transition_id: self.transition_counter,
2809                    sequence: 0,
2810                    from,
2811                    to: PaneDragResizeState::Idle,
2812                    effect: PaneDragResizeEffect::Canceled {
2813                        target: Some(target),
2814                        pointer_id: Some(pointer_id),
2815                        reason: PaneCancelReason::Programmatic,
2816                    },
2817                })
2818            }
2819        }
2820    }
2821
2822    /// Apply one semantic pane input event and emit deterministic transition
2823    /// diagnostics.
2824    pub fn apply_event(
2825        &mut self,
2826        event: &PaneSemanticInputEvent,
2827    ) -> Result<PaneDragResizeTransition, PaneDragResizeMachineError> {
2828        event
2829            .validate()
2830            .map_err(PaneDragResizeMachineError::InvalidEvent)?;
2831
2832        let from = self.state;
2833        let effect = match (self.state, &event.kind) {
2834            (
2835                PaneDragResizeState::Idle,
2836                PaneSemanticInputEventKind::PointerDown {
2837                    target,
2838                    pointer_id,
2839                    position,
2840                    ..
2841                },
2842            ) => {
2843                self.state = PaneDragResizeState::Armed {
2844                    target: *target,
2845                    pointer_id: *pointer_id,
2846                    origin: *position,
2847                    current: *position,
2848                    started_sequence: event.sequence,
2849                };
2850                PaneDragResizeEffect::Armed {
2851                    target: *target,
2852                    pointer_id: *pointer_id,
2853                    origin: *position,
2854                }
2855            }
2856            (
2857                PaneDragResizeState::Idle,
2858                PaneSemanticInputEventKind::KeyboardResize {
2859                    target,
2860                    direction,
2861                    units,
2862                },
2863            ) => PaneDragResizeEffect::KeyboardApplied {
2864                target: *target,
2865                direction: *direction,
2866                units: *units,
2867            },
2868            (
2869                PaneDragResizeState::Idle,
2870                PaneSemanticInputEventKind::WheelNudge { target, lines },
2871            ) => PaneDragResizeEffect::WheelApplied {
2872                target: *target,
2873                lines: *lines,
2874            },
2875            (PaneDragResizeState::Idle, _) => PaneDragResizeEffect::Noop {
2876                reason: PaneDragResizeNoopReason::IdleWithoutActiveDrag,
2877            },
2878            (
2879                PaneDragResizeState::Armed {
2880                    target,
2881                    pointer_id,
2882                    origin,
2883                    current: _,
2884                    started_sequence,
2885                },
2886                PaneSemanticInputEventKind::PointerMove {
2887                    target: incoming_target,
2888                    pointer_id: incoming_pointer_id,
2889                    position,
2890                    ..
2891                },
2892            ) => {
2893                if *incoming_pointer_id != pointer_id {
2894                    PaneDragResizeEffect::Noop {
2895                        reason: PaneDragResizeNoopReason::PointerMismatch,
2896                    }
2897                } else if *incoming_target != target {
2898                    PaneDragResizeEffect::Noop {
2899                        reason: PaneDragResizeNoopReason::TargetMismatch,
2900                    }
2901                } else {
2902                    self.state = PaneDragResizeState::Armed {
2903                        target,
2904                        pointer_id,
2905                        origin,
2906                        current: *position,
2907                        started_sequence,
2908                    };
2909                    if crossed_drag_threshold(origin, *position, self.drag_threshold) {
2910                        self.state = PaneDragResizeState::Dragging {
2911                            target,
2912                            pointer_id,
2913                            origin,
2914                            current: *position,
2915                            started_sequence,
2916                            drag_started_sequence: event.sequence,
2917                        };
2918                        let (total_delta_x, total_delta_y) = delta(origin, *position);
2919                        PaneDragResizeEffect::DragStarted {
2920                            target,
2921                            pointer_id,
2922                            origin,
2923                            current: *position,
2924                            total_delta_x,
2925                            total_delta_y,
2926                        }
2927                    } else {
2928                        PaneDragResizeEffect::Noop {
2929                            reason: PaneDragResizeNoopReason::ThresholdNotReached,
2930                        }
2931                    }
2932                }
2933            }
2934            (
2935                PaneDragResizeState::Armed {
2936                    target,
2937                    pointer_id,
2938                    origin,
2939                    ..
2940                },
2941                PaneSemanticInputEventKind::PointerUp {
2942                    target: incoming_target,
2943                    pointer_id: incoming_pointer_id,
2944                    position,
2945                    ..
2946                },
2947            ) => {
2948                if *incoming_pointer_id != pointer_id {
2949                    PaneDragResizeEffect::Noop {
2950                        reason: PaneDragResizeNoopReason::PointerMismatch,
2951                    }
2952                } else if *incoming_target != target {
2953                    PaneDragResizeEffect::Noop {
2954                        reason: PaneDragResizeNoopReason::TargetMismatch,
2955                    }
2956                } else {
2957                    self.state = PaneDragResizeState::Idle;
2958                    let (total_delta_x, total_delta_y) = delta(origin, *position);
2959                    PaneDragResizeEffect::Committed {
2960                        target,
2961                        pointer_id,
2962                        origin,
2963                        end: *position,
2964                        total_delta_x,
2965                        total_delta_y,
2966                    }
2967                }
2968            }
2969            (
2970                PaneDragResizeState::Armed {
2971                    target, pointer_id, ..
2972                },
2973                PaneSemanticInputEventKind::Cancel {
2974                    target: incoming_target,
2975                    reason,
2976                },
2977            ) => {
2978                if !cancel_target_matches(target, *incoming_target) {
2979                    PaneDragResizeEffect::Noop {
2980                        reason: PaneDragResizeNoopReason::TargetMismatch,
2981                    }
2982                } else {
2983                    self.state = PaneDragResizeState::Idle;
2984                    PaneDragResizeEffect::Canceled {
2985                        target: Some(target),
2986                        pointer_id: Some(pointer_id),
2987                        reason: *reason,
2988                    }
2989                }
2990            }
2991            (
2992                PaneDragResizeState::Armed {
2993                    target, pointer_id, ..
2994                },
2995                PaneSemanticInputEventKind::Blur {
2996                    target: incoming_target,
2997                },
2998            ) => {
2999                if !cancel_target_matches(target, *incoming_target) {
3000                    PaneDragResizeEffect::Noop {
3001                        reason: PaneDragResizeNoopReason::TargetMismatch,
3002                    }
3003                } else {
3004                    self.state = PaneDragResizeState::Idle;
3005                    PaneDragResizeEffect::Canceled {
3006                        target: Some(target),
3007                        pointer_id: Some(pointer_id),
3008                        reason: PaneCancelReason::Blur,
3009                    }
3010                }
3011            }
3012            (PaneDragResizeState::Armed { .. }, PaneSemanticInputEventKind::PointerDown { .. }) => {
3013                PaneDragResizeEffect::Noop {
3014                    reason: PaneDragResizeNoopReason::ActiveDragAlreadyInProgress,
3015                }
3016            }
3017            (
3018                PaneDragResizeState::Armed { .. },
3019                PaneSemanticInputEventKind::KeyboardResize { .. }
3020                | PaneSemanticInputEventKind::WheelNudge { .. },
3021            ) => PaneDragResizeEffect::Noop {
3022                reason: PaneDragResizeNoopReason::ActiveStateDisallowsDiscreteInput,
3023            },
3024            (
3025                PaneDragResizeState::Dragging {
3026                    target,
3027                    pointer_id,
3028                    origin,
3029                    current,
3030                    started_sequence,
3031                    drag_started_sequence,
3032                },
3033                PaneSemanticInputEventKind::PointerMove {
3034                    target: incoming_target,
3035                    pointer_id: incoming_pointer_id,
3036                    position,
3037                    ..
3038                },
3039            ) => {
3040                if *incoming_pointer_id != pointer_id {
3041                    PaneDragResizeEffect::Noop {
3042                        reason: PaneDragResizeNoopReason::PointerMismatch,
3043                    }
3044                } else if *incoming_target != target {
3045                    PaneDragResizeEffect::Noop {
3046                        reason: PaneDragResizeNoopReason::TargetMismatch,
3047                    }
3048                } else {
3049                    let previous = current;
3050                    if !crossed_drag_threshold(previous, *position, self.update_hysteresis) {
3051                        PaneDragResizeEffect::Noop {
3052                            reason: PaneDragResizeNoopReason::BelowHysteresis,
3053                        }
3054                    } else {
3055                        let (delta_x, delta_y) = delta(previous, *position);
3056                        let (total_delta_x, total_delta_y) = delta(origin, *position);
3057                        self.state = PaneDragResizeState::Dragging {
3058                            target,
3059                            pointer_id,
3060                            origin,
3061                            current: *position,
3062                            started_sequence,
3063                            drag_started_sequence,
3064                        };
3065                        PaneDragResizeEffect::DragUpdated {
3066                            target,
3067                            pointer_id,
3068                            previous,
3069                            current: *position,
3070                            delta_x,
3071                            delta_y,
3072                            total_delta_x,
3073                            total_delta_y,
3074                        }
3075                    }
3076                }
3077            }
3078            (
3079                PaneDragResizeState::Dragging {
3080                    target,
3081                    pointer_id,
3082                    origin,
3083                    ..
3084                },
3085                PaneSemanticInputEventKind::PointerUp {
3086                    target: incoming_target,
3087                    pointer_id: incoming_pointer_id,
3088                    position,
3089                    ..
3090                },
3091            ) => {
3092                if *incoming_pointer_id != pointer_id {
3093                    PaneDragResizeEffect::Noop {
3094                        reason: PaneDragResizeNoopReason::PointerMismatch,
3095                    }
3096                } else if *incoming_target != target {
3097                    PaneDragResizeEffect::Noop {
3098                        reason: PaneDragResizeNoopReason::TargetMismatch,
3099                    }
3100                } else {
3101                    self.state = PaneDragResizeState::Idle;
3102                    let (total_delta_x, total_delta_y) = delta(origin, *position);
3103                    PaneDragResizeEffect::Committed {
3104                        target,
3105                        pointer_id,
3106                        origin,
3107                        end: *position,
3108                        total_delta_x,
3109                        total_delta_y,
3110                    }
3111                }
3112            }
3113            (
3114                PaneDragResizeState::Dragging {
3115                    target, pointer_id, ..
3116                },
3117                PaneSemanticInputEventKind::Cancel {
3118                    target: incoming_target,
3119                    reason,
3120                },
3121            ) => {
3122                if !cancel_target_matches(target, *incoming_target) {
3123                    PaneDragResizeEffect::Noop {
3124                        reason: PaneDragResizeNoopReason::TargetMismatch,
3125                    }
3126                } else {
3127                    self.state = PaneDragResizeState::Idle;
3128                    PaneDragResizeEffect::Canceled {
3129                        target: Some(target),
3130                        pointer_id: Some(pointer_id),
3131                        reason: *reason,
3132                    }
3133                }
3134            }
3135            (
3136                PaneDragResizeState::Dragging {
3137                    target, pointer_id, ..
3138                },
3139                PaneSemanticInputEventKind::Blur {
3140                    target: incoming_target,
3141                },
3142            ) => {
3143                if !cancel_target_matches(target, *incoming_target) {
3144                    PaneDragResizeEffect::Noop {
3145                        reason: PaneDragResizeNoopReason::TargetMismatch,
3146                    }
3147                } else {
3148                    self.state = PaneDragResizeState::Idle;
3149                    PaneDragResizeEffect::Canceled {
3150                        target: Some(target),
3151                        pointer_id: Some(pointer_id),
3152                        reason: PaneCancelReason::Blur,
3153                    }
3154                }
3155            }
3156            (
3157                PaneDragResizeState::Dragging { .. },
3158                PaneSemanticInputEventKind::PointerDown { .. },
3159            ) => PaneDragResizeEffect::Noop {
3160                reason: PaneDragResizeNoopReason::ActiveDragAlreadyInProgress,
3161            },
3162            (
3163                PaneDragResizeState::Dragging { .. },
3164                PaneSemanticInputEventKind::KeyboardResize { .. }
3165                | PaneSemanticInputEventKind::WheelNudge { .. },
3166            ) => PaneDragResizeEffect::Noop {
3167                reason: PaneDragResizeNoopReason::ActiveStateDisallowsDiscreteInput,
3168            },
3169        };
3170
3171        self.transition_counter = self.transition_counter.saturating_add(1);
3172        Ok(PaneDragResizeTransition {
3173            transition_id: self.transition_counter,
3174            sequence: event.sequence,
3175            from,
3176            to: self.state,
3177            effect,
3178        })
3179    }
3180}
3181
3182/// Lifecycle machine configuration/runtime errors.
3183#[derive(Debug, Clone, PartialEq, Eq)]
3184pub enum PaneDragResizeMachineError {
3185    InvalidDragThreshold { threshold: u16 },
3186    InvalidUpdateHysteresis { hysteresis: u16 },
3187    InvalidEvent(PaneSemanticInputEventError),
3188}
3189
3190impl fmt::Display for PaneDragResizeMachineError {
3191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3192        match self {
3193            Self::InvalidDragThreshold { threshold } => {
3194                write!(f, "drag threshold must be > 0 (got {threshold})")
3195            }
3196            Self::InvalidUpdateHysteresis { hysteresis } => {
3197                write!(f, "update hysteresis must be > 0 (got {hysteresis})")
3198            }
3199            Self::InvalidEvent(error) => write!(f, "invalid semantic pane input event: {error}"),
3200        }
3201    }
3202}
3203
3204impl std::error::Error for PaneDragResizeMachineError {
3205    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
3206        if let Self::InvalidEvent(error) = self {
3207            return Some(error);
3208        }
3209        None
3210    }
3211}
3212
3213fn delta(origin: PanePointerPosition, current: PanePointerPosition) -> (i32, i32) {
3214    (current.x - origin.x, current.y - origin.y)
3215}
3216
3217fn crossed_drag_threshold(
3218    origin: PanePointerPosition,
3219    current: PanePointerPosition,
3220    threshold: u16,
3221) -> bool {
3222    let (dx, dy) = delta(origin, current);
3223    let threshold = i64::from(threshold);
3224    let squared_distance = i64::from(dx) * i64::from(dx) + i64::from(dy) * i64::from(dy);
3225    squared_distance >= threshold * threshold
3226}
3227
3228fn cancel_target_matches(active: PaneResizeTarget, incoming: Option<PaneResizeTarget>) -> bool {
3229    incoming.is_none() || incoming == Some(active)
3230}
3231
3232fn round_f64_to_i32(value: f64) -> i32 {
3233    if !value.is_finite() {
3234        return 0;
3235    }
3236    if value >= f64::from(i32::MAX) {
3237        return i32::MAX;
3238    }
3239    if value <= f64::from(i32::MIN) {
3240        return i32::MIN;
3241    }
3242    value.round() as i32
3243}
3244
3245fn axis_share_from_pointer(
3246    rect: Rect,
3247    pointer: PanePointerPosition,
3248    axis: SplitAxis,
3249    inset_cells: f64,
3250) -> f64 {
3251    let inset = inset_cells.max(0.0);
3252    let (origin, extent, coordinate) = match axis {
3253        SplitAxis::Horizontal => (
3254            f64::from(rect.x),
3255            f64::from(rect.width),
3256            f64::from(pointer.x),
3257        ),
3258        SplitAxis::Vertical => (
3259            f64::from(rect.y),
3260            f64::from(rect.height),
3261            f64::from(pointer.y),
3262        ),
3263    };
3264    if extent <= 0.0 {
3265        return 0.5;
3266    }
3267    let low = origin + inset.min(extent / 2.0);
3268    let high = (origin + extent) - inset.min(extent / 2.0);
3269    if high <= low {
3270        return 0.5;
3271    }
3272    ((coordinate - low) / (high - low)).clamp(0.0, 1.0)
3273}
3274
3275fn elastic_ratio_bps(raw_bps: u16, pressure: PanePressureSnapProfile) -> u16 {
3276    let raw = f64::from(raw_bps.clamp(1, 9_999)) / 10_000.0;
3277    let confidence = (f64::from(pressure.strength_bps) / 10_000.0).clamp(0.0, 1.0);
3278    let edge_band = (0.16 - confidence * 0.09).clamp(0.05, 0.18);
3279    let resistance = (0.62 - confidence * 0.34).clamp(0.18, 0.68);
3280    let eased = if raw < edge_band {
3281        let ratio = (raw / edge_band).clamp(0.0, 1.0);
3282        edge_band * ratio.powf(1.0 / (1.0 + resistance))
3283    } else if raw > 1.0 - edge_band {
3284        let ratio = ((1.0 - raw) / edge_band).clamp(0.0, 1.0);
3285        1.0 - edge_band * ratio.powf(1.0 / (1.0 + resistance))
3286    } else {
3287        raw
3288    };
3289    (eased * 10_000.0).round().clamp(1.0, 9_999.0) as u16
3290}
3291
3292fn classify_resize_grip(
3293    rect: Rect,
3294    pointer: PanePointerPosition,
3295    inset_cells: f64,
3296) -> Option<PaneResizeGrip> {
3297    let inset = inset_cells.max(0.5);
3298    let left = f64::from(rect.x);
3299    let right = f64::from(rect.x.saturating_add(rect.width.saturating_sub(1)));
3300    let top = f64::from(rect.y);
3301    let bottom = f64::from(rect.y.saturating_add(rect.height.saturating_sub(1)));
3302    let px = f64::from(pointer.x);
3303    let py = f64::from(pointer.y);
3304
3305    if px < left - inset || px > right + inset || py < top - inset || py > bottom + inset {
3306        return None;
3307    }
3308
3309    let mut near_left = (px - left).abs() <= inset;
3310    let mut near_right = (px - right).abs() <= inset;
3311    let mut near_top = (py - top).abs() <= inset;
3312    let mut near_bottom = (py - bottom).abs() <= inset;
3313
3314    // Disambiguate overlapping zones (small panes) by proximity
3315    if near_left && near_right {
3316        if (px - left).abs() < (px - right).abs() {
3317            near_right = false;
3318        } else {
3319            near_left = false;
3320        }
3321    }
3322    if near_top && near_bottom {
3323        if (py - top).abs() < (py - bottom).abs() {
3324            near_bottom = false;
3325        } else {
3326            near_top = false;
3327        }
3328    }
3329
3330    match (near_left, near_right, near_top, near_bottom) {
3331        (true, false, true, false) => Some(PaneResizeGrip::TopLeft),
3332        (false, true, true, false) => Some(PaneResizeGrip::TopRight),
3333        (true, false, false, true) => Some(PaneResizeGrip::BottomLeft),
3334        (false, true, false, true) => Some(PaneResizeGrip::BottomRight),
3335        (true, false, false, false) => Some(PaneResizeGrip::Left),
3336        (false, true, false, false) => Some(PaneResizeGrip::Right),
3337        (false, false, true, false) => Some(PaneResizeGrip::Top),
3338        (false, false, false, true) => Some(PaneResizeGrip::Bottom),
3339        _ => None,
3340    }
3341}
3342
3343fn euclidean_distance(a: PanePointerPosition, b: PanePointerPosition) -> f64 {
3344    let dx = f64::from(a.x - b.x);
3345    let dy = f64::from(a.y - b.y);
3346    (dx * dx + dy * dy).sqrt()
3347}
3348
3349fn rect_zone_anchor(rect: Rect, zone: PaneDockZone) -> PanePointerPosition {
3350    let left = i32::from(rect.x);
3351    let right = i32::from(rect.x.saturating_add(rect.width.saturating_sub(1)));
3352    let top = i32::from(rect.y);
3353    let bottom = i32::from(rect.y.saturating_add(rect.height.saturating_sub(1)));
3354    let mid_x = (left + right) / 2;
3355    let mid_y = (top + bottom) / 2;
3356    match zone {
3357        PaneDockZone::Left => PanePointerPosition::new(left, mid_y),
3358        PaneDockZone::Right => PanePointerPosition::new(right, mid_y),
3359        PaneDockZone::Top => PanePointerPosition::new(mid_x, top),
3360        PaneDockZone::Bottom => PanePointerPosition::new(mid_x, bottom),
3361        PaneDockZone::Center => PanePointerPosition::new(mid_x, mid_y),
3362    }
3363}
3364
3365fn dock_zone_ghost_rect(rect: Rect, zone: PaneDockZone) -> Rect {
3366    match zone {
3367        PaneDockZone::Left => {
3368            Rect::new(rect.x, rect.y, (rect.width / 2).max(1), rect.height.max(1))
3369        }
3370        PaneDockZone::Right => {
3371            let width = (rect.width / 2).max(1);
3372            Rect::new(
3373                rect.x.saturating_add(rect.width.saturating_sub(width)),
3374                rect.y,
3375                width,
3376                rect.height.max(1),
3377            )
3378        }
3379        PaneDockZone::Top => Rect::new(rect.x, rect.y, rect.width.max(1), (rect.height / 2).max(1)),
3380        PaneDockZone::Bottom => {
3381            let height = (rect.height / 2).max(1);
3382            Rect::new(
3383                rect.x,
3384                rect.y.saturating_add(rect.height.saturating_sub(height)),
3385                rect.width.max(1),
3386                height,
3387            )
3388        }
3389        PaneDockZone::Center => rect,
3390    }
3391}
3392
3393fn dock_zone_score(distance: f64, radius: f64, zone: PaneDockZone) -> f64 {
3394    if radius <= 0.0 || distance > radius {
3395        return 0.0;
3396    }
3397    let base = 1.0 - (distance / radius);
3398    let zone_weight = match zone {
3399        PaneDockZone::Center => 0.85,
3400        PaneDockZone::Left | PaneDockZone::Right | PaneDockZone::Top | PaneDockZone::Bottom => 1.0,
3401    };
3402    base * zone_weight
3403}
3404
3405const fn dock_zone_rank(zone: PaneDockZone) -> u8 {
3406    match zone {
3407        PaneDockZone::Left => 0,
3408        PaneDockZone::Right => 1,
3409        PaneDockZone::Top => 2,
3410        PaneDockZone::Bottom => 3,
3411        PaneDockZone::Center => 4,
3412    }
3413}
3414
3415fn dock_preview_for_rect(
3416    target: PaneId,
3417    rect: Rect,
3418    pointer: PanePointerPosition,
3419    magnetic_field_cells: f64,
3420) -> Option<PaneDockPreview> {
3421    let radius = magnetic_field_cells.max(0.5);
3422    let zones = [
3423        PaneDockZone::Left,
3424        PaneDockZone::Right,
3425        PaneDockZone::Top,
3426        PaneDockZone::Bottom,
3427        PaneDockZone::Center,
3428    ];
3429    let mut best: Option<PaneDockPreview> = None;
3430    for zone in zones {
3431        let anchor = rect_zone_anchor(rect, zone);
3432        let distance = euclidean_distance(anchor, pointer);
3433        let score = dock_zone_score(distance, radius, zone);
3434        if score <= 0.0 {
3435            continue;
3436        }
3437        let candidate = PaneDockPreview {
3438            target,
3439            zone,
3440            score,
3441            ghost_rect: dock_zone_ghost_rect(rect, zone),
3442        };
3443        match best {
3444            Some(current) if candidate.score <= current.score => {}
3445            _ => best = Some(candidate),
3446        }
3447    }
3448    best
3449}
3450
3451fn dock_zone_motion_intent(zone: PaneDockZone, motion: PaneMotionVector) -> f64 {
3452    let dx = f64::from(motion.delta_x);
3453    let dy = f64::from(motion.delta_y);
3454    let abs_dx = dx.abs();
3455    let abs_dy = dy.abs();
3456    let total = (abs_dx + abs_dy).max(1.0);
3457    let horizontal = abs_dx / total;
3458    let vertical = abs_dy / total;
3459    let speed_factor = (motion.speed / 140.0).clamp(0.0, 1.0);
3460    let noise_penalty = (f64::from(motion.direction_changes) / 10.0).clamp(0.0, 1.0);
3461
3462    let directional = match zone {
3463        PaneDockZone::Left => {
3464            if dx < 0.0 {
3465                0.95 + horizontal * 0.55
3466            } else {
3467                1.0 - horizontal * 0.35
3468            }
3469        }
3470        PaneDockZone::Right => {
3471            if dx > 0.0 {
3472                0.95 + horizontal * 0.55
3473            } else {
3474                1.0 - horizontal * 0.35
3475            }
3476        }
3477        PaneDockZone::Top => {
3478            if dy < 0.0 {
3479                0.95 + vertical * 0.55
3480            } else {
3481                1.0 - vertical * 0.35
3482            }
3483        }
3484        PaneDockZone::Bottom => {
3485            if dy > 0.0 {
3486                0.95 + vertical * 0.55
3487            } else {
3488                1.0 - vertical * 0.35
3489            }
3490        }
3491        PaneDockZone::Center => {
3492            let axis_ambiguity = 1.0 - horizontal.max(vertical);
3493            0.9 + axis_ambiguity * 0.25 - speed_factor * 0.12
3494        }
3495    };
3496    (directional - noise_penalty * 0.22).clamp(0.55, 1.45)
3497}
3498
3499fn dock_preview_for_rect_with_motion(
3500    target: PaneId,
3501    rect: Rect,
3502    pointer: PanePointerPosition,
3503    magnetic_field_cells: f64,
3504    motion: PaneMotionVector,
3505) -> Option<PaneDockPreview> {
3506    let radius = magnetic_field_cells.max(0.5);
3507    let zones = [
3508        PaneDockZone::Left,
3509        PaneDockZone::Right,
3510        PaneDockZone::Top,
3511        PaneDockZone::Bottom,
3512        PaneDockZone::Center,
3513    ];
3514    let mut best: Option<PaneDockPreview> = None;
3515    for zone in zones {
3516        let anchor = rect_zone_anchor(rect, zone);
3517        let distance = euclidean_distance(anchor, pointer);
3518        let base = dock_zone_score(distance, radius, zone);
3519        if base <= 0.0 {
3520            continue;
3521        }
3522        let intent = dock_zone_motion_intent(zone, motion);
3523        let score = (base * intent).clamp(0.0, 1.0);
3524        if score <= 0.0 {
3525            continue;
3526        }
3527        let candidate = PaneDockPreview {
3528            target,
3529            zone,
3530            score,
3531            ghost_rect: dock_zone_ghost_rect(rect, zone),
3532        };
3533        match best {
3534            Some(current) if candidate.score <= current.score => {}
3535            _ => best = Some(candidate),
3536        }
3537    }
3538    best
3539}
3540
3541fn zone_to_axis_placement_and_target_share(
3542    zone: PaneDockZone,
3543    incoming_share_bps: u16,
3544) -> (SplitAxis, PanePlacement, u16) {
3545    let incoming = incoming_share_bps.clamp(500, 9_500);
3546    let target_share = 10_000_u16.saturating_sub(incoming);
3547    match zone {
3548        PaneDockZone::Left => (
3549            SplitAxis::Horizontal,
3550            PanePlacement::IncomingFirst,
3551            incoming,
3552        ),
3553        PaneDockZone::Right => (
3554            SplitAxis::Horizontal,
3555            PanePlacement::ExistingFirst,
3556            target_share,
3557        ),
3558        PaneDockZone::Top => (SplitAxis::Vertical, PanePlacement::IncomingFirst, incoming),
3559        PaneDockZone::Bottom => (
3560            SplitAxis::Vertical,
3561            PanePlacement::ExistingFirst,
3562            target_share,
3563        ),
3564        PaneDockZone::Center => (SplitAxis::Horizontal, PanePlacement::ExistingFirst, 5_000),
3565    }
3566}
3567
3568/// Supported structural pane operations.
3569#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3570#[serde(tag = "op", rename_all = "snake_case")]
3571pub enum PaneOperation {
3572    /// Split an existing leaf by wrapping it with a new split parent and adding
3573    /// one new sibling leaf.
3574    SplitLeaf {
3575        target: PaneId,
3576        axis: SplitAxis,
3577        ratio: PaneSplitRatio,
3578        placement: PanePlacement,
3579        new_leaf: PaneLeaf,
3580    },
3581    /// Close a non-root pane (leaf or subtree) and promote its sibling.
3582    CloseNode { target: PaneId },
3583    /// Move an existing subtree next to a target node by wrapping the target in
3584    /// a new split with the source subtree.
3585    MoveSubtree {
3586        source: PaneId,
3587        target: PaneId,
3588        axis: SplitAxis,
3589        ratio: PaneSplitRatio,
3590        placement: PanePlacement,
3591    },
3592    /// Swap two non-ancestor subtrees.
3593    SwapNodes { first: PaneId, second: PaneId },
3594    /// Set an explicit split ratio on an existing split node.
3595    SetSplitRatio {
3596        split: PaneId,
3597        ratio: PaneSplitRatio,
3598    },
3599    /// Canonicalize all split ratios to reduced form and validate positivity.
3600    NormalizeRatios,
3601}
3602
3603impl PaneOperation {
3604    /// Operation family.
3605    #[must_use]
3606    pub const fn kind(&self) -> PaneOperationKind {
3607        match self {
3608            Self::SplitLeaf { .. } => PaneOperationKind::SplitLeaf,
3609            Self::CloseNode { .. } => PaneOperationKind::CloseNode,
3610            Self::MoveSubtree { .. } => PaneOperationKind::MoveSubtree,
3611            Self::SwapNodes { .. } => PaneOperationKind::SwapNodes,
3612            Self::SetSplitRatio { .. } => PaneOperationKind::SetSplitRatio,
3613            Self::NormalizeRatios => PaneOperationKind::NormalizeRatios,
3614        }
3615    }
3616
3617    #[must_use]
3618    fn referenced_nodes(&self) -> Vec<PaneId> {
3619        match self {
3620            Self::SplitLeaf { target, .. } | Self::CloseNode { target } => vec![*target],
3621            Self::MoveSubtree { source, target, .. }
3622            | Self::SwapNodes {
3623                first: source,
3624                second: target,
3625            } => {
3626                vec![*source, *target]
3627            }
3628            Self::SetSplitRatio { split, .. } => vec![*split],
3629            Self::NormalizeRatios => Vec::new(),
3630        }
3631    }
3632}
3633
3634/// Stable operation discriminator used in logs and telemetry.
3635#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3636#[serde(rename_all = "snake_case")]
3637pub enum PaneOperationKind {
3638    SplitLeaf,
3639    CloseNode,
3640    MoveSubtree,
3641    SwapNodes,
3642    SetSplitRatio,
3643    NormalizeRatios,
3644}
3645
3646/// Semantic family of a pane operation.
3647///
3648/// The family partitions operations by how far their effect can reach in the
3649/// tree, which is what makes certified fast paths sound. `Local` operations
3650/// admit cheaper application and validation; `Structural` operations always use
3651/// the conservative clone-and-full-validate baseline. The family is the single
3652/// source of truth for the per-operation execution and validation strategy, so
3653/// the "escalation decision" for any operation is fully recoverable from its
3654/// [`PaneOperationKind`].
3655#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
3656#[serde(rename_all = "snake_case")]
3657pub enum PaneOperationFamily {
3658    /// Bounded mutation whose effect is confined to a single split node and its
3659    /// immediate parent/child closure (currently only `SetSplitRatio`). Eligible
3660    /// for the in-place atomic apply path and local-closure validation, both of
3661    /// which are proven equivalent to the conservative baseline.
3662    Local,
3663    /// Topology-changing mutation that can affect arbitrary regions of the tree
3664    /// (`SplitLeaf`, `CloseNode`, `MoveSubtree`, `SwapNodes`, `NormalizeRatios`).
3665    /// Always uses the conservative clone-and-whole-tree-validate path.
3666    Structural,
3667}
3668
3669impl PaneOperationKind {
3670    /// Classify this operation kind into its [`PaneOperationFamily`].
3671    #[must_use]
3672    pub const fn family(self) -> PaneOperationFamily {
3673        match self {
3674            Self::SetSplitRatio => PaneOperationFamily::Local,
3675            Self::SplitLeaf
3676            | Self::CloseNode
3677            | Self::MoveSubtree
3678            | Self::SwapNodes
3679            | Self::NormalizeRatios => PaneOperationFamily::Structural,
3680        }
3681    }
3682}
3683
3684impl PaneOperation {
3685    /// Classify this operation into its [`PaneOperationFamily`].
3686    #[must_use]
3687    pub const fn family(&self) -> PaneOperationFamily {
3688        self.kind().family()
3689    }
3690}
3691
3692/// Successful transactional operation result.
3693#[derive(Debug, Clone, PartialEq, Eq)]
3694pub struct PaneOperationOutcome {
3695    pub operation_id: u64,
3696    pub kind: PaneOperationKind,
3697    /// Nodes touched by the operation. Inline for the common small case (the
3698    /// resize fast path touches one node), so building an outcome on the hot
3699    /// path does not heap-allocate.
3700    pub touched_nodes: SmallVec<[PaneId; 4]>,
3701    pub before_hash: u64,
3702    pub after_hash: u64,
3703}
3704
3705/// Failure payload for transactional operation APIs.
3706#[derive(Debug, Clone, PartialEq, Eq)]
3707pub struct PaneOperationError {
3708    pub operation_id: u64,
3709    pub kind: PaneOperationKind,
3710    /// Nodes touched by the rejected operation. Inline for the common small case
3711    /// (see [`PaneOperationOutcome::touched_nodes`]).
3712    pub touched_nodes: SmallVec<[PaneId; 4]>,
3713    pub before_hash: u64,
3714    pub after_hash: u64,
3715    pub reason: PaneOperationFailure,
3716}
3717
3718/// Structured reasons for pane operation failure.
3719#[derive(Debug, Clone, PartialEq, Eq)]
3720pub enum PaneOperationFailure {
3721    MissingNode {
3722        node_id: PaneId,
3723    },
3724    NodeNotLeaf {
3725        node_id: PaneId,
3726    },
3727    ParentNotSplit {
3728        node_id: PaneId,
3729    },
3730    ParentChildMismatch {
3731        parent: PaneId,
3732        child: PaneId,
3733    },
3734    CannotCloseRoot {
3735        node_id: PaneId,
3736    },
3737    CannotMoveRoot {
3738        node_id: PaneId,
3739    },
3740    SameNode {
3741        first: PaneId,
3742        second: PaneId,
3743    },
3744    AncestorConflict {
3745        ancestor: PaneId,
3746        descendant: PaneId,
3747    },
3748    TargetRemovedByDetach {
3749        target: PaneId,
3750        detached_parent: PaneId,
3751    },
3752    PaneIdOverflow {
3753        current: PaneId,
3754    },
3755    InvalidRatio {
3756        node_id: PaneId,
3757        numerator: u32,
3758        denominator: u32,
3759    },
3760    Validation(PaneModelError),
3761}
3762
3763impl fmt::Display for PaneOperationFailure {
3764    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3765        match self {
3766            Self::MissingNode { node_id } => write!(f, "node {} not found", node_id.0),
3767            Self::NodeNotLeaf { node_id } => write!(f, "node {} is not a leaf", node_id.0),
3768            Self::ParentNotSplit { node_id } => {
3769                write!(f, "node {} is not a split parent", node_id.0)
3770            }
3771            Self::ParentChildMismatch { parent, child } => write!(
3772                f,
3773                "split parent {} does not reference child {}",
3774                parent.0, child.0
3775            ),
3776            Self::CannotCloseRoot { node_id } => {
3777                write!(f, "cannot close root node {}", node_id.0)
3778            }
3779            Self::CannotMoveRoot { node_id } => {
3780                write!(f, "cannot move root node {}", node_id.0)
3781            }
3782            Self::SameNode { first, second } => write!(
3783                f,
3784                "operation requires distinct nodes, got {} and {}",
3785                first.0, second.0
3786            ),
3787            Self::AncestorConflict {
3788                ancestor,
3789                descendant,
3790            } => write!(
3791                f,
3792                "operation would create cycle: node {} is an ancestor of {}",
3793                ancestor.0, descendant.0
3794            ),
3795            Self::TargetRemovedByDetach {
3796                target,
3797                detached_parent,
3798            } => write!(
3799                f,
3800                "target {} would be removed while detaching parent {}",
3801                target.0, detached_parent.0
3802            ),
3803            Self::PaneIdOverflow { current } => {
3804                write!(f, "pane id overflow after {}", current.0)
3805            }
3806            Self::InvalidRatio {
3807                node_id,
3808                numerator,
3809                denominator,
3810            } => write!(
3811                f,
3812                "split node {} has invalid ratio {numerator}/{denominator}",
3813                node_id.0
3814            ),
3815            Self::Validation(err) => write!(f, "{err}"),
3816        }
3817    }
3818}
3819
3820impl std::error::Error for PaneOperationFailure {
3821    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
3822        if let Self::Validation(err) = self {
3823            return Some(err);
3824        }
3825        None
3826    }
3827}
3828
3829impl fmt::Display for PaneOperationError {
3830    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3831        write!(
3832            f,
3833            "pane op {} ({:?}) failed: {} [nodes={:?}, before_hash={:#x}, after_hash={:#x}]",
3834            self.operation_id,
3835            self.kind,
3836            self.reason,
3837            self.touched_nodes
3838                .iter()
3839                .map(|node_id| node_id.0)
3840                .collect::<Vec<_>>(),
3841            self.before_hash,
3842            self.after_hash
3843        )
3844    }
3845}
3846
3847impl std::error::Error for PaneOperationError {
3848    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
3849        Some(&self.reason)
3850    }
3851}
3852
3853/// One deterministic operation journal row emitted by a transaction.
3854#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3855pub struct PaneOperationJournalEntry {
3856    pub transaction_id: u64,
3857    pub sequence: u64,
3858    pub operation_id: u64,
3859    pub operation: PaneOperation,
3860    pub kind: PaneOperationKind,
3861    pub touched_nodes: Vec<PaneId>,
3862    pub before_hash: u64,
3863    pub after_hash: u64,
3864    pub result: PaneOperationJournalResult,
3865}
3866
3867/// Journal result state for one attempted operation.
3868#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3869#[serde(tag = "status", rename_all = "snake_case")]
3870pub enum PaneOperationJournalResult {
3871    Applied,
3872    Rejected { reason: String },
3873}
3874
3875/// Finalized transaction payload emitted by commit/rollback.
3876#[derive(Debug, Clone, PartialEq, Eq)]
3877pub struct PaneTransactionOutcome {
3878    pub transaction_id: u64,
3879    pub committed: bool,
3880    pub tree: PaneTree,
3881    pub journal: Vec<PaneOperationJournalEntry>,
3882}
3883
3884/// Transaction boundary wrapper for pane mutations.
3885#[derive(Debug, Clone, PartialEq, Eq)]
3886pub struct PaneTransaction {
3887    transaction_id: u64,
3888    sequence: u64,
3889    base_tree: PaneTree,
3890    working_tree: PaneTree,
3891    journal: Vec<PaneOperationJournalEntry>,
3892}
3893
3894impl PaneTransaction {
3895    fn new(transaction_id: u64, base_tree: PaneTree) -> Self {
3896        Self {
3897            transaction_id,
3898            sequence: 1,
3899            base_tree: base_tree.clone(),
3900            working_tree: base_tree,
3901            journal: Vec::new(),
3902        }
3903    }
3904
3905    /// Transaction identifier supplied by the caller.
3906    #[must_use]
3907    pub const fn transaction_id(&self) -> u64 {
3908        self.transaction_id
3909    }
3910
3911    /// Current mutable working tree for read-only inspection.
3912    #[must_use]
3913    pub fn tree(&self) -> &PaneTree {
3914        &self.working_tree
3915    }
3916
3917    /// Journal entries in deterministic insertion order.
3918    #[must_use]
3919    pub fn journal(&self) -> &[PaneOperationJournalEntry] {
3920        &self.journal
3921    }
3922
3923    /// Attempt one operation against the transaction working tree.
3924    ///
3925    /// Every attempt is journaled, including rejected operations.
3926    pub fn apply_operation(
3927        &mut self,
3928        operation_id: u64,
3929        operation: PaneOperation,
3930    ) -> Result<PaneOperationOutcome, PaneOperationError> {
3931        let operation_for_journal = operation.clone();
3932        let kind = operation_for_journal.kind();
3933        let sequence = self.next_sequence();
3934
3935        match self.working_tree.apply_operation(operation_id, operation) {
3936            Ok(outcome) => {
3937                self.journal.push(PaneOperationJournalEntry {
3938                    transaction_id: self.transaction_id,
3939                    sequence,
3940                    operation_id,
3941                    operation: operation_for_journal,
3942                    kind,
3943                    touched_nodes: outcome.touched_nodes.to_vec(),
3944                    before_hash: outcome.before_hash,
3945                    after_hash: outcome.after_hash,
3946                    result: PaneOperationJournalResult::Applied,
3947                });
3948                Ok(outcome)
3949            }
3950            Err(err) => {
3951                self.journal.push(PaneOperationJournalEntry {
3952                    transaction_id: self.transaction_id,
3953                    sequence,
3954                    operation_id,
3955                    operation: operation_for_journal,
3956                    kind,
3957                    touched_nodes: err.touched_nodes.to_vec(),
3958                    before_hash: err.before_hash,
3959                    after_hash: err.after_hash,
3960                    result: PaneOperationJournalResult::Rejected {
3961                        reason: err.reason.to_string(),
3962                    },
3963                });
3964                Err(err)
3965            }
3966        }
3967    }
3968
3969    /// Finalize and keep all successful mutations.
3970    #[must_use]
3971    pub fn commit(self) -> PaneTransactionOutcome {
3972        PaneTransactionOutcome {
3973            transaction_id: self.transaction_id,
3974            committed: true,
3975            tree: self.working_tree,
3976            journal: self.journal,
3977        }
3978    }
3979
3980    /// Finalize and discard all mutations.
3981    #[must_use]
3982    pub fn rollback(self) -> PaneTransactionOutcome {
3983        PaneTransactionOutcome {
3984            transaction_id: self.transaction_id,
3985            committed: false,
3986            tree: self.base_tree,
3987            journal: self.journal,
3988        }
3989    }
3990
3991    fn next_sequence(&mut self) -> u64 {
3992        let sequence = self.sequence;
3993        self.sequence = self.sequence.saturating_add(1);
3994        sequence
3995    }
3996}
3997
3998/// Validated pane tree model for runtime usage.
3999#[derive(Debug, Clone, PartialEq, Eq)]
4000pub struct PaneTree {
4001    schema_version: u16,
4002    root: PaneId,
4003    next_id: PaneId,
4004    nodes: BTreeMap<PaneId, PaneNodeRecord>,
4005    extensions: BTreeMap<String, String>,
4006}
4007
4008impl PaneTree {
4009    /// Build a singleton tree with one root leaf.
4010    #[must_use]
4011    pub fn singleton(surface_key: impl Into<String>) -> Self {
4012        let root = PaneId::MIN;
4013        let mut nodes = BTreeMap::new();
4014        let _ = nodes.insert(
4015            root,
4016            PaneNodeRecord::leaf(root, None, PaneLeaf::new(surface_key)),
4017        );
4018        Self {
4019            schema_version: PANE_TREE_SCHEMA_VERSION,
4020            root,
4021            next_id: root.checked_next().unwrap_or(root),
4022            nodes,
4023            extensions: BTreeMap::new(),
4024        }
4025    }
4026
4027    /// Construct and validate from a serial snapshot.
4028    pub fn from_snapshot(mut snapshot: PaneTreeSnapshot) -> Result<Self, PaneModelError> {
4029        if snapshot.schema_version != PANE_TREE_SCHEMA_VERSION {
4030            return Err(PaneModelError::UnsupportedSchemaVersion {
4031                version: snapshot.schema_version,
4032            });
4033        }
4034        snapshot.canonicalize();
4035        let mut nodes = BTreeMap::new();
4036        for node in snapshot.nodes {
4037            let node_id = node.id;
4038            if nodes.insert(node_id, node).is_some() {
4039                return Err(PaneModelError::DuplicateNodeId { node_id });
4040            }
4041        }
4042        validate_tree(snapshot.root, snapshot.next_id, &nodes)?;
4043        Ok(Self {
4044            schema_version: snapshot.schema_version,
4045            root: snapshot.root,
4046            next_id: snapshot.next_id,
4047            nodes,
4048            extensions: snapshot.extensions,
4049        })
4050    }
4051
4052    /// Export to canonical snapshot form.
4053    #[must_use]
4054    pub fn to_snapshot(&self) -> PaneTreeSnapshot {
4055        let mut snapshot = PaneTreeSnapshot {
4056            schema_version: self.schema_version,
4057            root: self.root,
4058            next_id: self.next_id,
4059            nodes: self.nodes.values().cloned().collect(),
4060            extensions: self.extensions.clone(),
4061        };
4062        snapshot.canonicalize();
4063        snapshot
4064    }
4065
4066    /// Root node ID.
4067    #[must_use]
4068    pub const fn root(&self) -> PaneId {
4069        self.root
4070    }
4071
4072    /// Next deterministic ID value.
4073    #[must_use]
4074    pub const fn next_id(&self) -> PaneId {
4075        self.next_id
4076    }
4077
4078    /// Current schema version.
4079    #[must_use]
4080    pub const fn schema_version(&self) -> u16 {
4081        self.schema_version
4082    }
4083
4084    /// Lookup a node by ID.
4085    #[must_use]
4086    pub fn node(&self, id: PaneId) -> Option<&PaneNodeRecord> {
4087        self.nodes.get(&id)
4088    }
4089
4090    /// Iterate nodes in canonical ID order.
4091    pub fn nodes(&self) -> impl Iterator<Item = &PaneNodeRecord> {
4092        self.nodes.values()
4093    }
4094
4095    pub(crate) const fn extensions(&self) -> &BTreeMap<String, String> {
4096        &self.extensions
4097    }
4098
4099    /// Validate internal invariants.
4100    pub fn validate(&self) -> Result<(), PaneModelError> {
4101        validate_tree(self.root, self.next_id, &self.nodes)
4102    }
4103
4104    /// Structured invariant diagnostics for the current tree snapshot.
4105    #[must_use]
4106    pub fn invariant_report(&self) -> PaneInvariantReport {
4107        self.to_snapshot().invariant_report()
4108    }
4109
4110    /// Deterministic structural hash of the current tree state.
4111    ///
4112    /// This is intended for operation logs and replay diagnostics.
4113    #[must_use]
4114    pub fn state_hash(&self) -> u64 {
4115        self.hash_state(false)
4116    }
4117
4118    /// History pairing distinguishes raw serialized ratios that the public
4119    /// semantic hash normalizes through its accessors. This is a diagnostic
4120    /// fingerprint, not a cryptographic identity or an equality proof.
4121    pub(crate) fn history_state_hash(&self) -> u64 {
4122        self.hash_state(true)
4123    }
4124
4125    fn hash_state(&self, raw_ratios: bool) -> u64 {
4126        const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
4127        const PRIME: u64 = 0x0000_0001_0000_01b3;
4128
4129        fn mix(hash: &mut u64, byte: u8) {
4130            *hash ^= u64::from(byte);
4131            *hash = hash.wrapping_mul(PRIME);
4132        }
4133
4134        fn mix_bytes(hash: &mut u64, bytes: &[u8]) {
4135            for byte in bytes {
4136                mix(hash, *byte);
4137            }
4138        }
4139
4140        fn mix_u16(hash: &mut u64, value: u16) {
4141            mix_bytes(hash, &value.to_le_bytes());
4142        }
4143
4144        fn mix_u32(hash: &mut u64, value: u32) {
4145            mix_bytes(hash, &value.to_le_bytes());
4146        }
4147
4148        fn mix_u64(hash: &mut u64, value: u64) {
4149            mix_bytes(hash, &value.to_le_bytes());
4150        }
4151
4152        fn mix_bool(hash: &mut u64, value: bool) {
4153            mix(hash, u8::from(value));
4154        }
4155
4156        fn mix_opt_u16(hash: &mut u64, value: Option<u16>) {
4157            match value {
4158                Some(value) => {
4159                    mix(hash, 1);
4160                    mix_u16(hash, value);
4161                }
4162                None => mix(hash, 0),
4163            }
4164        }
4165
4166        fn mix_opt_pane_id(hash: &mut u64, value: Option<PaneId>) {
4167            match value {
4168                Some(value) => {
4169                    mix(hash, 1);
4170                    mix_u64(hash, value.get());
4171                }
4172                None => mix(hash, 0),
4173            }
4174        }
4175
4176        fn mix_str(hash: &mut u64, value: &str) {
4177            mix_u64(hash, value.len() as u64);
4178            mix_bytes(hash, value.as_bytes());
4179        }
4180
4181        fn mix_extensions(hash: &mut u64, extensions: &BTreeMap<String, String>) {
4182            mix_u64(hash, extensions.len() as u64);
4183            for (key, value) in extensions {
4184                mix_str(hash, key);
4185                mix_str(hash, value);
4186            }
4187        }
4188
4189        fn mix_constraints(hash: &mut u64, constraints: PaneConstraints) {
4190            mix_u16(hash, constraints.min_width);
4191            mix_u16(hash, constraints.min_height);
4192            mix_opt_u16(hash, constraints.max_width);
4193            mix_opt_u16(hash, constraints.max_height);
4194            mix_bool(hash, constraints.collapsible);
4195        }
4196
4197        let mut hash = OFFSET_BASIS;
4198        mix_u16(&mut hash, self.schema_version);
4199        mix_u64(&mut hash, self.root.get());
4200        mix_u64(&mut hash, self.next_id.get());
4201        mix_extensions(&mut hash, &self.extensions);
4202        mix_u64(&mut hash, self.nodes.len() as u64);
4203
4204        for node in self.nodes.values() {
4205            mix_u64(&mut hash, node.id.get());
4206            mix_opt_pane_id(&mut hash, node.parent);
4207            mix_constraints(&mut hash, node.constraints);
4208            mix_extensions(&mut hash, &node.extensions);
4209
4210            match &node.kind {
4211                PaneNodeKind::Leaf(leaf) => {
4212                    mix(&mut hash, 1);
4213                    mix_str(&mut hash, &leaf.surface_key);
4214                    mix_extensions(&mut hash, &leaf.extensions);
4215                }
4216                PaneNodeKind::Split(split) => {
4217                    mix(&mut hash, 2);
4218                    let axis_byte = match split.axis {
4219                        SplitAxis::Horizontal => 1,
4220                        SplitAxis::Vertical => 2,
4221                    };
4222                    mix(&mut hash, axis_byte);
4223                    mix_u32(
4224                        &mut hash,
4225                        if raw_ratios {
4226                            split.ratio.numerator
4227                        } else {
4228                            split.ratio.numerator()
4229                        },
4230                    );
4231                    mix_u32(
4232                        &mut hash,
4233                        if raw_ratios {
4234                            split.ratio.denominator
4235                        } else {
4236                            split.ratio.denominator()
4237                        },
4238                    );
4239                    mix_u64(&mut hash, split.first.get());
4240                    mix_u64(&mut hash, split.second.get());
4241                }
4242            }
4243        }
4244
4245        hash
4246    }
4247
4248    /// Start a transaction boundary for one or more structural operations.
4249    ///
4250    /// Transactions stage mutations on a cloned working tree and provide a
4251    /// deterministic operation journal for replay, undo/redo, and auditing.
4252    #[must_use]
4253    pub fn begin_transaction(&self, transaction_id: u64) -> PaneTransaction {
4254        PaneTransaction::new(transaction_id, self.clone())
4255    }
4256
4257    /// Apply one structural operation atomically.
4258    ///
4259    /// The operation is executed on a cloned working tree. On success, the
4260    /// mutated clone replaces `self`; on failure, `self` is unchanged.
4261    ///
4262    /// Operations in the [`PaneOperationFamily::Local`] family take a certified
4263    /// fast path (in-place atomic mutation + local-closure validation) that is
4264    /// proven equivalent to the conservative baseline in
4265    /// `tests/pane_operation_family_equivalence.rs`. To bypass every fast path
4266    /// and force the conservative whole-tree baseline, use
4267    /// [`PaneTree::apply_operation_conservative`].
4268    pub fn apply_operation(
4269        &mut self,
4270        operation_id: u64,
4271        operation: PaneOperation,
4272    ) -> Result<PaneOperationOutcome, PaneOperationError> {
4273        if let PaneOperation::SetSplitRatio { split, ratio } = operation {
4274            // Certified Local fast path: confine work to the touched split.
4275            return self.apply_set_split_ratio_atomic(operation_id, split, ratio);
4276        }
4277
4278        self.apply_operation_generic(operation_id, operation, PaneValidationMode::Adaptive)
4279    }
4280
4281    /// Apply one structural operation using the conservative baseline path.
4282    ///
4283    /// This always clones a working tree and runs the whole-tree validator
4284    /// regardless of [`PaneOperationFamily`], bypassing every certified fast
4285    /// path. It is the easy-to-force conservative validator for diagnosis,
4286    /// rollback, and rollout, and serves as the differential oracle that the
4287    /// `Local` fast paths are proven equivalent to. Semantics (accept/reject and
4288    /// resulting tree) are identical to [`PaneTree::apply_operation`]; only the
4289    /// execution and validation cost differ.
4290    pub fn apply_operation_conservative(
4291        &mut self,
4292        operation_id: u64,
4293        operation: PaneOperation,
4294    ) -> Result<PaneOperationOutcome, PaneOperationError> {
4295        self.apply_operation_generic(operation_id, operation, PaneValidationMode::AlwaysFull)
4296    }
4297
4298    /// Generic clone-based application shared by the adaptive and conservative
4299    /// entry points. The `mode` selects whether validation follows the operation
4300    /// family ([`PaneValidationMode::Adaptive`]) or is forced to the whole-tree
4301    /// validator ([`PaneValidationMode::AlwaysFull`]).
4302    fn apply_operation_generic(
4303        &mut self,
4304        operation_id: u64,
4305        operation: PaneOperation,
4306        mode: PaneValidationMode,
4307    ) -> Result<PaneOperationOutcome, PaneOperationError> {
4308        let kind = operation.kind();
4309        let before_hash = self.state_hash();
4310        let mut working = self.clone();
4311        let mut touched = operation
4312            .referenced_nodes()
4313            .into_iter()
4314            .collect::<BTreeSet<_>>();
4315
4316        if let Err(reason) = working.apply_operation_inner(operation, &mut touched) {
4317            return Err(PaneOperationError {
4318                operation_id,
4319                kind,
4320                touched_nodes: touched.into_iter().collect(),
4321                before_hash,
4322                after_hash: working.state_hash(),
4323                reason,
4324            });
4325        }
4326
4327        // Collect the touched set once and reuse it for validation and the
4328        // outcome (compact storage; the `&SmallVec` coerces to `&[PaneId]`).
4329        let touched_nodes: SmallVec<[PaneId; 4]> = touched.into_iter().collect();
4330        if let Err(err) = working.validate_after_operation_with_mode(kind, &touched_nodes, mode) {
4331            return Err(PaneOperationError {
4332                operation_id,
4333                kind,
4334                touched_nodes,
4335                before_hash,
4336                after_hash: working.state_hash(),
4337                reason: PaneOperationFailure::Validation(err),
4338            });
4339        }
4340
4341        let after_hash = working.state_hash();
4342        *self = working;
4343
4344        Ok(PaneOperationOutcome {
4345            operation_id,
4346            kind,
4347            touched_nodes,
4348            before_hash,
4349            after_hash,
4350        })
4351    }
4352
4353    fn apply_set_split_ratio_atomic(
4354        &mut self,
4355        operation_id: u64,
4356        split_id: PaneId,
4357        ratio: PaneSplitRatio,
4358    ) -> Result<PaneOperationOutcome, PaneOperationError> {
4359        let kind = PaneOperationKind::SetSplitRatio;
4360        let before_hash = self.state_hash();
4361        let normalized =
4362            PaneSplitRatio::new(ratio.numerator(), ratio.denominator()).map_err(|_| {
4363                PaneOperationError {
4364                    operation_id,
4365                    kind,
4366                    touched_nodes: smallvec![split_id],
4367                    before_hash,
4368                    after_hash: before_hash,
4369                    reason: PaneOperationFailure::InvalidRatio {
4370                        node_id: split_id,
4371                        numerator: ratio.numerator(),
4372                        denominator: ratio.denominator(),
4373                    },
4374                }
4375            })?;
4376
4377        let previous_ratio = {
4378            let node = self.nodes.get_mut(&split_id).ok_or(PaneOperationError {
4379                operation_id,
4380                kind,
4381                touched_nodes: smallvec![split_id],
4382                before_hash,
4383                after_hash: before_hash,
4384                reason: PaneOperationFailure::MissingNode { node_id: split_id },
4385            })?;
4386            let PaneNodeKind::Split(split) = &mut node.kind else {
4387                return Err(PaneOperationError {
4388                    operation_id,
4389                    kind,
4390                    touched_nodes: smallvec![split_id],
4391                    before_hash,
4392                    after_hash: before_hash,
4393                    reason: PaneOperationFailure::ParentNotSplit { node_id: split_id },
4394                });
4395            };
4396            let previous_ratio = split.ratio;
4397            split.ratio = normalized;
4398            previous_ratio
4399        };
4400
4401        if let Err(err) = self.validate_after_operation(kind, &[split_id]) {
4402            let node = self.nodes.get_mut(&split_id).ok_or(PaneOperationError {
4403                operation_id,
4404                kind,
4405                touched_nodes: smallvec![split_id],
4406                before_hash,
4407                after_hash: before_hash,
4408                reason: PaneOperationFailure::Validation(err.clone()),
4409            })?;
4410            let PaneNodeKind::Split(split) = &mut node.kind else {
4411                return Err(PaneOperationError {
4412                    operation_id,
4413                    kind,
4414                    touched_nodes: smallvec![split_id],
4415                    before_hash,
4416                    after_hash: before_hash,
4417                    reason: PaneOperationFailure::Validation(err),
4418                });
4419            };
4420            split.ratio = previous_ratio;
4421            return Err(PaneOperationError {
4422                operation_id,
4423                kind,
4424                touched_nodes: smallvec![split_id],
4425                before_hash,
4426                after_hash: before_hash,
4427                reason: PaneOperationFailure::Validation(err),
4428            });
4429        }
4430
4431        let after_hash = self.state_hash();
4432        Ok(PaneOperationOutcome {
4433            operation_id,
4434            kind,
4435            touched_nodes: smallvec![split_id],
4436            before_hash,
4437            after_hash,
4438        })
4439    }
4440
4441    fn apply_operation_in_place_for_replay(
4442        &mut self,
4443        operation_id: u64,
4444        operation: &PaneOperation,
4445    ) -> Result<(), PaneOperationError> {
4446        let kind = operation.kind();
4447        let before_hash = self.state_hash();
4448        let referenced: SmallVec<[PaneId; 4]> = operation.referenced_nodes().into_iter().collect();
4449        let mut touched = referenced.iter().copied().collect::<BTreeSet<_>>();
4450
4451        if let Err(reason) = self.apply_operation_inner_ref(operation, &mut touched) {
4452            return Err(PaneOperationError {
4453                operation_id,
4454                kind,
4455                touched_nodes: referenced,
4456                before_hash,
4457                after_hash: self.state_hash(),
4458                reason,
4459            });
4460        }
4461
4462        // Validation walks the grown touched set (compact slice); errors keep
4463        // reporting the initially-referenced nodes, preserving prior semantics.
4464        let grown: SmallVec<[PaneId; 4]> = touched.into_iter().collect();
4465        if let Err(err) = self.validate_after_operation(kind, &grown) {
4466            return Err(PaneOperationError {
4467                operation_id,
4468                kind,
4469                touched_nodes: referenced,
4470                before_hash,
4471                after_hash: self.state_hash(),
4472                reason: PaneOperationFailure::Validation(err),
4473            });
4474        }
4475
4476        Ok(())
4477    }
4478
4479    fn validate_after_operation(
4480        &self,
4481        kind: PaneOperationKind,
4482        touched: &[PaneId],
4483    ) -> Result<(), PaneModelError> {
4484        self.validate_after_operation_with_mode(kind, touched, PaneValidationMode::Adaptive)
4485    }
4486
4487    fn validate_after_operation_with_mode(
4488        &self,
4489        kind: PaneOperationKind,
4490        touched: &[PaneId],
4491        mode: PaneValidationMode,
4492    ) -> Result<(), PaneModelError> {
4493        let strategy = match mode {
4494            PaneValidationMode::AlwaysFull => PaneValidationStrategy::FullTree,
4495            PaneValidationMode::Adaptive => self.validation_strategy_for_operation(kind),
4496        };
4497        match strategy {
4498            PaneValidationStrategy::FullTree => self.validate(),
4499            PaneValidationStrategy::LocalClosure => self.validate_local_closure(touched),
4500        }
4501    }
4502
4503    /// Map an operation kind to its validation strategy via its operation family.
4504    /// The family is the single source of truth, so this is the deterministic,
4505    /// auditable "escalation decision" for any operation.
4506    const fn validation_strategy_for_operation(
4507        &self,
4508        kind: PaneOperationKind,
4509    ) -> PaneValidationStrategy {
4510        match kind.family() {
4511            PaneOperationFamily::Local => PaneValidationStrategy::LocalClosure,
4512            PaneOperationFamily::Structural => PaneValidationStrategy::FullTree,
4513        }
4514    }
4515
4516    fn validate_local_closure(&self, touched: &[PaneId]) -> Result<(), PaneModelError> {
4517        for node_id in touched {
4518            let node = self
4519                .nodes
4520                .get(node_id)
4521                .ok_or(PaneModelError::MissingRoot { root: *node_id })?;
4522            node.constraints.validate(*node_id)?;
4523
4524            if *node_id == self.root {
4525                if let Some(parent) = node.parent {
4526                    return Err(PaneModelError::RootHasParent {
4527                        root: self.root,
4528                        parent,
4529                    });
4530                }
4531            } else if let Some(parent_id) = node.parent {
4532                let parent = self
4533                    .nodes
4534                    .get(&parent_id)
4535                    .ok_or(PaneModelError::MissingParent {
4536                        node_id: *node_id,
4537                        parent: parent_id,
4538                    })?;
4539                let PaneNodeKind::Split(split) = &parent.kind else {
4540                    return Err(PaneModelError::ParentMismatch {
4541                        node_id: *node_id,
4542                        expected: Some(parent_id),
4543                        actual: node.parent,
4544                    });
4545                };
4546                if split.first != *node_id && split.second != *node_id {
4547                    return Err(PaneModelError::ParentMismatch {
4548                        node_id: *node_id,
4549                        expected: Some(parent_id),
4550                        actual: node.parent,
4551                    });
4552                }
4553            }
4554
4555            if let PaneNodeKind::Split(split) = &node.kind {
4556                if split.ratio.numerator() == 0 || split.ratio.denominator() == 0 {
4557                    return Err(PaneModelError::InvalidSplitRatio {
4558                        numerator: split.ratio.numerator(),
4559                        denominator: split.ratio.denominator(),
4560                    });
4561                }
4562                if split.first == *node_id || split.second == *node_id {
4563                    return Err(PaneModelError::SelfReferentialSplit { node_id: *node_id });
4564                }
4565                if split.first == split.second {
4566                    return Err(PaneModelError::DuplicateSplitChildren {
4567                        node_id: *node_id,
4568                        child: split.first,
4569                    });
4570                }
4571                for child_id in [split.first, split.second] {
4572                    let child = self
4573                        .nodes
4574                        .get(&child_id)
4575                        .ok_or(PaneModelError::MissingChild {
4576                            parent: *node_id,
4577                            child: child_id,
4578                        })?;
4579                    if child.parent != Some(*node_id) {
4580                        return Err(PaneModelError::ParentMismatch {
4581                            node_id: child_id,
4582                            expected: Some(*node_id),
4583                            actual: child.parent,
4584                        });
4585                    }
4586                }
4587            }
4588        }
4589
4590        Ok(())
4591    }
4592
4593    fn apply_operation_inner(
4594        &mut self,
4595        operation: PaneOperation,
4596        touched: &mut BTreeSet<PaneId>,
4597    ) -> Result<(), PaneOperationFailure> {
4598        match operation {
4599            PaneOperation::SplitLeaf {
4600                target,
4601                axis,
4602                ratio,
4603                placement,
4604                new_leaf,
4605            } => self.apply_split_leaf(target, axis, ratio, placement, new_leaf, touched),
4606            PaneOperation::CloseNode { target } => self.apply_close_node(target, touched),
4607            PaneOperation::MoveSubtree {
4608                source,
4609                target,
4610                axis,
4611                ratio,
4612                placement,
4613            } => self.apply_move_subtree(source, target, axis, ratio, placement, touched),
4614            PaneOperation::SwapNodes { first, second } => {
4615                self.apply_swap_nodes(first, second, touched)
4616            }
4617            PaneOperation::SetSplitRatio { split, ratio } => {
4618                self.apply_set_split_ratio(split, ratio, touched)
4619            }
4620            PaneOperation::NormalizeRatios => self.apply_normalize_ratios(touched),
4621        }
4622    }
4623
4624    fn apply_operation_inner_ref(
4625        &mut self,
4626        operation: &PaneOperation,
4627        touched: &mut BTreeSet<PaneId>,
4628    ) -> Result<(), PaneOperationFailure> {
4629        match operation {
4630            PaneOperation::SplitLeaf {
4631                target,
4632                axis,
4633                ratio,
4634                placement,
4635                new_leaf,
4636            } => self.apply_split_leaf(
4637                *target,
4638                *axis,
4639                *ratio,
4640                *placement,
4641                new_leaf.clone(),
4642                touched,
4643            ),
4644            PaneOperation::CloseNode { target } => self.apply_close_node(*target, touched),
4645            PaneOperation::MoveSubtree {
4646                source,
4647                target,
4648                axis,
4649                ratio,
4650                placement,
4651            } => self.apply_move_subtree(*source, *target, *axis, *ratio, *placement, touched),
4652            PaneOperation::SwapNodes { first, second } => {
4653                self.apply_swap_nodes(*first, *second, touched)
4654            }
4655            PaneOperation::SetSplitRatio { split, ratio } => {
4656                self.apply_set_split_ratio(*split, *ratio, touched)
4657            }
4658            PaneOperation::NormalizeRatios => self.apply_normalize_ratios(touched),
4659        }
4660    }
4661
4662    fn apply_split_leaf(
4663        &mut self,
4664        target: PaneId,
4665        axis: SplitAxis,
4666        ratio: PaneSplitRatio,
4667        placement: PanePlacement,
4668        new_leaf: PaneLeaf,
4669        touched: &mut BTreeSet<PaneId>,
4670    ) -> Result<(), PaneOperationFailure> {
4671        let target_parent = match self.nodes.get(&target) {
4672            Some(PaneNodeRecord {
4673                parent,
4674                kind: PaneNodeKind::Leaf(_),
4675                ..
4676            }) => *parent,
4677            Some(_) => {
4678                return Err(PaneOperationFailure::NodeNotLeaf { node_id: target });
4679            }
4680            None => {
4681                return Err(PaneOperationFailure::MissingNode { node_id: target });
4682            }
4683        };
4684
4685        let split_id = self.allocate_node_id()?;
4686        let new_leaf_id = self.allocate_node_id()?;
4687        touched.extend([target, split_id, new_leaf_id]);
4688        if let Some(parent_id) = target_parent {
4689            let _ = touched.insert(parent_id);
4690        }
4691
4692        let (first, second) = placement.ordered(target, new_leaf_id);
4693        let split_record = PaneNodeRecord::split(
4694            split_id,
4695            target_parent,
4696            PaneSplit {
4697                axis,
4698                ratio,
4699                first,
4700                second,
4701            },
4702        );
4703
4704        if let Some(target_node) = self.nodes.get_mut(&target) {
4705            target_node.parent = Some(split_id);
4706        }
4707        let _ = self.nodes.insert(
4708            new_leaf_id,
4709            PaneNodeRecord::leaf(new_leaf_id, Some(split_id), new_leaf),
4710        );
4711        let _ = self.nodes.insert(split_id, split_record);
4712
4713        if let Some(parent_id) = target_parent {
4714            self.replace_child(parent_id, target, split_id)?;
4715        } else {
4716            self.root = split_id;
4717        }
4718
4719        Ok(())
4720    }
4721
4722    fn apply_close_node(
4723        &mut self,
4724        target: PaneId,
4725        touched: &mut BTreeSet<PaneId>,
4726    ) -> Result<(), PaneOperationFailure> {
4727        if !self.nodes.contains_key(&target) {
4728            return Err(PaneOperationFailure::MissingNode { node_id: target });
4729        }
4730        if target == self.root {
4731            return Err(PaneOperationFailure::CannotCloseRoot { node_id: target });
4732        }
4733
4734        let subtree_ids = self.collect_subtree_ids(target)?;
4735        for node_id in &subtree_ids {
4736            let _ = touched.insert(*node_id);
4737        }
4738
4739        let (parent_id, sibling_id, grandparent_id) =
4740            self.promote_sibling_after_detach(target, touched)?;
4741        let _ = touched.insert(parent_id);
4742        let _ = touched.insert(sibling_id);
4743        if let Some(grandparent_id) = grandparent_id {
4744            let _ = touched.insert(grandparent_id);
4745        }
4746
4747        for node_id in subtree_ids {
4748            let _ = self.nodes.remove(&node_id);
4749        }
4750
4751        Ok(())
4752    }
4753
4754    fn apply_move_subtree(
4755        &mut self,
4756        source: PaneId,
4757        target: PaneId,
4758        axis: SplitAxis,
4759        ratio: PaneSplitRatio,
4760        placement: PanePlacement,
4761        touched: &mut BTreeSet<PaneId>,
4762    ) -> Result<(), PaneOperationFailure> {
4763        if source == target {
4764            return Err(PaneOperationFailure::SameNode {
4765                first: source,
4766                second: target,
4767            });
4768        }
4769
4770        if !self.nodes.contains_key(&source) {
4771            return Err(PaneOperationFailure::MissingNode { node_id: source });
4772        }
4773        if !self.nodes.contains_key(&target) {
4774            return Err(PaneOperationFailure::MissingNode { node_id: target });
4775        }
4776
4777        if source == self.root {
4778            return Err(PaneOperationFailure::CannotMoveRoot { node_id: source });
4779        }
4780        if self.is_ancestor(source, target)? {
4781            return Err(PaneOperationFailure::AncestorConflict {
4782                ancestor: source,
4783                descendant: target,
4784            });
4785        }
4786
4787        let source_parent = self
4788            .nodes
4789            .get(&source)
4790            .and_then(|node| node.parent)
4791            .ok_or(PaneOperationFailure::CannotMoveRoot { node_id: source })?;
4792        if source_parent == target {
4793            return Err(PaneOperationFailure::TargetRemovedByDetach {
4794                target,
4795                detached_parent: source_parent,
4796            });
4797        }
4798
4799        let _ = touched.insert(source);
4800        let _ = touched.insert(target);
4801        let _ = touched.insert(source_parent);
4802
4803        let (removed_parent, sibling_id, grandparent_id) =
4804            self.promote_sibling_after_detach(source, touched)?;
4805        let _ = touched.insert(removed_parent);
4806        let _ = touched.insert(sibling_id);
4807        if let Some(grandparent_id) = grandparent_id {
4808            let _ = touched.insert(grandparent_id);
4809        }
4810
4811        if let Some(source_node) = self.nodes.get_mut(&source) {
4812            source_node.parent = None;
4813        }
4814
4815        if !self.nodes.contains_key(&target) {
4816            return Err(PaneOperationFailure::MissingNode { node_id: target });
4817        }
4818        let target_parent = self.nodes.get(&target).and_then(|node| node.parent);
4819        if let Some(parent_id) = target_parent {
4820            let _ = touched.insert(parent_id);
4821        }
4822
4823        let split_id = self.allocate_node_id()?;
4824        let _ = touched.insert(split_id);
4825        let (first, second) = placement.ordered(target, source);
4826
4827        if let Some(target_node) = self.nodes.get_mut(&target) {
4828            target_node.parent = Some(split_id);
4829        }
4830        if let Some(source_node) = self.nodes.get_mut(&source) {
4831            source_node.parent = Some(split_id);
4832        }
4833
4834        let _ = self.nodes.insert(
4835            split_id,
4836            PaneNodeRecord::split(
4837                split_id,
4838                target_parent,
4839                PaneSplit {
4840                    axis,
4841                    ratio,
4842                    first,
4843                    second,
4844                },
4845            ),
4846        );
4847
4848        if let Some(parent_id) = target_parent {
4849            self.replace_child(parent_id, target, split_id)?;
4850        } else {
4851            self.root = split_id;
4852        }
4853
4854        Ok(())
4855    }
4856
4857    fn apply_swap_nodes(
4858        &mut self,
4859        first: PaneId,
4860        second: PaneId,
4861        touched: &mut BTreeSet<PaneId>,
4862    ) -> Result<(), PaneOperationFailure> {
4863        if first == second {
4864            return Ok(());
4865        }
4866
4867        if !self.nodes.contains_key(&first) {
4868            return Err(PaneOperationFailure::MissingNode { node_id: first });
4869        }
4870        if !self.nodes.contains_key(&second) {
4871            return Err(PaneOperationFailure::MissingNode { node_id: second });
4872        }
4873        if self.is_ancestor(first, second)? {
4874            return Err(PaneOperationFailure::AncestorConflict {
4875                ancestor: first,
4876                descendant: second,
4877            });
4878        }
4879        if self.is_ancestor(second, first)? {
4880            return Err(PaneOperationFailure::AncestorConflict {
4881                ancestor: second,
4882                descendant: first,
4883            });
4884        }
4885
4886        let _ = touched.insert(first);
4887        let _ = touched.insert(second);
4888
4889        let first_parent = self.nodes.get(&first).and_then(|node| node.parent);
4890        let second_parent = self.nodes.get(&second).and_then(|node| node.parent);
4891
4892        if first_parent == second_parent {
4893            if let Some(parent_id) = first_parent {
4894                let _ = touched.insert(parent_id);
4895                self.swap_children(parent_id, first, second)?;
4896            }
4897            return Ok(());
4898        }
4899
4900        match (first_parent, second_parent) {
4901            (Some(left_parent), Some(right_parent)) => {
4902                let _ = touched.insert(left_parent);
4903                let _ = touched.insert(right_parent);
4904                self.replace_child(left_parent, first, second)?;
4905                self.replace_child(right_parent, second, first)?;
4906                if let Some(left) = self.nodes.get_mut(&first) {
4907                    left.parent = Some(right_parent);
4908                }
4909                if let Some(right) = self.nodes.get_mut(&second) {
4910                    right.parent = Some(left_parent);
4911                }
4912            }
4913            (None, Some(parent_id)) => {
4914                let _ = touched.insert(parent_id);
4915                self.replace_child(parent_id, second, first)?;
4916                if let Some(first_node) = self.nodes.get_mut(&first) {
4917                    first_node.parent = Some(parent_id);
4918                }
4919                if let Some(second_node) = self.nodes.get_mut(&second) {
4920                    second_node.parent = None;
4921                }
4922                self.root = second;
4923            }
4924            (Some(parent_id), None) => {
4925                let _ = touched.insert(parent_id);
4926                self.replace_child(parent_id, first, second)?;
4927                if let Some(first_node) = self.nodes.get_mut(&first) {
4928                    first_node.parent = None;
4929                }
4930                if let Some(second_node) = self.nodes.get_mut(&second) {
4931                    second_node.parent = Some(parent_id);
4932                }
4933                self.root = first;
4934            }
4935            (None, None) => {}
4936        }
4937
4938        Ok(())
4939    }
4940
4941    fn apply_normalize_ratios(
4942        &mut self,
4943        touched: &mut BTreeSet<PaneId>,
4944    ) -> Result<(), PaneOperationFailure> {
4945        for node in self.nodes.values_mut() {
4946            if let PaneNodeKind::Split(split) = &mut node.kind {
4947                let normalized =
4948                    PaneSplitRatio::new(split.ratio.numerator(), split.ratio.denominator())
4949                        .map_err(|_| PaneOperationFailure::InvalidRatio {
4950                            node_id: node.id,
4951                            numerator: split.ratio.numerator(),
4952                            denominator: split.ratio.denominator(),
4953                        })?;
4954                split.ratio = normalized;
4955                let _ = touched.insert(node.id);
4956            }
4957        }
4958        Ok(())
4959    }
4960
4961    fn apply_set_split_ratio(
4962        &mut self,
4963        split_id: PaneId,
4964        ratio: PaneSplitRatio,
4965        touched: &mut BTreeSet<PaneId>,
4966    ) -> Result<(), PaneOperationFailure> {
4967        let node = self
4968            .nodes
4969            .get_mut(&split_id)
4970            .ok_or(PaneOperationFailure::MissingNode { node_id: split_id })?;
4971        let PaneNodeKind::Split(split) = &mut node.kind else {
4972            return Err(PaneOperationFailure::ParentNotSplit { node_id: split_id });
4973        };
4974        split.ratio =
4975            PaneSplitRatio::new(ratio.numerator(), ratio.denominator()).map_err(|_| {
4976                PaneOperationFailure::InvalidRatio {
4977                    node_id: split_id,
4978                    numerator: ratio.numerator(),
4979                    denominator: ratio.denominator(),
4980                }
4981            })?;
4982        let _ = touched.insert(split_id);
4983        Ok(())
4984    }
4985
4986    fn replace_child(
4987        &mut self,
4988        parent_id: PaneId,
4989        old_child: PaneId,
4990        new_child: PaneId,
4991    ) -> Result<(), PaneOperationFailure> {
4992        let parent = self
4993            .nodes
4994            .get_mut(&parent_id)
4995            .ok_or(PaneOperationFailure::MissingNode { node_id: parent_id })?;
4996        let PaneNodeKind::Split(split) = &mut parent.kind else {
4997            return Err(PaneOperationFailure::ParentNotSplit { node_id: parent_id });
4998        };
4999
5000        if split.first == old_child {
5001            split.first = new_child;
5002            return Ok(());
5003        }
5004        if split.second == old_child {
5005            split.second = new_child;
5006            return Ok(());
5007        }
5008
5009        Err(PaneOperationFailure::ParentChildMismatch {
5010            parent: parent_id,
5011            child: old_child,
5012        })
5013    }
5014
5015    fn swap_children(
5016        &mut self,
5017        parent_id: PaneId,
5018        left: PaneId,
5019        right: PaneId,
5020    ) -> Result<(), PaneOperationFailure> {
5021        let parent = self
5022            .nodes
5023            .get_mut(&parent_id)
5024            .ok_or(PaneOperationFailure::MissingNode { node_id: parent_id })?;
5025        let PaneNodeKind::Split(split) = &mut parent.kind else {
5026            return Err(PaneOperationFailure::ParentNotSplit { node_id: parent_id });
5027        };
5028
5029        let has_pair = (split.first == left && split.second == right)
5030            || (split.first == right && split.second == left);
5031        if !has_pair {
5032            return Err(PaneOperationFailure::ParentChildMismatch {
5033                parent: parent_id,
5034                child: left,
5035            });
5036        }
5037
5038        std::mem::swap(&mut split.first, &mut split.second);
5039        Ok(())
5040    }
5041
5042    fn promote_sibling_after_detach(
5043        &mut self,
5044        detached: PaneId,
5045        touched: &mut BTreeSet<PaneId>,
5046    ) -> Result<(PaneId, PaneId, Option<PaneId>), PaneOperationFailure> {
5047        let parent_id = self
5048            .nodes
5049            .get(&detached)
5050            .ok_or(PaneOperationFailure::MissingNode { node_id: detached })?
5051            .parent
5052            .ok_or(PaneOperationFailure::CannotMoveRoot { node_id: detached })?;
5053        let parent_node = self
5054            .nodes
5055            .get(&parent_id)
5056            .ok_or(PaneOperationFailure::MissingNode { node_id: parent_id })?;
5057        let PaneNodeKind::Split(parent_split) = &parent_node.kind else {
5058            return Err(PaneOperationFailure::ParentNotSplit { node_id: parent_id });
5059        };
5060
5061        let sibling_id = if parent_split.first == detached {
5062            parent_split.second
5063        } else if parent_split.second == detached {
5064            parent_split.first
5065        } else {
5066            return Err(PaneOperationFailure::ParentChildMismatch {
5067                parent: parent_id,
5068                child: detached,
5069            });
5070        };
5071
5072        let grandparent_id = parent_node.parent;
5073        let _ = touched.insert(parent_id);
5074        let _ = touched.insert(sibling_id);
5075        if let Some(grandparent_id) = grandparent_id {
5076            let _ = touched.insert(grandparent_id);
5077            self.replace_child(grandparent_id, parent_id, sibling_id)?;
5078        } else {
5079            self.root = sibling_id;
5080        }
5081
5082        let sibling_node =
5083            self.nodes
5084                .get_mut(&sibling_id)
5085                .ok_or(PaneOperationFailure::MissingNode {
5086                    node_id: sibling_id,
5087                })?;
5088        sibling_node.parent = grandparent_id;
5089        let _ = self.nodes.remove(&parent_id);
5090
5091        Ok((parent_id, sibling_id, grandparent_id))
5092    }
5093
5094    fn is_ancestor(
5095        &self,
5096        ancestor: PaneId,
5097        mut node_id: PaneId,
5098    ) -> Result<bool, PaneOperationFailure> {
5099        loop {
5100            let node = self
5101                .nodes
5102                .get(&node_id)
5103                .ok_or(PaneOperationFailure::MissingNode { node_id })?;
5104            let Some(parent_id) = node.parent else {
5105                return Ok(false);
5106            };
5107            if parent_id == ancestor {
5108                return Ok(true);
5109            }
5110            node_id = parent_id;
5111        }
5112    }
5113
5114    fn collect_subtree_ids(&self, root_id: PaneId) -> Result<Vec<PaneId>, PaneOperationFailure> {
5115        if !self.nodes.contains_key(&root_id) {
5116            return Err(PaneOperationFailure::MissingNode { node_id: root_id });
5117        }
5118
5119        let mut out = Vec::new();
5120        let mut stack = vec![root_id];
5121        while let Some(node_id) = stack.pop() {
5122            let node = self
5123                .nodes
5124                .get(&node_id)
5125                .ok_or(PaneOperationFailure::MissingNode { node_id })?;
5126            out.push(node_id);
5127            if let PaneNodeKind::Split(split) = &node.kind {
5128                stack.push(split.first);
5129                stack.push(split.second);
5130            }
5131        }
5132        Ok(out)
5133    }
5134
5135    fn allocate_node_id(&mut self) -> Result<PaneId, PaneOperationFailure> {
5136        let current = self.next_id;
5137        self.next_id = self
5138            .next_id
5139            .checked_next()
5140            .map_err(|_| PaneOperationFailure::PaneIdOverflow { current })?;
5141        Ok(current)
5142    }
5143
5144    /// Solve the split-tree into concrete rectangles for the provided viewport.
5145    ///
5146    /// Deterministic tie-break rule:
5147    /// - Desired split size is `floor(available * ratio)`.
5148    /// - If clamping is required by constraints, we clamp into the feasible
5149    ///   interval for the first child's entire subtree; remainder goes to the
5150    ///   second child. Descendant bounds are propagated before placing nodes.
5151    ///
5152    /// Complexity:
5153    /// - Time: `O(node_count * log(node_count))` (two DFS passes with map lookups)
5154    /// - Space: `O(node_count)` (subtree bounds and output rectangle maps)
5155    pub fn solve_layout(&self, area: Rect) -> Result<PaneLayout, PaneModelError> {
5156        let mut bounds = BTreeMap::new();
5157        self.subtree_constraints(self.root, &mut bounds)?;
5158        let mut rects = BTreeMap::new();
5159        self.solve_node(self.root, area, &bounds, &mut rects)?;
5160        Ok(PaneLayout { area, rects })
5161    }
5162
5163    fn subtree_constraints(
5164        &self,
5165        node_id: PaneId,
5166        bounds: &mut BTreeMap<PaneId, PaneConstraints>,
5167    ) -> Result<PaneConstraints, PaneModelError> {
5168        let node = self
5169            .nodes
5170            .get(&node_id)
5171            .ok_or(PaneModelError::MissingRoot { root: node_id })?;
5172        let mut constraints = node.constraints;
5173        if let PaneNodeKind::Split(split) = &node.kind {
5174            for child in [split.first, split.second] {
5175                if !self.nodes.contains_key(&child) {
5176                    return Err(PaneModelError::MissingChild {
5177                        parent: node_id,
5178                        child,
5179                    });
5180                }
5181            }
5182            let first = self.subtree_constraints(split.first, bounds)?;
5183            let second = self.subtree_constraints(split.second, bounds)?;
5184            let width = subtree_axis_bounds(
5185                node_id,
5186                SplitAxis::Horizontal,
5187                split.axis,
5188                constraints,
5189                first,
5190                second,
5191            )?;
5192            let height = subtree_axis_bounds(
5193                node_id,
5194                SplitAxis::Vertical,
5195                split.axis,
5196                constraints,
5197                first,
5198                second,
5199            )?;
5200            constraints.min_width = width.min;
5201            constraints.max_width = width.max;
5202            constraints.min_height = height.min;
5203            constraints.max_height = height.max;
5204        }
5205        bounds.insert(node_id, constraints);
5206        Ok(constraints)
5207    }
5208
5209    fn solve_node(
5210        &self,
5211        node_id: PaneId,
5212        area: Rect,
5213        bounds: &BTreeMap<PaneId, PaneConstraints>,
5214        rects: &mut BTreeMap<PaneId, Rect>,
5215    ) -> Result<(), PaneModelError> {
5216        let Some(node) = self.nodes.get(&node_id) else {
5217            return Err(PaneModelError::MissingRoot { root: node_id });
5218        };
5219
5220        validate_area_against_constraints(node_id, area, node.constraints)?;
5221        let _ = rects.insert(node_id, area);
5222
5223        let PaneNodeKind::Split(split) = &node.kind else {
5224            return Ok(());
5225        };
5226
5227        let first_constraints = bounds
5228            .get(&split.first)
5229            .ok_or(PaneModelError::MissingChild {
5230                parent: node_id,
5231                child: split.first,
5232            })?;
5233        let second_constraints = bounds
5234            .get(&split.second)
5235            .ok_or(PaneModelError::MissingChild {
5236                parent: node_id,
5237                child: split.second,
5238            })?;
5239
5240        let available = match split.axis {
5241            SplitAxis::Horizontal => area.width,
5242            SplitAxis::Vertical => area.height,
5243        };
5244
5245        let (first_size, second_size) = solve_split_sizes(
5246            node_id,
5247            split.axis,
5248            available,
5249            split.ratio,
5250            axis_bounds(*first_constraints, split.axis),
5251            axis_bounds(*second_constraints, split.axis),
5252        )?;
5253
5254        let (first_rect, second_rect) = match split.axis {
5255            SplitAxis::Horizontal => (
5256                Rect::new(area.x, area.y, first_size, area.height),
5257                Rect::new(
5258                    area.x.saturating_add(first_size),
5259                    area.y,
5260                    second_size,
5261                    area.height,
5262                ),
5263            ),
5264            SplitAxis::Vertical => (
5265                Rect::new(area.x, area.y, area.width, first_size),
5266                Rect::new(
5267                    area.x,
5268                    area.y.saturating_add(first_size),
5269                    area.width,
5270                    second_size,
5271                ),
5272            ),
5273        };
5274
5275        self.solve_node(split.first, first_rect, bounds, rects)?;
5276        self.solve_node(split.second, second_rect, bounds, rects)?;
5277        Ok(())
5278    }
5279
5280    /// Pick the best magnetic docking preview at a pointer location.
5281    #[must_use]
5282    pub fn choose_dock_preview(
5283        &self,
5284        layout: &PaneLayout,
5285        pointer: PanePointerPosition,
5286        magnetic_field_cells: f64,
5287    ) -> Option<PaneDockPreview> {
5288        self.choose_dock_preview_excluding(layout, pointer, magnetic_field_cells, None)
5289    }
5290
5291    /// Return top-ranked magnetic docking candidates (best-first) using
5292    /// motion-aware intent weighting.
5293    #[must_use]
5294    pub fn ranked_dock_previews_with_motion(
5295        &self,
5296        layout: &PaneLayout,
5297        pointer: PanePointerPosition,
5298        motion: PaneMotionVector,
5299        magnetic_field_cells: f64,
5300        excluded: Option<PaneId>,
5301        limit: usize,
5302    ) -> Vec<PaneDockPreview> {
5303        self.collect_dock_previews_excluding_with_motion(
5304            layout,
5305            pointer,
5306            magnetic_field_cells,
5307            excluded,
5308            motion,
5309            limit,
5310        )
5311    }
5312
5313    /// Plan a pane move with inertial projection, magnetic docking, and
5314    /// pressure-sensitive snapping.
5315    pub fn plan_reflow_move_with_preview(
5316        &self,
5317        source: PaneId,
5318        layout: &PaneLayout,
5319        pointer: PanePointerPosition,
5320        motion: PaneMotionVector,
5321        inertial: Option<PaneInertialThrow>,
5322        magnetic_field_cells: f64,
5323    ) -> Result<PaneReflowMovePlan, PaneReflowPlanError> {
5324        if !self.nodes.contains_key(&source) {
5325            return Err(PaneReflowPlanError::MissingSource { source });
5326        }
5327        if source == self.root {
5328            return Err(PaneReflowPlanError::SourceCannotMoveRoot { source });
5329        }
5330
5331        let projected = inertial
5332            .map(|profile| profile.projected_pointer(pointer))
5333            .unwrap_or(pointer);
5334        let preview = self
5335            .choose_dock_preview_excluding_with_motion(
5336                layout,
5337                projected,
5338                magnetic_field_cells,
5339                Some(source),
5340                motion,
5341            )
5342            .ok_or(PaneReflowPlanError::NoDockTarget)?;
5343
5344        let snap_profile = PanePressureSnapProfile::from_motion(motion);
5345        let magnetic_boost = (preview.score * 1_800.0).round().clamp(0.0, 1_800.0) as u16;
5346        let incoming_share_bps = snap_profile
5347            .strength_bps
5348            .saturating_sub(2_200)
5349            .saturating_add(magnetic_boost / 2)
5350            .clamp(2_400, 7_800);
5351
5352        let operations = if preview.zone == PaneDockZone::Center {
5353            vec![PaneOperation::SwapNodes {
5354                first: source,
5355                second: preview.target,
5356            }]
5357        } else {
5358            let (axis, placement, target_first_share) =
5359                zone_to_axis_placement_and_target_share(preview.zone, incoming_share_bps);
5360            let ratio = PaneSplitRatio::new(
5361                u32::from(target_first_share.max(1)),
5362                u32::from(10_000_u16.saturating_sub(target_first_share).max(1)),
5363            )
5364            .map_err(|_| PaneReflowPlanError::InvalidRatio {
5365                numerator: u32::from(target_first_share.max(1)),
5366                denominator: u32::from(10_000_u16.saturating_sub(target_first_share).max(1)),
5367            })?;
5368            vec![PaneOperation::MoveSubtree {
5369                source,
5370                target: preview.target,
5371                axis,
5372                ratio,
5373                placement,
5374            }]
5375        };
5376
5377        Ok(PaneReflowMovePlan {
5378            source,
5379            pointer,
5380            projected_pointer: projected,
5381            preview,
5382            snap_profile,
5383            operations,
5384        })
5385    }
5386
5387    /// Apply a previously planned reflow move.
5388    pub fn apply_reflow_move_plan(
5389        &mut self,
5390        operation_seed: u64,
5391        plan: &PaneReflowMovePlan,
5392    ) -> Result<Vec<PaneOperationOutcome>, PaneOperationError> {
5393        let mut outcomes = Vec::with_capacity(plan.operations.len());
5394        for (index, operation) in plan.operations.iter().cloned().enumerate() {
5395            let outcome =
5396                self.apply_operation(operation_seed.saturating_add(index as u64), operation)?;
5397            outcomes.push(outcome);
5398        }
5399        Ok(outcomes)
5400    }
5401
5402    /// Plan any-edge / any-corner organic resize for one leaf.
5403    pub fn plan_edge_resize(
5404        &self,
5405        leaf: PaneId,
5406        layout: &PaneLayout,
5407        grip: PaneResizeGrip,
5408        pointer: PanePointerPosition,
5409        pressure: PanePressureSnapProfile,
5410    ) -> Result<PaneEdgeResizePlan, PaneEdgeResizePlanError> {
5411        let node = self
5412            .nodes
5413            .get(&leaf)
5414            .ok_or(PaneEdgeResizePlanError::MissingLeaf { leaf })?;
5415        if !matches!(node.kind, PaneNodeKind::Leaf(_)) {
5416            return Err(PaneEdgeResizePlanError::NodeNotLeaf { node: leaf });
5417        }
5418
5419        let tuned_snap = pressure.apply_to_tuning(PaneSnapTuning::default());
5420        let mut operations = Vec::with_capacity(2);
5421
5422        if let Some(_toward_max) = grip.horizontal_edge() {
5423            let split_id = self
5424                .nearest_axis_split_for_node(leaf, SplitAxis::Horizontal)
5425                .ok_or(PaneEdgeResizePlanError::NoAxisSplit {
5426                    leaf,
5427                    axis: SplitAxis::Horizontal,
5428                })?;
5429            let split_rect = layout
5430                .rect(split_id)
5431                .ok_or(PaneEdgeResizePlanError::MissingLayoutRect { node: split_id })?;
5432            let share = axis_share_from_pointer(
5433                split_rect,
5434                pointer,
5435                SplitAxis::Horizontal,
5436                PANE_EDGE_GRIP_INSET_CELLS,
5437            );
5438            let raw_bps = elastic_ratio_bps(
5439                (share * 10_000.0).round().clamp(1.0, 9_999.0) as u16,
5440                pressure,
5441            );
5442            let snapped = tuned_snap
5443                .decide(raw_bps, None)
5444                .snapped_ratio_bps
5445                .unwrap_or(raw_bps);
5446            let ratio = PaneSplitRatio::new(
5447                u32::from(snapped.max(1)),
5448                u32::from(10_000_u16.saturating_sub(snapped).max(1)),
5449            )
5450            .map_err(|_| PaneEdgeResizePlanError::InvalidRatio {
5451                numerator: u32::from(snapped.max(1)),
5452                denominator: u32::from(10_000_u16.saturating_sub(snapped).max(1)),
5453            })?;
5454            operations.push(PaneOperation::SetSplitRatio {
5455                split: split_id,
5456                ratio,
5457            });
5458        }
5459
5460        if let Some(_toward_max) = grip.vertical_edge() {
5461            let split_id = self
5462                .nearest_axis_split_for_node(leaf, SplitAxis::Vertical)
5463                .ok_or(PaneEdgeResizePlanError::NoAxisSplit {
5464                    leaf,
5465                    axis: SplitAxis::Vertical,
5466                })?;
5467            let split_rect = layout
5468                .rect(split_id)
5469                .ok_or(PaneEdgeResizePlanError::MissingLayoutRect { node: split_id })?;
5470            let share = axis_share_from_pointer(
5471                split_rect,
5472                pointer,
5473                SplitAxis::Vertical,
5474                PANE_EDGE_GRIP_INSET_CELLS,
5475            );
5476            let raw_bps = elastic_ratio_bps(
5477                (share * 10_000.0).round().clamp(1.0, 9_999.0) as u16,
5478                pressure,
5479            );
5480            let snapped = tuned_snap
5481                .decide(raw_bps, None)
5482                .snapped_ratio_bps
5483                .unwrap_or(raw_bps);
5484            let ratio = PaneSplitRatio::new(
5485                u32::from(snapped.max(1)),
5486                u32::from(10_000_u16.saturating_sub(snapped).max(1)),
5487            )
5488            .map_err(|_| PaneEdgeResizePlanError::InvalidRatio {
5489                numerator: u32::from(snapped.max(1)),
5490                denominator: u32::from(10_000_u16.saturating_sub(snapped).max(1)),
5491            })?;
5492            operations.push(PaneOperation::SetSplitRatio {
5493                split: split_id,
5494                ratio,
5495            });
5496        }
5497
5498        Ok(PaneEdgeResizePlan {
5499            leaf,
5500            grip,
5501            operations,
5502        })
5503    }
5504
5505    /// Apply all operations generated by an edge/corner resize plan.
5506    pub fn apply_edge_resize_plan(
5507        &mut self,
5508        operation_seed: u64,
5509        plan: &PaneEdgeResizePlan,
5510    ) -> Result<Vec<PaneOperationOutcome>, PaneOperationError> {
5511        let mut outcomes = Vec::with_capacity(plan.operations.len());
5512        for (index, operation) in plan.operations.iter().cloned().enumerate() {
5513            outcomes.push(
5514                self.apply_operation(operation_seed.saturating_add(index as u64), operation)?,
5515            );
5516        }
5517        Ok(outcomes)
5518    }
5519
5520    /// Build a normalized split ratio from a first-child share in basis points.
5521    ///
5522    /// The share is clamped to `1..=9_999` so neither child collapses to a zero
5523    /// ratio, mirroring the bounds enforced by [`PaneTree::plan_edge_resize`].
5524    fn ratio_from_first_share_bps(
5525        first_share_bps: u16,
5526    ) -> Result<PaneSplitRatio, PaneSplitterResizePlanError> {
5527        let first = first_share_bps.clamp(1, 9_999);
5528        let numerator = u32::from(first);
5529        let denominator = u32::from(10_000_u16 - first);
5530        PaneSplitRatio::new(numerator, denominator).map_err(|_| {
5531            PaneSplitterResizePlanError::InvalidRatio {
5532                numerator,
5533                denominator,
5534            }
5535        })
5536    }
5537
5538    /// Resolve a [`PaneResizeTarget`] to its split node, verifying axis agreement.
5539    fn resolve_splitter_target(
5540        &self,
5541        target: PaneResizeTarget,
5542    ) -> Result<&PaneSplit, PaneSplitterResizePlanError> {
5543        let node =
5544            self.nodes
5545                .get(&target.split_id)
5546                .ok_or(PaneSplitterResizePlanError::MissingSplit {
5547                    split: target.split_id,
5548                })?;
5549        let PaneNodeKind::Split(split) = &node.kind else {
5550            return Err(PaneSplitterResizePlanError::NotASplit {
5551                node: target.split_id,
5552            });
5553        };
5554        if split.axis != target.axis {
5555            return Err(PaneSplitterResizePlanError::AxisMismatch {
5556                split: target.split_id,
5557                expected: target.axis,
5558                actual: split.axis,
5559            });
5560        }
5561        Ok(split)
5562    }
5563
5564    /// Plan a split-ratio operation for a directly-addressed splitter target
5565    /// from one pointer sample.
5566    ///
5567    /// This is the splitter-handle analogue of [`PaneTree::plan_edge_resize`]:
5568    /// where `plan_edge_resize` walks from a leaf to its nearest ancestor split,
5569    /// this resizes the split named by [`PaneResizeTarget`] directly. The pointer
5570    /// position is projected onto the split's axis (with the same elastic edge
5571    /// resistance and pressure-tuned snapping used by edge resize) to derive the
5572    /// new first-child share. It is the pointer-drag primitive consumed by
5573    /// [`PaneTree::operations_for_transition`].
5574    pub fn plan_splitter_resize(
5575        &self,
5576        target: PaneResizeTarget,
5577        layout: &PaneLayout,
5578        pointer: PanePointerPosition,
5579        pressure: PanePressureSnapProfile,
5580    ) -> Result<PaneOperation, PaneSplitterResizePlanError> {
5581        self.resolve_splitter_target(target)?;
5582        let split_rect =
5583            layout
5584                .rect(target.split_id)
5585                .ok_or(PaneSplitterResizePlanError::MissingLayoutRect {
5586                    node: target.split_id,
5587                })?;
5588        let share =
5589            axis_share_from_pointer(split_rect, pointer, target.axis, PANE_EDGE_GRIP_INSET_CELLS);
5590        let raw_bps = elastic_ratio_bps(
5591            (share * 10_000.0).round().clamp(1.0, 9_999.0) as u16,
5592            pressure,
5593        );
5594        let snapped = pressure
5595            .apply_to_tuning(PaneSnapTuning::default())
5596            .decide(raw_bps, None)
5597            .snapped_ratio_bps
5598            .unwrap_or(raw_bps);
5599        let ratio = Self::ratio_from_first_share_bps(snapped)?;
5600        Ok(PaneOperation::SetSplitRatio {
5601            split: target.split_id,
5602            ratio,
5603        })
5604    }
5605
5606    /// Plan a discrete split-ratio nudge for a directly-addressed splitter
5607    /// target.
5608    ///
5609    /// The split's *current* ratio is stepped by `delta_bps`: positive values
5610    /// grow the first child, negative values grow the second. This realizes
5611    /// keyboard- and wheel-driven resize transitions, which carry no pointer
5612    /// geometry and instead advance the existing ratio.
5613    pub fn plan_splitter_nudge(
5614        &self,
5615        target: PaneResizeTarget,
5616        delta_bps: i32,
5617    ) -> Result<PaneOperation, PaneSplitterResizePlanError> {
5618        let split = self.resolve_splitter_target(target)?;
5619        let total = u64::from(split.ratio.numerator()) + u64::from(split.ratio.denominator());
5620        let current_bps = ((u64::from(split.ratio.numerator()) * 10_000) / total) as i32;
5621        let next_bps = current_bps.saturating_add(delta_bps).clamp(1, 9_999) as u16;
5622        let ratio = Self::ratio_from_first_share_bps(next_bps)?;
5623        Ok(PaneOperation::SetSplitRatio {
5624            split: target.split_id,
5625            ratio,
5626        })
5627    }
5628
5629    /// Bridge one drag/resize state-machine transition into the pane operations
5630    /// that realize it against this tree.
5631    ///
5632    /// This is the connective tissue between host input adapters — the terminal
5633    /// `PaneTerminalAdapter` and the web pointer-capture adapter — and live
5634    /// [`PaneTree`] mutation. Adapters emit [`PaneDragResizeTransition`] values;
5635    /// this method converts each geometry-bearing effect into [`PaneOperation`]s
5636    /// ready for [`PaneTree::apply_operation`]:
5637    ///
5638    /// - `DragStarted` / `DragUpdated` / `Committed` → pointer-derived
5639    ///   [`PaneTree::plan_splitter_resize`] at the effect's current/end position.
5640    /// - `KeyboardApplied` / `WheelApplied` → [`PaneTree::plan_splitter_nudge`]
5641    ///   stepping by [`PANE_SNAP_DEFAULT_STEP_BPS`] per unit/line.
5642    ///
5643    /// Non-geometric transitions (`Armed`, `Canceled`, `Noop`) and targets that
5644    /// can no longer be resolved against `layout` (for example a split removed
5645    /// since the gesture began) yield an empty vector. For diagnostics on
5646    /// resolution failures, call [`PaneTree::plan_splitter_resize`] /
5647    /// [`PaneTree::plan_splitter_nudge`] directly.
5648    #[must_use]
5649    pub fn operations_for_transition(
5650        &self,
5651        transition: &PaneDragResizeTransition,
5652        layout: &PaneLayout,
5653        pressure: PanePressureSnapProfile,
5654    ) -> Vec<PaneOperation> {
5655        let planned = match transition.effect {
5656            PaneDragResizeEffect::DragStarted {
5657                target, current, ..
5658            }
5659            | PaneDragResizeEffect::DragUpdated {
5660                target, current, ..
5661            } => self.plan_splitter_resize(target, layout, current, pressure),
5662            PaneDragResizeEffect::Committed { target, end, .. } => {
5663                self.plan_splitter_resize(target, layout, end, pressure)
5664            }
5665            PaneDragResizeEffect::KeyboardApplied {
5666                target,
5667                direction,
5668                units,
5669            } => {
5670                let magnitude = i32::from(units) * i32::from(PANE_SNAP_DEFAULT_STEP_BPS);
5671                let delta_bps = match direction {
5672                    PaneResizeDirection::Increase => magnitude,
5673                    PaneResizeDirection::Decrease => -magnitude,
5674                };
5675                self.plan_splitter_nudge(target, delta_bps)
5676            }
5677            PaneDragResizeEffect::WheelApplied { target, lines } => {
5678                let delta_bps = i32::from(lines) * i32::from(PANE_SNAP_DEFAULT_STEP_BPS);
5679                self.plan_splitter_nudge(target, delta_bps)
5680            }
5681            PaneDragResizeEffect::Armed { .. }
5682            | PaneDragResizeEffect::Canceled { .. }
5683            | PaneDragResizeEffect::Noop { .. } => return Vec::new(),
5684        };
5685        planned.into_iter().collect()
5686    }
5687
5688    /// Plan a cluster move by moving the anchor and then reattaching members.
5689    pub fn plan_group_move(
5690        &self,
5691        selection: &PaneSelectionState,
5692        layout: &PaneLayout,
5693        pointer: PanePointerPosition,
5694        motion: PaneMotionVector,
5695        inertial: Option<PaneInertialThrow>,
5696        magnetic_field_cells: f64,
5697    ) -> Result<PaneGroupTransformPlan, PaneReflowPlanError> {
5698        if selection.is_empty() {
5699            return Ok(PaneGroupTransformPlan {
5700                members: Vec::new(),
5701                operations: Vec::new(),
5702            });
5703        }
5704        let members = selection.as_sorted_vec();
5705        let anchor = selection.anchor.unwrap_or(members[0]);
5706        let reflow = self.plan_reflow_move_with_preview(
5707            anchor,
5708            layout,
5709            pointer,
5710            motion,
5711            inertial,
5712            magnetic_field_cells,
5713        )?;
5714        let mut operations = reflow.operations.clone();
5715        if members.len() > 1 {
5716            let (axis, placement, target_first_share) =
5717                zone_to_axis_placement_and_target_share(reflow.preview.zone, 5_000);
5718            let ratio = PaneSplitRatio::new(
5719                u32::from(target_first_share.max(1)),
5720                u32::from(10_000_u16.saturating_sub(target_first_share).max(1)),
5721            )
5722            .map_err(|_| PaneReflowPlanError::InvalidRatio {
5723                numerator: u32::from(target_first_share.max(1)),
5724                denominator: u32::from(10_000_u16.saturating_sub(target_first_share).max(1)),
5725            })?;
5726            for member in members.iter().copied().filter(|member| *member != anchor) {
5727                operations.push(PaneOperation::MoveSubtree {
5728                    source: member,
5729                    target: anchor,
5730                    axis,
5731                    ratio,
5732                    placement,
5733                });
5734            }
5735        }
5736        Ok(PaneGroupTransformPlan {
5737            members,
5738            operations,
5739        })
5740    }
5741
5742    /// Plan a cluster resize by resizing the shared outer boundary while
5743    /// preserving internal cluster ratios.
5744    pub fn plan_group_resize(
5745        &self,
5746        selection: &PaneSelectionState,
5747        layout: &PaneLayout,
5748        grip: PaneResizeGrip,
5749        pointer: PanePointerPosition,
5750        pressure: PanePressureSnapProfile,
5751    ) -> Result<PaneGroupTransformPlan, PaneEdgeResizePlanError> {
5752        if selection.is_empty() {
5753            return Ok(PaneGroupTransformPlan {
5754                members: Vec::new(),
5755                operations: Vec::new(),
5756            });
5757        }
5758        let members = selection.as_sorted_vec();
5759        let cluster_root = self
5760            .lowest_common_ancestor(&members)
5761            .unwrap_or_else(|| selection.anchor.unwrap_or(members[0]));
5762        let proxy_leaf = selection.anchor.unwrap_or(members[0]);
5763
5764        let tuned_snap = pressure.apply_to_tuning(PaneSnapTuning::default());
5765        let mut operations = Vec::with_capacity(2);
5766
5767        if grip.horizontal_edge().is_some() {
5768            let split_id = self
5769                .nearest_axis_split_for_node(cluster_root, SplitAxis::Horizontal)
5770                .ok_or(PaneEdgeResizePlanError::NoAxisSplit {
5771                    leaf: proxy_leaf,
5772                    axis: SplitAxis::Horizontal,
5773                })?;
5774            let split_rect = layout
5775                .rect(split_id)
5776                .ok_or(PaneEdgeResizePlanError::MissingLayoutRect { node: split_id })?;
5777            let share = axis_share_from_pointer(
5778                split_rect,
5779                pointer,
5780                SplitAxis::Horizontal,
5781                PANE_EDGE_GRIP_INSET_CELLS,
5782            );
5783            let raw_bps = elastic_ratio_bps(
5784                (share * 10_000.0).round().clamp(1.0, 9_999.0) as u16,
5785                pressure,
5786            );
5787            let snapped = tuned_snap
5788                .decide(raw_bps, None)
5789                .snapped_ratio_bps
5790                .unwrap_or(raw_bps);
5791            let ratio = PaneSplitRatio::new(
5792                u32::from(snapped.max(1)),
5793                u32::from(10_000_u16.saturating_sub(snapped).max(1)),
5794            )
5795            .map_err(|_| PaneEdgeResizePlanError::InvalidRatio {
5796                numerator: u32::from(snapped.max(1)),
5797                denominator: u32::from(10_000_u16.saturating_sub(snapped).max(1)),
5798            })?;
5799            operations.push(PaneOperation::SetSplitRatio {
5800                split: split_id,
5801                ratio,
5802            });
5803        }
5804
5805        if grip.vertical_edge().is_some() {
5806            let split_id = self
5807                .nearest_axis_split_for_node(cluster_root, SplitAxis::Vertical)
5808                .ok_or(PaneEdgeResizePlanError::NoAxisSplit {
5809                    leaf: proxy_leaf,
5810                    axis: SplitAxis::Vertical,
5811                })?;
5812            let split_rect = layout
5813                .rect(split_id)
5814                .ok_or(PaneEdgeResizePlanError::MissingLayoutRect { node: split_id })?;
5815            let share = axis_share_from_pointer(
5816                split_rect,
5817                pointer,
5818                SplitAxis::Vertical,
5819                PANE_EDGE_GRIP_INSET_CELLS,
5820            );
5821            let raw_bps = elastic_ratio_bps(
5822                (share * 10_000.0).round().clamp(1.0, 9_999.0) as u16,
5823                pressure,
5824            );
5825            let snapped = tuned_snap
5826                .decide(raw_bps, None)
5827                .snapped_ratio_bps
5828                .unwrap_or(raw_bps);
5829            let ratio = PaneSplitRatio::new(
5830                u32::from(snapped.max(1)),
5831                u32::from(10_000_u16.saturating_sub(snapped).max(1)),
5832            )
5833            .map_err(|_| PaneEdgeResizePlanError::InvalidRatio {
5834                numerator: u32::from(snapped.max(1)),
5835                denominator: u32::from(10_000_u16.saturating_sub(snapped).max(1)),
5836            })?;
5837            operations.push(PaneOperation::SetSplitRatio {
5838                split: split_id,
5839                ratio,
5840            });
5841        }
5842
5843        Ok(PaneGroupTransformPlan {
5844            members,
5845            operations,
5846        })
5847    }
5848
5849    /// Apply a group transform plan.
5850    pub fn apply_group_transform_plan(
5851        &mut self,
5852        operation_seed: u64,
5853        plan: &PaneGroupTransformPlan,
5854    ) -> Result<Vec<PaneOperationOutcome>, PaneOperationError> {
5855        let mut outcomes = Vec::with_capacity(plan.operations.len());
5856        for (index, operation) in plan.operations.iter().cloned().enumerate() {
5857            outcomes.push(
5858                self.apply_operation(operation_seed.saturating_add(index as u64), operation)?,
5859            );
5860        }
5861        Ok(outcomes)
5862    }
5863
5864    /// Plan adaptive topology transitions using core split-tree operations.
5865    pub fn plan_intelligence_mode(
5866        &self,
5867        mode: PaneLayoutIntelligenceMode,
5868        primary: PaneId,
5869    ) -> Result<Vec<PaneOperation>, PaneReflowPlanError> {
5870        if !self.nodes.contains_key(&primary) {
5871            return Err(PaneReflowPlanError::MissingSource { source: primary });
5872        }
5873        let mut leaves = self
5874            .nodes
5875            .values()
5876            .filter_map(|node| matches!(node.kind, PaneNodeKind::Leaf(_)).then_some(node.id))
5877            .collect::<Vec<_>>();
5878        leaves.sort_unstable();
5879        let secondary = leaves.iter().copied().find(|leaf| *leaf != primary);
5880
5881        let focused_ratio =
5882            PaneSplitRatio::new(7, 3).map_err(|_| PaneReflowPlanError::InvalidRatio {
5883                numerator: 7,
5884                denominator: 3,
5885            })?;
5886        let balanced_ratio =
5887            PaneSplitRatio::new(1, 1).map_err(|_| PaneReflowPlanError::InvalidRatio {
5888                numerator: 1,
5889                denominator: 1,
5890            })?;
5891        let monitor_ratio =
5892            PaneSplitRatio::new(2, 1).map_err(|_| PaneReflowPlanError::InvalidRatio {
5893                numerator: 2,
5894                denominator: 1,
5895            })?;
5896
5897        let mut operations = Vec::new();
5898        match mode {
5899            PaneLayoutIntelligenceMode::Focus => {
5900                if primary != self.root {
5901                    operations.push(PaneOperation::MoveSubtree {
5902                        source: primary,
5903                        target: self.root,
5904                        axis: SplitAxis::Horizontal,
5905                        ratio: focused_ratio,
5906                        placement: PanePlacement::IncomingFirst,
5907                    });
5908                }
5909            }
5910            PaneLayoutIntelligenceMode::Compare => {
5911                if let Some(other) = secondary
5912                    && other != primary
5913                {
5914                    operations.push(PaneOperation::MoveSubtree {
5915                        source: primary,
5916                        target: other,
5917                        axis: SplitAxis::Horizontal,
5918                        ratio: balanced_ratio,
5919                        placement: PanePlacement::IncomingFirst,
5920                    });
5921                }
5922            }
5923            PaneLayoutIntelligenceMode::Monitor => {
5924                if primary != self.root {
5925                    operations.push(PaneOperation::MoveSubtree {
5926                        source: primary,
5927                        target: self.root,
5928                        axis: SplitAxis::Vertical,
5929                        ratio: monitor_ratio,
5930                        placement: PanePlacement::IncomingFirst,
5931                    });
5932                }
5933            }
5934            PaneLayoutIntelligenceMode::Compact => {
5935                for node in self.nodes.values() {
5936                    if matches!(node.kind, PaneNodeKind::Split(_)) {
5937                        operations.push(PaneOperation::SetSplitRatio {
5938                            split: node.id,
5939                            ratio: balanced_ratio,
5940                        });
5941                    }
5942                }
5943                operations.push(PaneOperation::NormalizeRatios);
5944            }
5945        }
5946        Ok(operations)
5947    }
5948
5949    fn choose_dock_preview_excluding(
5950        &self,
5951        layout: &PaneLayout,
5952        pointer: PanePointerPosition,
5953        magnetic_field_cells: f64,
5954        excluded: Option<PaneId>,
5955    ) -> Option<PaneDockPreview> {
5956        let mut best: Option<PaneDockPreview> = None;
5957        for node in self.nodes.values() {
5958            if !matches!(node.kind, PaneNodeKind::Leaf(_)) {
5959                continue;
5960            }
5961            if excluded == Some(node.id) {
5962                continue;
5963            }
5964            let Some(rect) = layout.rect(node.id) else {
5965                continue;
5966            };
5967            let Some(candidate) =
5968                dock_preview_for_rect(node.id, rect, pointer, magnetic_field_cells)
5969            else {
5970                continue;
5971            };
5972            match best {
5973                Some(current)
5974                    if candidate.score < current.score
5975                        || (candidate.score == current.score
5976                            && candidate.target > current.target) => {}
5977                _ => best = Some(candidate),
5978            }
5979        }
5980        best
5981    }
5982
5983    fn choose_dock_preview_excluding_with_motion(
5984        &self,
5985        layout: &PaneLayout,
5986        pointer: PanePointerPosition,
5987        magnetic_field_cells: f64,
5988        excluded: Option<PaneId>,
5989        motion: PaneMotionVector,
5990    ) -> Option<PaneDockPreview> {
5991        self.collect_dock_previews_excluding_with_motion(
5992            layout,
5993            pointer,
5994            magnetic_field_cells,
5995            excluded,
5996            motion,
5997            1,
5998        )
5999        .into_iter()
6000        .next()
6001    }
6002
6003    fn collect_dock_previews_excluding_with_motion(
6004        &self,
6005        layout: &PaneLayout,
6006        pointer: PanePointerPosition,
6007        magnetic_field_cells: f64,
6008        excluded: Option<PaneId>,
6009        motion: PaneMotionVector,
6010        limit: usize,
6011    ) -> Vec<PaneDockPreview> {
6012        let limit = limit.max(1);
6013        let mut candidates = Vec::new();
6014        for node in self.nodes.values() {
6015            if !matches!(node.kind, PaneNodeKind::Leaf(_)) {
6016                continue;
6017            }
6018            if excluded == Some(node.id) {
6019                continue;
6020            }
6021            let Some(rect) = layout.rect(node.id) else {
6022                continue;
6023            };
6024            let Some(candidate) = dock_preview_for_rect_with_motion(
6025                node.id,
6026                rect,
6027                pointer,
6028                magnetic_field_cells,
6029                motion,
6030            ) else {
6031                continue;
6032            };
6033            candidates.push(candidate);
6034        }
6035        candidates.sort_by(|left, right| {
6036            right
6037                .score
6038                .total_cmp(&left.score)
6039                .then_with(|| left.target.cmp(&right.target))
6040                .then_with(|| dock_zone_rank(left.zone).cmp(&dock_zone_rank(right.zone)))
6041        });
6042        if candidates.len() > limit {
6043            candidates.truncate(limit);
6044        }
6045        candidates
6046    }
6047
6048    fn nearest_axis_split_for_node(&self, node: PaneId, axis: SplitAxis) -> Option<PaneId> {
6049        let mut cursor = Some(node);
6050        while let Some(node_id) = cursor {
6051            let parent = self.nodes.get(&node_id).and_then(|record| record.parent)?;
6052            let parent_record = self.nodes.get(&parent)?;
6053            if let PaneNodeKind::Split(split) = &parent_record.kind
6054                && split.axis == axis
6055            {
6056                return Some(parent);
6057            }
6058            cursor = Some(parent);
6059        }
6060        None
6061    }
6062
6063    fn lowest_common_ancestor(&self, nodes: &[PaneId]) -> Option<PaneId> {
6064        if nodes.is_empty() {
6065            return None;
6066        }
6067        let mut ancestor_paths = nodes
6068            .iter()
6069            .map(|node_id| self.ancestor_chain(*node_id))
6070            .collect::<Option<Vec<_>>>()?;
6071        let first = ancestor_paths.remove(0);
6072        first
6073            .into_iter()
6074            .find(|candidate| ancestor_paths.iter().all(|path| path.contains(candidate)))
6075    }
6076
6077    fn ancestor_chain(&self, node: PaneId) -> Option<Vec<PaneId>> {
6078        let mut out = Vec::new();
6079        let mut cursor = Some(node);
6080        while let Some(node_id) = cursor {
6081            if !self.nodes.contains_key(&node_id) {
6082                return None;
6083            }
6084            out.push(node_id);
6085            cursor = self.nodes.get(&node_id).and_then(|record| record.parent);
6086        }
6087        Some(out)
6088    }
6089}
6090
6091impl PaneInteractionTimeline {
6092    /// Construct a timeline with an explicit baseline snapshot.
6093    #[must_use]
6094    pub fn with_baseline(tree: &PaneTree) -> Self {
6095        Self {
6096            baseline: Some(tree.to_snapshot()),
6097            entries: Vec::new(),
6098            cursor: 0,
6099            checkpoints: Vec::new(),
6100            checkpoint_interval: DEFAULT_PANE_TIMELINE_CHECKPOINT_INTERVAL,
6101            max_entries: DEFAULT_PANE_TIMELINE_MAX_ENTRIES,
6102        }
6103    }
6104
6105    /// Return a copy of this timeline configured with a retained-entry cap.
6106    #[must_use]
6107    pub fn with_max_entries(mut self, max_entries: usize) -> Self {
6108        self.max_entries = max_entries;
6109        self
6110    }
6111
6112    /// Install a retained-entry cap and immediately enforce it, pruning the
6113    /// oldest entries (advancing the replay baseline and re-basing checkpoints)
6114    /// if the timeline currently exceeds `max_entries`.
6115    ///
6116    /// Unlike [`with_max_entries`](Self::with_max_entries) this acts on an
6117    /// existing timeline in place, so a retention policy can re-bound it
6118    /// retroactively. The newest entries are always kept, so the head state —
6119    /// and its `after_hash` — is preserved. Returns the number of entries pruned
6120    /// by this call. `0` is unbounded.
6121    pub fn set_max_entries(&mut self, max_entries: usize) -> usize {
6122        let before = self.entries.len();
6123        self.max_entries = max_entries;
6124        self.enforce_entry_limit();
6125        before.saturating_sub(self.entries.len())
6126    }
6127
6128    /// Number of currently-applied entries.
6129    #[must_use]
6130    pub const fn applied_len(&self) -> usize {
6131        self.cursor
6132    }
6133
6134    /// Next operation id above every retained history entry.
6135    #[must_use]
6136    pub fn next_operation_id(&self) -> u64 {
6137        self.entries
6138            .iter()
6139            .map(|entry| entry.operation_id)
6140            .max()
6141            .unwrap_or(0)
6142            .saturating_add(1)
6143            .max(1)
6144    }
6145
6146    /// Replay/checkpoint diagnostics for the current cursor.
6147    #[must_use]
6148    pub fn replay_diagnostics(&self) -> PaneInteractionTimelineReplayDiagnostics {
6149        let replay_start_idx = self
6150            .checkpoints
6151            .iter()
6152            .rev()
6153            .find(|checkpoint| checkpoint.applied_len <= self.cursor)
6154            .map_or(0, |checkpoint| checkpoint.applied_len);
6155
6156        PaneInteractionTimelineReplayDiagnostics {
6157            entry_count: self.entries.len(),
6158            cursor: self.cursor,
6159            checkpoint_count: self.checkpoints.len(),
6160            checkpoint_interval: self.checkpoint_interval,
6161            checkpoint_hit: replay_start_idx != 0,
6162            replay_start_idx,
6163            replay_depth: self.cursor.saturating_sub(replay_start_idx),
6164        }
6165    }
6166
6167    /// Retained-state diagnostics for memory telemetry and pruning analysis.
6168    #[must_use]
6169    pub fn retention_diagnostics(&self) -> PaneInteractionTimelineRetentionDiagnostics {
6170        let mut snapshot_stats = PaneTimelineSnapshotRetentionStats::default();
6171        let baseline_present = self.baseline.is_some();
6172        if let Some(baseline) = &self.baseline {
6173            snapshot_stats.add_snapshot(baseline);
6174        }
6175        for checkpoint in &self.checkpoints {
6176            snapshot_stats.add_snapshot(&checkpoint.snapshot);
6177        }
6178
6179        let retained_operation_payload_bytes = self
6180            .entries
6181            .iter()
6182            .map(|entry| pane_operation_retained_payload_bytes(&entry.operation))
6183            .sum::<usize>();
6184        let estimated_entry_struct_bytes = self
6185            .entries
6186            .len()
6187            .saturating_mul(std::mem::size_of::<PaneInteractionTimelineEntry>());
6188        let estimated_checkpoint_struct_bytes = self
6189            .checkpoints
6190            .len()
6191            .saturating_mul(std::mem::size_of::<PaneInteractionTimelineCheckpoint>());
6192        let estimated_snapshot_struct_bytes = snapshot_stats
6193            .snapshot_count
6194            .saturating_mul(std::mem::size_of::<PaneTreeSnapshot>())
6195            .saturating_add(
6196                snapshot_stats
6197                    .node_count
6198                    .saturating_mul(std::mem::size_of::<PaneNodeRecord>()),
6199            );
6200        let estimated_total_retained_bytes = std::mem::size_of::<Self>()
6201            .saturating_add(estimated_entry_struct_bytes)
6202            .saturating_add(estimated_checkpoint_struct_bytes)
6203            .saturating_add(estimated_snapshot_struct_bytes)
6204            .saturating_add(snapshot_stats.leaf_payload_bytes)
6205            .saturating_add(snapshot_stats.extension_payload_bytes)
6206            .saturating_add(retained_operation_payload_bytes);
6207
6208        PaneInteractionTimelineRetentionDiagnostics {
6209            entry_count: self.entries.len(),
6210            cursor: self.cursor,
6211            redo_entry_count: self.entries.len().saturating_sub(self.cursor),
6212            checkpoint_count: self.checkpoints.len(),
6213            checkpoint_interval: self.checkpoint_interval,
6214            max_entries: self.max_entries,
6215            baseline_present,
6216            retained_snapshot_count: snapshot_stats.snapshot_count,
6217            baseline_node_count: self
6218                .baseline
6219                .as_ref()
6220                .map_or(0, |snapshot| snapshot.nodes.len()),
6221            checkpoint_node_count: self
6222                .checkpoints
6223                .iter()
6224                .map(|checkpoint| checkpoint.snapshot.nodes.len())
6225                .sum(),
6226            retained_snapshot_node_count: snapshot_stats.node_count,
6227            retained_leaf_payload_bytes: snapshot_stats.leaf_payload_bytes,
6228            retained_extension_entry_count: snapshot_stats.extension_entry_count,
6229            retained_extension_payload_bytes: snapshot_stats.extension_payload_bytes,
6230            retained_operation_payload_bytes,
6231            estimated_entry_struct_bytes,
6232            estimated_checkpoint_struct_bytes,
6233            estimated_snapshot_struct_bytes,
6234            estimated_total_retained_bytes,
6235        }
6236    }
6237
6238    /// Deterministic checkpoint-spacing decision from measured snapshot and replay costs.
6239    #[must_use]
6240    pub fn checkpoint_decision(
6241        snapshot_cost_ns: u128,
6242        replay_step_cost_ns: u128,
6243    ) -> PaneInteractionTimelineCheckpointDecision {
6244        let interval =
6245            analytically_tuned_checkpoint_interval(snapshot_cost_ns, replay_step_cost_ns);
6246        let replay_depth_ns = replay_step_cost_ns.saturating_mul(interval as u128) / 2;
6247        PaneInteractionTimelineCheckpointDecision {
6248            checkpoint_interval: interval,
6249            estimated_snapshot_cost_ns: snapshot_cost_ns,
6250            estimated_replay_step_cost_ns: replay_step_cost_ns,
6251            estimated_replay_depth_ns: replay_depth_ns,
6252        }
6253    }
6254
6255    /// Append one operation by applying it to the provided tree.
6256    ///
6257    /// If the cursor is behind the head (after undo), redo entries are dropped
6258    /// before appending the new branch.
6259    pub fn apply_and_record(
6260        &mut self,
6261        tree: &mut PaneTree,
6262        sequence: u64,
6263        operation_id: u64,
6264        operation: PaneOperation,
6265    ) -> Result<PaneOperationOutcome, PaneOperationError> {
6266        let baseline = self.baseline.is_none().then(|| tree.to_snapshot());
6267        // Tree application is transactional. Only a successful edit may
6268        // install a baseline or discard the currently retained redo branch.
6269        let outcome = tree.apply_operation(operation_id, operation.clone())?;
6270        self.record_applied(tree, baseline, sequence, operation, &outcome, None, true);
6271        Ok(outcome)
6272    }
6273
6274    /// Apply one operation and merge adjacent resize deltas for the same split.
6275    ///
6276    /// The first delta keeps its pre-gesture hash so undo still restores the
6277    /// state before the drag began, while replay uses the most recent ratio.
6278    /// Coalescing is limited to entries whose operation id is above the
6279    /// gesture-start boundary, so separate drags on the same split remain
6280    /// separate undo steps.
6281    pub fn apply_and_record_coalesced_resize_delta(
6282        &mut self,
6283        tree: &mut PaneTree,
6284        sequence: u64,
6285        operation_id: u64,
6286        operation: PaneOperation,
6287        coalesce_after_operation_id: u64,
6288    ) -> Result<PaneOperationOutcome, PaneOperationError> {
6289        let baseline = self.baseline.is_none().then(|| tree.to_snapshot());
6290        let outcome = tree.apply_operation(operation_id, operation.clone())?;
6291        self.record_applied(
6292            tree,
6293            baseline,
6294            sequence,
6295            operation,
6296            &outcome,
6297            Some(coalesce_after_operation_id),
6298            true,
6299        );
6300        Ok(outcome)
6301    }
6302
6303    /// Commit an already successful operation without executing it again.
6304    /// Returns whether the preceding resize entry was replaced.
6305    #[allow(clippy::too_many_arguments)]
6306    pub(crate) fn record_applied(
6307        &mut self,
6308        tree: &PaneTree,
6309        baseline: Option<PaneTreeSnapshot>,
6310        sequence: u64,
6311        operation: PaneOperation,
6312        outcome: &PaneOperationOutcome,
6313        coalesce_after: Option<u64>,
6314        checkpoints_enabled: bool,
6315    ) -> bool {
6316        if let Some(baseline) = baseline {
6317            self.baseline = Some(baseline);
6318        }
6319        if self.cursor < self.entries.len() {
6320            self.entries.truncate(self.cursor);
6321            self.checkpoints
6322                .retain(|checkpoint| checkpoint.applied_len <= self.cursor);
6323        }
6324        let coalesced_before_hash = match &operation {
6325            PaneOperation::SetSplitRatio { split, .. } if self.cursor == self.entries.len() => self
6326                .entries
6327                .last()
6328                .and_then(|entry| match &entry.operation {
6329                    PaneOperation::SetSplitRatio {
6330                        split: previous_split,
6331                        ..
6332                    } if previous_split == split
6333                        && coalesce_after.is_some_and(|boundary| entry.operation_id > boundary) =>
6334                    {
6335                        Some(entry.before_hash)
6336                    }
6337                    _ => None,
6338                }),
6339            _ => None,
6340        };
6341
6342        if let Some(before_hash) = coalesced_before_hash
6343            && let Some(entry) = self.entries.last_mut()
6344        {
6345            *entry = PaneInteractionTimelineEntry {
6346                sequence,
6347                operation_id: outcome.operation_id,
6348                operation,
6349                before_hash,
6350                after_hash: outcome.after_hash,
6351            };
6352            self.cursor = self.entries.len();
6353            self.checkpoints
6354                .retain(|checkpoint| checkpoint.applied_len < self.cursor);
6355            self.enforce_entry_limit();
6356            if checkpoints_enabled {
6357                self.maybe_record_checkpoint(tree);
6358            }
6359            return true;
6360        }
6361
6362        self.entries.push(PaneInteractionTimelineEntry {
6363            sequence,
6364            operation_id: outcome.operation_id,
6365            operation,
6366            before_hash: outcome.before_hash,
6367            after_hash: outcome.after_hash,
6368        });
6369        self.cursor = self.entries.len();
6370        self.enforce_entry_limit();
6371        if checkpoints_enabled {
6372            self.maybe_record_checkpoint(tree);
6373        }
6374        false
6375    }
6376
6377    /// Undo the last applied entry by deterministic rebuild from baseline.
6378    /// Replay failure leaves both the tree and timeline unchanged.
6379    pub fn undo(&mut self, tree: &mut PaneTree) -> Result<bool, PaneInteractionTimelineError> {
6380        if self.cursor == 0 {
6381            return Ok(false);
6382        }
6383        *tree = self.replay_at(self.cursor - 1)?;
6384        self.cursor -= 1;
6385        Ok(true)
6386    }
6387
6388    /// Redo one entry by deterministic rebuild from baseline.
6389    /// Replay failure leaves both the tree and timeline unchanged.
6390    pub fn redo(&mut self, tree: &mut PaneTree) -> Result<bool, PaneInteractionTimelineError> {
6391        if self.cursor >= self.entries.len() {
6392            return Ok(false);
6393        }
6394        *tree = self.replay_at(self.cursor + 1)?;
6395        self.cursor += 1;
6396        Ok(true)
6397    }
6398
6399    /// Rebuild a new tree from baseline and currently-applied entries.
6400    pub fn replay(&self) -> Result<PaneTree, PaneInteractionTimelineError> {
6401        self.replay_at(self.cursor)
6402    }
6403
6404    fn replay_at(&self, cursor: usize) -> Result<PaneTree, PaneInteractionTimelineError> {
6405        let (mut tree, start_idx) = self.restore_replay_start(cursor)?;
6406        for entry in self.entries.iter().take(cursor).skip(start_idx) {
6407            tree.apply_operation_in_place_for_replay(entry.operation_id, &entry.operation)
6408                .map_err(|source| PaneInteractionTimelineError::ApplyFailed { source })?;
6409        }
6410        Ok(tree)
6411    }
6412
6413    fn restore_replay_start(
6414        &self,
6415        cursor: usize,
6416    ) -> Result<(PaneTree, usize), PaneInteractionTimelineError> {
6417        if let Some(checkpoint) = self
6418            .checkpoints
6419            .iter()
6420            .rev()
6421            .find(|checkpoint| checkpoint.applied_len <= cursor)
6422        {
6423            let tree = PaneTree::from_snapshot(checkpoint.snapshot.clone())
6424                .map_err(|source| PaneInteractionTimelineError::BaselineInvalid { source })?;
6425            return Ok((tree, checkpoint.applied_len));
6426        }
6427
6428        let baseline = self
6429            .baseline
6430            .clone()
6431            .ok_or(PaneInteractionTimelineError::MissingBaseline)?;
6432        let tree = PaneTree::from_snapshot(baseline)
6433            .map_err(|source| PaneInteractionTimelineError::BaselineInvalid { source })?;
6434        Ok((tree, 0))
6435    }
6436
6437    fn maybe_record_checkpoint(&mut self, tree: &PaneTree) {
6438        if self.checkpoint_interval == 0 || self.cursor == 0 {
6439            return;
6440        }
6441        if !self.cursor.is_multiple_of(self.checkpoint_interval) {
6442            return;
6443        }
6444        if let Some(checkpoint) = self
6445            .checkpoints
6446            .iter_mut()
6447            .find(|checkpoint| checkpoint.applied_len == self.cursor)
6448        {
6449            checkpoint.snapshot = tree.to_snapshot();
6450            return;
6451        }
6452        self.checkpoints.push(PaneInteractionTimelineCheckpoint {
6453            applied_len: self.cursor,
6454            snapshot: tree.to_snapshot(),
6455        });
6456    }
6457
6458    fn enforce_entry_limit(&mut self) {
6459        if self.max_entries == 0 || self.entries.len() <= self.max_entries {
6460            return;
6461        }
6462
6463        // Never prune past the cursor: the current state is baseline +
6464        // entries[..cursor], so baking an entry beyond the cursor into the
6465        // baseline would silently replace the user's (undone-to) state with a
6466        // later one. Excess entries are tolerated until the cursor advances.
6467        let prune_count = self
6468            .entries
6469            .len()
6470            .saturating_sub(self.max_entries)
6471            .min(self.cursor);
6472        if prune_count == 0 {
6473            return;
6474        }
6475        let Some(baseline) = self.baseline.clone() else {
6476            return;
6477        };
6478        let Ok(mut baseline_tree) = PaneTree::from_snapshot(baseline) else {
6479            return;
6480        };
6481
6482        for entry in self.entries.iter().take(prune_count) {
6483            if baseline_tree
6484                .apply_operation_in_place_for_replay(entry.operation_id, &entry.operation)
6485                .is_err()
6486            {
6487                return;
6488            }
6489        }
6490
6491        self.baseline = Some(baseline_tree.to_snapshot());
6492        drop(self.entries.drain(..prune_count));
6493        self.cursor = self
6494            .cursor
6495            .saturating_sub(prune_count)
6496            .min(self.entries.len());
6497        self.checkpoints = self
6498            .checkpoints
6499            .iter()
6500            .filter(|checkpoint| checkpoint.applied_len > prune_count)
6501            .map(|checkpoint| PaneInteractionTimelineCheckpoint {
6502                applied_len: checkpoint.applied_len - prune_count,
6503                snapshot: checkpoint.snapshot.clone(),
6504            })
6505            .collect();
6506    }
6507}
6508
6509#[derive(Debug, Clone, Copy, Default)]
6510struct PaneTimelineSnapshotRetentionStats {
6511    snapshot_count: usize,
6512    node_count: usize,
6513    leaf_payload_bytes: usize,
6514    extension_entry_count: usize,
6515    extension_payload_bytes: usize,
6516}
6517
6518impl PaneTimelineSnapshotRetentionStats {
6519    fn add_snapshot(&mut self, snapshot: &PaneTreeSnapshot) {
6520        self.snapshot_count = self.snapshot_count.saturating_add(1);
6521        self.node_count = self.node_count.saturating_add(snapshot.nodes.len());
6522        self.extension_entry_count = self
6523            .extension_entry_count
6524            .saturating_add(snapshot.extensions.len());
6525        self.extension_payload_bytes = self
6526            .extension_payload_bytes
6527            .saturating_add(string_map_payload_bytes(&snapshot.extensions));
6528
6529        for node in &snapshot.nodes {
6530            self.extension_entry_count = self
6531                .extension_entry_count
6532                .saturating_add(node.extensions.len());
6533            self.extension_payload_bytes = self
6534                .extension_payload_bytes
6535                .saturating_add(string_map_payload_bytes(&node.extensions));
6536            if let PaneNodeKind::Leaf(leaf) = &node.kind {
6537                self.leaf_payload_bytes = self
6538                    .leaf_payload_bytes
6539                    .saturating_add(pane_leaf_surface_payload_bytes(leaf));
6540                self.extension_entry_count = self
6541                    .extension_entry_count
6542                    .saturating_add(leaf.extensions.len());
6543                self.extension_payload_bytes = self
6544                    .extension_payload_bytes
6545                    .saturating_add(string_map_payload_bytes(&leaf.extensions));
6546            }
6547        }
6548    }
6549}
6550
6551fn pane_operation_retained_payload_bytes(operation: &PaneOperation) -> usize {
6552    match operation {
6553        PaneOperation::SplitLeaf { new_leaf, .. } => pane_leaf_retained_payload_bytes(new_leaf),
6554        PaneOperation::CloseNode { .. }
6555        | PaneOperation::MoveSubtree { .. }
6556        | PaneOperation::SwapNodes { .. }
6557        | PaneOperation::SetSplitRatio { .. }
6558        | PaneOperation::NormalizeRatios => 0,
6559    }
6560}
6561
6562fn pane_leaf_retained_payload_bytes(leaf: &PaneLeaf) -> usize {
6563    pane_leaf_surface_payload_bytes(leaf).saturating_add(string_map_payload_bytes(&leaf.extensions))
6564}
6565
6566fn pane_leaf_surface_payload_bytes(leaf: &PaneLeaf) -> usize {
6567    leaf.surface_key.len()
6568}
6569
6570fn string_map_payload_bytes(map: &BTreeMap<String, String>) -> usize {
6571    map.iter()
6572        .map(|(key, value)| key.len().saturating_add(value.len()))
6573        .sum()
6574}
6575
6576fn analytically_tuned_checkpoint_interval(
6577    snapshot_cost_ns: u128,
6578    replay_step_cost_ns: u128,
6579) -> usize {
6580    if snapshot_cost_ns == 0 || replay_step_cost_ns == 0 {
6581        return DEFAULT_PANE_TIMELINE_CHECKPOINT_INTERVAL;
6582    }
6583
6584    let ratio = snapshot_cost_ns.saturating_mul(2) / replay_step_cost_ns;
6585    let root = integer_sqrt(ratio).max(1);
6586    usize::try_from(root).unwrap_or(DEFAULT_PANE_TIMELINE_CHECKPOINT_INTERVAL)
6587}
6588
6589fn integer_sqrt(value: u128) -> u128 {
6590    if value < 2 {
6591        return value;
6592    }
6593
6594    let mut left = 1u128;
6595    let mut right = value;
6596    let mut answer = 1u128;
6597    while left <= right {
6598        let mid = left + (right - left) / 2;
6599        if mid <= value / mid {
6600            answer = mid;
6601            left = mid + 1;
6602        } else {
6603            right = mid - 1;
6604        }
6605    }
6606    answer
6607}
6608
6609/// Deterministic allocator for pane IDs.
6610#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
6611pub struct PaneIdAllocator {
6612    next: PaneId,
6613}
6614
6615impl PaneIdAllocator {
6616    /// Start allocating from a known ID.
6617    #[must_use]
6618    pub const fn with_next(next: PaneId) -> Self {
6619        Self { next }
6620    }
6621
6622    /// Create allocator from the next ID in a validated tree.
6623    #[must_use]
6624    pub fn from_tree(tree: &PaneTree) -> Self {
6625        Self { next: tree.next_id }
6626    }
6627
6628    /// Peek at the next ID without consuming.
6629    #[must_use]
6630    pub const fn peek(&self) -> PaneId {
6631        self.next
6632    }
6633
6634    /// Allocate the next ID and advance.
6635    pub fn allocate(&mut self) -> Result<PaneId, PaneModelError> {
6636        let current = self.next;
6637        self.next = self.next.checked_next()?;
6638        Ok(current)
6639    }
6640}
6641
6642impl Default for PaneIdAllocator {
6643    fn default() -> Self {
6644        Self { next: PaneId::MIN }
6645    }
6646}
6647
6648/// Validation errors for pane schema construction.
6649#[derive(Debug, Clone, PartialEq, Eq)]
6650pub enum PaneModelError {
6651    ZeroPaneId,
6652    UnsupportedSchemaVersion {
6653        version: u16,
6654    },
6655    DuplicateNodeId {
6656        node_id: PaneId,
6657    },
6658    MissingRoot {
6659        root: PaneId,
6660    },
6661    RootHasParent {
6662        root: PaneId,
6663        parent: PaneId,
6664    },
6665    MissingParent {
6666        node_id: PaneId,
6667        parent: PaneId,
6668    },
6669    MissingChild {
6670        parent: PaneId,
6671        child: PaneId,
6672    },
6673    MultipleParents {
6674        child: PaneId,
6675        first_parent: PaneId,
6676        second_parent: PaneId,
6677    },
6678    ParentMismatch {
6679        node_id: PaneId,
6680        expected: Option<PaneId>,
6681        actual: Option<PaneId>,
6682    },
6683    SelfReferentialSplit {
6684        node_id: PaneId,
6685    },
6686    DuplicateSplitChildren {
6687        node_id: PaneId,
6688        child: PaneId,
6689    },
6690    InvalidSplitRatio {
6691        numerator: u32,
6692        denominator: u32,
6693    },
6694    InvalidConstraint {
6695        node_id: PaneId,
6696        axis: &'static str,
6697        min: u16,
6698        max: u16,
6699    },
6700    NodeConstraintUnsatisfied {
6701        node_id: PaneId,
6702        axis: &'static str,
6703        actual: u16,
6704        min: u16,
6705        max: Option<u16>,
6706    },
6707    OverconstrainedSplit {
6708        node_id: PaneId,
6709        axis: SplitAxis,
6710        available: u16,
6711        first_min: u16,
6712        first_max: u16,
6713        second_min: u16,
6714        second_max: u16,
6715    },
6716    /// Descendant bounds and the containing node have no common feasible size.
6717    InfeasibleSubtree {
6718        node_id: PaneId,
6719        axis: SplitAxis,
6720        min: u32,
6721        max: u16,
6722    },
6723    CycleDetected {
6724        node_id: PaneId,
6725    },
6726    UnreachableNode {
6727        node_id: PaneId,
6728    },
6729    NextIdNotGreaterThanExisting {
6730        next_id: PaneId,
6731        max_existing: PaneId,
6732    },
6733    PaneIdOverflow {
6734        current: PaneId,
6735    },
6736}
6737
6738impl fmt::Display for PaneModelError {
6739    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6740        match self {
6741            Self::ZeroPaneId => write!(f, "pane id 0 is invalid"),
6742            Self::UnsupportedSchemaVersion { version } => {
6743                write!(
6744                    f,
6745                    "unsupported pane schema version {version} (expected {PANE_TREE_SCHEMA_VERSION})"
6746                )
6747            }
6748            Self::DuplicateNodeId { node_id } => write!(f, "duplicate pane node id {}", node_id.0),
6749            Self::MissingRoot { root } => write!(f, "root pane node {} not found", root.0),
6750            Self::RootHasParent { root, parent } => write!(
6751                f,
6752                "root pane node {} must not have parent {}",
6753                root.0, parent.0
6754            ),
6755            Self::MissingParent { node_id, parent } => write!(
6756                f,
6757                "node {} references missing parent {}",
6758                node_id.0, parent.0
6759            ),
6760            Self::MissingChild { parent, child } => write!(
6761                f,
6762                "split node {} references missing child {}",
6763                parent.0, child.0
6764            ),
6765            Self::MultipleParents {
6766                child,
6767                first_parent,
6768                second_parent,
6769            } => write!(
6770                f,
6771                "node {} has multiple parents: {} and {}",
6772                child.0, first_parent.0, second_parent.0
6773            ),
6774            Self::ParentMismatch {
6775                node_id,
6776                expected,
6777                actual,
6778            } => write!(
6779                f,
6780                "node {} parent mismatch: expected {:?}, got {:?}",
6781                node_id.0,
6782                expected.map(PaneId::get),
6783                actual.map(PaneId::get)
6784            ),
6785            Self::SelfReferentialSplit { node_id } => {
6786                write!(f, "split node {} cannot reference itself", node_id.0)
6787            }
6788            Self::DuplicateSplitChildren { node_id, child } => write!(
6789                f,
6790                "split node {} references child {} twice",
6791                node_id.0, child.0
6792            ),
6793            Self::InvalidSplitRatio {
6794                numerator,
6795                denominator,
6796            } => write!(
6797                f,
6798                "invalid split ratio {numerator}/{denominator}: both values must be > 0"
6799            ),
6800            Self::InvalidConstraint {
6801                node_id,
6802                axis,
6803                min,
6804                max,
6805            } => write!(
6806                f,
6807                "invalid {axis} constraints for node {}: max {max} < min {min}",
6808                node_id.0
6809            ),
6810            Self::NodeConstraintUnsatisfied {
6811                node_id,
6812                axis,
6813                actual,
6814                min,
6815                max,
6816            } => write!(
6817                f,
6818                "node {} {axis}={} violates constraints [min={}, max={:?}]",
6819                node_id.0, actual, min, max
6820            ),
6821            Self::OverconstrainedSplit {
6822                node_id,
6823                axis,
6824                available,
6825                first_min,
6826                first_max,
6827                second_min,
6828                second_max,
6829            } => write!(
6830                f,
6831                "overconstrained {:?} split at node {} (available={}): first[min={}, max={}], second[min={}, max={}]",
6832                axis, node_id.0, available, first_min, first_max, second_min, second_max
6833            ),
6834            Self::InfeasibleSubtree {
6835                node_id,
6836                axis,
6837                min,
6838                max,
6839            } => write!(
6840                f,
6841                "infeasible {axis:?} subtree at node {}: required minimum {min} exceeds maximum {max}",
6842                node_id.0
6843            ),
6844            Self::CycleDetected { node_id } => {
6845                write!(f, "cycle detected at node {}", node_id.0)
6846            }
6847            Self::UnreachableNode { node_id } => {
6848                write!(f, "node {} is unreachable from root", node_id.0)
6849            }
6850            Self::NextIdNotGreaterThanExisting {
6851                next_id,
6852                max_existing,
6853            } => write!(
6854                f,
6855                "next_id {} must be greater than max existing id {}",
6856                next_id.0, max_existing.0
6857            ),
6858            Self::PaneIdOverflow { current } => {
6859                write!(f, "pane id overflow after {}", current.0)
6860            }
6861        }
6862    }
6863}
6864
6865impl std::error::Error for PaneModelError {}
6866
6867fn snapshot_state_hash(snapshot: &PaneTreeSnapshot) -> u64 {
6868    const OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
6869    const PRIME: u64 = 0x0000_0001_0000_01b3;
6870
6871    fn mix(hash: &mut u64, byte: u8) {
6872        *hash ^= u64::from(byte);
6873        *hash = hash.wrapping_mul(PRIME);
6874    }
6875
6876    fn mix_bytes(hash: &mut u64, bytes: &[u8]) {
6877        for byte in bytes {
6878            mix(hash, *byte);
6879        }
6880    }
6881
6882    fn mix_u16(hash: &mut u64, value: u16) {
6883        mix_bytes(hash, &value.to_le_bytes());
6884    }
6885
6886    fn mix_u32(hash: &mut u64, value: u32) {
6887        mix_bytes(hash, &value.to_le_bytes());
6888    }
6889
6890    fn mix_u64(hash: &mut u64, value: u64) {
6891        mix_bytes(hash, &value.to_le_bytes());
6892    }
6893
6894    fn mix_bool(hash: &mut u64, value: bool) {
6895        mix(hash, u8::from(value));
6896    }
6897
6898    fn mix_opt_u16(hash: &mut u64, value: Option<u16>) {
6899        match value {
6900            Some(value) => {
6901                mix(hash, 1);
6902                mix_u16(hash, value);
6903            }
6904            None => mix(hash, 0),
6905        }
6906    }
6907
6908    fn mix_opt_pane_id(hash: &mut u64, value: Option<PaneId>) {
6909        match value {
6910            Some(value) => {
6911                mix(hash, 1);
6912                mix_u64(hash, value.get());
6913            }
6914            None => mix(hash, 0),
6915        }
6916    }
6917
6918    fn mix_str(hash: &mut u64, value: &str) {
6919        mix_u64(hash, value.len() as u64);
6920        mix_bytes(hash, value.as_bytes());
6921    }
6922
6923    fn mix_extensions(hash: &mut u64, extensions: &BTreeMap<String, String>) {
6924        mix_u64(hash, extensions.len() as u64);
6925        for (key, value) in extensions {
6926            mix_str(hash, key);
6927            mix_str(hash, value);
6928        }
6929    }
6930
6931    let mut canonical = snapshot.clone();
6932    canonical.canonicalize();
6933
6934    let mut hash = OFFSET_BASIS;
6935    mix_u16(&mut hash, canonical.schema_version);
6936    mix_u64(&mut hash, canonical.root.get());
6937    mix_u64(&mut hash, canonical.next_id.get());
6938    mix_extensions(&mut hash, &canonical.extensions);
6939    mix_u64(&mut hash, canonical.nodes.len() as u64);
6940
6941    for node in &canonical.nodes {
6942        mix_u64(&mut hash, node.id.get());
6943        mix_opt_pane_id(&mut hash, node.parent);
6944        mix_u16(&mut hash, node.constraints.min_width);
6945        mix_u16(&mut hash, node.constraints.min_height);
6946        mix_opt_u16(&mut hash, node.constraints.max_width);
6947        mix_opt_u16(&mut hash, node.constraints.max_height);
6948        mix_bool(&mut hash, node.constraints.collapsible);
6949        mix_extensions(&mut hash, &node.extensions);
6950
6951        match &node.kind {
6952            PaneNodeKind::Leaf(leaf) => {
6953                mix(&mut hash, 1);
6954                mix_str(&mut hash, &leaf.surface_key);
6955                mix_extensions(&mut hash, &leaf.extensions);
6956            }
6957            PaneNodeKind::Split(split) => {
6958                mix(&mut hash, 2);
6959                let axis_byte = match split.axis {
6960                    SplitAxis::Horizontal => 1,
6961                    SplitAxis::Vertical => 2,
6962                };
6963                mix(&mut hash, axis_byte);
6964                mix_u32(&mut hash, split.ratio.numerator());
6965                mix_u32(&mut hash, split.ratio.denominator());
6966                mix_u64(&mut hash, split.first.get());
6967                mix_u64(&mut hash, split.second.get());
6968            }
6969        }
6970    }
6971
6972    hash
6973}
6974
6975fn push_invariant_issue(
6976    issues: &mut Vec<PaneInvariantIssue>,
6977    code: PaneInvariantCode,
6978    repairable: bool,
6979    node_id: Option<PaneId>,
6980    related_node: Option<PaneId>,
6981    message: impl Into<String>,
6982) {
6983    issues.push(PaneInvariantIssue {
6984        code,
6985        severity: PaneInvariantSeverity::Error,
6986        repairable,
6987        node_id,
6988        related_node,
6989        message: message.into(),
6990    });
6991}
6992
6993fn dfs_collect_cycles_and_reachable(
6994    node_id: PaneId,
6995    nodes: &BTreeMap<PaneId, PaneNodeRecord>,
6996    visiting: &mut BTreeSet<PaneId>,
6997    visited: &mut BTreeSet<PaneId>,
6998    cycle_nodes: &mut BTreeSet<PaneId>,
6999) {
7000    if visiting.contains(&node_id) {
7001        let _ = cycle_nodes.insert(node_id);
7002        return;
7003    }
7004    if !visited.insert(node_id) {
7005        return;
7006    }
7007
7008    let _ = visiting.insert(node_id);
7009    if let Some(node) = nodes.get(&node_id)
7010        && let PaneNodeKind::Split(split) = &node.kind
7011    {
7012        for child in [split.first, split.second] {
7013            if nodes.contains_key(&child) {
7014                dfs_collect_cycles_and_reachable(child, nodes, visiting, visited, cycle_nodes);
7015            }
7016        }
7017    }
7018    let _ = visiting.remove(&node_id);
7019}
7020
7021fn build_invariant_report(snapshot: &PaneTreeSnapshot) -> PaneInvariantReport {
7022    let mut issues = Vec::new();
7023
7024    if snapshot.schema_version != PANE_TREE_SCHEMA_VERSION {
7025        push_invariant_issue(
7026            &mut issues,
7027            PaneInvariantCode::UnsupportedSchemaVersion,
7028            false,
7029            None,
7030            None,
7031            format!(
7032                "unsupported schema version {} (expected {})",
7033                snapshot.schema_version, PANE_TREE_SCHEMA_VERSION
7034            ),
7035        );
7036    }
7037
7038    let mut nodes = BTreeMap::new();
7039    for node in &snapshot.nodes {
7040        if nodes.insert(node.id, node.clone()).is_some() {
7041            push_invariant_issue(
7042                &mut issues,
7043                PaneInvariantCode::DuplicateNodeId,
7044                false,
7045                Some(node.id),
7046                None,
7047                format!("duplicate node id {}", node.id.get()),
7048            );
7049        }
7050    }
7051
7052    if let Some(max_existing) = nodes.keys().next_back().copied()
7053        && snapshot.next_id <= max_existing
7054    {
7055        push_invariant_issue(
7056            &mut issues,
7057            PaneInvariantCode::NextIdNotGreaterThanExisting,
7058            true,
7059            Some(snapshot.next_id),
7060            Some(max_existing),
7061            format!(
7062                "next_id {} must be greater than max node id {}",
7063                snapshot.next_id.get(),
7064                max_existing.get()
7065            ),
7066        );
7067    }
7068
7069    if !nodes.contains_key(&snapshot.root) {
7070        push_invariant_issue(
7071            &mut issues,
7072            PaneInvariantCode::MissingRoot,
7073            false,
7074            Some(snapshot.root),
7075            None,
7076            format!("root node {} is missing", snapshot.root.get()),
7077        );
7078    }
7079
7080    let mut expected_parents = BTreeMap::new();
7081    for node in nodes.values() {
7082        if let Err(err) = node.constraints.validate(node.id) {
7083            push_invariant_issue(
7084                &mut issues,
7085                PaneInvariantCode::InvalidConstraint,
7086                false,
7087                Some(node.id),
7088                None,
7089                err.to_string(),
7090            );
7091        }
7092
7093        if let Some(parent) = node.parent
7094            && !nodes.contains_key(&parent)
7095        {
7096            push_invariant_issue(
7097                &mut issues,
7098                PaneInvariantCode::MissingParent,
7099                true,
7100                Some(node.id),
7101                Some(parent),
7102                format!(
7103                    "node {} references missing parent {}",
7104                    node.id.get(),
7105                    parent.get()
7106                ),
7107            );
7108        }
7109
7110        if let PaneNodeKind::Split(split) = &node.kind {
7111            if split.ratio.numerator() == 0 || split.ratio.denominator() == 0 {
7112                push_invariant_issue(
7113                    &mut issues,
7114                    PaneInvariantCode::InvalidSplitRatio,
7115                    false,
7116                    Some(node.id),
7117                    None,
7118                    format!(
7119                        "split node {} has invalid ratio {}/{}",
7120                        node.id.get(),
7121                        split.ratio.numerator(),
7122                        split.ratio.denominator()
7123                    ),
7124                );
7125            }
7126
7127            if split.first == node.id || split.second == node.id {
7128                push_invariant_issue(
7129                    &mut issues,
7130                    PaneInvariantCode::SelfReferentialSplit,
7131                    false,
7132                    Some(node.id),
7133                    None,
7134                    format!("split node {} references itself", node.id.get()),
7135                );
7136            }
7137
7138            if split.first == split.second {
7139                push_invariant_issue(
7140                    &mut issues,
7141                    PaneInvariantCode::DuplicateSplitChildren,
7142                    false,
7143                    Some(node.id),
7144                    Some(split.first),
7145                    format!(
7146                        "split node {} references child {} twice",
7147                        node.id.get(),
7148                        split.first.get()
7149                    ),
7150                );
7151            }
7152
7153            for child in [split.first, split.second] {
7154                if !nodes.contains_key(&child) {
7155                    push_invariant_issue(
7156                        &mut issues,
7157                        PaneInvariantCode::MissingChild,
7158                        false,
7159                        Some(node.id),
7160                        Some(child),
7161                        format!(
7162                            "split node {} references missing child {}",
7163                            node.id.get(),
7164                            child.get()
7165                        ),
7166                    );
7167                    continue;
7168                }
7169
7170                if let Some(first_parent) = expected_parents.insert(child, node.id)
7171                    && first_parent != node.id
7172                {
7173                    push_invariant_issue(
7174                        &mut issues,
7175                        PaneInvariantCode::MultipleParents,
7176                        false,
7177                        Some(child),
7178                        Some(node.id),
7179                        format!(
7180                            "node {} has multiple split parents {} and {}",
7181                            child.get(),
7182                            first_parent.get(),
7183                            node.id.get()
7184                        ),
7185                    );
7186                }
7187            }
7188        }
7189    }
7190
7191    if let Some(root_node) = nodes.get(&snapshot.root)
7192        && let Some(parent) = root_node.parent
7193    {
7194        push_invariant_issue(
7195            &mut issues,
7196            PaneInvariantCode::RootHasParent,
7197            true,
7198            Some(snapshot.root),
7199            Some(parent),
7200            format!(
7201                "root node {} must not have parent {}",
7202                snapshot.root.get(),
7203                parent.get()
7204            ),
7205        );
7206    }
7207
7208    for node in nodes.values() {
7209        let expected_parent = if node.id == snapshot.root {
7210            None
7211        } else {
7212            expected_parents.get(&node.id).copied()
7213        };
7214
7215        if node.parent != expected_parent {
7216            push_invariant_issue(
7217                &mut issues,
7218                PaneInvariantCode::ParentMismatch,
7219                true,
7220                Some(node.id),
7221                expected_parent,
7222                format!(
7223                    "node {} parent mismatch: expected {:?}, got {:?}",
7224                    node.id.get(),
7225                    expected_parent.map(PaneId::get),
7226                    node.parent.map(PaneId::get)
7227                ),
7228            );
7229        }
7230    }
7231
7232    if nodes.contains_key(&snapshot.root) {
7233        let mut visiting = BTreeSet::new();
7234        let mut visited = BTreeSet::new();
7235        let mut cycle_nodes = BTreeSet::new();
7236        dfs_collect_cycles_and_reachable(
7237            snapshot.root,
7238            &nodes,
7239            &mut visiting,
7240            &mut visited,
7241            &mut cycle_nodes,
7242        );
7243
7244        for node_id in cycle_nodes {
7245            push_invariant_issue(
7246                &mut issues,
7247                PaneInvariantCode::CycleDetected,
7248                false,
7249                Some(node_id),
7250                None,
7251                format!("cycle detected at node {}", node_id.get()),
7252            );
7253        }
7254
7255        for node_id in nodes.keys() {
7256            if !visited.contains(node_id) {
7257                push_invariant_issue(
7258                    &mut issues,
7259                    PaneInvariantCode::UnreachableNode,
7260                    true,
7261                    Some(*node_id),
7262                    None,
7263                    format!("node {} is unreachable from root", node_id.get()),
7264                );
7265            }
7266        }
7267    }
7268
7269    issues.sort_by(|left, right| {
7270        (
7271            left.code,
7272            left.node_id.is_none(),
7273            left.node_id,
7274            left.related_node.is_none(),
7275            left.related_node,
7276            &left.message,
7277        )
7278            .cmp(&(
7279                right.code,
7280                right.node_id.is_none(),
7281                right.node_id,
7282                right.related_node.is_none(),
7283                right.related_node,
7284                &right.message,
7285            ))
7286    });
7287
7288    PaneInvariantReport {
7289        snapshot_hash: snapshot_state_hash(snapshot),
7290        issues,
7291    }
7292}
7293
7294fn repair_snapshot_safe(
7295    mut snapshot: PaneTreeSnapshot,
7296) -> Result<PaneRepairOutcome, PaneRepairError> {
7297    snapshot.canonicalize();
7298
7299    let before_hash = snapshot_state_hash(&snapshot);
7300    let report_before = build_invariant_report(&snapshot);
7301    let mut unsafe_codes = report_before
7302        .issues
7303        .iter()
7304        .filter(|issue| issue.severity == PaneInvariantSeverity::Error && !issue.repairable)
7305        .map(|issue| issue.code)
7306        .collect::<Vec<_>>();
7307    unsafe_codes.sort();
7308    unsafe_codes.dedup();
7309
7310    if !unsafe_codes.is_empty() {
7311        return Err(PaneRepairError {
7312            before_hash,
7313            report: report_before,
7314            reason: PaneRepairFailure::UnsafeIssuesPresent {
7315                codes: unsafe_codes,
7316            },
7317        });
7318    }
7319
7320    let mut nodes = BTreeMap::new();
7321    for node in snapshot.nodes {
7322        let _ = nodes.entry(node.id).or_insert(node);
7323    }
7324
7325    let mut actions = Vec::new();
7326    let mut expected_parents = BTreeMap::new();
7327    for node in nodes.values() {
7328        if let PaneNodeKind::Split(split) = &node.kind {
7329            for child in [split.first, split.second] {
7330                let _ = expected_parents.entry(child).or_insert(node.id);
7331            }
7332        }
7333    }
7334
7335    for node in nodes.values_mut() {
7336        let expected_parent = if node.id == snapshot.root {
7337            None
7338        } else {
7339            expected_parents.get(&node.id).copied()
7340        };
7341        if node.parent != expected_parent {
7342            actions.push(PaneRepairAction::ReparentNode {
7343                node_id: node.id,
7344                before_parent: node.parent,
7345                after_parent: expected_parent,
7346            });
7347            node.parent = expected_parent;
7348        }
7349
7350        if let PaneNodeKind::Split(split) = &mut node.kind {
7351            let normalized =
7352                PaneSplitRatio::new(split.ratio.numerator(), split.ratio.denominator()).map_err(
7353                    |error| PaneRepairError {
7354                        before_hash,
7355                        report: report_before.clone(),
7356                        reason: PaneRepairFailure::ValidationFailed { error },
7357                    },
7358                )?;
7359            if split.ratio != normalized {
7360                actions.push(PaneRepairAction::NormalizeRatio {
7361                    node_id: node.id,
7362                    before_numerator: split.ratio.numerator(),
7363                    before_denominator: split.ratio.denominator(),
7364                    after_numerator: normalized.numerator(),
7365                    after_denominator: normalized.denominator(),
7366                });
7367                split.ratio = normalized;
7368            }
7369        }
7370    }
7371
7372    let mut visiting = BTreeSet::new();
7373    let mut visited = BTreeSet::new();
7374    let mut cycle_nodes = BTreeSet::new();
7375    if nodes.contains_key(&snapshot.root) {
7376        dfs_collect_cycles_and_reachable(
7377            snapshot.root,
7378            &nodes,
7379            &mut visiting,
7380            &mut visited,
7381            &mut cycle_nodes,
7382        );
7383    }
7384    if !cycle_nodes.is_empty() {
7385        let mut codes = vec![PaneInvariantCode::CycleDetected];
7386        codes.sort();
7387        codes.dedup();
7388        return Err(PaneRepairError {
7389            before_hash,
7390            report: report_before,
7391            reason: PaneRepairFailure::UnsafeIssuesPresent { codes },
7392        });
7393    }
7394
7395    let all_node_ids = nodes.keys().copied().collect::<Vec<_>>();
7396    for node_id in all_node_ids {
7397        if !visited.contains(&node_id) {
7398            let _ = nodes.remove(&node_id);
7399            actions.push(PaneRepairAction::RemoveOrphanNode { node_id });
7400        }
7401    }
7402
7403    if let Some(max_existing) = nodes.keys().next_back().copied()
7404        && snapshot.next_id <= max_existing
7405    {
7406        let after = max_existing
7407            .checked_next()
7408            .map_err(|error| PaneRepairError {
7409                before_hash,
7410                report: report_before.clone(),
7411                reason: PaneRepairFailure::ValidationFailed { error },
7412            })?;
7413        actions.push(PaneRepairAction::BumpNextId {
7414            before: snapshot.next_id,
7415            after,
7416        });
7417        snapshot.next_id = after;
7418    }
7419
7420    snapshot.nodes = nodes.into_values().collect();
7421    snapshot.canonicalize();
7422
7423    let tree = PaneTree::from_snapshot(snapshot).map_err(|error| PaneRepairError {
7424        before_hash,
7425        report: report_before.clone(),
7426        reason: PaneRepairFailure::ValidationFailed { error },
7427    })?;
7428    let report_after = tree.invariant_report();
7429    let after_hash = tree.state_hash();
7430
7431    Ok(PaneRepairOutcome {
7432        before_hash,
7433        after_hash,
7434        report_before,
7435        report_after,
7436        actions,
7437        tree,
7438    })
7439}
7440
7441fn validate_tree(
7442    root: PaneId,
7443    next_id: PaneId,
7444    nodes: &BTreeMap<PaneId, PaneNodeRecord>,
7445) -> Result<(), PaneModelError> {
7446    if !nodes.contains_key(&root) {
7447        return Err(PaneModelError::MissingRoot { root });
7448    }
7449
7450    let max_existing = nodes.keys().next_back().copied().unwrap_or(root);
7451    if next_id <= max_existing {
7452        return Err(PaneModelError::NextIdNotGreaterThanExisting {
7453            next_id,
7454            max_existing,
7455        });
7456    }
7457
7458    let mut expected_parents = BTreeMap::new();
7459
7460    for node in nodes.values() {
7461        node.constraints.validate(node.id)?;
7462
7463        if let Some(parent) = node.parent
7464            && !nodes.contains_key(&parent)
7465        {
7466            return Err(PaneModelError::MissingParent {
7467                node_id: node.id,
7468                parent,
7469            });
7470        }
7471
7472        if let PaneNodeKind::Split(split) = &node.kind {
7473            if split.ratio.numerator() == 0 || split.ratio.denominator() == 0 {
7474                return Err(PaneModelError::InvalidSplitRatio {
7475                    numerator: split.ratio.numerator(),
7476                    denominator: split.ratio.denominator(),
7477                });
7478            }
7479
7480            if split.first == node.id || split.second == node.id {
7481                return Err(PaneModelError::SelfReferentialSplit { node_id: node.id });
7482            }
7483            if split.first == split.second {
7484                return Err(PaneModelError::DuplicateSplitChildren {
7485                    node_id: node.id,
7486                    child: split.first,
7487                });
7488            }
7489
7490            for child in [split.first, split.second] {
7491                if !nodes.contains_key(&child) {
7492                    return Err(PaneModelError::MissingChild {
7493                        parent: node.id,
7494                        child,
7495                    });
7496                }
7497                if let Some(first_parent) = expected_parents.insert(child, node.id)
7498                    && first_parent != node.id
7499                {
7500                    return Err(PaneModelError::MultipleParents {
7501                        child,
7502                        first_parent,
7503                        second_parent: node.id,
7504                    });
7505                }
7506            }
7507        }
7508    }
7509
7510    if let Some(parent) = nodes.get(&root).and_then(|node| node.parent) {
7511        return Err(PaneModelError::RootHasParent { root, parent });
7512    }
7513
7514    for node in nodes.values() {
7515        let expected = if node.id == root {
7516            None
7517        } else {
7518            expected_parents.get(&node.id).copied()
7519        };
7520        if node.parent != expected {
7521            return Err(PaneModelError::ParentMismatch {
7522                node_id: node.id,
7523                expected,
7524                actual: node.parent,
7525            });
7526        }
7527    }
7528
7529    let mut visiting = BTreeSet::new();
7530    let mut visited = BTreeSet::new();
7531    dfs_validate(root, nodes, &mut visiting, &mut visited)?;
7532
7533    if visited.len() != nodes.len()
7534        && let Some(node_id) = nodes.keys().find(|node_id| !visited.contains(node_id))
7535    {
7536        return Err(PaneModelError::UnreachableNode { node_id: *node_id });
7537    }
7538
7539    Ok(())
7540}
7541
7542#[derive(Debug, Clone, Copy)]
7543struct AxisBounds {
7544    min: u16,
7545    max: Option<u16>,
7546}
7547
7548fn axis_bounds(constraints: PaneConstraints, axis: SplitAxis) -> AxisBounds {
7549    match axis {
7550        SplitAxis::Horizontal => AxisBounds {
7551            min: constraints.min_width,
7552            max: constraints.max_width,
7553        },
7554        SplitAxis::Vertical => AxisBounds {
7555            min: constraints.min_height,
7556            max: constraints.max_height,
7557        },
7558    }
7559}
7560
7561fn subtree_axis_bounds(
7562    node_id: PaneId,
7563    axis: SplitAxis,
7564    split_axis: SplitAxis,
7565    own: PaneConstraints,
7566    first: PaneConstraints,
7567    second: PaneConstraints,
7568) -> Result<AxisBounds, PaneModelError> {
7569    let own = axis_bounds(own, axis);
7570    let first = axis_bounds(first, axis);
7571    let second = axis_bounds(second, axis);
7572    let first_max = u32::from(first.max.unwrap_or(u16::MAX));
7573    let second_max = u32::from(second.max.unwrap_or(u16::MAX));
7574    // Children partition the split axis, and share the full perpendicular axis.
7575    // Widen before adding: a 65536-cell minimum must never become 0 or 65535.
7576    let (min, max) = if axis == split_axis {
7577        (
7578            u32::from(first.min) + u32::from(second.min),
7579            first_max + second_max,
7580        )
7581    } else {
7582        (
7583            u32::from(first.min.max(second.min)),
7584            first_max.min(second_max),
7585        )
7586    };
7587    let min = min.max(u32::from(own.min));
7588    let max = max.min(u32::from(own.max.unwrap_or(u16::MAX))) as u16;
7589    if min > u32::from(max) {
7590        return Err(PaneModelError::InfeasibleSubtree {
7591            node_id,
7592            axis,
7593            min,
7594            max,
7595        });
7596    }
7597    Ok(AxisBounds {
7598        min: min as u16,
7599        max: Some(max),
7600    })
7601}
7602
7603fn validate_area_against_constraints(
7604    node_id: PaneId,
7605    area: Rect,
7606    constraints: PaneConstraints,
7607) -> Result<(), PaneModelError> {
7608    if area.width < constraints.min_width {
7609        return Err(PaneModelError::NodeConstraintUnsatisfied {
7610            node_id,
7611            axis: "width",
7612            actual: area.width,
7613            min: constraints.min_width,
7614            max: constraints.max_width,
7615        });
7616    }
7617    if area.height < constraints.min_height {
7618        return Err(PaneModelError::NodeConstraintUnsatisfied {
7619            node_id,
7620            axis: "height",
7621            actual: area.height,
7622            min: constraints.min_height,
7623            max: constraints.max_height,
7624        });
7625    }
7626    if let Some(max_width) = constraints.max_width
7627        && area.width > max_width
7628    {
7629        return Err(PaneModelError::NodeConstraintUnsatisfied {
7630            node_id,
7631            axis: "width",
7632            actual: area.width,
7633            min: constraints.min_width,
7634            max: constraints.max_width,
7635        });
7636    }
7637    if let Some(max_height) = constraints.max_height
7638        && area.height > max_height
7639    {
7640        return Err(PaneModelError::NodeConstraintUnsatisfied {
7641            node_id,
7642            axis: "height",
7643            actual: area.height,
7644            min: constraints.min_height,
7645            max: constraints.max_height,
7646        });
7647    }
7648    Ok(())
7649}
7650
7651fn solve_split_sizes(
7652    node_id: PaneId,
7653    axis: SplitAxis,
7654    available: u16,
7655    ratio: PaneSplitRatio,
7656    first: AxisBounds,
7657    second: AxisBounds,
7658) -> Result<(u16, u16), PaneModelError> {
7659    let first_max = first.max.unwrap_or(available).min(available);
7660    let second_max = second.max.unwrap_or(available).min(available);
7661
7662    let feasible_first_min = first.min.max(available.saturating_sub(second_max));
7663    let feasible_first_max = first_max.min(available.saturating_sub(second.min));
7664
7665    if feasible_first_min > feasible_first_max {
7666        return Err(PaneModelError::OverconstrainedSplit {
7667            node_id,
7668            axis,
7669            available,
7670            first_min: first.min,
7671            first_max,
7672            second_min: second.min,
7673            second_max,
7674        });
7675    }
7676
7677    let total_weight = u64::from(ratio.numerator()) + u64::from(ratio.denominator());
7678    let desired_first_u64 = (u64::from(available) * u64::from(ratio.numerator())) / total_weight;
7679    let desired_first = desired_first_u64 as u16;
7680
7681    let first_size = desired_first.clamp(feasible_first_min, feasible_first_max);
7682    let second_size = available.saturating_sub(first_size);
7683    Ok((first_size, second_size))
7684}
7685
7686fn dfs_validate(
7687    node_id: PaneId,
7688    nodes: &BTreeMap<PaneId, PaneNodeRecord>,
7689    visiting: &mut BTreeSet<PaneId>,
7690    visited: &mut BTreeSet<PaneId>,
7691) -> Result<(), PaneModelError> {
7692    if visiting.contains(&node_id) {
7693        return Err(PaneModelError::CycleDetected { node_id });
7694    }
7695    if !visited.insert(node_id) {
7696        return Ok(());
7697    }
7698
7699    let _ = visiting.insert(node_id);
7700    if let Some(node) = nodes.get(&node_id)
7701        && let PaneNodeKind::Split(split) = &node.kind
7702    {
7703        dfs_validate(split.first, nodes, visiting, visited)?;
7704        dfs_validate(split.second, nodes, visiting, visited)?;
7705    }
7706    let _ = visiting.remove(&node_id);
7707    Ok(())
7708}
7709
7710fn gcd_u32(mut left: u32, mut right: u32) -> u32 {
7711    while right != 0 {
7712        let rem = left % right;
7713        left = right;
7714        right = rem;
7715    }
7716    left.max(1)
7717}
7718
7719#[cfg(test)]
7720mod tests {
7721    use super::*;
7722    use proptest::prelude::*;
7723
7724    fn id(raw: u64) -> PaneId {
7725        PaneId::new(raw).expect("test ID must be non-zero")
7726    }
7727
7728    fn make_valid_snapshot() -> PaneTreeSnapshot {
7729        let root = id(1);
7730        let left = id(2);
7731        let right = id(3);
7732
7733        PaneTreeSnapshot {
7734            schema_version: PANE_TREE_SCHEMA_VERSION,
7735            root,
7736            next_id: id(4),
7737            nodes: vec![
7738                PaneNodeRecord::leaf(
7739                    right,
7740                    Some(root),
7741                    PaneLeaf {
7742                        surface_key: "right".to_string(),
7743                        extensions: BTreeMap::new(),
7744                    },
7745                ),
7746                PaneNodeRecord::split(
7747                    root,
7748                    None,
7749                    PaneSplit {
7750                        axis: SplitAxis::Horizontal,
7751                        ratio: PaneSplitRatio::new(3, 2).expect("valid ratio"),
7752                        first: left,
7753                        second: right,
7754                    },
7755                ),
7756                PaneNodeRecord::leaf(
7757                    left,
7758                    Some(root),
7759                    PaneLeaf {
7760                        surface_key: "left".to_string(),
7761                        extensions: BTreeMap::new(),
7762                    },
7763                ),
7764            ],
7765            extensions: BTreeMap::new(),
7766        }
7767    }
7768
7769    fn split_ratio(tree: &PaneTree, split: PaneId) -> PaneSplitRatio {
7770        let node = tree.node(split).expect("split node should exist");
7771        let PaneNodeKind::Split(split_node) = &node.kind else {
7772            let expected_split_node = false;
7773            assert!(expected_split_node, "node should be a split");
7774            return PaneSplitRatio::default();
7775        };
7776        split_node.ratio
7777    }
7778
7779    fn make_nested_snapshot() -> PaneTreeSnapshot {
7780        let root = id(1);
7781        let left = id(2);
7782        let right_split = id(3);
7783        let right_top = id(4);
7784        let right_bottom = id(5);
7785
7786        PaneTreeSnapshot {
7787            schema_version: PANE_TREE_SCHEMA_VERSION,
7788            root,
7789            next_id: id(6),
7790            nodes: vec![
7791                PaneNodeRecord::split(
7792                    root,
7793                    None,
7794                    PaneSplit {
7795                        axis: SplitAxis::Horizontal,
7796                        ratio: PaneSplitRatio::new(1, 1).expect("valid ratio"),
7797                        first: left,
7798                        second: right_split,
7799                    },
7800                ),
7801                PaneNodeRecord::leaf(left, Some(root), PaneLeaf::new("left")),
7802                PaneNodeRecord::split(
7803                    right_split,
7804                    Some(root),
7805                    PaneSplit {
7806                        axis: SplitAxis::Vertical,
7807                        ratio: PaneSplitRatio::new(1, 1).expect("valid ratio"),
7808                        first: right_top,
7809                        second: right_bottom,
7810                    },
7811                ),
7812                PaneNodeRecord::leaf(right_top, Some(right_split), PaneLeaf::new("right_top")),
7813                PaneNodeRecord::leaf(
7814                    right_bottom,
7815                    Some(right_split),
7816                    PaneLeaf::new("right_bottom"),
7817                ),
7818            ],
7819            extensions: BTreeMap::new(),
7820        }
7821    }
7822
7823    #[test]
7824    fn ratio_is_normalized() {
7825        let ratio = PaneSplitRatio::new(12, 8).expect("ratio should normalize");
7826        assert_eq!(ratio.numerator(), 3);
7827        assert_eq!(ratio.denominator(), 2);
7828    }
7829
7830    #[test]
7831    fn snapshot_round_trip_preserves_canonical_order() {
7832        let tree =
7833            PaneTree::from_snapshot(make_valid_snapshot()).expect("snapshot should validate");
7834        let snapshot = tree.to_snapshot();
7835        let ids = snapshot
7836            .nodes
7837            .iter()
7838            .map(|node| node.id.get())
7839            .collect::<Vec<_>>();
7840        assert_eq!(ids, vec![1, 2, 3]);
7841    }
7842
7843    #[test]
7844    fn duplicate_node_id_is_rejected() {
7845        let mut snapshot = make_valid_snapshot();
7846        snapshot.nodes.push(PaneNodeRecord::leaf(
7847            id(2),
7848            Some(id(1)),
7849            PaneLeaf::new("dup"),
7850        ));
7851        let err = PaneTree::from_snapshot(snapshot).expect_err("duplicate ID should fail");
7852        assert_eq!(err, PaneModelError::DuplicateNodeId { node_id: id(2) });
7853    }
7854
7855    #[test]
7856    fn missing_child_is_rejected() {
7857        let mut snapshot = make_valid_snapshot();
7858        snapshot.nodes.retain(|node| node.id != id(3));
7859        let err = PaneTree::from_snapshot(snapshot).expect_err("missing child should fail");
7860        assert_eq!(
7861            err,
7862            PaneModelError::MissingChild {
7863                parent: id(1),
7864                child: id(3),
7865            }
7866        );
7867    }
7868
7869    #[test]
7870    fn unreachable_node_is_rejected() {
7871        let mut snapshot = make_valid_snapshot();
7872        snapshot
7873            .nodes
7874            .push(PaneNodeRecord::leaf(id(10), None, PaneLeaf::new("orphan")));
7875        snapshot.next_id = id(11);
7876        let err = PaneTree::from_snapshot(snapshot).expect_err("orphan should fail");
7877        assert_eq!(err, PaneModelError::UnreachableNode { node_id: id(10) });
7878    }
7879
7880    #[test]
7881    fn next_id_must_be_greater_than_existing_ids() {
7882        let mut snapshot = make_valid_snapshot();
7883        snapshot.next_id = id(3);
7884        let err = PaneTree::from_snapshot(snapshot).expect_err("next_id should be > max ID");
7885        assert_eq!(
7886            err,
7887            PaneModelError::NextIdNotGreaterThanExisting {
7888                next_id: id(3),
7889                max_existing: id(3),
7890            }
7891        );
7892    }
7893
7894    #[test]
7895    fn constraints_validate_bounds() {
7896        let constraints = PaneConstraints {
7897            min_width: 8,
7898            min_height: 1,
7899            max_width: Some(4),
7900            max_height: None,
7901            collapsible: false,
7902            margin: None,
7903            padding: None,
7904        };
7905        let err = constraints
7906            .validate(id(5))
7907            .expect_err("max width below min width must fail");
7908        assert_eq!(
7909            err,
7910            PaneModelError::InvalidConstraint {
7911                node_id: id(5),
7912                axis: "width",
7913                min: 8,
7914                max: 4,
7915            }
7916        );
7917    }
7918
7919    #[test]
7920    fn allocator_is_deterministic() {
7921        let mut allocator = PaneIdAllocator::default();
7922        assert_eq!(allocator.allocate().expect("id 1"), id(1));
7923        assert_eq!(allocator.allocate().expect("id 2"), id(2));
7924        assert_eq!(allocator.peek(), id(3));
7925    }
7926
7927    #[test]
7928    fn snapshot_json_shape_contains_forward_compat_fields() {
7929        let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
7930        let json = serde_json::to_value(tree.to_snapshot()).expect("snapshot should serialize");
7931        assert_eq!(json["schema_version"], serde_json::json!(1));
7932        assert!(json.get("extensions").is_some());
7933        let nodes = json["nodes"]
7934            .as_array()
7935            .expect("nodes should serialize as array");
7936        assert_eq!(nodes.len(), 3);
7937        assert!(nodes[0].get("kind").is_some());
7938    }
7939
7940    #[test]
7941    fn solver_horizontal_ratio_split() {
7942        let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
7943        let layout = tree
7944            .solve_layout(Rect::new(0, 0, 50, 10))
7945            .expect("layout solve should succeed");
7946
7947        assert_eq!(layout.rect(id(1)), Some(Rect::new(0, 0, 50, 10)));
7948        assert_eq!(layout.rect(id(2)), Some(Rect::new(0, 0, 30, 10)));
7949        assert_eq!(layout.rect(id(3)), Some(Rect::new(30, 0, 20, 10)));
7950    }
7951
7952    #[test]
7953    fn solver_clamps_to_child_minimum_constraints() {
7954        let mut snapshot = make_valid_snapshot();
7955        for node in &mut snapshot.nodes {
7956            if node.id == id(2) {
7957                node.constraints.min_width = 35;
7958            }
7959        }
7960
7961        let tree = PaneTree::from_snapshot(snapshot).expect("valid tree");
7962        let layout = tree
7963            .solve_layout(Rect::new(0, 0, 50, 10))
7964            .expect("layout solve should succeed");
7965
7966        assert_eq!(layout.rect(id(2)), Some(Rect::new(0, 0, 35, 10)));
7967        assert_eq!(layout.rect(id(3)), Some(Rect::new(35, 0, 15, 10)));
7968    }
7969
7970    #[test]
7971    fn solver_rejects_overconstrained_split() {
7972        let mut snapshot = make_valid_snapshot();
7973        for node in &mut snapshot.nodes {
7974            if node.id == id(2) {
7975                node.constraints.min_width = 30;
7976            }
7977            if node.id == id(3) {
7978                node.constraints.min_width = 30;
7979            }
7980        }
7981
7982        let tree = PaneTree::from_snapshot(snapshot).expect("valid tree");
7983        let err = tree
7984            .solve_layout(Rect::new(0, 0, 50, 10))
7985            .expect_err("infeasible constraints should fail");
7986
7987        assert_eq!(
7988            err,
7989            PaneModelError::OverconstrainedSplit {
7990                node_id: id(1),
7991                axis: SplitAxis::Horizontal,
7992                available: 50,
7993                first_min: 30,
7994                first_max: 50,
7995                second_min: 30,
7996                second_max: 50,
7997            }
7998        );
7999    }
8000
8001    #[test]
8002    fn solver_is_deterministic() {
8003        let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
8004        let first = tree
8005            .solve_layout(Rect::new(0, 0, 79, 17))
8006            .expect("first solve should succeed");
8007        let second = tree
8008            .solve_layout(Rect::new(0, 0, 79, 17))
8009            .expect("second solve should succeed");
8010        assert_eq!(first, second);
8011    }
8012
8013    #[test]
8014    fn solver_reserves_space_for_nested_minima() {
8015        for axis in [SplitAxis::Horizontal, SplitAxis::Vertical] {
8016            let mut snapshot = make_nested_snapshot();
8017            for node in &mut snapshot.nodes {
8018                if let PaneNodeKind::Split(split) = &mut node.kind {
8019                    split.axis = axis;
8020                    split.ratio = PaneSplitRatio::new(3, 2).expect("ratio");
8021                }
8022                if node.id == id(4) || node.id == id(5) {
8023                    node.constraints.min_width = 2;
8024                    node.constraints.min_height = 2;
8025                }
8026            }
8027            let tree = PaneTree::from_snapshot(snapshot).expect("nested tree");
8028            let before = tree.to_snapshot();
8029            let layout = tree
8030                .solve_layout(Rect::new(10, 20, 7, 7))
8031                .expect("three leaves fit when descendant minima are respected");
8032            let (left, nested) = match axis {
8033                SplitAxis::Horizontal => (Rect::new(10, 20, 3, 7), Rect::new(13, 20, 4, 7)),
8034                SplitAxis::Vertical => (Rect::new(10, 20, 7, 3), Rect::new(10, 23, 7, 4)),
8035            };
8036            assert_eq!(layout.rect(id(2)), Some(left));
8037            assert_eq!(layout.rect(id(3)), Some(nested));
8038            assert_eq!(
8039                tree.to_snapshot(),
8040                before,
8041                "solving does not mutate history"
8042            );
8043        }
8044    }
8045
8046    #[test]
8047    fn solver_respects_nested_maxima_across_axes() {
8048        for axis in [SplitAxis::Horizontal, SplitAxis::Vertical] {
8049            let mut snapshot = make_nested_snapshot();
8050            for node in &mut snapshot.nodes {
8051                if let PaneNodeKind::Split(split) = &mut node.kind {
8052                    split.axis = if node.id == id(1) {
8053                        axis
8054                    } else if axis == SplitAxis::Horizontal {
8055                        SplitAxis::Vertical
8056                    } else {
8057                        SplitAxis::Horizontal
8058                    };
8059                    split.ratio = PaneSplitRatio::new(1, 1).expect("ratio");
8060                }
8061                if node.id == id(4) || node.id == id(5) {
8062                    match axis {
8063                        SplitAxis::Horizontal => node.constraints.max_width = Some(3),
8064                        SplitAxis::Vertical => node.constraints.max_height = Some(3),
8065                    }
8066                }
8067            }
8068            let tree = PaneTree::from_snapshot(snapshot).expect("nested tree");
8069            let layout = tree
8070                .solve_layout(Rect::new(0, 0, 10, 10))
8071                .expect("remaining space belongs to the uncapped sibling");
8072            let nested = layout.rect(id(3)).expect("nested rectangle");
8073            assert_eq!(
8074                match axis {
8075                    SplitAxis::Horizontal => nested.width,
8076                    SplitAxis::Vertical => nested.height,
8077                },
8078                3
8079            );
8080        }
8081    }
8082
8083    #[test]
8084    fn solver_descendant_bounds_cover_zero_and_u16_limits() {
8085        for axis in [SplitAxis::Horizontal, SplitAxis::Vertical] {
8086            for (first, second, extent, fits) in [
8087                (0, 0, 0, true),
8088                (32_767, 32_768, u16::MAX, true),
8089                (32_767, 32_768, u16::MAX - 1, false),
8090                (32_768, 32_768, u16::MAX, false),
8091            ] {
8092                let mut snapshot = make_nested_snapshot();
8093                for node in &mut snapshot.nodes {
8094                    node.constraints.min_width = 0;
8095                    node.constraints.min_height = 0;
8096                    if let PaneNodeKind::Split(split) = &mut node.kind {
8097                        split.axis = axis;
8098                    }
8099                    let minimum = if node.id == id(4) {
8100                        first
8101                    } else if node.id == id(5) {
8102                        second
8103                    } else {
8104                        0
8105                    };
8106                    match axis {
8107                        SplitAxis::Horizontal => node.constraints.min_width = minimum,
8108                        SplitAxis::Vertical => node.constraints.min_height = minimum,
8109                    }
8110                }
8111                let tree = PaneTree::from_snapshot(snapshot).expect("valid bounds");
8112                let area = match axis {
8113                    SplitAxis::Horizontal => Rect::new(0, 0, extent, 1),
8114                    SplitAxis::Vertical => Rect::new(0, 0, 1, extent),
8115                };
8116                assert_eq!(
8117                    tree.solve_layout(area).is_ok(),
8118                    fits,
8119                    "{axis:?}: {first}+{second} in {extent}"
8120                );
8121            }
8122        }
8123    }
8124
8125    // Independent feasibility oracle: enumerate every integer partition, without
8126    // using the production bounds propagation or its ratio/clamping algorithm.
8127    fn exhaustive_pane_feasibility(
8128        tree: &PaneTree,
8129        node_id: PaneId,
8130        width: u16,
8131        height: u16,
8132    ) -> bool {
8133        let node = tree.node(node_id).expect("oracle node");
8134        let c = node.constraints;
8135        if width < c.min_width
8136            || height < c.min_height
8137            || c.max_width.is_some_and(|max| width > max)
8138            || c.max_height.is_some_and(|max| height > max)
8139        {
8140            return false;
8141        }
8142        match &node.kind {
8143            PaneNodeKind::Leaf(_) => true,
8144            PaneNodeKind::Split(split) => match split.axis {
8145                SplitAxis::Horizontal => (0..=width).any(|first| {
8146                    exhaustive_pane_feasibility(tree, split.first, first, height)
8147                        && exhaustive_pane_feasibility(tree, split.second, width - first, height)
8148                }),
8149                SplitAxis::Vertical => (0..=height).any(|first| {
8150                    exhaustive_pane_feasibility(tree, split.first, width, first)
8151                        && exhaustive_pane_feasibility(tree, split.second, width, height - first)
8152                }),
8153            },
8154        }
8155    }
8156
8157    proptest! {
8158        #![proptest_config(ProptestConfig::with_cases(256))]
8159
8160        #[test]
8161        fn solver_matches_exhaustive_nested_feasibility(
8162            bounds in prop::collection::vec((0u16..5, 0u16..5, prop::option::of(0u16..5), prop::option::of(0u16..5)), 5),
8163            axes in any::<[bool; 2]>(),
8164            weights in prop::array::uniform4(1u32..9),
8165        ) {
8166            let mut snapshot = make_nested_snapshot();
8167            let mut split_index = 0;
8168            for (node, (min_width, min_height, width_slack, height_slack)) in snapshot.nodes.iter_mut().zip(bounds) {
8169                node.constraints.min_width = min_width;
8170                node.constraints.min_height = min_height;
8171                node.constraints.max_width = width_slack.map(|slack| min_width + slack);
8172                node.constraints.max_height = height_slack.map(|slack| min_height + slack);
8173                if let PaneNodeKind::Split(split) = &mut node.kind {
8174                    split.axis = if axes[split_index] { SplitAxis::Horizontal } else { SplitAxis::Vertical };
8175                    split.ratio = PaneSplitRatio::new(weights[split_index * 2], weights[split_index * 2 + 1]).expect("positive weights");
8176                    split_index += 1;
8177                }
8178            }
8179            let tree = PaneTree::from_snapshot(snapshot).expect("valid individual constraints");
8180            let before = tree.to_snapshot();
8181            for width in 0..=12 {
8182                for height in 0..=12 {
8183                    let expected = exhaustive_pane_feasibility(&tree, tree.root(), width, height);
8184                    let actual = tree.solve_layout(Rect::new(2, 3, width, height));
8185                    prop_assert_eq!(actual.is_ok(), expected, "viewport {}x{}, result {:?}, tree {:?}", width, height, actual, before);
8186                    if let Ok(layout) = actual {
8187                        for node in tree.nodes() {
8188                            let rect = layout.rect(node.id).expect("every node has a rectangle");
8189                            prop_assert!(rect.x >= 2 && rect.y >= 3);
8190                            prop_assert!(rect.right() <= 2 + width && rect.bottom() <= 3 + height);
8191                            prop_assert!(exhaustive_pane_feasibility(&tree, node.id, rect.width, rect.height));
8192                        }
8193                    }
8194                }
8195            }
8196            prop_assert_eq!(tree.to_snapshot(), before);
8197        }
8198    }
8199
8200    #[test]
8201    fn split_leaf_wraps_existing_leaf_with_new_split() {
8202        let mut tree = PaneTree::singleton("root");
8203        let outcome = tree
8204            .apply_operation(
8205                7,
8206                PaneOperation::SplitLeaf {
8207                    target: id(1),
8208                    axis: SplitAxis::Horizontal,
8209                    ratio: PaneSplitRatio::new(3, 2).expect("valid ratio"),
8210                    placement: PanePlacement::ExistingFirst,
8211                    new_leaf: PaneLeaf::new("new"),
8212                },
8213            )
8214            .expect("split should succeed");
8215
8216        assert_eq!(outcome.operation_id, 7);
8217        assert_eq!(outcome.kind, PaneOperationKind::SplitLeaf);
8218        assert_ne!(outcome.before_hash, outcome.after_hash);
8219        assert_eq!(tree.root(), id(2));
8220
8221        let root = tree.node(id(2)).expect("split node exists");
8222        let PaneNodeKind::Split(split) = &root.kind else {
8223            unreachable!("root should be split");
8224        };
8225        assert_eq!(split.first, id(1));
8226        assert_eq!(split.second, id(3));
8227
8228        let original = tree.node(id(1)).expect("original leaf exists");
8229        assert_eq!(original.parent, Some(id(2)));
8230        assert!(matches!(original.kind, PaneNodeKind::Leaf(_)));
8231
8232        let new_leaf = tree.node(id(3)).expect("new leaf exists");
8233        assert_eq!(new_leaf.parent, Some(id(2)));
8234        let PaneNodeKind::Leaf(leaf) = &new_leaf.kind else {
8235            unreachable!("new node must be leaf");
8236        };
8237        assert_eq!(leaf.surface_key, "new");
8238        assert!(tree.validate().is_ok());
8239    }
8240
8241    #[test]
8242    fn touched_nodes_compact_storage_holds_correct_content() {
8243        // Compact (`SmallVec`) touched-node storage must round-trip the same
8244        // content as before across the structural, fast, and rejected paths.
8245        let mut tree = PaneTree::singleton("root");
8246        let split = tree
8247            .apply_operation(
8248                1,
8249                PaneOperation::SplitLeaf {
8250                    target: id(1),
8251                    axis: SplitAxis::Horizontal,
8252                    ratio: PaneSplitRatio::new(1, 1).expect("ratio"),
8253                    placement: PanePlacement::ExistingFirst,
8254                    new_leaf: PaneLeaf::new("b"),
8255                },
8256            )
8257            .expect("split should succeed");
8258        // Structural op: touched set carries the target (multi-element case).
8259        assert!(split.touched_nodes.contains(&id(1)));
8260
8261        // SetSplitRatio (the resize fast path) touches exactly the split node.
8262        let resize = tree
8263            .apply_operation(
8264                2,
8265                PaneOperation::SetSplitRatio {
8266                    split: id(2),
8267                    ratio: PaneSplitRatio::new(3, 1).expect("ratio"),
8268                },
8269            )
8270            .expect("resize should succeed");
8271        assert_eq!(resize.touched_nodes.to_vec(), vec![id(2)]);
8272
8273        // A rejected fast-path op also carries compact touched-node storage.
8274        let rejected = tree
8275            .apply_operation(
8276                3,
8277                PaneOperation::SetSplitRatio {
8278                    split: id(999),
8279                    ratio: PaneSplitRatio::new(1, 1).expect("ratio"),
8280                },
8281            )
8282            .expect_err("missing split must be rejected");
8283        assert_eq!(rejected.touched_nodes.to_vec(), vec![id(999)]);
8284    }
8285
8286    #[test]
8287    fn close_node_promotes_sibling_and_removes_split_parent() {
8288        let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
8289        let outcome = tree
8290            .apply_operation(8, PaneOperation::CloseNode { target: id(2) })
8291            .expect("close should succeed");
8292        assert_eq!(outcome.kind, PaneOperationKind::CloseNode);
8293
8294        assert_eq!(tree.root(), id(3));
8295        assert!(tree.node(id(1)).is_none());
8296        assert!(tree.node(id(2)).is_none());
8297        assert_eq!(tree.node(id(3)).and_then(|node| node.parent), None);
8298        assert!(tree.validate().is_ok());
8299    }
8300
8301    #[test]
8302    fn close_root_is_rejected_with_stable_hashes() {
8303        let mut tree = PaneTree::singleton("root");
8304        let err = tree
8305            .apply_operation(9, PaneOperation::CloseNode { target: id(1) })
8306            .expect_err("closing root must fail");
8307
8308        assert_eq!(err.operation_id, 9);
8309        assert_eq!(err.kind, PaneOperationKind::CloseNode);
8310        assert_eq!(
8311            err.reason,
8312            PaneOperationFailure::CannotCloseRoot { node_id: id(1) }
8313        );
8314        assert_eq!(err.before_hash, err.after_hash);
8315        assert_eq!(tree.root(), id(1));
8316        assert!(tree.validate().is_ok());
8317    }
8318
8319    #[test]
8320    fn move_subtree_wraps_target_and_detaches_old_parent() {
8321        let mut tree = PaneTree::from_snapshot(make_nested_snapshot()).expect("valid tree");
8322        let outcome = tree
8323            .apply_operation(
8324                10,
8325                PaneOperation::MoveSubtree {
8326                    source: id(4),
8327                    target: id(2),
8328                    axis: SplitAxis::Vertical,
8329                    ratio: PaneSplitRatio::new(2, 1).expect("valid ratio"),
8330                    placement: PanePlacement::ExistingFirst,
8331                },
8332            )
8333            .expect("move should succeed");
8334        assert_eq!(outcome.kind, PaneOperationKind::MoveSubtree);
8335
8336        assert!(
8337            tree.node(id(3)).is_none(),
8338            "old split parent should be removed"
8339        );
8340        assert_eq!(tree.node(id(5)).and_then(|node| node.parent), Some(id(1)));
8341
8342        let inserted_split = tree
8343            .nodes()
8344            .find(|node| matches!(node.kind, PaneNodeKind::Split(_)) && node.id.get() >= 6)
8345            .expect("new split should exist");
8346        let PaneNodeKind::Split(split) = &inserted_split.kind else {
8347            unreachable!();
8348        };
8349        assert_eq!(split.first, id(2));
8350        assert_eq!(split.second, id(4));
8351        assert_eq!(
8352            tree.node(id(2)).and_then(|node| node.parent),
8353            Some(inserted_split.id)
8354        );
8355        assert_eq!(
8356            tree.node(id(4)).and_then(|node| node.parent),
8357            Some(inserted_split.id)
8358        );
8359        assert!(tree.validate().is_ok());
8360    }
8361
8362    #[test]
8363    fn move_subtree_rejects_ancestor_target() {
8364        let mut tree = PaneTree::from_snapshot(make_nested_snapshot()).expect("valid tree");
8365        let err = tree
8366            .apply_operation(
8367                11,
8368                PaneOperation::MoveSubtree {
8369                    source: id(3),
8370                    target: id(4),
8371                    axis: SplitAxis::Horizontal,
8372                    ratio: PaneSplitRatio::new(1, 1).expect("valid ratio"),
8373                    placement: PanePlacement::ExistingFirst,
8374                },
8375            )
8376            .expect_err("ancestor move must fail");
8377
8378        assert_eq!(err.kind, PaneOperationKind::MoveSubtree);
8379        assert_eq!(
8380            err.reason,
8381            PaneOperationFailure::AncestorConflict {
8382                ancestor: id(3),
8383                descendant: id(4),
8384            }
8385        );
8386        assert!(tree.validate().is_ok());
8387    }
8388
8389    #[test]
8390    fn swap_nodes_exchanges_sibling_positions() {
8391        let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
8392        let outcome = tree
8393            .apply_operation(
8394                12,
8395                PaneOperation::SwapNodes {
8396                    first: id(2),
8397                    second: id(3),
8398                },
8399            )
8400            .expect("swap should succeed");
8401        assert_eq!(outcome.kind, PaneOperationKind::SwapNodes);
8402
8403        let root = tree.node(id(1)).expect("root exists");
8404        let PaneNodeKind::Split(split) = &root.kind else {
8405            unreachable!("root should remain split");
8406        };
8407        assert_eq!(split.first, id(3));
8408        assert_eq!(split.second, id(2));
8409        assert_eq!(tree.node(id(2)).and_then(|node| node.parent), Some(id(1)));
8410        assert_eq!(tree.node(id(3)).and_then(|node| node.parent), Some(id(1)));
8411        assert!(tree.validate().is_ok());
8412    }
8413
8414    #[test]
8415    fn swap_nodes_rejects_ancestor_relation() {
8416        let mut tree = PaneTree::from_snapshot(make_nested_snapshot()).expect("valid tree");
8417        let err = tree
8418            .apply_operation(
8419                13,
8420                PaneOperation::SwapNodes {
8421                    first: id(3),
8422                    second: id(4),
8423                },
8424            )
8425            .expect_err("ancestor swap must fail");
8426
8427        assert_eq!(err.kind, PaneOperationKind::SwapNodes);
8428        assert_eq!(
8429            err.reason,
8430            PaneOperationFailure::AncestorConflict {
8431                ancestor: id(3),
8432                descendant: id(4),
8433            }
8434        );
8435        assert!(tree.validate().is_ok());
8436    }
8437
8438    #[test]
8439    fn normalize_ratios_canonicalizes_non_reduced_values() {
8440        let mut snapshot = make_valid_snapshot();
8441        for node in &mut snapshot.nodes {
8442            if let PaneNodeKind::Split(split) = &mut node.kind {
8443                split.ratio = PaneSplitRatio {
8444                    numerator: 12,
8445                    denominator: 8,
8446                };
8447            }
8448        }
8449
8450        let mut tree = PaneTree::from_snapshot(snapshot).expect("valid tree");
8451        let outcome = tree
8452            .apply_operation(14, PaneOperation::NormalizeRatios)
8453            .expect("normalize should succeed");
8454        assert_eq!(outcome.kind, PaneOperationKind::NormalizeRatios);
8455
8456        let root = tree.node(id(1)).expect("root exists");
8457        let PaneNodeKind::Split(split) = &root.kind else {
8458            unreachable!("root should be split");
8459        };
8460        assert_eq!(split.ratio.numerator(), 3);
8461        assert_eq!(split.ratio.denominator(), 2);
8462    }
8463
8464    #[test]
8465    fn transaction_commit_persists_mutations_and_journal_order() {
8466        let tree = PaneTree::singleton("root");
8467        let mut tx = tree.begin_transaction(77);
8468
8469        let split = tx
8470            .apply_operation(
8471                100,
8472                PaneOperation::SplitLeaf {
8473                    target: id(1),
8474                    axis: SplitAxis::Horizontal,
8475                    ratio: PaneSplitRatio::new(1, 1).expect("valid ratio"),
8476                    placement: PanePlacement::ExistingFirst,
8477                    new_leaf: PaneLeaf::new("secondary"),
8478                },
8479            )
8480            .expect("split should succeed");
8481        assert_eq!(split.kind, PaneOperationKind::SplitLeaf);
8482
8483        let normalize = tx
8484            .apply_operation(101, PaneOperation::NormalizeRatios)
8485            .expect("normalize should succeed");
8486        assert_eq!(normalize.kind, PaneOperationKind::NormalizeRatios);
8487
8488        let outcome = tx.commit();
8489        assert!(outcome.committed);
8490        assert_eq!(outcome.transaction_id, 77);
8491        assert_eq!(outcome.tree.root(), id(2));
8492        assert_eq!(outcome.journal.len(), 2);
8493        assert_eq!(outcome.journal[0].sequence, 1);
8494        assert_eq!(outcome.journal[1].sequence, 2);
8495        assert_eq!(outcome.journal[0].operation_id, 100);
8496        assert_eq!(outcome.journal[1].operation_id, 101);
8497        assert_eq!(
8498            outcome.journal[0].result,
8499            PaneOperationJournalResult::Applied
8500        );
8501        assert_eq!(
8502            outcome.journal[1].result,
8503            PaneOperationJournalResult::Applied
8504        );
8505    }
8506
8507    #[test]
8508    fn transaction_rollback_discards_mutations() {
8509        let tree = PaneTree::singleton("root");
8510        let before_hash = tree.state_hash();
8511        let mut tx = tree.begin_transaction(78);
8512
8513        tx.apply_operation(
8514            200,
8515            PaneOperation::SplitLeaf {
8516                target: id(1),
8517                axis: SplitAxis::Vertical,
8518                ratio: PaneSplitRatio::new(2, 1).expect("valid ratio"),
8519                placement: PanePlacement::ExistingFirst,
8520                new_leaf: PaneLeaf::new("extra"),
8521            },
8522        )
8523        .expect("split should succeed");
8524
8525        let outcome = tx.rollback();
8526        assert!(!outcome.committed);
8527        assert_eq!(outcome.tree.state_hash(), before_hash);
8528        assert_eq!(outcome.tree.root(), id(1));
8529        assert_eq!(outcome.journal.len(), 1);
8530        assert_eq!(outcome.journal[0].operation_id, 200);
8531    }
8532
8533    #[test]
8534    fn transaction_journals_rejected_operation_without_mutation() {
8535        let tree = PaneTree::singleton("root");
8536        let mut tx = tree.begin_transaction(79);
8537        let before_hash = tx.tree().state_hash();
8538
8539        let err = tx
8540            .apply_operation(300, PaneOperation::CloseNode { target: id(1) })
8541            .expect_err("close root should fail");
8542        assert_eq!(err.before_hash, err.after_hash);
8543        assert_eq!(tx.tree().state_hash(), before_hash);
8544
8545        let journal = tx.journal();
8546        assert_eq!(journal.len(), 1);
8547        assert_eq!(journal[0].operation_id, 300);
8548        let PaneOperationJournalResult::Rejected { reason } = &journal[0].result else {
8549            unreachable!("journal entry should be rejected");
8550        };
8551        assert!(reason.contains("cannot close root"));
8552    }
8553
8554    #[test]
8555    fn transaction_journal_is_deterministic_for_equivalent_runs() {
8556        let base = PaneTree::singleton("root");
8557
8558        let mut first_tx = base.begin_transaction(80);
8559        first_tx
8560            .apply_operation(
8561                1,
8562                PaneOperation::SplitLeaf {
8563                    target: id(1),
8564                    axis: SplitAxis::Horizontal,
8565                    ratio: PaneSplitRatio::new(3, 1).expect("valid ratio"),
8566                    placement: PanePlacement::IncomingFirst,
8567                    new_leaf: PaneLeaf::new("new"),
8568                },
8569            )
8570            .expect("split should succeed");
8571        first_tx
8572            .apply_operation(2, PaneOperation::NormalizeRatios)
8573            .expect("normalize should succeed");
8574        let first = first_tx.commit();
8575
8576        let mut second_tx = base.begin_transaction(80);
8577        second_tx
8578            .apply_operation(
8579                1,
8580                PaneOperation::SplitLeaf {
8581                    target: id(1),
8582                    axis: SplitAxis::Horizontal,
8583                    ratio: PaneSplitRatio::new(3, 1).expect("valid ratio"),
8584                    placement: PanePlacement::IncomingFirst,
8585                    new_leaf: PaneLeaf::new("new"),
8586                },
8587            )
8588            .expect("split should succeed");
8589        second_tx
8590            .apply_operation(2, PaneOperation::NormalizeRatios)
8591            .expect("normalize should succeed");
8592        let second = second_tx.commit();
8593
8594        assert_eq!(first.tree.state_hash(), second.tree.state_hash());
8595        assert_eq!(first.journal, second.journal);
8596    }
8597
8598    #[test]
8599    fn invariant_report_detects_parent_mismatch_and_orphan() {
8600        let mut snapshot = make_valid_snapshot();
8601        for node in &mut snapshot.nodes {
8602            if node.id == id(2) {
8603                node.parent = Some(id(3));
8604            }
8605        }
8606        snapshot
8607            .nodes
8608            .push(PaneNodeRecord::leaf(id(10), None, PaneLeaf::new("orphan")));
8609        snapshot.next_id = id(11);
8610
8611        let report = snapshot.invariant_report();
8612        assert!(report.has_errors());
8613        assert!(
8614            report
8615                .issues
8616                .iter()
8617                .any(|issue| issue.code == PaneInvariantCode::ParentMismatch)
8618        );
8619        assert!(
8620            report
8621                .issues
8622                .iter()
8623                .any(|issue| issue.code == PaneInvariantCode::UnreachableNode)
8624        );
8625    }
8626
8627    #[test]
8628    fn repair_safe_normalizes_ratio_repairs_parents_and_removes_orphans() {
8629        let mut snapshot = make_valid_snapshot();
8630        for node in &mut snapshot.nodes {
8631            if node.id == id(1) {
8632                node.parent = Some(id(3));
8633                let PaneNodeKind::Split(split) = &mut node.kind else {
8634                    unreachable!("root should be split");
8635                };
8636                split.ratio = PaneSplitRatio {
8637                    numerator: 12,
8638                    denominator: 8,
8639                };
8640            }
8641            if node.id == id(2) {
8642                node.parent = Some(id(3));
8643            }
8644        }
8645        snapshot
8646            .nodes
8647            .push(PaneNodeRecord::leaf(id(10), None, PaneLeaf::new("orphan")));
8648        snapshot.next_id = id(11);
8649
8650        let repaired = snapshot.repair_safe().expect("repair should succeed");
8651        assert_ne!(repaired.before_hash, repaired.after_hash);
8652        assert!(repaired.tree.validate().is_ok());
8653        assert!(!repaired.report_after.has_errors());
8654        assert!(
8655            repaired
8656                .actions
8657                .iter()
8658                .any(|action| matches!(action, PaneRepairAction::NormalizeRatio { node_id, .. } if *node_id == id(1)))
8659        );
8660        assert!(
8661            repaired
8662                .actions
8663                .iter()
8664                .any(|action| matches!(action, PaneRepairAction::ReparentNode { node_id, .. } if *node_id == id(1)))
8665        );
8666        assert!(
8667            repaired
8668                .actions
8669                .iter()
8670                .any(|action| matches!(action, PaneRepairAction::RemoveOrphanNode { node_id } if *node_id == id(10)))
8671        );
8672    }
8673
8674    #[test]
8675    fn repair_safe_rejects_unsafe_topology() {
8676        let mut snapshot = make_valid_snapshot();
8677        snapshot.nodes.retain(|node| node.id != id(3));
8678
8679        let err = snapshot
8680            .repair_safe()
8681            .expect_err("missing-child topology must be rejected");
8682        assert!(matches!(
8683            err.reason,
8684            PaneRepairFailure::UnsafeIssuesPresent { .. }
8685        ));
8686        let PaneRepairFailure::UnsafeIssuesPresent { codes } = err.reason else {
8687            unreachable!("expected unsafe issue failure");
8688        };
8689        assert!(codes.contains(&PaneInvariantCode::MissingChild));
8690    }
8691
8692    #[test]
8693    fn repair_safe_is_deterministic_for_equivalent_snapshot() {
8694        let mut snapshot = make_valid_snapshot();
8695        for node in &mut snapshot.nodes {
8696            if node.id == id(1) {
8697                let PaneNodeKind::Split(split) = &mut node.kind else {
8698                    unreachable!("root should be split");
8699                };
8700                split.ratio = PaneSplitRatio {
8701                    numerator: 12,
8702                    denominator: 8,
8703                };
8704            }
8705        }
8706        snapshot
8707            .nodes
8708            .push(PaneNodeRecord::leaf(id(10), None, PaneLeaf::new("orphan")));
8709        snapshot.next_id = id(11);
8710
8711        let first = snapshot.clone().repair_safe().expect("first repair");
8712        let second = snapshot.repair_safe().expect("second repair");
8713
8714        assert_eq!(first.tree.state_hash(), second.tree.state_hash());
8715        assert_eq!(first.actions, second.actions);
8716        assert_eq!(first.report_after, second.report_after);
8717    }
8718
8719    fn default_target() -> PaneResizeTarget {
8720        PaneResizeTarget {
8721            split_id: id(7),
8722            axis: SplitAxis::Horizontal,
8723        }
8724    }
8725
8726    #[test]
8727    fn semantic_input_event_fixture_round_trip_covers_all_variants() {
8728        let mut pointer_down = PaneSemanticInputEvent::new(
8729            1,
8730            PaneSemanticInputEventKind::PointerDown {
8731                target: default_target(),
8732                pointer_id: 11,
8733                button: PanePointerButton::Primary,
8734                position: PanePointerPosition::new(42, 9),
8735            },
8736        );
8737        pointer_down.modifiers = PaneModifierSnapshot {
8738            shift: true,
8739            alt: false,
8740            ctrl: true,
8741            meta: false,
8742        };
8743        let pointer_down_fixture = r#"{"schema_version":1,"sequence":1,"modifiers":{"shift":true,"alt":false,"ctrl":true,"meta":false},"event":"pointer_down","target":{"split_id":7,"axis":"horizontal"},"pointer_id":11,"button":"primary","position":{"x":42,"y":9},"extensions":{}}"#;
8744
8745        let pointer_move = PaneSemanticInputEvent::new(
8746            2,
8747            PaneSemanticInputEventKind::PointerMove {
8748                target: default_target(),
8749                pointer_id: 11,
8750                position: PanePointerPosition::new(45, 8),
8751                delta_x: 3,
8752                delta_y: -1,
8753            },
8754        );
8755        let pointer_move_fixture = r#"{"schema_version":1,"sequence":2,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"pointer_move","target":{"split_id":7,"axis":"horizontal"},"pointer_id":11,"position":{"x":45,"y":8},"delta_x":3,"delta_y":-1,"extensions":{}}"#;
8756
8757        let pointer_up = PaneSemanticInputEvent::new(
8758            3,
8759            PaneSemanticInputEventKind::PointerUp {
8760                target: default_target(),
8761                pointer_id: 11,
8762                button: PanePointerButton::Primary,
8763                position: PanePointerPosition::new(45, 8),
8764            },
8765        );
8766        let pointer_up_fixture = r#"{"schema_version":1,"sequence":3,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"pointer_up","target":{"split_id":7,"axis":"horizontal"},"pointer_id":11,"button":"primary","position":{"x":45,"y":8},"extensions":{}}"#;
8767
8768        let wheel_nudge = PaneSemanticInputEvent::new(
8769            4,
8770            PaneSemanticInputEventKind::WheelNudge {
8771                target: default_target(),
8772                lines: -2,
8773            },
8774        );
8775        let wheel_nudge_fixture = r#"{"schema_version":1,"sequence":4,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"wheel_nudge","target":{"split_id":7,"axis":"horizontal"},"lines":-2,"extensions":{}}"#;
8776
8777        let keyboard_resize = PaneSemanticInputEvent::new(
8778            5,
8779            PaneSemanticInputEventKind::KeyboardResize {
8780                target: default_target(),
8781                direction: PaneResizeDirection::Increase,
8782                units: 3,
8783            },
8784        );
8785        let keyboard_resize_fixture = r#"{"schema_version":1,"sequence":5,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"keyboard_resize","target":{"split_id":7,"axis":"horizontal"},"direction":"increase","units":3,"extensions":{}}"#;
8786
8787        let cancel = PaneSemanticInputEvent::new(
8788            6,
8789            PaneSemanticInputEventKind::Cancel {
8790                target: Some(default_target()),
8791                reason: PaneCancelReason::PointerCancel,
8792            },
8793        );
8794        let cancel_fixture = r#"{"schema_version":1,"sequence":6,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"cancel","target":{"split_id":7,"axis":"horizontal"},"reason":"pointer_cancel","extensions":{}}"#;
8795
8796        let blur =
8797            PaneSemanticInputEvent::new(7, PaneSemanticInputEventKind::Blur { target: None });
8798        let blur_fixture = r#"{"schema_version":1,"sequence":7,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"blur","target":null,"extensions":{}}"#;
8799
8800        let fixtures = [
8801            ("pointer_down", pointer_down_fixture, pointer_down),
8802            ("pointer_move", pointer_move_fixture, pointer_move),
8803            ("pointer_up", pointer_up_fixture, pointer_up),
8804            ("wheel_nudge", wheel_nudge_fixture, wheel_nudge),
8805            ("keyboard_resize", keyboard_resize_fixture, keyboard_resize),
8806            ("cancel", cancel_fixture, cancel),
8807            ("blur", blur_fixture, blur),
8808        ];
8809
8810        for (name, fixture, expected) in fixtures {
8811            let parsed: PaneSemanticInputEvent =
8812                serde_json::from_str(fixture).expect("fixture should parse");
8813            assert_eq!(
8814                parsed, expected,
8815                "{name} fixture should match expected shape"
8816            );
8817            parsed.validate().expect("fixture should validate");
8818            let encoded = serde_json::to_string(&parsed).expect("event should encode");
8819            assert_eq!(encoded, fixture, "{name} fixture should be canonical");
8820        }
8821    }
8822
8823    #[test]
8824    fn semantic_input_event_defaults_schema_version_to_current() {
8825        let fixture = r#"{"sequence":9,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"blur","target":null,"extensions":{}}"#;
8826        let parsed: PaneSemanticInputEvent =
8827            serde_json::from_str(fixture).expect("fixture should parse");
8828        assert_eq!(
8829            parsed.schema_version,
8830            PANE_SEMANTIC_INPUT_EVENT_SCHEMA_VERSION
8831        );
8832        parsed.validate().expect("defaulted event should validate");
8833    }
8834
8835    #[test]
8836    fn semantic_input_event_rejects_invalid_invariants() {
8837        let target = default_target();
8838
8839        let mut schema_version = PaneSemanticInputEvent::new(
8840            1,
8841            PaneSemanticInputEventKind::Blur {
8842                target: Some(target),
8843            },
8844        );
8845        schema_version.schema_version = 99;
8846        assert_eq!(
8847            schema_version.validate(),
8848            Err(PaneSemanticInputEventError::UnsupportedSchemaVersion {
8849                version: 99,
8850                expected: PANE_SEMANTIC_INPUT_EVENT_SCHEMA_VERSION
8851            })
8852        );
8853
8854        let sequence = PaneSemanticInputEvent::new(
8855            0,
8856            PaneSemanticInputEventKind::Blur {
8857                target: Some(target),
8858            },
8859        );
8860        assert_eq!(
8861            sequence.validate(),
8862            Err(PaneSemanticInputEventError::ZeroSequence)
8863        );
8864
8865        let pointer = PaneSemanticInputEvent::new(
8866            2,
8867            PaneSemanticInputEventKind::PointerDown {
8868                target,
8869                pointer_id: 0,
8870                button: PanePointerButton::Primary,
8871                position: PanePointerPosition::new(0, 0),
8872            },
8873        );
8874        assert_eq!(
8875            pointer.validate(),
8876            Err(PaneSemanticInputEventError::ZeroPointerId)
8877        );
8878
8879        let wheel = PaneSemanticInputEvent::new(
8880            3,
8881            PaneSemanticInputEventKind::WheelNudge { target, lines: 0 },
8882        );
8883        assert_eq!(
8884            wheel.validate(),
8885            Err(PaneSemanticInputEventError::ZeroWheelLines)
8886        );
8887
8888        let keyboard = PaneSemanticInputEvent::new(
8889            4,
8890            PaneSemanticInputEventKind::KeyboardResize {
8891                target,
8892                direction: PaneResizeDirection::Decrease,
8893                units: 0,
8894            },
8895        );
8896        assert_eq!(
8897            keyboard.validate(),
8898            Err(PaneSemanticInputEventError::ZeroResizeUnits)
8899        );
8900    }
8901
8902    #[test]
8903    fn semantic_input_trace_fixture_round_trip_and_checksum_validation() {
8904        let fixture = r#"{"metadata":{"schema_version":1,"seed":7,"start_unix_ms":1700000000000,"host":"terminal","checksum":0},"events":[{"schema_version":1,"sequence":1,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"pointer_down","target":{"split_id":7,"axis":"horizontal"},"pointer_id":11,"button":"primary","position":{"x":10,"y":4},"extensions":{}},{"schema_version":1,"sequence":2,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"pointer_move","target":{"split_id":7,"axis":"horizontal"},"pointer_id":11,"position":{"x":13,"y":4},"delta_x":0,"delta_y":0,"extensions":{}},{"schema_version":1,"sequence":3,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"pointer_move","target":{"split_id":7,"axis":"horizontal"},"pointer_id":11,"position":{"x":15,"y":6},"delta_x":0,"delta_y":0,"extensions":{}},{"schema_version":1,"sequence":4,"modifiers":{"shift":false,"alt":false,"ctrl":false,"meta":false},"event":"pointer_up","target":{"split_id":7,"axis":"horizontal"},"pointer_id":11,"button":"primary","position":{"x":16,"y":6},"extensions":{}}]}"#;
8905
8906        let parsed: PaneSemanticInputTrace =
8907            serde_json::from_str(fixture).expect("trace fixture should parse");
8908        let checksum_mismatch = parsed
8909            .validate()
8910            .expect_err("fixture checksum=0 should fail validation");
8911        assert!(matches!(
8912            checksum_mismatch,
8913            PaneSemanticInputTraceError::ChecksumMismatch { recorded: 0, .. }
8914        ));
8915
8916        let mut canonical = parsed;
8917        canonical.metadata.checksum = canonical.recompute_checksum();
8918        canonical
8919            .validate()
8920            .expect("canonicalized fixture should validate");
8921        let encoded = serde_json::to_string(&canonical).expect("trace should encode");
8922        let reparsed: PaneSemanticInputTrace =
8923            serde_json::from_str(&encoded).expect("encoded fixture should parse");
8924        assert_eq!(reparsed, canonical);
8925        assert_eq!(reparsed.metadata.checksum, reparsed.recompute_checksum());
8926    }
8927
8928    #[test]
8929    fn semantic_input_trace_rejects_out_of_order_sequence() {
8930        let target = default_target();
8931        let mut trace = PaneSemanticInputTrace::new(
8932            42,
8933            1_700_000_000_111,
8934            "web",
8935            vec![
8936                PaneSemanticInputEvent::new(
8937                    1,
8938                    PaneSemanticInputEventKind::PointerDown {
8939                        target,
8940                        pointer_id: 9,
8941                        button: PanePointerButton::Primary,
8942                        position: PanePointerPosition::new(0, 0),
8943                    },
8944                ),
8945                PaneSemanticInputEvent::new(
8946                    2,
8947                    PaneSemanticInputEventKind::PointerMove {
8948                        target,
8949                        pointer_id: 9,
8950                        position: PanePointerPosition::new(2, 0),
8951                        delta_x: 0,
8952                        delta_y: 0,
8953                    },
8954                ),
8955                PaneSemanticInputEvent::new(
8956                    3,
8957                    PaneSemanticInputEventKind::PointerUp {
8958                        target,
8959                        pointer_id: 9,
8960                        button: PanePointerButton::Primary,
8961                        position: PanePointerPosition::new(2, 0),
8962                    },
8963                ),
8964            ],
8965        )
8966        .expect("trace should construct");
8967
8968        trace.events[2].sequence = 2;
8969        trace.metadata.checksum = trace.recompute_checksum();
8970        assert_eq!(
8971            trace.validate(),
8972            Err(PaneSemanticInputTraceError::SequenceOutOfOrder {
8973                index: 2,
8974                previous: 2,
8975                current: 2
8976            })
8977        );
8978    }
8979
8980    #[test]
8981    fn semantic_replay_fixture_runner_produces_diff_artifacts() {
8982        let target = default_target();
8983        let trace = PaneSemanticInputTrace::new(
8984            99,
8985            1_700_000_000_222,
8986            "terminal",
8987            vec![
8988                PaneSemanticInputEvent::new(
8989                    1,
8990                    PaneSemanticInputEventKind::PointerDown {
8991                        target,
8992                        pointer_id: 11,
8993                        button: PanePointerButton::Primary,
8994                        position: PanePointerPosition::new(10, 4),
8995                    },
8996                ),
8997                PaneSemanticInputEvent::new(
8998                    2,
8999                    PaneSemanticInputEventKind::PointerMove {
9000                        target,
9001                        pointer_id: 11,
9002                        position: PanePointerPosition::new(13, 4),
9003                        delta_x: 0,
9004                        delta_y: 0,
9005                    },
9006                ),
9007                PaneSemanticInputEvent::new(
9008                    3,
9009                    PaneSemanticInputEventKind::PointerMove {
9010                        target,
9011                        pointer_id: 11,
9012                        position: PanePointerPosition::new(15, 6),
9013                        delta_x: 0,
9014                        delta_y: 0,
9015                    },
9016                ),
9017                PaneSemanticInputEvent::new(
9018                    4,
9019                    PaneSemanticInputEventKind::PointerUp {
9020                        target,
9021                        pointer_id: 11,
9022                        button: PanePointerButton::Primary,
9023                        position: PanePointerPosition::new(16, 6),
9024                    },
9025                ),
9026            ],
9027        )
9028        .expect("trace should construct");
9029
9030        let mut baseline_machine = PaneDragResizeMachine::default();
9031        let baseline = trace
9032            .replay(&mut baseline_machine)
9033            .expect("baseline replay should pass");
9034        let fixture = PaneSemanticReplayFixture {
9035            trace: trace.clone(),
9036            expected_transitions: baseline.transitions.clone(),
9037            expected_final_state: baseline.final_state,
9038        };
9039
9040        let mut pass_machine = PaneDragResizeMachine::default();
9041        let pass_report = fixture
9042            .run(&mut pass_machine)
9043            .expect("fixture replay should succeed");
9044        assert!(pass_report.passed);
9045        assert!(pass_report.diffs.is_empty());
9046
9047        let mut mismatch_fixture = fixture.clone();
9048        mismatch_fixture.expected_transitions[1].transition_id += 77;
9049        mismatch_fixture.expected_final_state = PaneDragResizeState::Armed {
9050            target,
9051            pointer_id: 11,
9052            origin: PanePointerPosition::new(10, 4),
9053            current: PanePointerPosition::new(10, 4),
9054            started_sequence: 1,
9055        };
9056
9057        let mut mismatch_machine = PaneDragResizeMachine::default();
9058        let mismatch_report = mismatch_fixture
9059            .run(&mut mismatch_machine)
9060            .expect("mismatch replay should still execute");
9061        assert!(!mismatch_report.passed);
9062        assert!(
9063            mismatch_report
9064                .diffs
9065                .iter()
9066                .any(|diff| diff.kind == PaneSemanticReplayDiffKind::TransitionMismatch)
9067        );
9068        assert!(
9069            mismatch_report
9070                .diffs
9071                .iter()
9072                .any(|diff| diff.kind == PaneSemanticReplayDiffKind::FinalStateMismatch)
9073        );
9074    }
9075
9076    fn default_coordinate_normalizer() -> PaneCoordinateNormalizer {
9077        PaneCoordinateNormalizer::new(
9078            PanePointerPosition::new(100, 50),
9079            PanePointerPosition::new(20, 10),
9080            8,
9081            16,
9082            PaneScaleFactor::new(2, 1).expect("valid dpr"),
9083            PaneScaleFactor::ONE,
9084            PaneCoordinateRoundingPolicy::TowardNegativeInfinity,
9085        )
9086        .expect("normalizer should be valid")
9087    }
9088
9089    #[test]
9090    fn coordinate_normalizer_css_device_and_cell_pipeline() {
9091        let normalizer = default_coordinate_normalizer();
9092
9093        let css = normalizer
9094            .normalize(PaneInputCoordinate::CssPixels {
9095                position: PanePointerPosition::new(116, 82),
9096            })
9097            .expect("css normalization should succeed");
9098        assert_eq!(
9099            css,
9100            PaneNormalizedCoordinate {
9101                global_cell: PanePointerPosition::new(22, 12),
9102                local_cell: PanePointerPosition::new(2, 2),
9103                local_css: PanePointerPosition::new(16, 32),
9104            }
9105        );
9106
9107        let device = normalizer
9108            .normalize(PaneInputCoordinate::DevicePixels {
9109                position: PanePointerPosition::new(232, 164),
9110            })
9111            .expect("device normalization should match css");
9112        assert_eq!(device, css);
9113
9114        let cell = normalizer
9115            .normalize(PaneInputCoordinate::Cell {
9116                position: PanePointerPosition::new(3, 1),
9117            })
9118            .expect("cell normalization should succeed");
9119        assert_eq!(
9120            cell,
9121            PaneNormalizedCoordinate {
9122                global_cell: PanePointerPosition::new(23, 11),
9123                local_cell: PanePointerPosition::new(3, 1),
9124                local_css: PanePointerPosition::new(24, 16),
9125            }
9126        );
9127    }
9128
9129    #[test]
9130    fn coordinate_normalizer_zoom_and_rounding_tie_breaks_are_deterministic() {
9131        let zoomed = PaneCoordinateNormalizer::new(
9132            PanePointerPosition::new(100, 50),
9133            PanePointerPosition::new(0, 0),
9134            8,
9135            8,
9136            PaneScaleFactor::ONE,
9137            PaneScaleFactor::new(5, 4).expect("valid zoom"),
9138            PaneCoordinateRoundingPolicy::TowardNegativeInfinity,
9139        )
9140        .expect("zoomed normalizer should be valid");
9141
9142        let zoomed_point = zoomed
9143            .normalize(PaneInputCoordinate::CssPixels {
9144                position: PanePointerPosition::new(120, 70),
9145            })
9146            .expect("zoomed normalization should succeed");
9147        assert_eq!(zoomed_point.local_css, PanePointerPosition::new(16, 16));
9148        assert_eq!(zoomed_point.local_cell, PanePointerPosition::new(2, 2));
9149
9150        let nearest = PaneCoordinateNormalizer::new(
9151            PanePointerPosition::new(0, 0),
9152            PanePointerPosition::new(0, 0),
9153            10,
9154            10,
9155            PaneScaleFactor::ONE,
9156            PaneScaleFactor::ONE,
9157            PaneCoordinateRoundingPolicy::NearestHalfTowardNegativeInfinity,
9158        )
9159        .expect("nearest normalizer should be valid");
9160
9161        let positive_tie = nearest
9162            .normalize(PaneInputCoordinate::CssPixels {
9163                position: PanePointerPosition::new(15, 0),
9164            })
9165            .expect("positive tie should normalize");
9166        let positive_above_tie = nearest
9167            .normalize(PaneInputCoordinate::CssPixels {
9168                position: PanePointerPosition::new(16, 0),
9169            })
9170            .expect("positive > half should normalize");
9171        let negative_tie = nearest
9172            .normalize(PaneInputCoordinate::CssPixels {
9173                position: PanePointerPosition::new(-15, 0),
9174            })
9175            .expect("negative tie should normalize");
9176
9177        assert_eq!(positive_tie.local_cell.x, 1);
9178        assert_eq!(positive_above_tie.local_cell.x, 2);
9179        assert_eq!(negative_tie.local_cell.x, -2);
9180    }
9181
9182    #[test]
9183    fn coordinate_normalizer_rejects_invalid_configuration() {
9184        assert_eq!(
9185            PaneScaleFactor::new(0, 1).expect_err("zero numerator must fail"),
9186            PaneCoordinateNormalizationError::InvalidScaleFactor {
9187                field: "scale_factor",
9188                numerator: 0,
9189                denominator: 1,
9190            }
9191        );
9192
9193        let err = PaneCoordinateNormalizer::new(
9194            PanePointerPosition::new(0, 0),
9195            PanePointerPosition::new(0, 0),
9196            0,
9197            10,
9198            PaneScaleFactor::ONE,
9199            PaneScaleFactor::ONE,
9200            PaneCoordinateRoundingPolicy::TowardNegativeInfinity,
9201        )
9202        .expect_err("zero width must fail");
9203        assert_eq!(
9204            err,
9205            PaneCoordinateNormalizationError::InvalidCellSize {
9206                width: 0,
9207                height: 10,
9208            }
9209        );
9210    }
9211
9212    #[test]
9213    fn coordinate_normalizer_repeated_device_updates_do_not_drift() {
9214        let normalizer = PaneCoordinateNormalizer::new(
9215            PanePointerPosition::new(0, 0),
9216            PanePointerPosition::new(0, 0),
9217            7,
9218            11,
9219            PaneScaleFactor::new(3, 2).expect("valid dpr"),
9220            PaneScaleFactor::new(5, 4).expect("valid zoom"),
9221            PaneCoordinateRoundingPolicy::TowardNegativeInfinity,
9222        )
9223        .expect("normalizer should be valid");
9224
9225        let mut prev = i32::MIN;
9226        for x in 150..190 {
9227            let first = normalizer
9228                .normalize(PaneInputCoordinate::DevicePixels {
9229                    position: PanePointerPosition::new(x, 0),
9230                })
9231                .expect("first normalization should succeed");
9232            let second = normalizer
9233                .normalize(PaneInputCoordinate::DevicePixels {
9234                    position: PanePointerPosition::new(x, 0),
9235                })
9236                .expect("second normalization should succeed");
9237
9238            assert_eq!(
9239                first, second,
9240                "normalization should be stable for same input"
9241            );
9242            assert!(
9243                first.global_cell.x >= prev,
9244                "cell coordinate should be monotonic"
9245            );
9246            if prev != i32::MIN {
9247                assert!(
9248                    first.global_cell.x - prev <= 1,
9249                    "cell coordinate should not jump by more than one per pixel step"
9250                );
9251            }
9252            prev = first.global_cell.x;
9253        }
9254    }
9255
9256    #[test]
9257    fn snap_tuning_is_deterministic_with_tie_breaks_and_hysteresis() {
9258        let tuning = PaneSnapTuning::default();
9259
9260        let tie = tuning.decide(3_250, None);
9261        assert_eq!(tie.nearest_ratio_bps, 3_000);
9262        assert_eq!(tie.snapped_ratio_bps, None);
9263        assert_eq!(tie.reason, PaneSnapReason::UnsnapOutsideWindow);
9264
9265        let snap = tuning.decide(3_499, None);
9266        assert_eq!(snap.nearest_ratio_bps, 3_500);
9267        assert_eq!(snap.snapped_ratio_bps, Some(3_500));
9268        assert_eq!(snap.reason, PaneSnapReason::SnappedNearest);
9269
9270        let retain = tuning.decide(3_390, Some(3_500));
9271        assert_eq!(retain.snapped_ratio_bps, Some(3_500));
9272        assert_eq!(retain.reason, PaneSnapReason::RetainedPrevious);
9273
9274        assert_eq!(
9275            PaneSnapTuning::new(0, 125).expect_err("step=0 must fail"),
9276            PaneInteractionPolicyError::InvalidSnapTuning {
9277                step_bps: 0,
9278                hysteresis_bps: 125
9279            }
9280        );
9281    }
9282
9283    #[test]
9284    fn precision_policy_applies_axis_lock_and_mode_scaling() {
9285        let fine = PanePrecisionPolicy::from_modifiers(
9286            PaneModifierSnapshot {
9287                shift: true,
9288                alt: true,
9289                ctrl: false,
9290                meta: false,
9291            },
9292            SplitAxis::Horizontal,
9293        );
9294        assert_eq!(fine.mode, PanePrecisionMode::Fine);
9295        assert_eq!(fine.axis_lock, Some(SplitAxis::Horizontal));
9296        assert_eq!(fine.apply_delta(5, 3).expect("fine delta"), (2, 0));
9297
9298        let coarse = PanePrecisionPolicy::from_modifiers(
9299            PaneModifierSnapshot {
9300                shift: false,
9301                alt: false,
9302                ctrl: true,
9303                meta: false,
9304            },
9305            SplitAxis::Vertical,
9306        );
9307        assert_eq!(coarse.mode, PanePrecisionMode::Coarse);
9308        assert_eq!(coarse.axis_lock, None);
9309        assert_eq!(coarse.apply_delta(2, -3).expect("coarse delta"), (4, -6));
9310    }
9311
9312    #[test]
9313    fn drag_behavior_tuning_validates_and_threshold_helpers_are_stable() {
9314        let tuning = PaneDragBehaviorTuning::new(3, 2, PaneSnapTuning::default())
9315            .expect("valid tuning should construct");
9316        assert!(tuning.should_start_drag(
9317            PanePointerPosition::new(0, 0),
9318            PanePointerPosition::new(3, 0)
9319        ));
9320        assert!(!tuning.should_start_drag(
9321            PanePointerPosition::new(0, 0),
9322            PanePointerPosition::new(2, 0)
9323        ));
9324        assert!(tuning.should_emit_drag_update(
9325            PanePointerPosition::new(10, 10),
9326            PanePointerPosition::new(12, 10)
9327        ));
9328        assert!(!tuning.should_emit_drag_update(
9329            PanePointerPosition::new(10, 10),
9330            PanePointerPosition::new(11, 10)
9331        ));
9332
9333        assert_eq!(
9334            PaneDragBehaviorTuning::new(0, 2, PaneSnapTuning::default())
9335                .expect_err("activation threshold=0 must fail"),
9336            PaneInteractionPolicyError::InvalidThreshold {
9337                field: "activation_threshold",
9338                value: 0
9339            }
9340        );
9341        assert_eq!(
9342            PaneDragBehaviorTuning::new(2, 0, PaneSnapTuning::default())
9343                .expect_err("hysteresis=0 must fail"),
9344            PaneInteractionPolicyError::InvalidThreshold {
9345                field: "update_hysteresis",
9346                value: 0
9347            }
9348        );
9349    }
9350
9351    fn pointer_down_event(
9352        sequence: u64,
9353        target: PaneResizeTarget,
9354        pointer_id: u32,
9355        x: i32,
9356        y: i32,
9357    ) -> PaneSemanticInputEvent {
9358        PaneSemanticInputEvent::new(
9359            sequence,
9360            PaneSemanticInputEventKind::PointerDown {
9361                target,
9362                pointer_id,
9363                button: PanePointerButton::Primary,
9364                position: PanePointerPosition::new(x, y),
9365            },
9366        )
9367    }
9368
9369    fn pointer_move_event(
9370        sequence: u64,
9371        target: PaneResizeTarget,
9372        pointer_id: u32,
9373        x: i32,
9374        y: i32,
9375    ) -> PaneSemanticInputEvent {
9376        PaneSemanticInputEvent::new(
9377            sequence,
9378            PaneSemanticInputEventKind::PointerMove {
9379                target,
9380                pointer_id,
9381                position: PanePointerPosition::new(x, y),
9382                delta_x: 0,
9383                delta_y: 0,
9384            },
9385        )
9386    }
9387
9388    fn pointer_up_event(
9389        sequence: u64,
9390        target: PaneResizeTarget,
9391        pointer_id: u32,
9392        x: i32,
9393        y: i32,
9394    ) -> PaneSemanticInputEvent {
9395        PaneSemanticInputEvent::new(
9396            sequence,
9397            PaneSemanticInputEventKind::PointerUp {
9398                target,
9399                pointer_id,
9400                button: PanePointerButton::Primary,
9401                position: PanePointerPosition::new(x, y),
9402            },
9403        )
9404    }
9405
9406    #[test]
9407    fn drag_resize_machine_full_lifecycle_commit() {
9408        let mut machine = PaneDragResizeMachine::default();
9409        let target = default_target();
9410
9411        let down = machine
9412            .apply_event(&pointer_down_event(1, target, 10, 10, 4))
9413            .expect("down should arm");
9414        assert_eq!(down.transition_id, 1);
9415        assert_eq!(down.sequence, 1);
9416        assert_eq!(machine.state(), down.to);
9417        assert!(matches!(
9418            down.effect,
9419            PaneDragResizeEffect::Armed {
9420                target: t,
9421                pointer_id: 10,
9422                origin: PanePointerPosition { x: 10, y: 4 }
9423            } if t == target
9424        ));
9425
9426        let below_threshold = machine
9427            .apply_event(&pointer_move_event(2, target, 10, 11, 4))
9428            .expect("small move should not start drag");
9429        assert_eq!(
9430            below_threshold.effect,
9431            PaneDragResizeEffect::Noop {
9432                reason: PaneDragResizeNoopReason::ThresholdNotReached
9433            }
9434        );
9435        assert!(matches!(machine.state(), PaneDragResizeState::Armed { .. }));
9436
9437        let drag_start = machine
9438            .apply_event(&pointer_move_event(3, target, 10, 13, 4))
9439            .expect("large move should start drag");
9440        assert!(matches!(
9441            drag_start.effect,
9442            PaneDragResizeEffect::DragStarted {
9443                target: t,
9444                pointer_id: 10,
9445                total_delta_x: 3,
9446                total_delta_y: 0,
9447                ..
9448            } if t == target
9449        ));
9450        assert!(matches!(
9451            machine.state(),
9452            PaneDragResizeState::Dragging { .. }
9453        ));
9454
9455        let drag_update = machine
9456            .apply_event(&pointer_move_event(4, target, 10, 15, 6))
9457            .expect("drag move should update");
9458        assert!(matches!(
9459            drag_update.effect,
9460            PaneDragResizeEffect::DragUpdated {
9461                target: t,
9462                pointer_id: 10,
9463                delta_x: 2,
9464                delta_y: 2,
9465                total_delta_x: 5,
9466                total_delta_y: 2,
9467                ..
9468            } if t == target
9469        ));
9470
9471        let commit = machine
9472            .apply_event(&pointer_up_event(5, target, 10, 16, 6))
9473            .expect("up should commit drag");
9474        assert!(matches!(
9475            commit.effect,
9476            PaneDragResizeEffect::Committed {
9477                target: t,
9478                pointer_id: 10,
9479                total_delta_x: 6,
9480                total_delta_y: 2,
9481                ..
9482            } if t == target
9483        ));
9484        assert_eq!(machine.state(), PaneDragResizeState::Idle);
9485    }
9486
9487    #[test]
9488    fn drag_resize_machine_cancel_and_blur_paths_are_reason_coded() {
9489        let target = default_target();
9490
9491        let mut cancel_machine = PaneDragResizeMachine::default();
9492        cancel_machine
9493            .apply_event(&pointer_down_event(1, target, 1, 2, 2))
9494            .expect("down should arm");
9495        let cancel = cancel_machine
9496            .apply_event(&PaneSemanticInputEvent::new(
9497                2,
9498                PaneSemanticInputEventKind::Cancel {
9499                    target: Some(target),
9500                    reason: PaneCancelReason::FocusLost,
9501                },
9502            ))
9503            .expect("cancel should reset to idle");
9504        assert_eq!(cancel_machine.state(), PaneDragResizeState::Idle);
9505        assert_eq!(
9506            cancel.effect,
9507            PaneDragResizeEffect::Canceled {
9508                target: Some(target),
9509                pointer_id: Some(1),
9510                reason: PaneCancelReason::FocusLost
9511            }
9512        );
9513
9514        let mut blur_machine = PaneDragResizeMachine::default();
9515        blur_machine
9516            .apply_event(&pointer_down_event(3, target, 2, 5, 5))
9517            .expect("down should arm");
9518        blur_machine
9519            .apply_event(&pointer_move_event(4, target, 2, 8, 5))
9520            .expect("move should start dragging");
9521        let blur = blur_machine
9522            .apply_event(&PaneSemanticInputEvent::new(
9523                5,
9524                PaneSemanticInputEventKind::Blur {
9525                    target: Some(target),
9526                },
9527            ))
9528            .expect("blur should cancel active drag");
9529        assert_eq!(blur_machine.state(), PaneDragResizeState::Idle);
9530        assert_eq!(
9531            blur.effect,
9532            PaneDragResizeEffect::Canceled {
9533                target: Some(target),
9534                pointer_id: Some(2),
9535                reason: PaneCancelReason::Blur
9536            }
9537        );
9538    }
9539
9540    #[test]
9541    fn drag_resize_machine_duplicate_end_and_pointer_mismatch_are_safe_noops() {
9542        let mut machine = PaneDragResizeMachine::default();
9543        let target = default_target();
9544
9545        machine
9546            .apply_event(&pointer_down_event(1, target, 9, 0, 0))
9547            .expect("down should arm");
9548
9549        let mismatch = machine
9550            .apply_event(&pointer_move_event(2, target, 99, 3, 0))
9551            .expect("mismatch should be ignored");
9552        assert_eq!(
9553            mismatch.effect,
9554            PaneDragResizeEffect::Noop {
9555                reason: PaneDragResizeNoopReason::PointerMismatch
9556            }
9557        );
9558        assert!(matches!(machine.state(), PaneDragResizeState::Armed { .. }));
9559
9560        machine
9561            .apply_event(&pointer_move_event(3, target, 9, 3, 0))
9562            .expect("drag should start");
9563        machine
9564            .apply_event(&pointer_up_event(4, target, 9, 3, 0))
9565            .expect("up should commit");
9566        assert_eq!(machine.state(), PaneDragResizeState::Idle);
9567
9568        let duplicate_end = machine
9569            .apply_event(&pointer_up_event(5, target, 9, 3, 0))
9570            .expect("duplicate end should noop");
9571        assert_eq!(
9572            duplicate_end.effect,
9573            PaneDragResizeEffect::Noop {
9574                reason: PaneDragResizeNoopReason::IdleWithoutActiveDrag
9575            }
9576        );
9577    }
9578
9579    #[test]
9580    fn drag_resize_machine_discrete_inputs_in_idle_and_validation_errors() {
9581        let mut machine = PaneDragResizeMachine::default();
9582        let target = default_target();
9583
9584        let keyboard = machine
9585            .apply_event(&PaneSemanticInputEvent::new(
9586                1,
9587                PaneSemanticInputEventKind::KeyboardResize {
9588                    target,
9589                    direction: PaneResizeDirection::Increase,
9590                    units: 2,
9591                },
9592            ))
9593            .expect("keyboard resize should apply in idle");
9594        assert_eq!(
9595            keyboard.effect,
9596            PaneDragResizeEffect::KeyboardApplied {
9597                target,
9598                direction: PaneResizeDirection::Increase,
9599                units: 2
9600            }
9601        );
9602        assert_eq!(machine.state(), PaneDragResizeState::Idle);
9603
9604        let wheel = machine
9605            .apply_event(&PaneSemanticInputEvent::new(
9606                2,
9607                PaneSemanticInputEventKind::WheelNudge { target, lines: -1 },
9608            ))
9609            .expect("wheel nudge should apply in idle");
9610        assert_eq!(
9611            wheel.effect,
9612            PaneDragResizeEffect::WheelApplied { target, lines: -1 }
9613        );
9614
9615        let invalid_pointer = PaneSemanticInputEvent::new(
9616            3,
9617            PaneSemanticInputEventKind::PointerDown {
9618                target,
9619                pointer_id: 0,
9620                button: PanePointerButton::Primary,
9621                position: PanePointerPosition::new(0, 0),
9622            },
9623        );
9624        let err = machine
9625            .apply_event(&invalid_pointer)
9626            .expect_err("invalid input should be rejected");
9627        assert_eq!(
9628            err,
9629            PaneDragResizeMachineError::InvalidEvent(PaneSemanticInputEventError::ZeroPointerId)
9630        );
9631
9632        assert_eq!(
9633            PaneDragResizeMachine::new(0).expect_err("zero threshold should fail"),
9634            PaneDragResizeMachineError::InvalidDragThreshold { threshold: 0 }
9635        );
9636    }
9637
9638    #[test]
9639    fn drag_resize_machine_hysteresis_suppresses_micro_jitter() {
9640        let target = default_target();
9641        let mut machine = PaneDragResizeMachine::new_with_hysteresis(2, 2)
9642            .expect("explicit machine tuning should construct");
9643        machine
9644            .apply_event(&pointer_down_event(1, target, 22, 0, 0))
9645            .expect("down should arm");
9646        machine
9647            .apply_event(&pointer_move_event(2, target, 22, 2, 0))
9648            .expect("move should start dragging");
9649
9650        let jitter = machine
9651            .apply_event(&pointer_move_event(3, target, 22, 3, 0))
9652            .expect("small move should be ignored");
9653        assert_eq!(
9654            jitter.effect,
9655            PaneDragResizeEffect::Noop {
9656                reason: PaneDragResizeNoopReason::BelowHysteresis
9657            }
9658        );
9659
9660        let update = machine
9661            .apply_event(&pointer_move_event(4, target, 22, 4, 0))
9662            .expect("larger move should update drag");
9663        assert!(matches!(
9664            update.effect,
9665            PaneDragResizeEffect::DragUpdated { .. }
9666        ));
9667        assert_eq!(
9668            PaneDragResizeMachine::new_with_hysteresis(2, 0)
9669                .expect_err("zero hysteresis must fail"),
9670            PaneDragResizeMachineError::InvalidUpdateHysteresis { hysteresis: 0 }
9671        );
9672    }
9673
9674    // -----------------------------------------------------------------------
9675    // force_cancel lifecycle robustness (bd-24v9m)
9676    // -----------------------------------------------------------------------
9677
9678    #[test]
9679    fn force_cancel_idle_is_noop() {
9680        let mut machine = PaneDragResizeMachine::default();
9681        assert!(!machine.is_active());
9682        assert!(machine.force_cancel().is_none());
9683        assert_eq!(machine.state(), PaneDragResizeState::Idle);
9684    }
9685
9686    #[test]
9687    fn force_cancel_from_armed_resets_to_idle() {
9688        let target = default_target();
9689        let mut machine = PaneDragResizeMachine::default();
9690        machine
9691            .apply_event(&pointer_down_event(1, target, 22, 5, 5))
9692            .expect("down should arm");
9693        assert!(machine.is_active());
9694
9695        let transition = machine
9696            .force_cancel()
9697            .expect("armed machine should produce transition");
9698        assert_eq!(transition.to, PaneDragResizeState::Idle);
9699        assert!(matches!(
9700            transition.effect,
9701            PaneDragResizeEffect::Canceled {
9702                reason: PaneCancelReason::Programmatic,
9703                ..
9704            }
9705        ));
9706        assert!(!machine.is_active());
9707        assert_eq!(machine.state(), PaneDragResizeState::Idle);
9708    }
9709
9710    #[test]
9711    fn force_cancel_from_dragging_resets_to_idle() {
9712        let target = default_target();
9713        let mut machine = PaneDragResizeMachine::default();
9714        machine
9715            .apply_event(&pointer_down_event(1, target, 22, 0, 0))
9716            .expect("down");
9717        machine
9718            .apply_event(&pointer_move_event(2, target, 22, 5, 0))
9719            .expect("move past threshold to start drag");
9720        assert!(matches!(
9721            machine.state(),
9722            PaneDragResizeState::Dragging { .. }
9723        ));
9724        assert!(machine.is_active());
9725
9726        let transition = machine
9727            .force_cancel()
9728            .expect("dragging machine should produce transition");
9729        assert_eq!(transition.to, PaneDragResizeState::Idle);
9730        assert!(matches!(
9731            transition.effect,
9732            PaneDragResizeEffect::Canceled {
9733                target: Some(_),
9734                pointer_id: Some(22),
9735                reason: PaneCancelReason::Programmatic,
9736            }
9737        ));
9738        assert!(!machine.is_active());
9739    }
9740
9741    #[test]
9742    fn force_cancel_is_idempotent() {
9743        let target = default_target();
9744        let mut machine = PaneDragResizeMachine::default();
9745        machine
9746            .apply_event(&pointer_down_event(1, target, 22, 5, 5))
9747            .expect("down should arm");
9748
9749        let first = machine.force_cancel();
9750        assert!(first.is_some());
9751        let second = machine.force_cancel();
9752        assert!(second.is_none());
9753        assert_eq!(machine.state(), PaneDragResizeState::Idle);
9754    }
9755
9756    #[test]
9757    fn force_cancel_preserves_transition_counter_monotonicity() {
9758        let target = default_target();
9759        let mut machine = PaneDragResizeMachine::default();
9760
9761        let t1 = machine
9762            .apply_event(&pointer_down_event(1, target, 22, 0, 0))
9763            .expect("arm");
9764        let t2 = machine.force_cancel().expect("force cancel from armed");
9765        assert!(t2.transition_id > t1.transition_id);
9766
9767        // Re-arm and force cancel again to confirm counter keeps incrementing
9768        let t3 = machine
9769            .apply_event(&pointer_down_event(2, target, 22, 10, 10))
9770            .expect("re-arm");
9771        let t4 = machine.force_cancel().expect("second force cancel");
9772        assert!(t3.transition_id > t2.transition_id);
9773        assert!(t4.transition_id > t3.transition_id);
9774    }
9775
9776    #[test]
9777    fn force_cancel_records_prior_state_in_from_field() {
9778        let target = default_target();
9779        let mut machine = PaneDragResizeMachine::default();
9780        machine
9781            .apply_event(&pointer_down_event(1, target, 22, 0, 0))
9782            .expect("arm");
9783
9784        let armed_state = machine.state();
9785        let transition = machine.force_cancel().expect("force cancel");
9786        assert_eq!(transition.from, armed_state);
9787    }
9788
9789    #[test]
9790    fn machine_usable_after_force_cancel() {
9791        let target = default_target();
9792        let mut machine = PaneDragResizeMachine::default();
9793
9794        // Full lifecycle: arm → force cancel → arm again → normal commit
9795        machine
9796            .apply_event(&pointer_down_event(1, target, 22, 0, 0))
9797            .expect("arm");
9798        machine.force_cancel();
9799
9800        machine
9801            .apply_event(&pointer_down_event(2, target, 22, 10, 10))
9802            .expect("re-arm after force cancel");
9803        machine
9804            .apply_event(&pointer_move_event(3, target, 22, 15, 10))
9805            .expect("move to drag");
9806        let commit = machine
9807            .apply_event(&pointer_up_event(4, target, 22, 15, 10))
9808            .expect("commit");
9809        assert!(matches!(
9810            commit.effect,
9811            PaneDragResizeEffect::Committed { .. }
9812        ));
9813        assert_eq!(machine.state(), PaneDragResizeState::Idle);
9814    }
9815
9816    proptest! {
9817        #[test]
9818        fn ratio_is_always_reduced(numerator in 1u32..100_000, denominator in 1u32..100_000) {
9819            let ratio = PaneSplitRatio::new(numerator, denominator).expect("positive ratio must be valid");
9820            let gcd = gcd_u32(ratio.numerator(), ratio.denominator());
9821            prop_assert_eq!(gcd, 1);
9822        }
9823
9824        #[test]
9825        fn allocator_produces_monotonic_ids(
9826            start in 1u64..1_000_000,
9827            count in 1usize..64,
9828        ) {
9829            let mut allocator = PaneIdAllocator::with_next(PaneId::new(start).expect("start must be valid"));
9830            let mut prev = 0u64;
9831            for _ in 0..count {
9832                let current = allocator.allocate().expect("allocation must succeed").get();
9833                prop_assert!(current > prev);
9834                prev = current;
9835            }
9836        }
9837
9838        #[test]
9839        fn split_solver_preserves_available_space(
9840            numerator in 1u32..64,
9841            denominator in 1u32..64,
9842            first_min in 0u16..40,
9843            second_min in 0u16..40,
9844            available in 0u16..80,
9845        ) {
9846            let ratio = PaneSplitRatio::new(numerator, denominator).expect("ratio must be valid");
9847            prop_assume!(first_min.saturating_add(second_min) <= available);
9848
9849            let (first_size, second_size) = solve_split_sizes(
9850                id(1),
9851                SplitAxis::Horizontal,
9852                available,
9853                ratio,
9854                AxisBounds { min: first_min, max: None },
9855                AxisBounds { min: second_min, max: None },
9856            ).expect("feasible split should solve");
9857
9858            prop_assert_eq!(first_size.saturating_add(second_size), available);
9859            prop_assert!(first_size >= first_min);
9860            prop_assert!(second_size >= second_min);
9861        }
9862
9863        #[test]
9864        fn split_then_close_round_trip_preserves_validity(
9865            numerator in 1u32..32,
9866            denominator in 1u32..32,
9867            incoming_first in any::<bool>(),
9868        ) {
9869            let mut tree = PaneTree::singleton("root");
9870            let placement = if incoming_first {
9871                PanePlacement::IncomingFirst
9872            } else {
9873                PanePlacement::ExistingFirst
9874            };
9875            let ratio = PaneSplitRatio::new(numerator, denominator).expect("ratio must be valid");
9876
9877            tree.apply_operation(
9878                1,
9879                PaneOperation::SplitLeaf {
9880                    target: id(1),
9881                    axis: SplitAxis::Horizontal,
9882                    ratio,
9883                    placement,
9884                    new_leaf: PaneLeaf::new("extra"),
9885                },
9886            ).expect("split should succeed");
9887
9888            let split_root_id = tree.root();
9889            let split_root = tree.node(split_root_id).expect("split root exists");
9890            let PaneNodeKind::Split(split) = &split_root.kind else {
9891                unreachable!("root should be split");
9892            };
9893            let extra_leaf_id = if split.first == id(1) {
9894                split.second
9895            } else {
9896                split.first
9897            };
9898
9899            tree.apply_operation(2, PaneOperation::CloseNode { target: extra_leaf_id })
9900                .expect("close should succeed");
9901
9902            prop_assert_eq!(tree.root(), id(1));
9903            prop_assert!(matches!(
9904                tree.node(id(1)).map(|node| &node.kind),
9905                Some(PaneNodeKind::Leaf(_))
9906            ));
9907            prop_assert!(tree.validate().is_ok());
9908        }
9909
9910        #[test]
9911        fn transaction_rollback_restores_initial_state_hash(
9912            numerator in 1u32..64,
9913            denominator in 1u32..64,
9914            incoming_first in any::<bool>(),
9915        ) {
9916            let base = PaneTree::singleton("root");
9917            let initial_hash = base.state_hash();
9918            let mut tx = base.begin_transaction(90);
9919            let placement = if incoming_first {
9920                PanePlacement::IncomingFirst
9921            } else {
9922                PanePlacement::ExistingFirst
9923            };
9924
9925            tx.apply_operation(
9926                1,
9927                PaneOperation::SplitLeaf {
9928                    target: id(1),
9929                    axis: SplitAxis::Horizontal,
9930                    ratio: PaneSplitRatio::new(numerator, denominator).expect("valid ratio"),
9931                    placement,
9932                    new_leaf: PaneLeaf::new("new"),
9933                },
9934            ).expect("split should succeed");
9935
9936            let rolled_back = tx.rollback();
9937            prop_assert_eq!(rolled_back.tree.state_hash(), initial_hash);
9938            prop_assert_eq!(rolled_back.tree.root(), id(1));
9939            prop_assert!(rolled_back.tree.validate().is_ok());
9940        }
9941
9942        #[test]
9943        fn repair_safe_is_deterministic_under_recoverable_damage(
9944            numerator in 1u32..32,
9945            denominator in 1u32..32,
9946            add_orphan in any::<bool>(),
9947            mismatch_parent in any::<bool>(),
9948        ) {
9949            let mut snapshot = make_valid_snapshot();
9950            for node in &mut snapshot.nodes {
9951                if node.id == id(1) {
9952                    let PaneNodeKind::Split(split) = &mut node.kind else {
9953                        unreachable!("root should be split");
9954                    };
9955                    split.ratio = PaneSplitRatio {
9956                        numerator: numerator.saturating_mul(2),
9957                        denominator: denominator.saturating_mul(2),
9958                    };
9959                }
9960                if mismatch_parent && node.id == id(2) {
9961                    node.parent = Some(id(3));
9962                }
9963            }
9964            if add_orphan {
9965                snapshot
9966                    .nodes
9967                    .push(PaneNodeRecord::leaf(id(10), None, PaneLeaf::new("orphan")));
9968                snapshot.next_id = id(11);
9969            }
9970
9971            let first = snapshot.clone().repair_safe().expect("first repair should succeed");
9972            let second = snapshot.repair_safe().expect("second repair should succeed");
9973
9974            prop_assert_eq!(first.tree.state_hash(), second.tree.state_hash());
9975            prop_assert_eq!(first.actions, second.actions);
9976            prop_assert_eq!(first.report_after, second.report_after);
9977        }
9978    }
9979
9980    #[test]
9981    fn set_split_ratio_operation_updates_existing_split() {
9982        let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
9983        tree.apply_operation(
9984            900,
9985            PaneOperation::SetSplitRatio {
9986                split: id(1),
9987                ratio: PaneSplitRatio::new(5, 3).expect("valid ratio"),
9988            },
9989        )
9990        .expect("set split ratio should succeed");
9991
9992        let root = tree.node(id(1)).expect("root exists");
9993        let PaneNodeKind::Split(split) = &root.kind else {
9994            unreachable!("root should be split");
9995        };
9996        assert_eq!(split.ratio.numerator(), 5);
9997        assert_eq!(split.ratio.denominator(), 3);
9998    }
9999
10000    #[test]
10001    fn layout_classifies_any_edge_grips_and_edge_resize_plans_apply() {
10002        let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10003        let layout = tree
10004            .solve_layout(Rect::new(0, 0, 120, 48))
10005            .expect("layout should solve");
10006        let left_rect = layout.rect(id(2)).expect("leaf 2 rect");
10007        let pointer = PanePointerPosition::new(
10008            i32::from(
10009                left_rect
10010                    .x
10011                    .saturating_add(left_rect.width.saturating_sub(1)),
10012            ),
10013            i32::from(left_rect.y.saturating_add(left_rect.height / 2)),
10014        );
10015        let grip = layout
10016            .classify_resize_grip(id(2), pointer, PANE_EDGE_GRIP_INSET_CELLS)
10017            .expect("grip should classify");
10018        assert!(matches!(
10019            grip,
10020            PaneResizeGrip::Right | PaneResizeGrip::TopRight | PaneResizeGrip::BottomRight
10021        ));
10022
10023        let plan = tree
10024            .plan_edge_resize(
10025                id(2),
10026                &layout,
10027                grip,
10028                pointer,
10029                PanePressureSnapProfile {
10030                    strength_bps: 8_000,
10031                    hysteresis_bps: 250,
10032                },
10033            )
10034            .expect("edge resize plan should build");
10035        assert!(!plan.operations.is_empty());
10036        tree.apply_edge_resize_plan(901, &plan)
10037            .expect("edge resize plan should apply");
10038        assert!(tree.validate().is_ok());
10039    }
10040
10041    #[test]
10042    fn pane_layout_visual_rect_applies_default_margin_and_padding() {
10043        let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10044        let layout = tree
10045            .solve_layout(Rect::new(0, 0, 120, 48))
10046            .expect("layout should solve");
10047        let raw = layout.rect(id(2)).expect("leaf rect exists");
10048        let visual = layout.visual_rect(id(2)).expect("visual rect exists");
10049        assert!(visual.width <= raw.width);
10050        assert!(visual.height <= raw.height);
10051        assert!(visual.width > 0);
10052        assert!(visual.height > 0);
10053    }
10054
10055    #[test]
10056    fn magnetic_docking_preview_and_reflow_plan_are_generated() {
10057        let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10058        let layout = tree
10059            .solve_layout(Rect::new(0, 0, 100, 40))
10060            .expect("layout should solve");
10061        let right_rect = layout.rect(id(3)).expect("leaf 3 rect");
10062        let pointer = PanePointerPosition::new(
10063            i32::from(right_rect.x),
10064            i32::from(right_rect.y.saturating_add(right_rect.height / 2)),
10065        );
10066        let preview = tree
10067            .choose_dock_preview(&layout, pointer, PANE_MAGNETIC_FIELD_CELLS)
10068            .expect("magnetic preview should exist");
10069        assert!(preview.score > 0.0);
10070
10071        let plan = tree
10072            .plan_reflow_move_with_preview(
10073                id(2),
10074                &layout,
10075                pointer,
10076                PaneMotionVector::from_delta(24, 0, 48, 0),
10077                Some(PaneInertialThrow::from_motion(
10078                    PaneMotionVector::from_delta(24, 0, 48, 0),
10079                )),
10080                PANE_MAGNETIC_FIELD_CELLS,
10081            )
10082            .expect("reflow plan should build");
10083        assert!(!plan.operations.is_empty());
10084    }
10085
10086    #[test]
10087    fn group_move_and_group_resize_plan_generation() {
10088        let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10089        let layout = tree
10090            .solve_layout(Rect::new(0, 0, 100, 40))
10091            .expect("layout should solve");
10092        let mut selection = PaneSelectionState::default();
10093        selection.shift_toggle(id(2));
10094        assert_eq!(selection.selected.len(), 1);
10095
10096        let move_plan = tree
10097            .plan_group_move(
10098                &selection,
10099                &layout,
10100                PanePointerPosition::new(80, 4),
10101                PaneMotionVector::from_delta(30, 2, 64, 1),
10102                None,
10103                PANE_MAGNETIC_FIELD_CELLS,
10104            )
10105            .expect("group move plan should build");
10106        assert!(!move_plan.operations.is_empty());
10107
10108        let resize_plan = tree
10109            .plan_group_resize(
10110                &selection,
10111                &layout,
10112                PaneResizeGrip::Right,
10113                PanePointerPosition::new(70, 20),
10114                PanePressureSnapProfile::from_motion(PaneMotionVector::from_delta(40, 1, 32, 0)),
10115            )
10116            .expect("group resize plan should build");
10117        assert!(!resize_plan.operations.is_empty());
10118    }
10119
10120    #[test]
10121    fn classify_resize_grip_handles_small_panes() {
10122        // 1x1 pane at (10, 10)
10123        let rect = Rect::new(10, 10, 1, 1);
10124        let pointer = PanePointerPosition::new(10, 10);
10125        let grip = classify_resize_grip(rect, pointer, 1.5).expect("should classify");
10126        // Tie-break prefers BottomRight (Right/Bottom)
10127        assert_eq!(grip, PaneResizeGrip::BottomRight);
10128
10129        // 2x1 pane at (10, 10)
10130        let rect2 = Rect::new(10, 10, 2, 1);
10131        // Left pixel (10, 10)
10132        let ptr_left = PanePointerPosition::new(10, 10);
10133        let grip_left = classify_resize_grip(rect2, ptr_left, 1.5).expect("left pixel");
10134        assert_eq!(grip_left, PaneResizeGrip::BottomLeft);
10135
10136        // Right pixel (11, 10)
10137        let ptr_right = PanePointerPosition::new(11, 10);
10138        let grip_right = classify_resize_grip(rect2, ptr_right, 1.5).expect("right pixel");
10139        assert_eq!(grip_right, PaneResizeGrip::BottomRight);
10140    }
10141
10142    #[test]
10143    fn pressure_sensitive_snap_prefers_fast_straight_drags() {
10144        let slow = PanePressureSnapProfile::from_motion(PaneMotionVector::from_delta(4, 1, 300, 3));
10145        let fast = PanePressureSnapProfile::from_motion(PaneMotionVector::from_delta(40, 2, 48, 0));
10146        assert!(fast.strength_bps > slow.strength_bps);
10147        assert!(fast.hysteresis_bps >= slow.hysteresis_bps);
10148    }
10149
10150    #[test]
10151    fn pressure_sensitive_snap_penalizes_direction_noise() {
10152        let stable =
10153            PanePressureSnapProfile::from_motion(PaneMotionVector::from_delta(32, 2, 60, 0));
10154        let noisy =
10155            PanePressureSnapProfile::from_motion(PaneMotionVector::from_delta(32, 2, 60, 7));
10156        assert!(stable.strength_bps > noisy.strength_bps);
10157    }
10158
10159    #[test]
10160    fn dock_zone_motion_intent_prefers_directionally_aligned_zones() {
10161        let rightward = PaneMotionVector::from_delta(36, 2, 50, 0);
10162        let left_bias = dock_zone_motion_intent(PaneDockZone::Left, rightward);
10163        let right_bias = dock_zone_motion_intent(PaneDockZone::Right, rightward);
10164        assert!(right_bias > left_bias);
10165
10166        let downward = PaneMotionVector::from_delta(2, 32, 52, 0);
10167        let top_bias = dock_zone_motion_intent(PaneDockZone::Top, downward);
10168        let bottom_bias = dock_zone_motion_intent(PaneDockZone::Bottom, downward);
10169        assert!(bottom_bias > top_bias);
10170    }
10171
10172    #[test]
10173    fn dock_zone_motion_intent_noise_reduces_alignment_confidence() {
10174        let stable = dock_zone_motion_intent(
10175            PaneDockZone::Right,
10176            PaneMotionVector::from_delta(40, 1, 45, 0),
10177        );
10178        let noisy = dock_zone_motion_intent(
10179            PaneDockZone::Right,
10180            PaneMotionVector::from_delta(40, 1, 45, 8),
10181        );
10182        assert!(stable > noisy);
10183    }
10184
10185    #[test]
10186    fn elastic_ratio_bps_resists_extreme_edges_more_at_low_confidence() {
10187        let near_edge = 350;
10188        let low_confidence = elastic_ratio_bps(
10189            near_edge,
10190            PanePressureSnapProfile {
10191                strength_bps: 1_800,
10192                hysteresis_bps: 120,
10193            },
10194        );
10195        let high_confidence = elastic_ratio_bps(
10196            near_edge,
10197            PanePressureSnapProfile {
10198                strength_bps: 8_600,
10199                hysteresis_bps: 520,
10200            },
10201        );
10202        assert!(low_confidence > near_edge);
10203        assert!(high_confidence <= low_confidence);
10204    }
10205
10206    #[test]
10207    fn ranked_dock_previews_with_motion_returns_descending_scores() {
10208        let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10209        let layout = tree
10210            .solve_layout(Rect::new(0, 0, 100, 40))
10211            .expect("layout should solve");
10212        let right_rect = layout.rect(id(3)).expect("leaf 3 rect");
10213        let pointer = PanePointerPosition::new(
10214            i32::from(right_rect.x),
10215            i32::from(right_rect.y.saturating_add(right_rect.height / 2)),
10216        );
10217        let ranked = tree.ranked_dock_previews_with_motion(
10218            &layout,
10219            pointer,
10220            PaneMotionVector::from_delta(28, 2, 48, 0),
10221            PANE_MAGNETIC_FIELD_CELLS,
10222            Some(id(2)),
10223            3,
10224        );
10225        assert!(!ranked.is_empty());
10226        for pair in ranked.windows(2) {
10227            assert!(pair[0].score >= pair[1].score);
10228        }
10229    }
10230
10231    #[test]
10232    fn inertial_throw_projects_farther_for_faster_motion() {
10233        let start = PanePointerPosition::new(40, 12);
10234        let slow = PaneInertialThrow::from_motion(PaneMotionVector::from_delta(6, 0, 220, 1))
10235            .projected_pointer(start);
10236        let fast = PaneInertialThrow::from_motion(PaneMotionVector::from_delta(42, 0, 40, 0))
10237            .projected_pointer(start);
10238        assert!(fast.x > slow.x);
10239    }
10240
10241    #[test]
10242    fn affordance_hover_emphasis_ramps_monotonically_to_full() {
10243        let motion = PaneAffordanceMotion::default();
10244        let mut prev = 0u16;
10245        for frame in 0..=motion.fade_in_frames {
10246            let bps = motion.hover_emphasis_bps(frame);
10247            assert!(bps >= prev, "ramp must be monotonic non-decreasing");
10248            assert!(bps <= PANE_AFFORDANCE_EMPHASIS_FULL_BPS);
10249            prev = bps;
10250        }
10251        // Reaches full at the end and saturates beyond it.
10252        assert_eq!(
10253            motion.hover_emphasis_bps(motion.fade_in_frames),
10254            PANE_AFFORDANCE_EMPHASIS_FULL_BPS
10255        );
10256        assert_eq!(
10257            motion.hover_emphasis_bps(motion.fade_in_frames + 50),
10258            PANE_AFFORDANCE_EMPHASIS_FULL_BPS
10259        );
10260        // Ease-out: more progress is made in the first half than the second.
10261        let half = motion.fade_in_frames / 2;
10262        let first_half_gain = motion.hover_emphasis_bps(half);
10263        let second_half_gain = PANE_AFFORDANCE_EMPHASIS_FULL_BPS - first_half_gain;
10264        assert!(
10265            first_half_gain >= second_half_gain,
10266            "ease-out should front-load the ramp ({first_half_gain} vs {second_half_gain})"
10267        );
10268    }
10269
10270    #[test]
10271    fn affordance_reduced_motion_steps_instantly_without_losing_the_cue() {
10272        let reduced = PaneAffordanceMotion::reduced();
10273        assert!(reduced.reduced_motion);
10274        // Hover: full emphasis on the very first frame — the state change is
10275        // still expressed, just without an in-between ramp.
10276        assert_eq!(
10277            reduced.hover_emphasis_bps(0),
10278            PANE_AFFORDANCE_EMPHASIS_FULL_BPS
10279        );
10280        // Active pulse: steady full emphasis at every phase (no oscillation).
10281        for phase in [0u64, 1, 12, 24, 47, 1_000_000] {
10282            assert_eq!(
10283                reduced.active_pulse_bps(phase),
10284                PANE_AFFORDANCE_EMPHASIS_FULL_BPS
10285            );
10286        }
10287        // with_reduced_motion derives the same stepped behavior from a flag.
10288        let derived = PaneAffordanceMotion::default().with_reduced_motion(true);
10289        assert_eq!(derived.hover_emphasis_bps(0), reduced.hover_emphasis_bps(0));
10290    }
10291
10292    #[test]
10293    fn affordance_active_pulse_oscillates_within_bounds_and_is_periodic() {
10294        let motion = PaneAffordanceMotion::default();
10295        let period = u64::from(motion.pulse_period_frames);
10296        let mut min = u16::MAX;
10297        let mut max = 0u16;
10298        for phase in 0..period {
10299            let bps = motion.active_pulse_bps(phase);
10300            assert!(bps >= motion.pulse_floor_bps, "never below the floor");
10301            assert!(bps <= PANE_AFFORDANCE_EMPHASIS_FULL_BPS, "never above full");
10302            min = min.min(bps);
10303            max = max.max(bps);
10304            // Periodicity: phase and phase+period agree.
10305            assert_eq!(bps, motion.active_pulse_bps(phase + period));
10306            assert_eq!(bps, motion.active_pulse_bps(phase + 5 * period));
10307        }
10308        assert_eq!(min, motion.pulse_floor_bps, "trough sits at the floor");
10309        assert_eq!(max, PANE_AFFORDANCE_EMPHASIS_FULL_BPS, "peak reaches full");
10310        // Peak is at the midpoint of the period.
10311        assert_eq!(
10312            motion.active_pulse_bps(u64::from(motion.pulse_period_frames / 2)),
10313            PANE_AFFORDANCE_EMPHASIS_FULL_BPS
10314        );
10315    }
10316
10317    #[test]
10318    fn affordance_motion_is_deterministic_and_clock_free() {
10319        let motion = PaneAffordanceMotion::default();
10320        // Two independent evaluations of the same phase agree exactly — the
10321        // policy reads only the supplied tick, never a wall clock.
10322        for frame in 0..200u64 {
10323            assert_eq!(
10324                motion.active_pulse_bps(frame),
10325                motion.active_pulse_bps(frame)
10326            );
10327        }
10328        for frame in 0..50u16 {
10329            assert_eq!(
10330                motion.hover_emphasis_bps(frame),
10331                motion.hover_emphasis_bps(frame)
10332            );
10333        }
10334    }
10335
10336    #[test]
10337    fn affordance_zero_timing_fields_degrade_to_full() {
10338        let instant = PaneAffordanceMotion {
10339            fade_in_frames: 0,
10340            pulse_period_frames: 0,
10341            ..PaneAffordanceMotion::default()
10342        };
10343        assert_eq!(
10344            instant.hover_emphasis_bps(0),
10345            PANE_AFFORDANCE_EMPHASIS_FULL_BPS
10346        );
10347        assert_eq!(
10348            instant.active_pulse_bps(7),
10349            PANE_AFFORDANCE_EMPHASIS_FULL_BPS
10350        );
10351    }
10352
10353    #[test]
10354    fn intelligence_mode_compact_emits_ratio_normalization_ops() {
10355        let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10356        let ops = tree
10357            .plan_intelligence_mode(PaneLayoutIntelligenceMode::Compact, id(2))
10358            .expect("compact mode should plan");
10359        assert!(
10360            ops.iter()
10361                .any(|op| matches!(op, PaneOperation::NormalizeRatios))
10362        );
10363        assert!(
10364            ops.iter()
10365                .any(|op| matches!(op, PaneOperation::SetSplitRatio { .. }))
10366        );
10367    }
10368
10369    #[test]
10370    fn interaction_timeline_supports_undo_redo_and_replay() {
10371        let mut tree = PaneTree::singleton("root");
10372        let mut timeline = PaneInteractionTimeline::default();
10373
10374        timeline
10375            .apply_and_record(
10376                &mut tree,
10377                1,
10378                1000,
10379                PaneOperation::SplitLeaf {
10380                    target: id(1),
10381                    axis: SplitAxis::Horizontal,
10382                    ratio: PaneSplitRatio::new(1, 1).expect("valid ratio"),
10383                    placement: PanePlacement::ExistingFirst,
10384                    new_leaf: PaneLeaf::new("aux"),
10385                },
10386            )
10387            .expect("split should apply");
10388        let split_hash = tree.state_hash();
10389        assert_eq!(timeline.applied_len(), 1);
10390
10391        let undone = timeline.undo(&mut tree).expect("undo should succeed");
10392        assert!(undone);
10393        assert_eq!(tree.root(), id(1));
10394
10395        let redone = timeline.redo(&mut tree).expect("redo should succeed");
10396        assert!(redone);
10397        assert_eq!(tree.state_hash(), split_hash);
10398
10399        let replayed = timeline.replay().expect("replay should succeed");
10400        assert_eq!(replayed.state_hash(), tree.state_hash());
10401    }
10402
10403    #[test]
10404    fn interaction_timeline_replay_matches_recorded_ratio_updates() {
10405        let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10406        let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
10407        let split_ids: Vec<_> = tree
10408            .nodes()
10409            .filter_map(|node| match node.kind {
10410                PaneNodeKind::Split(_) => Some(node.id),
10411                PaneNodeKind::Leaf(_) => None,
10412            })
10413            .collect();
10414        assert!(!split_ids.is_empty());
10415        let ratios = [
10416            PaneSplitRatio::new(3, 2).expect("valid ratio"),
10417            PaneSplitRatio::new(2, 3).expect("valid ratio"),
10418            PaneSplitRatio::new(5, 4).expect("valid ratio"),
10419            PaneSplitRatio::new(4, 5).expect("valid ratio"),
10420        ];
10421
10422        for idx in 0..16u64 {
10423            timeline
10424                .apply_and_record(
10425                    &mut tree,
10426                    idx,
10427                    20_000 + idx,
10428                    PaneOperation::SetSplitRatio {
10429                        split: split_ids[idx as usize % split_ids.len()],
10430                        ratio: ratios[idx as usize % ratios.len()],
10431                    },
10432                )
10433                .expect("ratio update should apply");
10434        }
10435
10436        let replayed = timeline.replay().expect("replay should succeed");
10437        assert_eq!(replayed.state_hash(), tree.state_hash());
10438        assert_eq!(replayed.to_snapshot(), tree.to_snapshot());
10439    }
10440
10441    fn timeline_with_redo_entry(
10442        checkpoint_interval: usize,
10443    ) -> (PaneTree, PaneInteractionTimeline, Vec<PaneTreeSnapshot>) {
10444        let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10445        let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
10446        timeline.checkpoint_interval = checkpoint_interval;
10447        let mut states = vec![tree.to_snapshot()];
10448        for (operation_id, numerator) in [(1, 4), (2, 5), (3, 6), (4, 7)] {
10449            timeline
10450                .apply_and_record(
10451                    &mut tree,
10452                    operation_id,
10453                    operation_id,
10454                    PaneOperation::SetSplitRatio {
10455                        split: id(1),
10456                        ratio: PaneSplitRatio::new(numerator, 10).expect("valid ratio"),
10457                    },
10458                )
10459                .expect("valid recorded edit");
10460            states.push(tree.to_snapshot());
10461        }
10462        assert!(timeline.undo(&mut tree).expect("retain a redo entry"));
10463        assert_eq!(timeline.applied_len(), 3);
10464        assert_eq!(tree.to_snapshot(), states[3]);
10465        (tree, timeline, states)
10466    }
10467
10468    fn assert_timeline_navigation_failure_is_atomic(redo: bool, invalid_operation: bool) {
10469        let (mut tree, mut timeline, states) = timeline_with_redo_entry(0);
10470        let valid_history = timeline.clone();
10471        let missing = id(u64::MAX);
10472        let expected_error = if invalid_operation {
10473            // Replay must execute the first valid edit before rejecting the
10474            // second one, without publishing that partial tree to the caller.
10475            timeline.entries[1].operation = PaneOperation::CloseNode { target: missing };
10476            let before_hash = timeline.entries[0].after_hash;
10477            PaneInteractionTimelineError::ApplyFailed {
10478                source: PaneOperationError {
10479                    operation_id: 2,
10480                    kind: PaneOperationKind::CloseNode,
10481                    touched_nodes: smallvec![missing],
10482                    before_hash,
10483                    after_hash: before_hash,
10484                    reason: PaneOperationFailure::MissingNode { node_id: missing },
10485                },
10486            }
10487        } else {
10488            timeline.baseline.as_mut().expect("baseline").root = missing;
10489            PaneInteractionTimelineError::BaselineInvalid {
10490                source: PaneModelError::MissingRoot { root: missing },
10491            }
10492        };
10493        let before_tree = tree.to_snapshot();
10494        let before_history = timeline.clone();
10495        let before_redo = timeline.entries[timeline.cursor..].to_vec();
10496        let error = if redo {
10497            timeline.redo(&mut tree)
10498        } else {
10499            timeline.undo(&mut tree)
10500        }
10501        .expect_err("invalid replay input must be rejected");
10502        assert_eq!(error, expected_error, "original replay error must survive");
10503        assert_eq!(
10504            tree.to_snapshot(),
10505            before_tree,
10506            "failed navigation changed tree"
10507        );
10508        assert_eq!(timeline.cursor, 3, "failed navigation changed cursor");
10509        assert_eq!(timeline.entries[timeline.cursor..], before_redo);
10510        assert_eq!(
10511            timeline, before_history,
10512            "failed navigation changed history"
10513        );
10514
10515        // Repair only the rejected input; navigation must resume from the
10516        // exact same cursor, retaining the original redo branch.
10517        if invalid_operation {
10518            timeline.entries[1] = valid_history.entries[1].clone();
10519        } else {
10520            timeline.baseline = valid_history.baseline;
10521        }
10522        let target = if redo { 4 } else { 2 };
10523        assert!(if redo {
10524            timeline.redo(&mut tree).expect("redo after input repair")
10525        } else {
10526            timeline.undo(&mut tree).expect("undo after input repair")
10527        });
10528        assert_eq!(timeline.cursor, target);
10529        assert_eq!(tree.to_snapshot(), states[target]);
10530        assert!(if redo {
10531            timeline.undo(&mut tree).expect("undo restored navigation")
10532        } else {
10533            timeline.redo(&mut tree).expect("redo restored navigation")
10534        });
10535        assert_eq!(timeline.cursor, 3);
10536        assert_eq!(tree.to_snapshot(), before_tree);
10537        assert_eq!(timeline.entries[timeline.cursor..], before_redo);
10538    }
10539
10540    #[test]
10541    fn interaction_timeline_undo_invalid_baseline_is_atomic() {
10542        assert_timeline_navigation_failure_is_atomic(false, false);
10543    }
10544
10545    #[test]
10546    fn interaction_timeline_redo_invalid_baseline_is_atomic() {
10547        assert_timeline_navigation_failure_is_atomic(true, false);
10548    }
10549
10550    #[test]
10551    fn interaction_timeline_undo_invalid_operation_is_atomic() {
10552        assert_timeline_navigation_failure_is_atomic(false, true);
10553    }
10554
10555    #[test]
10556    fn interaction_timeline_redo_invalid_operation_is_atomic() {
10557        assert_timeline_navigation_failure_is_atomic(true, true);
10558    }
10559
10560    #[test]
10561    fn interaction_timeline_navigation_boundaries_preserve_state() {
10562        let mut empty_tree = PaneTree::singleton("empty history");
10563        let mut empty_timeline = PaneInteractionTimeline::default();
10564        let empty_snapshot = empty_tree.to_snapshot();
10565        assert_eq!(empty_timeline.undo(&mut empty_tree), Ok(false));
10566        assert_eq!(empty_timeline.redo(&mut empty_tree), Ok(false));
10567        assert_eq!(empty_tree.to_snapshot(), empty_snapshot);
10568        assert_eq!(empty_timeline, PaneInteractionTimeline::default());
10569
10570        for checkpoint_interval in [0, 1] {
10571            let (mut tree, mut timeline, states) = timeline_with_redo_entry(checkpoint_interval);
10572            for cursor in (0..3).rev() {
10573                assert_eq!(timeline.undo(&mut tree), Ok(true));
10574                assert_eq!(timeline.applied_len(), cursor);
10575                assert_eq!(tree.to_snapshot(), states[cursor]);
10576            }
10577            let before_history = timeline.clone();
10578            assert_eq!(timeline.undo(&mut tree), Ok(false));
10579            assert_eq!(timeline, before_history);
10580            assert_eq!(tree.to_snapshot(), states[0]);
10581            for (cursor, state) in states.iter().enumerate().skip(1) {
10582                assert_eq!(timeline.redo(&mut tree), Ok(true));
10583                assert_eq!(timeline.applied_len(), cursor);
10584                assert_eq!(&tree.to_snapshot(), state);
10585            }
10586            let before_history = timeline.clone();
10587            assert_eq!(timeline.redo(&mut tree), Ok(false));
10588            assert_eq!(timeline, before_history);
10589            assert_eq!(tree.to_snapshot(), states[4]);
10590        }
10591    }
10592
10593    #[test]
10594    fn rejected_timeline_operation_preserves_redo_branch() {
10595        for coalesced in [false, true] {
10596            let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10597            let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
10598            timeline.checkpoint_interval = 1;
10599            for (operation_id, numerator) in [(1, 4), (2, 5)] {
10600                timeline
10601                    .apply_and_record(
10602                        &mut tree,
10603                        operation_id,
10604                        operation_id,
10605                        PaneOperation::SetSplitRatio {
10606                            split: id(1),
10607                            ratio: PaneSplitRatio::new(numerator, 2).expect("valid ratio"),
10608                        },
10609                    )
10610                    .expect("valid edit");
10611            }
10612            let head = tree.to_snapshot();
10613            assert!(timeline.undo(&mut tree).expect("undo"));
10614            let before_tree = tree.to_snapshot();
10615            let before_history = timeline.clone();
10616            let invalid = PaneOperation::SetSplitRatio {
10617                split: id(u64::MAX),
10618                ratio: PaneSplitRatio::new(1, 1).expect("valid ratio"),
10619            };
10620            let result = if coalesced {
10621                timeline.apply_and_record_coalesced_resize_delta(&mut tree, 3, 3, invalid, 0)
10622            } else {
10623                timeline.apply_and_record(&mut tree, 3, 3, invalid)
10624            };
10625            assert!(result.is_err(), "missing split must be rejected");
10626            assert_eq!(tree.to_snapshot(), before_tree);
10627            assert_eq!(
10628                timeline, before_history,
10629                "rejection lost redo; coalesced={coalesced}"
10630            );
10631            assert!(timeline.redo(&mut tree).expect("redo survived rejection"));
10632            assert_eq!(tree.to_snapshot(), head);
10633            assert!(timeline.undo(&mut tree).expect("undo before valid branch"));
10634            let replacement = PaneOperation::SetSplitRatio {
10635                split: id(1),
10636                ratio: PaneSplitRatio::new(7, 2).expect("valid ratio"),
10637            };
10638            if coalesced {
10639                timeline.apply_and_record_coalesced_resize_delta(&mut tree, 4, 4, replacement, 2)
10640            } else {
10641                timeline.apply_and_record(&mut tree, 4, 4, replacement)
10642            }
10643            .expect("a valid edit replaces the redo branch");
10644            assert!(
10645                !timeline
10646                    .redo(&mut tree)
10647                    .expect("no stale redo after valid branch")
10648            );
10649            assert_eq!(timeline.entries.len(), 2);
10650            assert_eq!(timeline.entries.last().unwrap().operation_id, 4);
10651            assert_eq!(
10652                timeline
10653                    .replay()
10654                    .expect("valid branch replay")
10655                    .to_snapshot(),
10656                tree.to_snapshot()
10657            );
10658        }
10659    }
10660
10661    #[test]
10662    fn rejected_initial_timeline_operation_does_not_install_a_baseline() {
10663        for coalesced in [false, true] {
10664            let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10665            let before_tree = tree.to_snapshot();
10666            let mut timeline = PaneInteractionTimeline::default();
10667            let before_history = timeline.clone();
10668            let invalid = PaneOperation::CloseNode {
10669                target: id(u64::MAX),
10670            };
10671            let result = if coalesced {
10672                timeline.apply_and_record_coalesced_resize_delta(&mut tree, 1, 1, invalid, 0)
10673            } else {
10674                timeline.apply_and_record(&mut tree, 1, 1, invalid)
10675            };
10676            assert!(result.is_err());
10677            assert_eq!(tree.to_snapshot(), before_tree);
10678            assert_eq!(
10679                timeline, before_history,
10680                "rejection changed baseline; coalesced={coalesced}"
10681            );
10682        }
10683    }
10684
10685    #[test]
10686    fn interaction_timeline_coalesces_resize_deltas_for_same_split() {
10687        let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10688        let initial_hash = tree.state_hash();
10689        let split = id(1);
10690        let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
10691        let ratios = [
10692            PaneSplitRatio::new(4, 6).expect("valid ratio"),
10693            PaneSplitRatio::new(7, 3).expect("valid ratio"),
10694            PaneSplitRatio::new(2, 5).expect("valid ratio"),
10695        ];
10696
10697        for (index, ratio) in ratios.into_iter().enumerate() {
10698            timeline
10699                .apply_and_record_coalesced_resize_delta(
10700                    &mut tree,
10701                    index as u64 + 1,
10702                    100 + index as u64,
10703                    PaneOperation::SetSplitRatio { split, ratio },
10704                    0,
10705                )
10706                .expect("ratio update should apply");
10707        }
10708
10709        assert_eq!(timeline.entries.len(), 1);
10710        assert_eq!(timeline.cursor, 1);
10711        assert_eq!(timeline.entries[0].operation_id, 102);
10712        assert_eq!(timeline.entries[0].before_hash, initial_hash);
10713        assert_eq!(split_ratio(&tree, split), ratios[2]);
10714        assert_eq!(timeline.next_operation_id(), 103);
10715
10716        let replayed = timeline.replay().expect("replay should succeed");
10717        assert_eq!(replayed.to_snapshot(), tree.to_snapshot());
10718
10719        assert!(timeline.undo(&mut tree).expect("undo should succeed"));
10720        assert_eq!(tree.state_hash(), initial_hash);
10721        assert!(timeline.redo(&mut tree).expect("redo should succeed"));
10722        assert_eq!(split_ratio(&tree, split), ratios[2]);
10723    }
10724
10725    #[test]
10726    fn interaction_timeline_keeps_separate_resize_gestures_distinct() {
10727        let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10728        let split = id(1);
10729        let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
10730        let first_ratio = PaneSplitRatio::new(4, 6).expect("valid ratio");
10731        let second_ratio = PaneSplitRatio::new(7, 3).expect("valid ratio");
10732
10733        timeline
10734            .apply_and_record_coalesced_resize_delta(
10735                &mut tree,
10736                1,
10737                101,
10738                PaneOperation::SetSplitRatio {
10739                    split,
10740                    ratio: first_ratio,
10741                },
10742                100,
10743            )
10744            .expect("first gesture should apply");
10745        timeline
10746            .apply_and_record_coalesced_resize_delta(
10747                &mut tree,
10748                2,
10749                102,
10750                PaneOperation::SetSplitRatio {
10751                    split,
10752                    ratio: second_ratio,
10753                },
10754                101,
10755            )
10756            .expect("second gesture should apply");
10757
10758        assert_eq!(timeline.entries.len(), 2);
10759        assert_eq!(timeline.cursor, 2);
10760        assert_eq!(split_ratio(&tree, split), second_ratio);
10761        assert!(timeline.undo(&mut tree).expect("undo should succeed"));
10762        assert_eq!(split_ratio(&tree, split), first_ratio);
10763    }
10764
10765    #[test]
10766    fn interaction_timeline_refreshes_checkpoint_when_coalescing_head() {
10767        let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10768        let split = id(1);
10769        let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
10770        timeline.checkpoint_interval = 1;
10771
10772        timeline
10773            .apply_and_record_coalesced_resize_delta(
10774                &mut tree,
10775                1,
10776                201,
10777                PaneOperation::SetSplitRatio {
10778                    split,
10779                    ratio: PaneSplitRatio::new(6, 4).expect("valid ratio"),
10780                },
10781                200,
10782            )
10783            .expect("first ratio should apply");
10784        timeline
10785            .apply_and_record_coalesced_resize_delta(
10786                &mut tree,
10787                2,
10788                202,
10789                PaneOperation::SetSplitRatio {
10790                    split,
10791                    ratio: PaneSplitRatio::new(8, 2).expect("valid ratio"),
10792                },
10793                200,
10794            )
10795            .expect("second ratio should apply");
10796
10797        assert_eq!(timeline.entries.len(), 1);
10798        assert_eq!(timeline.checkpoints.len(), 1);
10799        assert_eq!(timeline.checkpoints[0].applied_len, 1);
10800        assert_eq!(timeline.checkpoints[0].snapshot, tree.to_snapshot());
10801    }
10802
10803    #[test]
10804    fn interaction_timeline_enforces_configured_max_entries() {
10805        let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10806        let mut timeline = PaneInteractionTimeline::with_baseline(&tree).with_max_entries(3);
10807        let split = id(1);
10808        let ratios = [
10809            PaneSplitRatio::new(4, 6).expect("valid ratio"),
10810            PaneSplitRatio::new(5, 5).expect("valid ratio"),
10811            PaneSplitRatio::new(6, 4).expect("valid ratio"),
10812            PaneSplitRatio::new(7, 3).expect("valid ratio"),
10813            PaneSplitRatio::new(8, 2).expect("valid ratio"),
10814        ];
10815
10816        for (index, ratio) in ratios.into_iter().enumerate() {
10817            timeline
10818                .apply_and_record(
10819                    &mut tree,
10820                    index as u64 + 1,
10821                    300 + index as u64,
10822                    PaneOperation::SetSplitRatio { split, ratio },
10823                )
10824                .expect("ratio update should apply");
10825        }
10826
10827        assert_eq!(timeline.entries.len(), 3);
10828        assert_eq!(timeline.cursor, 3);
10829        assert_eq!(timeline.entries[0].operation_id, 302);
10830        assert_eq!(timeline.entries[2].operation_id, 304);
10831        assert_eq!(timeline.next_operation_id(), 305);
10832        let replayed = timeline.replay().expect("replay should succeed");
10833        assert_eq!(replayed.to_snapshot(), tree.to_snapshot());
10834    }
10835
10836    #[test]
10837    fn interaction_timeline_records_checkpoints_at_default_interval() {
10838        let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10839        let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
10840        let split_ids: Vec<_> = tree
10841            .nodes()
10842            .filter_map(|node| match node.kind {
10843                PaneNodeKind::Split(_) => Some(node.id),
10844                PaneNodeKind::Leaf(_) => None,
10845            })
10846            .collect();
10847        let ratios = [
10848            PaneSplitRatio::new(3, 2).expect("valid ratio"),
10849            PaneSplitRatio::new(2, 3).expect("valid ratio"),
10850            PaneSplitRatio::new(5, 4).expect("valid ratio"),
10851            PaneSplitRatio::new(4, 5).expect("valid ratio"),
10852        ];
10853
10854        for idx in 0..16u64 {
10855            timeline
10856                .apply_and_record(
10857                    &mut tree,
10858                    idx,
10859                    30_000 + idx,
10860                    PaneOperation::SetSplitRatio {
10861                        split: split_ids[idx as usize % split_ids.len()],
10862                        ratio: ratios[idx as usize % ratios.len()],
10863                    },
10864                )
10865                .expect("ratio update should apply");
10866        }
10867
10868        assert_eq!(timeline.checkpoints.len(), 1);
10869        assert_eq!(timeline.checkpoints[0].applied_len, 16);
10870        assert_eq!(timeline.checkpoints[0].snapshot, tree.to_snapshot());
10871    }
10872
10873    #[test]
10874    fn interaction_timeline_discards_stale_checkpoints_after_branching() {
10875        let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10876        let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
10877        let split_ids: Vec<_> = tree
10878            .nodes()
10879            .filter_map(|node| match node.kind {
10880                PaneNodeKind::Split(_) => Some(node.id),
10881                PaneNodeKind::Leaf(_) => None,
10882            })
10883            .collect();
10884        let ratios = [
10885            PaneSplitRatio::new(3, 2).expect("valid ratio"),
10886            PaneSplitRatio::new(2, 3).expect("valid ratio"),
10887            PaneSplitRatio::new(5, 4).expect("valid ratio"),
10888            PaneSplitRatio::new(4, 5).expect("valid ratio"),
10889        ];
10890
10891        for idx in 0..32u64 {
10892            timeline
10893                .apply_and_record(
10894                    &mut tree,
10895                    idx,
10896                    40_000 + idx,
10897                    PaneOperation::SetSplitRatio {
10898                        split: split_ids[idx as usize % split_ids.len()],
10899                        ratio: ratios[idx as usize % ratios.len()],
10900                    },
10901                )
10902                .expect("ratio update should apply");
10903        }
10904
10905        assert_eq!(timeline.checkpoints.len(), 2);
10906        timeline.undo(&mut tree).expect("undo should succeed");
10907        timeline.undo(&mut tree).expect("undo should succeed");
10908        timeline.undo(&mut tree).expect("undo should succeed");
10909        timeline.undo(&mut tree).expect("undo should succeed");
10910        timeline.undo(&mut tree).expect("undo should succeed");
10911
10912        timeline
10913            .apply_and_record(
10914                &mut tree,
10915                99,
10916                99_999,
10917                PaneOperation::SetSplitRatio {
10918                    split: split_ids[0],
10919                    ratio: PaneSplitRatio::new(7, 5).expect("valid ratio"),
10920                },
10921            )
10922            .expect("branching update should apply");
10923
10924        assert_eq!(timeline.cursor, 28);
10925        assert_eq!(timeline.entries.len(), 28);
10926        assert_eq!(timeline.checkpoints.len(), 1);
10927        assert_eq!(timeline.checkpoints[0].applied_len, 16);
10928    }
10929
10930    #[test]
10931    fn interaction_timeline_replay_diagnostics_report_checkpoint_hit_and_depth() {
10932        let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
10933        let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
10934        let split_ids: Vec<_> = tree
10935            .nodes()
10936            .filter_map(|node| match node.kind {
10937                PaneNodeKind::Split(_) => Some(node.id),
10938                PaneNodeKind::Leaf(_) => None,
10939            })
10940            .collect();
10941
10942        for idx in 0..20u64 {
10943            timeline
10944                .apply_and_record(
10945                    &mut tree,
10946                    idx,
10947                    50_000 + idx,
10948                    PaneOperation::SetSplitRatio {
10949                        split: split_ids[idx as usize % split_ids.len()],
10950                        ratio: PaneSplitRatio::new(3, 2).expect("valid ratio"),
10951                    },
10952                )
10953                .expect("ratio update should apply");
10954        }
10955
10956        let diagnostics = timeline.replay_diagnostics();
10957        assert_eq!(diagnostics.entry_count, 20);
10958        assert_eq!(diagnostics.cursor, 20);
10959        assert_eq!(diagnostics.checkpoint_interval, 16);
10960        assert_eq!(diagnostics.checkpoint_count, 1);
10961        assert!(diagnostics.checkpoint_hit);
10962        assert_eq!(diagnostics.replay_start_idx, 16);
10963        assert_eq!(diagnostics.replay_depth, 4);
10964    }
10965
10966    #[test]
10967    fn interaction_timeline_retention_diagnostics_reports_entry_and_snapshot_footprint() {
10968        let mut tree = PaneTree::singleton("root");
10969        let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
10970        timeline.checkpoint_interval = 1;
10971
10972        timeline
10973            .apply_and_record(
10974                &mut tree,
10975                1,
10976                60_000,
10977                PaneOperation::SplitLeaf {
10978                    target: id(1),
10979                    axis: SplitAxis::Horizontal,
10980                    ratio: PaneSplitRatio::new(1, 1).expect("valid ratio"),
10981                    placement: PanePlacement::ExistingFirst,
10982                    new_leaf: PaneLeaf::new("aux"),
10983                },
10984            )
10985            .expect("split should apply");
10986
10987        let diagnostics = timeline.retention_diagnostics();
10988        assert_eq!(diagnostics.entry_count, 1);
10989        assert_eq!(diagnostics.cursor, 1);
10990        assert_eq!(diagnostics.redo_entry_count, 0);
10991        assert_eq!(diagnostics.checkpoint_count, 1);
10992        assert_eq!(diagnostics.checkpoint_interval, 1);
10993        assert!(diagnostics.baseline_present);
10994        assert_eq!(diagnostics.retained_snapshot_count, 2);
10995        assert_eq!(diagnostics.baseline_node_count, 1);
10996        assert_eq!(diagnostics.checkpoint_node_count, 3);
10997        assert_eq!(diagnostics.retained_snapshot_node_count, 4);
10998        assert_eq!(diagnostics.retained_operation_payload_bytes, "aux".len());
10999        assert!(
11000            diagnostics.retained_leaf_payload_bytes >= "root".len() + "aux".len(),
11001            "leaf payload bytes should include retained surface keys"
11002        );
11003        assert!(
11004            diagnostics.estimated_total_retained_bytes
11005                >= diagnostics.estimated_entry_struct_bytes
11006                    + diagnostics.estimated_checkpoint_struct_bytes
11007                    + diagnostics.estimated_snapshot_struct_bytes
11008        );
11009    }
11010
11011    #[test]
11012    fn interaction_timeline_retention_diagnostics_separates_leaf_keys_from_extensions() {
11013        let mut snapshot = make_valid_snapshot();
11014        snapshot
11015            .extensions
11016            .insert("tree".to_string(), "wide".to_string());
11017
11018        let left_node = snapshot
11019            .nodes
11020            .iter_mut()
11021            .find(|node| node.id == id(2))
11022            .expect("left leaf should be present");
11023        left_node
11024            .extensions
11025            .insert("node".to_string(), "hot".to_string());
11026        let PaneNodeKind::Leaf(leaf) = &mut left_node.kind else {
11027            let expected_leaf_node = false;
11028            assert!(expected_leaf_node, "left node should be a leaf");
11029            return;
11030        };
11031        leaf.extensions
11032            .insert("leaf".to_string(), "memo".to_string());
11033
11034        let tree = PaneTree::from_snapshot(snapshot).expect("snapshot should validate");
11035        let timeline = PaneInteractionTimeline::with_baseline(&tree);
11036        let diagnostics = timeline.retention_diagnostics();
11037
11038        assert_eq!(diagnostics.retained_snapshot_count, 1);
11039        assert_eq!(
11040            diagnostics.retained_leaf_payload_bytes,
11041            "left".len() + "right".len()
11042        );
11043        assert_eq!(diagnostics.retained_extension_entry_count, 3);
11044        assert_eq!(
11045            diagnostics.retained_extension_payload_bytes,
11046            "tree".len() + "wide".len() + "node".len() + "hot".len() + "leaf".len() + "memo".len()
11047        );
11048    }
11049
11050    #[test]
11051    fn interaction_timeline_retention_diagnostics_reports_redo_entries() {
11052        let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11053        let mut timeline = PaneInteractionTimeline::with_baseline(&tree);
11054        let split = id(1);
11055
11056        for (idx, ratio) in [
11057            PaneSplitRatio::new(4, 6).expect("valid ratio"),
11058            PaneSplitRatio::new(6, 4).expect("valid ratio"),
11059        ]
11060        .into_iter()
11061        .enumerate()
11062        {
11063            timeline
11064                .apply_and_record(
11065                    &mut tree,
11066                    idx as u64 + 1,
11067                    70_000 + idx as u64,
11068                    PaneOperation::SetSplitRatio { split, ratio },
11069                )
11070                .expect("ratio update should apply");
11071        }
11072
11073        assert!(timeline.undo(&mut tree).expect("undo should succeed"));
11074        let diagnostics = timeline.retention_diagnostics();
11075        assert_eq!(diagnostics.entry_count, 2);
11076        assert_eq!(diagnostics.cursor, 1);
11077        assert_eq!(diagnostics.redo_entry_count, 1);
11078    }
11079
11080    #[test]
11081    fn interaction_timeline_checkpoint_decision_prefers_shorter_interval_for_expensive_replay_steps()
11082     {
11083        let slow_replay =
11084            PaneInteractionTimeline::checkpoint_decision(10_000, 2_500).checkpoint_interval;
11085        let cheap_replay =
11086            PaneInteractionTimeline::checkpoint_decision(10_000, 100).checkpoint_interval;
11087
11088        assert!(slow_replay < cheap_replay);
11089        assert!(slow_replay >= 1);
11090        assert!(cheap_replay >= 1);
11091    }
11092
11093    #[test]
11094    fn set_split_ratio_uses_local_validation_strategy() {
11095        let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11096        assert_eq!(
11097            tree.validation_strategy_for_operation(PaneOperationKind::SetSplitRatio),
11098            PaneValidationStrategy::LocalClosure
11099        );
11100        assert_eq!(
11101            tree.validation_strategy_for_operation(PaneOperationKind::NormalizeRatios),
11102            PaneValidationStrategy::FullTree
11103        );
11104    }
11105
11106    #[test]
11107    fn local_validation_closure_rejects_parent_mismatch_for_touched_split() {
11108        let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11109        let split_id = id(1);
11110        let child_id = id(2);
11111        tree.nodes.get_mut(&child_id).expect("child present").parent = None;
11112
11113        let err = tree
11114            .validate_local_closure(&[split_id])
11115            .expect_err("local closure should detect broken child parent");
11116        assert!(matches!(
11117            err,
11118            PaneModelError::ParentMismatch {
11119                node_id,
11120                expected: Some(expected),
11121                actual: None,
11122            } if node_id == child_id && expected == split_id
11123        ));
11124    }
11125
11126    #[test]
11127    fn operation_family_classifier_partitions_local_and_structural_kinds() {
11128        assert_eq!(
11129            PaneOperationKind::SetSplitRatio.family(),
11130            PaneOperationFamily::Local
11131        );
11132        for kind in [
11133            PaneOperationKind::SplitLeaf,
11134            PaneOperationKind::CloseNode,
11135            PaneOperationKind::MoveSubtree,
11136            PaneOperationKind::SwapNodes,
11137            PaneOperationKind::NormalizeRatios,
11138        ] {
11139            assert_eq!(
11140                kind.family(),
11141                PaneOperationFamily::Structural,
11142                "operation kind {kind:?} must be structural"
11143            );
11144        }
11145        // PaneOperation::family() delegates to its kind.
11146        let op = PaneOperation::SetSplitRatio {
11147            split: id(1),
11148            ratio: PaneSplitRatio::new(1, 1).expect("valid ratio"),
11149        };
11150        assert_eq!(op.family(), PaneOperationFamily::Local);
11151        assert_eq!(op.family(), op.kind().family());
11152    }
11153
11154    #[test]
11155    fn validation_strategy_is_derived_from_operation_family() {
11156        let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11157        assert_eq!(
11158            tree.validation_strategy_for_operation(PaneOperationKind::SetSplitRatio),
11159            PaneValidationStrategy::LocalClosure
11160        );
11161        for kind in [
11162            PaneOperationKind::SplitLeaf,
11163            PaneOperationKind::CloseNode,
11164            PaneOperationKind::MoveSubtree,
11165            PaneOperationKind::SwapNodes,
11166            PaneOperationKind::NormalizeRatios,
11167        ] {
11168            assert_eq!(
11169                tree.validation_strategy_for_operation(kind),
11170                PaneValidationStrategy::FullTree,
11171                "structural kind {kind:?} must use whole-tree validation"
11172            );
11173        }
11174    }
11175
11176    #[test]
11177    fn always_full_validation_mode_catches_corruption_outside_touched_closure() {
11178        // A corruption far from the touched node is invisible to local-closure
11179        // validation but caught by the forced whole-tree validator. This proves
11180        // the conservative override is genuinely distinct and easy to force.
11181        let mut tree = PaneTree::from_snapshot(make_nested_snapshot()).expect("valid tree");
11182        // Break the parent pointer of a leaf (id 5) that is NOT in the touched
11183        // closure of the root split (id 1).
11184        let far_leaf = id(5);
11185        tree.nodes.get_mut(&far_leaf).expect("present").parent = None;
11186
11187        let touched = [id(1)];
11188
11189        // Adaptive validation for the Local family only inspects the touched
11190        // closure (the root split and its direct children), so it misses the
11191        // far corruption.
11192        assert!(
11193            tree.validate_after_operation_with_mode(
11194                PaneOperationKind::SetSplitRatio,
11195                &touched,
11196                PaneValidationMode::Adaptive,
11197            )
11198            .is_ok(),
11199            "local closure over the root split must not see a far leaf corruption"
11200        );
11201
11202        // Forcing whole-tree validation catches it regardless of touched set.
11203        assert!(
11204            tree.validate_after_operation_with_mode(
11205                PaneOperationKind::SetSplitRatio,
11206                &touched,
11207                PaneValidationMode::AlwaysFull,
11208            )
11209            .is_err(),
11210            "forced full validation must detect the far leaf corruption"
11211        );
11212    }
11213
11214    fn neutral_pressure() -> PanePressureSnapProfile {
11215        PanePressureSnapProfile {
11216            strength_bps: 5_000,
11217            hysteresis_bps: 100,
11218        }
11219    }
11220
11221    fn first_share_bps(op: &PaneOperation) -> u32 {
11222        match op {
11223            PaneOperation::SetSplitRatio { ratio, .. } => {
11224                ratio.numerator() * 10_000 / (ratio.numerator() + ratio.denominator())
11225            }
11226            other => panic!("expected SetSplitRatio, got {other:?}"),
11227        }
11228    }
11229
11230    fn split_target(split: PaneId, axis: SplitAxis) -> PaneResizeTarget {
11231        PaneResizeTarget {
11232            split_id: split,
11233            axis,
11234        }
11235    }
11236
11237    fn drag_updated_transition(
11238        target: PaneResizeTarget,
11239        current: PanePointerPosition,
11240    ) -> PaneDragResizeTransition {
11241        PaneDragResizeTransition {
11242            transition_id: 1,
11243            sequence: 1,
11244            from: PaneDragResizeState::Idle,
11245            to: PaneDragResizeState::Idle,
11246            effect: PaneDragResizeEffect::DragUpdated {
11247                target,
11248                pointer_id: 1,
11249                previous: PanePointerPosition::new(current.x - 1, current.y),
11250                current,
11251                delta_x: 1,
11252                delta_y: 0,
11253                total_delta_x: 1,
11254                total_delta_y: 0,
11255            },
11256        }
11257    }
11258
11259    #[test]
11260    fn plan_splitter_resize_tracks_pointer_along_axis() {
11261        let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11262        let layout = tree
11263            .solve_layout(Rect::new(0, 0, 60, 16))
11264            .expect("layout solves");
11265        let rect = layout.rect(id(1)).expect("root split rect");
11266        let target = split_target(id(1), SplitAxis::Horizontal);
11267
11268        let left_pointer = PanePointerPosition::new(i32::from(rect.x) + 2, i32::from(rect.y) + 4);
11269        let right_pointer = PanePointerPosition::new(
11270            i32::from(rect.x) + i32::from(rect.width) - 3,
11271            i32::from(rect.y) + 4,
11272        );
11273
11274        let left_op = tree
11275            .plan_splitter_resize(target, &layout, left_pointer, neutral_pressure())
11276            .expect("left plan");
11277        let right_op = tree
11278            .plan_splitter_resize(target, &layout, right_pointer, neutral_pressure())
11279            .expect("right plan");
11280
11281        assert!(matches!(left_op, PaneOperation::SetSplitRatio { split, .. } if split == id(1)));
11282        assert!(matches!(right_op, PaneOperation::SetSplitRatio { split, .. } if split == id(1)));
11283        // Dragging the splitter rightward grows the first (left) child's share.
11284        assert!(
11285            first_share_bps(&right_op) > first_share_bps(&left_op),
11286            "right={} left={}",
11287            first_share_bps(&right_op),
11288            first_share_bps(&left_op)
11289        );
11290    }
11291
11292    #[test]
11293    fn plan_splitter_resize_rejects_non_split_target() {
11294        let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11295        let layout = tree
11296            .solve_layout(Rect::new(0, 0, 60, 16))
11297            .expect("layout solves");
11298        // id(2) is the left leaf, not a split.
11299        let err = tree
11300            .plan_splitter_resize(
11301                split_target(id(2), SplitAxis::Horizontal),
11302                &layout,
11303                PanePointerPosition::new(5, 5),
11304                neutral_pressure(),
11305            )
11306            .expect_err("leaf target must be rejected");
11307        assert_eq!(err, PaneSplitterResizePlanError::NotASplit { node: id(2) });
11308    }
11309
11310    #[test]
11311    fn plan_splitter_resize_rejects_axis_mismatch() {
11312        let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11313        let layout = tree
11314            .solve_layout(Rect::new(0, 0, 60, 16))
11315            .expect("layout solves");
11316        let err = tree
11317            .plan_splitter_resize(
11318                split_target(id(1), SplitAxis::Vertical),
11319                &layout,
11320                PanePointerPosition::new(5, 5),
11321                neutral_pressure(),
11322            )
11323            .expect_err("axis mismatch must be rejected");
11324        assert_eq!(
11325            err,
11326            PaneSplitterResizePlanError::AxisMismatch {
11327                split: id(1),
11328                expected: SplitAxis::Vertical,
11329                actual: SplitAxis::Horizontal,
11330            }
11331        );
11332    }
11333
11334    #[test]
11335    fn plan_splitter_resize_rejects_missing_split() {
11336        let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11337        let layout = tree
11338            .solve_layout(Rect::new(0, 0, 60, 16))
11339            .expect("layout solves");
11340        let err = tree
11341            .plan_splitter_resize(
11342                split_target(id(99), SplitAxis::Horizontal),
11343                &layout,
11344                PanePointerPosition::new(5, 5),
11345                neutral_pressure(),
11346            )
11347            .expect_err("missing split must be rejected");
11348        assert_eq!(
11349            err,
11350            PaneSplitterResizePlanError::MissingSplit { split: id(99) }
11351        );
11352    }
11353
11354    #[test]
11355    fn plan_splitter_nudge_steps_current_ratio() {
11356        let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11357        // make_valid_snapshot's root ratio is 3/2 -> a first-child share of 6000 bps.
11358        let target = split_target(id(1), SplitAxis::Horizontal);
11359        let up = tree
11360            .plan_splitter_nudge(target, i32::from(PANE_SNAP_DEFAULT_STEP_BPS))
11361            .expect("nudge up");
11362        let down = tree
11363            .plan_splitter_nudge(target, -i32::from(PANE_SNAP_DEFAULT_STEP_BPS))
11364            .expect("nudge down");
11365        assert_eq!(first_share_bps(&up), 6_500);
11366        assert_eq!(first_share_bps(&down), 5_500);
11367    }
11368
11369    #[test]
11370    fn operations_for_transition_drag_updated_mutates_ratio() {
11371        let mut tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11372        let layout = tree
11373            .solve_layout(Rect::new(0, 0, 60, 16))
11374            .expect("layout solves");
11375        let rect = layout.rect(id(1)).expect("root split rect");
11376        let target = split_target(id(1), SplitAxis::Horizontal);
11377        let pointer = PanePointerPosition::new(
11378            i32::from(rect.x) + i32::from(rect.width) - 3,
11379            i32::from(rect.y) + 4,
11380        );
11381        let transition = drag_updated_transition(target, pointer);
11382
11383        let before = split_ratio(&tree, id(1));
11384        let before_share =
11385            before.numerator() * 10_000 / (before.numerator() + before.denominator());
11386
11387        let ops = tree.operations_for_transition(&transition, &layout, neutral_pressure());
11388        assert_eq!(ops.len(), 1);
11389        for (offset, op) in ops.iter().cloned().enumerate() {
11390            tree.apply_operation(1_000 + offset as u64, op)
11391                .expect("operation applies");
11392        }
11393
11394        let after = split_ratio(&tree, id(1));
11395        let after_share = after.numerator() * 10_000 / (after.numerator() + after.denominator());
11396        assert!(
11397            after_share > before_share,
11398            "after={after_share} before={before_share}"
11399        );
11400    }
11401
11402    #[test]
11403    fn operations_for_transition_keyboard_applied_nudges() {
11404        let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11405        let layout = tree
11406            .solve_layout(Rect::new(0, 0, 60, 16))
11407            .expect("layout solves");
11408        let target = split_target(id(1), SplitAxis::Horizontal);
11409        let transition = PaneDragResizeTransition {
11410            transition_id: 2,
11411            sequence: 2,
11412            from: PaneDragResizeState::Idle,
11413            to: PaneDragResizeState::Idle,
11414            effect: PaneDragResizeEffect::KeyboardApplied {
11415                target,
11416                direction: PaneResizeDirection::Increase,
11417                units: 2,
11418            },
11419        };
11420        let ops = tree.operations_for_transition(&transition, &layout, neutral_pressure());
11421        assert_eq!(ops.len(), 1);
11422        // 6000 (3/2) + 2 * 500 = 7000.
11423        assert_eq!(first_share_bps(&ops[0]), 7_000);
11424    }
11425
11426    #[test]
11427    fn operations_for_transition_is_empty_for_non_geometric_and_unresolvable() {
11428        let tree = PaneTree::from_snapshot(make_valid_snapshot()).expect("valid tree");
11429        let layout = tree
11430            .solve_layout(Rect::new(0, 0, 60, 16))
11431            .expect("layout solves");
11432        let target = split_target(id(1), SplitAxis::Horizontal);
11433
11434        let armed = PaneDragResizeTransition {
11435            transition_id: 3,
11436            sequence: 3,
11437            from: PaneDragResizeState::Idle,
11438            to: PaneDragResizeState::Idle,
11439            effect: PaneDragResizeEffect::Armed {
11440                target,
11441                pointer_id: 1,
11442                origin: PanePointerPosition::new(5, 5),
11443            },
11444        };
11445        assert!(
11446            tree.operations_for_transition(&armed, &layout, neutral_pressure())
11447                .is_empty()
11448        );
11449
11450        let canceled = PaneDragResizeTransition {
11451            transition_id: 4,
11452            sequence: 4,
11453            from: PaneDragResizeState::Idle,
11454            to: PaneDragResizeState::Idle,
11455            effect: PaneDragResizeEffect::Canceled {
11456                target: Some(target),
11457                pointer_id: Some(1),
11458                reason: PaneCancelReason::EscapeKey,
11459            },
11460        };
11461        assert!(
11462            tree.operations_for_transition(&canceled, &layout, neutral_pressure())
11463                .is_empty()
11464        );
11465
11466        // A drag targeting a split that no longer exists is swallowed (no panic,
11467        // no operation), matching the documented best-effort bridge contract.
11468        let stale = drag_updated_transition(
11469            split_target(id(99), SplitAxis::Horizontal),
11470            PanePointerPosition::new(10, 5),
11471        );
11472        assert!(
11473            tree.operations_for_transition(&stale, &layout, neutral_pressure())
11474                .is_empty()
11475        );
11476    }
11477}