# LeashFramework v7 Clean Physics Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Deliver a v7 source/runtime package that removes competing leash-bone physics ownership, stabilizes idle chain motion and terrain collision, hardens locomotion/recovery, cleans source/dependency layout, and preserves every shipped NIF byte-for-byte.

**Architecture:** C++ owns leash transforms through immutable per-bind rest state plus a stateful RopeSolver. Version-sensitive movement/world-query work is isolated behind small adapters, runtime XMLs become passive declarations generated/verified from templates, and UI/settings are decomposed without changing Papyrus or save-facing interfaces.

**Tech Stack:** C++23, CommonLibSSE-NG, SKSE, Havok queries, CMake/vcpkg, Glaze, ImGui/SKSE Menu Framework, Python verification scripts, standalone C++ regression tests.

**Spec:** `docs/superpowers/specs/2026-08-25-leashframework-v7-clean-physics-design.md`

## Global Constraints

- Do not add, remove, rename, reorder, or otherwise change current NIF nodes/bones in collars, chains, or ropes.
- All shipped `.nif` files must remain byte-for-byte identical to v6.
- Preserve Leash.esm FormIDs, Papyrus signatures, persistent leash data, min/max semantics, and anti-break behavior.
- Never force direct locomotion during ragdoll or any non-normal knock/get-up state.
- Keep Body Rope `_0`/`_1` pairs and all existing runtime XML paths.
- Do not claim 10/10 or in-game correctness without Windows build and in-game acceptance evidence.

---

### Task 1: Baseline immutable-assets verification and static audit harness

**Files:** Create `tools/verify_v7.py`, `tests/nif_manifest_v6.sha256`, `VERIFY_V7.bat`.

**Interfaces:** Verifier consumes the runtime tree, returns non-zero on NIF hash drift, dynamic FSMP ownership, old metadata/dependency patterns, hidden solver overrides, personal paths, or forbidden direct corrections.

- [ ] Generate SHA-256 manifest for every v6 NIF from the untouched baseline.
- [ ] Write verification script for NIF hashes, XML ownership, metadata/path hygiene, and source invariants.
- [ ] Run verifier before production changes and confirm it detects known v6 audit failures while NIF hashes match.

### Task 2: Source/dependency cleanup

**Files:** Move `include/SKSEMenuFramework.h` to `third_party/SKSEMenuFramework/SKSEMenuFramework.h`; create `src/UI/MenuFramework.h`; modify `ModMenu.cpp`, `DebugOverlay.cpp`, `CMakeLists.txt`, `vcpkg.json`, `meta.ini`.

- [ ] Add verifier expectations for old include path, `hello-world`, DirectXTK first-party manifest declaration, required transitive CMake discovery, and personal paths.
- [ ] Move third-party header and update first-party includes through wrapper.
- [ ] Remove DirectXTK from the first-party manifest, retain transitive CMake discovery required by CommonLibSSE, and sanitize metadata.
- [ ] Run static verifier.

### Task 3: Immutable bind-time rest state and pose writer

**Files:** Create `src/Leash/LeashRestState.*`, `src/Leash/LeashPoseWriter.*`; modify `LeashInstance.*`; test `tests/rest_state_test.cpp`.

**Interfaces:** `LeashRestState::Capture(...)`, `Reset()`, position/rotation/segment getters; `LeashPoseWriter::Apply(...)` and `ApplyDeferred(...)` only write bound leash bones.

- [ ] Write failing rest-state regression test proving segment lengths do not drift after simulated transforms.
- [ ] Implement rest-state capture independent from simulation output.
- [ ] Remove per-frame rest reconstruction; recapture only on bind/root/reset.
- [ ] Extract pose/deferred writing and stale-root validation.
- [ ] Run tests and verifier.

### Task 4: Material profiles, real solver settings, and sleep

**Files:** Create `src/Physics/RopeMaterialProfile.*`, `src/Physics/RopeSolverPolicy.h`; modify `SimulationSettings.h`, `RopeSolver.*`, `LeashInstance.cpp`, `LeashManager.cpp`; tests `rope_solver_policy_test.cpp`, `material_profile_test.cpp`.

- [ ] Add failing tests for configured iterations, compliance, normalized damping, sleep and wake.
- [ ] Remove hidden 128+32 iteration override and use validated `constraintIterations`.
- [ ] Use configured compliance instead of forced zero.
- [ ] Add sleep/wake state and conservative material profiles for MetalChain/Rope/Magic/Fallback.
- [ ] Run tests and verifier.

### Task 5: Segment-volume world collision and bounded snag release

**Files:** Create `src/Physics/SegmentCollision.*`; modify `WorldCollision.*`, `RopeSolver.cpp`; test `segment_collision_test.cpp`.

- [ ] Write failing plane/edge penetration tests for a segment with non-zero radius.
- [ ] Implement pure capsule/plane projection helper.
- [ ] Integrate adjacent-segment validation, including segments next to anchors.
- [ ] Keep snag release local, timed and automatically restored.
- [ ] Run tests and verifier.

### Task 6: Engine adapters and safer anti-break correction

**Files:** Create `src/Engine/ActorStateAdapter.*`, `CharacterControllerAdapter.*`, `HavokAdapter.*`; modify direct locomotion/pull/recovery/leash correction paths; test `fall_recovery_sequence_test.cpp`.

- [ ] Expand locomotion regression tests across knock states and ragdoll -> knock5 -> get-up6 -> normal0.
- [ ] Centralize fail-closed actor state checks and null-safe diagnostics.
- [ ] Route anti-break correction through bounded adapter; forbid transitions and reacquire anchors after accepted movement.
- [ ] Restrict direct `SetPosition()` to explicit adapter emergency fallback and teleport semantics.
- [ ] Run tests and verifier.

### Task 7: Settings/UI cleanup

**Files:** Create `src/UI/SettingsPage.*`, `DebugPage.*`; modify `ModMenu.cpp`, recovery settings and manager validation; test `settings_policy_test.cpp`.

- [ ] Add tests for clamping/migration policy.
- [ ] Keep `distanceMultiplier` serialized for compatibility but remove it from normal UI and runtime trigger behavior.
- [ ] Split settings/debug page rendering from menu registration.
- [ ] Ensure iteration/compliance controls map directly to runtime values.
- [ ] Run tests and verifier.

### Task 8: Passive FSMP XML templates

**Files:** Create `tools/physics_templates/*.xml.in`, `tools/generate_physics_xml.py`; update runtime `meshes/Leash/**/Physics_*.xml` paths only, never NIFs.

- [ ] Add verifier rule rejecting non-zero mass leash ownership or leash-node constraints.
- [ ] Generate passive XMLs for every currently referenced runtime path.
- [ ] Parse all XMLs and run ownership audit.

### Task 9: Dynamic mesh selection hardening

**Files:** Create `src/Runtime/LeashVisualController.*`; modify `DynamicLeashMeshes.*`, manager; test `visual_size_mapping_test.cpp`.

- [ ] Add tests for all size thresholds.
- [ ] Extract deterministic pure size mapping.
- [ ] Keep global `ApplyMaximum()` as startup compatibility fallback, not per-tick behavior.
- [ ] Add fail-closed actor-scoped selection scaffold that defers unsafe replacement.
- [ ] Run tests and verifier.

### Task 10: Diagnostics/readability/build packaging

**Files:** Harden diagnostics; create `tools/build_native.bat`, `tools/verify_runtime.bat`, `AUDIT_V7.md`; simplify top-level rebuild BAT only where behavior remains compatible.

- [ ] Add missing null guards and rate-limit high-frequency warnings where safe.
- [ ] Move reusable verification/build checks under `tools/`.
- [ ] Produce evidence-based audit with Windows/in-game items clearly marked unverified.

### Task 11: Final verification and package

- [ ] Run all standalone C++ tests with GCC and Clang available in the container.
- [ ] Run Python verifier plus XML/JSON validity checks.
- [ ] Verify every NIF SHA-256 matches v6.
- [ ] Diff v6 vs v7 and inspect for accidental caches/binaries/personal paths.
- [ ] Create `LeashFramework_v6_to_v7.diff` and `LeashFramework_COMPLETE_v7_CleanPhysics_Source.zip`.
- [ ] Report Windows SKSE build and in-game acceptance as unverified until the user tests them.
