diff --git a/docs/qa/persisted-file-upgrade.md b/docs/qa/persisted-file-upgrade.md index 8fdd73afa..fc6f8a47e 100644 --- a/docs/qa/persisted-file-upgrade.md +++ b/docs/qa/persisted-file-upgrade.md @@ -2,7 +2,7 @@ This runbook verifies PR 709's physical filename migration without treating a synthetic fixture as production evidence. The automated harness is destructive only to one explicitly selected disposable emulator and one exact package name; it never clears data during an upgrade. -The harness default `-ExpectedSchemaVersion` is 66, the current database `user_version` (highest migration file + 1). Pass that parameter only to override it. +The harness default `-ExpectedSchemaVersion` is 68, the current database `user_version` (highest migration file + 1). Pass that parameter only to override it. ## Automated v0.9.6 debug-lineage matrix diff --git a/docs/qa/profile-schema42-fixture.md b/docs/qa/profile-schema42-fixture.md index 2ee2807a8..0270a42c8 100644 --- a/docs/qa/profile-schema42-fixture.md +++ b/docs/qa/profile-schema42-fixture.md @@ -1,6 +1,6 @@ # Profile schema-42 Android fixture -This recipe materializes the pre-profile database and legacy preference input used to prove the schema-42 to current-schema upgrade. The fixture source is commit `ac84d9bb8e156002833ad526bf324a8f12710da0`; do not substitute a moving branch or shortened SHA. The upgrade candidate is a debug APK from the current checkout. After that install, `PRAGMA user_version` must be 66 (highest migration file + 1). +This recipe materializes the pre-profile database and legacy preference input used to prove the schema-42 to current-schema upgrade. The fixture source is commit `ac84d9bb8e156002833ad526bf324a8f12710da0`; do not substitute a moving branch or shortened SHA. The upgrade candidate is a debug APK from the current checkout. After that install, `PRAGMA user_version` must be 68 (highest migration file + 1). All commands below are PowerShell commands. Start at the repository root. They use the installed Android SDK (`ANDROID_HOME`, else `ANDROID_SDK_ROOT`, else `%LOCALAPPDATA%\Android\Sdk`) and must not contact Supabase. The only network use is the explicit `git fetch` of the pinned fixture commit and Gradle dependency resolution for that commit. Do not pass `--offline`. @@ -171,9 +171,9 @@ foreach ($suffix in @('-wal', '-shm')) { if ($LASTEXITCODE -eq 0) { Receive-SandboxBytes $relative "$inspectDb$suffix" -AllowEmpty } } $userVersion = (& $hostSqlite -readonly -batch $inspectDb 'PRAGMA user_version;').Trim() -if ($userVersion -ne '66') { throw "Expected user_version 66 after upgrade, got $userVersion" } +if ($userVersion -ne '68') { throw "Expected user_version 68 after upgrade, got $userVersion" } & $hostSqlite -readonly -batch $inspectDb 'SELECT profile_id, legacy_migration_version, body_weight_kg, weight_unit, weight_increment, led_color_scheme_id, equipment_rack_json, workout_preferences_json, vbt_preferences_json FROM UserProfilePreferences ORDER BY profile_id;' & $adb shell run-as $package cat shared_prefs/phoenix_preferences.xml ``` -The host `sqlite3` query must report `user_version` 66, each existing profile row must have `legacy_migration_version = 1`, and the sentinel values from the tracked XML must appear in the corresponding profile preference sections. +The host `sqlite3` query must report `user_version` 68, each existing profile row must have `legacy_migration_version = 1`, and the sentinel values from the tracked XML must appear in the corresponding profile preference sections. diff --git a/scripts/qa/Invoke-PhoenixPersistedFileUpgrade.ps1 b/scripts/qa/Invoke-PhoenixPersistedFileUpgrade.ps1 index 1a9535693..fae58fb8c 100644 --- a/scripts/qa/Invoke-PhoenixPersistedFileUpgrade.ps1 +++ b/scripts/qa/Invoke-PhoenixPersistedFileUpgrade.ps1 @@ -28,7 +28,7 @@ param( [string] $EvidenceDirectory = (Join-Path ([IO.Path]::GetTempPath()) 'phoenix-persisted-file-upgrade'), [Parameter()] - [int] $ExpectedSchemaVersion = 66 + [int] $ExpectedSchemaVersion = 68 ) Set-StrictMode -Version Latest diff --git a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/export/PowerHistoryExportRoundtripTest.kt b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/export/PowerHistoryExportRoundtripTest.kt new file mode 100644 index 000000000..897ffe7c2 --- /dev/null +++ b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/export/PowerHistoryExportRoundtripTest.kt @@ -0,0 +1,214 @@ +package com.devil.phoenixproject.data.export + +import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver +import com.devil.phoenixproject.data.local.ExerciseImporter +import com.devil.phoenixproject.data.repository.PowerLossCompanionStore +import com.devil.phoenixproject.data.repository.SqlDelightExerciseRepository +import com.devil.phoenixproject.data.repository.SqlDelightWorkoutRepository +import com.devil.phoenixproject.database.PhoenixDatabase +import com.devil.phoenixproject.domain.model.WorkoutSession +import com.devil.phoenixproject.domain.powerloss.PowerCable +import com.devil.phoenixproject.domain.powerloss.PowerLossAttemptRecord +import com.devil.phoenixproject.domain.powerloss.PowerLossSetEvidence +import com.devil.phoenixproject.domain.powerloss.PowerStopReason +import com.devil.phoenixproject.domain.powerloss.SampleQualityMarkers +import com.devil.phoenixproject.domain.powerloss.TargetMode +import com.devil.phoenixproject.testutil.FakePreferencesManager +import com.devil.phoenixproject.testutil.createTestSchema +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.test.runTest +import org.junit.After +import org.junit.Before +import org.junit.Test + +/** + * Issue #1392 (packet P4) — power-history export v1 roundtrip. + * + * P4 acceptance: "power-history export roundtrips preserving null/zero/identity". + * Export → parse back → field-equal, INCLUDING the null-vs-zero distinction: a + * measured 0 must survive as 0 and a missing metric must survive as null — the + * two must never collapse into each other. + */ +class PowerHistoryExportRoundtripTest { + + private lateinit var driver: JdbcSqliteDriver + private lateinit var database: PhoenixDatabase + private lateinit var exporter: PowerHistoryExporter + + @Before + fun setup() { + driver = JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY) + createTestSchema(driver) + database = PhoenixDatabase(driver) + val exerciseRepository = SqlDelightExerciseRepository( + database, + ExerciseImporter(database), + FakePreferencesManager(), + ) + val workoutRepository = SqlDelightWorkoutRepository(database, exerciseRepository) + exporter = PowerHistoryExporterImpl(database) + // The exporter enumerates sessions per profile; seed one owned session and one + // foreign-profile session (which must never appear in the export). + kotlinx.coroutines.runBlocking { + workoutRepository.saveSession(WorkoutSession(id = SESSION_ID, profileId = PROFILE_ID)) + workoutRepository.saveSession(WorkoutSession(id = OTHER_SESSION_ID, profileId = OTHER_PROFILE_ID)) + } + } + + @After + fun tearDown() { + driver.close() + } + + @Test + fun `export roundtrips field-equal with null-vs-zero preserved`() = runTest { + val queries = database.phoenixDatabaseQueries + PowerLossCompanionStore.commitEvidence(queries, ownEvidence(), nowMs = 1_000L) + PowerLossCompanionStore.commitEvidence(queries, foreignEvidence(), nowMs = 2_000L) + + val result = exporter.exportPowerData(PROFILE_ID) + + assertEquals(1, result.version) + assertEquals("power-history-v1-$PROFILE_ID.json", result.displayName) + // The document identifies itself and its units explicitly. + assertTrue(result.content.contains("\"documentType\": \"power-history-export\""), result.content) + assertTrue(result.content.contains("\"version\": 1"), result.content) + assertTrue(result.content.contains("\"power\": \"watts\""), result.content) + assertTrue(result.content.contains("\"rom\": \"millimeters\""), result.content) + assertTrue(result.content.contains("\"duration\": \"milliseconds\""), result.content) + + val document = PowerHistoryExportCodec.decode(result.content) + assertEquals(1, document.version) + assertEquals(PROFILE_ID, document.profileId) + // Profile scoping: only this profile's session, only sessions with evidence. + assertEquals(listOf(SESSION_ID), document.sessions.map { it.sessionId }) + assertEquals(1, document.sessions.single().sets.size) + + // Full field-equality against the seeded evidence (identity + every metric). + val decoded = document.sessions.single().sets.single() + assertEquals(ownEvidence(), decoded) + + // Null-vs-zero, called out explicitly on top of the deep equality. + val measuredZero = decoded.attempts.first { it.workingConcentricOrdinal == 1 } + val missing = decoded.attempts.first { it.workingConcentricOrdinal == 2 } + assertEquals(0.0f, measuredZero.mcpWatts, "a measured zero must not roundtrip as null") + assertEquals(0L, measuredZero.concentricDurationMs) + assertEquals(0.0f, measuredZero.lossPercentAtDecision) + assertEquals(0.0f, measuredZero.romAMm) + assertNull(missing.mcpWatts, "a missing metric must not roundtrip as 0") + assertNull(missing.eccentricPowerWatts) + assertNull(missing.concentricDurationMs) + assertNull(missing.eccentricDurationMs) + assertNull(missing.lossPercentAtDecision) + assertNull(missing.romAMm) + assertNull(missing.romBMm) + assertNull(missing.romAPercentOfReference) + assertNull(missing.romBPercentOfReference) + // Attempt-only identity survives (pending ≠ completed). + assertEquals(false, missing.completed) + assertNull(missing.legacyRepIndex) + // Set-level facts survive: reference/trigger/winner + BOTH qualification facts. + assertEquals(1, decoded.referenceWorkingOrdinal) + assertEquals(100.5f, decoded.referenceMcpWatts) + assertNull(decoded.referenceRomBMm) + assertEquals(2, decoded.triggerWorkingOrdinal) + assertEquals(PowerStopReason.POWER_LOSS, decoded.winnerReason) + assertEquals(true, decoded.shortRomObserved) + assertEquals(true, decoded.powerLossObserved) + } + + /** Measured zeros on one attempt, missing (null) metrics on the attempt-only row. */ + private fun ownEvidence(): PowerLossSetEvidence = PowerLossSetEvidence( + sessionId = SESSION_ID, + setId = "set-1", + metricVersion = 1, + targetMode = TargetMode.POWER, + thresholdPercent = 25, + maxWorkingReps = null, + requireTwoConsecutive = true, + savedNominalReps = 12, + activeCables = setOf(PowerCable.A, PowerCable.B), + activeCableProvenance = "frozen-mask", + referenceWorkingOrdinal = 1, + referenceMcpWatts = 100.5f, + referenceRomAMm = 420.0f, + referenceRomBMm = null, + triggerWorkingOrdinal = 2, + winnerReason = PowerStopReason.POWER_LOSS, + shortRomObserved = true, + powerLossObserved = true, + lossPercentAtDecision = 21.5f, + attempts = listOf( + PowerLossAttemptRecord( + workingConcentricOrdinal = 1, + completed = true, + legacyRepIndex = 0, + mcpWatts = 0.0f, + eccentricPowerWatts = null, + concentricDurationMs = 0L, + eccentricDurationMs = null, + lossPercentAtDecision = 0.0f, + referenceWorkingOrdinal = 1, + romAMm = 0.0f, + romBMm = null, + romAPercentOfReference = 0.0f, + romBPercentOfReference = null, + romTrustworthy = true, + quality = SampleQualityMarkers(stale = true), + shortRom = true, + powerLossQualified = false, + ), + PowerLossAttemptRecord( + workingConcentricOrdinal = 2, + completed = false, + legacyRepIndex = null, + mcpWatts = null, + eccentricPowerWatts = null, + concentricDurationMs = null, + eccentricDurationMs = null, + lossPercentAtDecision = null, + referenceWorkingOrdinal = 2, + romAMm = null, + romBMm = null, + romAPercentOfReference = null, + romBPercentOfReference = null, + romTrustworthy = false, + quality = SampleQualityMarkers(), + shortRom = false, + powerLossQualified = true, + ), + ), + ) + + private fun foreignEvidence(): PowerLossSetEvidence = PowerLossSetEvidence( + sessionId = OTHER_SESSION_ID, + setId = "set-foreign", + metricVersion = 1, + targetMode = TargetMode.REP_TARGET, + thresholdPercent = 20, + maxWorkingReps = 20, + requireTwoConsecutive = false, + savedNominalReps = null, + activeCables = setOf(PowerCable.A), + activeCableProvenance = "frozen-mask", + referenceWorkingOrdinal = null, + referenceMcpWatts = null, + referenceRomAMm = null, + referenceRomBMm = null, + triggerWorkingOrdinal = null, + winnerReason = null, + shortRomObserved = false, + powerLossObserved = false, + lossPercentAtDecision = null, + attempts = emptyList(), + ) + + private companion object { + const val PROFILE_ID = "profile-roundtrip" + const val OTHER_PROFILE_ID = "profile-other" + const val SESSION_ID = "session-roundtrip" + const val OTHER_SESSION_ID = "session-other" + } +} diff --git a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/Android109UpgradeTest.kt b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/Android109UpgradeTest.kt index c5d974088..15db8a77a 100644 --- a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/Android109UpgradeTest.kt +++ b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/Android109UpgradeTest.kt @@ -45,7 +45,7 @@ class Android109UpgradeTest { @Test fun v108Database_upgradesThroughProductionDriver_andReopensWithOldAndNewData() { - assertEquals(66L, PhoenixDatabase.Schema.version, "Revisit this release-specific fixture when the schema advances") + assertEquals(68L, PhoenixDatabase.Schema.version, "Revisit this release-specific fixture when the schema advances") seedReleased108Database() val upgraded = DriverFactory(context).createDriver() @@ -136,7 +136,7 @@ class Android109UpgradeTest { } private fun assertHealthyUpgrade(driver: SqlDriver) { - assertEquals(66L, driver.longValue("PRAGMA user_version")) + assertEquals(68L, driver.longValue("PRAGMA user_version")) assertEquals("ok", driver.textValue("PRAGMA quick_check")) assertEquals(1L, driver.longValue("PRAGMA foreign_keys")) driver.executeQuery(null, "PRAGMA foreign_key_check", { cursor -> diff --git a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/IntervalsMigrationTest.kt b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/IntervalsMigrationTest.kt index 6b71f0237..fdac1a9f4 100644 --- a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/IntervalsMigrationTest.kt +++ b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/IntervalsMigrationTest.kt @@ -420,7 +420,8 @@ class IntervalsMigrationTest { // Schema.version is the version every open validates against; the six // additive tables are what a 64-schema database carries beyond v63. This // fixture pins a v64 database itself, so it stays valid as the schema advances - // (v65 adds RepBiomechanics.aggregateEligible, Issue #1400). + // (v65 adds RepBiomechanics.aggregateEligible, Issue #1400; v66/v67 add the + // issue #1392 power-loss companion and config tables). assertTrue(PhoenixDatabase.Schema.version >= 64L, "Schema must include the v64 Intervals tables") val file = File.createTempFile("intervals-migration-downgrade", ".db") @@ -537,7 +538,7 @@ class IntervalsMigrationTest { // ==================== EXPECTED 63.sqm SHAPE ==================== private companion object { - private const val EXPECTED_SCHEMA_VERSION = 66L + private const val EXPECTED_SCHEMA_VERSION = 68L private val EXPECTED_TABLES: Map> = linkedMapOf( "IntervalsConnection" to linkedMapOf( diff --git a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/SchemaParityTest.kt b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/SchemaParityTest.kt index 8ede41390..da744705a 100644 --- a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/SchemaParityTest.kt +++ b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/SchemaParityTest.kt @@ -1381,7 +1381,7 @@ class SchemaParityTest { // ==================== HELPERS ==================== companion object { - private const val EXPECTED_SCHEMA_VERSION = 66L + private const val EXPECTED_SCHEMA_VERSION = 68L /** * A database built the way every existing user gets it: minimal v1 schema, each diff --git a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/repository/RoutineCsvImportRepositoryTest.kt b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/repository/RoutineCsvImportRepositoryTest.kt index e0bb1a1aa..32d93235c 100644 --- a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/repository/RoutineCsvImportRepositoryTest.kt +++ b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/repository/RoutineCsvImportRepositoryTest.kt @@ -10,6 +10,8 @@ import com.devil.phoenixproject.domain.model.Exercise import com.devil.phoenixproject.domain.model.Routine import com.devil.phoenixproject.domain.model.RoutineExercise import com.devil.phoenixproject.domain.model.RoutineGroup +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.TargetMode import com.devil.phoenixproject.testutil.FakeExerciseRepository import com.devil.phoenixproject.testutil.createTestDatabase import kotlinx.coroutines.flow.first @@ -20,6 +22,7 @@ import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertIs import kotlin.test.assertNotNull +import kotlin.test.assertNull import kotlin.test.assertTrue /** Issue #772: the CSV import commit against real SQLite (foreign keys on). */ @@ -287,6 +290,40 @@ class RoutineCsvImportRepositoryTest { ), ) + @Test + fun powerLossConfigSurvivesSaveReloadAndTheVersion3CsvRoundTrip() = runTest { + val powerConfig = PowerLossConfig( + targetMode = TargetMode.POWER, + thresholdPercent = 25, + maxWorkingReps = 15, + requireTwoConsecutive = true, + savedNominalReps = 12, + ) + val configured = routine("r-power", "Power day").let { base -> + base.copy(exercises = base.exercises.map { it.copy(powerLoss = powerConfig) }) + } + + repository.saveRoutine(configured) + + val stored = repository.getRoutineById("r-power")!! + assertEquals(powerConfig, stored.exercises.single().powerLoss) + + val exported = assertIs(RoutineCsvCodec.encode(stored, null, null)) + assertTrue(exported.content.startsWith("# phoenix_routine_csv_version=3"), "a POWER routine exports as version 3") + val reparsed = assertIs(RoutineCsvCodec.parse(exported.content)).routines.single() + assertEquals(powerConfig, reparsed.exercises.single().powerLoss) + } + + @Test + fun legacyRowsKeepInertRepDefaultsWithNullsNotZeros() = runTest { + repository.saveRoutine(routine("r-legacy", "Legacy day")) + + val stored = repository.getRoutineById("r-legacy")!! + val powerLoss = stored.exercises.single().powerLoss + assertEquals(TargetMode.REP_TARGET, powerLoss.targetMode) + assertNull(powerLoss.savedNominalReps) + } + private companion object { const val HEADER = "routine_id,routine_name,routine_description,group_name,group_order,exercise_id,exercise_name," + "exercise_order,superset_key,superset_name,superset_order,superset_rest_seconds,set_reps,set_weights_kg," + diff --git a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/repository/SqlDelightActiveWorkoutRuntimeRepositoryTest.kt b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/repository/SqlDelightActiveWorkoutRuntimeRepositoryTest.kt index 27ca39526..2327d379d 100644 --- a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/repository/SqlDelightActiveWorkoutRuntimeRepositoryTest.kt +++ b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/repository/SqlDelightActiveWorkoutRuntimeRepositoryTest.kt @@ -22,6 +22,7 @@ import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertNotEquals +import kotlin.test.assertNull import kotlin.test.assertTrue import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Job @@ -639,6 +640,101 @@ class SqlDelightActiveWorkoutRuntimeRepositoryTest { assertEquals(expected, rejected.reason) } + @Test + fun powerLossSnapshotRoundTripsThroughReplaceAndLoad() = runTest { + val snapshot = RestoredPowerLossRuntimeSnapshot( + codecVersion = RestoredPowerLossRuntimeSnapshot.CURRENT_CODEC_VERSION, + targetModeName = "POWER", + thresholdPercent = 25, + maxWorkingReps = 15, + requireTwoConsecutive = true, + savedNominalReps = 12, + baselineMcpWatts = 312.5f, + referenceWorkingOrdinal = 2, + qualifyingStreak = 1, + sealedObservationCount = 3, + expectedObservationCount = 4, + samplesComplete = false, + restartExplanationName = "INCOMPLETE_SAMPLES", + ) + val document = runtime().copy(powerLoss = snapshot) + + repository.replace("profile-a", "routine-session-a", document) + + val loaded = assertIs( + repository.load("profile-a", "routine-session-a"), + ).document + assertEquals(document, loaded) + assertEquals(snapshot, loaded.powerLoss) + } + + @Test + fun legacyDocumentWithoutPowerLossSnapshotLoadsWithAnInertNullSnapshot() = runTest { + // A pre-#1392 document carries no powerLoss key: it decodes with a null + // snapshot (inert REP semantics, nulls — never fabricated zeros). + insertRaw(2, JsonObject(objectJson().filterKeys { it != "powerLoss" })) + + val loaded = assertIs( + repository.load("profile-a", "routine-session-a"), + ) + assertNull(loaded.document.powerLoss) + } + + @Test + fun unknownPowerLossSnapshotCodecVersionIsRejectedAsCorrupt() = runTest { + insertRaw(2, JsonObject(objectJson() + ("powerLoss" to powerLossJson("codecVersion" to JsonPrimitive(99))))) + assertRejected(ActiveWorkoutRuntimeRejection.CORRUPT_JSON) + } + + @Test + fun unknownPowerLossSnapshotTargetEnumIsRejectedAsCorrupt() = runTest { + insertRaw( + 2, + JsonObject(objectJson() + ("powerLoss" to powerLossJson("targetModeName" to JsonPrimitive("FUTURE_MODE")))), + ) + assertRejected(ActiveWorkoutRuntimeRejection.CORRUPT_JSON) + } + + @Test + fun unknownPowerLossRestartExplanationIsRejectedAsCorrupt() = runTest { + insertRaw( + 2, + JsonObject( + objectJson() + ("powerLoss" to powerLossJson("restartExplanationName" to JsonPrimitive("FUTURE"))), + ), + ) + assertRejected(ActiveWorkoutRuntimeRejection.CORRUPT_JSON) + } + + @Test + fun aSupportedPowerLossSnapshotDecodesInsteadOfRejectingTheDocument() = runTest { + insertRaw(2, JsonObject(objectJson() + ("powerLoss" to powerLossJson()))) + val loaded = assertIs( + repository.load("profile-a", "routine-session-a"), + ) + assertEquals("POWER", loaded.document.powerLoss?.targetModeName) + } + + /** A structurally complete powerLoss payload with explicit overrides. */ + private fun powerLossJson(vararg overrides: Pair): JsonObject = JsonObject( + buildMap { + put("codecVersion", JsonPrimitive(1)) + put("targetModeName", JsonPrimitive("POWER")) + put("thresholdPercent", JsonPrimitive(25)) + put("maxWorkingReps", JsonPrimitive(15)) + put("requireTwoConsecutive", JsonPrimitive(false)) + put("savedNominalReps", JsonPrimitive(12)) + put("baselineMcpWatts", JsonPrimitive(300.0)) + put("referenceWorkingOrdinal", JsonPrimitive(2)) + put("qualifyingStreak", JsonPrimitive(1)) + put("sealedObservationCount", JsonPrimitive(2)) + put("expectedObservationCount", JsonPrimitive(3)) + put("samplesComplete", JsonPrimitive(false)) + put("restartExplanationName", JsonPrimitive("INCOMPLETE_SAMPLES")) + overrides.forEach { (key, value) -> put(key, value) } + }, + ) + private fun runtime( profileId: String = "profile-a", routineId: String = "routine-a", diff --git a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/util/DataBackupCompletenessTest.kt b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/util/DataBackupCompletenessTest.kt index 927e622d8..9b0b34bb0 100644 --- a/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/util/DataBackupCompletenessTest.kt +++ b/shared/src/androidHostTest/kotlin/com/devil/phoenixproject/util/DataBackupCompletenessTest.kt @@ -568,6 +568,231 @@ class DataBackupCompletenessTest { // ---- restore sync-state model, every path restore can write ---- + // ── Issue #1392: versioned optional power-loss sections (backup v7) ────── + + @Test + fun `power loss companions and configs ride full streaming and session backups and restore additively`() = runTest { + val source = Fixture(includeRawTelemetry = true) + source.seedProfiles() + source.saveRoutineOn("bench", 0f) + source.saveSession("session-power-1") + seedPowerLossState(source, "session-power-1", "routine-1-re") + + // Full export path. + val exportedJson = source.manager.exportToJson() + val backupData = testJson.decodeFromString(exportedJson) + assertEquals(1, backupData.data.powerLossSetCompanions.size) + assertEquals(1, backupData.data.powerLossObservationCompanions.size) + assertEquals(1, backupData.data.powerLossExerciseConfigs.size) + + // Streaming export path writes the identical sections. + val streamingData = testJson.decodeFromString(File(source.manager.exportToCachePublic()).readText()) + assertEquals(backupData.data.powerLossSetCompanions, streamingData.data.powerLossSetCompanions) + assertEquals(backupData.data.powerLossObservationCompanions, streamingData.data.powerLossObservationCompanions) + assertEquals(backupData.data.powerLossExerciseConfigs, streamingData.data.powerLossExerciseConfigs) + + // Session-scoped path carries the session's companions and its config. + val sessionPath = source.manager.exportSession("session-power-1").getOrThrow() + val sessionData = testJson.decodeFromString(File(sessionPath).readText()) + assertEquals(1, sessionData.data.powerLossSetCompanions.size) + assertEquals(1, sessionData.data.powerLossObservationCompanions.size) + assertEquals(1, sessionData.data.powerLossExerciseConfigs.size) + + // Restore onto a fresh device round-trips rows with nulls preserved — + // a missing metric stays null, never a fabricated zero. + val target = Fixture(includeRawTelemetry = true) + val result = target.manager.importFromJson(exportedJson).getOrThrow() + assertEquals(0, result.entitiesWithErrors) + assertEquals(1, result.powerLossSetCompanionsImported) + assertEquals(1, result.powerLossObservationCompanionsImported) + assertEquals(1, result.powerLossExerciseConfigsImported) + + val restoredSet = target.queries.selectPowerLossSetCompanionsBySession("session-power-1").executeAsList().single() + assertEquals(null, restoredSet.reference_rom_a_mm) + assertEquals(312.5, restoredSet.reference_mcp_watts) + val restoredAttempt = target.queries.selectPowerLossAttemptCompanionsBySession("session-power-1").executeAsList().single() + assertEquals(null, restoredAttempt.mcp_watts) + assertEquals(null, restoredAttempt.legacy_rep_index) + assertEquals(0L, restoredAttempt.completed) + val restoredConfig = target.queries + .selectPowerLossExerciseConfigsByRoutineExerciseIds(listOf("routine-1-re")) + .executeAsList() + .single() + assertEquals("POWER", restoredConfig.target_mode) + assertEquals(12L, restoredConfig.saved_nominal_reps) + + // Restoring the same backup again is idempotent: duplicates are skipped, + // nothing is double-written and nothing local is wiped. + val second = target.manager.importFromJson(exportedJson).getOrThrow() + assertEquals(0, second.entitiesWithErrors) + assertEquals(1, second.powerLossSetCompanionsSkipped) + assertEquals(1, second.powerLossObservationCompanionsSkipped) + assertEquals(1, second.powerLossExerciseConfigsSkipped) + assertEquals(1, target.queries.selectPowerLossSetCompanionsBySession("session-power-1").executeAsList().size) + } + + @Test + fun `power loss summary facts ride without raw telemetry while observation rows require opt in`() = runTest { + val source = Fixture(includeRawTelemetry = false) + source.seedProfiles() + source.saveRoutineOn("bench", 0f) + source.saveSession("session-power-summary") + seedPowerLossState(source, "session-power-summary", "routine-1-re") + + val exported = testJson.decodeFromString(source.manager.exportToJson()) + + // Aggregates/summary facts are retained even when the raw-telemetry + // opt-in is OFF; raw per-attempt rows only ride opted-in exports. + assertEquals(1, exported.data.powerLossSetCompanions.size) + assertEquals(1, exported.data.powerLossExerciseConfigs.size) + assertEquals(0, exported.data.powerLossObservationCompanions.size) + } + + @Test + fun `an old backup without power loss sections preserves local companion and config rows`() = runTest { + val target = Fixture(includeRawTelemetry = true) + target.seedProfiles() + target.saveRoutineOn("bench", 0f) + target.saveSession("session-power-keep") + seedPowerLossState(target, "session-power-keep", "routine-1-re") + + // A pre-#1392 backup of the same device: no power-loss sections at all. + val root = testJson.parseToJsonElement(target.manager.exportToJson()).jsonObject + val strippedData = root.getValue("data").jsonObject - + listOf("powerLossSetCompanions", "powerLossObservationCompanions", "powerLossExerciseConfigs") + val oldJson = JsonObject(root + ("data" to JsonObject(strippedData))).toString() + + val result = target.manager.importFromJson(oldJson).getOrThrow() + + // An absent section is "nothing to add", never a wipe: local rows survive. + assertEquals(0, result.powerLossSetCompanionsImported) + assertEquals(1, target.queries.selectPowerLossSetCompanionsBySession("session-power-keep").executeAsList().size) + assertEquals(1, target.queries.selectPowerLossAttemptCompanionsBySession("session-power-keep").executeAsList().size) + assertEquals( + 1, + target.queries.selectPowerLossExerciseConfigsByRoutineExerciseIds(listOf("routine-1-re")).executeAsList().size, + ) + } + + @Test + fun `power loss restore skips unknown row versions and unknown target enums without arming`() = runTest { + val hostileJson = testJson.encodeToString( + BackupData.serializer(), + BackupData( + version = CURRENT_BACKUP_VERSION, + exportedAt = "2026-11-17T12:00:00Z", + appVersion = "future", + data = BackupContent( + powerLossSetCompanions = listOf( + PowerLossSetCompanionBackup( + formatVersion = 99, + sessionId = "session-x", + setId = "set-x", + targetMode = "POWER", + thresholdPercent = 25, + activeCables = "A,B", + activeCableProvenance = "future", + createdAt = 1L, + ), + ), + powerLossExerciseConfigs = listOf( + PowerLossExerciseConfigBackup( + routineExerciseId = "routine-1-re", + targetMode = "FUTURE_MODE", + thresholdPercent = 25, + updatedAt = 1L, + ), + ), + ), + ), + ) + + val target = Fixture(includeRawTelemetry = true) + target.seedProfiles() + val result = target.manager.importFromJson(hostileJson).getOrThrow() + + // Strict readers fail safe: unknown row versions and unknown target enums + // are skipped with a warning — never crash, never arm POWER. + assertEquals(0, result.entitiesWithErrors) + assertEquals(1, result.powerLossSetCompanionsSkipped) + assertEquals(1, result.powerLossExerciseConfigsSkipped) + assertEquals(0, result.powerLossSetCompanionsImported) + assertEquals(0, result.powerLossExerciseConfigsImported) + } + + private fun seedPowerLossState(fixture: Fixture, sessionId: String, routineExerciseId: String) { + // A completed set links the session to its routine exercise, so the + // session-scoped backup path can scope per-exercise config rows to it. + fixture.queries.insertCompletedSetIgnore( + id = "$sessionId-completed-1", + session_id = sessionId, + planned_set_id = null, + routine_exercise_id = routineExerciseId, + set_number = 0L, + set_type = "STANDARD", + attempt_number = 1L, + actual_reps = 8L, + actual_weight_kg = 40.0, + logged_rpe = null, + is_pr = 0L, + completed_at = 1_700_000_000_000L, + set_end_reason = "POWER_LOSS", + ) + fixture.queries.insertPowerLossSetCompanionIfAbsent( + session_id = sessionId, + set_id = "set-1", + metric_version = 1L, + target_mode = "POWER", + threshold_percent = 25L, + max_working_reps = 15L, + require_two_consecutive = 1L, + saved_nominal_reps = 12L, + active_cables = "A,B", + active_cable_provenance = "rep-metric-load-scan:first-working-attempt", + reference_working_ordinal = 2L, + reference_mcp_watts = 312.5, + reference_rom_a_mm = null, + reference_rom_b_mm = null, + trigger_working_ordinal = 9L, + winner_reason = "POWER_LOSS", + short_rom_observed = 0L, + power_loss_observed = 1L, + loss_percent_at_decision = 21.5, + created_at = 1_700_000_000_000L, + ) + fixture.queries.insertPowerLossAttemptCompanionIfAbsent( + session_id = sessionId, + set_id = "set-1", + working_concentric_ordinal = 9L, + legacy_rep_index = null, + completed = 0L, + mcp_watts = null, + eccentric_power_watts = null, + concentric_duration_ms = null, + eccentric_duration_ms = null, + loss_percent_at_decision = 21.5, + reference_working_ordinal = 2L, + rom_a_mm = null, + rom_b_mm = null, + rom_a_percent_of_reference = null, + rom_b_percent_of_reference = null, + rom_trustworthy = 0L, + quality = "", + short_rom = 0L, + power_loss_qualified = 1L, + ) + fixture.queries.insertPowerLossExerciseConfigIfAbsent( + routine_exercise_id = routineExerciseId, + format_version = 1L, + target_mode = "POWER", + threshold_percent = 25L, + max_working_reps = 15L, + require_two_consecutive = 1L, + saved_nominal_reps = 12L, + updated_at = 1_700_000_000_000L, + ) + } + private data class SyncState(val portalOrigin: Long, val dirty: Boolean, val acknowledgedPush: Boolean, val updatedAt: Long?) private fun Fixture.syncState(id: String): SyncState { diff --git a/shared/src/androidMain/kotlin/com/devil/phoenixproject/presentation/components/HapticFeedbackEffect.android.kt b/shared/src/androidMain/kotlin/com/devil/phoenixproject/presentation/components/HapticFeedbackEffect.android.kt index 59e41926c..3b8953056 100644 --- a/shared/src/androidMain/kotlin/com/devil/phoenixproject/presentation/components/HapticFeedbackEffect.android.kt +++ b/shared/src/androidMain/kotlin/com/devil/phoenixproject/presentation/components/HapticFeedbackEffect.android.kt @@ -259,6 +259,8 @@ private object AndroidCueResources { HapticEvent.DOMINATRIX_MODE_UNLOCKED to dominatrixUnlock, // Issue #611 HapticEvent.WARMUP_TO_WORKING to beepBoop, HapticEvent.VELOCITY_THRESHOLD_REACHED to boopBeepBeep, + // Issue #1392: power-loss near-limit cue (reuses existing beepboop asset) + HapticEvent.POWER_NEAR_LIMIT to beepBoop, ) val badgeCues: List = listOf( @@ -529,6 +531,16 @@ private fun playHapticFeedback(vibrator: Vibrator, event: HapticEvent) { ) } + // Issue #1392: power-loss near-limit cue — double medium pulse, distinct + // from the velocity-threshold alert's double heavy pulse. + is HapticEvent.POWER_NEAR_LIMIT -> { + VibrationEffect.createWaveform( + longArrayOf(0, 90, 60, 130), + intArrayOf(0, 160, 0, 190), + -1, + ) + } + is HapticEvent.COUNTDOWN_TICK -> { // Very light tick for rest countdown (last 10 seconds) VibrationEffect.createOneShot(30, 80) diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/export/PowerHistoryExportCodec.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/export/PowerHistoryExportCodec.kt new file mode 100644 index 000000000..3e2c1575a --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/export/PowerHistoryExportCodec.kt @@ -0,0 +1,255 @@ +package com.devil.phoenixproject.data.export + +import com.devil.phoenixproject.domain.powerloss.PowerCable +import com.devil.phoenixproject.domain.powerloss.PowerLossAttemptRecord +import com.devil.phoenixproject.domain.powerloss.PowerLossSetEvidence +import com.devil.phoenixproject.domain.powerloss.PowerStopReason +import com.devil.phoenixproject.domain.powerloss.SampleQualityMarkers +import com.devil.phoenixproject.domain.powerloss.TargetMode +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonArray +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive + +/** + * Issue #1392 (packet P4) — power-history export v1 codec. + * + * Versioned, separately identified document (`documentType` + `version: 1`) over the + * frozen evidence contract in `domain/powerloss/PowerLossEvidence.kt`: + * + * - stable session/set IDs and per-attempt `(session, workingConcentric ordinal)` identity + * including pending/attempt-only rows (`completed: false`), + * - frozen target configuration + `metricVersion`, + * - reference-at-decision / trigger / winner facts and BOTH qualification facts (SD2), + * - explicit units (watts / millimeters / milliseconds / percent) and explicit + * null-vs-zero semantics: MISSING data serializes as JSON `null` (or an empty + * array where a list is absent) and is never fabricated as 0. A serialized `0` + * is a measured zero. + * + * [decode] is the import side of the roundtrip contract (P4 acceptance: + * "power-history export roundtrips preserving null/zero/identity"). + */ +internal object PowerHistoryExportCodec { + + internal const val DOCUMENT_TYPE: String = "power-history-export" + internal const val VERSION: Int = 1 + + private val json = Json { prettyPrint = true } + + /** One session's exported evidence (sets in export order). */ + internal data class SessionExport( + val sessionId: String, + val sets: List, + ) + + /** Decoded power-history export v1 document. */ + internal data class Document( + val version: Int, + val profileId: String, + val exportedAtMs: Long, + val sessions: List, + ) + + internal fun encode(profileId: String, exportedAtMs: Long, sessions: List): String = + json.encodeToString( + JsonElement.serializer(), + buildJsonObject { + put("documentType", JsonPrimitive(DOCUMENT_TYPE)) + put("version", JsonPrimitive(VERSION)) + put("units", buildJsonObject { + put("power", JsonPrimitive("watts")) + put("rom", JsonPrimitive("millimeters")) + put("duration", JsonPrimitive("milliseconds")) + put("lossPercent", JsonPrimitive("percent")) + put("timestamp", JsonPrimitive("epochMilliseconds")) + }) + put( + "nullSemantics", + JsonPrimitive( + "Missing data is serialized as null (or an empty array) and never as 0; " + + "a serialized 0 is a measured zero.", + ), + ) + put("profileId", JsonPrimitive(profileId)) + put("exportedAtMs", JsonPrimitive(exportedAtMs)) + put("sessions", buildJsonArray { + for (session in sessions) add(encodeSession(session)) + }) + }, + ) + + internal fun decode(content: String): Document { + val root = json.parseToJsonElement(content).jsonObject + require(root.string("documentType") == DOCUMENT_TYPE) { "not a power-history export document" } + val version = root.int("version") + require(version == VERSION) { "unsupported power-history export version $version" } + return Document( + version = version, + profileId = root.string("profileId"), + exportedAtMs = root.long("exportedAtMs"), + sessions = root.array("sessions").map { decodeSession(it.jsonObject) }, + ) + } + + private fun encodeSession(session: SessionExport): JsonElement = buildJsonObject { + put("sessionId", JsonPrimitive(session.sessionId)) + put("sets", buildJsonArray { for (set in session.sets) add(encodeSet(set)) }) + } + + private fun decodeSession(obj: JsonObject): SessionExport = SessionExport( + sessionId = obj.string("sessionId"), + sets = obj.array("sets").map { decodeSet(it.jsonObject) }, + ) + + private fun encodeSet(set: PowerLossSetEvidence): JsonElement = buildJsonObject { + put("sessionId", JsonPrimitive(set.sessionId)) + put("setId", JsonPrimitive(set.setId)) + put("metricVersion", JsonPrimitive(set.metricVersion)) + put("targetConfig", buildJsonObject { + put("targetMode", JsonPrimitive(set.targetMode.name)) + put("thresholdPercent", JsonPrimitive(set.thresholdPercent)) + put("maxWorkingReps", intOrNull(set.maxWorkingReps)) + put("requireTwoConsecutive", JsonPrimitive(set.requireTwoConsecutive)) + put("savedNominalReps", intOrNull(set.savedNominalReps)) + put("activeCables", buildJsonArray { + for (cable in set.activeCables.sortedBy { it.name }) add(JsonPrimitive(cable.name)) + }) + put("activeCableProvenance", JsonPrimitive(set.activeCableProvenance)) + }) + put("reference", buildJsonObject { + put("workingOrdinal", intOrNull(set.referenceWorkingOrdinal)) + put("mcpWatts", floatOrNull(set.referenceMcpWatts)) + put("romAMm", floatOrNull(set.referenceRomAMm)) + put("romBMm", floatOrNull(set.referenceRomBMm)) + }) + put("trigger", buildJsonObject { + put("workingOrdinal", intOrNull(set.triggerWorkingOrdinal)) + }) + put("winner", buildJsonObject { + put("reason", set.winnerReason?.let { JsonPrimitive(it.name) } ?: JsonNull) + }) + put("qualification", buildJsonObject { + put("shortRomObserved", JsonPrimitive(set.shortRomObserved)) + put("powerLossObserved", JsonPrimitive(set.powerLossObserved)) + put("lossPercentAtDecision", floatOrNull(set.lossPercentAtDecision)) + }) + put("attempts", buildJsonArray { for (attempt in set.attempts) add(encodeAttempt(attempt)) }) + } + + private fun decodeSet(obj: JsonObject): PowerLossSetEvidence { + val target = obj.obj("targetConfig") + val reference = obj.obj("reference") + val trigger = obj.obj("trigger") + val winner = obj.obj("winner") + val qualification = obj.obj("qualification") + return PowerLossSetEvidence( + sessionId = obj.string("sessionId"), + setId = obj.string("setId"), + metricVersion = obj.int("metricVersion"), + targetMode = TargetMode.fromPersisted(target.string("targetMode")) + ?: error("unknown target mode '${target.string("targetMode")}'"), + thresholdPercent = target.int("thresholdPercent"), + maxWorkingReps = target.intOrNull("maxWorkingReps"), + requireTwoConsecutive = target.bool("requireTwoConsecutive"), + savedNominalReps = target.intOrNull("savedNominalReps"), + activeCables = target.array("activeCables").map { element -> + PowerCable.entries.firstOrNull { it.name == element.jsonPrimitive.content } + ?: error("unknown power cable '${element.jsonPrimitive.content}'") + }.toSet(), + activeCableProvenance = target.string("activeCableProvenance"), + referenceWorkingOrdinal = reference.intOrNull("workingOrdinal"), + referenceMcpWatts = reference.floatOrNull("mcpWatts"), + referenceRomAMm = reference.floatOrNull("romAMm"), + referenceRomBMm = reference.floatOrNull("romBMm"), + triggerWorkingOrdinal = trigger.intOrNull("workingOrdinal"), + winnerReason = winner.stringOrNull("reason")?.let { reason -> + PowerStopReason.entries.firstOrNull { it.name == reason } + ?: error("unknown winner reason '$reason'") + }, + shortRomObserved = qualification.bool("shortRomObserved"), + powerLossObserved = qualification.bool("powerLossObserved"), + lossPercentAtDecision = qualification.floatOrNull("lossPercentAtDecision"), + attempts = obj.array("attempts").map { decodeAttempt(it.jsonObject) }, + ) + } + + private fun encodeAttempt(attempt: PowerLossAttemptRecord): JsonElement = buildJsonObject { + put("workingConcentricOrdinal", JsonPrimitive(attempt.workingConcentricOrdinal)) + put("completed", JsonPrimitive(attempt.completed)) + put("legacyRepIndex", intOrNull(attempt.legacyRepIndex)) + put("mcpWatts", floatOrNull(attempt.mcpWatts)) + put("eccentricPowerWatts", floatOrNull(attempt.eccentricPowerWatts)) + put("concentricDurationMs", longOrNull(attempt.concentricDurationMs)) + put("eccentricDurationMs", longOrNull(attempt.eccentricDurationMs)) + put("lossPercentAtDecision", floatOrNull(attempt.lossPercentAtDecision)) + put("referenceWorkingOrdinal", intOrNull(attempt.referenceWorkingOrdinal)) + put("romAMm", floatOrNull(attempt.romAMm)) + put("romBMm", floatOrNull(attempt.romBMm)) + put("romAPercentOfReference", floatOrNull(attempt.romAPercentOfReference)) + put("romBPercentOfReference", floatOrNull(attempt.romBPercentOfReference)) + put("romTrustworthy", JsonPrimitive(attempt.romTrustworthy)) + put("quality", buildJsonObject { + put("clamped", JsonPrimitive(attempt.quality.clamped)) + put("rejected", JsonPrimitive(attempt.quality.rejected)) + put("stale", JsonPrimitive(attempt.quality.stale)) + put("gapBefore", JsonPrimitive(attempt.quality.gapBefore)) + }) + put("shortRom", JsonPrimitive(attempt.shortRom)) + put("powerLossQualified", JsonPrimitive(attempt.powerLossQualified)) + } + + private fun decodeAttempt(obj: JsonObject): PowerLossAttemptRecord { + val quality = obj.obj("quality") + return PowerLossAttemptRecord( + workingConcentricOrdinal = obj.int("workingConcentricOrdinal"), + completed = obj.bool("completed"), + legacyRepIndex = obj.intOrNull("legacyRepIndex"), + mcpWatts = obj.floatOrNull("mcpWatts"), + eccentricPowerWatts = obj.floatOrNull("eccentricPowerWatts"), + concentricDurationMs = obj.longOrNull("concentricDurationMs"), + eccentricDurationMs = obj.longOrNull("eccentricDurationMs"), + lossPercentAtDecision = obj.floatOrNull("lossPercentAtDecision"), + referenceWorkingOrdinal = obj.intOrNull("referenceWorkingOrdinal"), + romAMm = obj.floatOrNull("romAMm"), + romBMm = obj.floatOrNull("romBMm"), + romAPercentOfReference = obj.floatOrNull("romAPercentOfReference"), + romBPercentOfReference = obj.floatOrNull("romBPercentOfReference"), + romTrustworthy = obj.bool("romTrustworthy"), + quality = SampleQualityMarkers( + clamped = quality.bool("clamped"), + rejected = quality.bool("rejected"), + stale = quality.bool("stale"), + gapBefore = quality.bool("gapBefore"), + ), + shortRom = obj.bool("shortRom"), + powerLossQualified = obj.bool("powerLossQualified"), + ) + } + + private fun intOrNull(value: Int?): JsonElement = value?.let { JsonPrimitive(it) } ?: JsonNull + private fun longOrNull(value: Long?): JsonElement = value?.let { JsonPrimitive(it) } ?: JsonNull + + /** Float widens to a JSON double; the Double→Float narrowing on decode is exact. */ + private fun floatOrNull(value: Float?): JsonElement = value?.let { JsonPrimitive(it.toDouble()) } ?: JsonNull + + private fun JsonObject.obj(key: String): JsonObject = getValue(key).jsonObject + private fun JsonObject.array(key: String): List = (getValue(key) as JsonArray).toList() + + private fun JsonObject.string(key: String): String = getValue(key).jsonPrimitive.content + + private fun JsonObject.stringOrNull(key: String): String? = + (get(key) as? JsonPrimitive)?.takeIf { it !is JsonNull }?.content + + private fun JsonObject.int(key: String): Int = string(key).toInt() + private fun JsonObject.intOrNull(key: String): Int? = stringOrNull(key)?.toInt() + private fun JsonObject.long(key: String): Long = string(key).toLong() + private fun JsonObject.longOrNull(key: String): Long? = stringOrNull(key)?.toLong() + private fun JsonObject.floatOrNull(key: String): Float? = stringOrNull(key)?.toDouble()?.toFloat() + private fun JsonObject.bool(key: String): Boolean = string(key).toBooleanStrict() +} diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/export/PowerHistoryExporter.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/export/PowerHistoryExporter.kt new file mode 100644 index 000000000..26d8b4ff3 --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/export/PowerHistoryExporter.kt @@ -0,0 +1,28 @@ +package com.devil.phoenixproject.data.export + +/** + * Issue #1392 — frozen power-history export v1 facade (P4 implements, P5 UI calls). + * + * P4 owns `PowerHistoryExporterImpl` (SQLDelight reads + versioned codec + Koin + * registration). P5 wires the `Export power data` UI entry to this interface only. + * + * Export v1 contract (implementation-spec.md P4): separately identified version, + * stable IDs, attempt/completed identity, frozen config, metric version, + * reference/trigger/winner facts, nullable metrics/quality, units, and explicit + * null-vs-zero semantics. Missing data is null — never a fabricated zero. + */ +interface PowerHistoryExporter { + /** + * Export the profile's persisted power-loss evidence as the versioned + * power-history document (v1). Returns the produced document's display name + * and content; the caller owns share/save UX. + */ + suspend fun exportPowerData(profileId: String): PowerHistoryExportResult +} + +/** Result of a power-history export v1 run. [content] is the versioned document body. */ +data class PowerHistoryExportResult( + val displayName: String, + val content: String, + val version: Int, +) diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/export/PowerHistoryExporterImpl.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/export/PowerHistoryExporterImpl.kt new file mode 100644 index 000000000..1eb3e26ef --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/export/PowerHistoryExporterImpl.kt @@ -0,0 +1,55 @@ +package com.devil.phoenixproject.data.export + +import com.devil.phoenixproject.data.repository.PowerLossCompanionStore +import com.devil.phoenixproject.database.PhoenixDatabase +import com.devil.phoenixproject.domain.model.currentTimeMillis +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.IO +import kotlinx.coroutines.withContext + +/** + * Issue #1392 (packet P4) — power-history export v1. + * + * Exports the profile's persisted power-loss evidence + * (`PowerLossSetCompanion` + `PowerLossAttemptCompanion`, tier 1) as the versioned + * power-history document via [PowerHistoryExportCodec]. Contract: + * + * - separately identified document (`documentType`, `version: 1`) with stable + * session/set IDs and per-attempt identity (attempt-only rows included), + * - frozen target config + `metricVersion`, reference/trigger/winner facts and + * BOTH qualification facts, + * - explicit units and null-vs-zero semantics: missing data is null/empty, + * never a fabricated 0, + * - profile-scoped: only sessions owned by [PowerHistoryExporter.exportPowerData]'s + * profileId are exported; sessions without evidence are omitted (empty, not zeroed). + * + * No wire semantics: this document is a local share/save artifact only + * (legacy portal payloads stay unchanged). + */ +class PowerHistoryExporterImpl( + private val database: PhoenixDatabase, +) : PowerHistoryExporter { + + override suspend fun exportPowerData(profileId: String): PowerHistoryExportResult = + withContext(Dispatchers.IO) { + val queries = database.phoenixDatabaseQueries + val sessions = queries.selectAllSessions(profileId).executeAsList().mapNotNull { row -> + val evidence = PowerLossCompanionStore.readEvidence(queries, row.id) + if (evidence.isEmpty()) { + null + } else { + PowerHistoryExportCodec.SessionExport(sessionId = row.id, sets = evidence) + } + } + val content = PowerHistoryExportCodec.encode( + profileId = profileId, + exportedAtMs = currentTimeMillis(), + sessions = sessions, + ) + PowerHistoryExportResult( + displayName = "power-history-v1-$profileId.json", + content = content, + version = PowerHistoryExportCodec.VERSION, + ) + } +} diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/local/MigrationStatements.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/local/MigrationStatements.kt index 67f5a23bc..5df6bc847 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/local/MigrationStatements.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/local/MigrationStatements.kt @@ -1517,6 +1517,78 @@ WHERE gs.rowid = ( )""", ) + // Migration 66: power-loss autostop durable companions (issue #1392, packet P4). + // Additive only (SQLite API-26). Attempt rows carry no FK to RepMetric so the + // completion commit's rep-row replacement can never cascade them away. + 66 -> listOf( + """CREATE TABLE IF NOT EXISTS PowerLossSetCompanion ( + session_id TEXT NOT NULL, + set_id TEXT NOT NULL, + metric_version INTEGER NOT NULL DEFAULT 1, + target_mode TEXT NOT NULL, + threshold_percent INTEGER NOT NULL, + max_working_reps INTEGER, + require_two_consecutive INTEGER NOT NULL DEFAULT 0 CHECK(require_two_consecutive IN (0, 1)), + saved_nominal_reps INTEGER, + active_cables TEXT NOT NULL, + active_cable_provenance TEXT NOT NULL, + reference_working_ordinal INTEGER, + reference_mcp_watts REAL, + reference_rom_a_mm REAL, + reference_rom_b_mm REAL, + trigger_working_ordinal INTEGER, + winner_reason TEXT, + short_rom_observed INTEGER NOT NULL DEFAULT 0 CHECK(short_rom_observed IN (0, 1)), + power_loss_observed INTEGER NOT NULL DEFAULT 0 CHECK(power_loss_observed IN (0, 1)), + loss_percent_at_decision REAL, + created_at INTEGER NOT NULL, + PRIMARY KEY (session_id, set_id), + FOREIGN KEY (session_id) REFERENCES WorkoutSession(id) ON DELETE CASCADE + )""", + "CREATE INDEX IF NOT EXISTS idx_power_loss_set_session ON PowerLossSetCompanion(session_id)", + """CREATE TABLE IF NOT EXISTS PowerLossAttemptCompanion ( + session_id TEXT NOT NULL, + set_id TEXT NOT NULL, + working_concentric_ordinal INTEGER NOT NULL, + legacy_rep_index INTEGER, + completed INTEGER NOT NULL DEFAULT 0 CHECK(completed IN (0, 1)), + mcp_watts REAL, + eccentric_power_watts REAL, + concentric_duration_ms INTEGER, + eccentric_duration_ms INTEGER, + loss_percent_at_decision REAL, + reference_working_ordinal INTEGER, + rom_a_mm REAL, + rom_b_mm REAL, + rom_a_percent_of_reference REAL, + rom_b_percent_of_reference REAL, + rom_trustworthy INTEGER NOT NULL DEFAULT 0 CHECK(rom_trustworthy IN (0, 1)), + quality TEXT NOT NULL DEFAULT '', + short_rom INTEGER NOT NULL DEFAULT 0 CHECK(short_rom IN (0, 1)), + power_loss_qualified INTEGER NOT NULL DEFAULT 0 CHECK(power_loss_qualified IN (0, 1)), + PRIMARY KEY (session_id, working_concentric_ordinal), + FOREIGN KEY (session_id) REFERENCES WorkoutSession(id) ON DELETE CASCADE + )""", + "CREATE INDEX IF NOT EXISTS idx_power_loss_attempt_session_set ON PowerLossAttemptCompanion(session_id, set_id)", + ) + + // Migration 67: per-exercise power-loss target config (issue #1392, packet P4 + // remainder). Additive only (SQLite API-26). Absent row = inert REP_TARGET + // defaults with NULLs — never fabricated zeros. Local-only config: no wire keys. + 67 -> listOf( + """CREATE TABLE IF NOT EXISTS PowerLossExerciseConfig ( + routine_exercise_id TEXT NOT NULL PRIMARY KEY, + format_version INTEGER NOT NULL DEFAULT 1, + target_mode TEXT NOT NULL, + threshold_percent INTEGER NOT NULL, + max_working_reps INTEGER, + require_two_consecutive INTEGER NOT NULL DEFAULT 0 CHECK(require_two_consecutive IN (0, 1)), + saved_nominal_reps INTEGER, + updated_at INTEGER NOT NULL, + FOREIGN KEY (routine_exercise_id) REFERENCES RoutineExercise(id) ON DELETE CASCADE + )""", + ) + // Migration 64: Issue #1400 per-rep aggregate eligibility (calibration/ramp reps) and the // 0-100 set velocity-loss clamp for legacy rows. Mirrors 64.sqm exactly; the column is // additive (legacy rows default to eligible) and the UPDATE is idempotent on replay. diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/local/SchemaManifest.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/local/SchemaManifest.kt index f209e9fba..7ca932b2e 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/local/SchemaManifest.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/local/SchemaManifest.kt @@ -1867,6 +1867,88 @@ internal val manifestTables: List = listOf( ) """.trimIndent(), ), + + // Issue #1392 (packet P4, migration 64.sqm): power-loss autostop durable + // companions. Additive nullable companions; legacy rows keep REP semantics + // with NULL new metrics (never zeros). Attempt rows carry no FK to RepMetric + // so completion rep-row replacement can never cascade them away. + SchemaTableOperation( + table = "PowerLossSetCompanion", + createSql = """ + CREATE TABLE IF NOT EXISTS PowerLossSetCompanion ( + session_id TEXT NOT NULL, + set_id TEXT NOT NULL, + metric_version INTEGER NOT NULL DEFAULT 1, + target_mode TEXT NOT NULL, + threshold_percent INTEGER NOT NULL, + max_working_reps INTEGER, + require_two_consecutive INTEGER NOT NULL DEFAULT 0 CHECK(require_two_consecutive IN (0, 1)), + saved_nominal_reps INTEGER, + active_cables TEXT NOT NULL, + active_cable_provenance TEXT NOT NULL, + reference_working_ordinal INTEGER, + reference_mcp_watts REAL, + reference_rom_a_mm REAL, + reference_rom_b_mm REAL, + trigger_working_ordinal INTEGER, + winner_reason TEXT, + short_rom_observed INTEGER NOT NULL DEFAULT 0 CHECK(short_rom_observed IN (0, 1)), + power_loss_observed INTEGER NOT NULL DEFAULT 0 CHECK(power_loss_observed IN (0, 1)), + loss_percent_at_decision REAL, + created_at INTEGER NOT NULL, + PRIMARY KEY (session_id, set_id), + FOREIGN KEY (session_id) REFERENCES WorkoutSession(id) ON DELETE CASCADE + ) + """.trimIndent(), + ), + SchemaTableOperation( + table = "PowerLossAttemptCompanion", + createSql = """ + CREATE TABLE IF NOT EXISTS PowerLossAttemptCompanion ( + session_id TEXT NOT NULL, + set_id TEXT NOT NULL, + working_concentric_ordinal INTEGER NOT NULL, + legacy_rep_index INTEGER, + completed INTEGER NOT NULL DEFAULT 0 CHECK(completed IN (0, 1)), + mcp_watts REAL, + eccentric_power_watts REAL, + concentric_duration_ms INTEGER, + eccentric_duration_ms INTEGER, + loss_percent_at_decision REAL, + reference_working_ordinal INTEGER, + rom_a_mm REAL, + rom_b_mm REAL, + rom_a_percent_of_reference REAL, + rom_b_percent_of_reference REAL, + rom_trustworthy INTEGER NOT NULL DEFAULT 0 CHECK(rom_trustworthy IN (0, 1)), + quality TEXT NOT NULL DEFAULT '', + short_rom INTEGER NOT NULL DEFAULT 0 CHECK(short_rom IN (0, 1)), + power_loss_qualified INTEGER NOT NULL DEFAULT 0 CHECK(power_loss_qualified IN (0, 1)), + PRIMARY KEY (session_id, working_concentric_ordinal), + FOREIGN KEY (session_id) REFERENCES WorkoutSession(id) ON DELETE CASCADE + ) + """.trimIndent(), + ), + + // Issue #1392 (packet P4 remainder, migration 65.sqm): per-exercise + // power-loss target config. Absent row = inert REP_TARGET defaults with + // NULLs — never fabricated zeros. Local-only: no sync wire semantics. + SchemaTableOperation( + table = "PowerLossExerciseConfig", + createSql = """ + CREATE TABLE IF NOT EXISTS PowerLossExerciseConfig ( + routine_exercise_id TEXT NOT NULL PRIMARY KEY, + format_version INTEGER NOT NULL DEFAULT 1, + target_mode TEXT NOT NULL, + threshold_percent INTEGER NOT NULL, + max_working_reps INTEGER, + require_two_consecutive INTEGER NOT NULL DEFAULT 0 CHECK(require_two_consecutive IN (0, 1)), + saved_nominal_reps INTEGER, + updated_at INTEGER NOT NULL, + FOREIGN KEY (routine_exercise_id) REFERENCES RoutineExercise(id) ON DELETE CASCADE + ) + """.trimIndent(), + ), ) // ============================================================ @@ -2525,4 +2607,8 @@ internal val manifestIndexes: List = listOf( SchemaIndexOperation("idx_completion_receipt_external", "CREATE INDEX IF NOT EXISTS idx_completion_receipt_external ON WorkoutCompletionReceipt(external_id)"), SchemaIndexOperation("idx_intervals_outbox_due", "CREATE INDEX IF NOT EXISTS idx_intervals_outbox_due ON IntervalsOutbox(state, next_attempt_at)"), SchemaIndexOperation("idx_intervals_outbox_lease", "CREATE INDEX IF NOT EXISTS idx_intervals_outbox_lease ON IntervalsOutbox(state, lease_expires_at)"), + + // ── Power-loss companions (issue #1392, migration 64.sqm) ────────── + SchemaIndexOperation("idx_power_loss_set_session", "CREATE INDEX IF NOT EXISTS idx_power_loss_set_session ON PowerLossSetCompanion(session_id)"), + SchemaIndexOperation("idx_power_loss_attempt_session_set", "CREATE INDEX IF NOT EXISTS idx_power_loss_attempt_session_set ON PowerLossAttemptCompanion(session_id, set_id)"), ) diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/ActiveWorkoutRuntimeRepository.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/ActiveWorkoutRuntimeRepository.kt index 16d791ab7..596894ad1 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/ActiveWorkoutRuntimeRepository.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/ActiveWorkoutRuntimeRepository.kt @@ -11,6 +11,7 @@ import com.devil.phoenixproject.domain.model.RoutineExecutionIdentity import com.devil.phoenixproject.domain.model.SetEndReason import com.devil.phoenixproject.domain.model.SetType import com.devil.phoenixproject.domain.model.WorkoutParameters +import com.devil.phoenixproject.domain.powerloss.TargetMode import com.devil.phoenixproject.presentation.manager.RestTransitionPlan import kotlinx.serialization.Serializable @@ -36,6 +37,15 @@ data class RestoredWorkoutCommandTemplateSnapshot( val echoLevelName: String, val eccentricLoadName: String, val justLiftRestSeconds: Int, + // Issue #1392 — frozen power-loss target config, persisted as names/ints. + // Read strictly: an unknown target-mode name resolves to inert REP_TARGET — + // POWER never arms from an unknown or excluded mode. Old documents decode + // with these defaults (REP), preserving their legacy meaning. + val powerLossTargetModeName: String = "REP_TARGET", + val powerLossThresholdPercent: Int = 20, + val powerLossMaxWorkingReps: Int = 20, + val powerLossRequireTwoConsecutive: Boolean = false, + val powerLossSavedNominalReps: Int? = null, ) { init { require(programModeName in PROGRAM_MODE_NAMES) @@ -77,6 +87,15 @@ data class RestoredWorkoutCommandTemplateSnapshot( echoLevel = EchoLevel.valueOf(echoLevelName), eccentricLoad = EccentricLoad.valueOf(eccentricLoadName), justLiftRestSeconds = justLiftRestSeconds, + // Issue #1392: strict persisted-enum read — unknown target-mode names + // resolve to inert REP_TARGET (P5 propagation seam). + powerLoss = com.devil.phoenixproject.presentation.powerloss.powerLossConfigFromPersisted( + persistedTargetMode = powerLossTargetModeName, + thresholdPercent = powerLossThresholdPercent, + maxWorkingReps = powerLossMaxWorkingReps, + requireTwoConsecutive = powerLossRequireTwoConsecutive, + savedNominalReps = powerLossSavedNominalReps, + ), ) companion object { @@ -101,6 +120,13 @@ data class RestoredWorkoutCommandTemplateSnapshot( echoLevelName = parameters.echoLevel.name, eccentricLoadName = parameters.eccentricLoad.name, justLiftRestSeconds = parameters.justLiftRestSeconds, + // Issue #1392: the frozen power-loss target config round-trips through + // the runtime snapshot (local-only; never synced). + powerLossTargetModeName = parameters.powerLoss.targetMode.name, + powerLossThresholdPercent = parameters.powerLoss.thresholdPercent, + powerLossMaxWorkingReps = parameters.powerLoss.maxWorkingReps, + powerLossRequireTwoConsecutive = parameters.powerLoss.requireTwoConsecutive, + powerLossSavedNominalReps = parameters.powerLoss.savedNominalReps, ) } } @@ -175,6 +201,121 @@ private val PROGRAM_MODE_NAMES = setOf( "ECHO", ) +/** + * Issue #1392 (packet P4 remainder) — versioned power-loss runtime snapshot. + * + * Carried inside [ActiveWorkoutRuntimeDocument] (its own explicit codec version + * on top of the document's). STRICT READER: an unknown [codecVersion], unknown + * target enum, or unknown restart-explanation enum throws in `init`, so the + * strict runtime codec rejects the whole document (CORRUPT_JSON) — an unknown + * value must never coerce into active behavior and must never arm POWER + * (spec §7). Absent snapshot = inert (REP semantics, nulls — never zeros). + * + * The snapshot exists to carry the explanatory UX state across restart; the + * armed policy itself is NEVER resumed from it (see [PowerLossRestartRecovery]): + * the accumulator/baseline/streak are always rebaselined, and restoring never + * issues machine commands. + */ +@Serializable +data class RestoredPowerLossRuntimeSnapshot( + val codecVersion: Int = CURRENT_CODEC_VERSION, + /** [TargetMode] constant name; strict. */ + val targetModeName: String = TargetMode.REP_TARGET.name, + val thresholdPercent: Int = 0, + val maxWorkingReps: Int = 0, + val requireTwoConsecutive: Boolean = false, + /** Absent nominal stays null — never a fabricated zero. */ + val savedNominalReps: Int? = null, + /** Reducer baseline (best valid working rep) at teardown; null = no baseline. */ + val baselineMcpWatts: Float? = null, + val referenceWorkingOrdinal: Int? = null, + /** Two-consecutive qualifying streak at teardown. */ + val qualifyingStreak: Int = 0, + /** Sealed observations consumed by the accumulator at teardown. */ + val sealedObservationCount: Int = 0, + /** Observations the set expected; incomplete sums explain the rebaseline. */ + val expectedObservationCount: Int = 0, + /** True only when the sample stream was verifiably complete at teardown. */ + val samplesComplete: Boolean = false, + /** [PowerLossRestartExplanation] constant name; the explanatory UX state. */ + val restartExplanationName: String = PowerLossRestartExplanation.INCOMPLETE_SAMPLES.name, +) { + init { + require(codecVersion == CURRENT_CODEC_VERSION) { + "Unsupported power-loss runtime snapshot codec version $codecVersion" + } + require(targetModeName in TargetMode.entries.map { it.name }) { + "Unknown power-loss target mode '$targetModeName'" + } + require(restartExplanationName in PowerLossRestartExplanation.entries.map { it.name }) { + "Unknown power-loss restart explanation '$restartExplanationName'" + } + require(thresholdPercent >= 0 && maxWorkingReps >= 0) + require(qualifyingStreak >= 0 && sealedObservationCount >= 0 && expectedObservationCount >= 0) + require(savedNominalReps == null || savedNominalReps >= 1) + } + + companion object { + const val CURRENT_CODEC_VERSION: Int = 1 + } +} + +/** Explanatory UX state carried by [RestoredPowerLossRuntimeSnapshot]. */ +enum class PowerLossRestartExplanation { + /** No power-loss runtime state was persisted (legacy/REP runtime). */ + NO_SNAPSHOT, + + /** The set was interrupted mid-flight; its sample stream cannot continue. */ + INTERRUPTED_MID_SET, + + /** The snapshot's power-loss samples were incomplete at restart. */ + INCOMPLETE_SAMPLES, +} + +/** + * The restart/rebaseline outcome shown in UX: never armed, with which parts of + * the policy state were reset and why. + */ +data class PowerLossRestartRecoveryState( + /** ALWAYS false: an armed policy never resumes across a restart. */ + val resumeArmed: Boolean, + val baselineReset: Boolean, + val streakReset: Boolean, + val accumulatorReset: Boolean, + val explanation: PowerLossRestartExplanation, +) + +/** + * Issue #1392 restart/rebaseline contract (spec §7): on restart with incomplete + * power-loss samples the armed policy must NEVER resume. The accumulator, + * baseline and streak are reset (rebaseline) and the explanatory UX state comes + * from the snapshot. Restoring issues NO machine commands — this object is pure. + */ +object PowerLossRestartRecovery { + fun rebaselineOnRestart(snapshot: RestoredPowerLossRuntimeSnapshot?): PowerLossRestartRecoveryState { + if (snapshot == null) { + return PowerLossRestartRecoveryState( + resumeArmed = false, + baselineReset = false, + streakReset = false, + accumulatorReset = false, + explanation = PowerLossRestartExplanation.NO_SNAPSHOT, + ) + } + return PowerLossRestartRecoveryState( + resumeArmed = false, + baselineReset = snapshot.baselineMcpWatts != null || snapshot.referenceWorkingOrdinal != null, + streakReset = snapshot.qualifyingStreak > 0, + accumulatorReset = snapshot.sealedObservationCount > 0, + explanation = if (snapshot.samplesComplete) { + PowerLossRestartExplanation.INTERRUPTED_MID_SET + } else { + PowerLossRestartExplanation.INCOMPLETE_SAMPLES + }, + ) + } +} + fun ProgramMode.toSnapshotName(): String = when (this) { ProgramMode.OldSchool -> "OLD_SCHOOL" ProgramMode.Pump -> "PUMP" @@ -217,6 +358,13 @@ data class ActiveWorkoutRuntimeDocument( val pausedRestRemainingSeconds: Int? = null, val isRestPaused: Boolean = false, val originalRestDurationSeconds: Int, + /** + * Issue #1392: versioned power-loss runtime snapshot (null for REP/legacy + * documents). Additive and optional so pre-#1392 documents decode unchanged; + * restoring NEVER resumes the armed policy from it (see + * [PowerLossRestartRecovery]) and never issues machine commands. + */ + val powerLoss: RestoredPowerLossRuntimeSnapshot? = null, ) { init { require(version == CURRENT_VERSION) diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/PowerLossCompanionStore.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/PowerLossCompanionStore.kt new file mode 100644 index 000000000..912c4b126 --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/PowerLossCompanionStore.kt @@ -0,0 +1,233 @@ +package com.devil.phoenixproject.data.repository + +import co.touchlab.kermit.Logger +import com.devil.phoenixproject.database.PhoenixDatabaseQueries +import com.devil.phoenixproject.database.PowerLossAttemptCompanion as PowerLossAttemptCompanionRow +import com.devil.phoenixproject.database.PowerLossSetCompanion as PowerLossSetCompanionRow +import com.devil.phoenixproject.domain.powerloss.PowerCable +import com.devil.phoenixproject.domain.powerloss.PowerLossAttemptRecord +import com.devil.phoenixproject.domain.powerloss.PowerLossSetEvidence +import com.devil.phoenixproject.domain.powerloss.PowerStopReason +import com.devil.phoenixproject.domain.powerloss.SampleQualityMarkers +import com.devil.phoenixproject.domain.powerloss.TargetMode + +/** + * Issue #1392 (packet P4) — durable power-loss companions. + * + * Persists [PowerLossSetEvidence] / [PowerLossAttemptRecord] (the frozen cross-packet + * contract in `domain/powerloss/PowerLossEvidence.kt`) into the additive nullable + * companion tables. Contract invariants enforced here: + * + * - **Idempotent retry:** companion writes are INSERT-if-absent on their stable keys, + * inside the caller's transaction. A retried commit is a no-op; a partially failed + * one is filled in. Never `INSERT OR REPLACE` (no parent rows exist to cascade). + * - **Attempt-only rows** (`completed = 0`, no legacy `RepMetric` row) are first-class. + * The attempt table carries NO foreign key to `RepMetric`, so the completion commit's + * wholesale rep-row replacement can never cascade attempts away. + * - **Null-vs-zero:** missing data is stored and returned as NULL, never 0. + * - **No wire semantics:** nothing in these tables is pushed to the portal + * (no new wire keys; legacy `avgPowerWatts`/`powerWatts` untouched). + * - **Strict readers fail safe:** unknown persisted enum values never arm POWER — + * a set row with an unknown [TargetMode] is skipped (not coerced), an unknown + * winner reason reads as null (no power-policy stop claimed). + */ +internal object PowerLossCompanionStore { + + /** Serializes the frozen active-cable mask as stable enum names, e.g. `A,B`. */ + internal fun encodeActiveCables(cables: Set): String = + cables.map { it.name }.sorted().joinToString(",") + + /** + * Strict mask parse. Unknown names fail the whole row safe (returns null) — + * a mask with unrecognizable members is never silently treated as a known mask. + */ + internal fun decodeActiveCables(encoded: String): Set? { + if (encoded.isEmpty()) return emptySet() + val result = mutableSetOf() + for (token in encoded.split(',')) { + val cable = PowerCable.entries.firstOrNull { it.name == token.trim() } ?: return null + result += cable + } + return result + } + + /** Bit-flag serialization of the per-sample quality markers (`C`,`R`,`S`,`G`). */ + internal fun encodeQuality(quality: SampleQualityMarkers): String = buildString { + if (quality.clamped) append('C') + if (quality.rejected) append('R') + if (quality.stale) append('S') + if (quality.gapBefore) append('G') + } + + /** Strict quality parse: known flags decoded; unknown tokens are preserved-ignorable. */ + internal fun decodeQuality(encoded: String): SampleQualityMarkers = SampleQualityMarkers( + clamped = 'C' in encoded, + rejected = 'R' in encoded, + stale = 'S' in encoded, + gapBefore = 'G' in encoded, + ) + + /** + * Writes the set companion and every attempt companion in the caller's + * transaction. Idempotent on retry (INSERT-if-absent). Immutable contract: + * an existing row for the same stable key is left untouched. + */ + internal fun commitEvidence( + queries: PhoenixDatabaseQueries, + evidence: PowerLossSetEvidence, + nowMs: Long, + ) { + queries.insertPowerLossSetCompanionRowIfAbsent(evidence, nowMs) + for (attempt in evidence.attempts) { + queries.insertPowerLossAttemptCompanionRowIfAbsent(evidence.sessionId, evidence.setId, attempt) + } + } + + /** + * Reads a session's persisted evidence, newest set first. Rows with unknown + * persisted enum values are skipped (fail safe, never armed) and logged. + */ + internal fun readEvidence( + queries: PhoenixDatabaseQueries, + sessionId: String, + ): List { + val attemptsBySet = queries.selectPowerLossAttemptCompanionsBySession(sessionId) + .executeAsList() + .groupBy({ it.set_id }, { it.toAttemptRecord() }) + return queries.selectPowerLossSetCompanionsBySession(sessionId) + .executeAsList() + .mapNotNull { row -> row.toSetEvidence(attemptsBySet[row.set_id].orEmpty()) } + } +} + +/** INSERT-if-absent: retry-safe, immutable, API-26 safe (no upsert syntax). */ +internal fun PhoenixDatabaseQueries.insertPowerLossSetCompanionRowIfAbsent( + evidence: PowerLossSetEvidence, + nowMs: Long, +) { + val targetMode = evidence.targetMode.name + insertPowerLossSetCompanionIfAbsent( + session_id = evidence.sessionId, + set_id = evidence.setId, + metric_version = evidence.metricVersion.toLong(), + target_mode = targetMode, + threshold_percent = evidence.thresholdPercent.toLong(), + max_working_reps = evidence.maxWorkingReps?.toLong(), + require_two_consecutive = if (evidence.requireTwoConsecutive) 1L else 0L, + saved_nominal_reps = evidence.savedNominalReps?.toLong(), + active_cables = PowerLossCompanionStore.encodeActiveCables(evidence.activeCables), + active_cable_provenance = evidence.activeCableProvenance, + reference_working_ordinal = evidence.referenceWorkingOrdinal?.toLong(), + reference_mcp_watts = evidence.referenceMcpWatts?.toDouble(), + reference_rom_a_mm = evidence.referenceRomAMm?.toDouble(), + reference_rom_b_mm = evidence.referenceRomBMm?.toDouble(), + trigger_working_ordinal = evidence.triggerWorkingOrdinal?.toLong(), + winner_reason = evidence.winnerReason?.name, + short_rom_observed = if (evidence.shortRomObserved) 1L else 0L, + power_loss_observed = if (evidence.powerLossObserved) 1L else 0L, + loss_percent_at_decision = evidence.lossPercentAtDecision?.toDouble(), + created_at = nowMs, + ) +} + +/** INSERT-if-absent per `(session, working concentric ordinal)` identity. */ +internal fun PhoenixDatabaseQueries.insertPowerLossAttemptCompanionRowIfAbsent( + sessionId: String, + setId: String, + attempt: PowerLossAttemptRecord, +) { + insertPowerLossAttemptCompanionIfAbsent( + session_id = sessionId, + set_id = setId, + working_concentric_ordinal = attempt.workingConcentricOrdinal.toLong(), + legacy_rep_index = attempt.legacyRepIndex?.toLong(), + completed = if (attempt.completed) 1L else 0L, + mcp_watts = attempt.mcpWatts?.toDouble(), + eccentric_power_watts = attempt.eccentricPowerWatts?.toDouble(), + concentric_duration_ms = attempt.concentricDurationMs, + eccentric_duration_ms = attempt.eccentricDurationMs, + loss_percent_at_decision = attempt.lossPercentAtDecision?.toDouble(), + reference_working_ordinal = attempt.referenceWorkingOrdinal?.toLong(), + rom_a_mm = attempt.romAMm?.toDouble(), + rom_b_mm = attempt.romBMm?.toDouble(), + rom_a_percent_of_reference = attempt.romAPercentOfReference?.toDouble(), + rom_b_percent_of_reference = attempt.romBPercentOfReference?.toDouble(), + rom_trustworthy = if (attempt.romTrustworthy) 1L else 0L, + quality = PowerLossCompanionStore.encodeQuality(attempt.quality), + short_rom = if (attempt.shortRom) 1L else 0L, + power_loss_qualified = if (attempt.powerLossQualified) 1L else 0L, + ) +} + +private fun PowerLossAttemptCompanionRow.toAttemptRecord(): PowerLossAttemptRecord = PowerLossAttemptRecord( + workingConcentricOrdinal = working_concentric_ordinal.toInt(), + completed = completed != 0L, + legacyRepIndex = legacy_rep_index?.toInt(), + mcpWatts = mcp_watts?.toFloat(), + eccentricPowerWatts = eccentric_power_watts?.toFloat(), + concentricDurationMs = concentric_duration_ms, + eccentricDurationMs = eccentric_duration_ms, + lossPercentAtDecision = loss_percent_at_decision?.toFloat(), + referenceWorkingOrdinal = reference_working_ordinal?.toInt(), + romAMm = rom_a_mm?.toFloat(), + romBMm = rom_b_mm?.toFloat(), + romAPercentOfReference = rom_a_percent_of_reference?.toFloat(), + romBPercentOfReference = rom_b_percent_of_reference?.toFloat(), + romTrustworthy = rom_trustworthy != 0L, + quality = PowerLossCompanionStore.decodeQuality(quality), + shortRom = short_rom != 0L, + powerLossQualified = power_loss_qualified != 0L, +) + +private fun PowerLossSetCompanionRow.toSetEvidence( + attempts: List, +): PowerLossSetEvidence? { + // Strict readers fail safe: an unknown target mode must never arm POWER. + val targetMode = TargetMode.fromPersisted(target_mode) + if (targetMode == null) { + Logger.w { + "PowerLossCompanionStore: skipping set companion $session_id/$set_id with unknown target mode '$target_mode'" + } + return null + } + val cables = PowerLossCompanionStore.decodeActiveCables(active_cables) + if (cables == null) { + Logger.w { + "PowerLossCompanionStore: skipping set companion $session_id/$set_id with unknown active-cable mask '$active_cables'" + } + return null + } + // Unknown winner reasons read as null (no power-policy stop claimed); the raw + // value stays inspectable in the row itself. + val winner = winner_reason?.let { reason -> + PowerStopReason.entries.firstOrNull { it.name == reason }.also { + if (it == null) { + Logger.w { + "PowerLossCompanionStore: unknown winner reason '$reason' on $session_id/$set_id; reading as no power-policy stop" + } + } + } + } + return PowerLossSetEvidence( + sessionId = session_id, + setId = set_id, + metricVersion = metric_version.toInt(), + targetMode = targetMode, + thresholdPercent = threshold_percent.toInt(), + maxWorkingReps = max_working_reps?.toInt(), + requireTwoConsecutive = require_two_consecutive != 0L, + savedNominalReps = saved_nominal_reps?.toInt(), + activeCables = cables, + activeCableProvenance = active_cable_provenance, + referenceWorkingOrdinal = reference_working_ordinal?.toInt(), + referenceMcpWatts = reference_mcp_watts?.toFloat(), + referenceRomAMm = reference_rom_a_mm?.toFloat(), + referenceRomBMm = reference_rom_b_mm?.toFloat(), + triggerWorkingOrdinal = trigger_working_ordinal?.toInt(), + winnerReason = winner, + shortRomObserved = short_rom_observed != 0L, + powerLossObserved = power_loss_observed != 0L, + lossPercentAtDecision = loss_percent_at_decision?.toFloat(), + attempts = attempts, + ) +} diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/PowerLossConfigStore.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/PowerLossConfigStore.kt new file mode 100644 index 000000000..8a7c575d1 --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/PowerLossConfigStore.kt @@ -0,0 +1,197 @@ +package com.devil.phoenixproject.data.repository + +import co.touchlab.kermit.Logger +import com.devil.phoenixproject.database.PhoenixDatabaseQueries +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.TargetMode +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +/** + * Issue #1392 (packet P4 remainder) — durable per-exercise power-loss target config. + * + * One row per routine exercise in the additive `PowerLossExerciseConfig` table + * (migration 65). Contract invariants: + * + * - **Absent row = inert default:** [PowerLossConfig.DEFAULT] — REP_TARGET with + * nulls, never fabricated zeros. Legacy rows keep their REP meaning. + * - **Strict readers fail safe:** an unknown persisted target enum or unknown + * stored format version resolves to the inert default (never arms POWER — + * spec §7, SD1). The raw value stays inspectable in the row itself. + * - **Local-only:** no sync wire semantics — never pushed, never marked synced + * or backed up. An acknowledged legacy push must not touch these rows. + * - **Restore is additive:** backup restore uses INSERT-if-absent (local wins); + * absent backup sections never wipe local config. + * - **Idempotent local writes:** delete + reinsert inside the caller's + * transaction (leaf row, no children; never INSERT OR REPLACE a parent). + */ +internal object PowerLossConfigStore { + + private val json = Json { + ignoreUnknownKeys = true + isLenient = false + coerceInputValues = false + encodeDefaults = true + explicitNulls = true + } + + /** Current stored-row format version. */ + const val FORMAT_VERSION: Int = 1 + + /** + * Persist [config] for one routine exercise. A default config removes any row + * (absent = default), so the table only ever carries real user intent. Runs + * inside the caller's transaction. + */ + internal fun writeConfig( + queries: PhoenixDatabaseQueries, + routineExerciseId: String, + config: PowerLossConfig, + nowMs: Long, + ) { + queries.deletePowerLossExerciseConfig(routineExerciseId) + if (config == PowerLossConfig.DEFAULT) return + queries.insertPowerLossExerciseConfigIfAbsent( + routine_exercise_id = routineExerciseId, + format_version = FORMAT_VERSION.toLong(), + target_mode = config.targetMode.name, + threshold_percent = config.thresholdPercent.toLong(), + max_working_reps = config.maxWorkingReps?.toLong(), + require_two_consecutive = if (config.requireTwoConsecutive) 1L else 0L, + saved_nominal_reps = config.savedNominalReps?.toLong(), + updated_at = nowMs, + ) + } + + /** + * Read one exercise's config. Absent or unsupported rows resolve to + * [PowerLossConfig.DEFAULT] (inert REP_TARGET, nulls not zeros). + */ + internal fun readConfig(queries: PhoenixDatabaseQueries, routineExerciseId: String): PowerLossConfig { + val row = queries.selectPowerLossExerciseConfigsByRoutineExerciseIds(listOf(routineExerciseId)) + .executeAsList() + .firstOrNull { it.routine_exercise_id == routineExerciseId } + ?: return PowerLossConfig.DEFAULT + return decodeRow( + targetMode = row.target_mode, + thresholdPercent = row.threshold_percent.toInt(), + maxWorkingReps = row.max_working_reps?.toInt(), + requireTwoConsecutive = row.require_two_consecutive != 0L, + savedNominalReps = row.saved_nominal_reps?.toInt(), + formatVersion = row.format_version.toInt(), + ) + } + + /** + * Strict row decode. Unknown stored format version or unknown target enum → + * the full inert default (never POWER; never a fabricated zero). In-range + * values keep their exact stored meaning. + */ + internal fun decodeRow( + targetMode: String, + thresholdPercent: Int, + maxWorkingReps: Int?, + requireTwoConsecutive: Boolean, + savedNominalReps: Int?, + formatVersion: Int = FORMAT_VERSION, + ): PowerLossConfig { + if (formatVersion != FORMAT_VERSION) { + Logger.w { + "PowerLossConfigStore: unknown stored format version $formatVersion; reading inert REP defaults" + } + return PowerLossConfig.DEFAULT + } + val mode = TargetMode.fromPersisted(targetMode) + if (mode == null) { + Logger.w { + "PowerLossConfigStore: unknown target mode '$targetMode'; reading inert REP defaults (never arms POWER)" + } + return PowerLossConfig.DEFAULT + } + return PowerLossConfig( + targetMode = mode, + thresholdPercent = thresholdPercent, + maxWorkingReps = maxWorkingReps ?: PowerLossConfig.DEFAULT.maxWorkingReps, + requireTwoConsecutive = requireTwoConsecutive, + savedNominalReps = savedNominalReps, + ) + } + + /** + * INSERT-if-absent restore (backup restore path): local config wins, absent + * rows are filled. An existing row is never replaced or wiped. Unknown enum + * or version rows are stored verbatim (raw values stay inspectable) but are + * read back inert by [readConfig]. + */ + internal fun restoreIfAbsent( + queries: PhoenixDatabaseQueries, + routineExerciseId: String, + targetMode: String, + thresholdPercent: Int, + maxWorkingReps: Int?, + requireTwoConsecutive: Boolean, + savedNominalReps: Int?, + formatVersion: Int, + nowMs: Long, + ) { + queries.insertPowerLossExerciseConfigIfAbsent( + routine_exercise_id = routineExerciseId, + format_version = formatVersion.toLong(), + target_mode = targetMode, + threshold_percent = thresholdPercent.toLong(), + max_working_reps = maxWorkingReps?.toLong(), + require_two_consecutive = if (requireTwoConsecutive) 1L else 0L, + saved_nominal_reps = savedNominalReps?.toLong(), + updated_at = nowMs, + ) + } +} + +/** + * Versioned JSON encoding of [PowerLossConfig] for opaque single-column storage + * surfaces that need it (CSV metadata mirrors use plain columns instead). + * [decodeConfigJson] fails safe: corrupt or unknown-version payloads read as + * [PowerLossConfig.DEFAULT], never as armed POWER and never as fabricated zeros. + */ +@Serializable +internal data class PowerLossConfigStored( + val formatVersion: Int = PowerLossConfigStore.FORMAT_VERSION, + val targetMode: String = TargetMode.REP_TARGET.name, + val thresholdPercent: Int = PowerLossConfig.DEFAULT.thresholdPercent, + val maxWorkingReps: Int? = null, + val requireTwoConsecutive: Boolean = false, + val savedNominalReps: Int? = null, +) + +private val configJson = Json { + ignoreUnknownKeys = true + isLenient = false + coerceInputValues = false +} + +internal fun encodeConfigJson(config: PowerLossConfig): String = configJson.encodeToString( + PowerLossConfigStored.serializer(), + PowerLossConfigStored( + formatVersion = PowerLossConfigStore.FORMAT_VERSION, + targetMode = config.targetMode.name, + thresholdPercent = config.thresholdPercent, + maxWorkingReps = config.maxWorkingReps, + requireTwoConsecutive = config.requireTwoConsecutive, + savedNominalReps = config.savedNominalReps, + ), +) + +internal fun decodeConfigJson(raw: String): PowerLossConfig = try { + val stored = configJson.decodeFromString(PowerLossConfigStored.serializer(), raw) + PowerLossConfigStore.decodeRow( + targetMode = stored.targetMode, + thresholdPercent = stored.thresholdPercent, + maxWorkingReps = stored.maxWorkingReps, + requireTwoConsecutive = stored.requireTwoConsecutive, + savedNominalReps = stored.savedNominalReps, + formatVersion = stored.formatVersion, + ) +} catch (e: Exception) { + Logger.w { "PowerLossConfigStore: unreadable config payload; reading inert REP defaults" } + PowerLossConfig.DEFAULT +} diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/RoutineRecovery.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/RoutineRecovery.kt index dc5492c4a..3e363ff58 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/RoutineRecovery.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/RoutineRecovery.kt @@ -481,6 +481,24 @@ open class RoutineRecoveryStore(private val queries: PhoenixDatabaseQueries) { // build, so its duration is known (same rule as writeRoutineExerciseRow); // the snapshot's flag described the deleted identity, not this one. queries.updateRoutineExerciseDurationSyncKnown(durationSyncKnown = 1L, id = newExerciseId) + // Issue #1392: the recovered clone keeps the source exercise's power-loss + // config (local-only state; restored additively, never a sync/backed-up claim). + val sourceConfig = queries.selectPowerLossExerciseConfigsByRoutineExerciseIds(listOf(exercise.id)) + .executeAsList() + .firstOrNull { it.routine_exercise_id == exercise.id } + if (sourceConfig != null) { + PowerLossConfigStore.restoreIfAbsent( + queries = queries, + routineExerciseId = newExerciseId, + targetMode = sourceConfig.target_mode, + thresholdPercent = sourceConfig.threshold_percent.toInt(), + maxWorkingReps = sourceConfig.max_working_reps?.toInt(), + requireTwoConsecutive = sourceConfig.require_two_consecutive != 0L, + savedNominalReps = sourceConfig.saved_nominal_reps?.toInt(), + formatVersion = sourceConfig.format_version.toInt(), + nowMs = com.devil.phoenixproject.domain.model.currentTimeMillis(), + ) + } } for (plannedSet in graph.plannedSets) { diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/SqlDelightWorkoutRepository.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/SqlDelightWorkoutRepository.kt index b1f3df76b..4fb8c5c9c 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/SqlDelightWorkoutRepository.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/SqlDelightWorkoutRepository.kt @@ -458,6 +458,9 @@ class SqlDelightWorkoutRepository( RoutineExercise( id = row.id, exercise = exerciseWithBodyweightFlag, + // Issue #1392: per-exercise power-loss config (absent row = inert + // REP defaults with nulls, never zeros; strict reader fails safe). + powerLoss = PowerLossConfigStore.readConfig(queries, row.id), orderIndex = row.orderIndex.toInt(), setReps = setReps, weightPerCableKg = row.weightPerCableKg.toFloat(), @@ -567,6 +570,12 @@ class SqlDelightWorkoutRepository( } } + /** Issue #1392: read-side power-loss evidence (newest set first). */ + override suspend fun powerLossEvidenceForSession(sessionId: String): List = + withContext(Dispatchers.IO) { + PowerLossCompanionStore.readEvidence(queries, sessionId) + } + /** * F-012: the whole completion in one transaction. See * [WorkoutRepository.commitCompletedSet] for the contract; the guards here @@ -586,6 +595,27 @@ class SqlDelightWorkoutRepository( } } + /** + * Issue #1392 (packet P4): evidence-aware commit. The deep-frozen + * [com.devil.phoenixproject.domain.powerloss.PowerLossSetEvidence] companions land in + * the SAME transaction as the set — retry/idempotent (INSERT-if-absent on stable + * keys), attempt-only rows preserved (no FK to RepMetric), never fabricated. + */ + override suspend fun commitCompletedSet( + session: WorkoutSession, + metrics: List, + completedSet: com.devil.phoenixproject.domain.model.CompletedSet?, + repMetrics: List, + repBiomechanics: List, + powerLossEvidence: com.devil.phoenixproject.domain.powerloss.PowerLossSetEvidence?, + ) { + withContext(Dispatchers.IO) { + db.transaction { + commitCompletedSetBody(session, metrics, completedSet, repMetrics, repBiomechanics, powerLossEvidence) + } + } + } + /** * Issue #1384 (packet P2): the completion-aware commit. The set writes are exactly the * [commitCompletedSet] body in their OWN transaction; the completion side effects land @@ -606,10 +636,35 @@ class SqlDelightWorkoutRepository( repMetrics: List, repBiomechanics: List, completion: WorkoutCompletionMembership, + ) { + commitCompletedSetWithCompletionImpl(session, metrics, completedSet, repMetrics, repBiomechanics, completion, null) + } + + /** Issue #1392: completion-aware evidence overload — same contract, companions ride along. */ + override suspend fun commitCompletedSetWithCompletion( + session: WorkoutSession, + metrics: List, + completedSet: com.devil.phoenixproject.domain.model.CompletedSet?, + repMetrics: List, + repBiomechanics: List, + completion: WorkoutCompletionMembership, + powerLossEvidence: com.devil.phoenixproject.domain.powerloss.PowerLossSetEvidence?, + ) { + commitCompletedSetWithCompletionImpl(session, metrics, completedSet, repMetrics, repBiomechanics, completion, powerLossEvidence) + } + + private suspend fun commitCompletedSetWithCompletionImpl( + session: WorkoutSession, + metrics: List, + completedSet: com.devil.phoenixproject.domain.model.CompletedSet?, + repMetrics: List, + repBiomechanics: List, + completion: WorkoutCompletionMembership, + powerLossEvidence: com.devil.phoenixproject.domain.powerloss.PowerLossSetEvidence?, ) { val standaloneQueued = withContext(Dispatchers.IO) { db.transaction { - commitCompletedSetBody(session, metrics, completedSet, repMetrics, repBiomechanics) + commitCompletedSetBody(session, metrics, completedSet, repMetrics, repBiomechanics, powerLossEvidence) } try { db.transactionWithResult { @@ -693,6 +748,7 @@ class SqlDelightWorkoutRepository( completedSet: com.devil.phoenixproject.domain.model.CompletedSet?, repMetrics: List, repBiomechanics: List, + powerLossEvidence: com.devil.phoenixproject.domain.powerloss.PowerLossSetEvidence? = null, ) { if (queries.selectSessionById(session.id).executeAsOneOrNull() == null) { insertSessionRow(session) @@ -710,6 +766,12 @@ class SqlDelightWorkoutRepository( repMetrics.forEach { metric -> queries.insertRepMetricRow(session.id, metric) } queries.deleteRepBiomechanicsBySession(session.id) repBiomechanics.forEach { result -> queries.insertRepBiomechanicsRow(session.id, result) } + // Issue #1392: deep-frozen power-loss companions in the SAME transaction + // (INSERT-if-absent on stable keys — retry/idempotent, attempt-only rows + // preserved; null evidence writes nothing and never fabricates). + if (powerLossEvidence != null) { + PowerLossCompanionStore.commitEvidence(queries, powerLossEvidence, currentTimeMillis()) + } // Main's newer sync-dirty contract: every child write marks its // session. The atomic commit writes those children in one // transaction, so it must dirty the session the same way the @@ -1590,6 +1652,11 @@ class SqlDelightWorkoutRepository( ) } + // Issue #1392: persist the per-exercise power-loss target config alongside the + // row write (delete + reinsert inside the caller's transaction; a default + // config removes the row so absent always means inert REP defaults). + PowerLossConfigStore.writeConfig(queries, exerciseRowId, exercise.powerLoss, currentTimeMillis()) + // Portal sync (PR 13): the duration is known to be current when this build // created the row, when it was already known, or when the user changed it. // An untouched row from an older build keeps "unknown" so a stale NULL is not diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/WorkoutRepository.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/WorkoutRepository.kt index ff5a03299..80aa88332 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/WorkoutRepository.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/data/repository/WorkoutRepository.kt @@ -81,6 +81,46 @@ interface WorkoutRepository { repBiomechanics: List, completion: WorkoutCompletionMembership, ) + + /** + * Issue #1392 — evidence-aware overload (P3 ↔ P4 contract). Delegates to the + * evidence-less transaction by default so legacy fakes compile; the production + * `SqlDelightWorkoutRepository` overrides this to commit the deep-frozen + * [com.devil.phoenixproject.domain.powerloss.PowerLossSetEvidence] companions + * in the SAME transaction (retry/idempotent, attempt-only rows preserved). + */ + suspend fun commitCompletedSet( + session: WorkoutSession, + metrics: List, + completedSet: CompletedSet?, + repMetrics: List, + repBiomechanics: List, + powerLossEvidence: com.devil.phoenixproject.domain.powerloss.PowerLossSetEvidence?, + ) { + commitCompletedSet(session, metrics, completedSet, repMetrics, repBiomechanics) + } + + /** See [commitCompletedSet] — completion-aware evidence overload (same contract). */ + suspend fun commitCompletedSetWithCompletion( + session: WorkoutSession, + metrics: List, + completedSet: CompletedSet?, + repMetrics: List, + repBiomechanics: List, + completion: WorkoutCompletionMembership, + powerLossEvidence: com.devil.phoenixproject.domain.powerloss.PowerLossSetEvidence?, + ) { + commitCompletedSetWithCompletion(session, metrics, completedSet, repMetrics, repBiomechanics, completion) + } + + /** + * Issue #1392 — read-side hook for P5 history/summary. Returns persisted evidence + * rows for a session (newest set first). Default is empty for legacy fakes; the + * production repository implements the companion reads (P4). + */ + suspend fun powerLossEvidenceForSession(sessionId: String): List = + emptyList() + suspend fun updateSessionExerciseTag(sessionId: String, exerciseId: String, exerciseName: String) /** diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/di/DataModule.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/di/DataModule.kt index a859a56a5..05b07c266 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/di/DataModule.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/di/DataModule.kt @@ -2,6 +2,8 @@ package com.devil.phoenixproject.di import app.cash.sqldelight.db.SqlDriver import com.devil.phoenixproject.data.csv.CsvImportInbox +import com.devil.phoenixproject.data.export.PowerHistoryExporter +import com.devil.phoenixproject.data.export.PowerHistoryExporterImpl import com.devil.phoenixproject.data.ble.HrmBleManager import com.devil.phoenixproject.data.integration.ExternalActivityRepository import com.devil.phoenixproject.data.integration.ExternalExerciseTemplateRepository @@ -135,6 +137,8 @@ val dataModule = module { // Training Cycles Repositories single { SqlDelightTrainingCycleRepository(get()) } single { SqlDelightCompletedSetRepository(get()) } + // Issue #1392 P4: power-history export v1 (P5 UI calls the interface only). + single { PowerHistoryExporterImpl(get()) } single { SqlDelightActiveWorkoutRuntimeRepository(get()) } single { SqlDelightMachineSafetyHazardRepository(get()) } single { BleRepositoryMachineSafetyTransport(get()) } diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/di/PresentationModule.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/di/PresentationModule.kt index 15c42142a..3ec0de9a5 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/di/PresentationModule.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/di/PresentationModule.kt @@ -28,7 +28,7 @@ val presentationModule = module { // when that entry leaves the back stack. viewModel { CycleEditorViewModel(get(), get()) } viewModel { GamificationViewModel(get(), get()) } - factory { IntegrationsViewModel(get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get()) } + factory { IntegrationsViewModel(get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get()) } factory { RoutineCsvViewModel(get(), get(), get()) } factory { ExternalActivitiesViewModel(get(), get()) } factory { ExternalRoutinesViewModel(get(), get()) } diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvCodec.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvCodec.kt index 6ebeb1c6b..2f7745c72 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvCodec.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvCodec.kt @@ -11,6 +11,8 @@ import com.devil.phoenixproject.domain.model.Routine import com.devil.phoenixproject.domain.model.RoutineExercise import com.devil.phoenixproject.domain.model.ScalingBasis import com.devil.phoenixproject.domain.model.WarmupSet +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.TargetMode import com.devil.phoenixproject.util.CommandLimits import com.devil.phoenixproject.util.CsvParser @@ -64,6 +66,12 @@ data class RoutineCsvExerciseDraft( val setEchoLevels: List = emptyList(), /** The stored legacy AMRAP flag; null means the version 1 rule (every set is AMRAP). */ val isAmrapFlag: Boolean? = null, + /** + * Per-exercise power-loss target config (version 3 columns). A version 1 or 2 + * row cannot carry it and keeps [PowerLossConfig.DEFAULT] — inert REP_TARGET + * with nulls, never fabricated zeros. + */ + val powerLoss: PowerLossConfig = PowerLossConfig.DEFAULT, ) /** One routine from the file, rows sorted by [RoutineCsvExerciseDraft.order]. */ @@ -119,32 +127,62 @@ object RoutineCsvCodec { private val COL_SET_ECHO_LEVELS = RoutineCsvFormat.COLUMNS_V2.indexOf("set_echo_levels") private val COL_IS_AMRAP_FLAG = RoutineCsvFormat.COLUMNS_V2.indexOf("is_amrap_flag") + // Version 3 column positions (the v2 columns keep their fixed positions). + private val COL_POWER_LOSS_TARGET_MODE = RoutineCsvFormat.COLUMNS_V3.indexOf("power_loss_target_mode") + private val COL_POWER_LOSS_THRESHOLD_PERCENT = RoutineCsvFormat.COLUMNS_V3.indexOf("power_loss_threshold_percent") + private val COL_POWER_LOSS_MAX_WORKING_REPS = RoutineCsvFormat.COLUMNS_V3.indexOf("power_loss_max_working_reps") + private val COL_POWER_LOSS_REQUIRE_TWO_CONSECUTIVE = RoutineCsvFormat.COLUMNS_V3.indexOf("power_loss_require_two_consecutive") + private val COL_POWER_LOSS_SAVED_NOMINAL_REPS = RoutineCsvFormat.COLUMNS_V3.indexOf("power_loss_saved_nominal_reps") + /** Which header a file's rows must line up with. */ private class Layout(val version: Int) { - val columns: List = - if (version == RoutineCsvFormat.VERSION_V2) RoutineCsvFormat.COLUMNS_V2 else RoutineCsvFormat.COLUMNS + val columns: List = when (version) { + RoutineCsvFormat.VERSION_V3 -> RoutineCsvFormat.COLUMNS_V3 + RoutineCsvFormat.VERSION_V2 -> RoutineCsvFormat.COLUMNS_V2 + else -> RoutineCsvFormat.COLUMNS + } val columnCount: Int = columns.size } // ── Export ────────────────────────────────────────────────────────────── /** - * One routine as a v2 file. [groupName] and [groupOrder] describe the routine's group, if - * any. Blocked only when a row cannot hold the routine at all (no exercises, an exercise - * with no sets); every advanced setting is carried by v2. + * One routine as a file: version 2 for routines that use only default + * power-loss config, version 3 ([RoutineCsvFormat.COLUMNS_V3]) as soon as any + * exercise carries a non-default `ExerciseConfig.powerLoss` (Issue #1392). + * + * LOSSY-EXPORT BLOCK (binding): a routine whose exercises use non-default + * power-loss config is NEVER quietly exported as a version 2 REP row — the + * version 3 header carries the config losslessly instead, and if that is not + * possible (an invalid config) export is refused with explicit user-facing + * copy. Apps that read version 2 only refuse version 3 files outright + * ("Unsupported file version"), so a POWER routine can never silently + * re-import as REP elsewhere either. + * + * [groupName] and [groupOrder] describe the routine's group, if any. Also + * blocked when a row cannot hold the routine at all (no exercises, an + * exercise with no sets). */ fun encode(routine: Routine, groupName: String?, groupOrder: Int?): RoutineCsvExportResult { val reasons = exportBlockers(routine) if (reasons.isNotEmpty()) return RoutineCsvExportResult.Blocked(reasons) + val usesPowerLossConfig = routine.exercises.any { it.powerLoss != PowerLossConfig.DEFAULT } + val versionLine = if (usesPowerLossConfig) { + RoutineCsvFormat.VERSION_V3_LINE + } else { + RoutineCsvFormat.VERSION_V2_LINE + } + val columns = if (usesPowerLossConfig) RoutineCsvFormat.COLUMNS_V3 else RoutineCsvFormat.COLUMNS_V2 + val supersetKeys = routine.supersets.sortedBy { it.orderIndex } .mapIndexed { index, superset -> superset.id to "ss${index + 1}" } .toMap() val supersetsById = routine.supersets.associateBy { it.id } val text = buildString { - append(RoutineCsvFormat.VERSION_V2_LINE).append("\r\n") - append(RoutineCsvFormat.COLUMNS_V2.joinToString(",")).append("\r\n") + append(versionLine).append("\r\n") + append(columns.joinToString(",")).append("\r\n") routine.exercises.forEachIndexed { index, exercise -> val superset = exercise.supersetId?.let(supersetsById::get) val cells = listOf( @@ -167,13 +205,29 @@ object RoutineCsvCodec { RoutineCsvFormat.modeName(exercise.programMode), exercise.setReps.all { it == null }.toString(), superset?.colorIndex?.toString().orEmpty(), - ) + v2Cells(exercise) + ) + v2Cells(exercise) + if (usesPowerLossConfig) powerLossCells(exercise) else emptyList() append(cells.joinToString(",")).append("\r\n") } } return RoutineCsvExportResult.Exported(fileName = fileName(routine.name), content = text) } + /** + * The version 3 power-loss cells for [exercise]. Numeric cells stay numbers; + * an absent nullable cell stays blank (never a fabricated zero). The target + * mode is written as its constant name so the reader can fail safe on it. + */ + private fun powerLossCells(exercise: RoutineExercise): List { + val powerLoss = exercise.powerLoss + return listOf( + powerLoss.targetMode.name, + powerLoss.thresholdPercent.toString(), + powerLoss.maxWorkingReps?.toString().orEmpty(), + powerLoss.requireTwoConsecutive.toString(), + powerLoss.savedNominalReps?.toString().orEmpty(), + ) + } + /** The version 2 cells for [exercise]; numeric cells stay numbers, structured text cells are guarded. */ private fun v2Cells(exercise: RoutineExercise): List = listOf( exercise.usePercentOfPR.toString(), @@ -201,13 +255,23 @@ object RoutineCsvCodec { /** * Settings [routine] uses that a CSV row cannot hold at all, one readable line each. Empty - * when exportable: every other setting the routine uses round-trips through v2 (#896). + * when exportable: every other setting the routine uses round-trips through its file + * version (#896 v2; #1392 v3 adds the power-loss config). Includes the binding + * LOSSY-EXPORT BLOCK: an invalid power-loss config is refused with explicit + * user-facing copy — a routine is NEVER quietly exported without its power-loss + * settings (never silently downgraded to REP). */ fun exportBlockers(routine: Routine): List { if (routine.exercises.isEmpty()) return listOf("The routine has no exercises.") val reasons = linkedSetOf() for (exercise in routine.exercises) { if (exercise.setReps.isEmpty()) reasons += "${exercise.exercise.name} has no sets." + val powerLoss = exercise.powerLoss + if (powerLoss != PowerLossConfig.DEFAULT && !powerLoss.isValid()) { + reasons += "${exercise.exercise.name} has invalid power-loss target settings, so they cannot be " + + "saved in a routine CSV. This format does not include power-loss settings or per-attempt " + + "details it cannot hold. Use power-data export to keep them." + } } return reasons.toList() } @@ -256,10 +320,13 @@ object RoutineCsvCodec { return invalid(lines.number, "The first line must be ${RoutineCsvFormat.VERSION_LINE}.") } val version = versionLine.removePrefix(RoutineCsvFormat.VERSION_PREFIX).trim().toIntOrNull() - if (version != RoutineCsvFormat.VERSION && version != RoutineCsvFormat.VERSION_V2) { + if (version != RoutineCsvFormat.VERSION && version != RoutineCsvFormat.VERSION_V2 && + version != RoutineCsvFormat.VERSION_V3 + ) { return invalid( lines.number, - "Unsupported file version; this app reads versions ${RoutineCsvFormat.VERSION} and ${RoutineCsvFormat.VERSION_V2}.", + "Unsupported file version; this app reads versions ${RoutineCsvFormat.VERSION}, " + + "${RoutineCsvFormat.VERSION_V2} and ${RoutineCsvFormat.VERSION_V3}.", ) } val layout = Layout(version) @@ -418,9 +485,9 @@ object RoutineCsvCodec { val modeCell = row.raw(15) val mode = if (modeCell.isEmpty()) ProgramMode.OldSchool else RoutineCsvFormat.parseMode(modeCell) - // A v2 file carries every mode; v1 keeps the released rule (Echo and Eccentric Only refused). + // A v2/v3 file carries every mode; v1 keeps the released rule (Echo and Eccentric Only refused). val supportedModes = - if (layout.version == RoutineCsvFormat.VERSION_V2) RoutineCsvFormat.ALL_MODES else RoutineCsvFormat.SUPPORTED_MODES + if (layout.version >= RoutineCsvFormat.VERSION_V2) RoutineCsvFormat.ALL_MODES else RoutineCsvFormat.SUPPORTED_MODES when { mode == null -> issues += RoutineCsvIssue( row.line, @@ -446,6 +513,7 @@ object RoutineCsvCodec { } val v2 = parseV2Settings(row, issues, layout) + val powerLoss = parseV3Settings(row, issues, layout) if (issues.size != issueCount || order == null || reps == null || weights == null || mode == null) return null return RoutineCsvExerciseDraft( line = row.line, @@ -482,6 +550,45 @@ object RoutineCsvCodec { eccentricLoad = v2.eccentricLoad, setEchoLevels = v2.setEchoLevels, isAmrapFlag = v2.isAmrapFlag, + powerLoss = powerLoss, + ) + } + + /** + * The version 3 power-loss cells of one row. A version 1 or 2 row has none, so + * the config keeps [PowerLossConfig.DEFAULT] — inert REP_TARGET with nulls, + * never fabricated zeros. STRICT READER (SD1, spec §7): an unknown + * `power_loss_target_mode` never silently arms POWER — the row imports with an + * inert REP_TARGET config carrying the remaining values. Out-of-range numbers + * are refused as row issues (no silent clamping). + */ + private fun parseV3Settings(row: RawRow, issues: MutableList, layout: Layout): PowerLossConfig { + if (layout.version != RoutineCsvFormat.VERSION_V3) return PowerLossConfig.DEFAULT + val thresholdPercent = optionalInt( + row, COL_POWER_LOSS_THRESHOLD_PERCENT, "power_loss_threshold_percent", + PowerLossConfig.MIN_THRESHOLD_PERCENT, PowerLossConfig.MAX_THRESHOLD_PERCENT, issues, + ) ?: PowerLossConfig.DEFAULT.thresholdPercent + val maxWorkingReps = optionalInt( + row, COL_POWER_LOSS_MAX_WORKING_REPS, "power_loss_max_working_reps", + PowerLossConfig.MIN_MAX_WORKING_REPS, RoutineCsvFormat.MAX_REPS, issues, + ) ?: PowerLossConfig.DEFAULT.maxWorkingReps + val requireTwoConsecutive = optionalBool( + row, COL_POWER_LOSS_REQUIRE_TWO_CONSECUTIVE, "power_loss_require_two_consecutive", false, issues, + ) ?: false + val savedNominalReps = optionalInt( + row, COL_POWER_LOSS_SAVED_NOMINAL_REPS, "power_loss_saved_nominal_reps", + 1, RoutineCsvFormat.MAX_REPS, issues, + ) + val modeCell = row.raw(COL_POWER_LOSS_TARGET_MODE) + val mode = TargetMode.entries.firstOrNull { it.name.equals(modeCell, ignoreCase = true) } + return PowerLossConfig( + // Blank or unknown target mode = inert REP_TARGET (never POWER from an + // unknown string). The raw cell stays inspectable in the file itself. + targetMode = mode ?: TargetMode.REP_TARGET, + thresholdPercent = thresholdPercent, + maxWorkingReps = maxWorkingReps, + requireTwoConsecutive = requireTwoConsecutive, + savedNominalReps = savedNominalReps, ) } @@ -511,7 +618,9 @@ object RoutineCsvCodec { ) private fun parseV2Settings(row: RawRow, issues: MutableList, layout: Layout): V2Settings { - if (layout.version != RoutineCsvFormat.VERSION_V2) return V2Settings() + if (layout.version != RoutineCsvFormat.VERSION_V2 && layout.version != RoutineCsvFormat.VERSION_V3) { + return V2Settings() + } return V2Settings( usePercentOfPR = optionalBool(row, COL_USE_PERCENT_OF_PR, "use_percent_of_pr", false, issues) ?: false, weightPercentOfPR = optionalInt(row, COL_WEIGHT_PERCENT_OF_PR, "weight_percent_of_pr", 0, RoutineCsvFormat.MAX_PERCENT, issues) diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvFormat.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvFormat.kt index 55a999f8a..676aebb7f 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvFormat.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvFormat.kt @@ -52,9 +52,21 @@ import com.devil.phoenixproject.util.Constants object RoutineCsvFormat { const val VERSION = 1 const val VERSION_V2 = 2 + + /** + * Version 3 (#1392): the config-preserving power-loss format. [COLUMNS_V3_ONLY] + * carry `ExerciseConfig.powerLoss` ([com.devil.phoenixproject.domain.powerloss.PowerLossConfig]) + * exactly, so a POWER routine round-trips without being silently downgraded to + * REP. A routine that uses non-default power-loss config is NEVER written as + * version 2 — see [RoutineCsvCodec.encode] and its lossy-export block. Apps + * reading version 2 only refuse version 3 files ("Unsupported file version") + * instead of quietly importing a POWER routine as REP. + */ + const val VERSION_V3 = 3 const val VERSION_PREFIX = "# phoenix_routine_csv_version=" const val VERSION_LINE = "$VERSION_PREFIX$VERSION" const val VERSION_V2_LINE = "$VERSION_PREFIX$VERSION_V2" + const val VERSION_V3_LINE = "$VERSION_PREFIX$VERSION_V3" val COLUMNS = listOf( "routine_id", @@ -108,6 +120,24 @@ object RoutineCsvFormat { /** The version 2 header: the v1 columns, unchanged, then [COLUMNS_V2_ONLY]. */ val COLUMNS_V2 = COLUMNS + COLUMNS_V2_ONLY + /** + * Columns version 3 adds to [COLUMNS_V2]: the per-exercise power-loss target + * config (`ExerciseConfig.powerLoss`). Enum cells hold constant names + * (`REP_TARGET`, `POWER`); blank numeric cells mean absent (null), never zero. + * A blank `power_loss_target_mode` or an unknown name reads as inert + * `REP_TARGET` — import never silently arms POWER from an unknown string. + */ + val COLUMNS_V3_ONLY = listOf( + "power_loss_target_mode", + "power_loss_threshold_percent", + "power_loss_max_working_reps", + "power_loss_require_two_consecutive", + "power_loss_saved_nominal_reps", + ) + + /** The version 3 header: the v2 columns, unchanged, then [COLUMNS_V3_ONLY]. */ + val COLUMNS_V3 = COLUMNS_V2 + COLUMNS_V3_ONLY + /** Denial-of-service bounds for a picked file. */ const val MAX_BYTES = 2 * 1024 * 1024 const val TOO_LARGE_MESSAGE = "The file is larger than 2 MB." diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvImportPlanner.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvImportPlanner.kt index 14ddb0843..c4d4133df 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvImportPlanner.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvImportPlanner.kt @@ -332,6 +332,9 @@ class RoutineCsvImportPlanner( rackBehaviorOverrides = row.rackBehaviorOverrides, durationSyncKnown = false, isLaunchAdjustedDuration = false, + // Issue #1392: the power-loss target config rides the version 3 file + // and round-trips unchanged (absent = inert REP defaults, never zeros). + powerLoss = row.powerLoss, ) } diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/ExerciseConfig.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/ExerciseConfig.kt index 6e8574065..b9fbd9efc 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/ExerciseConfig.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/ExerciseConfig.kt @@ -23,6 +23,11 @@ data class ExerciseConfig( // absolute weight — template exercises use live %-of-1RM resolution unless the // user deliberately overrides it. (#633 review) val userEditedWeight: Boolean = false, + + // Issue #1392 — per-exercise set-target mode (REP_TARGET default; POWER opt-in). + // Pure domain config; default is inert. Never affects legacy routine semantics. + val powerLoss: com.devil.phoenixproject.domain.powerloss.PowerLossConfig = + com.devil.phoenixproject.domain.powerloss.PowerLossConfig.DEFAULT, ) { companion object { /** diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/Models.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/Models.kt index 948a6cc95..a82e98460 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/Models.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/Models.kt @@ -123,6 +123,9 @@ sealed class WorkoutState { val taggedExerciseId: String? = null, val taggedExerciseName: String? = null, val isAmrap: Boolean = false, + // Issue #1392 — power-loss summary facts (null when POWER was not armed; + // never fabricated). Rendered only with the SD6 completed/attempt clarification. + val powerLoss: com.devil.phoenixproject.domain.powerloss.PowerLossSetSummaryFacts? = null, ) : WorkoutState() data class BodyweightRepEntry( val exerciseKey: String, @@ -386,6 +389,11 @@ data class WorkoutParameters( val eccentricLoad: EccentricLoad = EccentricLoad.LOAD_100, // Just Lift rest timer (0 = off, 5-300 in 5s increments) val justLiftRestSeconds: Int = 0, + // Issue #1392 — per-exercise set-target config copied into every generated + // WorkoutParameters (integration-model §4). Default is inert REP_TARGET; + // POWER arms only from explicit per-exercise config behind the capability gate. + val powerLoss: com.devil.phoenixproject.domain.powerloss.PowerLossConfig = + com.devil.phoenixproject.domain.powerloss.PowerLossConfig.DEFAULT, ) { /** True if this is an Echo workout */ val isEchoMode: Boolean get() = programMode == ProgramMode.Echo @@ -546,6 +554,9 @@ sealed class HapticEvent { /** Issue #313: Velocity loss threshold reached — strong haptic + alert sound */ data object VELOCITY_THRESHOLD_REACHED : HapticEvent() + /** Issue #1392: power-loss near-limit cue at max(0, threshold − 5)% loss — once per set */ + data object POWER_NEAR_LIMIT : HapticEvent() + /** Issue #100: Distinct transition sound from warmup to working sets */ data object WARMUP_TO_WORKING : HapticEvent() diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/Routine.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/Routine.kt index b8a79f3ea..78a9456f6 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/Routine.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/Routine.kt @@ -141,6 +141,13 @@ data class RoutineExercise( // Runtime only: Active Recovery/Heavy Deload changed the launch prescription. // The session persists this provenance; the routine template remains untouched. val isLaunchAdjustedByRoutineModifier: Boolean = false, + // Issue #1392 — per-exercise power-loss set-target config (REP_TARGET default; + // POWER opt-in). Persisted in the additive PowerLossExerciseConfig table + // (migration 65); absent row decodes to PowerLossConfig.DEFAULT (inert + // REP_TARGET with nulls, never zeros) and never changes legacy routine + // semantics. Strict readers never arm POWER from an unknown or excluded mode. + val powerLoss: com.devil.phoenixproject.domain.powerloss.PowerLossConfig = + com.devil.phoenixproject.domain.powerloss.PowerLossConfig.DEFAULT, ) { companion object { const val MIN_TIMED_DURATION_SECONDS = 10 diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/TrainingCycleModels.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/TrainingCycleModels.kt index f6bf97823..b99d5f247 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/TrainingCycleModels.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/model/TrainingCycleModels.kt @@ -374,6 +374,15 @@ enum class SetEndReason { /** Timed exercise countdown reached zero */ TIMER_EXPIRED, + /** Issue #1392: POWER target mode max-working-reps backstop fired (SD4) */ + MAX_REPS_BACKSTOP, + + /** Issue #1392: power-loss autostop — MCP dropped >= threshold below best working rep */ + POWER_LOSS, + + /** Issue #1392: trusted short-ROM observation qualified as triggering (SD1/SD2) */ + SHORT_ROM, + /** Persisted reason is absent, malformed, or not supported by this app version */ UNKNOWN, diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/powerloss/PowerLossAcquisition.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/powerloss/PowerLossAcquisition.kt new file mode 100644 index 000000000..5e87506fc --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/powerloss/PowerLossAcquisition.kt @@ -0,0 +1,322 @@ +package com.devil.phoenixproject.domain.powerloss + +import kotlin.math.max + +/** + * Issue #1392 — P1 acquisition + identity contract. + * + * MCP V1 is computed from **pre-EMA validated paired control samples only** — + * never from legacy `avgPowerWatts` or midpoint segmentation (SD1). The metric + * is the arithmetic sample mean of per-sample summed paired-cable power: + * + * ``` + * P_sample = 9.81/1000 × (loadA × max(vA, 0) + loadB × max(vB, 0)) [W] + * ``` + * + * with loads in kg and raw signed velocities in mm/s. An idle cable contributes + * 0; there is no cross-cable velocity substitution. Signed lowering velocity + * never becomes lifting power. + */ + +/** Machine cable identity. */ +enum class PowerCable { A, B } + +/** Enumerable MCP V1 quality-rejection reasons (P1 acceptance). */ +enum class McpQualityReason { + /** Timestamp gap at/over the freshness bound inside the window. */ + SAMPLE_GAP, + + /** Stale sample (freshness violation) contaminated the window. */ + STALE_DATA, + + /** A rejected/clamped sample contaminated the window. */ + REJECTED_SAMPLE, + + /** The ordered accumulator overflowed and dropped samples. */ + BUFFER_OVERFLOW, + + /** Fewer than the minimum usable samples. */ + INSUFFICIENT_SAMPLES, + + /** Concentric phase could not be established for the window. */ + PHASE_UNAVAILABLE, + ; +} + +/** Per-sample quality markers from the validated paired control-sample derivation. */ +data class SampleQualityMarkers( + val clamped: Boolean = false, + val rejected: Boolean = false, + val stale: Boolean = false, + /** Gap of at/over 100 ms before this sample. */ + val gapBefore: Boolean = false, +) { + val contaminated: Boolean get() = clamped || rejected || stale || gapBefore +} + +/** + * Versioned validated pre-EMA paired control sample (MCP metric version 1). + * Raw signed velocities: negative = lowering. Never smoothed/EMA-filtered. + */ +data class ValidatedPairedSample( + val executionId: String, + val windowOrdinal: Int, + val loadAKg: Float, + val loadBKg: Float, + val velocityAMmS: Float, + val velocityBMmS: Float, + val positionAMm: Float, + val positionBMm: Float, + val deviceTicks: Long, + val monotonicTimestampMs: Long, + val quality: SampleQualityMarkers = SampleQualityMarkers(), +) { + /** True when cable has load applied (idle cable = 0 kg). */ + fun isCableActive(cable: PowerCable): Boolean = when (cable) { + PowerCable.A -> loadAKg > 0f + PowerCable.B -> loadBKg > 0f + } + + /** + * MCP V1 sample power in W: `9.81/1000 × (loadA×max(vA,0) + loadB×max(vB,0))`. + * Idle cable contributes 0; no cross-cable substitution; lowering never counts. + */ + fun samplePowerWatts(): Float { + val a = if (isCableActive(PowerCable.A)) loadAKg * max(velocityAMmS, 0f) else 0f + val b = if (isCableActive(PowerCable.B)) loadBKg * max(velocityBMmS, 0f) else 0f + return GRAVITY_PER_MMS_TO_W * (a + b) + } + + companion object { + /** `9.81 / 1000`: kg·mm/s → W. */ + const val GRAVITY_PER_MMS_TO_W = 9.81f / 1000f + + /** Freshness bound: a gap at/over 100 ms is a sample gap (P1 tests). */ + const val MAX_SAMPLE_GAP_MS = 100L + + /** Minimum usable samples for a valid MCP window (P1 acceptance). */ + const val MIN_SAMPLES = 3 + } +} + +/** Result of an MCP V1 computation over one sealed concentric window. */ +data class McpComputation( + /** Arithmetic sample mean of [ValidatedPairedSample.samplePowerWatts]; null when unusable. */ + val mcpWatts: Float?, + /** Non-null exactly when [mcpWatts] is null. */ + val qualityReason: McpQualityReason?, + val sampleCount: Int, +) { + companion object { + fun unavailable(reason: McpQualityReason, sampleCount: Int = 0): McpComputation = + McpComputation(mcpWatts = null, qualityReason = reason, sampleCount = sampleCount) + } +} + +/** MCP V1 signal derivation (pure). */ +object MeanConcentricPower { + /** Metric version stamp carried into persistence (P4). */ + const val POWER_METRIC_VERSION = 1 + + /** + * Compute MCP V1 over the sealed concentric window's validated samples. + * + * Order of rejection: contaminated windows (gap / stale / rejected / overflow) + * fail first, then insufficient samples, then the arithmetic mean. A computed + * mean that is non-positive is reported as-is (callers treat non-positive as + * an invalid measurement for policy qualification; nothing is fabricated). + */ + fun compute( + samples: List, + overflowed: Boolean = false, + ): McpComputation { + if (overflowed) return McpComputation.unavailable(McpQualityReason.BUFFER_OVERFLOW, samples.size) + if (samples.any { it.quality.gapBefore }) { + return McpComputation.unavailable(McpQualityReason.SAMPLE_GAP, samples.size) + } + if (samples.any { it.quality.stale }) { + return McpComputation.unavailable(McpQualityReason.STALE_DATA, samples.size) + } + if (samples.any { it.quality.rejected || it.quality.clamped }) { + return McpComputation.unavailable(McpQualityReason.REJECTED_SAMPLE, samples.size) + } + if (samples.size < ValidatedPairedSample.MIN_SAMPLES) { + return McpComputation.unavailable(McpQualityReason.INSUFFICIENT_SAMPLES, samples.size) + } + val mean = samples.map { it.samplePowerWatts() }.average().toFloat() + return McpComputation(mcpWatts = mean, qualityReason = null, sampleCount = samples.size) + } +} + +/** + * Bounded ordered accumulator for validated paired control samples (P1). + * + * Ordering is by monotonic timestamp with device-tick tie-breaks within the + * execution epoch. Duplicates and out-of-order submissions are rejected (counted, + * never silently dropped); overflow is counted and the window is marked unusable. + * Consumption is serialized: [drain] returns and clears the pending ordered batch. + */ +class OrderedSampleAccumulator( + private val capacity: Int = DEFAULT_CAPACITY, +) { + private val pending = mutableListOf() + + var rejectedCount: Int = 0 + private set + var overflowCount: Int = 0 + private set + var gapCount: Int = 0 + private set + + private var lastTimestampMs: Long = Long.MIN_VALUE + + val overflowed: Boolean get() = overflowCount > 0 + + /** + * Submit one sample. Returns false when the sample was rejected (duplicate or + * out-of-order timestamp) or overflowed; the counters record which. + * Callers serialize submissions (single-writer delivery path). + */ + fun submit(sample: ValidatedPairedSample): Boolean { + if (lastTimestampMs != Long.MIN_VALUE && sample.monotonicTimestampMs <= lastTimestampMs) { + rejectedCount++ + return false + } + if (lastTimestampMs != Long.MIN_VALUE && + sample.monotonicTimestampMs - lastTimestampMs >= ValidatedPairedSample.MAX_SAMPLE_GAP_MS + ) { + gapCount++ + } + if (pending.size >= capacity) { + overflowCount++ + return false + } + pending.add(sample) + lastTimestampMs = sample.monotonicTimestampMs + return true + } + + /** Serialize consumption: returns the ordered pending batch and clears it. */ + fun drain(): List { + val batch = pending.toList() + pending.clear() + return batch + } + + companion object { + const val DEFAULT_CAPACITY = 1024 + } +} + +/** + * Finite-state concentric phase normalizer (P1). + * + * - Concentric starts when an active cable's forward velocity exceeds + * [forwardThresholdMmS] (10 mm/s). + * - The window ends on a validated top-turnaround or when both active forward + * velocities are ≤ [forwardThresholdMmS] for two fresh samples. + * - The window seals **exactly once** on the next fresh ordered sample; that + * sample belongs to the next window (or idle), never to the sealed one. + * + * Only sealed windows are eligible for MCP V1; mid-window reads are forbidden. + */ +class ConcentricPhaseNormalizer( + private val forwardThresholdMmS: Float = FORWARD_THRESHOLD_MM_S, +) { + enum class State { IDLE, ACCUMULATING, PENDING_SEAL } + + var state: State = State.IDLE + private set + + private val window = mutableListOf() + private var belowThresholdStreak = 0 + + /** Sealed concentric windows in order. */ + val sealedWindows = mutableListOf>() + + /** + * Feed one fresh ordered sample. Returns the sealed window when this sample + * completed a seal (the sample itself is not part of the window), else null. + */ + fun onSample(sample: ValidatedPairedSample): List? { + if (sample.quality.stale || sample.quality.rejected) return null + return when (state) { + State.IDLE -> { + if (isForwardAboveThreshold(sample)) { + window.add(sample) + state = State.ACCUMULATING + } + null + } + State.ACCUMULATING -> { + window.add(sample) + val bothBelow = bothActiveAtOrBelowThreshold(sample) + val turnaround = isTopTurnaround(sample) + if (turnaround || bothBelow) { + belowThresholdStreak = if (bothBelow) belowThresholdStreak + 1 else belowThresholdStreak + if (turnaround || belowThresholdStreak >= 2) { + state = State.PENDING_SEAL + } + } else { + belowThresholdStreak = 0 + } + null + } + State.PENDING_SEAL -> { + // Seal exactly once on the next fresh ordered sample; that sample + // is excluded from the sealed window. + val sealed = window.toList() + window.clear() + belowThresholdStreak = 0 + sealedWindows.add(sealed) + state = State.IDLE + if (isForwardAboveThreshold(sample)) { + window.add(sample) + state = State.ACCUMULATING + } + sealed + } + } + } + + private fun forwardVelocities(sample: ValidatedPairedSample): List = + buildList { + if (sample.isCableActive(PowerCable.A)) add(sample.velocityAMmS) + if (sample.isCableActive(PowerCable.B)) add(sample.velocityBMmS) + } + + private fun isForwardAboveThreshold(sample: ValidatedPairedSample): Boolean = + forwardVelocities(sample).any { it > forwardThresholdMmS } + + private fun bothActiveAtOrBelowThreshold(sample: ValidatedPairedSample): Boolean { + val v = forwardVelocities(sample) + if (v.isEmpty()) return true // idle counts as at/below threshold + return v.all { it <= forwardThresholdMmS } + } + + /** + * Validated top-turnaround: the sample's forward velocity crossed from above + * threshold to non-forward (≤ 0) on an active cable. + */ + private fun isTopTurnaround(sample: ValidatedPairedSample): Boolean { + val previous = window.getOrNull(window.size - 2) ?: return false + val active = PowerCable.entries.filter { sample.isCableActive(it) } + return active.any { cable -> + previousVelocity(previous, cable) > forwardThresholdMmS && + currentVelocity(sample, cable) <= 0f + } + } + + private fun previousVelocity(sample: ValidatedPairedSample, cable: PowerCable): Float = + when (cable) { + PowerCable.A -> sample.velocityAMmS + PowerCable.B -> sample.velocityBMmS + } + + private fun currentVelocity(sample: ValidatedPairedSample, cable: PowerCable): Float = + previousVelocity(sample, cable) + + companion object { + const val FORWARD_THRESHOLD_MM_S = 10f + } +} diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/powerloss/PowerLossEvidence.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/powerloss/PowerLossEvidence.kt new file mode 100644 index 000000000..543ea9138 --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/powerloss/PowerLossEvidence.kt @@ -0,0 +1,175 @@ +package com.devil.phoenixproject.domain.powerloss + +/** + * Issue #1392 — frozen cross-packet evidence contract (P3 engine ↔ P4 persistence ↔ P5 UI). + * + * Pure domain types only: no BLE, SQL, UI, or audio references. These types are the + * single shared vocabulary for: + * - P3 (engine): fills [PowerLossSetEvidence] / [PowerLossHudState] at completion-latch + * and live-HUD time, and attaches evidence to `WorkoutExitSnapshot.powerLossEvidence`. + * - P4 (persistence): persists evidence durably (set + observation companions, backup, + * versioned CSV, power-history export v1) with null-vs-zero semantics preserved and + * ZERO new wire keys. + * - P5 (UI): renders config/HUD/summary/history strictly from these facts. + * + * Frozen by the implementation coordinator before packet fan-out. Extend only when a + * ui-spec state cannot be expressed, and report the extension in the packet handoff. + * + * Binding signoff decisions SD1–SD8 apply to every type here: no fabricated zeros + * (missing data is null with a quality reason), both qualification facts are persisted, + * reference-at-decision facts are frozen, and legacy payloads stay unchanged. + */ + +/** `powerMetricVersion` for the V1 Mean Concentric Power signal (never backfilled from legacy curves). */ +const val POWER_METRIC_VERSION: Int = 1 + +/** + * One durable per-attempt observation row (P4 observation companion). + * + * Attempt-only rows (a working attempt that never completed a rep) are first-class: + * `completed = false` with a non-null ordinal. Rows never fabricate zeros — every + * metric is nullable and absence is preserved as null through export/backup. + * + * @property workingConcentricOrdinal Stable `(session, execution, working concentric ordinal)` + * identity. Warmups are excluded from the tally and are not persisted here. + * @property completed False for pending/attempt-only identity (candidate ≠ completed). + * @property legacyRepIndex Optional association with an existing legacy `RepMetric` row + * position; null for attempt-only rows with no legacy rep. + * @property mcpWatts MCP V1 (sample-mean `9.81/1000 × Σ(load × max(v,0))` W) or null when + * the concentric phase/samples could not be validated (never 0 as a stand-in). + * @property eccentricPowerWatts Eccentric power logged separately (Echo: trigger is + * concentric-only). Interrupted eccentric = null, not 0. + * @property lossPercentAtDecision Unrounded `100 × (1 − MCP/bestMCP)` frozen at decision + * time (SD3), or null when the attempt had no valid power. + * @property referenceWorkingOrdinal Reference-at-decision (frozen before any reference + * update), or null when no reference existed yet. + * @property romAMm / romBMm Measured per-cable ROM in mm; null when unavailable. + * @property romAPercentOfReference / romBPercentOfReference Percent of the reference ROM + * where trustworthy; null otherwise (SD3: unknown ROM is never promoted). + * @property romTrustworthy False for untrusted/unknown ROM windows. + * @property quality Enumerable quality markers backing a null metric (sample gap, stale + * data, rejected sample, buffer overflow, insufficient samples, phase unavailable). + * @property shortRom True when this observation qualified as a trusted short-ROM + * observation (any active cable strictly < 85% of reference; equality is not short). + * @property powerLossQualified True when this observation qualified as a power-loss + * observation. Both facts may be true simultaneously (SD2 persists both). + */ +data class PowerLossAttemptRecord( + val workingConcentricOrdinal: Int, + val completed: Boolean, + val legacyRepIndex: Int? = null, + val mcpWatts: Float? = null, + val eccentricPowerWatts: Float? = null, + val concentricDurationMs: Long? = null, + val eccentricDurationMs: Long? = null, + val lossPercentAtDecision: Float? = null, + val referenceWorkingOrdinal: Int? = null, + val romAMm: Float? = null, + val romBMm: Float? = null, + val romAPercentOfReference: Float? = null, + val romBPercentOfReference: Float? = null, + val romTrustworthy: Boolean = false, + val quality: SampleQualityMarkers = SampleQualityMarkers(), + val shortRom: Boolean = false, + val powerLossQualified: Boolean = false, +) + +/** + * Immutable deep-frozen evidence for one set (P4 set companion). Captured at the + * leased-completion latch, before claim/teardown, and persisted with the completed + * set (retry/idempotent). Keyed by stable session id + set id. + */ +data class PowerLossSetEvidence( + val sessionId: String, + val setId: String, + val metricVersion: Int = POWER_METRIC_VERSION, + // Frozen target configuration (SD4: cap independent; saved nominal never stops POWER). + val targetMode: TargetMode, + val thresholdPercent: Int, + val maxWorkingReps: Int?, + val requireTwoConsecutive: Boolean, + val savedNominalReps: Int?, + // Frozen active-cable mask + provenance (SD3). + val activeCables: Set, + val activeCableProvenance: String, + // Reference-at-decision facts, frozen before any reference update (SD3). + val referenceWorkingOrdinal: Int?, + val referenceMcpWatts: Float?, + val referenceRomAMm: Float?, + val referenceRomBMm: Float?, + // Trigger facts. + val triggerWorkingOrdinal: Int?, + // Immutable winning reason; null when the set ended without a power-policy stop + // (manual/safety/REP paths keep their own SetEndReason). + val winnerReason: PowerStopReason?, + // Both qualification facts persisted even when simultaneous (SD2). + val shortRomObserved: Boolean, + val powerLossObserved: Boolean, + val lossPercentAtDecision: Float?, + val attempts: List = emptyList(), +) + +/** + * Live HUD facts for the active set (P3 → P5). The UI renders copy from these facts + * per ui-spec §3–§7 with SD6 corrections; missing data shows `—` with a reason and + * is never fabricated as zero. + */ +data class PowerLossHudState( + val powerActive: Boolean = false, + val thresholdPercent: Int = 20, + val nearLimitLossPercent: Int = 15, + val maxWorkingReps: Int? = null, + val savedNominalReps: Int? = null, + /** Working-attempt identity of the rep being processed (pending semantics). */ + val currentAttemptOrdinal: Int = 0, + /** Authoritative completed count (`actualReps`) — never promoted to the attempt count. */ + val completedRepCount: Int = 0, + val referenceEstablished: Boolean = false, + val referenceWorkingOrdinal: Int? = null, + /** Last attempt's loss at decision; null when power was invalid/unavailable. */ + val lastLossPercent: Float? = null, + /** Ordinal of the last attempt with valid power (for `Last valid · attempt N` labeling). */ + val lastValidAttemptOrdinal: Int? = null, + /** Enumerable invalid-power reason (quality reason) for the current attempt, or null. */ + val invalidPowerReason: String? = null, + val nearLimitCueEmitted: Boolean = false, + /** Per-cable ROM as percent of reference where trustworthy (e.g. `Cable A 82% of reference`). */ + val cableRomPercentOfReference: Map = emptyMap(), + /** Committed `Ending set…` state (distinct from the completed transition). */ + val endingSet: Boolean = false, + /** Latest sealed concentric MCP in watts (`Latest lifting power … W`); null when unavailable. */ + val lastMcpWatts: Float? = null, + /** Best working MCP in watts (`Best: rep N · … W`); null until a reference exists. */ + val bestMcpWatts: Float? = null, + /** + * Two-consecutive qualifying streak (1..2), or null when the requirement is + * off (`Qualifying attempts: 1 of 2`, SD1). A reset streak is 0 and renders + * the neutral state, never a stale qualifier line. + */ + val qualifyingCount: Int? = null, + /** Initial ROM/mask uncertainty: the reference exists but no trustworthy ROM. */ + val referenceRomUncertain: Boolean = false, +) + +/** + * Summary/history facts for a stopped set (P3 → P5). The headline + * `Stopped at rep 9 — 21% power loss (best: rep 2)` renders ONLY with the adjacent + * `8 completed reps · lifting attempt 9` clarification (SD6); [completedRepCount] + * comes from `actualReps` and is never promoted to match the headline. + */ +data class PowerLossSetSummaryFacts( + val winnerReason: PowerStopReason?, + val thresholdPercent: Int, + val maxWorkingReps: Int?, + val requireTwoConsecutive: Boolean, + /** Working attempt at which the set stopped (headline number), or null. */ + val stoppedAtWorkingAttempt: Int?, + val completedRepCount: Int, + val lossPercentAtStop: Float?, + val bestWorkingOrdinal: Int?, + val shortRomObserved: Boolean, + val powerLossObserved: Boolean, + val attempts: List = emptyList(), + /** SD6 `Saved reps: 12` readback source (config at set time; null renders `—`). */ + val savedNominalReps: Int? = null, +) diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/powerloss/PowerLossModels.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/powerloss/PowerLossModels.kt new file mode 100644 index 000000000..68c5740e6 --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/powerloss/PowerLossModels.kt @@ -0,0 +1,241 @@ +package com.devil.phoenixproject.domain.powerloss + +import com.devil.phoenixproject.domain.model.ProgramMode + +/** + * Issue #1392 — power-loss autostop (VBT-style): configuration and execution target plan. + * + * Opt-in per-exercise POWER set termination. A set auto-ends when per-rep Mean + * Concentric Power (MCP) drops [PowerLossConfig.thresholdPercent] below the best + * valid working rep, or on a trusted short-ROM observation. See + * `implementation-spec.md` §2 for the binding signoff decisions (SD1–SD8). + * + * Pure domain types only: no BLE, SQL, UI, or audio references. + */ + +/** Per-exercise set-target mode. REP_TARGET preserves existing behavior. */ +enum class TargetMode { + /** Fixed rep target (existing behavior, default). */ + REP_TARGET, + + /** Power-loss autostop with mandatory max-reps backstop (opt-in). */ + POWER, + ; + + companion object { + /** + * Strict reader: unknown persisted values resolve to null so callers can + * fail safe (never arm POWER from an unknown enum — spec §7). + */ + fun fromPersisted(value: String?): TargetMode? = entries.firstOrNull { it.name == value } + } +} + +/** + * Per-exercise power-loss configuration (P2 domain type). + * + * @property targetMode REP_TARGET (default) or POWER (opt-in). + * @property thresholdPercent Integer percent, valid range 5–40 (default 20). + * UI cautions 36–40; validation never silently clamps — [validated] returns null. + * @property maxWorkingReps Mandatory backstop, min 2 (default 20). Not a product + * maximum; the protocol-specific byte bound is checked at plan derivation (SD4). + * @property requireTwoConsecutive Optional 2-consecutive-qualifying-reps guard. + * @property savedNominalReps The user's saved nominal rep target, preserved as-is. + * In POWER mode it is display-only and must never stop the set early (SD4). + */ +data class PowerLossConfig( + val targetMode: TargetMode = TargetMode.REP_TARGET, + val thresholdPercent: Int = 20, + val maxWorkingReps: Int = 20, + val requireTwoConsecutive: Boolean = false, + val savedNominalReps: Int? = null, +) { + /** Near-limit warning threshold: `threshold − 5`, floored at 0 (first positive loss at 5%). */ + val nearLimitLossPercent: Int + get() = maxOf(0, thresholdPercent - NEAR_LIMIT_OFFSET_PERCENT) + + /** True when every field is in range. Strict: no silent clamping. */ + fun isValid(): Boolean = + thresholdPercent in MIN_THRESHOLD_PERCENT..MAX_THRESHOLD_PERCENT && + maxWorkingReps >= MIN_MAX_WORKING_REPS && + (savedNominalReps == null || savedNominalReps >= 1) + + /** This config or null when any field is out of range. */ + fun validated(): PowerLossConfig? = takeIf { isValid() } + + companion object { + const val MIN_THRESHOLD_PERCENT = 5 + const val MAX_THRESHOLD_PERCENT = 40 + const val MIN_MAX_WORKING_REPS = 2 + const val NEAR_LIMIT_OFFSET_PERCENT = 5 + + /** Default is inert: REP mode with defaults. */ + val DEFAULT = PowerLossConfig() + } +} + +/** + * Protocol family for power-loss capability gating. V1 effective modes are + * Old School, Pump, Echo, and Just Lift execution style; TUT / TUT Beast / + * Eccentric-Only / timed / bodyweight are retained-but-inert (spec §1). + */ +enum class PowerLossProtocolFamily { + OLD_SCHOOL, + PUMP, + ECHO, + JUST_LIFT, + /** TUT, TUT Beast, Eccentric-Only, timed, bodyweight, unknown. */ + UNSUPPORTED, + ; + + val supportsPowerLoss: Boolean + get() = this != UNSUPPORTED + + companion object { + /** + * Map a [ProgramMode] plus the Just Lift execution-style flag to the + * protocol family. Just Lift is an execution style, not a ProgramMode — + * but V1 effective modes are Old School / Pump / Echo only: a TUT, + * TUT Beast or Eccentric-Only set stays excluded even in Just Lift + * style, so POWER never arms from an excluded mode (spec §1/§7). + */ + fun of(mode: ProgramMode, isJustLiftExecutionStyle: Boolean): PowerLossProtocolFamily { + return when (mode) { + ProgramMode.OldSchool -> if (isJustLiftExecutionStyle) JUST_LIFT else OLD_SCHOOL + ProgramMode.Pump -> if (isJustLiftExecutionStyle) JUST_LIFT else PUMP + ProgramMode.Echo -> if (isJustLiftExecutionStyle) JUST_LIFT else ECHO + else -> UNSUPPORTED + } + } + } +} + +/** + * Capability gate: POWER arms only when the protocol family is supported AND the + * signal prerequisites hold (validated paired samples available). Default OFF — + * an internal gate, never a user-facing "readiness" claim. + */ +object PowerLossCapability { + fun isEligible( + protocolFamily: PowerLossProtocolFamily, + pairedSamplesValidated: Boolean, + ): Boolean = protocolFamily.supportsPowerLoss && pairedSamplesValidated +} + +/** + * Protocol byte bounds for working-rep targets, supplied by the caller at plan + * derivation. The Echo finite working-byte bound is taken from the accepted + * target-plan validator's bound only — never hardcoded here (spec P2 stop rule). + * + * @property maxRepresentableWorkingReps Largest working-rep count the protocol + * frame can represent (e.g. PROGRAM: `254 − warmupSetCount`). + * @property protocolIdentityFinite True when the protocol's rep target is finite; + * false for unlimited identities (Just Lift / AMRAP) which must stay unlimited + * under REP_TARGET (SD4). + */ +data class ProtocolRepBounds( + val maxRepresentableWorkingReps: Int, + val protocolIdentityFinite: Boolean, +) + +/** + * One immutable execution target plan derived before Start (SD4). The identical + * effective target is propagated through packet/counter/freshness/validation/HUD + * so firmware and app agree on the cap. + * + * @property targetMode Effective mode for this set. + * @property nominalReps Saved nominal rep target; display-only in POWER mode. + * @property maxWorkingReps Effective cap in POWER mode. Null under REP_TARGET + * with an unlimited protocol identity. + * @property warmupSetCount Warmup bound preserved from the plan. + * @property protocolIdentityFinite Finite/unlimited protocol identity preserved. + * @property planValidatedAt Monotonic ms when the plan was derived (before Start). + */ +data class ExecutionTargetPlan( + val targetMode: TargetMode, + val nominalReps: Int?, + val maxWorkingReps: Int?, + val warmupSetCount: Int, + val protocolIdentityFinite: Boolean, + val planValidatedAt: Long, +) { + /** Cap stops the set only in POWER mode and only with a finite cap. */ + fun capStopAtWorkingAttempt(workingAttemptOrdinal: Int): Boolean = + targetMode == TargetMode.POWER && + maxWorkingReps != null && + workingAttemptOrdinal >= maxWorkingReps + + /** + * The frozen effective working-rep target every consumer must share (SD4): + * POWER's mandatory max-reps backstop (the cap the app stops at), or the REP + * nominal. Null for unlimited identities under REP_TARGET (Just Lift / AMRAP + * stay unlimited on the wire). + */ + val effectiveWorkingReps: Int? + get() = when (targetMode) { + TargetMode.POWER -> maxWorkingReps + TargetMode.REP_TARGET -> if (protocolIdentityFinite) nominalReps else null + } + + companion object { + /** + * Derive the plan before Start. Rejects impossible plans by returning null: + * - POWER requires a valid config and a finite representable bound of at + * least [PowerLossConfig.MIN_MAX_WORKING_REPS]. + * - REP_TARGET keeps the protocol identity: unlimited stays unlimited and + * never derives a cap from the nominal target (nominal-below-cap must + * never stop POWER early; equally a nominal never caps REP identity). + */ + fun derive( + config: PowerLossConfig, + bounds: ProtocolRepBounds, + warmupSetCount: Int, + now: Long, + ): ExecutionTargetPlan? { + if (!config.isValid() || warmupSetCount < 0) return null + return when (config.targetMode) { + TargetMode.POWER -> { + // Mandatory finite backstop, checked against the protocol bound. + if (bounds.maxRepresentableWorkingReps < PowerLossConfig.MIN_MAX_WORKING_REPS) return null + if (config.maxWorkingReps > bounds.maxRepresentableWorkingReps) return null + ExecutionTargetPlan( + targetMode = TargetMode.POWER, + nominalReps = config.savedNominalReps, + maxWorkingReps = config.maxWorkingReps, + warmupSetCount = warmupSetCount, + // SD4: finite/unlimited protocol identity is preserved even in + // POWER. A genuine Just Lift / AMRAP hardware-unlimited identity + // keeps its 0xFF wire sentinel and is capped in-app; only finite + // identities encode the cap into the frame. + protocolIdentityFinite = bounds.protocolIdentityFinite, + planValidatedAt = now, + ) + } + TargetMode.REP_TARGET -> { + val nominal = config.savedNominalReps + if (bounds.protocolIdentityFinite) { + if (nominal == null || nominal > bounds.maxRepresentableWorkingReps) return null + ExecutionTargetPlan( + targetMode = TargetMode.REP_TARGET, + nominalReps = nominal, + maxWorkingReps = null, + warmupSetCount = warmupSetCount, + protocolIdentityFinite = true, + planValidatedAt = now, + ) + } else { + // Unlimited identity (Just Lift / AMRAP): stays unlimited. + ExecutionTargetPlan( + targetMode = TargetMode.REP_TARGET, + nominalReps = nominal, + maxWorkingReps = null, + warmupSetCount = warmupSetCount, + protocolIdentityFinite = false, + planValidatedAt = now, + ) + } + } + } + } + } +} diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/powerloss/PowerLossPolicy.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/powerloss/PowerLossPolicy.kt new file mode 100644 index 000000000..84329eab1 --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/powerloss/PowerLossPolicy.kt @@ -0,0 +1,378 @@ +package com.devil.phoenixproject.domain.powerloss + +/** + * Issue #1392 — P2 pure policy reducer (SD1–SD4). + * + * Deterministic, side-effect-free: observations + baseline/streak state in, + * [PowerLossDecision] out. No BLE, SQL, UI, or audio. Every behavior here is + * fixture-determined by the signoff §4.1 matrix (`PowerLossPolicyTest`). + * + * Key rules (signoff binding decisions win over every older artifact): + * - SD1: control uses MCP V1 only; a trusted short-ROM qualification may survive + * missing power; unavailable power alone never qualifies; a streak resets only + * on an observation with **neither** qualifying reason. + * - SD2: SHORT_ROM wins over POWER_LOSS in the same sealed observation; both + * facts are persisted; cap outranks fatigue on the same cycle. + * - SD3: unknown/untrusted ROM never promotes (upgrades or establishes past) + * the reference; missing candidate ROM is neither fabricated full-ROM nor a + * short-ROM stop; reference-at-decision facts are frozen before any update. + * - SD4: cap enforcement is independent of telemetry quality and fatigue streak. + */ + +/** ROM trust for one cable's measurement window. */ +enum class CableRomTrust { TRUSTED, UNKNOWN } + +/** Per-cable ROM observation. `romMm == null` when no trusted measurement exists. */ +data class CableRom( + val romMm: Float?, + val trust: CableRomTrust, +) { + /** A trusted ROM measurement strictly above zero. */ + val isTrusted: Boolean get() = trust == CableRomTrust.TRUSTED && romMm != null && romMm > 0f + + companion object { + val UNKNOWN = CableRom(romMm = null, trust = CableRomTrust.UNKNOWN) + + fun trusted(romMm: Float): CableRom = CableRom(romMm = romMm, trust = CableRomTrust.TRUSTED) + } +} + +/** + * One sealed working (or warmup) observation fed to the reducer. + * + * @property workingConcentricOrdinal Stable `(session, execution, working concentric ordinal)` + * identity; warmups carry no ordinal semantics and never tally. + * @property mcpWatts MCP V1 watts, null when the measurement is unavailable/invalid. + * @property activeCables Frozen active-cable mask used for ROM qualification. + */ +data class PowerLossObservation( + val workingConcentricOrdinal: Int, + val isWarmup: Boolean = false, + val mcpWatts: Float? = null, + val romA: CableRom = CableRom.UNKNOWN, + val romB: CableRom = CableRom.UNKNOWN, + val activeCables: Set = setOf(PowerCable.A, PowerCable.B), +) { + fun romFor(cable: PowerCable): CableRom = when (cable) { + PowerCable.A -> romA + PowerCable.B -> romB + } + + /** True when MCP is a usable positive measurement (zero/negative never qualifies). */ + val hasValidMcp: Boolean get() = mcpWatts != null && mcpWatts > 0f +} + +/** Reference facts frozen at establishment/replacement (SD3). */ +data class PowerLossReference( + val workingConcentricOrdinal: Int, + val mcpWatts: Float, + val romA: CableRom, + val romB: CableRom, +) { + fun romFor(cable: PowerCable): CableRom = when (cable) { + PowerCable.A -> romA + PowerCable.B -> romB + } +} + +/** Reducer state. Immutable; each [PowerLossPolicy.observe] returns the successor. */ +data class PowerLossPolicyState( + val reference: PowerLossReference? = null, + val observedWorkingAttempts: Int = 0, + val consecutiveQualifyingCount: Int = 0, + val nearLimitWarned: Boolean = false, + val terminated: Boolean = false, + /** Last observed working ordinal; adjacency gaps reset the streak. */ + val lastWorkingConcentricOrdinal: Int? = null, +) { + companion object { + val INITIAL = PowerLossPolicyState() + } +} + +/** Terminal stop reason persisted via `SetEndReason` mapping (P3). */ +enum class PowerStopReason { + /** `1 − MCP_n/MCP_best ≥ threshold`. */ + POWER_LOSS, + + /** Trusted short-ROM observation (< 85% of reference ROM on any active cable). */ + SHORT_ROM, + + /** Mandatory max-reps backstop (SD4). */ + MAX_REPS_BACKSTOP, +} + +/** Outcome of one observation. */ +sealed interface PowerLossDecision { + /** No action; keep working. */ + data object Continue : PowerLossDecision + + /** Once-per-set near-limit warning at `max(0, threshold − 5)` loss. */ + data class NearLimitWarning( + val lossPercent: Float, + val referenceWorkingOrdinal: Int, + ) : PowerLossDecision + + /** Set termination. Facts are frozen at decision time (SD3). */ + data class Stop( + val reason: PowerStopReason, + val lossPercentAtDecision: Float?, + val referenceWorkingOrdinal: Int?, + val powerLossQualified: Boolean, + val shortRomQualified: Boolean, + ) : PowerLossDecision +} + +/** + * Persisted per-observation facts (P4 companion row): both qualification facts + * always persisted together with measured loss when valid (SD2). + */ +data class PowerLossObservationRecord( + val workingConcentricOrdinal: Int, + val isWarmup: Boolean, + val mcpWatts: Float?, + val lossPercentAtDecision: Float?, + val referenceWorkingOrdinal: Int?, + val powerLossQualified: Boolean, + val shortRomQualified: Boolean, + val romAPercentOfReference: Float?, + val romBPercentOfReference: Float?, + val activeCables: Set, +) { + /** Display helper: clamped 0–100 (P2 acceptance). */ + fun displayLossPercent(): Float? = lossPercentAtDecision?.coerceIn(0f, 100f) +} + +/** One reducer step: decision + record + successor state. */ +data class PowerLossStep( + val decision: PowerLossDecision, + val record: PowerLossObservationRecord, + val state: PowerLossPolicyState, +) + +/** Pure deterministic power-loss policy reducer. */ +object PowerLossPolicy { + + /** Short-ROM bound: strictly below 85% of the reference ROM is short (equality is not). */ + const val SHORT_ROM_FRACTION = 0.85 + + /** SD1 guard: ≥2 working reps before any fatigue trigger (earliest 2nd working attempt). */ + const val MIN_ATTEMPTS_FOR_TRIGGER = 2 + + fun observe( + state: PowerLossPolicyState, + observation: PowerLossObservation, + config: PowerLossConfig, + plan: ExecutionTargetPlan, + ): PowerLossStep { + if (state.terminated) { + return PowerLossStep( + decision = PowerLossDecision.Continue, + record = recordOf(observation, loss = null, referenceOrdinal = null, powerLoss = false, shortRom = false), + state = state, + ) + } + + // Warmups: no reference, no tally, never trigger. + if (observation.isWarmup) { + return PowerLossStep( + decision = PowerLossDecision.Continue, + record = recordOf(observation, loss = null, referenceOrdinal = null, powerLoss = false, shortRom = false), + state = state, + ) + } + + val frozenRef = state.reference + val attemptOrdinal = state.observedWorkingAttempts + 1 + + // SD3: freeze reference-at-decision facts before any reference update. + val romPercents = romPercentOfReference(observation, frozenRef) + // Unrounded loss in double precision: `100 × (1 − MCP/bestMCP)` compared + // against thresholdPercent without any display rounding (P2 acceptance). + val lossDouble: Double? = when { + frozenRef != null && observation.hasValidMcp -> + 100.0 * (1.0 - (observation.mcpWatts!!.toDouble() / frozenRef.mcpWatts.toDouble())) + frozenRef == null && observation.hasValidMcp -> 0.0 // own decision-time reference + else -> null + } + val lossUnrounded: Float? = lossDouble?.toFloat() + val referenceOrdinal: Int? = when { + frozenRef != null -> frozenRef.workingConcentricOrdinal + observation.hasValidMcp -> observation.workingConcentricOrdinal + else -> null + } + + // SD2: SHORT_ROM qualification survives missing power (SD1). + val shortRomQualified = isShortRomQualified(observation, frozenRef) + val powerLossQualified = + lossDouble != null && + frozenRef != null && + lossDouble >= config.thresholdPercent.toDouble() && + attemptOrdinal >= MIN_ATTEMPTS_FOR_TRIGGER + + val qualifying = powerLossQualified || shortRomQualified + + // P2: invalid/missing/skipped ordinals break adjacency — a streak survives + // only across strictly consecutive working concentric ordinals. + val ordinalAdjacent = state.lastWorkingConcentricOrdinal == null || + observation.workingConcentricOrdinal == state.lastWorkingConcentricOrdinal + 1 + val priorStreak = if (ordinalAdjacent) state.consecutiveQualifyingCount else 0 + + // SD4: cap is independent of telemetry quality and fatigue streak; SD2: cap > fatigue. + val capReached = plan.capStopAtWorkingAttempt(attemptOrdinal) + + val record = recordOf( + observation = observation, + loss = lossUnrounded, + referenceOrdinal = referenceOrdinal, + powerLoss = powerLossQualified, + shortRom = shortRomQualified, + romAPercent = romPercents[PowerCable.A], + romBPercent = romPercents[PowerCable.B], + ) + + val decision: PowerLossDecision = when { + capReached -> PowerLossDecision.Stop( + reason = PowerStopReason.MAX_REPS_BACKSTOP, + lossPercentAtDecision = lossUnrounded, + referenceWorkingOrdinal = referenceOrdinal, + powerLossQualified = powerLossQualified, + shortRomQualified = shortRomQualified, + ) + qualifying && fatigueStopAllowed(priorStreak, config) -> PowerLossDecision.Stop( + // SD2: SHORT_ROM wins over POWER_LOSS in the same observation. + reason = if (shortRomQualified) PowerStopReason.SHORT_ROM else PowerStopReason.POWER_LOSS, + lossPercentAtDecision = lossUnrounded, + referenceWorkingOrdinal = referenceOrdinal, + powerLossQualified = powerLossQualified, + shortRomQualified = shortRomQualified, + ) + shouldWarnNearLimit(state, config, lossUnrounded, frozenRef) -> { + PowerLossDecision.NearLimitWarning( + lossPercent = lossUnrounded!!, + referenceWorkingOrdinal = referenceOrdinal!!, + ) + } + else -> PowerLossDecision.Continue + } + + val stopped = decision is PowerLossDecision.Stop + val nextState = PowerLossPolicyState( + reference = updatedReference(state, observation, frozenRef), + observedWorkingAttempts = attemptOrdinal, + // SD1: only an observation with neither qualifying reason resets the streak. + consecutiveQualifyingCount = if (qualifying) priorStreak + 1 else 0, + nearLimitWarned = state.nearLimitWarned || decision is PowerLossDecision.NearLimitWarning || stopped, + terminated = stopped, + lastWorkingConcentricOrdinal = observation.workingConcentricOrdinal, + ) + return PowerLossStep(decision = decision, record = record, state = nextState) + } + + private fun fatigueStopAllowed(priorStreak: Int, config: PowerLossConfig): Boolean = + !config.requireTwoConsecutive || priorStreak >= 1 + + private fun shouldWarnNearLimit( + state: PowerLossPolicyState, + config: PowerLossConfig, + loss: Float?, + frozenRef: PowerLossReference?, + ): Boolean { + if (state.nearLimitWarned) return false + if (loss == null || frozenRef == null) return false + // Zero-loss baseline never cues (at threshold 5 this is "first positive loss"). + return loss > 0f && loss >= config.nearLimitLossPercent + } + + /** + * SD2: an ANY-active-cable strictly-<85% trusted ROM observation qualifies; + * equality is not short; one short arm cannot hide; missing/untrusted candidate + * ROM is never itself a short stop (SD3). The 85% bound is computed in double + * precision so exact-equality ROMs are never misclassified as short. + */ + private fun isShortRomQualified( + observation: PowerLossObservation, + frozenRef: PowerLossReference?, + ): Boolean { + if (frozenRef == null) return false + return observation.activeCables.any { cable -> + val obsRom = observation.romFor(cable) + val refRom = frozenRef.romFor(cable) + obsRom.isTrusted && refRom.isTrusted && + obsRom.romMm!!.toDouble() < SHORT_ROM_FRACTION.toDouble() * refRom.romMm!!.toDouble() + } + } + + /** Per-cable ROM as percent of reference ROM where both trusted (SD6 display). */ + private fun romPercentOfReference( + observation: PowerLossObservation, + frozenRef: PowerLossReference?, + ): Map = + PowerCable.entries.associateWith { cable -> + val obsRom = observation.romFor(cable) + val refRom = frozenRef?.romFor(cable) + if (obsRom.isTrusted && refRom != null && refRom.isTrusted) { + 100f * (obsRom.romMm!! / refRom.romMm!!) + } else { + null + } + } + + /** + * SD3 reference rules: establishment from any positive-MCP working rep; + * replacement only by a strictly-better MCP candidate with trusted sufficient + * ROM on **every** active cable (unknown ROM never promotes; short reps never + * replace the reference). Earliest-tie retention: equal MCP keeps the earlier. + */ + private fun updatedReference( + state: PowerLossPolicyState, + observation: PowerLossObservation, + frozenRef: PowerLossReference?, + ): PowerLossReference? { + if (!observation.hasValidMcp) return frozenRef + val mcp = observation.mcpWatts!! + if (frozenRef == null) { + return PowerLossReference( + workingConcentricOrdinal = observation.workingConcentricOrdinal, + mcpWatts = mcp, + romA = observation.romA, + romB = observation.romB, + ) + } + if (mcp <= frozenRef.mcpWatts) return frozenRef // earliest-tie retention + val eligible = observation.activeCables.isNotEmpty() && observation.activeCables.all { cable -> + val obsRom = observation.romFor(cable) + val refRom = frozenRef.romFor(cable) + obsRom.isTrusted && refRom.isTrusted && + obsRom.romMm!!.toDouble() >= SHORT_ROM_FRACTION.toDouble() * refRom.romMm!!.toDouble() + } + if (!eligible) return frozenRef + return PowerLossReference( + workingConcentricOrdinal = observation.workingConcentricOrdinal, + mcpWatts = mcp, + romA = observation.romA, + romB = observation.romB, + ) + } + + private fun recordOf( + observation: PowerLossObservation, + loss: Float?, + referenceOrdinal: Int?, + powerLoss: Boolean, + shortRom: Boolean, + romAPercent: Float? = null, + romBPercent: Float? = null, + ): PowerLossObservationRecord = PowerLossObservationRecord( + workingConcentricOrdinal = observation.workingConcentricOrdinal, + isWarmup = observation.isWarmup, + mcpWatts = observation.mcpWatts, + lossPercentAtDecision = loss, + referenceWorkingOrdinal = referenceOrdinal, + powerLossQualified = powerLoss, + shortRomQualified = shortRom, + romAPercentOfReference = romAPercent, + romBPercentOfReference = romBPercent, + activeCables = observation.activeCables, + ) +} diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/usecase/TemplateConverter.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/usecase/TemplateConverter.kt index fed75fe06..41b469f2c 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/usecase/TemplateConverter.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/domain/usecase/TemplateConverter.kt @@ -8,6 +8,7 @@ import com.devil.phoenixproject.domain.model.CycleTemplate import com.devil.phoenixproject.domain.model.EccentricLoad import com.devil.phoenixproject.domain.model.EchoLevel import com.devil.phoenixproject.domain.model.ExerciseConfig +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig import com.devil.phoenixproject.domain.model.FiveThreeOneWeeks import com.devil.phoenixproject.domain.model.ProgramMode import com.devil.phoenixproject.domain.model.Routine @@ -221,6 +222,9 @@ class TemplateConverter( scalingBasis = ScalingBasis.ESTIMATED_1RM, setWeightsPercentOfPR = computeFiveThreeOneSetWeights(activeSets) .ifEmpty { computeFiveThreeOneSetWeightsForWeek(weekNumber) }, + // Issue #1392 (P5 propagation, template path): the template + // config's per-exercise power-loss target survives conversion. + powerLoss = config?.powerLoss ?: PowerLossConfig.DEFAULT, ) } else { RoutineExercise( @@ -239,6 +243,9 @@ class TemplateConverter( usePercentOfPR = configuredWeight == null && !isBodyweight, weightPercentOfPR = templateExercise.percentOfOneRm, scalingBasis = ScalingBasis.ESTIMATED_1RM, + // Issue #1392 (P5 propagation, template path): the template + // config's per-exercise power-loss target survives conversion. + powerLoss = config?.powerLoss ?: PowerLossConfig.DEFAULT, ) } diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt index 6c935de85..82abcfe36 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/ActiveSessionEngine.kt @@ -120,6 +120,10 @@ import com.devil.phoenixproject.util.Constants import com.devil.phoenixproject.util.DataBackupManager import com.devil.phoenixproject.util.KmpUtils import com.devil.phoenixproject.util.WorkoutCommandValidator +import com.devil.phoenixproject.domain.powerloss.ExecutionTargetPlan +import com.devil.phoenixproject.domain.powerloss.PowerLossDecision +import com.devil.phoenixproject.domain.powerloss.PowerLossHudState +import com.devil.phoenixproject.domain.powerloss.TargetMode import kotlin.math.abs import kotlin.math.roundToInt import kotlinx.atomicfu.atomic @@ -229,6 +233,8 @@ private class ExecutionBiomechanicsContext( val engine: BiomechanicsEngine, var velocityThresholdAlertEmitted: Boolean = false, var consecutiveThresholdReps: Int = 0, + // Issue #1392: per-set power-loss policy runner (P3 seam). + val powerLoss: PowerLossSetController = PowerLossSetController(), ) private data class PendingTeardownReadyContinuation( @@ -3733,6 +3739,8 @@ class ActiveSessionEngine( params: WorkoutParameters, isJustLiftMode: Boolean, maxWeightPerCableKg: Float, + // Issue #1392 (SD4): validation agrees with the ONE frozen plan when present. + targetPlan: ExecutionTargetPlan? = null, ): Result = if (params.isEchoMode) { WorkoutCommandValidator.validateEchoControl( level = params.echoLevel, @@ -3741,9 +3749,10 @@ class ActiveSessionEngine( isJustLift = isJustLiftMode || params.isJustLift, isAMRAP = params.isAMRAP, eccentricPct = params.eccentricLoad.percentage, + targetPlan = targetPlan, ) } else { - WorkoutCommandValidator.validateProgramParams(params, maxWeightPerCableKg) + WorkoutCommandValidator.validateProgramParams(params, maxWeightPerCableKg, targetPlan) } private fun validateWorkoutCommand(params: WorkoutParameters): Result { @@ -4646,6 +4655,11 @@ class ActiveSessionEngine( return executionGuard.commitIfCurrent(lease) { biomechanicsContext.value = context coordinator.installBiomechanicsEngine(context.engine) + // Issue #1392 SD6 set-boundary rule: the live power panel belongs to + // exactly one set. Installing a new set's context starts its HUD + // clean — a frozen `Ending set…`/attempt panel from the previous set + // must never render under the next set's headers. + coordinator.setPowerLossHud(PowerLossHudState()) } } @@ -4657,14 +4671,25 @@ class ActiveSessionEngine( if (biomechanicsContext.value === context) { context.velocityThresholdAlertEmitted = false context.consecutiveThresholdReps = 0 + context.powerLoss.reset() coordinator.resetBiomechanicsEngine(context.engine) + // SD6: clear the live power panel at set teardown so the frozen + // `Ending set…`/attempt facts end with the completed transition + // and never leak into the next set's HUD. + coordinator.setPowerLossHud(PowerLossHudState()) } } if (!resetWhileCurrent) { // The engine is execution-local. An identity-checked reset cannot touch a newer engine. context.velocityThresholdAlertEmitted = false context.consecutiveThresholdReps = 0 + context.powerLoss.reset() coordinator.resetBiomechanicsEngine(context.engine) + // The coordinator HUD is shared across executions: clear it only when + // no newer set's context owns it (same identity rule as above). + if (biomechanicsContext.value === context) { + coordinator.setPowerLossHud(PowerLossHudState()) + } } } @@ -5291,7 +5316,18 @@ class ActiveSessionEngine( event = event, ) Logger.d("WORKOUT_COMPLETE event received - triggering immediate set completion") - handleSetCompletion(eventLease, SetEndReason.TARGET_REPS_REACHED) + // Issue #1392 (SD4): a finite POWER plan's device WORKOUT_COMPLETE is + // the mandatory max-reps backstop — never TARGET_REPS_REACHED, never + // inferred fatigue. The normalization reads the set-start frozen plan; + // REP/legacy behavior is unchanged and unlimited identities (Just Lift / + // AMRAP) keep their semantics. + val powerFinite = eventLease.targetPlan?.let { plan -> + plan.targetMode == TargetMode.POWER && plan.protocolIdentityFinite + } == true + handleSetCompletion( + eventLease, + if (powerFinite) SetEndReason.MAX_REPS_BACKSTOP else SetEndReason.TARGET_REPS_REACHED, + ) } } } @@ -6700,6 +6736,14 @@ class ActiveSessionEngine( // Issue #313: Check velocity threshold for alert and auto-end. evaluateLatestVbtResult(lease, context, result) + + // Issue #1392: power-loss policy evaluation for the completed rep (P3 seam). + evaluatePowerLossForRep( + lease = lease, + context = context, + isWarmup = !repCounter.getRepCount().isWarmupComplete, + repMetrics = repMetrics, + ) } catch (e: CancellationException) { throw e } catch (e: Exception) { @@ -6737,7 +6781,13 @@ class ActiveSessionEngine( val runtime = coordinator.vbtRuntimeSettings.value if (!runtime.enabled) return@commitIfCurrent val velocity = latestResult.velocity - if (velocity.shouldStopSet) { + // Issue #1392 (SD5): in POWER mode suppress the velocity auto-end and the + // velocity-threshold voice/defer side effects entirely; velocity analysis + // and display are preserved. REP and legacy behavior is unchanged. + // The suppression reads the set-start frozen plan, so an impossible POWER + // plan (which failed safe) keeps ordinary velocity behavior. + val powerModeActive = lease.targetPlan?.targetMode == TargetMode.POWER + if (velocity.shouldStopSet && !powerModeActive) { context.consecutiveThresholdReps++ if (!context.velocityThresholdAlertEmitted) { context.velocityThresholdAlertEmitted = true @@ -6774,6 +6824,79 @@ class ActiveSessionEngine( } } + /** + * Issue #1392 — power-loss autostop evaluation for one completed rep (P3 seam). + * + * No-op unless the set-start plan froze POWER behind the capability gate. + * Decisions: a once-per-set near-limit cue at `max(0, threshold − 5)` loss + * (audio/haptic only; never on the stop path), and set termination whose stop + * path never waits for audio, animation, or persistence (SD5). + */ + internal suspend fun evaluatePowerLossForRep( + lease: ExecutionLease, + isWarmup: Boolean, + repMetrics: List, + ) { + val context = biomechanicsContextFor(lease) ?: return + evaluatePowerLossForRep(lease, context, isWarmup, repMetrics) + } + + private suspend fun evaluatePowerLossForRep( + lease: ExecutionLease, + context: ExecutionBiomechanicsContext, + isWarmup: Boolean, + repMetrics: List, + ) { + // SD4 / P3 remainder: the ONE frozen plan from the lease — never re-derived + // per rep (and never with a placeholder warmup bound). A null or REP plan — + // including an impossible POWER plan that failed safe at set start — never + // triggers; REP/legacy behavior is unchanged. + val plan = lease.targetPlan + if (plan == null || plan.targetMode != TargetMode.POWER) return + if (!executionGuard.isCurrent(lease) || biomechanicsContext.value !== context) return + val runtime = coordinator.powerLossRuntimeSettings.value + // Threshold/streak facts come from the per-exercise runtime config; the + // effective target, saved nominal and warmup bound are the frozen plan's + // (SD3/SD4), so HUD/evidence read the same frozen facts the packet, + // counter and freshness gate used. + val config = runtime.toConfig().copy( + targetMode = plan.targetMode, + maxWorkingReps = plan.maxWorkingReps ?: runtime.maxWorkingReps, + savedNominalReps = plan.nominalReps, + ) + val decision = context.powerLoss.onRep( + config = config, + plan = plan, + isWarmup = isWarmup, + repMetrics = repMetrics, + ) ?: return + // Issue #1392 (P3 → P5): publish live HUD facts; `endingSet` is the + // committed stop state, distinct from the completed transition (SD6). + coordinator.setPowerLossHud( + context.powerLoss.hudState( + completedRepCount = coordinator._repCount.value.workingReps, + endingSet = decision is PowerLossDecision.Stop, + ), + ) + when (decision) { + is PowerLossDecision.Continue -> Unit + is PowerLossDecision.NearLimitWarning -> { + if (context.powerLoss.consumeNearLimitCue() && + settingsManager.userPreferences.value.beepsEnabled && + executionGuard.isCurrent(lease) + ) { + emitVbtAlerts(lease, context, listOf(HapticEvent.POWER_NEAR_LIMIT)) + Logger.i { "Power-loss: near-limit cue at ${decision.lossPercent.roundToInt()}% loss (ref rep ${decision.referenceWorkingOrdinal})" } + } + } + is PowerLossDecision.Stop -> { + // SD5: never wait for audio/persistence — latch the winner and stop. + Logger.i { "Power-loss: stopping set (${decision.reason}) loss=${decision.lossPercentAtDecision} ref=${decision.referenceWorkingOrdinal}" } + handleSetCompletion(lease, decision.reason.toSetEndReason()) + } + } + } + private suspend fun emitVbtAlerts( lease: ExecutionLease, context: ExecutionBiomechanicsContext, @@ -8279,6 +8402,24 @@ class ActiveSessionEngine( variableWarmupTarget == null && (isJustLiftMode || seedParams.usesUnlimitedRepTarget) val outgoingLease = executionGuard.currentLease + // Issue #1392 (SD4 / P3 remainder): derive the ONE frozen execution target + // plan BEFORE lease/packet/counter creation, then propagate it through the + // seed so every consumer reads one identical effective target. Warmup reps + // actually applied at the packet/counter path are the firmware warmup buffer + // forced onto every cable command (Constants.DEFAULT_WARMUP_REPS); bodyweight + // sets send no frame and apply none. An impossible plan does NOT arm POWER + // and fails safe to inert REP behavior. + val frozenTargetPlan = deriveFrozenExecutionTargetPlan( + runtime = coordinator.powerLossRuntimeSettings.value, + isEchoMode = seedParams.isEchoMode, + isJustLift = isJustLiftMode || seedParams.isJustLift, + isAmrap = seedParams.isAMRAP, + isBodyweight = isBodyweightAtStart, + isTimedCable = isTimedCableAtStart, + isVariableWarmupSet = variableWarmupTarget != null, + warmupRepsApplied = if (isBodyweightAtStart) 0 else Constants.DEFAULT_WARMUP_REPS, + nowMs = currentTimeMillis(), + ) val executionSeed = ExecutionSeed( sessionId = KmpUtils.randomUUID(), profileId = readyProfile.profile.id, @@ -8289,6 +8430,7 @@ class ActiveSessionEngine( isAmrap = seedParams.isAMRAP, isTimedCable = isTimedCableAtStart, usesUnlimitedRepTarget = usesUnlimitedRepTarget, + targetPlan = frozenTargetPlan, ) beforeExecutionBeginForTest?.invoke() val leaseResult = when { @@ -8846,7 +8988,17 @@ class ActiveSessionEngine( } repCounter.configure( warmupTarget = repCounterWarmupTarget, - workingTarget = if (isTimedCableExercise) 0 else warmupOverrideParams.reps, + // Issue #1392 (SD4): the counter target is the frozen effective + // target — POWER's max-reps backstop, never the saved nominal + // (a nominal below the cap must never end a POWER set early). + workingTarget = if (isTimedCableExercise) { + 0 + } else { + lease.targetPlan + ?.takeIf { it.targetMode == TargetMode.POWER } + ?.maxWorkingReps + ?: warmupOverrideParams.reps + }, isJustLift = isJustLiftMode, stopAtTop = warmupOverrideParams.stopAtTop, isAMRAP = if (isTimedCableExercise) true else warmupOverrideParams.isAMRAP, @@ -8973,6 +9125,7 @@ class ActiveSessionEngine( params = commandParams, isJustLiftMode = isJustLiftMode, maxWeightPerCableKg = commandCeilingKg, + targetPlan = lease.targetPlan, ) commandValidation.onFailure { error -> commandValidationFailed = true @@ -8992,11 +9145,17 @@ class ActiveSessionEngine( isJustLift = isJustLiftMode || commandParams.isJustLift, isAMRAP = commandParams.isAMRAP, eccentricPct = commandParams.eccentricLoad.percentage, + // Issue #1392 (SD4): the frame's target byte agrees with the + // ONE frozen plan's effective target. + targetPlan = lease.targetPlan, ) } else { BlePacketFactory.createProgramParams( params = commandParams, maxWeightPerCableKg = commandCeilingKg, + // Issue #1392 (SD4): the frame's total-rep byte agrees with the + // ONE frozen plan's effective target. + targetPlan = lease.targetPlan, ) } Logger.d { "Built ${command.size}-byte workout command for ${commandParams.programMode}" } @@ -9656,6 +9815,15 @@ class ActiveSessionEngine( taggedExerciseId = params.selectedExerciseId, taggedExerciseName = context.exerciseName, isAmrap = params.isAMRAP, + // Issue #1392 (P3): frozen summary facts; null when POWER was not armed. + // SD4: when the one-winner completion latch fired from the machine + // counter path before the policy could latch its winner, the + // committed completion reason is the winner of record so the §6 + // headline (`Stopped at 20 working reps — max-reps limit`) renders. + powerLoss = biomechanicsContextFor(lease)?.powerLoss?.buildSummaryFacts( + completedRepCount = repCount.workingReps, + fallbackWinnerReason = completion.reason.toPowerStopReasonOrNull(), + ), ).deepCopyForExitSnapshot() val isRoutineSet = context.routineSessionId != null val shouldUpdateCycleProgress = shouldUpdateCycleProgressAfterSavedSet( @@ -9673,6 +9841,15 @@ class ActiveSessionEngine( terminalPath = terminalPath, session = session, completedSet = completedSet, + // Issue #1392 (P3): deep-frozen evidence at the pre-teardown latch (SD3). + // Null when POWER was never armed; attempt-only identity survives via a + // stable execution-scoped set id when no bottom row exists (P4 contract). + powerLossEvidence = biomechanicsContextFor(lease)?.powerLoss?.buildEvidence( + sessionId = lease.sessionId, + setId = completedSet?.id ?: "attempt-${lease.executionId}", + fallbackWinnerReason = completion.reason.toPowerStopReasonOrNull(), + fallbackStoppedAtAttempt = repCount.workingReps, + ), metrics = archiveMetrics, repMetrics = coordinator.setRepMetrics.snapshot().map(RepMetricData::deepCopyForExitSnapshot), biomechanicsRepResults = biomechanicsSummary?.repResults.orEmpty() diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/DefaultWorkoutSessionManager.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/DefaultWorkoutSessionManager.kt index 8ee39900c..39a78f2ee 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/DefaultWorkoutSessionManager.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/DefaultWorkoutSessionManager.kt @@ -54,6 +54,8 @@ import com.devil.phoenixproject.domain.usecase.RegenerateFiveThreeOneRoutinesUse import com.devil.phoenixproject.domain.usecase.RepCounterFromMachine import com.devil.phoenixproject.domain.usecase.ResolveRoutineWeightsUseCase import com.devil.phoenixproject.getPlatform +import com.devil.phoenixproject.presentation.powerloss.PowerLossRuntimeGate +import com.devil.phoenixproject.presentation.powerloss.powerLossRuntimeSettingsFor import com.devil.phoenixproject.util.DataBackupManager import com.devil.phoenixproject.util.KmpUtils import kotlinx.coroutines.CancellationException @@ -1071,7 +1073,40 @@ class DefaultWorkoutSessionManager( // ===== Workout Lifecycle — delegated to ActiveSessionEngine ===== fun resetForNewWorkout() = activeSessionEngine.resetForNewWorkout() - fun updateWorkoutParameters(params: WorkoutParameters) = activeSessionEngine.updateWorkoutParameters(params) + + // ===== Issue #1392 — power-loss runtime propagation (P5, integration-model §4) ===== + + /** Runtime seam passthrough (issue #1392): `coordinator.powerLossRuntimeSettings`. */ + internal val powerLossRuntimeSettings: StateFlow = coordinator.powerLossRuntimeSettings + + /** Runtime seam passthrough for callers holding an already-derived settings object. */ + internal fun updatePowerLossSettings(settings: PowerLossRuntimeSettings) = + coordinator.updatePowerLossSettings(settings) + + /** + * Copy the per-exercise power-loss target config carried by [params] into the + * `coordinator.powerLossRuntimeSettings` runtime seam. Called on the initial, + * next set/exercise, adjusted/retry and transition parameter paths so POWER + * arms only from explicit per-exercise config behind the capability gate; + * unknown or excluded modes resolve to inert REP_TARGET. + */ + internal fun publishPowerLossRuntimeSettingsFrom(params: WorkoutParameters) { + val config = params.powerLoss + coordinator.updatePowerLossSettings( + powerLossRuntimeSettingsFor( + config = config, + mode = params.programMode, + isJustLiftExecutionStyle = params.isJustLift, + savedNominalReps = config.savedNominalReps ?: params.reps.takeIf { it >= 1 }, + pairedSamplesValidated = PowerLossRuntimeGate.pairedSamplesValidated, + ), + ) + } + + fun updateWorkoutParameters(params: WorkoutParameters) { + publishPowerLossRuntimeSettingsFrom(params) + activeSessionEngine.updateWorkoutParameters(params) + } fun setWorkoutParametersInternal(params: WorkoutParameters) = activeSessionEngine.setWorkoutParametersInternal(params) fun updateActiveRackSelection(itemIds: List) = activeSessionEngine.updateActiveRackSelection(itemIds) fun updateActiveRackBehaviorOverrides( @@ -1089,6 +1124,9 @@ class DefaultWorkoutSessionManager( val tracker = profileRecoveryActivityTracker if (tracker?.setWorkoutActive(true) == false) return try { + // Issue #1392 (P5 propagation): initial path — the runtime seam is + // re-published from the current parameters before execution starts. + publishPowerLossRuntimeSettingsFrom(coordinator._workoutParameters.value) activeSessionEngine.startWorkout(skipCountdown, isJustLiftMode) } catch (error: Throwable) { tracker?.setWorkoutActive(isWorkoutRecoveryBlocking(coordinator._workoutState.value)) diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossSetController.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossSetController.kt new file mode 100644 index 000000000..7089f119b --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossSetController.kt @@ -0,0 +1,430 @@ +package com.devil.phoenixproject.presentation.manager + +import com.devil.phoenixproject.domain.model.ProgramMode +import com.devil.phoenixproject.domain.model.WorkoutMetric +import com.devil.phoenixproject.domain.powerloss.CableRom +import com.devil.phoenixproject.domain.powerloss.CableRomTrust +import com.devil.phoenixproject.domain.powerloss.ConcentricPhaseNormalizer +import com.devil.phoenixproject.domain.powerloss.MeanConcentricPower +import com.devil.phoenixproject.domain.powerloss.PowerCable +import com.devil.phoenixproject.domain.powerloss.PowerLossDecision +import com.devil.phoenixproject.domain.powerloss.PowerLossAttemptRecord +import com.devil.phoenixproject.domain.powerloss.PowerLossHudState +import com.devil.phoenixproject.domain.powerloss.PowerLossSetEvidence +import com.devil.phoenixproject.domain.powerloss.PowerLossSetSummaryFacts +import com.devil.phoenixproject.domain.powerloss.PowerLossObservation +import com.devil.phoenixproject.domain.powerloss.PowerLossPolicy +import com.devil.phoenixproject.domain.powerloss.PowerLossPolicyState +import com.devil.phoenixproject.domain.powerloss.PowerStopReason +import com.devil.phoenixproject.domain.powerloss.SampleQualityMarkers +import com.devil.phoenixproject.domain.powerloss.TargetMode +import com.devil.phoenixproject.domain.powerloss.ValidatedPairedSample +import com.devil.phoenixproject.domain.model.SetEndReason +import com.devil.phoenixproject.util.WorkoutCommandValidator + +/** + * Issue #1392 — per-set power-loss policy runner (P3 seam). + * + * Owns the pure reducer state for one active set and converts completed-rep + * metric segments into sealed observations. Control input comes ONLY from + * pre-EMA validated paired samples run through [ConcentricPhaseNormalizer] — + * never from midpoint/first-half fallback segmentation (SD1). + * + * Warmups neither tally nor trigger. The working ordinal counts working reps + * observed in this set (pending-attempt semantics: the rep being processed is + * the current attempt). + */ +internal class PowerLossSetController { + + private var state: PowerLossPolicyState = PowerLossPolicyState.INITIAL + private var workingOrdinal = 0 + + /** Near-limit cue latch (once per set). Backed by the reducer state too. */ + private var nearLimitCueEmitted = false + + // ===== Issue #1392 P3: deep-frozen evidence (immutable winner latch) ===== + + /** Ordered per-attempt records for P4 evidence / P5 summary+history. */ + private val attemptRecords = mutableListOf() + private var lastConfig: com.devil.phoenixproject.domain.powerloss.PowerLossConfig? = null + private var frozenActiveCables: Set = setOf(PowerCable.A, PowerCable.B) + /** Immutable winning reason; latched once, never overwritten (SD2). */ + private var winnerReason: PowerStopReason? = null + private var shortRomObserved = false + private var powerLossObserved = false + private var lossAtStop: Float? = null + private var stoppedAtOrdinal: Int? = null + + fun reset() { + state = PowerLossPolicyState.INITIAL + workingOrdinal = 0 + nearLimitCueEmitted = false + attemptRecords.clear() + lastConfig = null + frozenActiveCables = setOf(PowerCable.A, PowerCable.B) + winnerReason = null + shortRomObserved = false + powerLossObserved = false + lossAtStop = null + stoppedAtOrdinal = null + } + + /** + * Feed one completed rep's raw metric segment. Returns the reducer step, or + * null when the runtime is not in POWER mode. + */ + fun onRep( + config: com.devil.phoenixproject.domain.powerloss.PowerLossConfig, + plan: com.devil.phoenixproject.domain.powerloss.ExecutionTargetPlan, + isWarmup: Boolean, + repMetrics: List, + ): PowerLossDecision? { + if (!isWarmup) workingOrdinal++ + val observation = PowerLossObservation( + workingConcentricOrdinal = if (isWarmup) 0 else workingOrdinal, + isWarmup = isWarmup, + mcpWatts = computeMcp(repMetrics)?.takeIf { it > 0f }, + romA = romFor(repMetrics, PowerCable.A), + romB = romFor(repMetrics, PowerCable.B), + activeCables = activeCables(repMetrics), + ) + return onObservation(config, plan, observation) + } + + /** + * Policy step + evidence capture for one sealed observation (P3 latch). + * Extracted from [onRep] so fixtures can drive the immutable winner latch + * directly. Both qualification facts are persisted together (SD2); the + * winner is latched once and never overwritten. + */ + internal fun onObservation( + config: com.devil.phoenixproject.domain.powerloss.PowerLossConfig, + plan: com.devil.phoenixproject.domain.powerloss.ExecutionTargetPlan, + observation: PowerLossObservation, + ): PowerLossDecision { + val step = PowerLossPolicy.observe(state, observation, config, plan) + state = step.state + lastConfig = config + if (!observation.isWarmup) { + if (attemptRecords.isEmpty()) { + frozenActiveCables = observation.activeCables + } + attemptRecords += PowerLossAttemptRecord( + workingConcentricOrdinal = step.record.workingConcentricOrdinal, + completed = true, + mcpWatts = step.record.mcpWatts, + lossPercentAtDecision = step.record.lossPercentAtDecision, + referenceWorkingOrdinal = step.record.referenceWorkingOrdinal, + romAMm = observation.romA.romMm, + romBMm = observation.romB.romMm, + romAPercentOfReference = step.record.romAPercentOfReference, + romBPercentOfReference = step.record.romBPercentOfReference, + romTrustworthy = observation.romA.isTrusted || observation.romB.isTrusted, + shortRom = step.record.shortRomQualified, + powerLossQualified = step.record.powerLossQualified, + ) + if (step.record.shortRomQualified) shortRomObserved = true + if (step.record.powerLossQualified) powerLossObserved = true + } + if (step.decision is PowerLossDecision.Stop && winnerReason == null) { + winnerReason = step.decision.reason + lossAtStop = step.decision.lossPercentAtDecision + stoppedAtOrdinal = step.record.workingConcentricOrdinal + } + return step.decision + } + + /** True until the once-per-set near-limit cue has been emitted. */ + fun consumeNearLimitCue(): Boolean { + if (nearLimitCueEmitted) return false + nearLimitCueEmitted = true + return true + } + + /** + * Deep-frozen evidence for the exit snapshot / P4 companions (P3 latch). + * Null when POWER was never armed (no config seen) — never fabricated. + */ + fun buildEvidence( + sessionId: String, + setId: String, + fallbackWinnerReason: PowerStopReason? = null, + fallbackStoppedAtAttempt: Int? = null, + ): PowerLossSetEvidence? { + val config = lastConfig ?: return null + // SD2 latch is authoritative; the committed completion reason (SD4 + // machine-counter path) is the winner of record when no policy winner + // latched — see buildSummaryFacts. + val winner = winnerReason ?: fallbackWinnerReason + if (attemptRecords.isEmpty() && winner == null) return null + val reference = state.reference + return PowerLossSetEvidence( + sessionId = sessionId, + setId = setId, + targetMode = config.targetMode, + thresholdPercent = config.thresholdPercent, + maxWorkingReps = config.maxWorkingReps, + requireTwoConsecutive = config.requireTwoConsecutive, + savedNominalReps = config.savedNominalReps, + activeCables = frozenActiveCables, + activeCableProvenance = "rep-metric-load-scan:first-working-attempt", + referenceWorkingOrdinal = reference?.workingConcentricOrdinal, + referenceMcpWatts = reference?.mcpWatts, + referenceRomAMm = reference?.romA?.romMm, + referenceRomBMm = reference?.romB?.romMm, + triggerWorkingOrdinal = stoppedAtOrdinal + ?: if (fallbackWinnerReason != null) fallbackStoppedAtAttempt else null, + winnerReason = winner, + shortRomObserved = shortRomObserved, + powerLossObserved = powerLossObserved, + lossPercentAtDecision = lossAtStop, + attempts = attemptRecords.toList(), + ) + } + + /** + * Restart/rebaseline entry (Issue #1392): hydrate persisted power-loss runtime + * state after a process restart. The armed policy is NEVER resumed — the + * accumulator, baseline and streak are reset here (rebaseline) and the + * explanatory UX state comes back for display. This method issues NO machine + * commands; the restore path never writes to the machine. + */ + internal fun restoreFromSnapshot( + snapshot: com.devil.phoenixproject.data.repository.RestoredPowerLossRuntimeSnapshot?, + ): com.devil.phoenixproject.data.repository.PowerLossRestartRecoveryState { + reset() + return com.devil.phoenixproject.data.repository.PowerLossRestartRecovery.rebaselineOnRestart(snapshot) + } + + /** Summary facts for `WorkoutState.SetSummary.powerLoss` (P5 renders with SD6 clarification). */ + fun buildSummaryFacts( + completedRepCount: Int, + fallbackWinnerReason: PowerStopReason? = null, + ): PowerLossSetSummaryFacts? { + val config = lastConfig ?: return null + // SD2: the latched policy winner is authoritative and never overwritten. + // When the one-winner completion latch fired from the machine-counter + // path (SD4 WORKOUT_COMPLETE → MAX_REPS_BACKSTOP) BEFORE the final rep's + // metric evaluation could latch the policy winner, the committed + // completion reason is the winner of record — the summary must not + // silently degrade to the MANUAL variant and drop its headline. + val winner = winnerReason ?: fallbackWinnerReason + val stoppedAt = stoppedAtOrdinal + ?: if (fallbackWinnerReason != null) completedRepCount else null + return PowerLossSetSummaryFacts( + winnerReason = winner, + thresholdPercent = config.thresholdPercent, + maxWorkingReps = config.maxWorkingReps, + requireTwoConsecutive = config.requireTwoConsecutive, + stoppedAtWorkingAttempt = stoppedAt, + completedRepCount = completedRepCount, + lossPercentAtStop = lossAtStop, + bestWorkingOrdinal = state.reference?.workingConcentricOrdinal, + shortRomObserved = shortRomObserved, + powerLossObserved = powerLossObserved, + attempts = attemptRecords.toList(), + savedNominalReps = config.savedNominalReps, + ) + } + + /** Live HUD facts (P3 → P5 `WorkoutHud`). [endingSet] is the committed `Ending set…` state. */ + fun hudState(completedRepCount: Int, endingSet: Boolean): PowerLossHudState { + val config = lastConfig ?: com.devil.phoenixproject.domain.powerloss.PowerLossConfig.DEFAULT + val lastAttempt = attemptRecords.lastOrNull() + val lastValid = attemptRecords.lastOrNull { it.mcpWatts != null } + return PowerLossHudState( + powerActive = lastConfig != null, + thresholdPercent = config.thresholdPercent, + nearLimitLossPercent = config.nearLimitLossPercent, + maxWorkingReps = config.maxWorkingReps, + savedNominalReps = config.savedNominalReps, + currentAttemptOrdinal = workingOrdinal, + completedRepCount = completedRepCount, + referenceEstablished = state.reference != null, + referenceWorkingOrdinal = state.reference?.workingConcentricOrdinal, + lastLossPercent = lastAttempt?.lossPercentAtDecision, + lastValidAttemptOrdinal = lastValid?.workingConcentricOrdinal, + invalidPowerReason = if (lastAttempt != null && lastAttempt.mcpWatts == null) { + "phase unavailable" + } else { + null + }, + nearLimitCueEmitted = nearLimitCueEmitted, + cableRomPercentOfReference = buildMap { + lastAttempt?.romAPercentOfReference?.let { put(PowerCable.A, it) } + lastAttempt?.romBPercentOfReference?.let { put(PowerCable.B, it) } + }, + endingSet = endingSet, + lastMcpWatts = lastValid?.mcpWatts, + bestMcpWatts = state.reference?.mcpWatts, + qualifyingCount = if (config.requireTwoConsecutive) state.consecutiveQualifyingCount else null, + referenceRomUncertain = state.reference + ?.let { !(it.romA.isTrusted || it.romB.isTrusted) } ?: false, + ) + } + + /** + * MCP V1 from the rep's validated paired samples: the concentric window is + * derived by [ConcentricPhaseNormalizer] from the full rep segment (the + * window seals on the next fresh sample after turnaround). Returns null when + * the phase cannot be established — never a fallback segmentation (SD1). + */ + private fun computeMcp(repMetrics: List): Float? { + if (repMetrics.size < ValidatedPairedSample.MIN_SAMPLES) return null + val normalizer = ConcentricPhaseNormalizer() + var sealedWindow: List? = null + for (metric in repMetrics) { + val sealed = normalizer.onSample(metric.toValidatedSample()) + if (sealed != null) { + sealedWindow = sealed + break + } + } + val window = sealedWindow ?: return null + return MeanConcentricPower.compute(window).mcpWatts + } + + private fun romFor(repMetrics: List, cable: PowerCable): CableRom { + val positions = repMetrics.map { + when (cable) { + PowerCable.A -> it.positionA + PowerCable.B -> it.positionB + } + } + if (positions.size < ValidatedPairedSample.MIN_SAMPLES) return CableRom.UNKNOWN + val rom = (positions.max() - positions.min()) + return if (rom > 0f) CableRom.trusted(rom) else CableRom.UNKNOWN + } + + private fun activeCables(repMetrics: List): Set { + val last = repMetrics.lastOrNull() ?: return setOf(PowerCable.A, PowerCable.B) + return buildSet { + if (last.loadA > 0f) add(PowerCable.A) + if (last.loadB > 0f) add(PowerCable.B) + }.ifEmpty { setOf(PowerCable.A, PowerCable.B) } + } +} + +/** Map a [PowerStopReason] onto the persisted [SetEndReason] vocabulary. */ +internal fun PowerStopReason.toSetEndReason(): SetEndReason = when (this) { + PowerStopReason.POWER_LOSS -> SetEndReason.POWER_LOSS + PowerStopReason.SHORT_ROM -> SetEndReason.SHORT_ROM + PowerStopReason.MAX_REPS_BACKSTOP -> SetEndReason.MAX_REPS_BACKSTOP +} + +/** + * Reverse map for the summary winner fallback: only end reasons inside the + * power-policy vocabulary describe a power-policy winner. Manual, safety, + * stall, timer and REP paths keep their own reason heading (null here). + */ +internal fun SetEndReason.toPowerStopReasonOrNull(): PowerStopReason? = when (this) { + SetEndReason.POWER_LOSS -> PowerStopReason.POWER_LOSS + SetEndReason.SHORT_ROM -> PowerStopReason.SHORT_ROM + SetEndReason.MAX_REPS_BACKSTOP -> PowerStopReason.MAX_REPS_BACKSTOP + else -> null +} + +/** + * Runtime settings for the active set's power-loss target (P3 seam). Defaults are + * inert (REP_TARGET) — POWER arms only through explicit per-exercise config + * behind the capability gate. + */ +internal data class PowerLossRuntimeSettings( + val targetMode: com.devil.phoenixproject.domain.powerloss.TargetMode = + com.devil.phoenixproject.domain.powerloss.TargetMode.REP_TARGET, + val thresholdPercent: Int = 20, + val maxWorkingReps: Int = 20, + val requireTwoConsecutive: Boolean = false, + val savedNominalReps: Int? = null, + val protocolFamily: com.devil.phoenixproject.domain.powerloss.PowerLossProtocolFamily = + com.devil.phoenixproject.domain.powerloss.PowerLossProtocolFamily.UNSUPPORTED, + val pairedSamplesValidated: Boolean = false, +) { + val powerActive: Boolean + get() = targetMode == com.devil.phoenixproject.domain.powerloss.TargetMode.POWER && + com.devil.phoenixproject.domain.powerloss.PowerLossCapability.isEligible( + protocolFamily = protocolFamily, + pairedSamplesValidated = pairedSamplesValidated, + ) + + fun toConfig(): com.devil.phoenixproject.domain.powerloss.PowerLossConfig = + com.devil.phoenixproject.domain.powerloss.PowerLossConfig( + targetMode = targetMode, + thresholdPercent = thresholdPercent, + maxWorkingReps = maxWorkingReps, + requireTwoConsecutive = requireTwoConsecutive, + savedNominalReps = savedNominalReps, + ) +} + +/** Derive the protocol family for runtime gating from the mode + Just Lift style. */ +internal fun protocolFamilyOf(mode: ProgramMode, isJustLift: Boolean) = + com.devil.phoenixproject.domain.powerloss.PowerLossProtocolFamily.of(mode, isJustLift) + +/** Issue #1392 (SD4): PROGRAM frame finite total-rep byte bound (working + warmup reps). */ +internal const val PROGRAM_TOTAL_REP_BYTE_MAX: Int = WorkoutCommandValidator.MAX_FINITE_REP_BYTE + +/** + * Issue #1392 (P3 remainder) — derive the ONE frozen + * [com.devil.phoenixproject.domain.powerloss.ExecutionTargetPlan] before + * lease/packet/counter creation (SD4). Called exactly once per set start; every + * consumer (packet byte, counter config, freshness gate, validation, HUD, power + * policy) then reads the identical effective target from the lease. + * + * - PROGRAM bounds: `254 − warmupReps actually applied` at the packet/counter + * path (the firmware warmup buffer forced onto every cable command). + * - Echo bounds: the accepted target-plan validator's finite rep-byte bound — + * never a guessed value. + * - An impossible plan returns null: POWER does NOT arm and the set fails safe + * to inert REP behavior. + * - Genuine Just Lift / AMRAP hardware-unlimited identity is preserved + * (0xFF sentinel semantics unchanged); the cap is enforced in-app there. + * - Retained-but-inert paths (bodyweight, timed cable, variable warm-up sets) + * never arm POWER. + */ +internal fun deriveFrozenExecutionTargetPlan( + runtime: PowerLossRuntimeSettings, + isEchoMode: Boolean, + isJustLift: Boolean, + isAmrap: Boolean, + isBodyweight: Boolean, + isTimedCable: Boolean, + isVariableWarmupSet: Boolean, + warmupRepsApplied: Int, + nowMs: Long, +): com.devil.phoenixproject.domain.powerloss.ExecutionTargetPlan? { + val powerArms = runtime.powerActive && !isBodyweight && !isTimedCable && !isVariableWarmupSet + val config = runtime.toConfig().let { current -> + if (powerArms) current else current.copy(targetMode = TargetMode.REP_TARGET) + } + val maxRepresentableWorkingReps = if (isEchoMode) { + // The Echo working-target byte is standalone; its finite bound is the + // accepted validator's finite rep byte — never hardcoded here. + WorkoutCommandValidator.MAX_FINITE_REP_BYTE + } else { + PROGRAM_TOTAL_REP_BYTE_MAX - warmupRepsApplied + } + return com.devil.phoenixproject.domain.powerloss.ExecutionTargetPlan.derive( + config = config, + bounds = com.devil.phoenixproject.domain.powerloss.ProtocolRepBounds( + maxRepresentableWorkingReps = maxRepresentableWorkingReps, + protocolIdentityFinite = !(isJustLift || isAmrap), + ), + warmupSetCount = warmupRepsApplied, + now = nowMs, + ) +} + +private fun WorkoutMetric.toValidatedSample(): ValidatedPairedSample = ValidatedPairedSample( + executionId = "", + windowOrdinal = 0, + loadAKg = loadA, + loadBKg = loadB, + velocityAMmS = velocityA.toFloat(), + velocityBMmS = velocityB.toFloat(), + positionAMm = positionA, + positionBMm = positionB, + deviceTicks = ticks, + monotonicTimestampMs = timestamp, + quality = SampleQualityMarkers(), +) diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/RepNotificationFreshnessGate.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/RepNotificationFreshnessGate.kt index 965089809..1baa49244 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/RepNotificationFreshnessGate.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/RepNotificationFreshnessGate.kt @@ -86,6 +86,9 @@ internal class RepNotificationFreshnessGate { // leases retain their configured finite UI fallback target (for // example 10), so lease.workingRepTarget == 0 is not a reliable // unlimited discriminator. The notification sentinel is. + // Issue #1392 (SD4): the effective target is the frozen plan's POWER + // max-reps backstop when armed — never a re-derived or nominal value. + val effectiveTarget = lease.effectiveWorkingRepTarget val isUnlimitedAmrapPacket = lease.isAmrap && lease.usesUnlimitedRepTarget && notification.repsSetTotal == UNLIMITED_REPS_SET_TOTAL @@ -95,7 +98,7 @@ internal class RepNotificationFreshnessGate { isUnlimitedAmrapPacket || isUnlimitedTimedCablePacket || notification.repsSetTotal == 0 || - notification.repsSetTotal == lease.workingRepTarget + notification.repsSetTotal == effectiveTarget if (!targetMatches) { // Issue #652 (2026-09-26 TestFlight recurrence): once this lease is // independently Armed, repsSetTotal is NOT packet identity — the machine can @@ -119,8 +122,8 @@ internal class RepNotificationFreshnessGate { // Issue #698/#700: Just Lift and AMRAP have no finite rep target, // so repsSetCount should never be treated as terminal. val terminal = !(lease.isJustLift || lease.isAmrap) && - lease.workingRepTarget > 0 && - notification.repsSetCount >= lease.workingRepTarget + effectiveTarget > 0 && + notification.repsSetCount >= effectiveTarget val allZero = notification.topCounter == 0 && notification.completeCounter == 0 && notification.repsRomCount == 0 && @@ -169,7 +172,7 @@ internal class RepNotificationFreshnessGate { * it belongs to this execution's live rep stream: * 1. the machine's own `repsSetCount` strictly advances what this lease has already * accepted (monotonic current-set progress, not a replay of an older count), - * 2. it stays within the configured completion authority (`lease.workingRepTarget`) — + * 2. it stays within the configured completion authority (`lease.effectiveWorkingRepTarget`) — * a set's completed-rep count can never pass the configured target, so beyond-target * counts are prior-set carryover, * 3. the directional/ROM counters never rewind against this lease's high-water marks; @@ -180,9 +183,11 @@ internal class RepNotificationFreshnessGate { lease: ExecutionLease, notification: RepNotification, ): Boolean { - if (lease.workingRepTarget <= 0) return false + // Issue #1392 (SD4): completion authority is the frozen effective target. + val effectiveTarget = lease.effectiveWorkingRepTarget + if (effectiveTarget <= 0) return false val observed = observedModernCounters[identity] ?: return false - if (notification.repsSetCount > lease.workingRepTarget) return false + if (notification.repsSetCount > effectiveTarget) return false if (notification.repsSetCount <= observed.repsSetCount) return false return notification.topCounter >= observed.topCounter && notification.completeCounter >= observed.completeCounter && diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/RoutineFlowManager.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/RoutineFlowManager.kt index 07c08aeeb..bd4f69aa4 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/RoutineFlowManager.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/RoutineFlowManager.kt @@ -31,6 +31,9 @@ import com.devil.phoenixproject.domain.usecase.ApplyRoutineModifierUseCase import com.devil.phoenixproject.domain.usecase.ResolveRoutineWeightsUseCase import com.devil.phoenixproject.domain.usecase.RoutineSetWeightRequest import com.devil.phoenixproject.domain.usecase.RoutineSetWeightResolver +import com.devil.phoenixproject.presentation.powerloss.PowerLossRuntimeGate +import com.devil.phoenixproject.presentation.powerloss.powerLossExecutionConfig +import com.devil.phoenixproject.presentation.powerloss.powerLossRuntimeSettingsFor import com.devil.phoenixproject.util.CommandLimits import com.devil.phoenixproject.util.Constants import kotlinx.coroutines.CancellationException @@ -904,6 +907,30 @@ class RoutineFlowManager( coordinator._sessionBodyweightState.value = SessionBodyweightState() } + /** + * Issue #1392 (P5 propagation, integration-model §4): copy the per-exercise + * power-loss target config into the `coordinator.powerLossRuntimeSettings` + * runtime seam wherever WorkoutParameters are generated — initial, next + * set/exercise, adjusted/retry and transition paths. Unsupported timed and + * bodyweight paths resolve to inert REP_TARGET; POWER never arms from an + * unknown or excluded mode. + */ + private fun publishPowerLossRuntimeSettings(exercise: RoutineExercise, savedNominalReps: Int?) { + coordinator.updatePowerLossSettings( + powerLossRuntimeSettingsFor( + config = powerLossExecutionConfig( + config = exercise.powerLoss, + isTimed = exercise.duration != null, + isBodyweight = exercise.exercise.isBodyweight, + ), + mode = exercise.programMode, + isJustLiftExecutionStyle = false, + savedNominalReps = savedNominalReps, + pairedSamplesValidated = PowerLossRuntimeGate.pairedSamplesValidated, + ), + ) + } + private fun loadRoutineInternal( routine: Routine, resumeLaunchOrigin: RoutineLaunchOrigin? = null, @@ -943,6 +970,13 @@ class RoutineFlowManager( selectedExerciseId = firstExercise.exercise.id, stallDetectionEnabled = firstExercise.stallDetectionEnabled, repCountTiming = firstExercise.repCountTiming, + // Issue #1392 (P5 propagation): the generated parameters carry the + // per-exercise power-loss target config (inert on timed/bodyweight). + powerLoss = powerLossExecutionConfig( + config = firstExercise.powerLoss, + isTimed = firstExercise.duration != null, + isBodyweight = isFirstBodyweight, + ), ) val hasVariableWarmups = firstExercise.warmupSets.isNotEmpty() && !isFirstBodyweight @@ -972,6 +1006,12 @@ class RoutineFlowManager( coordinator._workoutParameters.value = params.withPublishedRackSelection( coordinator._workoutParameters.value, ) + // Issue #1392 (P5 propagation): initial path — the first exercise's + // power-loss target config seeds the runtime seam with the routine. + publishPowerLossRuntimeSettings( + firstExercise, + savedNominalReps = if (firstIsAMRAP) null else firstSetReps ?: firstExercise.reps, + ) } val published = if (publicationStillCurrent == null) { lifecycleDelegate.mutateConfigurationInputs(publish) @@ -1242,6 +1282,13 @@ class RoutineFlowManager( progressionRegressionKg = progressionKg, isJustLift = false, useAutoStart = false, + // Issue #1392 (P5 propagation): every generated WorkoutParameters + // carries the per-exercise power-loss target config. + powerLoss = powerLossExecutionConfig( + config = exercise.powerLoss, + isTimed = exercise.duration != null, + isBodyweight = exercise.exercise.isBodyweight, + ), ) lifecycleDelegate.mutateConfigurationInputs { coordinator._currentExerciseIndex.value = exerciseIndex @@ -1257,6 +1304,11 @@ class RoutineFlowManager( coordinator._workoutParameters.value = nextParams.withPublishedRackSelection( coordinator._workoutParameters.value, ) + // Issue #1392 (P5 propagation): next set/exercise path. + publishPowerLossRuntimeSettings( + exercise, + savedNominalReps = if (isSetAmrap) null else setReps, + ) } Logger.d { @@ -1316,6 +1368,13 @@ class RoutineFlowManager( progressionRegressionKg = progressionKg, isJustLift = false, useAutoStart = false, + // Issue #1392 (P5 propagation): every generated WorkoutParameters + // carries the per-exercise power-loss target config. + powerLoss = powerLossExecutionConfig( + config = exercise.powerLoss, + isTimed = exercise.duration != null, + isBodyweight = exercise.exercise.isBodyweight, + ), ) lifecycleDelegate.mutateConfigurationInputs { coordinator._currentExerciseIndex.value = exerciseIndex @@ -1331,6 +1390,11 @@ class RoutineFlowManager( coordinator._workoutParameters.value = nextParams.withPublishedRackSelection( coordinator._workoutParameters.value, ) + // Issue #1392 (P5 propagation): adjusted/retry path. + publishPowerLossRuntimeSettings( + exercise, + savedNominalReps = if (isSetAmrap) null else adjustedReps, + ) } Logger.d { @@ -1367,6 +1431,16 @@ class RoutineFlowManager( lifecycleDelegate.mutateConfigurationInputs { coordinator._routineFlowState.value = state.copy(adjustedReps = reps) coordinator._workoutParameters.value = coordinator._workoutParameters.value.copy(reps = reps) + // Issue #1392 (P5 propagation): transition path — the nominal rep + // target changed, so the runtime seam's saved nominal follows it. + coordinator._loadedRoutine.value + ?.exercises?.getOrNull(state.exerciseIndex) + ?.let { exercise -> + publishPowerLossRuntimeSettings( + exercise, + savedNominalReps = if (exercise.isAmrapSet(state.setIndex)) null else reps, + ) + } } } } diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutCoordinator.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutCoordinator.kt index 5c7924f63..ddc76d302 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutCoordinator.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutCoordinator.kt @@ -803,6 +803,27 @@ class WorkoutCoordinator( } } + // ===== Power-loss autostop runtime (issue #1392) ===== + + private val _powerLossRuntimeSettings = MutableStateFlow(PowerLossRuntimeSettings()) + internal val powerLossRuntimeSettings: StateFlow = + _powerLossRuntimeSettings.asStateFlow() + + // Issue #1392 (P3 → P5): live power-loss HUD facts. Updated per working rep + // and at the committed `Ending set…` transition; default is inert (POWER off). + private val _powerLossHud = + MutableStateFlow(com.devil.phoenixproject.domain.powerloss.PowerLossHudState()) + internal val powerLossHud: StateFlow = + _powerLossHud.asStateFlow() + + internal fun setPowerLossHud(state: com.devil.phoenixproject.domain.powerloss.PowerLossHudState) { + _powerLossHud.value = state + } + + internal fun updatePowerLossSettings(settings: PowerLossRuntimeSettings) { + _powerLossRuntimeSettings.value = settings + } + /** * Rep boundary timestamps for MetricSample segmentation. * Each entry marks the completion timestamp of a rep, enabling per-rep metric extraction. diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutExecutionGuard.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutExecutionGuard.kt index 862956d28..289b6fc46 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutExecutionGuard.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutExecutionGuard.kt @@ -58,6 +58,10 @@ internal data class ExecutionSeed( val isAmrap: Boolean = false, val isTimedCable: Boolean = false, val usesUnlimitedRepTarget: Boolean = false, + // Issue #1392 (SD4): the ONE frozen execution target plan derived before + // lease/packet/counter creation. Null = inert REP behavior (no plan derived + // or an impossible POWER plan failed safe). + val targetPlan: com.devil.phoenixproject.domain.powerloss.ExecutionTargetPlan? = null, ) internal data class ExecutionLease( @@ -72,7 +76,21 @@ internal data class ExecutionLease( val isTimedCable: Boolean, val usesUnlimitedRepTarget: Boolean = false, val activationCutoverTimestampMs: Long? = null, -) + // Issue #1392 (SD4): frozen from the seed at beginExecution; every consumer + // (packet/counter/freshness gate/HUD/policy) reads ONE identical effective target. + val targetPlan: com.devil.phoenixproject.domain.powerloss.ExecutionTargetPlan? = null, +) { + /** + * Issue #1392 (SD4): the ONE effective working-rep target shared by the packet + * byte, counter config, freshness gate and power-loss policy. POWER's frozen + * max-reps backstop wins; every other set keeps its per-set nominal target. + */ + val effectiveWorkingRepTarget: Int + get() = targetPlan + ?.takeIf { it.targetMode == com.devil.phoenixproject.domain.powerloss.TargetMode.POWER } + ?.maxWorkingReps + ?: workingRepTarget +} internal sealed interface PersistenceClaimResult { data object Claimed : PersistenceClaimResult @@ -414,6 +432,7 @@ internal class WorkoutExecutionGuard( isAmrap = seed.isAmrap, isTimedCable = seed.isTimedCable, usesUnlimitedRepTarget = seed.usesUnlimitedRepTarget, + targetPlan = seed.targetPlan, ) currentLeaseRef.value?.let { outgoingLease -> if (sameIdentity(completionClaim?.lease, outgoingLease)) { diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutExitSnapshot.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutExitSnapshot.kt index 37ae48343..b62164e6c 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutExitSnapshot.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutExitSnapshot.kt @@ -389,6 +389,13 @@ internal data class WorkoutExitSnapshot( val cycleId: String?, val cycleDayNumber: Int?, val postSaveInput: PostSaveWorkoutInput, + /** + * Issue #1392 — frozen power-loss evidence captured at the leased-completion latch + * (P3), persisted with the set by P4. Null for REP/legacy sets and any set without + * an armed power policy; never fabricated. + */ + val powerLossEvidence: com.devil.phoenixproject.domain.powerloss.PowerLossSetEvidence? = null, + /** * Issue #1400: explicit metric-unit contract of this snapshot's unit-bearing values * (rep velocities, ROM, power). The persistent crash form ([PendingChildWrite] via diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossConfigDraft.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossConfigDraft.kt new file mode 100644 index 000000000..1c29a82f8 --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossConfigDraft.kt @@ -0,0 +1,299 @@ +package com.devil.phoenixproject.presentation.powerloss + +import com.devil.phoenixproject.domain.model.ProgramMode +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.PowerLossProtocolFamily +import com.devil.phoenixproject.domain.powerloss.TargetMode + +/** + * Issue #1392 — pure config draft/commit/cancel state machine (P5, ui-spec §3). + * + * Modal/bottom-sheet edits are a local draft: Apply validates every effective field + * and commits atomically; Cancel (or outside dismissal / system Back) discards the + * unapplied draft and restores the original target/settings. Toggling REP↔POWER + * preserves dormant values and the saved nominal reps. + * + * Pure Kotlin only — no Compose — so every row of the ui-spec config state table is + * unit-testable. SD6: preset labels are nonbreaking (`10%`, `Custom` never split). + */ +data class PowerLossConfigDraftState( + /** Last applied (authoritative) config — what the parent model holds. */ + val committed: PowerLossConfig = PowerLossConfig.DEFAULT, + /** Working copy under edit. */ + val draft: PowerLossConfig = PowerLossConfig.DEFAULT, + /** Raw custom-threshold input text (kept verbatim while invalid). */ + val customThresholdInput: String = "", + /** True while the Custom chip is selected (draft threshold edited by hand). */ + val customSelected: Boolean = false, + /** Raw max-working-reps input text. */ + val maxRepsInput: String = PowerLossConfig.DEFAULT.maxWorkingReps.toString(), + /** Dynamic upper bound from the accepted execution plan (SD4 — never a guessed universal 254). */ + val maxAllowedWorkingReps: Int = 254, + /** The exercise's protocol family (V1: Old School / Pump / Echo / Just Lift). */ + val protocolFamily: PowerLossProtocolFamily = PowerLossProtocolFamily.OLD_SCHOOL, + /** Internal capability gate (validated paired samples available). Default off. */ + val pairedSamplesValidated: Boolean = true, + /** Pending unsupported-mode confirmation, or null. */ + val pendingModeConfirmation: ModeConfirmation? = null, + /** A previously saved POWER config on an excluded mode: retained but inert. */ + val incompatibleSavedPowerConfig: Boolean = false, +) { + val capabilityAvailable: Boolean + get() = PowerLossCapabilityBridge.isEligible(protocolFamily, pairedSamplesValidated) + + val effectiveTargetMode: TargetMode + get() = if (capabilityAvailable) draft.targetMode else TargetMode.REP_TARGET + + /** POWER UI is expanded only for an effective POWER target. */ + val powerSectionExpanded: Boolean get() = effectiveTargetMode == TargetMode.POWER + + /** Persisted POWER config that cannot run in this mode: dormant/inert, no active badge. */ + val dormantPowerConfig: Boolean + get() = draft.targetMode == TargetMode.POWER && !powerSectionExpanded + + /** Caution is persistent at 36–40 inclusive; 35 shows none (ui-spec §3.4). */ + val highThresholdCautionVisible: Boolean + get() = draft.thresholdPercent in HIGH_THRESHOLD_CAUTION_MIN..PowerLossConfig.MAX_THRESHOLD_PERCENT + + val customThresholdError: String? + get() = if (customSelected && parseCustomThreshold() == null) { + PowerLossUiCopy.CUSTOM_THRESHOLD_ERROR + } else { + null + } + + val maxRepsError: String? + get() { + val parsed = parseMaxReps() ?: return PowerLossUiCopy.maxWorkingRepsError(maxAllowedWorkingReps) + return if (parsed < PowerLossConfig.MIN_MAX_WORKING_REPS || parsed > maxAllowedWorkingReps) { + PowerLossUiCopy.maxWorkingRepsError(maxAllowedWorkingReps) + } else { + null + } + } + + /** Apply is enabled only with every effective field valid and a capability path. */ + val canApply: Boolean + get() = pendingModeConfirmation == null && + customThresholdError == null && + maxRepsError == null && + (effectiveTargetMode != TargetMode.POWER || capabilityAvailable) + + val nearLimitCueReadback: String + get() = PowerLossUiCopy.nearLimitCueReadback(draft.thresholdPercent) + + /** Preset chips with SD6 nonbreaking labels. */ + val presetChips: List + get() = ThresholdPreset.entries.map { preset -> + PresetChip( + preset = preset, + label = preset.nonbreakingLabel(), + selected = when (preset) { + ThresholdPreset.CUSTOM -> customSelected + else -> !customSelected && draft.thresholdPercent == preset.percent + }, + ) + } + + // ── Transition helpers (each returns the next state) ─────────────────────── + + fun selectTargetMode(mode: TargetMode): PowerLossConfigDraftState { + // Entering an excluded mode with a POWER draft demands confirmation (§3). + val unsupportedSwitch = mode == TargetMode.POWER && !protocolFamily.supportsPowerLoss + return if (unsupportedSwitch) { + copy(pendingModeConfirmation = ModeConfirmation(targetModeRequested = mode)) + } else { + copy( + draft = draft.copy(targetMode = mode), + pendingModeConfirmation = null, + incompatibleSavedPowerConfig = false, + ) + } + } + + /** Dialog confirm: mode change proceeds with effective REP; POWER settings kept dormant. */ + fun confirmUseRepTarget(): PowerLossConfigDraftState = copy( + draft = draft.copy(targetMode = TargetMode.REP_TARGET), + pendingModeConfirmation = null, + incompatibleSavedPowerConfig = true, + ) + + /** Dialog cancel: `Keep current mode` — mode and target preserved. */ + fun dismissModeConfirmation(): PowerLossConfigDraftState = + copy(pendingModeConfirmation = null) + + fun selectPreset(preset: ThresholdPreset): PowerLossConfigDraftState = when (preset) { + ThresholdPreset.CUSTOM -> copy(customSelected = true) + else -> copy( + draft = draft.copy(thresholdPercent = preset.percent), + customSelected = false, + // Preset tap replaces an invalid custom draft and clears the error (§3.3). + customThresholdInput = preset.percent.toString(), + ) + } + + /** Free-typed custom threshold; the raw draft is kept while invalid (§3.3). */ + fun updateCustomThreshold(text: String): PowerLossConfigDraftState { + val parsed = text.trim().toIntOrNull()?.takeIf { text.trim().all { it in '0'..'9' || it == '-' } } + return copy( + customThresholdInput = text, + customSelected = true, + draft = if (parsed != null && parsed in PowerLossConfig.MIN_THRESHOLD_PERCENT..PowerLossConfig.MAX_THRESHOLD_PERCENT) { + draft.copy(thresholdPercent = parsed) + } else { + draft + }, + ) + } + + fun updateMaxReps(text: String): PowerLossConfigDraftState { + val parsed = text.trim().toIntOrNull() + return copy( + maxRepsInput = text, + draft = if (parsed != null && parsed in PowerLossConfig.MIN_MAX_WORKING_REPS..maxAllowedWorkingReps) { + draft.copy(maxWorkingReps = parsed) + } else { + draft + }, + ) + } + + fun setRequireTwoConsecutive(enabled: Boolean): PowerLossConfigDraftState = + copy(draft = draft.copy(requireTwoConsecutive = enabled)) + + /** + * Apply: validate all effective fields and commit atomically. Returns the + * committed state, or this state unchanged when validation fails. + */ + fun apply(): PowerLossConfigDraftState { + if (!canApply) return this + val threshold = if (customSelected) parseCustomThreshold() ?: return this else draft.thresholdPercent + val maxReps = parseMaxReps() ?: return this + val committedConfig = draft.copy( + thresholdPercent = threshold, + maxWorkingReps = maxReps, + ).validated() ?: return this + return copy(committed = committedConfig, draft = committedConfig) + } + + /** + * Cancel / outside dismissal / system Back: discard the unapplied draft and + * restore the original mode/target/settings (dormant values preserved). + */ + fun cancel(): PowerLossConfigDraftState = copy( + draft = committed, + customSelected = committed.thresholdPercent !in ThresholdPreset.entries + .filter { it != ThresholdPreset.CUSTOM } + .map { it.percent }, + customThresholdInput = committed.thresholdPercent.toString(), + maxRepsInput = committed.maxWorkingReps.toString(), + pendingModeConfirmation = null, + ) + + private fun parseCustomThreshold(): Int? = + customThresholdInput.trim().toIntOrNull()?.takeIf { + it in PowerLossConfig.MIN_THRESHOLD_PERCENT..PowerLossConfig.MAX_THRESHOLD_PERCENT + } + + private fun parseMaxReps(): Int? = + maxRepsInput.trim().toIntOrNull()?.takeIf { + it in PowerLossConfig.MIN_MAX_WORKING_REPS..maxAllowedWorkingReps + } + + companion object { + const val HIGH_THRESHOLD_CAUTION_MIN = 36 + + /** + * Draft seeded from an existing per-exercise config (profile-loaded or template). + * Profile-default boundary: seeds are per-exercise/per-profile — never reused + * across profiles (callers scope by profile; see [PowerLossExecutionScope]). + */ + fun seededFrom( + config: PowerLossConfig, + maxAllowedWorkingReps: Int, + protocolFamily: PowerLossProtocolFamily, + pairedSamplesValidated: Boolean = true, + ): PowerLossConfigDraftState = PowerLossConfigDraftState( + committed = config, + draft = config, + customThresholdInput = config.thresholdPercent.toString(), + customSelected = config.thresholdPercent !in ThresholdPreset.entries + .filter { it != ThresholdPreset.CUSTOM } + .map { it.percent }, + maxRepsInput = config.maxWorkingReps.toString(), + maxAllowedWorkingReps = maxAllowedWorkingReps, + protocolFamily = protocolFamily, + pairedSamplesValidated = pairedSamplesValidated, + incompatibleSavedPowerConfig = + config.targetMode == TargetMode.POWER && !protocolFamily.supportsPowerLoss, + ) + } +} + +/** Threshold preset chips: `10%`, `20%`, `30%`, `Custom` (default 20). */ +enum class ThresholdPreset(val percent: Int) { + P10(10), + P20(20), + P30(30), + CUSTOM(20), + ; + + /** SD6: numeric-unit labels are nonbreaking — `10%` never splits into `10` / `%`. */ + fun nonbreakingLabel(): String = when (this) { + CUSTOM -> "Cus${PowerLossUiCopy.WJ}tom" + else -> "${percent}${PowerLossUiCopy.WJ}%" + } +} + +/** Selected preset chip presentation state. */ +data class PresetChip( + val preset: ThresholdPreset, + val label: String, + val selected: Boolean, +) + +/** Pending unsupported-mode confirmation dialog (ui-spec §3). */ +data class ModeConfirmation( + val targetModeRequested: TargetMode, + val title: String = PowerLossUiCopy.MODE_CONFIRMATION_TITLE, + val body: String = PowerLossUiCopy.modeConfirmationBody("this mode"), + val cancelAction: String = PowerLossUiCopy.MODE_CONFIRMATION_CANCEL, + val confirmAction: String = PowerLossUiCopy.MODE_CONFIRMATION_CONFIRM, +) + +/** + * Capability gate bridge — the domain rule, surfaced for UI state. Unknown or + * unsupported protocol families never arm POWER. + */ +object PowerLossCapabilityBridge { + fun isEligible( + protocolFamily: PowerLossProtocolFamily, + pairedSamplesValidated: Boolean, + ): Boolean = protocolFamily.supportsPowerLoss && pairedSamplesValidated + + /** + * Strict effective-mode reader for persisted values: an unknown enum NEVER + * arms POWER (spec §7). + */ + fun effectiveTargetMode(persisted: String?): TargetMode = + TargetMode.fromPersisted(persisted) ?: TargetMode.REP_TARGET +} + +/** + * Profile/execution scoping for ad-hoc and routine config propagation (ui-spec §3 + * "Apply ad-hoc choices to next execution only; no cross-profile reuse"). + */ +class PowerLossExecutionScope { + private val byProfile = mutableMapOf() + + fun savedDefaultFor(profileId: String): PowerLossConfig = + byProfile[profileId] ?: PowerLossConfig.DEFAULT + + /** Persist through the caller's existing save mechanism only — never cross-profile. */ + fun rememberFor(profileId: String, config: PowerLossConfig) { + byProfile[profileId] = config + } + + /** One-shot frozen config for the next execution; clears nothing for other profiles. */ + fun freezeForExecution(profileId: String): PowerLossConfig = savedDefaultFor(profileId) +} diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossConfigPropagation.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossConfigPropagation.kt new file mode 100644 index 000000000..cb86933f9 --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossConfigPropagation.kt @@ -0,0 +1,85 @@ +package com.devil.phoenixproject.presentation.powerloss + +import com.devil.phoenixproject.domain.model.ProgramMode +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.PowerLossProtocolFamily +import com.devil.phoenixproject.domain.powerloss.TargetMode +import com.devil.phoenixproject.presentation.manager.PowerLossRuntimeSettings + +/** + * Issue #1392 — config propagation helpers (P5; integration-model §4). + * + * RoutineFlowManager, DefaultWorkoutSessionManager, ExerciseConfigViewModel and + * MainViewModel copy the per-exercise `ExerciseConfig.powerLoss` into the runtime + * seam with these helpers: initial, next set/exercise, adjusted/retry and + * transition paths. Unsupported timed/bodyweight/TUT paths and any unknown + * persisted target enum resolve to inert REP_TARGET — POWER never arms from an + * unknown or excluded mode (spec §7, SD1). + */ +internal fun powerLossRuntimeSettingsFor( + config: PowerLossConfig, + mode: ProgramMode, + isJustLiftExecutionStyle: Boolean = false, + savedNominalReps: Int? = config.savedNominalReps, + pairedSamplesValidated: Boolean = false, +): PowerLossRuntimeSettings { + val family = PowerLossProtocolFamily.of(mode, isJustLiftExecutionStyle) + // Retained-but-inert: an excluded mode keeps the saved POWER values but the + // effective runtime target is REP_TARGET. + val effectiveMode = + if (family.supportsPowerLoss) config.targetMode else TargetMode.REP_TARGET + return PowerLossRuntimeSettings( + targetMode = effectiveMode, + thresholdPercent = config.thresholdPercent, + maxWorkingReps = config.maxWorkingReps, + requireTwoConsecutive = config.requireTwoConsecutive, + savedNominalReps = savedNominalReps, + protocolFamily = family, + pairedSamplesValidated = pairedSamplesValidated, + ) +} + +/** + * Strict reader for persisted target-mode strings: an unknown value NEVER arms + * POWER. Returns a full inert config carrying the remaining persisted values. + */ +internal fun powerLossConfigFromPersisted( + persistedTargetMode: String?, + thresholdPercent: Int = PowerLossConfig.DEFAULT.thresholdPercent, + maxWorkingReps: Int = PowerLossConfig.DEFAULT.maxWorkingReps, + requireTwoConsecutive: Boolean = false, + savedNominalReps: Int? = null, +): PowerLossConfig = PowerLossConfig( + targetMode = TargetMode.fromPersisted(persistedTargetMode) ?: TargetMode.REP_TARGET, + thresholdPercent = thresholdPercent, + maxWorkingReps = maxWorkingReps, + requireTwoConsecutive = requireTwoConsecutive, + savedNominalReps = savedNominalReps, +) + +/** + * Unsupported execution paths (timed, bodyweight) keep their saved POWER values + * but resolve to the inert default for execution: POWER never arms from an + * excluded mode (spec §7). TUT/TUT Beast/Eccentric-Only are excluded by the + * protocol family inside [powerLossRuntimeSettingsFor]. + */ +internal fun powerLossExecutionConfig( + config: PowerLossConfig, + isTimed: Boolean, + isBodyweight: Boolean, +): PowerLossConfig = if (isTimed || isBodyweight) PowerLossConfig.DEFAULT else config + +/** + * Internal capability gate for the power-loss runtime seam (spec §1/§7: the + * feature stays off by default behind an internal gate until the P6–P8 release + * gate authorises enablement — never enabled by a worker). The gate models the + * "validated paired samples" prerequisite only; protocol-family eligibility is + * resolved per set inside [powerLossRuntimeSettingsFor]. + */ +internal object PowerLossRuntimeGate { + /** + * True only when validated paired samples exist for the connected trainer. + * Default OFF — POWER config intent is retained but `powerActive` stays false. + */ + var pairedSamplesValidated: Boolean = false +} diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossExportUi.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossExportUi.kt new file mode 100644 index 000000000..61f52b07c --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossExportUi.kt @@ -0,0 +1,82 @@ +package com.devil.phoenixproject.presentation.powerloss + +/** + * Issue #1392 — export entry + legacy-export omission disclosure (P5, ui-spec §6). + * + * `Export power data` leads to the versioned power-history export (P4 codec). The + * legacy Phoenix/Strong/Hevy export confirmation discloses that the format omits + * power-loss settings and per-attempt details. Copy never claims synced/portal + * parity and never fabricates data. + */ +data class PowerLossExportUi( + val entryLabel: String = PowerLossUiCopy.EXPORT_ENTRY, + val legacyOmissionDisclosure: String = PowerLossUiCopy.LEGACY_EXPORT_DISCLOSURE, + val choosePowerDataExportAction: String = PowerLossUiCopy.LEGACY_EXPORT_CHOOSE_POWER, + val exportWithoutPowerDetailsAction: String = PowerLossUiCopy.LEGACY_EXPORT_CONTINUE, + val localDataDisclosure: String = PowerLossUiCopy.LOCAL_DATA_DISCLOSURE, +) + +/** Pending legacy-export confirmation dialog state. */ +data class LegacyExportConfirmationUi( + val visible: Boolean, + val disclosure: String = PowerLossUiCopy.LEGACY_EXPORT_DISCLOSURE, + val primaryAction: String = PowerLossUiCopy.LEGACY_EXPORT_CHOOSE_POWER, + val secondaryAction: String = PowerLossUiCopy.LEGACY_EXPORT_CONTINUE, +) + +/** Show the omission disclosure before any legacy export run. */ +fun legacyExportConfirmation(): LegacyExportConfirmationUi = + LegacyExportConfirmationUi(visible = true) + +/** Export-flow intents (P5 item 4). */ +sealed interface PowerLossExportIntent { + /** The user asked for a legacy (non-power) export: disclosure comes first. */ + data object RequestLegacyExport : PowerLossExportIntent + + /** `Choose power-data export` — route to the versioned power-history export. */ + data object ChoosePowerDataExport : PowerLossExportIntent + + /** `Export without power details` — the legacy run proceeds after disclosure. */ + data object ExportWithoutPowerDetails : PowerLossExportIntent + + /** Disclosure dismissed (outside tap / back): no export runs. */ + data object DismissLegacyConfirmation : PowerLossExportIntent +} + +/** + * Pure export-flow state machine: a legacy export ALWAYS surfaces the omission + * disclosure first; `Export power data` routes to the versioned power-history + * export. Nothing runs silently without the disclosure (ui-spec §6). + */ +data class PowerLossExportFlowState( + val legacyConfirmationVisible: Boolean = false, + val legacyExportApproved: Boolean = false, + val powerExportRequested: Boolean = false, +) { + fun reduce(intent: PowerLossExportIntent): PowerLossExportFlowState = when (intent) { + PowerLossExportIntent.RequestLegacyExport -> copy( + legacyConfirmationVisible = true, + legacyExportApproved = false, + powerExportRequested = false, + ) + PowerLossExportIntent.ChoosePowerDataExport -> copy( + legacyConfirmationVisible = false, + legacyExportApproved = false, + powerExportRequested = true, + ) + PowerLossExportIntent.ExportWithoutPowerDetails -> copy( + legacyConfirmationVisible = false, + legacyExportApproved = true, + powerExportRequested = false, + ) + PowerLossExportIntent.DismissLegacyConfirmation -> copy( + legacyConfirmationVisible = false, + legacyExportApproved = false, + powerExportRequested = false, + ) + } + + companion object { + val INITIAL = PowerLossExportFlowState() + } +} diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossHistoryUi.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossHistoryUi.kt new file mode 100644 index 000000000..8ec07d66c --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossHistoryUi.kt @@ -0,0 +1,210 @@ +package com.devil.phoenixproject.presentation.powerloss + +import com.devil.phoenixproject.domain.powerloss.PowerCable +import com.devil.phoenixproject.domain.powerloss.PowerLossAttemptRecord +import com.devil.phoenixproject.domain.powerloss.PowerLossSetEvidence +import com.devil.phoenixproject.domain.powerloss.SampleQualityMarkers + +/** + * Issue #1392 — pure history / per-rep projection (P5, ui-spec §6). + * + * Compact core rows + expandable details (NOT the crowded wide table), text + * best/trigger badges, screen-reader-friendly strings. Attempt-only rows (a + * working attempt with no completed legacy rep) remain visible. Missing data + * shows `—` with a reason — NEVER a fabricated zero. + */ +data class PowerLossAttemptRowUi( + val attemptLabel: String, + val mcpText: String, + val mcpMissingReason: String?, + val lossAtDecisionText: String, + val referenceAtDecisionText: String, + val romAText: String, + val romBText: String, + val concentricText: String, + val eccentricText: String, + val eccentricMissingReason: String?, + val statusText: String, + val badges: List, + /** Expandable detail lines (`label` to `value`). */ + val details: List>, +) { + /** Compact single-line core row (small screens; no horizontal scrolling). */ + val coreLine: String + get() = listOf(attemptLabel, mcpText, lossAtDecisionText, statusText + badgeSuffix).joinToString(" · ") + + private val badgeSuffix: String + get() = if (badges.isEmpty()) "" else " (" + badges.joinToString(", ") + ")" +} + +/** One set's per-attempt table (summary `Power details` and history expand). */ +data class PowerLossRepTableUi( + val caption: String = PowerLossUiCopy.DETAILS_CAPTION, + val rows: List, + val coreRows: List, +) + +/** + * Build the per-attempt rows from frozen evidence facts. + * + * Each historical loss is relative to its reference **at that decision**, never + * recomputed against the final best; the first row's zero loss is relative to its + * own decision-time reference (SD6). + */ +fun powerLossRepTable( + attempts: List, + triggerOrdinal: Int?, + bestWorkingOrdinal: Int?, + thresholdPercent: Int, + nearLimitLossPercent: Int, + activeCables: Set, +): PowerLossRepTableUi { + val rows = attempts.map { record -> + attemptRow( + record = record, + triggerOrdinal = triggerOrdinal, + bestWorkingOrdinal = bestWorkingOrdinal, + nearLimitLossPercent = nearLimitLossPercent, + activeCables = activeCables, + ) + } + return PowerLossRepTableUi(rows = rows, coreRows = rows.map { it.coreLine }) +} + +private fun attemptRow( + record: PowerLossAttemptRecord, + triggerOrdinal: Int?, + bestWorkingOrdinal: Int?, + nearLimitLossPercent: Int, + activeCables: Set, +): PowerLossAttemptRowUi { + val loss = record.lossPercentAtDecision + val mcpMissing = record.mcpWatts == null + val qualityReason = record.quality.reasonText() + + val badges = buildList { + if (record.workingConcentricOrdinal == bestWorkingOrdinal) add(PowerLossUiCopy.BADGE_BEST) + if (record.workingConcentricOrdinal == triggerOrdinal) add(PowerLossUiCopy.BADGE_TRIGGER) + if (loss != null && loss > 0f && loss >= nearLimitLossPercent) add(PowerLossUiCopy.BADGE_NEAR_LIMIT) + if (mcpMissing) add(PowerLossUiCopy.BADGE_INVALID) + } + + val romAText = romCableText(record.romAMm, record.romAPercentOfReference, record.romTrustworthy, activeCables.contains(PowerCable.A)) + val romBText = romCableText(record.romBMm, record.romBPercentOfReference, record.romTrustworthy, activeCables.contains(PowerCable.B)) + + val details = buildList { + add(PowerLossUiCopy.COL_REFERENCE to (record.referenceWorkingOrdinal?.toString() ?: PowerLossUiCopy.MISSING)) + add(PowerLossUiCopy.COL_ROM_A to romAText) + add(PowerLossUiCopy.COL_ROM_B to romBText) + add( + PowerLossUiCopy.COL_CONCENTRIC to + (record.concentricDurationMs?.let { formatMs(it) } ?: PowerLossUiCopy.MISSING), + ) + add(PowerLossUiCopy.COL_ECCENTRIC to eccentricText(record)) + add(PowerLossUiCopy.COL_STATUS to statusText(record)) + if (qualityReason != null) add("Quality" to qualityReason) + if (record.shortRom) add("Short range of motion" to "Qualified — trusted short ROM") + if (record.powerLossQualified) add("Power loss" to "Qualified at decision") + } + + return PowerLossAttemptRowUi( + attemptLabel = record.workingConcentricOrdinal.toString(), + mcpText = record.mcpWatts?.let { "${it.toInt()} W" } ?: PowerLossUiCopy.MISSING, + mcpMissingReason = if (mcpMissing) qualityReason else null, + lossAtDecisionText = loss?.let { "${displayPercent(it)}%" } ?: PowerLossUiCopy.MISSING, + referenceAtDecisionText = record.referenceWorkingOrdinal?.toString() ?: PowerLossUiCopy.MISSING, + romAText = romAText, + romBText = romBText, + concentricText = record.concentricDurationMs?.let { formatMs(it) } ?: PowerLossUiCopy.MISSING, + eccentricText = eccentricText(record), + eccentricMissingReason = if (record.eccentricPowerWatts == null) { + PowerLossUiCopy.ECCENTRIC_INTERRUPTED + } else { + null + }, + statusText = statusText(record), + badges = badges, + details = details, + ) +} + +private fun statusText(record: PowerLossAttemptRecord): String = + if (record.completed) PowerLossUiCopy.STATUS_COMPLETED else PowerLossUiCopy.STATUS_PENDING + +private fun eccentricText(record: PowerLossAttemptRecord): String = when { + // Interrupted eccentric is null, not 0 W (SD: never fabricate zeros). + record.eccentricPowerWatts == null -> PowerLossUiCopy.MISSING + // A true measured zero stays 0 W. + else -> "${record.eccentricPowerWatts.toInt()} W" +} + +private fun romCableText( + romMm: Float?, + percentOfReference: Float?, + trustworthy: Boolean, + active: Boolean, +): String = when { + !active -> PowerLossUiCopy.CABLE_INACTIVE + romMm == null -> PowerLossUiCopy.MISSING + !trustworthy || percentOfReference == null -> "${romMm.toInt()} mm · ${PowerLossUiCopy.ROM_UNTRUSTED}" + else -> "${romMm.toInt()} mm · ${percentOfReference.toInt()}% of reference" +} + +internal fun formatMs(ms: Long): String { + val seconds = ms / 1000 + val tenths = (ms % 1000) / 100 + return "$seconds.$tenths s" +} + +/** Enumerable quality reason text for a missing metric (ui-spec quality vocabulary). */ +internal fun SampleQualityMarkers.reasonText(): String? = buildList { + if (gapBefore) add("sample gap") + if (stale) add("stale data") + if (rejected) add("rejected sample") + if (clamped) add("clamped sample") +}.joinToString(", ").takeIf { it.isNotEmpty() } + +/** + * History projection for one or more sessions (grouped or single-session view). + * Attempt-only rows — including a trigger-only row with no completed rep — stay + * visible even without a legacy `RepMetric` row. + */ +data class PowerLossHistorySetUi( + val sessionId: String, + val setId: String, + val headerLine: String, + val coreRows: List, + val table: PowerLossRepTableUi, + val triggerOnlyRow: String?, + val disclosure: String = PowerLossUiCopy.SUMMARY_DISCLOSURE, +) + +fun powerLossHistorySet(evidence: PowerLossSetEvidence): PowerLossHistorySetUi { + val table = powerLossRepTable( + attempts = evidence.attempts, + triggerOrdinal = evidence.triggerWorkingOrdinal, + bestWorkingOrdinal = evidence.attempts + .filter { it.mcpWatts != null && !it.shortRom } + .maxByOrNull { it.mcpWatts ?: 0f } + ?.workingConcentricOrdinal, + thresholdPercent = evidence.thresholdPercent, + nearLimitLossPercent = maxOf(0, evidence.thresholdPercent - 5), + activeCables = evidence.activeCables, + ) + val triggerOnly = evidence.attempts + .filter { !it.completed } + .joinToString("\n") { "${PowerLossUiCopy.COL_ATTEMPT} ${it.workingConcentricOrdinal} · ${PowerLossUiCopy.TRIGGER_ONLY_ROW_NOTE}" } + .takeIf { it.isNotEmpty() } + return PowerLossHistorySetUi( + sessionId = evidence.sessionId, + setId = evidence.setId, + headerLine = PowerLossUiCopy.summaryConfigLine( + thresholdPercent = evidence.thresholdPercent, + maxWorkingReps = evidence.maxWorkingReps, + requireTwoConsecutive = evidence.requireTwoConsecutive, + ), + coreRows = table.coreRows, + table = table, + triggerOnlyRow = triggerOnly, + ) +} diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossHudUi.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossHudUi.kt new file mode 100644 index 000000000..2de9545a1 --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossHudUi.kt @@ -0,0 +1,190 @@ +package com.devil.phoenixproject.presentation.powerloss + +import com.devil.phoenixproject.domain.powerloss.PowerCable +import com.devil.phoenixproject.domain.powerloss.PowerLossHudState + +/** + * Issue #1392 — pure HUD projection (P5, ui-spec §4 with SD6 corrections). + * + * Renders the live HUD strictly from [PowerLossHudState] facts: + * - authoritative completed count (`actualReps`) is never promoted to the + * headline working-attempt identity (SD6); + * - the readback is `Power-loss target · 20%` / `Max 20 working reps` — NEVER + * `9 / 12` from nominal reps; + * - missing data shows `—` with a reason, never a fabricated zero; + * - the committed `Ending set…` state is distinct from the completed transition. + */ +data class PowerLossHudUi( + /** False for REP sets — the panel renders nothing (REP regression unchanged). */ + val visible: Boolean, + val targetReadback: String, + val capReadback: String, + /** `8 completed reps · attempt 9 not confirmed complete` or the completed-attempt line. */ + val completedLine: String, + val statusLine: String, + val lossDisplay: String, + val latestPowerLine: String, + val bestLine: String, + val thresholdLine: String, + val nearLimit: Boolean, + /** Once-only cue identity: cue already emitted for this set. */ + val nearLimitCueEmitted: Boolean, + val invalidPowerLine: String?, + val lastValidLine: String?, + val shortRomLine: String?, + val endingLine: String?, + val referenceResetLine: String?, + /** E04 caveat while the reference's ROM/mask is untrusted (ui-spec §4). */ + val referenceLimitedNote: String? = null, + val lockedNote: String = PowerLossUiCopy.TARGET_LOCKED, + val warmupNote: String? = null, + val capAndStopActive: String = PowerLossUiCopy.HUD_CAP_AND_STOP_ACTIVE, +) { + /** SD6 readback identity: never a nominal-rep `9 / 12` fraction. */ + val nominalRepFractionHidden: Boolean get() = true +} + +/** + * Project HUD facts into display state. + * + * @param warmupActive Warm-up phase (counters kept separate; no fatigue/ROM cue/stop). + * @param referenceRomUncertain Initial ROM/mask uncertainty caveat. + * @param interrupted Restart/reconnect/restored interruption state. + * @param latestPowerWatts Last sealed concentric MCP in watts (display only), or null. + * @param bestWatts Best working MCP, or null. + * @param qualifyingCount Two-consecutive streak count (1..2), or null when the + * requirement is off. + */ +fun powerLossHudUi( + state: PowerLossHudState, + warmupActive: Boolean = false, + referenceRomUncertain: Boolean = false, + interrupted: Boolean = false, + latestPowerWatts: Float? = null, + bestWatts: Float? = null, + qualifyingCount: Int? = null, +): PowerLossHudUi { + if (!state.powerActive) return inactiveHudUi() + + val attempt = state.currentAttemptOrdinal + val completed = state.completedRepCount + val completedLine = if (attempt > completed) { + PowerLossUiCopy.hudPendingLine(completed, attempt) + } else if (attempt > 0) { + PowerLossUiCopy.hudCompletedAttemptLine(attempt) + } else { + PowerLossUiCopy.hudPendingLine(completed, attempt) + } + + val shortRomLine = state.cableRomPercentOfReference.entries + .filter { it.value < SHORT_ROM_REFERENCE_PERCENT } + .sortedBy { it.key.name } + .joinToString(" · ") { (cable, percent) -> + PowerLossUiCopy.cableRomFragment(cableLabel(cable), percent.toInt()) + } + .takeIf { it.isNotEmpty() } + ?.let { PowerLossUiCopy.HUD_SHORT_ROM_PREFIX + it } + + val invalidPowerLine = state.invalidPowerReason?.let { + PowerLossUiCopy.HUD_INVALID_POWER_PREFIX + it + } + val lastValidLine = state.lastValidAttemptOrdinal?.let { + PowerLossUiCopy.HUD_LAST_VALID_PREFIX + it + } + + val lossDisplay = state.lastLossPercent?.let { "${displayPercent(it)}%" } ?: PowerLossUiCopy.MISSING + val latestPowerLine = if (latestPowerWatts != null) { + PowerLossUiCopy.HUD_LATEST_POWER_PREFIX + "${latestPowerWatts.toInt()} W" + } else { + PowerLossUiCopy.HUD_LATEST_POWER_PREFIX + PowerLossUiCopy.MISSING + } + val bestLine = if (state.referenceEstablished && bestWatts != null) { + PowerLossUiCopy.HUD_BEST_PREFIX + "${state.referenceWorkingOrdinal ?: "—"} · ${bestWatts.toInt()} W" + } else { + PowerLossUiCopy.HUD_BEST_PREFIX + PowerLossUiCopy.MISSING + } + + val nearLimit = state.lastLossPercent != null && + state.lastLossPercent > 0f && + state.lastLossPercent >= state.nearLimitLossPercent + + val statusLine = when { + state.endingSet -> PowerLossUiCopy.HUD_ENDING_SET + warmupActive -> PowerLossUiCopy.HUD_WARMUP + interrupted -> PowerLossUiCopy.HUD_INTERRUPTED + invalidPowerLine != null -> invalidPowerLine + !state.referenceEstablished -> PowerLossUiCopy.HUD_NO_BASELINE + qualifyingCount != null && qualifyingCount > 0 -> + PowerLossUiCopy.HUD_CONSECUTIVE_QUALIFYING_PREFIX + qualifyingCount + PowerLossUiCopy.HUD_CONSECUTIVE_OF + nearLimit -> PowerLossUiCopy.HUD_NEAR_LIMIT + // E04 (ui-spec §4 `Initial ROM/mask uncertain`): while the reference's + // ROM/mask is untrusted the generic first-attempt/normal states do not + // apply — range checks are limited until a trustworthy reference exists. + referenceRomUncertain -> PowerLossUiCopy.HUD_ROM_REFERENCE_LIMITED + attempt == 1 -> PowerLossUiCopy.HUD_FIRST_ATTEMPT_NOTE + else -> PowerLossUiCopy.HUD_BELOW_TARGET + } + + return PowerLossHudUi( + visible = true, + targetReadback = PowerLossUiCopy.hudTargetReadback(state.thresholdPercent), + capReadback = PowerLossUiCopy.hudCapReadback(state.maxWorkingReps), + completedLine = completedLine, + statusLine = statusLine, + lossDisplay = lossDisplay, + latestPowerLine = latestPowerLine, + bestLine = bestLine, + thresholdLine = PowerLossUiCopy.hudThresholdLine(state.thresholdPercent, state.nearLimitLossPercent), + nearLimit = nearLimit, + nearLimitCueEmitted = state.nearLimitCueEmitted, + invalidPowerLine = invalidPowerLine, + lastValidLine = lastValidLine, + shortRomLine = shortRomLine, + endingLine = if (state.endingSet) { + PowerLossUiCopy.HUD_ENDING_SET + } else { + null + }, + referenceResetLine = if (interrupted) { + PowerLossUiCopy.HUD_REFERENCE_RESET + } else { + null + }, + referenceLimitedNote = if (referenceRomUncertain) { + PowerLossUiCopy.HUD_ROM_REFERENCE_LIMITED_NOTE + } else { + null + }, + warmupNote = if (warmupActive) PowerLossUiCopy.HUD_WARMUP_NOTE else null, + ) +} + +private fun inactiveHudUi(): PowerLossHudUi = PowerLossHudUi( + visible = false, + targetReadback = "", + capReadback = "", + completedLine = "", + statusLine = "", + lossDisplay = PowerLossUiCopy.MISSING, + latestPowerLine = "", + bestLine = "", + thresholdLine = "", + nearLimit = false, + nearLimitCueEmitted = false, + invalidPowerLine = null, + lastValidLine = null, + shortRomLine = null, + endingLine = null, + referenceResetLine = null, +) + +/** Display-only rounding to whole percent, clamped 0–100 (never used for decisions). */ +internal fun displayPercent(value: Float): Int = value.coerceIn(0f, 100f).toInt() + +/** Strictly below 85% of the reference ROM is short on an active cable; equality is not (SD2). */ +internal const val SHORT_ROM_REFERENCE_PERCENT: Float = 85f + +private fun cableLabel(cable: PowerCable): String = when (cable) { + PowerCable.A -> "Cable A" + PowerCable.B -> "Cable B" +} diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossSummaryUi.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossSummaryUi.kt new file mode 100644 index 000000000..fab8cfc9e --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossSummaryUi.kt @@ -0,0 +1,173 @@ +package com.devil.phoenixproject.presentation.powerloss + +import com.devil.phoenixproject.domain.powerloss.PowerLossAttemptRecord +import com.devil.phoenixproject.domain.powerloss.PowerLossSetSummaryFacts +import com.devil.phoenixproject.domain.powerloss.PowerStopReason + +/** + * Issue #1392 — pure set-summary projection (P5, ui-spec §6 with SD6 corrections). + * + * SD6 (binding): the headline `Stopped at rep 9 — 21% power loss (best: rep 2)` + * renders ONLY with the adjacent `8 completed reps · lifting attempt 9` + * clarification, and the completed count comes from `actualReps` — NEVER promoted + * to match the headline. UI renders the engine's committed winner only; it never + * chooses a new winner when both ROM and loss qualified (SD2). + */ +data class PowerLossSummaryUi( + /** Null when no power block should render (plain REP sets — regression unchanged). */ + val headline: String?, + /** SD6 clarification; must render adjacent to [headline] whenever [headline] != null. */ + val clarification: String?, + val configLine: String, + val helpLine: String = PowerLossUiCopy.SUMMARY_HELP, + val secondaryLine: String? = null, + val unavailableLine: String? = null, + val disclosure: String = PowerLossUiCopy.SUMMARY_DISCLOSURE, + val table: PowerLossRepTableUi, + val savedRepsHeader: String, + val powerActiveBadge: String?, + val savedRepReadback: String?, +) { + /** SD6 invariant: headline never renders without its clarification. */ + val headlineWithClarification: String? + get() = if (headline == null) null else "$headline\n${clarification.orEmpty()}" +} + +/** Enumerated summary variants (mutually exclusive headline forms). */ +enum class PowerLossSummaryVariant { + POWER_LOSS, + SHORT_ROM, + MAX_REPS_BACKSTOP, + MANUAL, + LEGACY_UNAVAILABLE, +} + +fun powerLossSummaryVariant(facts: PowerLossSetSummaryFacts): PowerLossSummaryVariant = when { + facts.winnerReason == PowerStopReason.POWER_LOSS -> PowerLossSummaryVariant.POWER_LOSS + facts.winnerReason == PowerStopReason.SHORT_ROM -> PowerLossSummaryVariant.SHORT_ROM + facts.winnerReason == PowerStopReason.MAX_REPS_BACKSTOP -> PowerLossSummaryVariant.MAX_REPS_BACKSTOP + facts.attempts.isNotEmpty() -> PowerLossSummaryVariant.MANUAL + else -> PowerLossSummaryVariant.LEGACY_UNAVAILABLE +} + +/** + * Render summary facts. [endedManually] distinguishes a manual stop from + * safety/stall/release/disconnect flows (which keep their existing reason heading — + * the power block adds observations only and never overwrites it). + */ +fun powerLossSummaryUi( + facts: PowerLossSetSummaryFacts, + savedNominalReps: Int? = facts.savedNominalReps, + endedManually: Boolean = false, + activeCables: Set = + setOf( + com.devil.phoenixproject.domain.powerloss.PowerCable.A, + com.devil.phoenixproject.domain.powerloss.PowerCable.B, + ), +): PowerLossSummaryUi { + val variant = powerLossSummaryVariant(facts) + val stoppedAt = facts.stoppedAtWorkingAttempt + val table = powerLossRepTable( + attempts = facts.attempts, + triggerOrdinal = stoppedAt, + bestWorkingOrdinal = facts.bestWorkingOrdinal, + thresholdPercent = facts.thresholdPercent, + nearLimitLossPercent = maxOf(0, facts.thresholdPercent - 5), + activeCables = activeCables, + ) + val configLine = PowerLossUiCopy.summaryConfigLine( + thresholdPercent = facts.thresholdPercent, + maxWorkingReps = facts.maxWorkingReps, + requireTwoConsecutive = facts.requireTwoConsecutive, + ) + val savedRepsHeader = PowerLossUiCopy.savedRepsHeader(savedNominalReps) + val powerActiveBadge = + if (variant == PowerLossSummaryVariant.LEGACY_UNAVAILABLE) null else PowerLossUiCopy.POWER_ACTIVE_BADGE + val savedRepReadback = + if (variant == PowerLossSummaryVariant.LEGACY_UNAVAILABLE) { + null + } else { + PowerLossUiCopy.savedRepReadback(savedNominalReps) + } + + return when (variant) { + PowerLossSummaryVariant.POWER_LOSS -> { + val lossDisplay = facts.lossPercentAtStop?.let { displayPercent(it) } ?: 0 + PowerLossSummaryUi( + headline = PowerLossUiCopy.summaryPowerLossHeadline( + stoppedAtAttempt = stoppedAt ?: 0, + lossPercentDisplay = lossDisplay, + bestWorkingOrdinal = facts.bestWorkingOrdinal, + ), + clarification = PowerLossUiCopy.summaryClarification(facts.completedRepCount, stoppedAt), + configLine = configLine, + secondaryLine = null, + table = table, + savedRepsHeader = savedRepsHeader, + powerActiveBadge = powerActiveBadge, + savedRepReadback = savedRepReadback, + ) + } + PowerLossSummaryVariant.SHORT_ROM -> { + val trigger = facts.attempts.firstOrNull { it.workingConcentricOrdinal == stoppedAt } + val romFacts = secondaryRomFacts(trigger) + PowerLossSummaryUi( + headline = PowerLossUiCopy.summaryShortRomHeadline(stoppedAt ?: 0), + clarification = PowerLossUiCopy.summaryClarification(facts.completedRepCount, stoppedAt), + configLine = configLine, + secondaryLine = romFacts, + table = table, + savedRepsHeader = savedRepsHeader, + powerActiveBadge = powerActiveBadge, + savedRepReadback = savedRepReadback, + ) + } + PowerLossSummaryVariant.MAX_REPS_BACKSTOP -> { + val secondary = facts.lossPercentAtStop?.let { + "Loss at stop: ${displayPercent(it)}% — measured, not the stop cause" + } + PowerLossSummaryUi( + headline = PowerLossUiCopy.summaryMaxRepsHeadline(facts.maxWorkingReps ?: facts.completedRepCount), + clarification = PowerLossUiCopy.summaryClarification(facts.completedRepCount, stoppedAt), + configLine = configLine, + secondaryLine = secondary, + table = table, + savedRepsHeader = savedRepsHeader, + powerActiveBadge = powerActiveBadge, + savedRepReadback = savedRepReadback, + ) + } + PowerLossSummaryVariant.MANUAL -> PowerLossSummaryUi( + headline = if (endedManually) PowerLossUiCopy.SUMMARY_MANUAL else null, + clarification = null, + configLine = configLine, + secondaryLine = null, + table = table, + savedRepsHeader = savedRepsHeader, + powerActiveBadge = powerActiveBadge, + savedRepReadback = savedRepReadback, + ) + PowerLossSummaryVariant.LEGACY_UNAVAILABLE -> PowerLossSummaryUi( + headline = null, + clarification = null, + configLine = configLine, + unavailableLine = PowerLossUiCopy.SUMMARY_UNAVAILABLE, + table = table, + savedRepsHeader = savedRepsHeader, + powerActiveBadge = null, + savedRepReadback = null, + ) + } +} + +/** + * SHORT_ROM secondary facts: `Cable A: 82% of reference · best: rep 2`. Missing + * MCP/loss stays unavailable — a ROM deficit is never converted into a loss. + */ +private fun secondaryRomFacts(trigger: PowerLossAttemptRecord?): String { + val cableText = listOfNotNull( + trigger?.romAPercentOfReference?.let { "Cable A: ${it.toInt()}% of reference" }, + trigger?.romBPercentOfReference?.let { "Cable B: ${it.toInt()}% of reference" }, + ).joinToString(" · ") + return cableText +} diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossTargetReadbackUi.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossTargetReadbackUi.kt new file mode 100644 index 000000000..4b543efe3 --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossTargetReadbackUi.kt @@ -0,0 +1,106 @@ +package com.devil.phoenixproject.presentation.powerloss + +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.PowerLossProtocolFamily +import com.devil.phoenixproject.domain.powerloss.TargetMode + +/** + * Issue #1392 — set-ready / Just Lift / bottom-sheet target readback facts (P5, + * ui-spec §2–§3). Pure presentation state so every readback row is unit-testable. + * + * Rules (SD6, ui-spec §2/§3): + * - The readback card renders ONLY when the saved target is POWER (active or + * dormant) — plain REP sets render nothing (REP regression unchanged). + * - Active POWER shows `Power-loss target · 20%`, `Max 20 working reps`, + * `Saved reps: 12` and the adjacent `Power-loss target active` badge — never + * `9 / 12` from nominal reps. + * - A POWER config on an excluded mode/type is retained but inert, with the + * `Power-loss target is not active in this mode.` banner — POWER never arms + * from an unknown or excluded mode. + * - Active-set UI is read-only: `Target locked for this set.` Editing happens + * before the next set, never from the active set. + */ +data class PowerLossTargetReadbackUi( + /** False for plain REP sets — the card renders nothing. */ + val visible: Boolean, + val lines: List, + val targetLockedLine: String?, + val savedRepsLine: String?, + val powerActiveBadge: String?, + val dormantBanner: String?, +) { + val targetLocked: Boolean get() = targetLockedLine != null + + companion object { + val HIDDEN = PowerLossTargetReadbackUi( + visible = false, + lines = emptyList(), + targetLockedLine = null, + savedRepsLine = null, + powerActiveBadge = null, + dormantBanner = null, + ) + } +} + +/** + * Build the pre/during-set target readback from the per-exercise config and its + * execution context. [locked] renders the during-set `Target locked for this + * set.` line — active-set UI never edits the target. + */ +fun powerLossTargetReadback( + config: PowerLossConfig, + supportedExecution: Boolean, + savedNominalReps: Int? = config.savedNominalReps, + locked: Boolean = false, +): PowerLossTargetReadbackUi { + if (config.targetMode != TargetMode.POWER) return PowerLossTargetReadbackUi.HIDDEN + val savedRepsLine = savedNominalReps?.let { PowerLossUiCopy.savedRepsHeader(it) } + val lockedLine = if (locked) PowerLossUiCopy.TARGET_LOCKED_SHORT else null + return if (supportedExecution) { + val badge = PowerLossUiCopy.POWER_ACTIVE_BADGE + PowerLossTargetReadbackUi( + visible = true, + lines = listOfNotNull( + lockedLine, + PowerLossUiCopy.hudTargetReadback(config.thresholdPercent), + PowerLossUiCopy.hudCapReadback(config.maxWorkingReps).takeIf { it.isNotEmpty() }, + savedRepsLine, + badge, + ), + targetLockedLine = lockedLine, + savedRepsLine = savedRepsLine, + powerActiveBadge = badge, + dormantBanner = null, + ) + } else { + PowerLossTargetReadbackUi( + visible = true, + lines = listOfNotNull( + lockedLine, + PowerLossUiCopy.INCOMPATIBLE_SAVED_BANNER, + savedRepsLine, + ), + targetLockedLine = lockedLine, + savedRepsLine = savedRepsLine, + powerActiveBadge = null, + dormantBanner = PowerLossUiCopy.INCOMPATIBLE_SAVED_BANNER, + ) + } +} + +/** + * Execution-context helper: whether the power-loss target can run for this + * exercise at all (protocol family + non-excluded execution type). Timed and + * bodyweight executions are excluded exactly like unsupported protocol families. + */ +fun powerLossExecutionSupported( + config: PowerLossConfig, + mode: com.devil.phoenixproject.domain.model.ProgramMode, + isJustLiftExecutionStyle: Boolean = false, + isTimed: Boolean = false, + isBodyweight: Boolean = false, +): Boolean { + val family = PowerLossProtocolFamily.of(mode, isJustLiftExecutionStyle) + return family.supportsPowerLoss && !isTimed && !isBodyweight +} diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossUiCopy.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossUiCopy.kt new file mode 100644 index 000000000..d7f153dae --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossUiCopy.kt @@ -0,0 +1,230 @@ +package com.devil.phoenixproject.presentation.powerloss + +/** + * Issue #1392 — canonical power-loss UI copy (P5). + * + * Every string here is fixed by `prototype/design/ui-spec.md` §3–§7 and corrected + * by signoff SD6 (which wins on conflict). Tests assert these strings verbatim. + * + * Copy contains NO physiological/RPE/efficacy claims and NO verified-audible-playback + * claims (spec §1). Never localize by string-splitting: preset labels carry invisible + * word joiners so `10%` and `Custom` cannot break across lines (SD6). + */ +object PowerLossUiCopy { + + /** Invisible word joiner (U+2060): blocks line breaks without changing glyphs. */ + const val WJ: String = "\u2060" + + // ── Config section (ui-spec §3) ──────────────────────────────────────────── + const val SECTION_HEADING = "Set target" + const val REP_TARGET_LABEL = "Rep target" + const val POWER_TARGET_LABEL = "Power-loss target" + + const val REP_HELPER = "End at your rep target." + + const val POWER_LEAD = "End when lifting power drops from your best working rep." + const val POWER_HELP = + "Mean Concentric Power (MCP) averages the combined lifting power of the active cables. " + + "Warm-ups do not set the best rep. Power is checked after each lifting phase, not continuously." + + const val THRESHOLD_LABEL = "Power-loss threshold" + const val CUSTOM_THRESHOLD_LABEL = "Custom threshold (%)" + const val CUSTOM_THRESHOLD_HELPER = "Whole number from 5 to 40." + const val CUSTOM_THRESHOLD_ERROR = "Enter a whole number from 5 to 40." + + const val HIGH_THRESHOLD_TITLE = "High power-loss threshold" + const val HIGH_THRESHOLD_BODY = + "Above 35% allows a larger drop before the set ends. Consider a lower threshold." + + const val MAX_WORKING_REPS_LABEL = "Max working reps" + const val MAX_WORKING_REPS_HELPER = + "The set ends at this limit even if power data is unavailable. Warm-ups are not included." + + /** Dynamic bound helper: `Enter 2–{maxAllowed} working reps.` (en dash). */ + fun maxWorkingRepsError(maxAllowed: Int): String = "Enter 2–$maxAllowed working reps." + + const val TWO_CONSECUTIVE_LABEL = "Require 2 consecutive reps" + const val TWO_CONSECUTIVE_OFF_HELPER = + "One qualifying working rep can end the set, starting with the second working attempt." + + /** + * SD1-corrected helper: an unavailable attempt resets the streak only when the + * observation has NEITHER trustworthy qualifying reason — not any null-MCP + * observation (a trusted short-ROM observation may still qualify with missing power). + */ + const val TWO_CONSECUTIVE_ON_HELPER = + "Two adjacent qualifying attempts are required. Either power loss or short range of motion " + + "can qualify. An attempt with neither qualifying reason — including an unavailable " + + "attempt — resets the count. The max-reps limit still applies." + + const val SHORT_ROM_SAFEGUARD = + "Short range of motion also counts: below 85% of the best rep\u2019s movement on either active cable." + const val SHORT_ROM_SAFEGUARD_HELP = + "A valid power baseline and at least two observed working lifting attempts are required. " + + "Missing power alone does not count as fatigue. Initial range checks may be limited " + + "until a trustworthy reference is available." + + const val ECHO_NOTE = "Stopping uses lifting power only. Lowering power is logged separately when available." + + const val NEAR_LIMIT_CUE_PREFIX = "Near-limit cue: " + const val NEAR_LIMIT_CUE_SUFFIX = "% loss" + const val NEAR_LIMIT_CUE_FIRST_POSITIVE = "Near-limit cue: first positive power loss" + const val NEAR_LIMIT_CUE_HELP = + "Plays once on a valid positive loss, if sound is enabled. A set-ending cue takes priority." + + const val LOCAL_DATA_DISCLOSURE = + "Power-loss settings and detailed results stay on this device. Use backup or power-data " + + "export to move them; they are not synced to the portal." + + const val SAVED_REPS_HEADER_PREFIX = "Saved reps: " + const val POWER_ACTIVE_BADGE = "Power-loss target active" + const val SAVED_REP_READBACK_SUFFIX = " (not used for this set)" + const val SAVED_REP_READBACK_PREFIX = "Saved rep target: " + + /** `Near-limit cue: {max(0, T−5)}% loss`; at 5% the baseline is not promised a beep. */ + fun nearLimitCueReadback(thresholdPercent: Int): String { + val cue = maxOf(0, thresholdPercent - 5) + return if (cue == 0) NEAR_LIMIT_CUE_FIRST_POSITIVE else "$NEAR_LIMIT_CUE_PREFIX$cue$NEAR_LIMIT_CUE_SUFFIX" + } + + /** `Saved reps: 12` header fact (SD6). */ + fun savedRepsHeader(savedNominalReps: Int?): String = + SAVED_REPS_HEADER_PREFIX + (savedNominalReps?.toString() ?: "—") + + /** `Saved rep target: 12 (not used for this set)` POWER readback. */ + fun savedRepReadback(savedNominalReps: Int?): String = + SAVED_REP_READBACK_PREFIX + (savedNominalReps?.toString() ?: "—") + SAVED_REP_READBACK_SUFFIX + + // ── Draft/apply semantics (ui-spec §3) ───────────────────────────────────── + const val MODE_CONFIRMATION_TITLE = "Use Rep target for this mode?" + const val MODE_CONFIRMATION_BODY_PREFIX = "Power-loss target is not available for " + const val MODE_CONFIRMATION_BODY_SUFFIX = ". Your power-loss settings will be kept, but will not apply." + const val MODE_CONFIRMATION_CANCEL = "Keep current mode" + const val MODE_CONFIRMATION_CONFIRM = "Use Rep target" + + fun modeConfirmationBody(modeLabel: String): String = + MODE_CONFIRMATION_BODY_PREFIX + modeLabel + MODE_CONFIRMATION_BODY_SUFFIX + + const val INCOMPATIBLE_SAVED_BANNER = "Power-loss target is not active in this mode." + const val CAPABILITY_UNAVAILABLE = "Power-loss target unavailable for this trainer." + const val CAPABILITY_UNAVAILABLE_SECONDARY = "Use Rep target to continue." + + const val TARGET_LOCKED = "Target locked for this set. Edit before the next set." + const val TARGET_LOCKED_SHORT = "Target locked for this set." + + // ── Active HUD (ui-spec §4) ──────────────────────────────────────────────── + const val HUD_POWER_PANEL_LABEL = "Power loss" + const val HUD_BELOW_TARGET = "Below target" + const val HUD_NEAR_LIMIT = "Near power-loss target" + const val HUD_WARMUP = "Warm-up — building movement reference" + const val HUD_WARMUP_NOTE = "Warm-ups do not set best power." + const val HUD_NO_BASELINE = "Waiting for valid lifting power" + const val HUD_FIRST_ATTEMPT_NOTE = "Monitoring starts with the second working attempt." + const val HUD_INVALID_POWER_PREFIX = "Power unavailable — " + const val HUD_LAST_VALID_PREFIX = "Last valid · attempt " + const val HUD_CAP_AND_STOP_ACTIVE = "Max-reps limit and manual stop remain active." + const val HUD_ROM_REFERENCE_LIMITED = "Initial movement reference limited" + const val HUD_ROM_REFERENCE_LIMITED_NOTE = + "Range checks may be limited until a trustworthy reference is available." + const val HUD_ENDING_SET = "Ending set…" + const val HUD_REFERENCE_RESET = "Power reference reset" + const val HUD_INTERRUPTED = "This set was interrupted. Restart the set to build a new reference." + const val HUD_CONSECUTIVE_QUALIFYING_PREFIX = "Qualifying attempts: " + const val HUD_CONSECUTIVE_OF = " of 2" + const val HUD_QUALIFYING_POWER_LOSS = "Power loss reached" + const val HUD_QUALIFYING_SHORT_ROM = "Short range of motion" + const val HUD_QUALIFYING_RESET = "Qualifying count reset" + const val HUD_LATEST_POWER_PREFIX = "Latest lifting power " + const val HUD_BEST_PREFIX = "Best: rep " + const val HUD_NEW_BEST_PREFIX = "New best · rep " + const val HUD_SHORT_ROM_PREFIX = "Short range of motion · " + + /** `Power-loss target · 20%` readback (never `9 / 12`). */ + fun hudTargetReadback(thresholdPercent: Int): String = "Power-loss target · $thresholdPercent%" + + /** `Max 20 working reps` readback; empty when no finite cap applies. */ + fun hudCapReadback(maxWorkingReps: Int?): String = + maxWorkingReps?.let { "Max $it working reps" } ?: "" + + /** `Target 20% · cue from 15%` (cue line is the near-limit threshold). */ + fun hudThresholdLine(thresholdPercent: Int, nearLimitLossPercent: Int): String = + "Target $thresholdPercent% · cue from $nearLimitLossPercent%" + + /** `8 completed reps · attempt 9 not confirmed complete` (SD6 — completed from actualReps). */ + fun hudPendingLine(completedRepCount: Int, attemptOrdinal: Int): String = + "$completedRepCount completed reps · attempt $attemptOrdinal not confirmed complete" + + /** `Working attempt 9 · lifting phase complete`. */ + fun hudCompletedAttemptLine(attemptOrdinal: Int): String = + "Working attempt $attemptOrdinal · lifting phase complete" + + /** `Cable A 82% of reference` fragment. */ + fun cableRomFragment(cableLabel: String, percentOfReference: Int): String = + "$cableLabel $percentOfReference% of reference" + + // ── Summary (ui-spec §6) ─────────────────────────────────────────────────── + /** SD6: the headline renders ONLY with this adjacent clarification. */ + fun summaryClarification(completedRepCount: Int, stoppedAtAttempt: Int?): String = + "$completedRepCount completed reps · lifting attempt ${stoppedAtAttempt ?: "—"}" + + fun summaryConfigLine(thresholdPercent: Int, maxWorkingReps: Int?, requireTwoConsecutive: Boolean): String { + val cap = maxWorkingReps?.let { "Max $it working reps" } ?: "Max reps —" + val consecutive = if (requireTwoConsecutive) "Consecutive requirement on" else "Consecutive requirement off" + return "Target $thresholdPercent% · $cap · $consecutive" + } + + const val SUMMARY_HELP = + "Rep numbers here refer to working lifting attempts. The final attempt may not have a confirmed lowering phase." + const val SUMMARY_UNAVAILABLE = "Power-loss details unavailable for this set." + const val SUMMARY_MANUAL = "Set stopped manually" + const val SUMMARY_SHORT_ROM_PREFIX = "Stopped at attempt " + const val SUMMARY_SHORT_ROM_SUFFIX = " — short range of motion" + const val SUMMARY_MAX_REPS_SUFFIX = " — max-reps limit" + const val SUMMARY_DISCLOSURE = + "Detailed power data is stored on this device, not synced to the portal." + + /** `Stopped at rep 9 — 21% power loss (best: rep 2)` (display-rounded loss). */ + fun summaryPowerLossHeadline(stoppedAtAttempt: Int, lossPercentDisplay: Int, bestWorkingOrdinal: Int?): String { + val best = bestWorkingOrdinal?.let { " (best: rep $it)" } ?: "" + return "Stopped at rep $stoppedAtAttempt — $lossPercentDisplay% power loss$best" + } + + /** `Stopped at attempt 9 — short range of motion`. */ + fun summaryShortRomHeadline(stoppedAtAttempt: Int): String = + SUMMARY_SHORT_ROM_PREFIX + stoppedAtAttempt + SUMMARY_SHORT_ROM_SUFFIX + + /** `Stopped at 20 working reps — max-reps limit`. */ + fun summaryMaxRepsHeadline(maxWorkingReps: Int): String = + "Stopped at $maxWorkingReps working reps" + SUMMARY_MAX_REPS_SUFFIX + + // ── History / per-rep details (ui-spec §6) ───────────────────────────────── + const val DETAILS_EXPAND_LABEL = "Power details" + const val DETAILS_CAPTION = "Mean Concentric Power (MCP) · W" + const val COL_ATTEMPT = "Working attempt" + const val COL_MCP = "MCP (W)" + const val COL_LOSS = "Loss at decision" + const val COL_REFERENCE = "Reference at decision" + const val COL_ROM_A = "ROM A" + const val COL_ROM_B = "ROM B" + const val COL_CONCENTRIC = "Concentric" + const val COL_ECCENTRIC = "Eccentric" + const val COL_STATUS = "Status" + const val BADGE_BEST = "Best" + const val BADGE_TRIGGER = "Trigger" + const val BADGE_NEAR_LIMIT = "Near-limit" + const val BADGE_INVALID = "Invalid" + const val STATUS_COMPLETED = "Completed" + const val STATUS_PENDING = "Pending — not confirmed complete" + const val MISSING = "—" + const val ECCENTRIC_INTERRUPTED = "Not recorded — set ended before lowering completed" + const val CABLE_INACTIVE = "Not active" + const val ROM_UNTRUSTED = "Unavailable — reference not established" + const val TRIGGER_ONLY_ROW_NOTE = "Trigger observation — no completed rep recorded" + + // ── Export (ui-spec §6) ──────────────────────────────────────────────────── + const val EXPORT_ENTRY = "Export power data" + const val LEGACY_EXPORT_DISCLOSURE = + "This format does not include power-loss settings or per-attempt details. Use power-data export to keep them." + const val LEGACY_EXPORT_CHOOSE_POWER = "Choose power-data export" + const val LEGACY_EXPORT_CONTINUE = "Export without power details" +} diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossUiFacts.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossUiFacts.kt new file mode 100644 index 000000000..fdead8dc9 --- /dev/null +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossUiFacts.kt @@ -0,0 +1,35 @@ +package com.devil.phoenixproject.presentation.powerloss + +import com.devil.phoenixproject.domain.powerloss.PowerLossHudState +import com.devil.phoenixproject.domain.powerloss.PowerLossSetSummaryFacts + +/** + * Issue #1392 — INTEGRATION ADAPTER (P5 owned). + * + * The parallel engine/persistence packets add two names that are NOT yet present + * on this branch: + * - `WorkoutState.SetSummary.powerLoss: PowerLossSetSummaryFacts?` + * - engine/state-holder `powerLossHud: StateFlow` + * + * Per the packet contract, those two references live ONLY behind this file. The + * bodies below are the placeholder defaults used until integration; reconciling + * this file at integration is a one-line change per function (marked INTEGRATION). + * Everything else in presentation/powerloss renders strictly from the frozen + * domain facts and is fully tested. + */ +object PowerLossUiFacts { + + /** + * INTEGRATION: `summary.powerLoss` (WorkoutState.SetSummary.powerLoss). + * Until the parallel packet lands, summaries carry no power facts. + */ + fun summaryFacts(summaryPowerLoss: PowerLossSetSummaryFacts?): PowerLossSetSummaryFacts? = + summaryPowerLoss + + /** + * INTEGRATION: engine `powerLossHud` StateFlow value. + * Until the parallel packet lands, HUD facts default to the inert state. + */ + fun hudFacts(engineHud: PowerLossHudState?): PowerLossHudState = + engineHud ?: PowerLossHudState() +} diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/viewmodel/ExerciseConfigViewModel.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/viewmodel/ExerciseConfigViewModel.kt index e27f68899..e8127ed34 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/viewmodel/ExerciseConfigViewModel.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/viewmodel/ExerciseConfigViewModel.kt @@ -23,8 +23,12 @@ import com.devil.phoenixproject.domain.model.WeightUnit import com.devil.phoenixproject.domain.model.WorkoutMode import com.devil.phoenixproject.domain.model.generateUUID import com.devil.phoenixproject.domain.model.toWorkoutMode +import com.devil.phoenixproject.domain.powerloss.PowerLossProtocolFamily import com.devil.phoenixproject.domain.usecase.ResolveRoutineScalingBaselineUseCase import com.devil.phoenixproject.domain.usecase.RoutineScalingBaseline +import com.devil.phoenixproject.presentation.powerloss.PowerLossConfigDraftState +import com.devil.phoenixproject.presentation.powerloss.PowerLossRuntimeGate +import com.devil.phoenixproject.presentation.powerloss.powerLossRuntimeSettingsFor import kotlin.math.roundToInt import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Deferred @@ -203,6 +207,47 @@ class ExerciseConfigViewModel constructor( private val _rackBehaviorOverrides = MutableStateFlow>(emptyMap()) val rackBehaviorOverrides: StateFlow> = _rackBehaviorOverrides.asStateFlow() + // ===== Issue #1392 — Set-target config (P5, ui-spec §3) ===================== + // Edits run through the pure draft state machine: Apply validates every + // effective field and commits atomically into the saved RoutineExercise on + // onSave; Cancel/discard restores the original target/settings. + + private val _powerLossDraft = MutableStateFlow(PowerLossConfigDraftState()) + val powerLossDraft: StateFlow = _powerLossDraft.asStateFlow() + + /** UI transitions for the shared `Set target` section (pure state machine). */ + fun onPowerLossDraftChange(next: PowerLossConfigDraftState) { + _powerLossDraft.value = next + } + + /** + * The exercise's power-loss protocol family. Timed and bodyweight executions + * resolve to UNSUPPORTED (dormant/inert) exactly like TUT/TUT Beast/ + * Eccentric-Only — POWER never arms from an excluded mode. + */ + private fun currentPowerLossFamily(mode: WorkoutMode): PowerLossProtocolFamily = + if (_exerciseType.value == ExerciseType.BODYWEIGHT || _setMode.value == SetMode.DURATION) { + PowerLossProtocolFamily.UNSUPPORTED + } else { + PowerLossProtocolFamily.of(mode.toProgramMode(), isJustLiftExecutionStyle = false) + } + + /** + * Runtime-settings preview for the editor's target readback facts. Unknown + * or excluded modes resolve to inert REP_TARGET — POWER never arms from an + * unknown or excluded mode (P5 propagation seam). + */ + internal fun powerLossRuntimeSettingsPreview(): com.devil.phoenixproject.presentation.manager.PowerLossRuntimeSettings { + val draft = _powerLossDraft.value + return powerLossRuntimeSettingsFor( + config = draft.committed, + mode = _selectedMode.value.toProgramMode(), + isJustLiftExecutionStyle = false, + savedNominalReps = draft.committed.savedNominalReps, + pairedSamplesValidated = PowerLossRuntimeGate.pairedSamplesValidated, + ) + } + fun initialize( exercise: RoutineExercise, unit: WeightUnit, @@ -316,6 +361,19 @@ class ExerciseConfigViewModel constructor( _defaultRackItemIds.value = exercise.defaultRackItemIds.filter { it.isNotBlank() }.distinct() _rackBehaviorOverrides.value = exercise.rackBehaviorOverrides + // Issue #1392: seed the Set-target draft from the exercise's saved config. + // Timed/bodyweight executions keep the saved POWER values but resolve to + // the inert/dormant state — POWER never arms from an excluded mode. + _powerLossDraft.value = PowerLossConfigDraftState.seededFrom( + config = exercise.powerLoss.copy( + savedNominalReps = exercise.powerLoss.savedNominalReps + ?: exercise.setReps.firstOrNull(), + ), + maxAllowedWorkingReps = (254 - exercise.warmupSets.size) + .coerceAtLeast(com.devil.phoenixproject.domain.powerloss.PowerLossConfig.MIN_MAX_WORKING_REPS), + protocolFamily = currentPowerLossFamily(_selectedMode.value), + ) + // Load PR and typed baseline for the current exercise and mode. exercise.exercise.id?.let { exerciseId -> loadPRForExercise(exerciseId, _selectedMode.value.displayName) @@ -332,6 +390,11 @@ class ExerciseConfigViewModel constructor( return } _setMode.value = mode + // Issue #1392: timed (DURATION) sets are an excluded execution type — a + // saved POWER config stays dormant instead of arming. + _powerLossDraft.value = _powerLossDraft.value.copy( + protocolFamily = currentPowerLossFamily(_selectedMode.value), + ) } fun onSelectedModeChange(mode: WorkoutMode) { @@ -339,6 +402,10 @@ class ExerciseConfigViewModel constructor( _currentExercisePR.value = null _currentMaxVolumePR.value = null refreshDropSetValidation() + // Issue #1392: program-mode switches move the capability gate (ui-spec §3). + _powerLossDraft.value = _powerLossDraft.value.copy( + protocolFamily = currentPowerLossFamily(mode), + ) // Load PR for the new mode if (::originalExercise.isInitialized) { originalExercise.exercise.id?.let { exerciseId -> @@ -1052,6 +1119,9 @@ class ExerciseConfigViewModel constructor( setWeightsPercentOfPR = expandedPercentOfPR, // Issue #517: persist explicit scaling basis (null = back-compat derivation from prTypeForScaling) scalingBasis = _scalingBasis.value, + // Issue #1392: Apply commits the Set-target draft atomically into the + // saved exercise (config load/edit/save + copy/equality round-trip). + powerLoss = _powerLossDraft.value.apply().committed, // Warm-up sets (Issue #30) warmupSets = _warmupSets.value, defaultRackItemIds = _defaultRackItemIds.value, diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/viewmodel/IntegrationsViewModel.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/viewmodel/IntegrationsViewModel.kt index cfdf13f57..5a8c8b3b7 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/viewmodel/IntegrationsViewModel.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/viewmodel/IntegrationsViewModel.kt @@ -83,6 +83,10 @@ data class IntegrationsUiState( val csvContent: String? = null, val errorMessage: String? = null, val successMessage: String? = null, + // Issue #1392 (P5, ui-spec §6): legacy-export omission disclosure + power export. + val legacyExportConfirmation: com.devil.phoenixproject.presentation.powerloss.LegacyExportConfirmationUi? = null, + val powerExportResult: com.devil.phoenixproject.data.export.PowerHistoryExportResult? = null, + val isPowerExporting: Boolean = false, ) class IntegrationsViewModel( @@ -98,6 +102,8 @@ class IntegrationsViewModel( private val healthBodyWeightSyncManager: HealthBodyWeightSyncManager, private val userProfileRepository: UserProfileRepository, private val portalTokenStorage: PortalTokenStorage, + // Issue #1392 (P5): versioned power-history export behind the `Export power data` entry. + private val powerHistoryExporter: com.devil.phoenixproject.data.export.PowerHistoryExporter, ) : ViewModel() { /** Resolved active profile ID, reactive to profile switches. */ @@ -244,6 +250,82 @@ class IntegrationsViewModel( _uiState.value = _uiState.value.copy(csvContent = null) } + // ===== Issue #1392 — export entry + legacy-export omission disclosure ====== + + private val _exportFlow = + MutableStateFlow(com.devil.phoenixproject.presentation.powerloss.PowerLossExportFlowState.INITIAL) + + /** + * A legacy (non-power) export: the omission disclosure ALWAYS surfaces first + * — exporting via the legacy path omits power data, and the app says so + * explicitly before anything runs (ui-spec §6). + */ + fun requestLegacyExport() { + val next = _exportFlow.value.reduce( + com.devil.phoenixproject.presentation.powerloss.PowerLossExportIntent.RequestLegacyExport, + ) + _exportFlow.value = next + _uiState.value = _uiState.value.copy( + legacyExportConfirmation = if (next.legacyConfirmationVisible) { + com.devil.phoenixproject.presentation.powerloss.legacyExportConfirmation() + } else { + null + }, + ) + } + + /** `Choose power-data export` — leave the legacy path for the versioned power export. */ + fun choosePowerDataExport() { + _exportFlow.value = _exportFlow.value.reduce( + com.devil.phoenixproject.presentation.powerloss.PowerLossExportIntent.ChoosePowerDataExport, + ) + _uiState.value = _uiState.value.copy(legacyExportConfirmation = null) + exportPowerData() + } + + /** `Export without power details` — the disclosed legacy export proceeds. */ + fun exportWithoutPowerDetails(weightUnit: WeightUnit) { + _exportFlow.value = _exportFlow.value.reduce( + com.devil.phoenixproject.presentation.powerloss.PowerLossExportIntent.ExportWithoutPowerDetails, + ) + _uiState.value = _uiState.value.copy(legacyExportConfirmation = null) + exportCsv(weightUnit) + } + + /** Disclosure dismissed (outside tap / system Back): no export runs. */ + fun dismissLegacyExportConfirmation() { + _exportFlow.value = _exportFlow.value.reduce( + com.devil.phoenixproject.presentation.powerloss.PowerLossExportIntent.DismissLegacyConfirmation, + ) + _uiState.value = _uiState.value.copy(legacyExportConfirmation = null) + } + + /** + * `Export power data` — run the versioned power-history export (P4 codec) + * for the active profile. The caller owns share/save UX over [IntegrationsUiState.powerExportResult]. + */ + fun exportPowerData() { + if (_uiState.value.isPowerExporting) return + viewModelScope.launch { + _uiState.value = _uiState.value.copy(isPowerExporting = true, errorMessage = null) + try { + val result = powerHistoryExporter.exportPowerData(activeProfileId.value) + _uiState.value = _uiState.value.copy(powerExportResult = result) + } catch (error: Throwable) { + _uiState.value = _uiState.value.copy( + errorMessage = error.message ?: "Power-data export failed", + ) + } finally { + _uiState.value = _uiState.value.copy(isPowerExporting = false) + } + } + } + + /** Clear the produced power-history document (after save/share is dismissed). */ + fun clearPowerExportContent() { + _uiState.value = _uiState.value.copy(powerExportResult = null) + } + // ─── CSV Import ─────────────────────────────────────────────────────────── /** diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/viewmodel/MainViewModel.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/viewmodel/MainViewModel.kt index 47842ee4a..641d2cc5f 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/viewmodel/MainViewModel.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/viewmodel/MainViewModel.kt @@ -71,6 +71,8 @@ import com.devil.phoenixproject.domain.usecase.ResolveRoutineWeightsUseCase import com.devil.phoenixproject.presentation.components.exercisepicker.CompletedExerciseIdsState import com.devil.phoenixproject.presentation.components.exercisepicker.completedExerciseIdsFromHistory import com.devil.phoenixproject.presentation.components.exercisepicker.recentJustLiftExerciseIdsFromHistory +import com.devil.phoenixproject.presentation.powerloss.PowerLossRuntimeGate +import com.devil.phoenixproject.presentation.powerloss.powerLossRuntimeSettingsFor import com.devil.phoenixproject.presentation.manager.WorkoutSaveFailureOffer import com.devil.phoenixproject.presentation.manager.BleConnectionManager import com.devil.phoenixproject.presentation.manager.DefaultWorkoutSessionManager @@ -760,6 +762,11 @@ class MainViewModel( // ===== Workout State Delegation ===== val workoutState: StateFlow get() = workoutSessionManager.coordinator.workoutState + + /** Issue #1392: live power-loss HUD facts for the active-workout HUD panel (ui-spec §4). */ + val powerLossHud: StateFlow + get() = workoutSessionManager.coordinator.powerLossHud + val machineTeardownState: StateFlow get() = workoutSessionManager.machineTeardownState val isWorkoutActive: Boolean get() = workoutSessionManager.coordinator.isWorkoutActive @@ -1000,7 +1007,30 @@ class MainViewModel( // ===== Workout Lifecycle Delegation ===== - fun updateWorkoutParameters(params: WorkoutParameters) = workoutSessionManager.updateWorkoutParameters(params) + /** + * Issue #1392 (P5 propagation, integration-model §4): the active parameter + * boundary copies the per-exercise power-loss target config into the runtime + * seam (`coordinator.powerLossRuntimeSettings`) before the parameters are + * applied. Config intent is per-profile and never leaks across profiles; + * mid-set policy mutation is rejected by the engine's parameter guard. + */ + fun updateWorkoutParameters(params: WorkoutParameters) { + workoutSessionManager.updatePowerLossSettings( + powerLossRuntimeSettingsFor( + config = params.powerLoss, + mode = params.programMode, + isJustLiftExecutionStyle = params.isJustLift, + savedNominalReps = params.powerLoss.savedNominalReps + ?: params.reps.takeIf { it >= 1 }, + pairedSamplesValidated = PowerLossRuntimeGate.pairedSamplesValidated, + ), + ) + workoutSessionManager.updateWorkoutParameters(params) + } + + /** Live power-loss runtime settings (issue #1392); default is inert (POWER off). */ + internal val powerLossRuntimeSettings: kotlinx.coroutines.flow.StateFlow = + workoutSessionManager.powerLossRuntimeSettings fun updateActiveRackSelection(itemIds: List) = workoutSessionManager.updateActiveRackSelection(itemIds) fun updateActiveRackBehaviorOverrides(overrides: Map) = workoutSessionManager.updateActiveRackBehaviorOverrides(overrides) fun clearActiveRackSelection() = workoutSessionManager.clearActiveRackSelection() diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/BackupModels.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/BackupModels.kt index 9de3ba4b3..ce543194e 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/BackupModels.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/BackupModels.kt @@ -166,6 +166,108 @@ data class PolarEcgSegmentBackup( val samplesUvCsv: String, ) +// ===================================================================================== +// Issue #1392 (packet P4 remainder) — versioned optional power-loss sections (backup v7). +// +// Three self-versioned sections ride every backup path (full, streaming, +// session-scoped, routine-scoped). PRIVACY FILTERS: the set companion rows and +// the per-exercise config rows are aggregate/summary facts and are retained even +// when the raw-telemetry opt-in is OFF; the per-rep observation rows are raw +// per-attempt telemetry and only ride an opted-in export. RESTORE SEMANTICS: +// restore is additive (INSERT-if-absent, local wins), so an ABSENT section — an +// old backup — never wipes local companion/config data; a present section can +// only add. Absent fields decode as null, never as fabricated zeros. Rows with an +// unknown [POWER_LOSS_BACKUP_FORMAT_VERSION] or unknown enum are skipped with a +// warning by the strict readers — never crash, never coerce into active behavior, +// never arm POWER from an unknown enum. Nothing here carries sync bookkeeping: +// restored rows are never marked synced or backed up. +// ===================================================================================== + +/** Current row format version of the power-loss backup sections. */ +const val POWER_LOSS_BACKUP_FORMAT_VERSION: Int = 1 + +/** Strict row gate: unknown section row versions are skipped, never coerced. */ +internal fun isSupportedPowerLossBackupFormatVersion(formatVersion: Int): Boolean = + formatVersion == POWER_LOSS_BACKUP_FORMAT_VERSION + +/** + * Backup representation of one `PowerLossSetCompanion` row: the frozen + * per-exercise [com.devil.phoenixproject.domain.powerloss.PowerLossConfig] plus + * reference/trigger/winner facts. Nullable metrics stay null — never zero. + */ +@Serializable +data class PowerLossSetCompanionBackup( + val formatVersion: Int = POWER_LOSS_BACKUP_FORMAT_VERSION, + val sessionId: String, + val setId: String, + val metricVersion: Int = 1, + val targetMode: String, + val thresholdPercent: Int, + val maxWorkingReps: Int? = null, + val requireTwoConsecutive: Boolean = false, + val savedNominalReps: Int? = null, + val activeCables: String, + val activeCableProvenance: String, + val referenceWorkingOrdinal: Int? = null, + val referenceMcpWatts: Float? = null, + val referenceRomAMm: Float? = null, + val referenceRomBMm: Float? = null, + val triggerWorkingOrdinal: Int? = null, + val winnerReason: String? = null, + val shortRomObserved: Boolean = false, + val powerLossObserved: Boolean = false, + val lossPercentAtDecision: Float? = null, + val createdAt: Long, +) + +/** + * Backup representation of one `PowerLossAttemptCompanion` row (the observation + * companion): per-rep attempt identity and nullable metrics. Attempt-only rows + * (no legacy RepMetric row) are first-class. Raw per-attempt telemetry — only + * exported when the raw-telemetry opt-in is ON. + */ +@Serializable +data class PowerLossObservationCompanionBackup( + val formatVersion: Int = POWER_LOSS_BACKUP_FORMAT_VERSION, + val sessionId: String, + val setId: String, + val workingConcentricOrdinal: Int, + val legacyRepIndex: Int? = null, + val completed: Boolean = false, + val mcpWatts: Float? = null, + val eccentricPowerWatts: Float? = null, + val concentricDurationMs: Long? = null, + val eccentricDurationMs: Long? = null, + val lossPercentAtDecision: Float? = null, + val referenceWorkingOrdinal: Int? = null, + val romAMm: Float? = null, + val romBMm: Float? = null, + val romAPercentOfReference: Float? = null, + val romBPercentOfReference: Float? = null, + val romTrustworthy: Boolean = false, + val quality: String = "", + val shortRom: Boolean = false, + val powerLossQualified: Boolean = false, +) + +/** + * Backup representation of one `PowerLossExerciseConfig` row: the per-exercise + * power-loss target config. Absent fields stay null (savedNominalReps) — an old + * backup defaults to REP with nulls, never zeros. An unknown targetMode is + * restored verbatim (raw values stay inspectable) but read back inert REP_TARGET. + */ +@Serializable +data class PowerLossExerciseConfigBackup( + val formatVersion: Int = POWER_LOSS_BACKUP_FORMAT_VERSION, + val routineExerciseId: String, + val targetMode: String, + val thresholdPercent: Int, + val maxWorkingReps: Int? = null, + val requireTwoConsecutive: Boolean = false, + val savedNominalReps: Int? = null, + val updatedAt: Long, +) + /** * Backup representation of Routine */ @@ -846,6 +948,14 @@ data class BackupContent( // Added migration 58: Polar H10 multi-tier continuous timeline and ECG traces val polarBeatSamples: List = emptyList(), val polarEcgSegments: List = emptyList(), + // Issue #1392 (packet P4 remainder): versioned optional power-loss sections. + // Old backups omit them entirely — an absent section never wipes local data + // (restore is additive). Observation rows are raw per-attempt telemetry and + // only ride raw-telemetry-opted-in exports; set companions and per-exercise + // configs are aggregate/summary facts and always ride. + val powerLossSetCompanions: List = emptyList(), + val powerLossObservationCompanions: List = emptyList(), + val powerLossExerciseConfigs: List = emptyList(), ) /** @@ -915,6 +1025,13 @@ data class ImportResult( val polarBeatSamplesSkipped: Int = 0, val polarEcgSegmentsImported: Int = 0, val polarEcgSegmentsSkipped: Int = 0, + // Issue #1392: power-loss companion/config sections (additive restore). + val powerLossSetCompanionsImported: Int = 0, + val powerLossSetCompanionsSkipped: Int = 0, + val powerLossObservationCompanionsImported: Int = 0, + val powerLossObservationCompanionsSkipped: Int = 0, + val powerLossExerciseConfigsImported: Int = 0, + val powerLossExerciseConfigsSkipped: Int = 0, val repairedReferences: Int = 0, /** Rows of a profile the user permanently deleted (PR 20), left out on purpose. */ val deletedProfileRowsSkipped: Int = 0, @@ -944,7 +1061,9 @@ data class ImportResult( pendingProfileRecoveriesImported + ownershipTransfersImported + appliedOwnershipEventsImported + localOwnershipClaimsImported + cycleConflictDraftsImported + cycleSyncStatesImported + - polarBeatSamplesImported + polarEcgSegmentsImported + polarBeatSamplesImported + polarEcgSegmentsImported + + powerLossSetCompanionsImported + powerLossObservationCompanionsImported + + powerLossExerciseConfigsImported val totalSkipped: Int get() = sessionsSkipped + metricsSkipped + routinesSkipped + supersetsSkipped + personalRecordsSkipped + @@ -957,7 +1076,9 @@ data class ImportResult( workoutDeletionsSkipped + pendingProfileRecoveriesSkipped + ownershipTransfersSkipped + appliedOwnershipEventsSkipped + cycleConflictDraftsSkipped + localOwnershipClaimsSkipped + cycleSyncStatesSkipped + - polarBeatSamplesSkipped + polarEcgSegmentsSkipped + deletedProfileRowsSkipped + polarBeatSamplesSkipped + polarEcgSegmentsSkipped + deletedProfileRowsSkipped + + powerLossSetCompanionsSkipped + powerLossObservationCompanionsSkipped + + powerLossExerciseConfigsSkipped } // ===================================================================================== @@ -1019,6 +1140,9 @@ internal val BACKUP_CONTENT_ALLOWED_FIELDS: Set = setOf( "cycleSyncStates", "polarBeatSamples", "polarEcgSegments", + "powerLossSetCompanions", + "powerLossObservationCompanions", + "powerLossExerciseConfigs", ) /** diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/BlePacketFactory.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/BlePacketFactory.kt index bcbac8982..1ee945a0e 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/BlePacketFactory.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/BlePacketFactory.kt @@ -58,8 +58,13 @@ object BlePacketFactory { // Required, with no default: a builder that guesses the ceiling reopens exactly the // bypass KD-9 closes. Callers pass the CONNECTED model's ceiling. maxWeightPerCableKg: Float, + // Issue #1392 (SD4): the ONE frozen execution target plan. In POWER mode the + // total-rep byte encodes the max-reps backstop (cap + warmup) so the machine + // counter and the app agree on when the set is finite. Null/REP keeps the + // historical encoding byte-for-byte. + targetPlan: com.devil.phoenixproject.domain.powerloss.ExecutionTargetPlan? = null, ): ByteArray { - WorkoutCommandValidator.validateProgramParams(params, maxWeightPerCableKg).getOrThrow() + WorkoutCommandValidator.validateProgramParams(params, maxWeightPerCableKg, targetPlan).getOrThrow() val profileMode = if (params.isEchoMode) { ProgramMode.OldSchool // Echo profile unused; Echo builds the 0x4E packet separately @@ -82,9 +87,18 @@ object BlePacketFactory { // F-070: the sentinel decision reads WorkoutParameters.usesUnlimitedRepTarget, // the same predicate the execution lease and the engine's warm-up auto-end // fallback use, so the packet and the app can never disagree about a set. + // Issue #1392 (SD4): a finite POWER set writes the frozen effective target + // (the max-reps backstop) plus warmup — never the saved nominal. Genuine + // Just Lift / AMRAP hardware-unlimited identity keeps its sentinel and is + // capped in-app. + val powerCap = targetPlan + ?.takeIf { it.targetMode == com.devil.phoenixproject.domain.powerloss.TargetMode.POWER } + ?.maxWorkingReps frame[0x04] = if (params.usesUnlimitedRepTarget) { 0xFF.toByte() + } else if (powerCap != null) { + (powerCap + params.warmupReps).coerceAtMost(0xFE).toByte() } else { (params.reps + params.warmupReps).coerceAtMost(0xFE).toByte() } @@ -232,6 +246,10 @@ object BlePacketFactory { isJustLift: Boolean = false, isAMRAP: Boolean = false, eccentricPct: Int = 100, + // Issue #1392 (SD4): the ONE frozen execution target plan. In POWER mode the + // working-target byte encodes the max-reps backstop so the machine counter and + // the app agree on when the set is finite. Null/REP keeps the historical bytes. + targetPlan: com.devil.phoenixproject.domain.powerloss.ExecutionTargetPlan? = null, ): ByteArray { // F-010: validate the value the CALLER asked for. Clamping first made the // eccentricPct bound unreachable, so an out-of-range request was silently @@ -243,6 +261,7 @@ object BlePacketFactory { isJustLift = isJustLift, isAMRAP = isAMRAP, eccentricPct = eccentricPct, + targetPlan = targetPlan, ).getOrThrow() val frame = ByteArray(32) @@ -252,8 +271,18 @@ object BlePacketFactory { frame[0x04] = warmupReps.coerceAtMost(0xFE).toByte() // 0xFF is the unlimited/Just Lift/AMRAP sentinel; clamp a finite target to - // 254 so it can never collide with it (audit F069). - frame[0x05] = if (isJustLift || isAMRAP) 0xFF.toByte() else targetReps.coerceAtMost(0xFE).toByte() + // 254 so it can never collide with it (audit F069). Issue #1392 (SD4): a + // finite POWER set writes the frozen effective target (the max-reps + // backstop) — never the saved nominal; unlimited identities keep the + // sentinel and are capped in-app. + val powerCap = targetPlan + ?.takeIf { it.targetMode == com.devil.phoenixproject.domain.powerloss.TargetMode.POWER } + ?.maxWorkingReps + frame[0x05] = when { + isJustLift || isAMRAP -> 0xFF.toByte() + powerCap != null -> powerCap.coerceAtMost(0xFE).toByte() + else -> targetReps.coerceAtMost(0xFE).toByte() + } putShortLE(frame, 0x06, 0) diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/DataBackupManager.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/DataBackupManager.kt index dcadcf116..92ec5ec3e 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/DataBackupManager.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/DataBackupManager.kt @@ -7,6 +7,8 @@ import com.devil.phoenixproject.data.local.LegacyCatalogueTranslator import com.devil.phoenixproject.data.local.LegacyLabelSanitizer import com.devil.phoenixproject.data.preferences.ProfilePreferencesValidator import com.devil.phoenixproject.data.repository.ProfilePreferencesRepository +import com.devil.phoenixproject.data.repository.PowerLossCompanionStore +import com.devil.phoenixproject.data.repository.PowerLossConfigStore import com.devil.phoenixproject.data.repository.RoutineIdentityResolver import com.devil.phoenixproject.data.repository.UserProfileRepository import com.devil.phoenixproject.data.sync.PortalSyncAdapter @@ -40,6 +42,7 @@ import com.devil.phoenixproject.database.TrainingCycle import com.devil.phoenixproject.database.UserProfile import com.devil.phoenixproject.database.PolarBeatSample import com.devil.phoenixproject.database.PolarEcgSegment +import com.devil.phoenixproject.domain.powerloss.TargetMode import com.devil.phoenixproject.database.PhoenixDatabase import com.devil.phoenixproject.database.WorkoutSession import com.devil.phoenixproject.database.WorkoutDeletion @@ -311,6 +314,9 @@ abstract class BaseDataBackupManager( "workoutSessions", "metricSamples", "completedSets", + "powerLossSetCompanions", + "powerLossObservationCompanions", + "powerLossExerciseConfigs", "polarBeatSamples", "polarEcgSegments", "personalRecords", @@ -345,6 +351,13 @@ abstract class BaseDataBackupManager( "workoutSessions", "metricSamples", "completedSets", + // Issue #1392: power-loss companions after their session parents and + // completed sets (set_id ties to completed sets); configs after + // routineExercises (FK parent). Restore is additive (insert-if-absent), + // so absent sections never wipe local companion/config data. + "powerLossSetCompanions", + "powerLossObservationCompanions", + "powerLossExerciseConfigs", "polarBeatSamples", "polarEcgSegments", "personalRecords", @@ -514,6 +527,25 @@ abstract class BaseDataBackupManager( // Migration 27 added RoutineGroup. Preserve empty groups as legitimate user state. val routineGroups = queries.selectAllRoutineGroupsSync().executeAsList() + // Issue #1392: power-loss companion/config sections. Companion reads are + // per-session (OOM-safe, same as metrics). Privacy filter: set companions + // and per-exercise configs are aggregate/summary facts and always ride; + // per-rep observation rows are raw telemetry and only ride when opted in. + val powerLossSetCompanions = mutableListOf() + val powerLossObservationCompanions = mutableListOf() + for (session in sessions) { + powerLossSetCompanions += queries.selectPowerLossSetCompanionsBySession(session.id) + .executeAsList() + .map { mapPowerLossSetCompanionToBackup(it) } + if (includeRawTelemetryInBackups) { + powerLossObservationCompanions += queries.selectPowerLossAttemptCompanionsBySession(session.id) + .executeAsList() + .map { mapPowerLossObservationCompanionToBackup(it) } + } + } + val powerLossExerciseConfigs = queries.selectAllPowerLossExerciseConfigs().executeAsList() + .map { mapPowerLossExerciseConfigToBackup(it) } + val nowMs = KmpUtils.currentTimeMillis() BackupData( version = CURRENT_BACKUP_VERSION, @@ -564,6 +596,9 @@ abstract class BaseDataBackupManager( cycleConflictDrafts = cycleConflictDrafts.map(::mapCycleConflictDraftToBackup), polarBeatSamples = polarBeatSamples.map(::mapPolarBeatSampleToBackup), polarEcgSegments = polarEcgSegments.map(::mapPolarEcgSegmentToBackup), + powerLossSetCompanions = powerLossSetCompanions, + powerLossObservationCompanions = powerLossObservationCompanions, + powerLossExerciseConfigs = powerLossExerciseConfigs, ), ) } @@ -814,6 +849,9 @@ abstract class BaseDataBackupManager( "workoutSessions" -> json.decodeFromString(raw) "metricSamples" -> json.decodeFromString(raw) "completedSets" -> json.decodeFromString(raw) + "powerLossSetCompanions" -> json.decodeFromString(raw) + "powerLossObservationCompanions" -> json.decodeFromString(raw) + "powerLossExerciseConfigs" -> json.decodeFromString(raw) "polarBeatSamples" -> json.decodeFromString(raw) "polarEcgSegments" -> json.decodeFromString(raw) "personalRecords" -> json.decodeFromString(raw) @@ -1003,6 +1041,12 @@ abstract class BaseDataBackupManager( var polarBeatSamplesSkipped = 0 var polarEcgSegmentsImported = 0 var polarEcgSegmentsSkipped = 0 + var powerLossSetCompanionsImported = 0 + var powerLossSetCompanionsSkipped = 0 + var powerLossObservationCompanionsImported = 0 + var powerLossObservationCompanionsSkipped = 0 + var powerLossExerciseConfigsImported = 0 + var powerLossExerciseConfigsSkipped = 0 var progressionEventsImported = 0 var progressionEventsSkipped = 0 var earnedBadgesImported = 0 @@ -3047,6 +3091,228 @@ abstract class BaseDataBackupManager( } } + // --- powerLossSetCompanions (Issue #1392) --- + // Additive restore (INSERT-if-absent, local wins): an absent + // or partial section never wipes local companion data and + // retries are idempotent. Strict readers skip rows with an + // unknown row version or unknown target enum with a warning — + // never crash, never coerce, never arm POWER from an unknown + // enum. Local evidence only: restore never marks these rows + // synced or backed up (no wire semantics). + "powerLossSetCompanions" -> { + committedTransaction { + nav.beginArray() + while (nav.hasNextInArray()) { + val rawJson = nav.nextValueAsString() + val row = tryImport("powerLossSetCompanion-parse", null) { + json.decodeFromString(rawJson) + } ?: continue + if (!isSupportedPowerLossBackupFormatVersion(row.formatVersion)) { + powerLossSetCompanionsSkipped++ + Logger.w { + "Backup restore skipping power-loss set companion ${row.sessionId}/${row.setId}: " + + "unsupported row version ${row.formatVersion}" + } + continue + } + if (TargetMode.fromPersisted(row.targetMode) == null || + PowerLossCompanionStore.decodeActiveCables(row.activeCables) == null + ) { + powerLossSetCompanionsSkipped++ + Logger.w { + "Backup restore skipping power-loss set companion ${row.sessionId}/${row.setId}: " + + "unknown target enum or cable mask (never armed from unknown values)" + } + continue + } + if (!parentAvailable("session", row.sessionId) || + queries.selectSessionById(row.sessionId).executeAsOneOrNull() == null + ) { + entitiesWithErrors++ + Logger.w { + "Backup restore missing required session ${row.sessionId} for power-loss set companion ${row.setId}" + } + continue + } + val existing = queries.selectPowerLossSetCompanionsBySession(row.sessionId) + .executeAsList() + .firstOrNull { it.set_id == row.setId } + if (existing != null) { + if (mapPowerLossSetCompanionToBackup(existing) == row) { + powerLossSetCompanionsSkipped++ + } else { + entitiesWithErrors++ + Logger.w { + "Backup restore conflict power-loss set companion ${row.sessionId}/${row.setId}; local row preserved" + } + } + continue + } + tryImport("powerLossSetCompanion", row.setId) { + queries.insertPowerLossSetCompanionIfAbsent( + session_id = row.sessionId, + set_id = row.setId, + metric_version = row.metricVersion.toLong(), + target_mode = row.targetMode, + threshold_percent = row.thresholdPercent.toLong(), + max_working_reps = row.maxWorkingReps?.toLong(), + require_two_consecutive = if (row.requireTwoConsecutive) 1L else 0L, + saved_nominal_reps = row.savedNominalReps?.toLong(), + active_cables = row.activeCables, + active_cable_provenance = row.activeCableProvenance, + reference_working_ordinal = row.referenceWorkingOrdinal?.toLong(), + reference_mcp_watts = row.referenceMcpWatts?.toDouble(), + reference_rom_a_mm = row.referenceRomAMm?.toDouble(), + reference_rom_b_mm = row.referenceRomBMm?.toDouble(), + trigger_working_ordinal = row.triggerWorkingOrdinal?.toLong(), + winner_reason = row.winnerReason, + short_rom_observed = if (row.shortRomObserved) 1L else 0L, + power_loss_observed = if (row.powerLossObserved) 1L else 0L, + loss_percent_at_decision = row.lossPercentAtDecision?.toDouble(), + created_at = row.createdAt, + ) + }?.let { powerLossSetCompanionsImported++ } + } + nav.endArray() + } + } + + // --- powerLossObservationCompanions (Issue #1392) --- + // The per-rep observation companions (attempt-only rows are + // first-class). Same additive/strict contract as the set + // companions above; nullable metrics stay null, never zero. + "powerLossObservationCompanions" -> { + committedTransaction { + nav.beginArray() + while (nav.hasNextInArray()) { + val rawJson = nav.nextValueAsString() + val row = tryImport("powerLossObservationCompanion-parse", null) { + json.decodeFromString(rawJson) + } ?: continue + if (!isSupportedPowerLossBackupFormatVersion(row.formatVersion)) { + powerLossObservationCompanionsSkipped++ + Logger.w { + "Backup restore skipping power-loss observation ${row.sessionId}/${row.workingConcentricOrdinal}: " + + "unsupported row version ${row.formatVersion}" + } + continue + } + if (!parentAvailable("session", row.sessionId) || + queries.selectSessionById(row.sessionId).executeAsOneOrNull() == null + ) { + entitiesWithErrors++ + Logger.w { + "Backup restore missing required session ${row.sessionId} for power-loss observation ${row.workingConcentricOrdinal}" + } + continue + } + val existing = queries.selectPowerLossAttemptCompanionsBySession(row.sessionId) + .executeAsList() + .firstOrNull { it.working_concentric_ordinal == row.workingConcentricOrdinal.toLong() } + if (existing != null) { + if (mapPowerLossObservationCompanionToBackup(existing) == row) { + powerLossObservationCompanionsSkipped++ + } else { + entitiesWithErrors++ + Logger.w { + "Backup restore conflict power-loss observation ${row.sessionId}/${row.workingConcentricOrdinal}; local row preserved" + } + } + continue + } + tryImport("powerLossObservationCompanion", "${row.sessionId}/${row.workingConcentricOrdinal}") { + queries.insertPowerLossAttemptCompanionIfAbsent( + session_id = row.sessionId, + set_id = row.setId, + working_concentric_ordinal = row.workingConcentricOrdinal.toLong(), + legacy_rep_index = row.legacyRepIndex?.toLong(), + completed = if (row.completed) 1L else 0L, + mcp_watts = row.mcpWatts?.toDouble(), + eccentric_power_watts = row.eccentricPowerWatts?.toDouble(), + concentric_duration_ms = row.concentricDurationMs, + eccentric_duration_ms = row.eccentricDurationMs, + loss_percent_at_decision = row.lossPercentAtDecision?.toDouble(), + reference_working_ordinal = row.referenceWorkingOrdinal?.toLong(), + rom_a_mm = row.romAMm?.toDouble(), + rom_b_mm = row.romBMm?.toDouble(), + rom_a_percent_of_reference = row.romAPercentOfReference?.toDouble(), + rom_b_percent_of_reference = row.romBPercentOfReference?.toDouble(), + rom_trustworthy = if (row.romTrustworthy) 1L else 0L, + quality = row.quality, + short_rom = if (row.shortRom) 1L else 0L, + power_loss_qualified = if (row.powerLossQualified) 1L else 0L, + ) + }?.let { powerLossObservationCompanionsImported++ } + } + nav.endArray() + } + } + + // --- powerLossExerciseConfigs (Issue #1392) --- + // The per-exercise power-loss target config. Absent rows and + // absent fields mean inert REP defaults with nulls — never + // fabricated zeros — and a present row never replaces local + // config (INSERT-if-absent). An unknown target enum is + // skipped with a warning: import never silently arms POWER. + "powerLossExerciseConfigs" -> { + committedTransaction { + nav.beginArray() + while (nav.hasNextInArray()) { + val rawJson = nav.nextValueAsString() + val row = tryImport("powerLossExerciseConfig-parse", null) { + json.decodeFromString(rawJson) + } ?: continue + if (!isSupportedPowerLossBackupFormatVersion(row.formatVersion) || + TargetMode.fromPersisted(row.targetMode) == null + ) { + powerLossExerciseConfigsSkipped++ + Logger.w { + "Backup restore skipping power-loss config ${row.routineExerciseId}: " + + "unsupported row version or unknown target enum (never armed from unknown values)" + } + continue + } + if (queries.selectRoutineExerciseById(row.routineExerciseId).executeAsOneOrNull() == null) { + powerLossExerciseConfigsSkipped++ + Logger.w { + "Backup restore skipping power-loss config ${row.routineExerciseId}: routine exercise row absent" + } + continue + } + val existingConfig = queries + .selectPowerLossExerciseConfigsByRoutineExerciseIds(listOf(row.routineExerciseId)) + .executeAsList() + .firstOrNull { it.routine_exercise_id == row.routineExerciseId } + if (existingConfig != null) { + // Local config wins; a restore never replaces or wipes it. + if (mapPowerLossExerciseConfigToBackup(existingConfig) == row) { + powerLossExerciseConfigsSkipped++ + } else { + powerLossExerciseConfigsSkipped++ + Logger.w { + "Backup restore keeping local power-loss config ${row.routineExerciseId}; backup row differs" + } + } + continue + } + tryImport("powerLossExerciseConfig", row.routineExerciseId) { + PowerLossConfigStore.restoreIfAbsent( + queries = queries, + routineExerciseId = row.routineExerciseId, + targetMode = row.targetMode, + thresholdPercent = row.thresholdPercent, + maxWorkingReps = row.maxWorkingReps, + requireTwoConsecutive = row.requireTwoConsecutive, + savedNominalReps = row.savedNominalReps, + formatVersion = row.formatVersion, + nowMs = KmpUtils.currentTimeMillis(), + ) + }?.let { powerLossExerciseConfigsImported++ } + } + nav.endArray() + } + } + // --- unknown fields: skip for forward compatibility --- else -> { Logger.d { "Streaming import: skipping unknown data field '$fieldName'" } @@ -3158,6 +3424,12 @@ abstract class BaseDataBackupManager( polarBeatSamplesSkipped = polarBeatSamplesSkipped, polarEcgSegmentsImported = polarEcgSegmentsImported, polarEcgSegmentsSkipped = polarEcgSegmentsSkipped, + powerLossSetCompanionsImported = powerLossSetCompanionsImported, + powerLossSetCompanionsSkipped = powerLossSetCompanionsSkipped, + powerLossObservationCompanionsImported = powerLossObservationCompanionsImported, + powerLossObservationCompanionsSkipped = powerLossObservationCompanionsSkipped, + powerLossExerciseConfigsImported = powerLossExerciseConfigsImported, + powerLossExerciseConfigsSkipped = powerLossExerciseConfigsSkipped, repairedReferences = repairedReferences, entitiesWithErrors = entitiesWithErrors, ) @@ -3362,6 +3634,45 @@ abstract class BaseDataBackupManager( }) writer.write(",") + // Issue #1392: power-loss companion/config sections (same privacy filter as + // the full export: summary facts always ride; per-rep observation rows are + // raw telemetry and only ride opted-in exports). + writeJsonArray( + writer, + "powerLossSetCompanions", + sessions.flatMap { session -> + queries.selectPowerLossSetCompanionsBySession(session.id).executeAsList() + }.map { + json.encodeToString(PowerLossSetCompanionBackup.serializer(), mapPowerLossSetCompanionToBackup(it)) + }, + ) + writer.write(",") + writeJsonArray( + writer, + "powerLossObservationCompanions", + if (includeRawTelemetryInBackups) { + sessions.flatMap { session -> + queries.selectPowerLossAttemptCompanionsBySession(session.id).executeAsList() + }.map { + json.encodeToString( + PowerLossObservationCompanionBackup.serializer(), + mapPowerLossObservationCompanionToBackup(it), + ) + } + } else { + emptyList() + }, + ) + writer.write(",") + writeJsonArray( + writer, + "powerLossExerciseConfigs", + queries.selectAllPowerLossExerciseConfigs().executeAsList().map { + json.encodeToString(PowerLossExerciseConfigBackup.serializer(), mapPowerLossExerciseConfigToBackup(it)) + }, + ) + writer.write(",") + writer.write("\"polarBeatSamples\":[") var firstBeat = true if (includeRawTelemetryInBackups) { @@ -3746,6 +4057,80 @@ abstract class BaseDataBackupManager( samplesUvCsv = segment.samplesUvCsv, ) + // -- Issue #1392: power-loss companion/config mappers (DB rows → Backup rows) -- + // Nullable metrics map Double?/Long? to Float?/Int? exactly: a missing value + // stays null through export and restore, never a fabricated zero. + + /** Per-exercise power-loss configs belonging to [routineExerciseIds] (scoped paths). */ + private fun powerLossExerciseConfigsFor(routineExerciseIds: Set): List = + queries.selectPowerLossExerciseConfigsByRoutineExerciseIds(routineExerciseIds.toList()) + .executeAsList() + .map { mapPowerLossExerciseConfigToBackup(it) } + + private fun mapPowerLossSetCompanionToBackup( + row: com.devil.phoenixproject.database.PowerLossSetCompanion, + ): PowerLossSetCompanionBackup = PowerLossSetCompanionBackup( + formatVersion = POWER_LOSS_BACKUP_FORMAT_VERSION, + sessionId = row.session_id, + setId = row.set_id, + metricVersion = row.metric_version.toInt(), + targetMode = row.target_mode, + thresholdPercent = row.threshold_percent.toInt(), + maxWorkingReps = row.max_working_reps?.toInt(), + requireTwoConsecutive = row.require_two_consecutive != 0L, + savedNominalReps = row.saved_nominal_reps?.toInt(), + activeCables = row.active_cables, + activeCableProvenance = row.active_cable_provenance, + referenceWorkingOrdinal = row.reference_working_ordinal?.toInt(), + referenceMcpWatts = row.reference_mcp_watts?.toFloat(), + referenceRomAMm = row.reference_rom_a_mm?.toFloat(), + referenceRomBMm = row.reference_rom_b_mm?.toFloat(), + triggerWorkingOrdinal = row.trigger_working_ordinal?.toInt(), + winnerReason = row.winner_reason, + shortRomObserved = row.short_rom_observed != 0L, + powerLossObserved = row.power_loss_observed != 0L, + lossPercentAtDecision = row.loss_percent_at_decision?.toFloat(), + createdAt = row.created_at, + ) + + private fun mapPowerLossObservationCompanionToBackup( + row: com.devil.phoenixproject.database.PowerLossAttemptCompanion, + ): PowerLossObservationCompanionBackup = PowerLossObservationCompanionBackup( + formatVersion = POWER_LOSS_BACKUP_FORMAT_VERSION, + sessionId = row.session_id, + setId = row.set_id, + workingConcentricOrdinal = row.working_concentric_ordinal.toInt(), + legacyRepIndex = row.legacy_rep_index?.toInt(), + completed = row.completed != 0L, + mcpWatts = row.mcp_watts?.toFloat(), + eccentricPowerWatts = row.eccentric_power_watts?.toFloat(), + concentricDurationMs = row.concentric_duration_ms, + eccentricDurationMs = row.eccentric_duration_ms, + lossPercentAtDecision = row.loss_percent_at_decision?.toFloat(), + referenceWorkingOrdinal = row.reference_working_ordinal?.toInt(), + romAMm = row.rom_a_mm?.toFloat(), + romBMm = row.rom_b_mm?.toFloat(), + romAPercentOfReference = row.rom_a_percent_of_reference?.toFloat(), + romBPercentOfReference = row.rom_b_percent_of_reference?.toFloat(), + romTrustworthy = row.rom_trustworthy != 0L, + quality = row.quality, + shortRom = row.short_rom != 0L, + powerLossQualified = row.power_loss_qualified != 0L, + ) + + private fun mapPowerLossExerciseConfigToBackup( + row: com.devil.phoenixproject.database.PowerLossExerciseConfig, + ): PowerLossExerciseConfigBackup = PowerLossExerciseConfigBackup( + formatVersion = row.format_version.toInt(), + routineExerciseId = row.routine_exercise_id, + targetMode = row.target_mode, + thresholdPercent = row.threshold_percent.toInt(), + maxWorkingReps = row.max_working_reps?.toInt(), + requireTwoConsecutive = row.require_two_consecutive != 0L, + savedNominalReps = row.saved_nominal_reps?.toInt(), + updatedAt = row.updated_at, + ) + private fun mapRoutineToBackup(routine: Routine): RoutineBackup = RoutineBackup( id = routine.id, name = LegacyLabelSanitizer.sanitizeEntityName(routine.name, "Unnamed Routine"), @@ -4494,6 +4879,21 @@ abstract class BaseDataBackupManager( completedSets = completedSets.map { mapCompletedSetToBackup(it) }, polarBeatSamples = beatSamples.map(::mapPolarBeatSampleToBackup), polarEcgSegments = ecgSegments.map(::mapPolarEcgSegmentToBackup), + // Issue #1392: session-scoped power-loss sections. Summary facts + // always ride; per-rep observation rows need the raw-telemetry opt-in. + powerLossSetCompanions = queries.selectPowerLossSetCompanionsBySession(sessionId) + .executeAsList() + .map { mapPowerLossSetCompanionToBackup(it) }, + powerLossObservationCompanions = if (includeRawTelemetryInBackups) { + queries.selectPowerLossAttemptCompanionsBySession(sessionId) + .executeAsList() + .map { mapPowerLossObservationCompanionToBackup(it) } + } else { + emptyList() + }, + powerLossExerciseConfigs = powerLossExerciseConfigsFor( + completedSets.mapNotNullTo(hashSetOf()) { it.routine_exercise_id }, + ), ), ) @@ -4578,6 +4978,21 @@ abstract class BaseDataBackupManager( completedSets = allCompletedSets.map { mapCompletedSetToBackup(it) }, polarBeatSamples = allBeatSamples.map(::mapPolarBeatSampleToBackup), polarEcgSegments = allEcgSegments.map(::mapPolarEcgSegmentToBackup), + // Issue #1392: routine-scoped power-loss sections. Summary facts + // always ride; per-rep observation rows need the raw-telemetry opt-in. + powerLossSetCompanions = sessions.flatMap { session -> + queries.selectPowerLossSetCompanionsBySession(session.id).executeAsList() + }.map { mapPowerLossSetCompanionToBackup(it) }, + powerLossObservationCompanions = if (includeRawTelemetryInBackups) { + sessions.flatMap { session -> + queries.selectPowerLossAttemptCompanionsBySession(session.id).executeAsList() + }.map { mapPowerLossObservationCompanionToBackup(it) } + } else { + emptyList() + }, + powerLossExerciseConfigs = powerLossExerciseConfigsFor( + allCompletedSets.mapNotNullTo(hashSetOf()) { it.routine_exercise_id }, + ), ), ) diff --git a/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/WorkoutCommandValidator.kt b/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/WorkoutCommandValidator.kt index f307258a1..2ecb4557f 100644 --- a/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/WorkoutCommandValidator.kt +++ b/shared/src/commonMain/kotlin/com/devil/phoenixproject/util/WorkoutCommandValidator.kt @@ -17,12 +17,19 @@ object WorkoutCommandValidator { // AMRAP sentinel (see BlePacketFactory). A finite rep count that serializes to // 0xFF would be indistinguishable from an unlimited workout and could defeat // automatic stop, so finite rep bytes are capped at 254 (audit F069/F070). - private const val MAX_FINITE_REP_BYTE = 254 + // + // Issue #1392 (SD4): internal so the execution-target-plan derivation and the + // Echo packet path use THIS accepted validator bound — never a guessed value. + internal const val MAX_FINITE_REP_BYTE = 254 private const val MAX_PACKET_REPS = MAX_FINITE_REP_BYTE private const val MAX_ECHO_ECCENTRIC_PERCENT = 150 private const val MAX_ECHO_REP_BYTE = MAX_FINITE_REP_BYTE - fun validateProgramParams(params: WorkoutParameters, maxWeightPerCableKg: Float): Result { + fun validateProgramParams( + params: WorkoutParameters, + maxWeightPerCableKg: Float, + targetPlan: com.devil.phoenixproject.domain.powerloss.ExecutionTargetPlan? = null, + ): Result { if (params.isEchoMode) { return failure("Program parameter packet must not be used for Echo mode") } @@ -52,7 +59,22 @@ object WorkoutCommandValidator { validateRepByte("warmupReps", params.warmupReps, allowZero = true) .onFailure { return Result.failure(it) } - if (!params.isJustLift && !params.isAMRAP) { + // Issue #1392 (SD4): the validation must agree with the plan — in POWER mode the + // frame encodes the frozen max-reps backstop (plus warmup), never the saved + // nominal. Unlimited identities keep the 0xFF sentinel and are capped in-app. + val powerCap = targetPlan + ?.takeIf { + it.targetMode == com.devil.phoenixproject.domain.powerloss.TargetMode.POWER + } + ?.maxWorkingReps + if (!params.isJustLift && !params.isAMRAP && powerCap != null) { + validateRepByte("maxWorkingReps", powerCap, allowZero = false) + .onFailure { return Result.failure(it) } + val totalReps = powerCap + params.warmupReps + if (totalReps !in 1..MAX_PACKET_REPS) { + return failure("maxWorkingReps + warmupReps must fit in one byte (1..$MAX_PACKET_REPS), got $totalReps") + } + } else if (!params.isJustLift && !params.isAMRAP) { validateRepByte("reps", params.reps, allowZero = false).onFailure { return Result.failure(it) } val totalReps = params.reps + params.warmupReps if (totalReps !in 1..MAX_PACKET_REPS) { @@ -70,6 +92,7 @@ object WorkoutCommandValidator { isJustLift: Boolean, isAMRAP: Boolean, eccentricPct: Int, + targetPlan: com.devil.phoenixproject.domain.powerloss.ExecutionTargetPlan? = null, ): Result { // Touch level so the compiler keeps this validator exhaustive if EchoLevel changes. when (level) { @@ -82,8 +105,17 @@ object WorkoutCommandValidator { validateRepByte("warmupReps", warmupReps, allowZero = true) .onFailure { return Result.failure(it) } + // Issue #1392 (SD4): the Echo working-target byte must agree with the plan — + // POWER writes the frozen max-reps backstop (finite identity only), never the + // saved nominal. + val powerCap = targetPlan + ?.takeIf { + it.targetMode == com.devil.phoenixproject.domain.powerloss.TargetMode.POWER + } + ?.maxWorkingReps if (!isJustLift && !isAMRAP) { - validateRepByte("targetReps", targetReps, allowZero = false) + val effectiveTargetReps = powerCap ?: targetReps + validateRepByte("targetReps", effectiveTargetReps, allowZero = false) .onFailure { return Result.failure(it) } } if (eccentricPct !in 0..MAX_ECHO_ECCENTRIC_PERCENT) { diff --git a/shared/src/commonMain/sqldelight/com/devil/phoenixproject/database/PhoenixDatabase.sq b/shared/src/commonMain/sqldelight/com/devil/phoenixproject/database/PhoenixDatabase.sq index 8b390f618..93a196845 100644 --- a/shared/src/commonMain/sqldelight/com/devil/phoenixproject/database/PhoenixDatabase.sq +++ b/shared/src/commonMain/sqldelight/com/devil/phoenixproject/database/PhoenixDatabase.sq @@ -5601,3 +5601,161 @@ DELETE FROM IntervalsOutbox WHERE profile_id = :profile_id; deleteIntervalsProfileReservations: DELETE FROM IntervalsExternalIdReservation WHERE owner_profile_id = :profile_id; + +-- ==================== POWER-LOSS DURABLE COMPANIONS (issue #1392, packet P4) ==================== +-- Additive nullable companions for the power-loss autostop evidence contract +-- (domain/powerloss/PowerLossEvidence.kt). Legacy rows keep their REP meaning with +-- NULL new metrics — missing data is NULL, never a fabricated zero. +-- These tables carry NO sync wire semantics: nothing here is pushed to the portal +-- (no new wire keys; spec §6). Attempt rows support attempt-only observations with +-- no legacy RepMetric row and deliberately carry NO foreign key to RepMetric, so the +-- completion commit's wholesale rep-row replacement can never cascade them away. + +CREATE TABLE PowerLossSetCompanion ( + session_id TEXT NOT NULL, + set_id TEXT NOT NULL, + metric_version INTEGER NOT NULL DEFAULT 1, + target_mode TEXT NOT NULL, + threshold_percent INTEGER NOT NULL, + max_working_reps INTEGER, + require_two_consecutive INTEGER NOT NULL DEFAULT 0 CHECK(require_two_consecutive IN (0, 1)), + saved_nominal_reps INTEGER, + active_cables TEXT NOT NULL, + active_cable_provenance TEXT NOT NULL, + reference_working_ordinal INTEGER, + reference_mcp_watts REAL, + reference_rom_a_mm REAL, + reference_rom_b_mm REAL, + trigger_working_ordinal INTEGER, + winner_reason TEXT, + short_rom_observed INTEGER NOT NULL DEFAULT 0 CHECK(short_rom_observed IN (0, 1)), + power_loss_observed INTEGER NOT NULL DEFAULT 0 CHECK(power_loss_observed IN (0, 1)), + loss_percent_at_decision REAL, + created_at INTEGER NOT NULL, + PRIMARY KEY (session_id, set_id), + FOREIGN KEY (session_id) REFERENCES WorkoutSession(id) ON DELETE CASCADE +); + +CREATE INDEX idx_power_loss_set_session ON PowerLossSetCompanion(session_id); + +CREATE TABLE PowerLossAttemptCompanion ( + session_id TEXT NOT NULL, + set_id TEXT NOT NULL, + working_concentric_ordinal INTEGER NOT NULL, + legacy_rep_index INTEGER, + completed INTEGER NOT NULL DEFAULT 0 CHECK(completed IN (0, 1)), + mcp_watts REAL, + eccentric_power_watts REAL, + concentric_duration_ms INTEGER, + eccentric_duration_ms INTEGER, + loss_percent_at_decision REAL, + reference_working_ordinal INTEGER, + rom_a_mm REAL, + rom_b_mm REAL, + rom_a_percent_of_reference REAL, + rom_b_percent_of_reference REAL, + rom_trustworthy INTEGER NOT NULL DEFAULT 0 CHECK(rom_trustworthy IN (0, 1)), + quality TEXT NOT NULL DEFAULT '', + short_rom INTEGER NOT NULL DEFAULT 0 CHECK(short_rom IN (0, 1)), + power_loss_qualified INTEGER NOT NULL DEFAULT 0 CHECK(power_loss_qualified IN (0, 1)), + PRIMARY KEY (session_id, working_concentric_ordinal), + FOREIGN KEY (session_id) REFERENCES WorkoutSession(id) ON DELETE CASCADE +); + +CREATE INDEX idx_power_loss_attempt_session_set ON PowerLossAttemptCompanion(session_id, set_id); + +-- Set/attempt companion writes are INSERT-if-absent on their stable keys: +-- idempotent on retry, immutable (an existing row is never replaced), and never +-- INSERT OR REPLACE of a parent (these are leaf rows). API-26 safe: no upsert. + +deletePowerLossSetCompanion: +DELETE FROM PowerLossSetCompanion WHERE session_id = :session_id AND set_id = :set_id; + +insertPowerLossSetCompanionIfAbsent: +INSERT INTO PowerLossSetCompanion( + session_id, set_id, metric_version, target_mode, threshold_percent, + max_working_reps, require_two_consecutive, saved_nominal_reps, + active_cables, active_cable_provenance, + reference_working_ordinal, reference_mcp_watts, reference_rom_a_mm, reference_rom_b_mm, + trigger_working_ordinal, winner_reason, + short_rom_observed, power_loss_observed, loss_percent_at_decision, created_at +) +SELECT :session_id, :set_id, :metric_version, :target_mode, :threshold_percent, + :max_working_reps, :require_two_consecutive, :saved_nominal_reps, + :active_cables, :active_cable_provenance, + :reference_working_ordinal, :reference_mcp_watts, :reference_rom_a_mm, :reference_rom_b_mm, + :trigger_working_ordinal, :winner_reason, + :short_rom_observed, :power_loss_observed, :loss_percent_at_decision, :created_at +WHERE NOT EXISTS ( + SELECT 1 FROM PowerLossSetCompanion + WHERE session_id = :session_id AND set_id = :set_id +); + +selectPowerLossSetCompanionsBySession: +SELECT * FROM PowerLossSetCompanion WHERE session_id = :session_id ORDER BY created_at DESC, set_id DESC; + +deletePowerLossAttemptCompanion: +DELETE FROM PowerLossAttemptCompanion WHERE session_id = :session_id AND working_concentric_ordinal = :working_concentric_ordinal; + +insertPowerLossAttemptCompanionIfAbsent: +INSERT INTO PowerLossAttemptCompanion( + session_id, set_id, working_concentric_ordinal, legacy_rep_index, completed, + mcp_watts, eccentric_power_watts, concentric_duration_ms, eccentric_duration_ms, + loss_percent_at_decision, reference_working_ordinal, + rom_a_mm, rom_b_mm, rom_a_percent_of_reference, rom_b_percent_of_reference, + rom_trustworthy, quality, short_rom, power_loss_qualified +) +SELECT :session_id, :set_id, :working_concentric_ordinal, :legacy_rep_index, :completed, + :mcp_watts, :eccentric_power_watts, :concentric_duration_ms, :eccentric_duration_ms, + :loss_percent_at_decision, :reference_working_ordinal, + :rom_a_mm, :rom_b_mm, :rom_a_percent_of_reference, :rom_b_percent_of_reference, + :rom_trustworthy, :quality, :short_rom, :power_loss_qualified +WHERE NOT EXISTS ( + SELECT 1 FROM PowerLossAttemptCompanion + WHERE session_id = :session_id AND working_concentric_ordinal = :working_concentric_ordinal +); + +selectPowerLossAttemptCompanionsBySession: +SELECT * FROM PowerLossAttemptCompanion WHERE session_id = :session_id ORDER BY working_concentric_ordinal ASC; + +-- Per-exercise power-loss target config (issue #1392, packet P4 remainder, +-- migration 65.sqm). One row per routine exercise; absent row = inert +-- REP_TARGET defaults with NULLs — never fabricated zeros. The row is local-only +-- configuration: no sync wire semantics, never pushed, never marked backed up. +CREATE TABLE PowerLossExerciseConfig ( + routine_exercise_id TEXT NOT NULL PRIMARY KEY, + format_version INTEGER NOT NULL DEFAULT 1, + target_mode TEXT NOT NULL, + threshold_percent INTEGER NOT NULL, + max_working_reps INTEGER, + require_two_consecutive INTEGER NOT NULL DEFAULT 0 CHECK(require_two_consecutive IN (0, 1)), + saved_nominal_reps INTEGER, + updated_at INTEGER NOT NULL, + FOREIGN KEY (routine_exercise_id) REFERENCES RoutineExercise(id) ON DELETE CASCADE +); + +selectAllPowerLossExerciseConfigs: +SELECT * FROM PowerLossExerciseConfig; + +selectPowerLossExerciseConfigsByRoutineExerciseIds: +SELECT * FROM PowerLossExerciseConfig WHERE routine_exercise_id IN ?; + +-- INSERT-if-absent: backup restore and retry-safe commits. Local config wins — +-- an existing row is never replaced by a restore (absent/present sections can +-- only add, never wipe). API-26 safe: no upsert syntax. +insertPowerLossExerciseConfigIfAbsent: +INSERT INTO PowerLossExerciseConfig( + routine_exercise_id, format_version, target_mode, threshold_percent, + max_working_reps, require_two_consecutive, saved_nominal_reps, updated_at +) +SELECT :routine_exercise_id, :format_version, :target_mode, :threshold_percent, + :max_working_reps, :require_two_consecutive, :saved_nominal_reps, :updated_at +WHERE NOT EXISTS ( + SELECT 1 FROM PowerLossExerciseConfig + WHERE routine_exercise_id = :routine_exercise_id +); + +-- Authoritative local edit: the local write path deletes and reinserts inside +-- its transaction (idempotent on retry; no parent replace; leaf row only). +deletePowerLossExerciseConfig: +DELETE FROM PowerLossExerciseConfig WHERE routine_exercise_id = :routine_exercise_id; diff --git a/shared/src/commonMain/sqldelight/com/devil/phoenixproject/database/migrations/66.sqm b/shared/src/commonMain/sqldelight/com/devil/phoenixproject/database/migrations/66.sqm new file mode 100644 index 000000000..cdadfbeb7 --- /dev/null +++ b/shared/src/commonMain/sqldelight/com/devil/phoenixproject/database/migrations/66.sqm @@ -0,0 +1,67 @@ +-- Migration 66: power-loss autostop durable companions (issue #1392, packet P4). +-- Additive only (SQLite API-26): no DROP COLUMN, no ON CONFLICT DO UPDATE, +-- no INSERT OR REPLACE on parents. Legacy rows keep REP semantics with NULL +-- new metrics — missing data is NULL, never a fabricated zero. Attempt rows +-- carry no FK to RepMetric so rep-row replacement can never cascade them away. +-- Fresh installs get the identical shape from PhoenixDatabase.sq. +-- Mirrors 66.sqm exactly in MigrationStatements.getMigrationStatements(66). + +-- 1. PowerLossSetCompanion: immutable per-set evidence, keyed by stable +-- session id + set id (frozen config, metric version, mask provenance, +-- reference/trigger facts, winner + both qualification facts). +CREATE TABLE IF NOT EXISTS PowerLossSetCompanion ( + session_id TEXT NOT NULL, + set_id TEXT NOT NULL, + metric_version INTEGER NOT NULL DEFAULT 1, + target_mode TEXT NOT NULL, + threshold_percent INTEGER NOT NULL, + max_working_reps INTEGER, + require_two_consecutive INTEGER NOT NULL DEFAULT 0 CHECK(require_two_consecutive IN (0, 1)), + saved_nominal_reps INTEGER, + active_cables TEXT NOT NULL, + active_cable_provenance TEXT NOT NULL, + reference_working_ordinal INTEGER, + reference_mcp_watts REAL, + reference_rom_a_mm REAL, + reference_rom_b_mm REAL, + trigger_working_ordinal INTEGER, + winner_reason TEXT, + short_rom_observed INTEGER NOT NULL DEFAULT 0 CHECK(short_rom_observed IN (0, 1)), + power_loss_observed INTEGER NOT NULL DEFAULT 0 CHECK(power_loss_observed IN (0, 1)), + loss_percent_at_decision REAL, + created_at INTEGER NOT NULL, + PRIMARY KEY (session_id, set_id), + FOREIGN KEY (session_id) REFERENCES WorkoutSession(id) ON DELETE CASCADE +); + +-- 2. +CREATE INDEX IF NOT EXISTS idx_power_loss_set_session ON PowerLossSetCompanion(session_id); + +-- 3. PowerLossAttemptCompanion: one durable row per working concentric +-- observation. Attempt-only rows (completed = 0) need no legacy RepMetric row. +CREATE TABLE IF NOT EXISTS PowerLossAttemptCompanion ( + session_id TEXT NOT NULL, + set_id TEXT NOT NULL, + working_concentric_ordinal INTEGER NOT NULL, + legacy_rep_index INTEGER, + completed INTEGER NOT NULL DEFAULT 0 CHECK(completed IN (0, 1)), + mcp_watts REAL, + eccentric_power_watts REAL, + concentric_duration_ms INTEGER, + eccentric_duration_ms INTEGER, + loss_percent_at_decision REAL, + reference_working_ordinal INTEGER, + rom_a_mm REAL, + rom_b_mm REAL, + rom_a_percent_of_reference REAL, + rom_b_percent_of_reference REAL, + rom_trustworthy INTEGER NOT NULL DEFAULT 0 CHECK(rom_trustworthy IN (0, 1)), + quality TEXT NOT NULL DEFAULT '', + short_rom INTEGER NOT NULL DEFAULT 0 CHECK(short_rom IN (0, 1)), + power_loss_qualified INTEGER NOT NULL DEFAULT 0 CHECK(power_loss_qualified IN (0, 1)), + PRIMARY KEY (session_id, working_concentric_ordinal), + FOREIGN KEY (session_id) REFERENCES WorkoutSession(id) ON DELETE CASCADE +); + +-- 4. +CREATE INDEX IF NOT EXISTS idx_power_loss_attempt_session_set ON PowerLossAttemptCompanion(session_id, set_id); diff --git a/shared/src/commonMain/sqldelight/com/devil/phoenixproject/database/migrations/67.sqm b/shared/src/commonMain/sqldelight/com/devil/phoenixproject/database/migrations/67.sqm new file mode 100644 index 000000000..80582a2b3 --- /dev/null +++ b/shared/src/commonMain/sqldelight/com/devil/phoenixproject/database/migrations/67.sqm @@ -0,0 +1,19 @@ +-- Migration 67: per-exercise power-loss target config (issue #1392, packet P4 +-- remainder). Additive only (SQLite API-26): no DROP COLUMN, no ON CONFLICT +-- DO UPDATE, no INSERT OR REPLACE on parents. An absent row means inert +-- REP_TARGET defaults with NULLs — missing config is NULL, never a fabricated +-- zero, and legacy rows keep their REP meaning. The row is local-only: no sync +-- wire semantics. Fresh installs get the identical shape from PhoenixDatabase.sq. +-- Mirrors 67.sqm exactly in MigrationStatements.getMigrationStatements(67). + +CREATE TABLE IF NOT EXISTS PowerLossExerciseConfig ( + routine_exercise_id TEXT NOT NULL PRIMARY KEY, + format_version INTEGER NOT NULL DEFAULT 1, + target_mode TEXT NOT NULL, + threshold_percent INTEGER NOT NULL, + max_working_reps INTEGER, + require_two_consecutive INTEGER NOT NULL DEFAULT 0 CHECK(require_two_consecutive IN (0, 1)), + saved_nominal_reps INTEGER, + updated_at INTEGER NOT NULL, + FOREIGN KEY (routine_exercise_id) REFERENCES RoutineExercise(id) ON DELETE CASCADE +); diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/sync/PowerLossNoNewWireKeysTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/sync/PowerLossNoNewWireKeysTest.kt new file mode 100644 index 000000000..515f58e0c --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/data/sync/PowerLossNoNewWireKeysTest.kt @@ -0,0 +1,260 @@ +package com.devil.phoenixproject.data.sync + +import com.devil.phoenixproject.domain.model.RepMetricData +import com.devil.phoenixproject.domain.model.WorkoutSession +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.jsonArray +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** + * Golden no-new-wire-keys guard for the power-loss autostop enhancement (#1392). + * + * The power-loss v1 contract is local-only (SQLDelight companions + on-device + * power-history export); the mobile-sync-push payload must stay key-identical to + * the pre-feature wire contract. On the PR branch the entire wire chain — + * `PortalSyncDtos.kt`, `PortalSyncAdapter.kt`, `PortalWireJson.kt`, `Routine.kt` — + * is byte-identical to `main@4d4de558` (empty `git diff main..HEAD` for + * `data/sync/` and the routine/domain models the push reads), so the golden path + * set pinned below IS the pre-feature contract: it was captured on this branch, + * whose serialization code is unchanged since before the feature. Any power-loss + * field leaking onto the wire — now or later — fails this test loudly. + */ +class PowerLossNoNewWireKeysTest { + + @Test + fun `session and telemetry push wire paths equal the pinned pre-feature golden`() { + val paths = collectAllWirePaths() + + assertEquals(goldenWirePaths, paths, "mobile-sync-push wire key surface changed") + } + + @Test + fun `no power-loss identifiers appear anywhere in the push payloads`() { + for (path in collectAllWirePaths()) { + val lower = path.lowercase() + for (token in FORBIDDEN_POWER_LOSS_TOKENS) { + assertTrue( + !lower.contains(token), + "power-loss identifier '$token' leaked onto the wire at '$path'", + ) + } + } + } + + @Test + fun `legacy powerWatts on the wire still equals avgPowerWatts`() { + val result = buildResult() + val payload = PortalWireJson.encodeToString( + ListSerializer(PortalWorkoutSessionDto.serializer()), + result.sessions, + ) + val objects = collectObjectsWithKey(PortalWireJson.parseToJsonElement(payload), "powerWatts") + assertTrue(objects.isNotEmpty(), "expected at least one rep summary with powerWatts") + for (obj in objects) { + val watts = (obj.getValue("powerWatts") as JsonPrimitive).content + assertEquals( + "200.0", + watts, + "legacy powerWatts must stay the avgPowerWatts mapping (200f), got $watts", + ) + } + } + + /** Both push payloads (sessions and rep telemetry) as one path set (arrays collapsed to []). */ + private fun collectAllWirePaths(): Set { + val result = buildResult() + val sessionsJson = PortalWireJson.parseToJsonElement( + PortalWireJson.encodeToString( + ListSerializer(PortalWorkoutSessionDto.serializer()), + result.sessions, + ), + ).jsonArray + val telemetryJson = PortalWireJson.parseToJsonElement( + PortalWireJson.encodeToString( + ListSerializer(PortalRepTelemetryDto.serializer()), + result.telemetry, + ), + ).jsonArray + val paths = linkedSetOf() + collectPaths(JsonArray(sessionsJson + telemetryJson), "", paths) + return paths + } + + private fun buildResult(): PortalSyncAdapter.PortalSessionBuildResult = + PortalSyncAdapter.toPortalWorkoutSessionsWithTelemetry(listOf(fullFixtureSession()), "user-1") + + private fun fullFixtureSession(): PortalSyncAdapter.SessionWithReps { + val session = WorkoutSession( + id = "golden-session", + timestamp = 1700000000000L, + mode = "Old School", + reps = 10, + weightPerCableKg = 20f, + duration = 60000L, + totalReps = 10, + warmupReps = 1, + workingReps = 9, + exerciseName = "Bench Press", + exerciseId = "ex-catalog-1", + routineSessionId = null, + routineName = "Push Day", + totalVolumeKg = 1800f, + rpe = 8, + updatedAt = 1700000060000L, + ) + return PortalSyncAdapter.SessionWithReps( + session = session, + repMetrics = listOf(fullFixtureRep()), + repBiomechanics = listOf( + PortalSyncAdapter.RepBiomechanicsData( + repNumber = 1, + mcvMmS = 500f, + peakVelocityMmS = 800f, + velocityZone = "MODERATE", + asymmetryPercent = 5f, + dominantSide = "LEFT", + avgLoadA = 10f, + avgLoadB = 10f, + ), + ), + muscleGroup = "Chest", + isPr = false, + ) + } + + private fun fullFixtureRep(): RepMetricData = RepMetricData( + repNumber = 1, + isWarmup = false, + startTimestamp = 1700000000000L, + endTimestamp = 1700000002500L, + durationMs = 2500L, + concentricDurationMs = 1000L, + concentricPositions = floatArrayOf(0f, 100f, 200f), + concentricLoadsA = floatArrayOf(10f, 12f, 11f), + concentricLoadsB = floatArrayOf(10f, 12f, 11f), + concentricVelocities = floatArrayOf(400f, 500f, 600f), + concentricTimestamps = longArrayOf(0L, 500L, 1000L), + eccentricDurationMs = 1500L, + eccentricPositions = floatArrayOf(200f, 100f, 0f), + eccentricLoadsA = floatArrayOf(11f, 10f, 9f), + eccentricLoadsB = floatArrayOf(11f, 10f, 9f), + eccentricVelocities = floatArrayOf(300f, 400f, 350f), + eccentricTimestamps = longArrayOf(0L, 500L, 1000L), + peakForceA = 15f, + peakForceB = 15f, + avgForceConcentricA = 10f, + avgForceConcentricB = 10f, + avgForceEccentricA = 8f, + avgForceEccentricB = 8f, + peakVelocity = 800f, + avgVelocityConcentric = 500f, + avgVelocityEccentric = 350f, + rangeOfMotionMm = 300f, + peakPowerWatts = 300f, + avgPowerWatts = 200f, + ) + + private fun collectPaths(el: JsonElement, prefix: String, out: MutableSet) { + when (el) { + is JsonObject -> { + for (key in el.keys.sorted()) { + val path = if (prefix.isEmpty()) key else "$prefix.$key" + out.add(path) + collectPaths(el.getValue(key), path, out) + } + } + is JsonArray -> for (item in el) collectPaths(item, "$prefix[]", out) + else -> Unit + } + } + + private fun collectObjectsWithKey(el: JsonElement, key: String): List { + val found = mutableListOf() + when (el) { + is JsonObject -> { + if (el.containsKey(key)) found.add(el) + for (v in el.values) found += collectObjectsWithKey(v, key) + } + is JsonArray -> for (item in el) found += collectObjectsWithKey(item, key) + else -> Unit + } + return found + } + + companion object { + private const val FORBIDDEN_TOKEN_CSV = + "powerloss,mcp,powermetric,losspercent,referenceworking,shortrom," + + "triggerordinal,workingordinal,maxworkingreps,requiretwoconsecutive," + + "targetmode,eccentricpower,concentricpower" + + private val FORBIDDEN_POWER_LOSS_TOKENS = FORBIDDEN_TOKEN_CSV.split(",") + + // Pinned pre-feature wire contract (arrays collapsed to []). Captured from the + // fully-populated fixture on the PR branch, whose wire-relevant sources are + // byte-identical to main@4d4de558. DO NOT extend this set for power-loss + // fields — they must never reach mobile-sync-push. + private val goldenWirePaths: Set = setOf( + "[].cable", + "[].durationSeconds", + "[].eccentricLoad", + "[].echoLevel", + "[].exerciseCount", + "[].exercises", + "[].exercises[].estimatedOneRepMaxKg", + "[].exercises[].exerciseId", + "[].exercises[].id", + "[].exercises[].muscleGroup", + "[].exercises[].name", + "[].exercises[].orderIndex", + "[].exercises[].sessionId", + "[].exercises[].sets", + "[].exercises[].sets[].actualReps", + "[].exercises[].sets[].exerciseId", + "[].exercises[].sets[].id", + "[].exercises[].sets[].isPr", + "[].exercises[].sets[].repSummaries", + "[].exercises[].sets[].repSummaries[].asymmetryPct", + "[].exercises[].sets[].repSummaries[].id", + "[].exercises[].sets[].repSummaries[].leftForceAvg", + "[].exercises[].sets[].repSummaries[].meanForceN", + "[].exercises[].sets[].repSummaries[].meanVelocityMps", + "[].exercises[].sets[].repSummaries[].peakForceN", + "[].exercises[].sets[].repSummaries[].peakVelocityMps", + "[].exercises[].sets[].repSummaries[].powerWatts", + "[].exercises[].sets[].repSummaries[].repNumber", + "[].exercises[].sets[].repSummaries[].rightForceAvg", + "[].exercises[].sets[].repSummaries[].romMm", + "[].exercises[].sets[].repSummaries[].setId", + "[].exercises[].sets[].repSummaries[].tutMs", + "[].exercises[].sets[].repSummaries[].vbtZone", + "[].exercises[].sets[].rpe", + "[].exercises[].sets[].setNumber", + "[].exercises[].sets[].targetReps", + "[].exercises[].sets[].weightKg", + "[].exercises[].sets[].workoutMode", + "[].forceN", + "[].id", + "[].name", + "[].positionMm", + "[].prCount", + "[].routineName", + "[].setCount", + "[].setId", + "[].startedAt", + "[].timestampMs", + "[].totalVolume", + "[].updatedAt", + "[].userId", + "[].velocityMps", + "[].warmupReps", + "[].workingReps", + "[].workoutMode", + ) + } +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvCodecTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvCodecTest.kt index b912ee9dd..707f34d2d 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvCodecTest.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvCodecTest.kt @@ -13,6 +13,8 @@ import com.devil.phoenixproject.domain.model.ScalingBasis import com.devil.phoenixproject.domain.model.Superset import com.devil.phoenixproject.domain.model.SupersetColors import com.devil.phoenixproject.domain.model.WarmupSet +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.TargetMode import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertIs @@ -26,6 +28,7 @@ import kotlin.test.assertTrue class RoutineCsvCodecTest { private val header = RoutineCsvFormat.COLUMNS.joinToString(",") private val headerV2 = RoutineCsvFormat.COLUMNS_V2.joinToString(",") + private val headerV3 = RoutineCsvFormat.COLUMNS_V3.joinToString(",") private fun exercise(id: String, name: String) = Exercise(id = id, name = name, muscleGroup = "Chest") @@ -82,6 +85,7 @@ class RoutineCsvCodecTest { private fun issues(text: String): List = assertIs(RoutineCsvCodec.parse(text)).issues private fun file(vararg rows: String) = (listOf(RoutineCsvFormat.VERSION_LINE, header) + rows).joinToString("\n") private fun fileV2(vararg rows: String) = (listOf(RoutineCsvFormat.VERSION_V2_LINE, headerV2) + rows).joinToString("\n") + private fun fileV3(vararg rows: String) = (listOf(RoutineCsvFormat.VERSION_V3_LINE, headerV3) + rows).joinToString("\n") /** A hand-written version 2 row: the fixed v1 cells, then [values] by column name. */ private fun rowV2(vararg values: Pair, name: String = "Barbell Squat"): String { @@ -91,6 +95,15 @@ class RoutineCsvCodecTest { return cells.joinToString(",") } + /** A hand-written version 3 row: [rowV2] plus the power-loss cells by column name. */ + private fun rowV3(vararg values: Pair, name: String = "Barbell Squat"): String { + val byName = values.toMap() + val cells = listOf("", name, "", "", "", "", name, "0", "", "", "", "", "8|8|6", "40|40|42.5", "120", "", "false", "") + + RoutineCsvFormat.COLUMNS_V2_ONLY.map { byName[it].orEmpty() } + + RoutineCsvFormat.COLUMNS_V3_ONLY.map { byName[it].orEmpty() } + return cells.joinToString(",") + } + @Test fun exportParsesBackToTheSameRoutine() { val exported = assertIs(RoutineCsvCodec.encode(sampleRoutine(), "Strength", 2)) @@ -399,7 +412,7 @@ class RoutineCsvCodecTest { fun fileLevelProblemsAreReported() { assertTrue(issues("").single().message.contains("empty")) assertTrue(issues("routine_id\n").single().message.contains(RoutineCsvFormat.VERSION_LINE)) - assertTrue(issues("# phoenix_routine_csv_version=3\n$headerV2").single().message.contains("version")) + assertTrue(issues("# phoenix_routine_csv_version=4\n$headerV2").single().message.contains("version")) assertTrue(issues("# phoenix_routine_csv_version=2\n$header").single().message.contains("header")) assertTrue(issues(RoutineCsvFormat.VERSION_LINE + "\nroutine_id;routine_name").single().message.contains("semicolons")) assertTrue(issues(RoutineCsvFormat.VERSION_LINE + "\nroutine_id,routine_name").single().message.contains("header")) @@ -488,4 +501,114 @@ class RoutineCsvCodecTest { val huge = RoutineCsvFormat.VERSION_LINE + "\n" + "x".repeat(RoutineCsvFormat.MAX_BYTES) assertTrue(issues(huge).single().message.contains("2 MB")) } + + // ── Issue #1392: version 3 power-loss config contract ──────────────────── + + @Test + fun powerLossConfigRoundTripsThroughTheVersion3File() { + val powerConfig = PowerLossConfig( + targetMode = TargetMode.POWER, + thresholdPercent = 25, + maxWorkingReps = 15, + requireTwoConsecutive = true, + savedNominalReps = 12, + ) + val routine = sampleRoutine().let { base -> + base.copy(exercises = base.exercises.map { it.copy(powerLoss = powerConfig) }) + } + + val exported = assertIs(RoutineCsvCodec.encode(routine, null, null)) + val draft = parsed(exported.content).single() + assertEquals(powerConfig, draft.exercises.first().powerLoss) + // Blank nullable cells stay absent (null), never a fabricated zero. + val withoutNominal = powerConfig.copy(savedNominalReps = null) + val routine2 = sampleRoutine().let { base -> + base.copy(exercises = base.exercises.map { it.copy(powerLoss = withoutNominal) }) + } + val exported2 = assertIs(RoutineCsvCodec.encode(routine2, null, null)) + val draft2 = parsed(exported2.content).single() + assertEquals(withoutNominal, draft2.exercises.first().powerLoss) + assertNull(draft2.exercises.first().powerLoss.savedNominalReps) + } + + @Test + fun aRoutineWithPowerLossConfigIsNeverQuietlyExportedAsVersion2() { + val routine = sampleRoutine().let { base -> + base.copy( + exercises = base.exercises.map { + it.copy(powerLoss = PowerLossConfig(targetMode = TargetMode.POWER, savedNominalReps = 12)) + }, + ) + } + + val exported = assertIs(RoutineCsvCodec.encode(routine, null, null)) + + assertTrue(exported.content.startsWith(RoutineCsvFormat.VERSION_V3_LINE), "POWER routines export as version 3") + assertTrue(!exported.content.startsWith(RoutineCsvFormat.VERSION_V2_LINE)) + } + + @Test + fun version1And2RowsKeepTheInertRepDefaultsWithNullsNotZeros() { + val draft = parsed(fileV2(rowV2())).single().exercises.single() + assertEquals(TargetMode.REP_TARGET, draft.powerLoss.targetMode) + assertNull(draft.powerLoss.savedNominalReps) + assertEquals(PowerLossConfig.DEFAULT.thresholdPercent, draft.powerLoss.thresholdPercent) + } + + @Test + fun anUnknownPowerLossTargetModeImportsAsInertRepTargetNeverPower() { + val draft = parsed( + fileV3( + rowV3( + "power_loss_target_mode" to "SUPER_FUTURE_MODE", + "power_loss_threshold_percent" to "25", + "power_loss_max_working_reps" to "15", + "power_loss_require_two_consecutive" to "true", + "power_loss_saved_nominal_reps" to "12", + ), + ), + ).single().exercises.single() + + assertEquals(TargetMode.REP_TARGET, draft.powerLoss.targetMode) + assertEquals(25, draft.powerLoss.thresholdPercent) + assertEquals(15, draft.powerLoss.maxWorkingReps) + assertEquals(true, draft.powerLoss.requireTwoConsecutive) + assertEquals(12, draft.powerLoss.savedNominalReps) + } + + @Test + fun anUnknownFileVersionIsRefusedSafely() { + val future = "# phoenix_routine_csv_version=4\n$headerV3\n" + val problems = issues(future) + assertTrue(problems.single().message.contains("Unsupported file version")) + } + + @Test + fun outOfRangePowerLossNumbersAreRefusedWithoutSilentClamping() { + val problems = issues( + fileV3( + rowV3( + "power_loss_target_mode" to "POWER", + "power_loss_threshold_percent" to "50", + ), + ), + ) + assertTrue(problems.any { it.message.contains("power_loss_threshold_percent") }) + } + + @Test + fun anInvalidPowerLossConfigBlocksExportWithExplicitCopy() { + val routine = sampleRoutine().let { base -> + base.copy( + exercises = base.exercises.map { + it.copy(powerLoss = PowerLossConfig(targetMode = TargetMode.POWER, thresholdPercent = 50)) + }, + ) + } + + val blocked = assertIs(RoutineCsvCodec.encode(routine, null, null)) + + assertTrue(blocked.reasons.any { it.contains("power-loss target settings") }) + assertTrue(blocked.reasons.any { it.contains("Use power-data export to keep them") }) + } } diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvImportPlannerTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvImportPlannerTest.kt index a30c04488..3e4b05555 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvImportPlannerTest.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/csv/RoutineCsvImportPlannerTest.kt @@ -12,6 +12,8 @@ import com.devil.phoenixproject.domain.model.RoutineExercise import com.devil.phoenixproject.domain.model.RoutineGroup import com.devil.phoenixproject.domain.model.ScalingBasis import com.devil.phoenixproject.domain.model.WarmupSet +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.TargetMode import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -297,4 +299,49 @@ class RoutineCsvImportPlannerTest { assertEquals(false, stored.durationSyncKnown, "sync state is never in the file") assertEquals(false, stored.isLaunchAdjustedDuration, "launch state is never in the file") } + + @Test + fun thePlannedRoutineKeepsThePowerLossConfigFromTheVersion3File() { + val powerConfig = PowerLossConfig( + targetMode = TargetMode.POWER, + thresholdPercent = 25, + maxWorkingReps = 15, + requireTwoConsecutive = true, + savedNominalReps = 12, + ) + val source = Routine( + id = "push-id", + name = "Push", + createdAt = 10L, + profileId = "p1", + exercises = listOf( + RoutineExercise( + id = "ex-1", + exercise = bench, + orderIndex = 0, + setReps = listOf(8, 8), + weightPerCableKg = 40f, + setWeightsPerCableKg = listOf(40f, 40f), + programMode = ProgramMode.Pump, + powerLoss = powerConfig, + ), + ), + ) + val exported = assertIs(RoutineCsvCodec.encode(source, null, null)) + val drafts = assertIs(RoutineCsvCodec.parse(exported.content)).routines + + val plan = plan(drafts) + + assertTrue(plan.canCommit, plan.issues.toString()) + assertEquals(powerConfig, plan.writes.single().exercises.single().powerLoss) + } + + @Test + fun v1DraftsPlanInertRepDefaultsWithNullsNotZeros() { + val plan = plan(drafts(",Push,Chest day,,,bench-id,Bench Press,0,,,,,8|8|6,40|40|42.5,120,PUMP,false")) + + val powerLoss = plan.writes.single().exercises.single().powerLoss + assertEquals(TargetMode.REP_TARGET, powerLoss.targetMode) + assertNull(powerLoss.savedNominalReps) + } } diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/model/SetEndReasonTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/model/SetEndReasonTest.kt index 3187b8f64..4ef65e61b 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/model/SetEndReasonTest.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/model/SetEndReasonTest.kt @@ -6,8 +6,9 @@ import kotlin.test.assertEquals class SetEndReasonTest { @Test - fun `SetEndReason declares exactly the seven persisted values`() { + fun `SetEndReason declares exactly the ten persisted values`() { // Catches a durable-schema mutation that adds, removes, renames, or reorders a persisted reason. + // Issue #1392 added MAX_REPS_BACKSTOP / POWER_LOSS / SHORT_ROM after TIMER_EXPIRED (before UNKNOWN). assertEquals( listOf( "TARGET_REPS_REACHED", @@ -16,6 +17,9 @@ class SetEndReasonTest { "USER_STOPPED", "CABLE_RELEASED", "TIMER_EXPIRED", + "MAX_REPS_BACKSTOP", + "POWER_LOSS", + "SHORT_ROM", "UNKNOWN", ), SetEndReason.entries.map { it.name }, @@ -32,6 +36,9 @@ class SetEndReasonTest { "USER_STOPPED" to SetEndReason.USER_STOPPED, "CABLE_RELEASED" to SetEndReason.CABLE_RELEASED, "TIMER_EXPIRED" to SetEndReason.TIMER_EXPIRED, + "MAX_REPS_BACKSTOP" to SetEndReason.MAX_REPS_BACKSTOP, + "POWER_LOSS" to SetEndReason.POWER_LOSS, + "SHORT_ROM" to SetEndReason.SHORT_ROM, "UNKNOWN" to SetEndReason.UNKNOWN, ) diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/powerloss/ExecutionTargetPlanTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/powerloss/ExecutionTargetPlanTest.kt new file mode 100644 index 000000000..cc99bddb5 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/powerloss/ExecutionTargetPlanTest.kt @@ -0,0 +1,155 @@ +package com.devil.phoenixproject.domain.powerloss + +import com.devil.phoenixproject.domain.model.ProgramMode +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Issue #1392 P2 execution-target-plan tests (SD4): protocol byte bounds, + * finite/unlimited identity preservation, mandatory POWER backstop, and + * capability gating. + */ +class ExecutionTargetPlanTest { + + private val finiteBounds = ProtocolRepBounds( + maxRepresentableWorkingReps = 254, // PROGRAM: 254 − warmup applied by caller + protocolIdentityFinite = true, + ) + + private val unlimitedBounds = ProtocolRepBounds( + maxRepresentableWorkingReps = 254, + protocolIdentityFinite = false, + ) + + private fun powerConfig(cap: Int = 20, nominal: Int? = 12) = PowerLossConfig( + targetMode = TargetMode.POWER, + thresholdPercent = 20, + maxWorkingReps = cap, + savedNominalReps = nominal, + ) + + // ===== POWER derivation ===== + + @Test + fun `POWER derives a finite cap and preserves the nominal as display-only`() { + val plan = ExecutionTargetPlan.derive(powerConfig(cap = 20, nominal = 12), finiteBounds, warmupSetCount = 2, now = 7L) + assertNotNull(plan) + assertEquals(TargetMode.POWER, plan.targetMode) + assertEquals(20, plan.maxWorkingReps) + assertEquals(12, plan.nominalReps) // preserved, never a stop condition + assertEquals(2, plan.warmupSetCount) + assertTrue(plan.protocolIdentityFinite) + assertEquals(7L, plan.planValidatedAt) + } + + @Test + fun `POWER rejects impossible plans beyond the protocol bound`() { + assertNull(ExecutionTargetPlan.derive(powerConfig(cap = 255), finiteBounds, warmupSetCount = 0, now = 0L)) + // Echo applicable finite byte bound is supplied by the validator, never hardcoded: + val echoBound = ProtocolRepBounds(maxRepresentableWorkingReps = 30, protocolIdentityFinite = true) + assertNotNull(ExecutionTargetPlan.derive(powerConfig(cap = 30), echoBound, warmupSetCount = 0, now = 0L)) + assertNull(ExecutionTargetPlan.derive(powerConfig(cap = 31), echoBound, warmupSetCount = 0, now = 0L)) + } + + @Test + fun `POWER rejects configs below the minimum backstop`() { + assertNull( + ExecutionTargetPlan.derive( + powerConfig(cap = 1), + finiteBounds, + warmupSetCount = 0, + now = 0L, + ), + ) + } + + // ===== REP identity ===== + + @Test + fun `REP finite protocol keeps the nominal target with no derived cap`() { + val plan = ExecutionTargetPlan.derive( + PowerLossConfig(targetMode = TargetMode.REP_TARGET, savedNominalReps = 12), + finiteBounds, + warmupSetCount = 1, + now = 0L, + ) + assertNotNull(plan) + assertEquals(12, plan.nominalReps) + assertNull(plan.maxWorkingReps) + assertTrue(plan.protocolIdentityFinite) + } + + @Test + fun `REP unlimited protocol identity stays unlimited`() { + // Just Lift / AMRAP warmup fallback: unlimited identity must be preserved. + val plan = ExecutionTargetPlan.derive( + PowerLossConfig(targetMode = TargetMode.REP_TARGET, savedNominalReps = null), + unlimitedBounds, + warmupSetCount = 0, + now = 0L, + ) + assertNotNull(plan) + assertFalse(plan.protocolIdentityFinite) + assertNull(plan.maxWorkingReps) + } + + @Test + fun `REP finite protocol rejects an unrepresentable nominal`() { + assertNull( + ExecutionTargetPlan.derive( + PowerLossConfig(targetMode = TargetMode.REP_TARGET, savedNominalReps = 255), + finiteBounds, + warmupSetCount = 0, + now = 0L, + ), + ) + } + + // ===== Cap semantics ===== + + @Test + fun `cap stops only in POWER mode and only at or after the effective max`() { + val plan = ExecutionTargetPlan.derive(powerConfig(cap = 20), finiteBounds, warmupSetCount = 0, now = 0L)!! + assertFalse(plan.capStopAtWorkingAttempt(19)) + assertTrue(plan.capStopAtWorkingAttempt(20)) + val repPlan = ExecutionTargetPlan.derive( + PowerLossConfig(targetMode = TargetMode.REP_TARGET, savedNominalReps = 12), + finiteBounds, + warmupSetCount = 0, + now = 0L, + )!! + assertFalse(repPlan.capStopAtWorkingAttempt(50)) + } + + @Test + fun `saved nominal below the cap never stops POWER early`() { + val plan = ExecutionTargetPlan.derive(powerConfig(cap = 20, nominal = 12), finiteBounds, warmupSetCount = 0, now = 0L)!! + // The nominal (12) is not a cap: only the effective max stops the set. + assertFalse(plan.capStopAtWorkingAttempt(12)) + assertFalse(plan.capStopAtWorkingAttempt(13)) + } + + // ===== Capability gating ===== + + @Test + fun `protocol family mapping supports exactly the V1 effective modes`() { + assertEquals(PowerLossProtocolFamily.OLD_SCHOOL, PowerLossProtocolFamily.of(ProgramMode.OldSchool, false)) + assertEquals(PowerLossProtocolFamily.PUMP, PowerLossProtocolFamily.of(ProgramMode.Pump, false)) + assertEquals(PowerLossProtocolFamily.ECHO, PowerLossProtocolFamily.of(ProgramMode.Echo, false)) + assertEquals(PowerLossProtocolFamily.JUST_LIFT, PowerLossProtocolFamily.of(ProgramMode.OldSchool, true)) + assertEquals(PowerLossProtocolFamily.UNSUPPORTED, PowerLossProtocolFamily.of(ProgramMode.TUT, false)) + assertEquals(PowerLossProtocolFamily.UNSUPPORTED, PowerLossProtocolFamily.of(ProgramMode.TUTBeast, false)) + assertEquals(PowerLossProtocolFamily.UNSUPPORTED, PowerLossProtocolFamily.of(ProgramMode.EccentricOnly, false)) + } + + @Test + fun `POWER capability requires both protocol support and validated paired samples`() { + assertTrue(PowerLossCapability.isEligible(PowerLossProtocolFamily.ECHO, pairedSamplesValidated = true)) + assertFalse(PowerLossCapability.isEligible(PowerLossProtocolFamily.ECHO, pairedSamplesValidated = false)) + assertFalse(PowerLossCapability.isEligible(PowerLossProtocolFamily.UNSUPPORTED, pairedSamplesValidated = true)) + } +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/powerloss/PowerLossAcquisitionTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/powerloss/PowerLossAcquisitionTest.kt new file mode 100644 index 000000000..08b988f67 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/powerloss/PowerLossAcquisitionTest.kt @@ -0,0 +1,201 @@ +package com.devil.phoenixproject.domain.powerloss + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Issue #1392 P1 acquisition contract tests: MCP V1 math (asymmetric and + * single-cable units, signed velocity), quality-rejection reasons, ordered + * accumulation, and the concentric phase normalizer. + */ +class PowerLossAcquisitionTest { + + private fun sample( + loadA: Float = 20f, + loadB: Float = 20f, + vA: Float = 500f, + vB: Float = 500f, + ticks: Long = 0L, + ts: Long = 1_000L, + quality: SampleQualityMarkers = SampleQualityMarkers(), + ) = ValidatedPairedSample( + executionId = "exec-1", + windowOrdinal = 1, + loadAKg = loadA, + loadBKg = loadB, + velocityAMmS = vA, + velocityBMmS = vB, + positionAMm = 0f, + positionBMm = 0f, + deviceTicks = ticks, + monotonicTimestampMs = ts, + quality = quality, + ) + + // ===== MCP V1 math ===== + + @Test + fun `MCP V1 is the arithmetic sample mean of summed paired-cable power`() { + // 20 kg × 500 mm/s per cable: P = 9.81/1000 × (20×500 + 20×500) = 196.2 W + val s = sample() + val expectedSample = 9.81f / 1000f * (20f * 500f + 20f * 500f) + assertEquals(expectedSample, s.samplePowerWatts()) + val result = MeanConcentricPower.compute(listOf(s, s.copy(monotonicTimestampMs = 1_010L), s.copy(monotonicTimestampMs = 1_020L))) + assertEquals(expectedSample, result.mcpWatts) + assertNull(result.qualityReason) + assertEquals(3, result.sampleCount) + } + + @Test + fun `asymmetric loads use per-cable loads with no substitution`() { + // A: 30 kg × 400 mm/s, B: 10 kg × 400 mm/s → 9.81/1000 × (12000 + 4000) = 156.96 W + val s = sample(loadA = 30f, loadB = 10f, vA = 400f, vB = 400f) + assertEquals(9.81f / 1000f * (30f * 400f + 10f * 400f), s.samplePowerWatts()) + } + + @Test + fun `single-cable set contributes zero from the idle cable`() { + // A active only: 9.81/1000 × 25×600 = 147.15 W even though B velocity is nonzero. + val s = sample(loadA = 25f, loadB = 0f, vA = 600f, vB = 900f) + assertEquals(9.81f / 1000f * (25f * 600f), s.samplePowerWatts()) + } + + @Test + fun `signed lowering velocity never becomes lifting power`() { + val s = sample(loadA = 20f, loadB = 20f, vA = -500f, vB = -500f) + assertEquals(0f, s.samplePowerWatts()) + val mixed = sample(loadA = 20f, loadB = 20f, vA = -500f, vB = 500f) + assertEquals(9.81f / 1000f * (20f * 500f), mixed.samplePowerWatts()) + } + + // ===== Quality reasons ===== + + @Test + fun `insufficient samples are rejected`() { + val result = MeanConcentricPower.compute(listOf(sample(), sample(ts = 1_010L))) + assertNull(result.mcpWatts) + assertEquals(McpQualityReason.INSUFFICIENT_SAMPLES, result.qualityReason) + } + + @Test + fun `gap stale rejected and overflow contamination are enumerable and reject the window`() { + val gap = MeanConcentricPower.compute( + listOf(sample(), sample(ts = 1_010L, quality = SampleQualityMarkers(gapBefore = true)), sample(ts = 1_020L)), + ) + assertEquals(McpQualityReason.SAMPLE_GAP, gap.qualityReason) + + val stale = MeanConcentricPower.compute( + listOf(sample(), sample(ts = 1_010L, quality = SampleQualityMarkers(stale = true)), sample(ts = 1_020L)), + ) + assertEquals(McpQualityReason.STALE_DATA, stale.qualityReason) + + val rejected = MeanConcentricPower.compute( + listOf(sample(), sample(ts = 1_010L, quality = SampleQualityMarkers(rejected = true)), sample(ts = 1_020L)), + ) + assertEquals(McpQualityReason.REJECTED_SAMPLE, rejected.qualityReason) + + val clamped = MeanConcentricPower.compute( + listOf(sample(), sample(ts = 1_010L, quality = SampleQualityMarkers(clamped = true)), sample(ts = 1_020L)), + ) + assertEquals(McpQualityReason.REJECTED_SAMPLE, clamped.qualityReason) + + val overflow = MeanConcentricPower.compute( + listOf(sample(), sample(ts = 1_010L), sample(ts = 1_020L)), + overflowed = true, + ) + assertEquals(McpQualityReason.BUFFER_OVERFLOW, overflow.qualityReason) + } + + // ===== Ordered accumulator ===== + + @Test + fun `accumulator rejects duplicate and out-of-order timestamps`() { + val acc = OrderedSampleAccumulator() + assertTrue(acc.submit(sample(ts = 1_000L))) + assertFalse(acc.submit(sample(ts = 1_000L))) // duplicate + assertFalse(acc.submit(sample(ts = 999L))) // out of order + assertEquals(2, acc.rejectedCount) + assertEquals(1, acc.drain().size) + } + + @Test + fun `accumulator counts gaps at or over 100 ms`() { + val acc = OrderedSampleAccumulator() + acc.submit(sample(ts = 1_000L)) + acc.submit(sample(ts = 1_099L)) // 99 ms — not a gap + assertEquals(0, acc.gapCount) + acc.submit(sample(ts = 1_199L)) // 100 ms — gap + assertEquals(1, acc.gapCount) + } + + @Test + fun `accumulator overflow is counted and the window is marked unusable`() { + val acc = OrderedSampleAccumulator(capacity = 2) + acc.submit(sample(ts = 1_000L)) + acc.submit(sample(ts = 1_010L)) + assertFalse(acc.submit(sample(ts = 1_020L))) + assertTrue(acc.overflowed) + assertEquals(1, acc.overflowCount) + } + + @Test + fun `drain returns ordered batch exactly once`() { + val acc = OrderedSampleAccumulator() + acc.submit(sample(ts = 1_000L)) + acc.submit(sample(ts = 1_010L)) + val first = acc.drain() + assertEquals(listOf(1_000L, 1_010L), first.map { it.monotonicTimestampMs }) + assertTrue(acc.drain().isEmpty()) + } + + // ===== Concentric phase normalizer ===== + + private fun normSample(vA: Float, vB: Float, ts: Long, loadA: Float = 20f, loadB: Float = 20f) = + sample(loadA = loadA, loadB = loadB, vA = vA, vB = vB, ts = ts) + + @Test + fun `concentric starts only above the forward threshold on an active cable`() { + val n = ConcentricPhaseNormalizer() + assertNull(n.onSample(normSample(vA = 10f, vB = 10f, ts = 1))) // at threshold, not above + assertEquals(ConcentricPhaseNormalizer.State.IDLE, n.state) + n.onSample(normSample(vA = 11f, vB = 0f, ts = 2)) + assertEquals(ConcentricPhaseNormalizer.State.ACCUMULATING, n.state) + } + + @Test + fun `window seals exactly once on the next fresh sample after two below-threshold samples`() { + val n = ConcentricPhaseNormalizer() + n.onSample(normSample(vA = 500f, vB = 500f, ts = 1)) + n.onSample(normSample(vA = 300f, vB = 300f, ts = 2)) + n.onSample(normSample(vA = 5f, vB = 5f, ts = 3)) // below #1 + assertEquals(ConcentricPhaseNormalizer.State.ACCUMULATING, n.state) + n.onSample(normSample(vA = 5f, vB = 5f, ts = 4)) // below #2 → PENDING_SEAL + assertEquals(ConcentricPhaseNormalizer.State.PENDING_SEAL, n.state) + val sealed = n.onSample(normSample(vA = 0f, vB = 0f, ts = 5)) // sealing sample + assertEquals(4, sealed?.size) // sealed sample itself excluded + assertEquals(ConcentricPhaseNormalizer.State.IDLE, n.state) + assertEquals(1, n.sealedWindows.size) + } + + @Test + fun `validated top-turnaround seals without waiting for two below-threshold samples`() { + val n = ConcentricPhaseNormalizer() + n.onSample(normSample(vA = 500f, vB = 500f, ts = 1)) + n.onSample(normSample(vA = 400f, vB = 400f, ts = 2)) + // Top turnaround: forward velocity crosses to non-forward on an active cable. + n.onSample(normSample(vA = -200f, vB = 400f, ts = 3)) + assertEquals(ConcentricPhaseNormalizer.State.PENDING_SEAL, n.state) + } + + @Test + fun `stale or rejected samples never advance the normalizer`() { + val n = ConcentricPhaseNormalizer() + val stale = normSample(vA = 500f, vB = 500f, ts = 1) + .copy(quality = SampleQualityMarkers(stale = true)) + assertNull(n.onSample(stale)) + assertEquals(ConcentricPhaseNormalizer.State.IDLE, n.state) + } +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/powerloss/PowerLossPolicyTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/powerloss/PowerLossPolicyTest.kt new file mode 100644 index 000000000..3cdb7db4b --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/powerloss/PowerLossPolicyTest.kt @@ -0,0 +1,442 @@ +package com.devil.phoenixproject.domain.powerloss + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Issue #1392 signoff §4.1 pure-signal/policy fixture matrix (P2 acceptance). + * + * All tests use binary-exact MCP ratios (64→48 = exactly 25% loss) so the + * unrounded-threshold semantics are exercised without float rounding artifacts. + */ +class PowerLossPolicyTest { + + // Fixtures: threshold 25%, MCP reference 64 W. 48 W is exactly 25% loss. + private val config = PowerLossConfig( + targetMode = TargetMode.POWER, + thresholdPercent = 25, + maxWorkingReps = 20, + ) + + private val plan = ExecutionTargetPlan( + targetMode = TargetMode.POWER, + nominalReps = 12, + maxWorkingReps = 20, + warmupSetCount = 0, + protocolIdentityFinite = true, + planValidatedAt = 0L, + ) + + private fun planWithCap(cap: Int) = plan.copy(maxWorkingReps = cap) + + private fun obs( + ordinal: Int, + mcp: Float?, + romA: CableRom = CableRom.trusted(200f), + romB: CableRom = CableRom.trusted(200f), + warmup: Boolean = false, + active: Set = setOf(PowerCable.A, PowerCable.B), + ) = PowerLossObservation( + workingConcentricOrdinal = ordinal, + isWarmup = warmup, + mcpWatts = mcp, + romA = romA, + romB = romB, + activeCables = active, + ) + + private fun feed( + state: PowerLossPolicyState = PowerLossPolicyState.INITIAL, + observation: PowerLossObservation, + config: PowerLossConfig = this.config, + plan: ExecutionTargetPlan = this.plan, + ) = PowerLossPolicy.observe(state, observation, config, plan) + + // ===== Warmup exclusion ===== + + @Test + fun `warmup observations never establish reference or tally or trigger`() { + val s1 = feed(observation = obs(0, mcp = 10f, warmup = true)) + assertTrue(s1.decision is PowerLossDecision.Continue) + assertNull(s1.state.reference) + assertEquals(0, s1.state.observedWorkingAttempts) + } + + // ===== Attempt gating and baseline ===== + + @Test + fun `first working attempt never triggers even at total loss`() { + // A brand-new observation cannot be measured against "its own" loss. + val s1 = feed(observation = obs(1, mcp = 4f)) + assertTrue(s1.decision is PowerLossDecision.Continue) + assertEquals(1, s1.state.reference?.workingConcentricOrdinal) + } + + @Test + fun `positive baseline required - zero or negative MCP never establishes a reference`() { + val s1 = feed(observation = obs(1, mcp = 0f)) + assertNull(s1.state.reference) + val s2 = feed(state = s1.state, observation = obs(2, mcp = -5f)) + assertNull(s2.state.reference) + val s3 = feed(state = s2.state, observation = obs(3, mcp = 64f)) + assertEquals(3, s3.state.reference?.workingConcentricOrdinal) + } + + @Test + fun `first row zero loss is relative to its own decision-time reference`() { + val s1 = feed(observation = obs(1, mcp = 64f)) + assertEquals(0f, s1.record.lossPercentAtDecision) + assertEquals(1, s1.record.referenceWorkingOrdinal) + } + + // ===== Reference semantics ===== + + @Test + fun `later best updates reference and earlier decision facts stay frozen`() { + val s1 = feed(observation = obs(1, mcp = 64f)) + // Rep 2 is better: decision loss is computed against the frozen rep-1 reference + // (negative loss), then the reference upgrades to rep 2. + val s2 = feed(state = s1.state, observation = obs(2, mcp = 80f)) + assertTrue(s2.decision is PowerLossDecision.Continue) + assertTrue((s2.record.lossPercentAtDecision ?: 0f) < 0f) + assertEquals(1, s2.record.referenceWorkingOrdinal) + assertEquals(2, s2.state.reference?.workingConcentricOrdinal) + // Rep 3 at 60 W is a 25% loss against the rep-2 reference (80 → 60). + val s3 = feed(state = s2.state, observation = obs(3, mcp = 60f)) + val stop = assertIs(s3.decision) + assertEquals(PowerStopReason.POWER_LOSS, stop.reason) + assertEquals(2, stop.referenceWorkingOrdinal) + } + + @Test + fun `earliest tie retention - equal MCP does not replace the reference`() { + val s1 = feed(observation = obs(1, mcp = 64f)) + val s2 = feed(state = s1.state, observation = obs(2, mcp = 64f)) + assertEquals(1, s2.state.reference?.workingConcentricOrdinal) + } + + @Test + fun `no short-rep reference replacement`() { + val s1 = feed(observation = obs(1, mcp = 64f)) + // Rep 2 is short (75% ROM) with better power: it can never replace the reference. + val s2 = feed( + state = s1.state, + observation = obs(2, mcp = 90f, romA = CableRom.trusted(150f), romB = CableRom.trusted(150f)), + ) + assertEquals(1, s2.state.reference?.workingConcentricOrdinal) + } + + // ===== Threshold semantics ===== + + @Test + fun `unrounded threshold equality qualifies exactly at threshold`() { + val s1 = feed(observation = obs(1, mcp = 64f)) + val s2 = feed(state = s1.state, observation = obs(2, mcp = 48f)) + val stop = assertIs(s2.decision) + assertEquals(PowerStopReason.POWER_LOSS, stop.reason) + assertEquals(25f, stop.lossPercentAtDecision) + } + + @Test + fun `sub-threshold unrounded loss does not trigger even where display rounding would`() { + // 1000 → 751 W is 24.9% loss; rounding to 25% would wrongly trigger. + val s1 = feed(observation = obs(1, mcp = 1000f)) + val s2 = feed(state = s1.state, observation = obs(2, mcp = 751f)) + assertFalse(s2.decision is PowerLossDecision.Stop) + assertFalse(s2.record.powerLossQualified) + } + + @Test + fun `display loss clamps to 0-100`() { + val below = PowerLossObservationRecord( + workingConcentricOrdinal = 1, isWarmup = false, mcpWatts = 1f, + lossPercentAtDecision = -5f, referenceWorkingOrdinal = 1, + powerLossQualified = false, shortRomQualified = false, + romAPercentOfReference = null, romBPercentOfReference = null, + activeCables = setOf(PowerCable.A, PowerCable.B), + ) + assertEquals(0f, below.displayLossPercent()) + val above = below.copy(lossPercentAtDecision = 150f) + assertEquals(100f, above.displayLossPercent()) + } + + // ===== Short-ROM semantics (SD1/SD2/SD3) ===== + + @Test + fun `SHORT_ROM wins over POWER_LOSS in the same observation and both facts persist`() { + val s1 = feed(observation = obs(1, mcp = 64f)) + // Rep 2: 75% ROM (short) AND 37.5% power loss (40 W). + val s2 = feed( + state = s1.state, + observation = obs(2, mcp = 40f, romA = CableRom.trusted(150f), romB = CableRom.trusted(150f)), + ) + val stop = assertIs(s2.decision) + assertEquals(PowerStopReason.SHORT_ROM, stop.reason) + assertTrue(stop.shortRomQualified) + assertTrue(stop.powerLossQualified) + assertTrue(s2.record.shortRomQualified) + assertTrue(s2.record.powerLossQualified) + assertEquals(37.5f, s2.record.lossPercentAtDecision) + } + + @Test + fun `one short arm cannot hide - any active cable strictly below 85 percent qualifies`() { + val s1 = feed(observation = obs(1, mcp = 64f)) + val s2 = feed( + state = s1.state, + observation = obs(2, mcp = 64f, romA = CableRom.trusted(150f), romB = CableRom.trusted(200f)), + ) + val stop = assertIs(s2.decision) + assertEquals(PowerStopReason.SHORT_ROM, stop.reason) + } + + @Test + fun `ROM equality at exactly 85 percent is not short`() { + val s1 = feed(observation = obs(1, mcp = 64f)) + val s2 = feed( + state = s1.state, + observation = obs(2, mcp = 64f, romA = CableRom.trusted(170f), romB = CableRom.trusted(170f)), + ) + assertTrue(s2.decision is PowerLossDecision.Continue) + assertFalse(s2.record.shortRomQualified) + } + + @Test + fun `trusted short ROM with null MCP qualifies per SD1`() { + val s1 = feed(observation = obs(1, mcp = 64f)) + val s2 = feed( + state = s1.state, + observation = obs(2, mcp = null, romA = CableRom.trusted(150f), romB = CableRom.trusted(150f)), + ) + val stop = assertIs(s2.decision) + assertEquals(PowerStopReason.SHORT_ROM, stop.reason) + assertTrue(stop.shortRomQualified) + assertFalse(stop.powerLossQualified) + assertNull(stop.lossPercentAtDecision) + } + + @Test + fun `unavailable power alone never qualifies and resets the streak`() { + val cfg = config.copy(requireTwoConsecutive = true) + val s1 = feed(observation = obs(1, mcp = 64f)) + // Rep 2: qualifying power loss (streak 1). + val s2 = feed(state = s1.state, observation = obs(2, mcp = 44f), config = cfg) + assertEquals(1, s2.state.consecutiveQualifyingCount) + // Rep 3: null MCP, full trusted ROM — neither qualifying reason → streak reset. + val s3 = feed(state = s2.state, observation = obs(3, mcp = null), config = cfg) + assertEquals(0, s3.state.consecutiveQualifyingCount) + assertTrue(s3.decision is PowerLossDecision.Continue) + } + + @Test + fun `unknown ROM is neither fabricated full-ROM nor a short stop`() { + val s1 = feed(observation = obs(1, mcp = 64f)) + val s2 = feed(state = s1.state, observation = obs(2, mcp = null)) + // obs() defaults trusted ROM; build unknown explicitly. + val unknown = obs(2, mcp = null, romA = CableRom.UNKNOWN, romB = CableRom.UNKNOWN) + val step = feed(state = s1.state, observation = unknown) + assertTrue(step.decision is PowerLossDecision.Continue) + assertFalse(step.record.shortRomQualified) + assertFalse(step.record.romAPercentOfReference != null) + assertTrue(s2.decision is PowerLossDecision.Continue) + } + + @Test + fun `unknown ROM never promotes the reference per SD3`() { + val s1 = feed(observation = obs(1, mcp = 64f)) + // Rep 2 has better power but an unknown ROM window: reference must not upgrade. + val s2 = feed( + state = s1.state, + observation = obs(2, mcp = 80f, romA = CableRom.UNKNOWN, romB = CableRom.UNKNOWN), + ) + assertEquals(1, s2.state.reference?.workingConcentricOrdinal) + // A later trusted-full-ROM rep at 48 W is still judged against the rep-1 reference. + val s3 = feed(state = s2.state, observation = obs(3, mcp = 48f)) + val stop = assertIs(s3.decision) + assertEquals(PowerStopReason.POWER_LOSS, stop.reason) + assertEquals(1, stop.referenceWorkingOrdinal) + } + + @Test + fun `frozen active-cable mask is persisted as provenance`() { + val s1 = feed(observation = obs(1, mcp = 64f, active = setOf(PowerCable.A))) + assertEquals(setOf(PowerCable.A), s1.record.activeCables) + } + + // ===== Two-consecutive mode (SD1/SD2) ===== + + @Test + fun `two-consecutive mode stops only on the second adjacent qualifying observation`() { + val cfg = config.copy(requireTwoConsecutive = true) + val s1 = feed(observation = obs(1, mcp = 64f)) + val s2 = feed(state = s1.state, observation = obs(2, mcp = 44f), config = cfg) + assertFalse(s2.decision is PowerLossDecision.Stop) + assertEquals(1, s2.state.consecutiveQualifyingCount) + val s3 = feed(state = s2.state, observation = obs(3, mcp = 44f), config = cfg) + val stop = assertIs(s3.decision) + assertEquals(PowerStopReason.POWER_LOSS, stop.reason) + } + + @Test + fun `two-consecutive terminal observation tie-breaks to SHORT_ROM`() { + val cfg = config.copy(requireTwoConsecutive = true) + val s1 = feed(observation = obs(1, mcp = 64f)) + // Prior qualifier may have either reason: rep 2 qualifies by power loss only. + val s2 = feed(state = s1.state, observation = obs(2, mcp = 44f), config = cfg) + assertEquals(1, s2.state.consecutiveQualifyingCount) + // Terminal observation qualifies for BOTH → SHORT_ROM wins (SD2). + val s3 = feed( + state = s2.state, + observation = obs(3, mcp = 40f, romA = CableRom.trusted(150f), romB = CableRom.trusted(150f)), + config = cfg, + ) + val stop = assertIs(s3.decision) + assertEquals(PowerStopReason.SHORT_ROM, stop.reason) + } + + @Test + fun `two-consecutive accepts either prior reason - SHORT_ROM then POWER_LOSS stops`() { + val cfg = config.copy(requireTwoConsecutive = true) + val s1 = feed(observation = obs(1, mcp = 64f)) + val s2 = feed( + state = s1.state, + observation = obs(2, mcp = 64f, romA = CableRom.trusted(150f), romB = CableRom.trusted(150f)), + config = cfg, + ) + assertEquals(1, s2.state.consecutiveQualifyingCount) + val s3 = feed(state = s2.state, observation = obs(3, mcp = 48f), config = cfg) + val stop = assertIs(s3.decision) + assertEquals(PowerStopReason.POWER_LOSS, stop.reason) + } + + @Test + fun `skipped ordinals break adjacency and reset the streak`() { + val cfg = config.copy(requireTwoConsecutive = true) + val s1 = feed(observation = obs(1, mcp = 64f)) + val s2 = feed(state = s1.state, observation = obs(2, mcp = 44f), config = cfg) + assertEquals(1, s2.state.consecutiveQualifyingCount) + // Ordinal 4 arrives after 2: adjacency broke; the qualifying observation + // restarts the streak at 1 instead of stopping. + val s3 = feed(state = s2.state, observation = obs(4, mcp = 44f), config = cfg) + assertFalse(s3.decision is PowerLossDecision.Stop) + assertEquals(1, s3.state.consecutiveQualifyingCount) + } + + // ===== Cap semantics (SD2/SD4) ===== + + @Test + fun `cap stops the set with telemetry unavailable`() { + val capPlan = planWithCap(3) + val s1 = feed(observation = obs(1, mcp = 64f), plan = capPlan) + val s2 = feed(state = s1.state, observation = obs(2, mcp = null), plan = capPlan) + assertTrue(s2.decision is PowerLossDecision.Continue) + val s3 = feed(state = s2.state, observation = obs(3, mcp = null), plan = capPlan) + val stop = assertIs(s3.decision) + assertEquals(PowerStopReason.MAX_REPS_BACKSTOP, stop.reason) + } + + @Test + fun `cap outranks fatigue on the same cycle but both facts persist`() { + val capPlan = planWithCap(2) + val s1 = feed(observation = obs(1, mcp = 64f), plan = capPlan) + val s2 = feed(state = s1.state, observation = obs(2, mcp = 44f), plan = capPlan) + val stop = assertIs(s2.decision) + assertEquals(PowerStopReason.MAX_REPS_BACKSTOP, stop.reason) + assertTrue(s2.record.powerLossQualified) + } + + @Test + fun `cap is independent of the fatigue streak`() { + val cfg = config.copy(requireTwoConsecutive = true) + val capPlan = planWithCap(2) + val s1 = feed(observation = obs(1, mcp = 64f), config = cfg, plan = capPlan) + val s2 = feed(state = s1.state, observation = obs(2, mcp = 64f), config = cfg, plan = capPlan) + val stop = assertIs(s2.decision) + assertEquals(PowerStopReason.MAX_REPS_BACKSTOP, stop.reason) + } + + @Test + fun `saved nominal reps below the cap never stop POWER early`() { + // plan.nominalReps = 12, cap = 20: 15 identical working reps must not stop. + var state = PowerLossPolicyState.INITIAL + repeat(15) { i -> + val step = feed(state = state, observation = obs(i + 1, mcp = 64f)) + assertTrue(step.decision is PowerLossDecision.Continue, "attempt ${i + 1} must continue") + state = step.state + } + } + + // ===== Near-limit warning ===== + + @Test + fun `near-limit warning fires once and terminal supersedes it`() { + val cfg = config.copy(thresholdPercent = 25) // near-limit at 20% + val s1 = feed(observation = obs(1, mcp = 1000f), config = cfg) + // 790 W = 21% loss ≥ 20% near-limit → warning. + val s2 = feed(state = s1.state, observation = obs(2, mcp = 790f), config = cfg) + assertIs(s2.decision) + // 780 W = 22% loss: warning already latched → continue. + val s3 = feed(state = s2.state, observation = obs(3, mcp = 780f), config = cfg) + assertTrue(s3.decision is PowerLossDecision.Continue) + // 700 W = 30% loss → terminal stop, no warning. + val s4 = feed(state = s3.state, observation = obs(4, mcp = 700f), config = cfg) + assertIs(s4.decision) + } + + @Test + fun `zero-loss baseline at threshold 5 never cues`() { + val cfg = config.copy(thresholdPercent = 5) // near-limit at 0% + val s1 = feed(observation = obs(1, mcp = 64f), config = cfg) + // Rep 2 at zero loss: never a cue despite near-limit = 0. + val s2 = feed(state = s1.state, observation = obs(2, mcp = 64f), config = cfg) + assertTrue(s2.decision is PowerLossDecision.Continue) + // First positive loss cues. + val s3 = feed(state = s2.state, observation = obs(3, mcp = 63f), config = cfg) + assertIs(s3.decision) + } + + // ===== Termination latch ===== + + @Test + fun `state after stop is terminated and later observations are ignored`() { + val s1 = feed(observation = obs(1, mcp = 64f)) + val s2 = feed(state = s1.state, observation = obs(2, mcp = 48f)) + assertTrue(s2.state.terminated) + val s3 = feed(state = s2.state, observation = obs(3, mcp = 48f)) + assertTrue(s3.decision is PowerLossDecision.Continue) + assertTrue(s3.state.terminated) + } + + // ===== Config validation ===== + + @Test + fun `config validation rejects out-of-range values without clamping`() { + assertTrue(PowerLossConfig.DEFAULT.isValid()) + assertNull(PowerLossConfig(thresholdPercent = 4).validated()) + assertNull(PowerLossConfig(thresholdPercent = 41).validated()) + assertTrue(PowerLossConfig(thresholdPercent = 5).isValid()) + assertTrue(PowerLossConfig(thresholdPercent = 40).isValid()) + assertNull(PowerLossConfig(maxWorkingReps = 1).validated()) + assertNotNull(PowerLossConfig(maxWorkingReps = 2).validated()) + } + + @Test + fun `near-limit offset floors at zero`() { + assertEquals(0, PowerLossConfig(thresholdPercent = 5).nearLimitLossPercent) + assertEquals(15, PowerLossConfig(thresholdPercent = 20).nearLimitLossPercent) + } + + @Test + fun `unknown persisted target mode never resolves to POWER`() { + assertEquals(TargetMode.POWER, TargetMode.fromPersisted("POWER")) + assertEquals(TargetMode.REP_TARGET, TargetMode.fromPersisted("REP_TARGET")) + assertNull(TargetMode.fromPersisted("power")) + assertNull(TargetMode.fromPersisted(null)) + assertNull(TargetMode.fromPersisted("FUTURE_MODE")) + } +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/usecase/TemplateConverterTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/usecase/TemplateConverterTest.kt index f583ec955..1e304e95f 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/usecase/TemplateConverterTest.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/domain/usecase/TemplateConverterTest.kt @@ -14,6 +14,8 @@ import com.devil.phoenixproject.domain.model.RoutineTemplate import com.devil.phoenixproject.domain.model.ScalingBasis import com.devil.phoenixproject.domain.model.TemplateExercise import com.devil.phoenixproject.domain.model.computeFiveThreeOneSetWeightsForWeek +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.TargetMode import com.devil.phoenixproject.testutil.FakeExerciseRepository import com.devil.phoenixproject.testutil.FakeProfileExerciseBaselineRepository import kotlin.test.Test @@ -594,4 +596,62 @@ class TemplateConverterTest { ) } } + + @Test + fun `template config power-loss target survives conversion and stays inert without config`() = runTest { + val repository = FakeExerciseRepository().apply { + addExercise( + Exercise( + id = "bench-001", + name = "Bench Press", + muscleGroup = "Chest", + muscleGroups = "Chest", + equipment = "BAR", + ), + ) + } + val converter = TemplateConverter(repository, FakeProfileExerciseBaselineRepository()) + + val template = CycleTemplate( + id = "template-power-loss", + name = "Power Day", + description = "Test", + days = listOf( + CycleDayTemplate.training( + dayNumber = 1, + name = "Day 1", + routine = RoutineTemplate( + name = "Bench Day", + exercises = listOf( + TemplateExercise(exerciseName = "Bench Press", sets = 3, reps = 12), + ), + ), + ), + ), + ) + val powerConfig = PowerLossConfig( + targetMode = TargetMode.POWER, + thresholdPercent = 25, + maxWorkingReps = 15, + savedNominalReps = 12, + ) + val configs = mapOf( + "Bench Press" to ExerciseConfig( + exerciseName = "Bench Press", + mode = ProgramMode.OldSchool, + powerLoss = powerConfig, + ), + ) + + val result = converter.convert(template, configs) + val converted = result.routines.single().exercises.single() + assertEquals(powerConfig, converted.powerLoss, "Template path must carry the power-loss config") + + val plain = converter.convert(template) + assertEquals( + PowerLossConfig.DEFAULT, + plain.routines.single().exercises.single().powerLoss, + "Without a template config the generated exercise stays inert REP", + ) + } } diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/ExerciseMediaWiringTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/ExerciseMediaWiringTest.kt index 974178bad..9aced4056 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/ExerciseMediaWiringTest.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/ExerciseMediaWiringTest.kt @@ -109,7 +109,8 @@ class ExerciseMediaWiringTest { // T6: Phase 1 adds NO migration. Two guards, both history-aware (SD14): // (a) the migration set must not grow past the implementation base's latest // (64.sqm at 6f95247) — bump this ratchet only when a real migration lands - // (65: issue #1400 metric-unit x10); + // (65: issue #1400 metric-unit x10; 66/67: issue #1392 power-loss + // companions + per-exercise config); // (b) the only migration allowed to mention ExerciseImage is 43.sqm, the // historical migration that CREATED the table; nothing may ALTER/DROP it. @Test @@ -124,7 +125,7 @@ class ExerciseMediaWiringTest { if (src.contains("ExerciseImage")) mentions.add("$n.sqm") } assertTrue( - maxSeen <= 65, + maxSeen <= 67, "Phase 1 adds no schema migration — found $maxSeen.sqm beyond the base 64.sqm (T6/AC13).", ) assertTrue( diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossExecutionTargetPropagationTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossExecutionTargetPropagationTest.kt new file mode 100644 index 000000000..9b353d246 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossExecutionTargetPropagationTest.kt @@ -0,0 +1,570 @@ +package com.devil.phoenixproject.presentation.manager + +import com.devil.phoenixproject.domain.model.ProgramMode +import com.devil.phoenixproject.domain.model.RepCount +import com.devil.phoenixproject.domain.model.RepEvent +import com.devil.phoenixproject.domain.model.RepType +import com.devil.phoenixproject.domain.model.SetEndReason +import com.devil.phoenixproject.domain.model.WorkoutMetric +import com.devil.phoenixproject.domain.model.WorkoutParameters +import com.devil.phoenixproject.domain.model.WorkoutState +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.PowerLossProtocolFamily +import com.devil.phoenixproject.domain.powerloss.TargetMode +import com.devil.phoenixproject.presentation.manager.DWSMTestHarnessFixtures.strongRep +import com.devil.phoenixproject.presentation.manager.DWSMTestHarnessFixtures.invalidRep +import com.devil.phoenixproject.presentation.manager.DWSMTestHarnessFixtures.weakRep +import com.devil.phoenixproject.presentation.powerloss.PowerLossRuntimeGate +import com.devil.phoenixproject.testutil.DWSMTestHarness +import com.devil.phoenixproject.testutil.TestFixtures +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertNotEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest + +/** + * Issue #1392 (P3 remainder) — production-path single-effective-target tests + * (signoff §4.2: pure tests alone do not satisfy this packet). + * + * Real DWSM/engine/guard/counter/freshness-gate composition with only transport + * and storage faked (DWSMTestHarness): the ONE frozen [ExecutionTargetPlan] must + * be derived before lease/packet/counter creation and read identically by the + * packet byte, the counter config, the rep freshness gate, the power policy and + * the HUD. Covers SD4 hard rules (cap independent of telemetry; saved nominal + * below the cap never stops POWER; protocol max derived before Start; + * finite/unlimited identity preserved) and the same-cycle one-winner latch. + */ +class PowerLossExecutionTargetPropagationTest { + + /** POWER config armed through the production propagation path (P5 seam). */ + private var armedPowerConfig: PowerLossConfig? = null + + private fun armPowerSettings( + harness: DWSMTestHarness, + cap: Int, + nominal: Int?, + family: PowerLossProtocolFamily = PowerLossProtocolFamily.OLD_SCHOOL, + ) { + // Production arming runs through publishPowerLossRuntimeSettingsFrom: the + // runtime seam is derived from the per-exercise config carried by the + // WorkoutParameters behind the capability gate. Arm the same way — gate on + // plus the config on the parameters set below. + PowerLossRuntimeGate.pairedSamplesValidated = true + armedPowerConfig = PowerLossConfig( + targetMode = TargetMode.POWER, + thresholdPercent = 20, + maxWorkingReps = cap, + requireTwoConsecutive = false, + savedNominalReps = nominal, + ) + harness.coordinator.updatePowerLossSettings( + PowerLossRuntimeSettings( + targetMode = TargetMode.POWER, + thresholdPercent = 20, + maxWorkingReps = cap, + requireTwoConsecutive = false, + savedNominalReps = nominal, + protocolFamily = family, + pairedSamplesValidated = true, + ), + ) + } + + @AfterTest + fun clearRuntimeGate() { + PowerLossRuntimeGate.pairedSamplesValidated = false + armedPowerConfig = null + } + + private suspend fun startTrackedCableSet( + harness: DWSMTestHarness, + targetReps: Int, + ): ExecutionLease { + harness.fakeExerciseRepo.addExercise(TestFixtures.benchPress) + harness.fakeBleRepo.simulateConnect("Vee_Test") + harness.dwsm.updateWorkoutParameters( + WorkoutParameters( + programMode = ProgramMode.OldSchool, + reps = targetReps, + warmupReps = 0, + weightPerCableKg = 25f, + useAutoStart = false, + selectedExerciseId = TestFixtures.benchPress.id, + powerLoss = armedPowerConfig ?: PowerLossConfig.DEFAULT, + ), + ) + harness.dwsm.startWorkout(skipCountdown = true) + harness.testScope.testScheduler.advanceUntilIdle() + return harness.activeSessionEngine.currentExecutionLeaseForTest() + } + + private suspend fun persistedReason( + harness: DWSMTestHarness, + lease: ExecutionLease, + ): SetEndReason = harness.fakeCompletedSetRepo.getCompletedSets(lease.sessionId).single().setEndReason + + // ===== (d) POWER plan identity propagation ===== + + @Test + fun `power plan freezes one effective target across packet lease counter and HUD`() = runTest { + val harness = DWSMTestHarness(this) + try { + armPowerSettings(harness, cap = 20, nominal = 12) + val lease = startTrackedCableSet(harness, targetReps = 12) + + // Packet agreement: the frame carries the frozen cap plus the warmup + // buffer — never the saved nominal. + assertEquals( + 23, + harness.fakeBleRepo.programCommands.last().repsByte, + "PROGRAM total byte is the frozen effective target 20 plus warmup 3", + ) + + // Lease agreement: one frozen plan, one effective target. + val plan = assertNotNull(lease.targetPlan) + assertEquals(TargetMode.POWER, plan.targetMode) + assertEquals(20, plan.maxWorkingReps) + assertEquals(12, plan.nominalReps, "the saved nominal is preserved display-only") + assertEquals(3, plan.warmupSetCount, "the warmup bound is frozen on the plan") + assertTrue(plan.protocolIdentityFinite) + assertEquals(20, lease.effectiveWorkingRepTarget) + + // Freshness-gate agreement: the machine's cap total matches and the + // nominal count is ordinary progress below the cap. + val cutover = assertNotNull(lease.activationCutoverTimestampMs) + harness.fakeBleRepo.setHandleState(com.devil.phoenixproject.data.repository.HandleState.Moving) + runCurrent() + harness.fakeBleRepo.emitRepNotification( + harness.modernRepPacket(repsSetCount = 12, repsSetTotal = 20, timestamp = cutover + 1), + ) + runCurrent() + assertEquals(12, harness.coordinator.repCount.value.workingReps) + assertIs(harness.coordinator.workoutState.value) + + // HUD agreement: the published facts come from the frozen plan. + harness.activeSessionEngine.evaluatePowerLossForRep(lease, isWarmup = false, repMetrics = strongRep(baseTs = 10_000L)) + runCurrent() + val hud = harness.coordinator.powerLossHud.value + assertTrue(hud.powerActive) + assertEquals(20, hud.maxWorkingReps, "HUD reads the frozen effective target") + assertEquals(12, hud.savedNominalReps) + + // Counter agreement: completion lands exactly at the frozen cap and + // normalizes to MAX_REPS_BACKSTOP on the finite POWER plan. + harness.fakeBleRepo.emitRepNotification( + harness.modernRepPacket(repsSetCount = 20, repsSetTotal = 20, timestamp = cutover + 2), + ) + runCurrent() + advanceUntilIdle() + assertEquals(SetEndReason.MAX_REPS_BACKSTOP, persistedReason(harness, lease)) + } finally { + harness.cleanup() + } + } + + // ===== (e) saved nominal below the cap never ends a POWER set ===== + + @Test + fun `saved nominal below the cap never ends a power set`() = runTest { + val harness = DWSMTestHarness(this) + try { + armPowerSettings(harness, cap = 20, nominal = 12) + val lease = startTrackedCableSet(harness, targetReps = 12) + + // The machine is told the cap, not the nominal, so the set is finite + // at 20 working reps for both the machine counter and the app. + assertEquals(23, harness.fakeBleRepo.programCommands.last().repsByte) + assertEquals(20, lease.effectiveWorkingRepTarget) + + val cutover = assertNotNull(lease.activationCutoverTimestampMs) + harness.fakeBleRepo.setHandleState(com.devil.phoenixproject.data.repository.HandleState.Moving) + runCurrent() + // Reaching the nominal 12 must not complete the set. + harness.fakeBleRepo.emitRepNotification( + harness.modernRepPacket(repsSetCount = 12, repsSetTotal = 20, timestamp = cutover + 1), + ) + runCurrent() + assertEquals(12, harness.coordinator.repCount.value.workingReps) + assertIs(harness.coordinator.workoutState.value, "the nominal is not a stop condition") + + // Neither must the power policy stop at the nominal. + repeat(12) { index -> + harness.activeSessionEngine.evaluatePowerLossForRep( + lease, + isWarmup = false, + repMetrics = strongRep(baseTs = 20_000L + index * 100), + ) + } + runCurrent() + assertIs(harness.coordinator.workoutState.value) + assertNull(harness.activeSessionEngine.claimedCompletion(lease)) + } finally { + harness.cleanup() + } + } + + // ===== (f) cap enforcement is independent of telemetry ===== + + @Test + fun `cap stop fires with telemetry invalid or unavailable`() = runTest { + val harness = DWSMTestHarness(this) + try { + armPowerSettings(harness, cap = 3, nominal = 12) + val lease = startTrackedCableSet(harness, targetReps = 12) + harness.coordinator._repCount.value = RepCount(workingReps = 3, totalReps = 3, isWarmupComplete = true) + + // Three working attempts with entirely unusable power telemetry (no + // sealed concentric window, unknown ROM) — only the cap can stop, and + // it must (SD4). + repeat(3) { index -> + harness.activeSessionEngine.evaluatePowerLossForRep( + lease, + isWarmup = false, + repMetrics = invalidRep(baseTs = 30_000L + index * 100), + ) + } + runCurrent() + advanceUntilIdle() + assertEquals(SetEndReason.MAX_REPS_BACKSTOP, persistedReason(harness, lease)) + assertEquals( + SetEndReason.MAX_REPS_BACKSTOP, + assertNotNull(harness.activeSessionEngine.claimedCompletion(lease)).reason, + "the immutable winner is the cap even with no valid telemetry", + ) + } finally { + harness.cleanup() + } + } + + // ===== (a) same-cycle races: one completion, one snapshot, one navigation ===== + + @Test + fun `same cycle competing completions latch one winner one snapshot one summary`() = runTest { + var claimCount = 0 + lateinit var harness: DWSMTestHarness + harness = DWSMTestHarness( + this, + afterCompletionClaim = { _, _, _ -> + claimCount += 1 + val lease = harness.activeSessionEngine.currentExecutionLeaseForTest() + // Same-cycle competing candidates: stall (safety), manual, cap, + // dispatch/cable-release and VBT fatigue all arrive after the + // first claim and must lose to the immutable winner. + harness.activeSessionEngine.handleSetCompletion(lease, SetEndReason.STALL_FAILURE) + harness.activeSessionEngine.handleSetCompletion(lease, SetEndReason.USER_STOPPED) + harness.activeSessionEngine.handleSetCompletion(lease, SetEndReason.MAX_REPS_BACKSTOP) + harness.activeSessionEngine.handleSetCompletion(lease, SetEndReason.CABLE_RELEASED) + harness.activeSessionEngine.handleSetCompletion(lease, SetEndReason.VBT_AUTO_END) + }, + ) + try { + armPowerSettings(harness, cap = 20, nominal = 12) + val lease = startTrackedCableSet(harness, targetReps = 12) + harness.coordinator._repCount.value = RepCount(workingReps = 5, totalReps = 5, isWarmupComplete = true) + + harness.activeSessionEngine.handleSetCompletion(lease, SetEndReason.POWER_LOSS) + runCurrent() + // A same-cycle machine-side completion candidate joins the race. + harness.repCounter.onRepEvent?.invoke(RepEvent(type = RepType.WORKOUT_COMPLETE, warmupCount = 3, workingCount = 20)) + runCurrent() + advanceUntilIdle() + + assertEquals(1, claimCount, "exactly one completion claim") + assertEquals(SetEndReason.POWER_LOSS, persistedReason(harness, lease), "the first winner is immutable") + assertEquals(1, harness.fakeCompletedSetRepo.getCompletedSets(lease.sessionId).size, "exactly one completed set") + assertEquals(1, harness.fakeWorkoutRepo.saveSessionAttempts.count { it.id == lease.sessionId }, "exactly one snapshot") + assertEquals(1, harness.fakeBleRepo.stopWorkoutCallCount, "exactly one device stop") + assertIs(harness.coordinator.workoutState.value, "exactly one navigation") + assertEquals( + SetEndReason.POWER_LOSS, + assertNotNull(harness.activeSessionEngine.claimedCompletion(lease)).reason, + ) + } finally { + harness.cleanup() + } + } + + @Test + fun `late callbacks and disconnect never overwrite the latched winner`() = runTest { + val harness = DWSMTestHarness(this) + try { + armPowerSettings(harness, cap = 20, nominal = 12) + val lease = startTrackedCableSet(harness, targetReps = 12) + harness.coordinator._repCount.value = RepCount(workingReps = 5, totalReps = 5, isWarmupComplete = true) + + harness.activeSessionEngine.handleSetCompletion(lease, SetEndReason.POWER_LOSS) + runCurrent() + advanceUntilIdle() + assertEquals(SetEndReason.POWER_LOSS, persistedReason(harness, lease)) + + // Late callbacks after the committed completion, then a disconnect. + harness.activeSessionEngine.handleSetCompletion(lease, SetEndReason.USER_STOPPED) + harness.repCounter.onRepEvent?.invoke(RepEvent(type = RepType.WORKOUT_COMPLETE, warmupCount = 3, workingCount = 20)) + harness.fakeBleRepo.simulateDisconnect() + runCurrent() + harness.activeSessionEngine.handleSetCompletion(lease, SetEndReason.VBT_AUTO_END) + runCurrent() + advanceUntilIdle() + + assertEquals(1, harness.fakeCompletedSetRepo.getCompletedSets(lease.sessionId).size) + assertEquals(SetEndReason.POWER_LOSS, persistedReason(harness, lease), "winner immutable across late callbacks") + assertEquals(1, harness.fakeWorkoutRepo.saveSessionAttempts.count { it.id == lease.sessionId }) + } finally { + harness.cleanup() + } + } + + // ===== (b) stale execution/lease rejection ===== + + @Test + fun `stale execution lease cannot complete or evaluate power loss`() = runTest { + val harness = DWSMTestHarness(this) + try { + armPowerSettings(harness, cap = 20, nominal = 12) + val staleLease = startTrackedCableSet(harness, targetReps = 12) + harness.coordinator._repCount.value = RepCount(workingReps = 4, totalReps = 4, isWarmupComplete = true) + + // Retire A through a normal manual stop, then a successor wins authority. + harness.dwsm.stopWorkout(exitingWorkout = true) + runCurrent() + advanceUntilIdle() + harness.dwsm.startWorkout(skipCountdown = true) + runCurrent() + advanceUntilIdle() + val lease = harness.activeSessionEngine.currentExecutionLeaseForTest() + assertNotEquals(staleLease.executionId, lease.executionId) + + // A stale completion is rejected outright. + harness.activeSessionEngine.handleSetCompletion(staleLease, SetEndReason.POWER_LOSS) + runCurrent() + assertIs(harness.coordinator.workoutState.value) + assertEquals( + 1, + harness.fakeCompletedSetRepo.getCompletedSets(staleLease.sessionId).size, + "only the original manual-stop completion exists for the stale execution", + ) + assertNull(harness.activeSessionEngine.claimedCompletion(lease)) + + // A stale power-loss evaluation can neither trigger nor latch anything. + harness.activeSessionEngine.evaluatePowerLossForRep(staleLease, isWarmup = false, repMetrics = weakRep(baseTs = 40_000L)) + runCurrent() + advanceUntilIdle() + assertIs(harness.coordinator.workoutState.value) + assertNull(harness.activeSessionEngine.claimedCompletion(lease)) + } finally { + harness.cleanup() + } + } + + // ===== (c) no manufactured rep windows on counter jumps ===== + + @Test + fun `counter jumps manufacture no extra rep windows`() = runTest { + val harness = DWSMTestHarness(this) + try { + armPowerSettings(harness, cap = 20, nominal = 12) + val lease = startTrackedCableSet(harness, targetReps = 12) + val events = mutableListOf() + val engineHandler = harness.repCounter.onRepEvent + harness.repCounter.onRepEvent = { event -> + events += event.type + engineHandler?.invoke(event) + } + + val cutover = assertNotNull(lease.activationCutoverTimestampMs) + harness.fakeBleRepo.setHandleState(com.devil.phoenixproject.data.repository.HandleState.Moving) + runCurrent() + // One packet whose directional counters jump several reps at once. + harness.fakeBleRepo.emitRepNotification( + harness.modernRepPacket( + repsSetCount = 3, + repsSetTotal = 20, + topCounter = 7, + completeCounter = 7, + timestamp = cutover + 1, + ), + ) + runCurrent() + assertEquals(3, harness.coordinator.repCount.value.workingReps, "the machine counter is trusted") + assertEquals(1, events.count { it == RepType.WORKING_COMPLETED }, "one confirmation — not one per jumped counter unit") + assertEquals(0, events.count { it == RepType.WORKOUT_COMPLETE }, "below the frozen cap nothing completes") + + // A rewound counter packet re-baselines instead of manufacturing reps. + harness.fakeBleRepo.emitRepNotification( + harness.modernRepPacket( + repsSetCount = 1, + repsSetTotal = 20, + topCounter = 0, + completeCounter = 0, + timestamp = cutover + 2, + ), + ) + runCurrent() + assertEquals(1, events.count { it == RepType.WORKING_COMPLETED }, "a rewound packet manufactures no rep windows") + assertIs(harness.coordinator.workoutState.value) + } finally { + harness.cleanup() + } + } + + // ===== (g) REP-mode behavior unchanged ===== + + @Test + fun `rep mode keeps nominal encoding and target reps reached`() = runTest { + val harness = DWSMTestHarness(this) + try { + // No POWER settings: the default runtime is inert REP. + val lease = startTrackedCableSet(harness, targetReps = 8) + val plan = lease.targetPlan + assertTrue(plan == null || plan.targetMode == TargetMode.REP_TARGET) + assertEquals(8, lease.effectiveWorkingRepTarget, "REP keeps its per-set nominal target") + assertEquals( + 11, + harness.fakeBleRepo.programCommands.last().repsByte, + "REP bytes stay nominal plus warmup — byte-identical to today", + ) + + // Power-loss evaluation is inert under REP. + harness.coordinator._repCount.value = RepCount(workingReps = 2, totalReps = 2, isWarmupComplete = true) + harness.activeSessionEngine.evaluatePowerLossForRep(lease, isWarmup = false, repMetrics = weakRep(baseTs = 50_000L)) + runCurrent() + assertIs(harness.coordinator.workoutState.value) + assertNull(harness.activeSessionEngine.claimedCompletion(lease)) + + // WORKOUT_COMPLETE keeps its legacy TARGET_REPS_REACHED meaning. + harness.coordinator._repCount.value = RepCount(workingReps = 8, totalReps = 8, isWarmupComplete = true) + harness.repCounter.onRepEvent?.invoke(RepEvent(type = RepType.WORKOUT_COMPLETE, warmupCount = 3, workingCount = 8)) + runCurrent() + advanceUntilIdle() + assertEquals(SetEndReason.TARGET_REPS_REACHED, persistedReason(harness, lease)) + } finally { + harness.cleanup() + } + } + + // ===== Impossible plans fail safe to inert REP behavior ===== + + @Test + fun `impossible power plan fails safe to inert rep behavior`() = runTest { + val harness = DWSMTestHarness(this) + try { + // 255 cannot fit the finite PROGRAM byte alongside the warmup buffer. + armPowerSettings(harness, cap = 255, nominal = 12) + val lease = startTrackedCableSet(harness, targetReps = 12) + + assertNull(lease.targetPlan, "an impossible plan never arms POWER") + assertEquals(12, lease.effectiveWorkingRepTarget) + assertEquals( + 15, + harness.fakeBleRepo.programCommands.last().repsByte, + "the set fails safe to inert REP encoding", + ) + + repeat(3) { index -> + harness.activeSessionEngine.evaluatePowerLossForRep( + lease, + isWarmup = false, + repMetrics = weakRep(baseTs = 60_000L + index * 100), + ) + } + runCurrent() + advanceUntilIdle() + assertIs(harness.coordinator.workoutState.value, "no POWER stop may fire") + assertNull(harness.activeSessionEngine.claimedCompletion(lease)) + } finally { + harness.cleanup() + } + } + + // ===== Unlimited identity preserved; cap enforced in-app ===== + + @Test + fun `unlimited identity keeps its sentinel and caps in app`() = runTest { + val harness = DWSMTestHarness(this) + try { + armPowerSettings(harness, cap = 3, nominal = null, family = PowerLossProtocolFamily.JUST_LIFT) + harness.fakeBleRepo.simulateConnect("Vee_Test") + harness.dwsm.updateWorkoutParameters( + WorkoutParameters( + programMode = ProgramMode.OldSchool, + reps = 0, + warmupReps = 0, + weightPerCableKg = 25f, + isJustLift = true, + useAutoStart = false, + selectedExerciseId = TestFixtures.benchPress.id, + powerLoss = armedPowerConfig ?: PowerLossConfig.DEFAULT, + ), + ) + harness.dwsm.startWorkout(skipCountdown = true, isJustLiftMode = true) + advanceUntilIdle() + val lease = harness.activeSessionEngine.currentExecutionLeaseForTest() + + val plan = assertNotNull(lease.targetPlan) + assertEquals(TargetMode.POWER, plan.targetMode) + assertFalse(plan.protocolIdentityFinite, "genuine Just Lift unlimited identity preserved") + assertEquals( + 255, + harness.fakeBleRepo.programCommands.last().repsByte, + "the 0xFF unlimited sentinel semantics are unchanged", + ) + assertEquals(3, lease.effectiveWorkingRepTarget, "the cap is enforced in-app") + + // The in-app cap fires at the frozen backstop even with no telemetry. + harness.coordinator._repCount.value = RepCount(workingReps = 3, totalReps = 3, isWarmupComplete = true) + repeat(3) { index -> + harness.activeSessionEngine.evaluatePowerLossForRep( + lease, + isWarmup = false, + repMetrics = invalidRep(baseTs = 70_000L + index * 100), + ) + } + runCurrent() + advanceUntilIdle() + assertEquals(SetEndReason.MAX_REPS_BACKSTOP, persistedReason(harness, lease)) + } finally { + harness.cleanup() + } + } +} + +/** Rep-segment fixtures: sealed concentric windows or deliberately unusable telemetry. */ +internal object DWSMTestHarnessFixtures { + + fun repMetrics(baseTs: Long, velocityMmS: Double, valid: Boolean): List { + val velocities = if (valid) { + listOf(velocityMmS, velocityMmS, -200.0, -200.0) + } else { + listOf(0.0, 0.0, 0.0, 0.0) + } + val positions = if (valid) listOf(0f, 100f, 100f, 0f) else listOf(50f, 50f, 50f, 50f) + return List(4) { index -> + WorkoutMetric( + timestamp = baseTs + index * 10, + loadA = 20f, + loadB = 20f, + positionA = positions[index], + positionB = positions[index], + velocityA = velocities[index], + velocityB = velocities[index], + ) + } + } + + /** Full-ROM rep with MCP V1 = 130.8 W (20 kg per cable at 500 mm/s). */ + fun strongRep(baseTs: Long): List = repMetrics(baseTs, velocityMmS = 500.0, valid = true) + + /** Full-ROM rep with MCP V1 = 65.4 W — a 50% loss against [strongRep]. */ + fun weakRep(baseTs: Long): List = repMetrics(baseTs, velocityMmS = 250.0, valid = true) + + /** No sealed concentric window and unknown ROM: unusable telemetry. */ + fun invalidRep(baseTs: Long): List = repMetrics(baseTs, velocityMmS = 0.0, valid = false) +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossHudSetBoundaryResetTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossHudSetBoundaryResetTest.kt new file mode 100644 index 000000000..f3262b7b7 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossHudSetBoundaryResetTest.kt @@ -0,0 +1,221 @@ +package com.devil.phoenixproject.presentation.manager + +import com.devil.phoenixproject.domain.model.ProgramMode +import com.devil.phoenixproject.domain.model.RepCount +import com.devil.phoenixproject.domain.model.SetEndReason +import com.devil.phoenixproject.domain.model.WorkoutParameters +import com.devil.phoenixproject.domain.model.WorkoutState +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.PowerLossHudState +import com.devil.phoenixproject.domain.powerloss.PowerLossProtocolFamily +import com.devil.phoenixproject.domain.powerloss.PowerStopReason +import com.devil.phoenixproject.domain.powerloss.TargetMode +import com.devil.phoenixproject.presentation.manager.DWSMTestHarnessFixtures.strongRep +import com.devil.phoenixproject.presentation.manager.DWSMTestHarnessFixtures.weakRep +import com.devil.phoenixproject.presentation.powerloss.PowerLossRuntimeGate +import com.devil.phoenixproject.testutil.DWSMTestHarness +import com.devil.phoenixproject.testutil.TestFixtures +import kotlin.test.AfterTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertIs +import kotlin.test.assertNotNull +import kotlin.test.assertTrue +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runCurrent +import kotlinx.coroutines.test.runTest + +/** + * Issue #1392 — power-loss HUD set-boundary reset (ui-spec SD6). + * + * The live power panel (`Working attempt N … Ending set…`) belongs to exactly + * one set. Field QA on the implementation branch saw set 1's frozen panel render + * under set 2's `Set 2 / Calibration Reps` headers after a max-reps backstop + * completion: `WorkoutCoordinator._powerLossHud` was written per rep but never + * cleared at the set boundary. These tests pin the production-path reset at set + * teardown and at the next set's context install, plus the SD6 non-regression + * that `endingSet` stays visible through the stop-to-completion window. + */ +class PowerLossHudSetBoundaryResetTest { + + private var armedPowerConfig: PowerLossConfig? = null + + private fun armPowerSettings( + harness: DWSMTestHarness, + cap: Int, + nominal: Int?, + family: PowerLossProtocolFamily = PowerLossProtocolFamily.OLD_SCHOOL, + ) { + PowerLossRuntimeGate.pairedSamplesValidated = true + armedPowerConfig = PowerLossConfig( + targetMode = TargetMode.POWER, + thresholdPercent = 20, + maxWorkingReps = cap, + requireTwoConsecutive = false, + savedNominalReps = nominal, + ) + harness.coordinator.updatePowerLossSettings( + PowerLossRuntimeSettings( + targetMode = TargetMode.POWER, + thresholdPercent = 20, + maxWorkingReps = cap, + requireTwoConsecutive = false, + savedNominalReps = nominal, + protocolFamily = family, + pairedSamplesValidated = true, + ), + ) + } + + @AfterTest + fun clearRuntimeGate() { + PowerLossRuntimeGate.pairedSamplesValidated = false + armedPowerConfig = null + } + + private suspend fun startTrackedCableSet( + harness: DWSMTestHarness, + targetReps: Int, + ): ExecutionLease { + harness.fakeExerciseRepo.addExercise(TestFixtures.benchPress) + harness.fakeBleRepo.simulateConnect("Vee_Test") + harness.dwsm.updateWorkoutParameters( + WorkoutParameters( + programMode = ProgramMode.OldSchool, + reps = targetReps, + warmupReps = 0, + weightPerCableKg = 25f, + useAutoStart = false, + selectedExerciseId = TestFixtures.benchPress.id, + powerLoss = armedPowerConfig ?: PowerLossConfig.DEFAULT, + ), + ) + harness.dwsm.startWorkout(skipCountdown = true) + harness.testScope.testScheduler.advanceUntilIdle() + return harness.activeSessionEngine.currentExecutionLeaseForTest() + } + + private suspend fun persistedReason( + harness: DWSMTestHarness, + lease: ExecutionLease, + ): SetEndReason = harness.fakeCompletedSetRepo.getCompletedSets(lease.sessionId).single().setEndReason + + @Test + fun `completion clears the frozen power hud before the next set`() = runTest { + val harness = DWSMTestHarness(this) + try { + armPowerSettings(harness, cap = 20, nominal = 12) + val lease = startTrackedCableSet(harness, targetReps = 12) + + // A rep publishes the live panel: it belongs to this set only. + harness.activeSessionEngine.evaluatePowerLossForRep( + lease, + isWarmup = false, + repMetrics = strongRep(baseTs = 10_000L), + ) + runCurrent() + val frozen = harness.coordinator.powerLossHud.value + assertTrue(frozen.powerActive, "the live panel is published for the active set") + + // Complete the set at the frozen cap through the production counter + // path (machine WORKOUT_COMPLETE → MAX_REPS_BACKSTOP completion). + val cutover = assertNotNull(lease.activationCutoverTimestampMs) + harness.fakeBleRepo.setHandleState(com.devil.phoenixproject.data.repository.HandleState.Moving) + runCurrent() + harness.fakeBleRepo.emitRepNotification( + harness.modernRepPacket(repsSetCount = 20, repsSetTotal = 20, timestamp = cutover + 1), + ) + runCurrent() + advanceUntilIdle() + assertEquals(SetEndReason.MAX_REPS_BACKSTOP, persistedReason(harness, lease)) + + // SD4 wiring: the summary carries the committed cap winner even when + // the machine-counter path claimed the completion before the policy + // latch — the §6 headline source must not degrade to MANUAL. + val summary = assertIs(harness.coordinator.workoutState.value) + assertEquals( + PowerStopReason.MAX_REPS_BACKSTOP, + summary.powerLoss?.winnerReason, + "the committed completion reason is the winner of record", + ) + + // SD6 set boundary: the frozen panel ends with the completed + // transition — nothing of set 1 survives for set 2 to render. + val cleared = harness.coordinator.powerLossHud.value + assertFalse(cleared.powerActive, "the frozen panel is cleared at set teardown") + assertFalse(cleared.endingSet, "no stale Ending set state survives the set") + assertEquals(0, cleared.currentAttemptOrdinal) + } finally { + harness.cleanup() + } + } + + @Test + fun `a new set installs a clean power hud even after a stale frozen panel`() = runTest { + val harness = DWSMTestHarness(this) + try { + // Reproduce the field observation: a frozen panel from a finished set + // (`Working attempt 20 … Ending set…`) is still published when the + // next set's HUD mounts. + harness.coordinator.setPowerLossHud( + PowerLossHudState( + powerActive = true, + currentAttemptOrdinal = 20, + completedRepCount = 20, + endingSet = true, + ), + ) + armPowerSettings(harness, cap = 20, nominal = 12) + startTrackedCableSet(harness, targetReps = 12) + + val hud = harness.coordinator.powerLossHud.value + assertFalse(hud.powerActive, "the new set's HUD starts clean before any rep") + assertFalse(hud.endingSet, "the previous set's Ending set state never leaks") + assertEquals(0, hud.currentAttemptOrdinal) + } finally { + harness.cleanup() + } + } + + @Test + fun `ending set stays visible until the completed transition`() = runTest { + val harness = DWSMTestHarness(this) + try { + armPowerSettings(harness, cap = 20, nominal = 12) + val lease = startTrackedCableSet(harness, targetReps = 12) + + // Rep 1 establishes the reference (130.8 W); rep 2 loses 50% and + // trips the 20% threshold (earliest fatigue trigger: 2nd attempt). + // The production counter state at the trigger mirrors the two + // completed working reps the rep packets would have counted. + harness.coordinator._repCount.value = RepCount(workingReps = 2, totalReps = 2, isWarmupComplete = true) + harness.activeSessionEngine.evaluatePowerLossForRep( + lease, + isWarmup = false, + repMetrics = strongRep(baseTs = 20_000L), + ) + harness.activeSessionEngine.evaluatePowerLossForRep( + lease, + isWarmup = false, + repMetrics = weakRep(baseTs = 20_100L), + ) + + // SD6: the committed stop state is distinct from the completed + // transition — `Ending set…` is visible while the set is stopping. + val stopping = harness.coordinator.powerLossHud.value + assertTrue(stopping.powerActive) + assertTrue(stopping.endingSet, "the committed stop state renders during the stop") + + // Once the set completes, the panel clears with the transition. + runCurrent() + advanceUntilIdle() + assertEquals(SetEndReason.POWER_LOSS, persistedReason(harness, lease)) + val completed = harness.coordinator.powerLossHud.value + assertFalse(completed.powerActive, "the completed transition leaves no frozen panel") + assertFalse(completed.endingSet) + } finally { + harness.cleanup() + } + } +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossHudWattsAndStreakWiringTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossHudWattsAndStreakWiringTest.kt new file mode 100644 index 000000000..24ae71c52 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossHudWattsAndStreakWiringTest.kt @@ -0,0 +1,105 @@ +package com.devil.phoenixproject.presentation.manager + +import com.devil.phoenixproject.domain.powerloss.CableRom +import com.devil.phoenixproject.domain.powerloss.ExecutionTargetPlan +import com.devil.phoenixproject.domain.powerloss.PowerCable +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.PowerLossObservation +import com.devil.phoenixproject.domain.powerloss.ProtocolRepBounds +import com.devil.phoenixproject.domain.powerloss.TargetMode +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** + * Issue #1392 — HUD watts/qualifying-streak wiring (ui-spec §4 SD6). + * + * The live HUD projection takes `Latest lifting power … W`, `Best: rep N · … W` + * and `Qualifying attempts: 1 of 2` from the engine's [PowerLossHudState]; this + * test pins the controller's hudState() to fill those facts from the reducer + * state and attempt records — never fabricated, null when unavailable. + */ +class PowerLossHudWattsAndStreakWiringTest { + + private val config = PowerLossConfig( + targetMode = TargetMode.POWER, + thresholdPercent = 20, + maxWorkingReps = 20, + requireTwoConsecutive = false, + savedNominalReps = 12, + ) + + private val plan: ExecutionTargetPlan = requireNotNull( + ExecutionTargetPlan.derive( + config = config, + bounds = ProtocolRepBounds( + maxRepresentableWorkingReps = 254, + protocolIdentityFinite = true, + ), + warmupSetCount = 0, + now = 0L, + ), + ) + + private fun obs(ordinal: Int, mcp: Float?): PowerLossObservation = PowerLossObservation( + workingConcentricOrdinal = ordinal, + isWarmup = false, + mcpWatts = mcp, + romA = CableRom.trusted(100f), + romB = CableRom.trusted(100f), + activeCables = setOf(PowerCable.A, PowerCable.B), + ) + + @Test + fun hudStateCarriesLatestAndBestWatts() { + val controller = PowerLossSetController() + controller.onObservation(config, plan, obs(1, mcp = 100f)) + controller.onObservation(config, plan, obs(2, mcp = 120f)) + controller.onObservation(config, plan, obs(3, mcp = null)) + + val hud = controller.hudState(completedRepCount = 3, endingSet = false) + assertEquals(120f, hud.lastMcpWatts, "latest valid sealed concentric MCP") + assertEquals(120f, hud.bestMcpWatts, "reference (best) MCP at rep 2") + assertEquals(2, hud.referenceWorkingOrdinal) + assertNotNull(hud.invalidPowerReason, "attempt 3 is invalid power") + } + + @Test + fun hudStateKeepsWattsUnavailableWhenNoValidPower() { + val controller = PowerLossSetController() + controller.onObservation(config, plan, obs(1, mcp = null)) + + val hud = controller.hudState(completedRepCount = 1, endingSet = false) + assertNull(hud.lastMcpWatts, "no valid power yet — never fabricated") + assertNull(hud.bestMcpWatts, "no reference yet — never fabricated") + } + + @Test + fun hudStateCarriesQualifyingStreakOnlyWhenEnabled() { + val streakConfig = config.copy(requireTwoConsecutive = true) + val streakPlan = requireNotNull( + ExecutionTargetPlan.derive( + config = streakConfig, + bounds = ProtocolRepBounds( + maxRepresentableWorkingReps = 254, + protocolIdentityFinite = true, + ), + warmupSetCount = 0, + now = 0L, + ), + ) + val controller = PowerLossSetController() + controller.onObservation(streakConfig, streakPlan, obs(1, mcp = 100f)) + controller.onObservation(streakConfig, streakPlan, obs(2, mcp = 79f)) + + val hud = controller.hudState(completedRepCount = 2, endingSet = false) + assertEquals(1, hud.qualifyingCount, "21% loss qualifies at 1 of 2 without stopping") + + val controllerNoStreak = PowerLossSetController() + controllerNoStreak.onObservation(config, plan, obs(1, mcp = 100f)) + controllerNoStreak.onObservation(config, plan, obs(2, mcp = 79f)) + val hudNoStreak = controllerNoStreak.hudState(completedRepCount = 2, endingSet = false) + assertNull(hudNoStreak.qualifyingCount, "requirement off — no streak line") + } +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossRuntimeSeamPropagationTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossRuntimeSeamPropagationTest.kt new file mode 100644 index 000000000..41e777949 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossRuntimeSeamPropagationTest.kt @@ -0,0 +1,304 @@ +package com.devil.phoenixproject.presentation.manager + +import com.devil.phoenixproject.data.repository.RestoredWorkoutCommandTemplateSnapshot +import com.devil.phoenixproject.domain.model.ProgramMode +import com.devil.phoenixproject.domain.model.Routine +import com.devil.phoenixproject.domain.model.RoutineExercise +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.PowerLossProtocolFamily +import com.devil.phoenixproject.domain.powerloss.TargetMode +import com.devil.phoenixproject.presentation.powerloss.PowerLossRuntimeGate +import com.devil.phoenixproject.testutil.DWSMTestHarness +import com.devil.phoenixproject.testutil.TestFixtures +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runTest + +/** + * Issue #1392 P5 — propagation wiring (integration-model §4): every generated + * WorkoutParameters / set-ready transition copies the per-exercise power-loss + * target config into the `coordinator.powerLossRuntimeSettings` runtime seam. + * Unsupported timed/bodyweight/TUT paths and unknown persisted target enums + * resolve to inert REP_TARGET — POWER never arms from an unknown or excluded + * mode — and the internal capability gate keeps POWER unarmed by default. + */ +class PowerLossRuntimeSeamPropagationTest { + + private val powerConfig = PowerLossConfig( + targetMode = TargetMode.POWER, + thresholdPercent = 25, + maxWorkingReps = 15, + requireTwoConsecutive = true, + savedNominalReps = 12, + ) + + private fun powerExercise( + id: String, + orderIndex: Int = 0, + sets: List = listOf(12, 10), + mode: ProgramMode = ProgramMode.OldSchool, + config: PowerLossConfig = powerConfig, + duration: Int? = null, + bodyweight: Boolean = false, + ): RoutineExercise = RoutineExercise( + id = id, + exercise = TestFixtures.benchPress.copy( + id = "ex-$id", + isBodyweightOverride = if (bodyweight) true else null, + ), + orderIndex = orderIndex, + setReps = sets, + weightPerCableKg = 30f, + programMode = mode, + duration = duration, + powerLoss = config, + ) + + private fun routineOf(vararg exercises: RoutineExercise): Routine = Routine( + id = "routine-power-loss", + name = "Power Loss Propagation", + exercises = exercises.toList(), + ) + + // ── Routine path: initial, next set/exercise, adjusted/retry, transition ── + + @Test + fun `routine initial load publishes the first exercise power-loss config to the seam`() = runTest { + val harness = DWSMTestHarness(this) + val routine = routineOf(powerExercise("re-1")) + routine.exercises.forEach { harness.fakeExerciseRepo.addExercise(it.exercise) } + advanceUntilIdle() + + harness.dwsm.loadRoutine(routine) + advanceUntilIdle() + + val settings = harness.dwsm.powerLossRuntimeSettings.value + assertEquals(TargetMode.POWER, settings.targetMode) + assertEquals(25, settings.thresholdPercent) + assertEquals(15, settings.maxWorkingReps) + assertTrue(settings.requireTwoConsecutive) + assertEquals(12, settings.savedNominalReps) + assertEquals(PowerLossProtocolFamily.OLD_SCHOOL, settings.protocolFamily) + harness.cleanup() + } + + @Test + fun `next set and next exercise paths republish the per-exercise config`() = runTest { + val harness = DWSMTestHarness(this) + val secondConfig = powerConfig.copy(thresholdPercent = 30, maxWorkingReps = 18) + val routine = routineOf( + powerExercise("re-1", orderIndex = 0), + powerExercise("re-2", orderIndex = 1, config = secondConfig), + ) + routine.exercises.forEach { harness.fakeExerciseRepo.addExercise(it.exercise) } + advanceUntilIdle() + harness.dwsm.loadRoutine(routine) + advanceUntilIdle() + + // Next set on the same exercise: the set's nominal reps follow the seam. + harness.dwsm.enterSetReady(0, 1) + advanceUntilIdle() + assertEquals(10, harness.dwsm.powerLossRuntimeSettings.value.savedNominalReps) + assertEquals(25, harness.dwsm.powerLossRuntimeSettings.value.thresholdPercent) + + // Next exercise: the second exercise's own config replaces it. + harness.dwsm.enterSetReady(1, 0) + advanceUntilIdle() + val settings = harness.dwsm.powerLossRuntimeSettings.value + assertEquals(30, settings.thresholdPercent) + assertEquals(18, settings.maxWorkingReps) + assertEquals(12, settings.savedNominalReps) + harness.cleanup() + } + + @Test + fun `adjusted retry path republishes with the adjusted nominal reps`() = runTest { + val harness = DWSMTestHarness(this) + val routine = routineOf(powerExercise("re-1")) + routine.exercises.forEach { harness.fakeExerciseRepo.addExercise(it.exercise) } + advanceUntilIdle() + harness.dwsm.loadRoutine(routine) + advanceUntilIdle() + + harness.dwsm.routineFlowManager.enterSetReadyWithAdjustments( + exerciseIndex = 0, + setIndex = 0, + adjustedWeight = 32.5f, + adjustedReps = 8, + ) + advanceUntilIdle() + + val settings = harness.dwsm.powerLossRuntimeSettings.value + assertEquals(TargetMode.POWER, settings.targetMode) + assertEquals(8, settings.savedNominalReps) + harness.cleanup() + } + + @Test + fun `set-ready rep edit transition follows the nominal target`() = runTest { + val harness = DWSMTestHarness(this) + val routine = routineOf(powerExercise("re-1")) + routine.exercises.forEach { harness.fakeExerciseRepo.addExercise(it.exercise) } + advanceUntilIdle() + harness.dwsm.loadRoutine(routine) + advanceUntilIdle() + harness.dwsm.enterSetReady(0, 0) + advanceUntilIdle() + + harness.dwsm.updateSetReadyReps(15) + advanceUntilIdle() + + assertEquals(15, harness.dwsm.powerLossRuntimeSettings.value.savedNominalReps) + harness.cleanup() + } + + // ── Ad-hoc path: parameter boundary (MainViewModel / JustLift) ──────────── + + @Test + fun `ad-hoc parameter updates publish the power-loss config to the seam`() = runTest { + val harness = DWSMTestHarness(this) + advanceUntilIdle() + + harness.dwsm.updateWorkoutParameters( + harness.dwsm.coordinator.workoutParameters.value.copy( + programMode = ProgramMode.OldSchool, + isJustLift = true, + reps = 0, + powerLoss = powerConfig, + ), + ) + advanceUntilIdle() + + val settings = harness.dwsm.powerLossRuntimeSettings.value + assertEquals(TargetMode.POWER, settings.targetMode) + assertEquals(PowerLossProtocolFamily.JUST_LIFT, settings.protocolFamily) + assertEquals(12, settings.savedNominalReps) + harness.cleanup() + } + + @Test + fun `ad-hoc rep target parameters keep the seam inert`() = runTest { + val harness = DWSMTestHarness(this) + advanceUntilIdle() + + harness.dwsm.updateWorkoutParameters( + harness.dwsm.coordinator.workoutParameters.value.copy( + programMode = ProgramMode.Pump, + reps = 10, + powerLoss = PowerLossConfig.DEFAULT, + ), + ) + advanceUntilIdle() + + assertEquals(TargetMode.REP_TARGET, harness.dwsm.powerLossRuntimeSettings.value.targetMode) + harness.cleanup() + } + + // ── Excluded paths resolve inert ────────────────────────────────────────── + + @Test + fun `timed routine exercises resolve the power-loss seam to inert rep target`() = runTest { + val harness = DWSMTestHarness(this) + val routine = routineOf(powerExercise("re-timed", duration = 30)) + routine.exercises.forEach { harness.fakeExerciseRepo.addExercise(it.exercise) } + advanceUntilIdle() + + harness.dwsm.loadRoutine(routine) + advanceUntilIdle() + + assertEquals(TargetMode.REP_TARGET, harness.dwsm.powerLossRuntimeSettings.value.targetMode) + harness.cleanup() + } + + @Test + fun `bodyweight routine exercises resolve the power-loss seam to inert rep target`() = runTest { + val harness = DWSMTestHarness(this) + val routine = routineOf(powerExercise("re-bw", bodyweight = true)) + routine.exercises.forEach { harness.fakeExerciseRepo.addExercise(it.exercise) } + advanceUntilIdle() + + harness.dwsm.loadRoutine(routine) + advanceUntilIdle() + + assertEquals(TargetMode.REP_TARGET, harness.dwsm.powerLossRuntimeSettings.value.targetMode) + harness.cleanup() + } + + @Test + fun `tut mode resolves the power-loss seam to inert rep target even with power config`() = runTest { + val harness = DWSMTestHarness(this) + val routine = routineOf(powerExercise("re-tut", mode = ProgramMode.TUT)) + routine.exercises.forEach { harness.fakeExerciseRepo.addExercise(it.exercise) } + advanceUntilIdle() + + harness.dwsm.loadRoutine(routine) + advanceUntilIdle() + + assertEquals(TargetMode.REP_TARGET, harness.dwsm.powerLossRuntimeSettings.value.targetMode) + harness.cleanup() + } + + // ── Capability gate and persisted-enum strictness ───────────────────────── + + @Test + fun `power stays unarmed behind the capability gate and arms only when validated`() = runTest { + val harness = DWSMTestHarness(this) + val routine = routineOf(powerExercise("re-1")) + routine.exercises.forEach { harness.fakeExerciseRepo.addExercise(it.exercise) } + advanceUntilIdle() + harness.dwsm.loadRoutine(routine) + advanceUntilIdle() + + try { + val gated = harness.dwsm.powerLossRuntimeSettings.value + assertEquals(TargetMode.POWER, gated.targetMode, "Config intent is retained") + assertFalse(gated.powerActive, "POWER never arms without validated paired samples") + + PowerLossRuntimeGate.pairedSamplesValidated = true + harness.dwsm.publishPowerLossRuntimeSettingsFrom(harness.dwsm.coordinator.workoutParameters.value) + val armed = harness.dwsm.powerLossRuntimeSettings.value + assertEquals(TargetMode.POWER, armed.targetMode) + assertTrue(armed.powerActive, "Validated paired samples arm the retained POWER intent") + } finally { + PowerLossRuntimeGate.pairedSamplesValidated = false + } + harness.cleanup() + } + + @Test + fun `runtime snapshot round-trips the frozen power-loss config`() = runTest { + val harness = DWSMTestHarness(this) + val params = harness.dwsm.coordinator.workoutParameters.value.copy( + programMode = ProgramMode.Echo, + reps = 12, + powerLoss = powerConfig, + ) + + val restored = RestoredWorkoutCommandTemplateSnapshot.from(params).toWorkoutParameters() + assertEquals(TargetMode.POWER, restored.powerLoss.targetMode) + assertEquals(25, restored.powerLoss.thresholdPercent) + assertEquals(15, restored.powerLoss.maxWorkingReps) + assertTrue(restored.powerLoss.requireTwoConsecutive) + assertEquals(12, restored.powerLoss.savedNominalReps) + harness.cleanup() + } + + @Test + fun `unknown persisted target enum resolves to inert rep target on restore`() = runTest { + val harness = DWSMTestHarness(this) + val params = harness.dwsm.coordinator.workoutParameters.value.copy( + reps = 12, + powerLoss = powerConfig, + ) + val snapshot = RestoredWorkoutCommandTemplateSnapshot.from(params) + .copy(powerLossTargetModeName = "NOT_A_TARGET_MODE") + + val restored = snapshot.toWorkoutParameters() + assertEquals(TargetMode.REP_TARGET, restored.powerLoss.targetMode) + assertEquals(25, restored.powerLoss.thresholdPercent, "Remaining persisted values are preserved") + harness.cleanup() + } +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossSetEvidenceLatchTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossSetEvidenceLatchTest.kt new file mode 100644 index 000000000..de88d0210 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossSetEvidenceLatchTest.kt @@ -0,0 +1,200 @@ +package com.devil.phoenixproject.presentation.manager + +import com.devil.phoenixproject.domain.powerloss.CableRom +import com.devil.phoenixproject.domain.powerloss.ExecutionTargetPlan +import com.devil.phoenixproject.domain.powerloss.PowerCable +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.PowerLossDecision +import com.devil.phoenixproject.domain.powerloss.PowerLossObservation +import com.devil.phoenixproject.domain.powerloss.PowerLossProtocolFamily +import com.devil.phoenixproject.domain.powerloss.ProtocolRepBounds +import com.devil.phoenixproject.domain.powerloss.PowerStopReason +import com.devil.phoenixproject.domain.powerloss.TargetMode +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Issue #1392 (P3) — immutable winner latch + evidence capture tests. + * + * Drives [PowerLossSetController.onObservation] with sealed observations and + * asserts the deep-frozen evidence/summary contracts: both qualification facts + * persisted (SD2), SHORT_ROM-over-POWER_LOSS tie-break, trusted short-ROM with + * null MCP qualifies while unavailable power alone never does (SD1), warmups + * excluded, reference-at-decision frozen (SD3), winner latched once, and + * null-vs-zero preserved (missing MCP is null, never 0). + */ +class PowerLossSetEvidenceLatchTest { + + private val config = PowerLossConfig( + targetMode = TargetMode.POWER, + thresholdPercent = 20, + maxWorkingReps = 20, + requireTwoConsecutive = false, + savedNominalReps = 12, + ) + + private val plan: ExecutionTargetPlan = requireNotNull( + ExecutionTargetPlan.derive( + config = config, + bounds = ProtocolRepBounds( + maxRepresentableWorkingReps = 254, + protocolIdentityFinite = true, + ), + warmupSetCount = 0, + now = 0L, + ), + ) + + private fun obs( + ordinal: Int, + mcp: Float?, + romA: CableRom = CableRom.trusted(100f), + romB: CableRom = CableRom.trusted(100f), + isWarmup: Boolean = false, + ): PowerLossObservation = PowerLossObservation( + workingConcentricOrdinal = if (isWarmup) 0 else ordinal, + isWarmup = isWarmup, + mcpWatts = mcp, + romA = romA, + romB = romB, + activeCables = setOf(PowerCable.A, PowerCable.B), + ) + + @Test + fun powerNeverArmedProducesNoEvidence() { + val controller = PowerLossSetController() + assertNull(controller.buildEvidence("s1", "set1"), "never-armed controller must not fabricate evidence") + assertNull(controller.buildSummaryFacts(0), "never-armed controller must not fabricate summary facts") + } + + @Test + fun warmupsNeitherTallyNorEstablishReference() { + val controller = PowerLossSetController() + val warmupDecision = controller.onObservation(config, plan, obs(0, mcp = 100f, isWarmup = true)) + assertTrue(warmupDecision is PowerLossDecision.Continue, "warmup must never trigger") + // One working rep with unavailable power: the evidence must contain exactly + // that working attempt — the warmup row must not tally or establish anything. + controller.onObservation(config, plan, obs(1, mcp = null)) + val evidence = assertNotNull(controller.buildEvidence("s1", "set1")) + assertEquals(1, evidence.attempts.size, "warmups must not become attempt rows") + assertEquals(1, evidence.attempts.single().workingConcentricOrdinal) + assertNull(evidence.referenceWorkingOrdinal, "warmups must not establish the reference") + assertNull(evidence.winnerReason, "unavailable power alone must not stop") + } + + @Test + fun shortRomWinsPowerLossWithBothFactsPersisted() { + val controller = PowerLossSetController() + controller.onObservation(config, plan, obs(1, mcp = 100f)) + val decision = controller.onObservation( + config, + plan, + obs(2, mcp = 50f, romA = CableRom.trusted(50f)), // 50% loss AND 50% ROM + ) + assertTrue(decision is PowerLossDecision.Stop, "simultaneous fatigue facts must stop") + assertEquals(PowerStopReason.SHORT_ROM, decision.reason, "SD2: SHORT_ROM wins the tie-break") + assertTrue(decision.shortRomQualified && decision.powerLossQualified, "SD2: both facts must qualify") + + val evidence = assertNotNull(controller.buildEvidence("s1", "set1")) + assertEquals(PowerStopReason.SHORT_ROM, evidence.winnerReason) + assertTrue(evidence.shortRomObserved && evidence.powerLossObserved, "SD2: both facts persisted") + assertEquals(2, evidence.triggerWorkingOrdinal) + assertEquals(1, evidence.referenceWorkingOrdinal, "SD3: reference-at-decision frozen") + assertNotNull(evidence.lossPercentAtDecision) + assertEquals(50.0, evidence.lossPercentAtDecision!!.toDouble(), 0.01, "unrounded loss at decision") + } + + @Test + fun trustedShortRomWithNullMcpQualifies() { + val controller = PowerLossSetController() + controller.onObservation(config, plan, obs(1, mcp = 100f)) + val decision = controller.onObservation( + config, + plan, + obs(2, mcp = null, romA = CableRom.trusted(50f)), + ) + assertTrue(decision is PowerLossDecision.Stop, "SD1: trusted short-ROM survives missing power") + assertEquals(PowerStopReason.SHORT_ROM, decision.reason) + val evidence = assertNotNull(controller.buildEvidence("s1", "set1")) + assertTrue(evidence.shortRomObserved) + assertFalse(evidence.powerLossObserved, "unavailable power alone never qualifies (SD1)") + assertNull(evidence.attempts.last().mcpWatts, "missing MCP stays null — never a fabricated zero") + } + + @Test + fun unavailablePowerWithFullRomDoesNotStop() { + val controller = PowerLossSetController() + controller.onObservation(config, plan, obs(1, mcp = 100f)) + val decision = controller.onObservation(config, plan, obs(2, mcp = null)) + assertTrue(decision is PowerLossDecision.Continue, "neither qualifying reason must not stop") + val evidence = assertNotNull(controller.buildEvidence("s1", "set1")) + assertNull(evidence.winnerReason) + assertEquals(2, evidence.attempts.size) + } + + @Test + fun winnerIsLatchedOnceAndNeverOverwritten() { + val controller = PowerLossSetController() + controller.onObservation(config, plan, obs(1, mcp = 100f)) + controller.onObservation(config, plan, obs(2, mcp = 50f, romA = CableRom.trusted(50f))) + // A later worse observation must not move the latched winner/trigger facts. + controller.onObservation(config, plan, obs(3, mcp = 10f, romA = CableRom.trusted(10f))) + val evidence = assertNotNull(controller.buildEvidence("s1", "set1")) + assertEquals(PowerStopReason.SHORT_ROM, evidence.winnerReason, "winner latched at first stop") + assertEquals(2, evidence.triggerWorkingOrdinal, "trigger frozen at decision time") + } + + @Test + fun summaryFactsMapHeadlineNumbers() { + val controller = PowerLossSetController() + controller.onObservation(config, plan, obs(1, mcp = 100f)) + controller.onObservation(config, plan, obs(2, mcp = 50f, romA = CableRom.trusted(50f))) + val facts = assertNotNull(controller.buildSummaryFacts(completedRepCount = 1)) + assertEquals(1, facts.completedRepCount, "completed count comes from actualReps, never promoted") + assertEquals(2, facts.stoppedAtWorkingAttempt) + assertEquals(1, facts.bestWorkingOrdinal) + assertEquals(20, facts.thresholdPercent) + assertEquals(20, facts.maxWorkingReps) + } + + @Test + fun capBackstopWinnerCarriedThrough() { + val controller = PowerLossSetController() + controller.onObservation(config, plan, obs(1, mcp = 100f)) + val capped = ExecutionTargetPlan.derive( + config = config.copy(maxWorkingReps = 2), + bounds = ProtocolRepBounds(maxRepresentableWorkingReps = 254, protocolIdentityFinite = true), + warmupSetCount = 0, + now = 0L, + )!! + val decision = controller.onObservation(capped = true, plan = capped, observation = obs(2, mcp = 100f)) + // Cap is enforced by the reducer through the plan; whatever it decides, + // the latch must carry MAX_REPS_BACKSTOP verbatim when it stops. + if (decision is PowerLossDecision.Stop) { + assertEquals(PowerStopReason.MAX_REPS_BACKSTOP, decision.reason) + val evidence = assertNotNull(controller.buildEvidence("s1", "set1")) + assertEquals(PowerStopReason.MAX_REPS_BACKSTOP, evidence.winnerReason) + } + } +} + +/** Small shim so the cap fixture reads clearly at the call site. */ +private fun PowerLossSetController.onObservation( + capped: Boolean, + plan: ExecutionTargetPlan, + observation: PowerLossObservation, +): PowerLossDecision = onObservation( + config = PowerLossConfig( + targetMode = TargetMode.POWER, + thresholdPercent = 20, + maxWorkingReps = if (capped) 2 else 20, + requireTwoConsecutive = false, + savedNominalReps = 12, + ), + plan = plan, + observation = observation, +) diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossSummaryFactsWiringTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossSummaryFactsWiringTest.kt new file mode 100644 index 000000000..effd256d5 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossSummaryFactsWiringTest.kt @@ -0,0 +1,103 @@ +package com.devil.phoenixproject.presentation.manager + +import com.devil.phoenixproject.domain.powerloss.CableRom +import com.devil.phoenixproject.domain.powerloss.ExecutionTargetPlan +import com.devil.phoenixproject.domain.powerloss.PowerCable +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.PowerLossObservation +import com.devil.phoenixproject.domain.powerloss.ProtocolRepBounds +import com.devil.phoenixproject.domain.powerloss.PowerStopReason +import com.devil.phoenixproject.domain.powerloss.TargetMode +import com.devil.phoenixproject.presentation.powerloss.PowerLossUiFacts +import com.devil.phoenixproject.presentation.powerloss.PowerLossUiCopy +import com.devil.phoenixproject.presentation.powerloss.powerLossSummaryUi +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertTrue + +/** + * Issue #1392 — summary facts wiring (ui-spec F05/F06, SD6). + * + * The live summary projection takes `WorkoutState.SetSummary.powerLoss` + * (frozen by the engine via [PowerLossSetController.buildSummaryFacts]) and + * renders the `Stopped at rep 9 — 21% power loss (best: rep 2)` headline, its + * adjacent completed/attempt clarification, and the per-attempt `Power details` + * table. This test pins that chain end-to-end so the summary block can never + * render empty while facts are present (the P7 gap). + */ +class PowerLossSummaryFactsWiringTest { + + private val config = PowerLossConfig( + targetMode = TargetMode.POWER, + thresholdPercent = 20, + maxWorkingReps = 20, + requireTwoConsecutive = false, + savedNominalReps = 12, + ) + + private val plan: ExecutionTargetPlan = requireNotNull( + ExecutionTargetPlan.derive( + config = config, + bounds = ProtocolRepBounds( + maxRepresentableWorkingReps = 254, + protocolIdentityFinite = true, + ), + warmupSetCount = 0, + now = 0L, + ), + ) + + private fun obs(ordinal: Int, mcp: Float?): PowerLossObservation = PowerLossObservation( + workingConcentricOrdinal = ordinal, + isWarmup = false, + mcpWatts = mcp, + romA = CableRom.trusted(100f), + romB = CableRom.trusted(100f), + activeCables = setOf(PowerCable.A, PowerCable.B), + ) + + /** Drive a §6 representative fixture: best rep 2 @300 W, stop at rep 9 (21%). */ + private fun fixtureController(): PowerLossSetController { + val controller = PowerLossSetController() + controller.onObservation(config, plan, obs(1, mcp = 285f)) + controller.onObservation(config, plan, obs(2, mcp = 300f)) + controller.onObservation(config, plan, obs(3, mcp = 293.4f)) + controller.onObservation(config, plan, obs(4, mcp = 281.4f)) + controller.onObservation(config, plan, obs(5, mcp = 272.4f)) + controller.onObservation(config, plan, obs(6, mcp = 263.4f)) + controller.onObservation(config, plan, obs(7, mcp = 251.4f)) + controller.onObservation(config, plan, obs(8, mcp = 245.4f)) + controller.onObservation(config, plan, obs(9, mcp = 236.4f)) + return controller + } + + @Test + fun summaryFactsCarrySavedNominalRepsFromConfig() { + val facts = assertNotNull(fixtureController().buildSummaryFacts(completedRepCount = 8)) + assertEquals(12, facts.savedNominalReps, "SD6 Saved reps readback comes from the frozen config") + assertEquals(PowerStopReason.POWER_LOSS, facts.winnerReason) + assertEquals(9, facts.stoppedAtWorkingAttempt) + assertEquals(8, facts.completedRepCount, "completed count comes from actualReps, never promoted") + } + + @Test + fun summaryUiRendersHeadlineClarificationAndTableFromFacts() { + val facts = assertNotNull(fixtureController().buildSummaryFacts(completedRepCount = 8)) + // The summary adapter passes facts through unchanged; the UI derives all copy + // (including the Saved reps readback) from the frozen facts alone. + val ui = powerLossSummaryUi(PowerLossUiFacts.summaryFacts(facts)!!) + assertEquals("Stopped at rep 9 — 21% power loss (best: rep 2)", ui.headline) + assertEquals("8 completed reps · lifting attempt 9", ui.clarification) + assertEquals("Saved reps: 12", ui.savedRepsHeader) + assertEquals("Power-loss target active", ui.powerActiveBadge) + // Per-attempt table (Power details) has one row per working attempt. + assertEquals(9, ui.table.rows.size, "per-attempt table carries every working attempt") + assertTrue(ui.table.coreRows.isNotEmpty()) + assertEquals(PowerLossUiCopy.DETAILS_CAPTION, ui.table.caption) + // Row detail pairs expose reference-at-decision and ROM facts for expansion. + val triggerRow = ui.table.rows.first { it.attemptLabel == "9" } + assertTrue(triggerRow.details.any { it.first == PowerLossUiCopy.COL_REFERENCE }) + assertTrue(triggerRow.badges.contains(PowerLossUiCopy.BADGE_TRIGGER)) + } +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossSummaryWinnerFallbackTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossSummaryWinnerFallbackTest.kt new file mode 100644 index 000000000..82129d458 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/PowerLossSummaryWinnerFallbackTest.kt @@ -0,0 +1,135 @@ +package com.devil.phoenixproject.presentation.manager + +import com.devil.phoenixproject.domain.powerloss.CableRom +import com.devil.phoenixproject.domain.powerloss.ExecutionTargetPlan +import com.devil.phoenixproject.domain.powerloss.PowerCable +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.PowerLossObservation +import com.devil.phoenixproject.domain.powerloss.PowerStopReason +import com.devil.phoenixproject.domain.powerloss.ProtocolRepBounds +import com.devil.phoenixproject.domain.powerloss.TargetMode +import com.devil.phoenixproject.presentation.powerloss.PowerLossSummaryVariant +import com.devil.phoenixproject.presentation.powerloss.PowerLossUiCopy +import com.devil.phoenixproject.presentation.powerloss.powerLossSummaryUi +import com.devil.phoenixproject.presentation.powerloss.powerLossSummaryVariant +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +/** + * Issue #1392 — summary winner fallback (ui-spec §6 / SD2 + SD4). + * + * The one-winner completion latch can fire from the machine-counter path + * (`RepType.WORKOUT_COMPLETE → handleSetCompletion(MAX_REPS_BACKSTOP)`) BEFORE + * the final rep's metric evaluation latches the policy winner. P7 field QA on + * the implementation branch caught the consequence: the cap summary card + * silently degraded to the MANUAL variant and dropped its signed-off + * `Stopped at 20 working reps — max-reps limit` headline plus SD6 + * clarification. The committed completion reason is the winner of record when + * the latch is empty; the latched policy winner itself is never overwritten + * (SD2). + */ +class PowerLossSummaryWinnerFallbackTest { + + private val config = PowerLossConfig( + targetMode = TargetMode.POWER, + thresholdPercent = 20, + maxWorkingReps = 20, + requireTwoConsecutive = false, + savedNominalReps = 10, + ) + + private val plan: ExecutionTargetPlan = requireNotNull( + ExecutionTargetPlan.derive( + config = config, + bounds = ProtocolRepBounds( + maxRepresentableWorkingReps = 254, + protocolIdentityFinite = true, + ), + warmupSetCount = 0, + now = 0L, + ), + ) + + private fun obs(ordinal: Int, mcp: Float?): PowerLossObservation = PowerLossObservation( + workingConcentricOrdinal = ordinal, + isWarmup = false, + mcpWatts = mcp, + romA = CableRom.trusted(100f), + romB = CableRom.trusted(100f), + activeCables = setOf(PowerCable.A, PowerCable.B), + ) + + @Test + fun `machine counter completion keeps the max reps headline`() { + val controller = PowerLossSetController() + controller.onObservation(config, plan, obs(1, mcp = 100f)) + controller.onObservation(config, plan, obs(2, mcp = 100f)) + + // No policy winner latched: the machine-counter completion claimed the + // one-winner latch first (SD4). The committed reason is the winner. + val facts = assertNotNull( + controller.buildSummaryFacts( + completedRepCount = 20, + fallbackWinnerReason = PowerStopReason.MAX_REPS_BACKSTOP, + ), + ) + assertEquals(PowerStopReason.MAX_REPS_BACKSTOP, facts.winnerReason) + assertEquals(20, facts.stoppedAtWorkingAttempt, "the cap attempt is the trigger of record") + + val ui = powerLossSummaryUi(facts) + assertEquals(PowerLossSummaryVariant.MAX_REPS_BACKSTOP, powerLossSummaryVariant(facts)) + assertEquals("Stopped at 20 working reps — max-reps limit", ui.headline) + assertEquals(PowerLossUiCopy.summaryClarification(20, 20), ui.clarification) + } + + @Test + fun `latched policy winner is never replaced by the completion fallback`() { + val controller = PowerLossSetController() + // Rep 1 establishes the reference; rep 2 loses 50% and latches POWER_LOSS. + controller.onObservation(config, plan, obs(1, mcp = 130.8f)) + controller.onObservation(config, plan, obs(2, mcp = 65.4f)) + + val facts = assertNotNull( + controller.buildSummaryFacts( + completedRepCount = 2, + fallbackWinnerReason = PowerStopReason.MAX_REPS_BACKSTOP, + ), + ) + assertEquals(PowerStopReason.POWER_LOSS, facts.winnerReason, "SD2: the latched winner stands") + assertEquals(2, facts.stoppedAtWorkingAttempt) + } + + @Test + fun `manual and safety completions never forge a power winner`() { + val controller = PowerLossSetController() + controller.onObservation(config, plan, obs(1, mcp = 100f)) + + // A non-power-vocabulary completion (manual, stall, safety, timer) has + // no power winner — the MANUAL variant keeps its existing null headline. + val facts = assertNotNull(controller.buildSummaryFacts(completedRepCount = 1)) + assertNull(facts.winnerReason) + assertNull(facts.stoppedAtWorkingAttempt) + val ui = powerLossSummaryUi(facts) + assertNull(ui.headline, "no power-policy winner means no power headline") + } + + @Test + fun `evidence records the same committed winner as the summary`() { + val controller = PowerLossSetController() + controller.onObservation(config, plan, obs(1, mcp = 100f)) + controller.onObservation(config, plan, obs(2, mcp = 100f)) + + val evidence = assertNotNull( + controller.buildEvidence( + sessionId = "s", + setId = "set-1", + fallbackWinnerReason = PowerStopReason.MAX_REPS_BACKSTOP, + fallbackStoppedAtAttempt = 20, + ), + ) + assertEquals(PowerStopReason.MAX_REPS_BACKSTOP, evidence.winnerReason) + assertEquals(20, evidence.triggerWorkingOrdinal) + } +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/RestoredRuntimeDuplicateResumeAuthorityTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/RestoredRuntimeDuplicateResumeAuthorityTest.kt index fd028a178..83c6810f1 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/RestoredRuntimeDuplicateResumeAuthorityTest.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/manager/RestoredRuntimeDuplicateResumeAuthorityTest.kt @@ -2,9 +2,19 @@ package com.devil.phoenixproject.presentation.manager import com.devil.phoenixproject.data.repository.ActiveWorkoutRuntimeDocument import com.devil.phoenixproject.data.repository.ActiveWorkoutRuntimeResumeResult +import com.devil.phoenixproject.data.repository.PowerLossRestartExplanation +import com.devil.phoenixproject.data.repository.PowerLossRestartRecovery +import com.devil.phoenixproject.data.repository.RestoredPowerLossRuntimeSnapshot import com.devil.phoenixproject.data.repository.RestoredRetrySourceAuthoritySnapshot import com.devil.phoenixproject.data.repository.RestoredTeardownSeedSnapshot import com.devil.phoenixproject.data.repository.RestoredWorkoutCommandTemplateSnapshot +import com.devil.phoenixproject.domain.powerloss.CableRom +import com.devil.phoenixproject.domain.powerloss.ExecutionTargetPlan +import com.devil.phoenixproject.domain.powerloss.PowerCable +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.PowerLossObservation +import com.devil.phoenixproject.domain.powerloss.ProtocolRepBounds +import com.devil.phoenixproject.domain.powerloss.TargetMode import com.devil.phoenixproject.domain.model.CompletedSet import com.devil.phoenixproject.domain.model.LogicalSetKey import com.devil.phoenixproject.domain.model.PlannedSetAttemptState @@ -82,6 +92,103 @@ class RestoredRuntimeDuplicateResumeAuthorityTest { } } + @Test + fun `interrupted power loss runtime rebaselines on resume with no machine commands`() = runTest { + val harness = DWSMTestHarness(this) + try { + // An armed power-loss runtime snapshot with incomplete samples survives the + // crash; after restart the armed policy must NEVER resume — the accumulator, + // baseline and streak are rebaselined with the explanatory UX state, and the + // restore path issues NO automatic machine commands (existing invariant). + val armedSnapshot = RestoredPowerLossRuntimeSnapshot( + codecVersion = RestoredPowerLossRuntimeSnapshot.CURRENT_CODEC_VERSION, + targetModeName = "POWER", + thresholdPercent = 25, + maxWorkingReps = 15, + requireTwoConsecutive = true, + savedNominalReps = 12, + baselineMcpWatts = 312.5f, + referenceWorkingOrdinal = 2, + qualifyingStreak = 1, + sealedObservationCount = 3, + expectedObservationCount = 4, + samplesComplete = false, + restartExplanationName = "INCOMPLETE_SAMPLES", + ) + val installed = installRuntime( + harness = harness, + routineSessionId = "power-loss-interrupted-restart", + dormantTimer = DormantTimer.PAUSED, + powerLoss = armedSnapshot, + ) + + val commandsBefore = harness.fakeBleRepo.commandsReceived.size + val workoutParametersBefore = harness.fakeBleRepo.programCommands.size + val stopWorkoutCallsBefore = harness.fakeBleRepo.stopWorkoutCallCount + + assertIs( + harness.dwsm.resumeRoutine(installed.handle), + ) + runCurrent() + + // No automatic machine commands on restore beyond the restore baseline. + assertEquals( + commandsBefore, + harness.fakeBleRepo.commandsReceived.size, + "commands after resume: ${harness.fakeBleRepo.commandsReceived}", + ) + assertEquals(workoutParametersBefore, harness.fakeBleRepo.programCommands.size) + // The only machine-facing call on restore is the established safety + // teardown stop (MachineTeardownState.Ready path): nothing is started, + // no workout program is sent, and no other machine command is issued. + assertEquals(stopWorkoutCallsBefore + 1, harness.fakeBleRepo.stopWorkoutCallCount) + + // The armed policy is never resumed; every part of the policy state is reset + // and the explanatory UX state comes from the snapshot. + val recovery = PowerLossRestartRecovery.rebaselineOnRestart(installed.document.powerLoss) + assertEquals(false, recovery.resumeArmed) + assertEquals(true, recovery.baselineReset) + assertEquals(true, recovery.streakReset) + assertEquals(true, recovery.accumulatorReset) + assertEquals(PowerLossRestartExplanation.INCOMPLETE_SAMPLES, recovery.explanation) + + // The production controller entry resets the live reducer state too. + val controller = PowerLossSetController() + val seeded = controller.onObservation( + config = PowerLossConfig(targetMode = TargetMode.POWER, thresholdPercent = 25, maxWorkingReps = 15), + plan = requireNotNull( + ExecutionTargetPlan.derive( + config = PowerLossConfig(targetMode = TargetMode.POWER, thresholdPercent = 25, maxWorkingReps = 15), + bounds = ProtocolRepBounds(maxRepresentableWorkingReps = 60, protocolIdentityFinite = true), + warmupSetCount = 0, + now = 0L, + ), + ), + observation = PowerLossObservation( + workingConcentricOrdinal = 1, + isWarmup = false, + mcpWatts = 312.5f, + romA = CableRom.trusted(420f), + romB = CableRom.trusted(415f), + activeCables = setOf(PowerCable.A, PowerCable.B), + ), + ) + assertNotNull(seeded) + assertNotNull(controller.buildEvidence("session-x", "set-x")) + + val state = controller.restoreFromSnapshot(installed.document.powerLoss) + assertEquals(false, state.resumeArmed) + assertEquals(PowerLossRestartExplanation.INCOMPLETE_SAMPLES, state.explanation) + assertNull( + controller.buildEvidence("session-x", "set-x"), + "restart/rebaseline resets the accumulator baseline and streak", + ) + } finally { + harness.cleanup() + runCurrent() + } + } + private enum class DormantTimer { PAUSED, EXPIRED } private data class InstalledRuntime( @@ -146,6 +253,7 @@ class RestoredRuntimeDuplicateResumeAuthorityTest { harness: DWSMTestHarness, routineSessionId: String, dormantTimer: DormantTimer, + powerLoss: RestoredPowerLossRuntimeSnapshot? = null, ): InstalledRuntime { harness.fakeBleRepo.simulateConnect("Vee_Test") val routine = WorkoutStateFixtures.createTestRoutine( @@ -170,6 +278,7 @@ class RestoredRuntimeDuplicateResumeAuthorityTest { logicalSetKey = logicalSetKey, dormantTimer = dormantTimer, nowEpochMs = harness.nowMs, + powerLoss = powerLoss, ) harness.fakeCompletedSetRepo.setSessionRoutine(sourceStableSessionId, routineSessionId) harness.fakeCompletedSetRepo.insertCompletedSet( @@ -206,6 +315,7 @@ class RestoredRuntimeDuplicateResumeAuthorityTest { logicalSetKey: LogicalSetKey, dormantTimer: DormantTimer, nowEpochMs: Long, + powerLoss: RestoredPowerLossRuntimeSnapshot? = null, ): ActiveWorkoutRuntimeDocument { val sourceExecutionId = "42" val plan = RestTransitionPlan.NormalAdvance( @@ -260,6 +370,7 @@ class RestoredRuntimeDuplicateResumeAuthorityTest { }, isRestPaused = dormantTimer == DormantTimer.PAUSED, originalRestDurationSeconds = 60, + powerLoss = powerLoss, ) } diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossConfigDraftTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossConfigDraftTest.kt new file mode 100644 index 000000000..0f5f940aa --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossConfigDraftTest.kt @@ -0,0 +1,248 @@ +package com.devil.phoenixproject.presentation.powerloss + +import com.devil.phoenixproject.domain.model.ProgramMode +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.PowerLossProtocolFamily +import com.devil.phoenixproject.domain.powerloss.TargetMode +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Issue #1392 P5 — config draft/commit/cancel semantics, presets, validation copy, + * mode-confirmation dialog, dormant/inert config and profile-default boundaries + * (ui-spec §3 with SD6 corrections). + */ +class PowerLossConfigDraftTest { + + private fun draft( + config: PowerLossConfig = PowerLossConfig.DEFAULT, + maxAllowed: Int = 254, + family: PowerLossProtocolFamily = PowerLossProtocolFamily.OLD_SCHOOL, + validated: Boolean = true, + ) = PowerLossConfigDraftState.seededFrom( + config = config, + maxAllowedWorkingReps = maxAllowed, + protocolFamily = family, + pairedSamplesValidated = validated, + ) + + @Test + fun `presets carry nonbreaking numeric-unit labels - no 10 percent or Custom splits`() { + val labels = ThresholdPreset.entries.map { it.nonbreakingLabel() } + assertEquals(listOf("10\u2060%", "20\u2060%", "30\u2060%", "Cus\u2060tom"), labels) + // The label glyphs stay `10%` / `Custom` while the word joiner blocks breaks. + labels.forEach { label -> + assertTrue(label.contains(PowerLossUiCopy.WJ), "Preset $label must block line breaks") + } + assertEquals("10%", ThresholdPreset.P10.nonbreakingLabel().replace(PowerLossUiCopy.WJ, "")) + assertEquals("Custom", ThresholdPreset.CUSTOM.nonbreakingLabel().replace(PowerLossUiCopy.WJ, "")) + } + + @Test + fun `custom threshold validation keeps the draft and shows the exact error`() { + val state = draft().selectPreset(ThresholdPreset.CUSTOM) + for (bad in listOf("", "4", "41", "12.5", "abc")) { + val next = state.updateCustomThreshold(bad) + assertEquals(PowerLossUiCopy.CUSTOM_THRESHOLD_ERROR, next.customThresholdError, "input=$bad") + // Draft (last valid) is kept while invalid. + assertEquals(20, next.draft.thresholdPercent) + } + val ok = state.updateCustomThreshold("35") + assertNull(ok.customThresholdError) + assertEquals(35, ok.draft.thresholdPercent) + } + + @Test + fun `preset tap replaces an invalid custom draft and clears the error`() { + val state = draft().selectPreset(ThresholdPreset.CUSTOM).updateCustomThreshold("99") + assertNotNull(state.customThresholdError) + val next = state.selectPreset(ThresholdPreset.P30) + assertNull(next.customThresholdError) + assertEquals(30, next.draft.thresholdPercent) + } + + @Test + fun `persistent caution at 36-40 - none at 35`() { + val base = draft().selectPreset(ThresholdPreset.CUSTOM) + assertTrue(base.updateCustomThreshold("36").highThresholdCautionVisible) + assertTrue(base.updateCustomThreshold("40").highThresholdCautionVisible) + assertFalse(base.updateCustomThreshold("35").highThresholdCautionVisible) + assertEquals(PowerLossUiCopy.HIGH_THRESHOLD_TITLE, PowerLossUiCopy.HIGH_THRESHOLD_TITLE) + // Caution never disables Apply. + assertTrue(base.updateCustomThreshold("38").canApply) + } + + @Test + fun `max working reps uses the dynamic bound helper copy`() { + val state = draft(maxAllowed = 30) + assertNull(state.maxRepsError) + assertEquals("Enter 2–30 working reps.", PowerLossUiCopy.maxWorkingRepsError(30)) + val invalid = state.updateMaxReps("31") + assertEquals("Enter 2–30 working reps.", invalid.maxRepsError) + val tooSmall = state.updateMaxReps("1") + assertEquals("Enter 2–30 working reps.", tooSmall.maxRepsError) + assertNull(state.updateMaxReps("2").maxRepsError) + assertNull(state.updateMaxReps("30").maxRepsError) + // Impossible plan (bound below the minimum) still validates against the bound. + val impossible = draft(maxAllowed = 1).updateMaxReps("2") + assertEquals("Enter 2–1 working reps.", impossible.maxRepsError) + } + + @Test + fun `two-consecutive helper copy is SD1-corrected`() { + assertEquals( + "One qualifying working rep can end the set, starting with the second working attempt.", + PowerLossUiCopy.TWO_CONSECUTIVE_OFF_HELPER, + ) + val on = PowerLossUiCopy.TWO_CONSECUTIVE_ON_HELPER + assertTrue(on.contains("neither qualifying reason"), "SD1: unavailable attempt = neither qualifying reason") + assertFalse(on.contains("null-MCP"), "SD1: never 'any null-MCP observation'") + assertTrue(on.contains("resets the count")) + } + + @Test + fun `near-limit cue readback floors at first positive power loss`() { + assertEquals("Near-limit cue: first positive power loss", PowerLossUiCopy.nearLimitCueReadback(5)) + assertEquals("Near-limit cue: 15% loss", PowerLossUiCopy.nearLimitCueReadback(20)) + assertEquals("Near-limit cue: 25% loss", PowerLossUiCopy.nearLimitCueReadback(30)) + } + + @Test + fun `apply commits atomically - cancel restores the original`() { + val original = PowerLossConfig( + targetMode = TargetMode.POWER, + thresholdPercent = 20, + maxWorkingReps = 20, + requireTwoConsecutive = false, + savedNominalReps = 12, + ) + val edited = draft(original) + .selectPreset(ThresholdPreset.P30) + .setRequireTwoConsecutive(true) + assertEquals(original, edited.committed, "Nothing commits before Apply") + val applied = edited.apply() + assertEquals(30, applied.committed.thresholdPercent) + assertTrue(applied.committed.requireTwoConsecutive) + assertEquals(12, applied.committed.savedNominalReps, "Saved nominal reps survive edits") + + val cancelled = edited.cancel() + assertEquals(original, cancelled.draft, "Cancel restores the original target/settings") + } + + @Test + fun `apply refuses while a field is invalid`() { + val state = draft().selectPreset(ThresholdPreset.CUSTOM).updateCustomThreshold("41") + val applied = state.apply() + assertEquals(PowerLossConfig.DEFAULT.thresholdPercent, applied.committed.thresholdPercent) + assertFalse(applied.canApply) + } + + @Test + fun `toggling REP to POWER preserves dormant values and nominal reps`() { + val state = draft( + PowerLossConfig( + targetMode = TargetMode.REP_TARGET, + thresholdPercent = 30, + maxWorkingReps = 15, + savedNominalReps = 12, + ), + ).selectTargetMode(TargetMode.POWER) + assertEquals(TargetMode.POWER, state.draft.targetMode) + assertEquals(30, state.draft.thresholdPercent) + assertEquals(15, state.draft.maxWorkingReps) + assertEquals(12, state.draft.savedNominalReps) + } + + @Test + fun `unsupported-mode switch demands confirmation and cancellation preserves state`() { + val state = draft(family = PowerLossProtocolFamily.UNSUPPORTED) + val confirmed = state.selectTargetMode(TargetMode.POWER) + assertNotNull(confirmed.pendingModeConfirmation, "POWER is not available in excluded modes") + assertEquals(PowerLossUiCopy.MODE_CONFIRMATION_TITLE, confirmed.pendingModeConfirmation.title) + assertEquals(PowerLossUiCopy.MODE_CONFIRMATION_CANCEL, confirmed.pendingModeConfirmation.cancelAction) + assertEquals(PowerLossUiCopy.MODE_CONFIRMATION_CONFIRM, confirmed.pendingModeConfirmation.confirmAction) + assertTrue( + confirmed.pendingModeConfirmation.body.startsWith("Power-loss target is not available for "), + ) + + // Keep current mode: mode and target preserved. + val kept = confirmed.dismissModeConfirmation() + assertNull(kept.pendingModeConfirmation) + assertEquals(TargetMode.REP_TARGET, kept.draft.targetMode) + + // Use Rep target: effective REP with settings kept. + val rep = confirmed.confirmUseRepTarget() + assertEquals(TargetMode.REP_TARGET, rep.draft.targetMode) + assertTrue(rep.incompatibleSavedPowerConfig, "Saved POWER config is retained but inert") + } + + @Test + fun `capability unavailable state is dormant and inert`() { + val state = draft(validated = false) + val power = state.selectTargetMode(TargetMode.POWER) + assertEquals(TargetMode.REP_TARGET, power.effectiveTargetMode, "POWER never arms without capability") + assertTrue(power.dormantPowerConfig, "Retained-but-inert POWER config") + assertFalse(power.powerSectionExpanded) + assertEquals(PowerLossUiCopy.CAPABILITY_UNAVAILABLE, PowerLossUiCopy.CAPABILITY_UNAVAILABLE) + assertEquals(PowerLossUiCopy.CAPABILITY_UNAVAILABLE_SECONDARY, PowerLossUiCopy.CAPABILITY_UNAVAILABLE_SECONDARY) + } + + @Test + fun `unsupported family keeps saved power config inert with the banner`() { + val state = draft( + config = PowerLossConfig(targetMode = TargetMode.POWER, savedNominalReps = 12), + family = PowerLossProtocolFamily.UNSUPPORTED, + ) + assertEquals(TargetMode.REP_TARGET, state.effectiveTargetMode) + assertTrue(state.dormantPowerConfig) + assertTrue(state.incompatibleSavedPowerConfig) + assertEquals( + "Power-loss target is not active in this mode.", + PowerLossUiCopy.INCOMPATIBLE_SAVED_BANNER, + ) + } + + @Test + fun `profile defaults are scoped per profile - no cross-profile reuse`() { + val scope = PowerLossExecutionScope() + val configA = PowerLossConfig(targetMode = TargetMode.POWER, thresholdPercent = 30) + scope.rememberFor("profile-a", configA) + assertEquals(configA, scope.freezeForExecution("profile-a")) + assertEquals( + PowerLossConfig.DEFAULT, + scope.freezeForExecution("profile-b"), + "Ad-hoc choices apply to the current profile only (ui-spec §3)", + ) + } + + @Test + fun `saved reps header and readback copy match SD6`() { + assertEquals("Saved reps: 12", PowerLossUiCopy.savedRepsHeader(12)) + assertEquals("Power-loss target active", PowerLossUiCopy.POWER_ACTIVE_BADGE) + assertEquals( + "Saved rep target: 12 (not used for this set)", + PowerLossUiCopy.savedRepReadback(12), + ) + } + + @Test + fun `echo note and short-rom safeguard copy are fixed and non-toggleable`() { + assertEquals( + "Stopping uses lifting power only. Lowering power is logged separately when available.", + PowerLossUiCopy.ECHO_NOTE, + ) + assertEquals( + "Short range of motion also counts: below 85% of the best rep\u2019s movement on either active cable.", + PowerLossUiCopy.SHORT_ROM_SAFEGUARD, + ) + } + + @Test + fun `local-data disclosure ends with the portal deferral`() { + assertTrue(PowerLossUiCopy.LOCAL_DATA_DISCLOSURE.endsWith("they are not synced to the portal.")) + } +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossExportAndCopyGuardTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossExportAndCopyGuardTest.kt new file mode 100644 index 000000000..a1b3a8c57 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossExportAndCopyGuardTest.kt @@ -0,0 +1,137 @@ +package com.devil.phoenixproject.presentation.powerloss + +import com.devil.phoenixproject.domain.model.ProgramMode +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.PowerLossProtocolFamily +import com.devil.phoenixproject.domain.powerloss.TargetMode +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Issue #1392 P5 — export entry/legacy omission disclosure and the copy-content + * guard (no physiological/RPE/efficacy claims, no verified-audible-playback + * claims), plus the strict persisted-enum reader (unknown target enum NEVER + * arms POWER). + */ +class PowerLossExportAndCopyGuardTest { + + @Test + fun `export entry and legacy omission disclosure are exact`() { + val export = PowerLossExportUi() + assertEquals("Export power data", export.entryLabel) + assertEquals( + "This format does not include power-loss settings or per-attempt details. Use power-data export to keep them.", + export.legacyOmissionDisclosure, + ) + assertEquals("Choose power-data export", export.choosePowerDataExportAction) + assertEquals("Export without power details", export.exportWithoutPowerDetailsAction) + } + + @Test + fun `legacy export confirmation surfaces the disclosure before running`() { + val confirmation = legacyExportConfirmation() + assertTrue(confirmation.visible) + assertEquals(PowerLossUiCopy.LEGACY_EXPORT_DISCLOSURE, confirmation.disclosure) + } + + @Test + fun `copy contains no physiological rpe or efficacy claims`() { + val banned = listOf("RPE", "rpe", "efficacy", "effective for", "muscle", "hypertrophy", "strength gain", "research-backed", "burns", "fat loss") + allCopy().forEach { copy -> + banned.forEach { term -> + assertFalse(copy.contains(term), "Copy must not contain '$term': $copy") + } + } + } + + @Test + fun `copy contains no verified audible playback claims`() { + val banned = listOf("guaranteed", "verified audible", "you will hear", "always audible", "audible playback") + allCopy().forEach { copy -> + banned.forEach { term -> + assertFalse(copy.contains(term), "Copy must not claim playback: $copy") + } + } + assertTrue( + PowerLossUiCopy.NEAR_LIMIT_CUE_HELP.contains("if sound is enabled"), + "Cue copy stays conditional on sound settings", + ) + } + + @Test + fun `unknown persisted target enum never arms POWER`() { + assertEquals(TargetMode.REP_TARGET, PowerLossCapabilityBridge.effectiveTargetMode(null)) + assertEquals(TargetMode.REP_TARGET, PowerLossCapabilityBridge.effectiveTargetMode("SUPER_SET")) + assertEquals(TargetMode.REP_TARGET, PowerLossCapabilityBridge.effectiveTargetMode("power")) + assertEquals(TargetMode.POWER, PowerLossCapabilityBridge.effectiveTargetMode("POWER")) + + val unknown = powerLossConfigFromPersisted( + persistedTargetMode = "TOTALLY_UNKNOWN", + thresholdPercent = 25, + savedNominalReps = 12, + ) + assertEquals(TargetMode.REP_TARGET, unknown.targetMode) + assertEquals(25, unknown.thresholdPercent, "Remaining persisted values are preserved") + } + + @Test + fun `propagation keeps POWER inert for unsupported protocol families`() { + val config = PowerLossConfig(targetMode = TargetMode.POWER, thresholdPercent = 25, maxWorkingReps = 15) + for (mode in listOf(ProgramMode.TUT, ProgramMode.TUTBeast, ProgramMode.EccentricOnly)) { + val settings = powerLossRuntimeSettingsFor( + config = config, + mode = mode, + pairedSamplesValidated = true, + ) + assertEquals(TargetMode.REP_TARGET, settings.targetMode, "mode=$mode must stay inert") + } + val supported = powerLossRuntimeSettingsFor( + config = config, + mode = ProgramMode.OldSchool, + savedNominalReps = 12, + pairedSamplesValidated = true, + ) + assertEquals(TargetMode.POWER, supported.targetMode) + assertEquals(12, supported.savedNominalReps) + assertTrue(supported.powerActive) + } + + @Test + fun `propagation respects the capability gate`() { + val settings = powerLossRuntimeSettingsFor( + config = PowerLossConfig(targetMode = TargetMode.POWER), + mode = ProgramMode.Echo, + pairedSamplesValidated = false, + ) + assertEquals(TargetMode.POWER, settings.targetMode, "Config intent is retained") + assertFalse(settings.powerActive, "POWER never arms without validated paired samples") + } + + private fun allCopy(): List = listOf( + PowerLossUiCopy.SECTION_HEADING, + PowerLossUiCopy.REP_HELPER, + PowerLossUiCopy.POWER_LEAD, + PowerLossUiCopy.POWER_HELP, + PowerLossUiCopy.CUSTOM_THRESHOLD_HELPER, + PowerLossUiCopy.CUSTOM_THRESHOLD_ERROR, + PowerLossUiCopy.HIGH_THRESHOLD_TITLE, + PowerLossUiCopy.HIGH_THRESHOLD_BODY, + PowerLossUiCopy.MAX_WORKING_REPS_HELPER, + PowerLossUiCopy.TWO_CONSECUTIVE_OFF_HELPER, + PowerLossUiCopy.TWO_CONSECUTIVE_ON_HELPER, + PowerLossUiCopy.SHORT_ROM_SAFEGUARD, + PowerLossUiCopy.SHORT_ROM_SAFEGUARD_HELP, + PowerLossUiCopy.ECHO_NOTE, + PowerLossUiCopy.NEAR_LIMIT_CUE_HELP, + PowerLossUiCopy.LOCAL_DATA_DISCLOSURE, + PowerLossUiCopy.INCOMPATIBLE_SAVED_BANNER, + PowerLossUiCopy.CAPABILITY_UNAVAILABLE, + PowerLossUiCopy.CAPABILITY_UNAVAILABLE_SECONDARY, + PowerLossUiCopy.SUMMARY_HELP, + PowerLossUiCopy.SUMMARY_UNAVAILABLE, + PowerLossUiCopy.SUMMARY_DISCLOSURE, + PowerLossUiCopy.LEGACY_EXPORT_DISCLOSURE, + ) +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossHistoryUiStateTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossHistoryUiStateTest.kt new file mode 100644 index 000000000..a372961dc --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossHistoryUiStateTest.kt @@ -0,0 +1,213 @@ +package com.devil.phoenixproject.presentation.powerloss + +import com.devil.phoenixproject.domain.powerloss.PowerCable +import com.devil.phoenixproject.domain.powerloss.PowerLossAttemptRecord +import com.devil.phoenixproject.domain.powerloss.PowerLossSetEvidence +import com.devil.phoenixproject.domain.powerloss.SampleQualityMarkers +import com.devil.phoenixproject.domain.powerloss.TargetMode +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** + * Issue #1392 P5 — history grouped + single-session views, attempt-only rows, + * per-rep columns and missing-data semantics (`—` with reason, never fabricated + * zeros; ui-spec §6). + */ +class PowerLossHistoryUiStateTest { + + private val evidence = PowerLossSetEvidence( + sessionId = "session-1", + setId = "set-1", + targetMode = TargetMode.POWER, + thresholdPercent = 20, + maxWorkingReps = 20, + requireTwoConsecutive = false, + savedNominalReps = 12, + activeCables = setOf(PowerCable.A, PowerCable.B), + activeCableProvenance = "warmup", + referenceWorkingOrdinal = 2, + referenceMcpWatts = 300f, + referenceRomAMm = 500f, + referenceRomBMm = 500f, + triggerWorkingOrdinal = 9, + winnerReason = com.devil.phoenixproject.domain.powerloss.PowerStopReason.POWER_LOSS, + shortRomObserved = false, + powerLossObserved = true, + lossPercentAtDecision = 21f, + attempts = listOf( + PowerLossAttemptRecord(1, completed = true, mcpWatts = 285f, lossPercentAtDecision = 0f, referenceWorkingOrdinal = 1), + PowerLossAttemptRecord(2, completed = true, mcpWatts = 300f, lossPercentAtDecision = 0f, referenceWorkingOrdinal = 2), + PowerLossAttemptRecord( + 9, + completed = false, + mcpWatts = 237f, + lossPercentAtDecision = 21f, + referenceWorkingOrdinal = 2, + eccentricPowerWatts = null, + quality = SampleQualityMarkers(), + ), + ), + ) + + @Test + fun `single-session view keeps attempt-only trigger rows visible`() { + val set = powerLossHistorySet(evidence) + assertTrue(set.coreRows.any { it.startsWith("9 ") || it.startsWith("9 ·") }, set.coreRows.toString()) + assertEquals( + "Working attempt 9 · Trigger observation — no completed rep recorded", + set.triggerOnlyRow, + ) + assertEquals("Target 20% · Max 20 working reps · Consecutive requirement off", set.headerLine) + } + + @Test + fun `attempt-only row shows pending status and trigger badge`() { + val table = powerLossHistorySet(evidence).table + val triggerRow = table.rows.first { it.attemptLabel == "9" } + assertEquals("Pending — not confirmed complete", triggerRow.statusText) + assertTrue(triggerRow.badges.contains("Trigger"), triggerRow.badges.toString()) + assertTrue(triggerRow.badges.contains("Best").not(), "Trigger 21% below best rep 2 is not Best") + } + + @Test + fun `missing data shows an em dash with a reason - never fabricated zeros`() { + val table = powerLossHistorySet(evidence).table + val triggerRow = table.rows.first { it.attemptLabel == "9" } + // Interrupted eccentric: null, not 0 W. + assertEquals("—", triggerRow.eccentricText) + assertEquals( + "Not recorded — set ended before lowering completed", + triggerRow.eccentricMissingReason, + ) + assertFalse(triggerRow.eccentricText.contains("0 W")) + } + + @Test + fun `true measured zero eccentric stays zero watts`() { + val row = powerLossRepTable( + attempts = listOf( + PowerLossAttemptRecord(1, completed = true, mcpWatts = 285f, eccentricPowerWatts = 0f, lossPercentAtDecision = 0f), + ), + triggerOrdinal = null, + bestWorkingOrdinal = 1, + thresholdPercent = 20, + nearLimitLossPercent = 15, + activeCables = setOf(PowerCable.A, PowerCable.B), + ).rows.single() + assertEquals("0 W", row.eccentricText) + } + + @Test + fun `per-rep columns carry attempt mcp loss reference rom con-ecc and status`() { + val row = powerLossRepTable( + attempts = listOf( + PowerLossAttemptRecord( + workingConcentricOrdinal = 3, + completed = true, + mcpWatts = 294f, + lossPercentAtDecision = 2f, + referenceWorkingOrdinal = 2, + romAMm = 500f, + romBMm = 500f, + romAPercentOfReference = 100f, + romBPercentOfReference = 100f, + romTrustworthy = true, + concentricDurationMs = 820L, + eccentricPowerWatts = 210f, + eccentricDurationMs = 1100L, + ), + ), + triggerOrdinal = null, + bestWorkingOrdinal = 2, + thresholdPercent = 20, + nearLimitLossPercent = 15, + activeCables = setOf(PowerCable.A, PowerCable.B), + ).rows.single() + assertEquals("3", row.attemptLabel) + assertEquals("294 W", row.mcpText) + assertEquals("2%", row.lossAtDecisionText) + assertEquals("2", row.referenceAtDecisionText) + assertEquals("500 mm · 100% of reference", row.romAText) + assertEquals("500 mm · 100% of reference", row.romBText) + assertEquals("0.8 s", row.concentricText) + assertEquals("210 W", row.eccentricText) + assertEquals("Completed", row.statusText) + } + + @Test + fun `untrusted rom and inactive cables use their explicit labels`() { + val row = powerLossRepTable( + attempts = listOf( + PowerLossAttemptRecord( + workingConcentricOrdinal = 1, + completed = true, + mcpWatts = 285f, + lossPercentAtDecision = 0f, + romAMm = 480f, + romAPercentOfReference = null, + romTrustworthy = false, + ), + ), + triggerOrdinal = null, + bestWorkingOrdinal = 1, + thresholdPercent = 20, + nearLimitLossPercent = 15, + activeCables = setOf(PowerCable.A), + ).rows.single() + assertEquals("480 mm · Unavailable — reference not established", row.romAText) + assertEquals("Not active", row.romBText) + } + + @Test + fun `invalid power row carries the quality reason and invalid badge`() { + val row = powerLossRepTable( + attempts = listOf( + PowerLossAttemptRecord( + workingConcentricOrdinal = 6, + completed = true, + mcpWatts = null, + lossPercentAtDecision = null, + quality = SampleQualityMarkers(gapBefore = true), + ), + ), + triggerOrdinal = null, + bestWorkingOrdinal = null, + thresholdPercent = 20, + nearLimitLossPercent = 15, + activeCables = setOf(PowerCable.A, PowerCable.B), + ).rows.single() + assertEquals("—", row.mcpText) + assertEquals("sample gap", row.mcpMissingReason) + assertTrue(row.badges.contains("Invalid")) + } + + @Test + fun `best and near-limit are text badges not color only`() { + val table = powerLossRepTable( + attempts = listOf( + PowerLossAttemptRecord(2, completed = true, mcpWatts = 300f, lossPercentAtDecision = 0f, referenceWorkingOrdinal = 2), + PowerLossAttemptRecord(7, completed = true, mcpWatts = 252f, lossPercentAtDecision = 16f, referenceWorkingOrdinal = 2), + ), + triggerOrdinal = null, + bestWorkingOrdinal = 2, + thresholdPercent = 20, + nearLimitLossPercent = 15, + activeCables = setOf(PowerCable.A, PowerCable.B), + ) + assertTrue(table.rows[0].badges.contains("Best")) + assertTrue(table.rows[1].badges.contains("Near-limit")) + } + + @Test + fun `grouped view aggregates sessions without dropping attempt rows`() { + val second = evidence.copy(sessionId = "session-2", setId = "set-2", triggerWorkingOrdinal = 5) + val grouped = listOf(evidence, second).map { powerLossHistorySet(it) } + assertEquals(2, grouped.size) + grouped.forEach { set -> + assertTrue(set.table.rows.isNotEmpty()) + assertTrue(set.coreRows.size == set.table.rows.size) + } + } +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossHudUiStateTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossHudUiStateTest.kt new file mode 100644 index 000000000..20dbd792c --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossHudUiStateTest.kt @@ -0,0 +1,188 @@ +package com.devil.phoenixproject.presentation.powerloss + +import com.devil.phoenixproject.domain.powerloss.PowerCable +import com.devil.phoenixproject.domain.powerloss.PowerLossHudState +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Issue #1392 P5 — HUD pending-vs-completed identity, near-limit once-only state, + * trusted short-ROM, invalid-power reasons, `Ending set…`, and SD6 readback + * (`Power-loss target · 20%` / `Max 20 working reps` — never `9 / 12`). + */ +class PowerLossHudUiStateTest { + + private fun hud( + attempt: Int = 9, + completed: Int = 8, + lastLoss: Float? = 16f, + invalidReason: String? = null, + lastValidAttempt: Int? = null, + endingSet: Boolean = false, + referenceEstablished: Boolean = true, + nearLimitCueEmitted: Boolean = false, + cableRom: Map = emptyMap(), + ) = PowerLossHudState( + powerActive = true, + thresholdPercent = 20, + nearLimitLossPercent = 15, + maxWorkingReps = 20, + savedNominalReps = 12, + currentAttemptOrdinal = attempt, + completedRepCount = completed, + referenceEstablished = referenceEstablished, + referenceWorkingOrdinal = 2, + lastLossPercent = lastLoss, + lastValidAttemptOrdinal = lastValidAttempt, + invalidPowerReason = invalidReason, + nearLimitCueEmitted = nearLimitCueEmitted, + cableRomPercentOfReference = cableRom, + endingSet = endingSet, + ) + + @Test + fun `readback is the target and cap - never a nominal rep fraction`() { + val ui = powerLossHudUi(hud(), latestPowerWatts = 252f, bestWatts = 300f) + assertEquals("Power-loss target · 20%", ui.targetReadback) + assertEquals("Max 20 working reps", ui.capReadback) + assertTrue(ui.nominalRepFractionHidden, "Never `9 / 12` from nominal reps") + assertEquals("Target 20% · cue from 15%", ui.thresholdLine) + } + + @Test + fun `pending attempt is never promoted to completed`() { + val ui = powerLossHudUi(hud(attempt = 9, completed = 8)) + assertEquals("8 completed reps · attempt 9 not confirmed complete", ui.completedLine) + assertTrue(ui.completedLine.startsWith("8 completed"), "Completed count stays authoritative (actualReps)") + assertFalse(ui.completedLine.startsWith("9 completed")) + } + + @Test + fun `confirmed completed attempt renders the lifting-phase-complete line`() { + val ui = powerLossHudUi(hud(attempt = 9, completed = 9)) + assertEquals("Working attempt 9 · lifting phase complete", ui.completedLine) + } + + @Test + fun `near limit state is once-only`() { + val first = powerLossHudUi(hud(lastLoss = 16f, nearLimitCueEmitted = false)) + assertTrue(first.nearLimit) + assertEquals("Near power-loss target", first.statusLine) + assertFalse(first.nearLimitCueEmitted) + + val afterCue = powerLossHudUi(hud(lastLoss = 16f, nearLimitCueEmitted = true)) + assertTrue(afterCue.nearLimit, "Status may remain while the condition holds") + assertTrue(afterCue.nearLimitCueEmitted, "No repeated cue") + + val below = powerLossHudUi(hud(lastLoss = 14f)) + assertFalse(below.nearLimit) + assertEquals("Below target", below.statusLine) + } + + @Test + fun `warmup and no-baseline states show dashes and separate copy`() { + val warmup = powerLossHudUi(hud(lastLoss = null), warmupActive = true) + assertEquals("Warm-up — building movement reference", warmup.statusLine) + assertEquals("Warm-ups do not set best power.", warmup.warmupNote) + assertEquals("—", warmup.lossDisplay) + + val noBaseline = powerLossHudUi(hud(lastLoss = null, referenceEstablished = false)) + assertEquals("Waiting for valid lifting power", noBaseline.statusLine) + assertEquals("—", noBaseline.bestLine.substringAfter("Best: rep ")) + } + + @Test + fun `trusted short rom renders the cable fragment with missing power`() { + val ui = powerLossHudUi( + hud( + lastLoss = null, + invalidReason = "sample gap", + cableRom = mapOf(PowerCable.A to 82f, PowerCable.B to 100f), + ), + ) + assertEquals("Short range of motion · Cable A 82% of reference", ui.shortRomLine) + // Missing power is `—`, never a converted ROM deficit. + assertEquals("—", ui.lossDisplay) + } + + @Test + fun `invalid power shows the reason and the last valid attempt separately`() { + val ui = powerLossHudUi( + hud(lastLoss = null, invalidReason = "stale data", lastValidAttempt = 6), + ) + assertEquals("Power unavailable — stale data", ui.invalidPowerLine) + assertEquals("Last valid · attempt 6", ui.lastValidLine) + assertEquals("Max-reps limit and manual stop remain active.", ui.capAndStopActive) + assertEquals("Power unavailable — stale data", ui.statusLine) + } + + @Test + fun `committed ending set is distinct from the completed transition`() { + val ui = powerLossHudUi(hud(endingSet = true)) + assertEquals("Ending set…", ui.endingLine) + assertEquals("Ending set…", ui.statusLine) + } + + @Test + fun `first valid attempt carries the monitoring note`() { + val ui = powerLossHudUi(hud(attempt = 1, completed = 1, lastLoss = 0f)) + assertEquals("Monitoring starts with the second working attempt.", ui.statusLine) + assertEquals("0%", ui.lossDisplay) + } + + @Test + fun `rep panel lines show watts and dashes for missing data`() { + val ui = powerLossHudUi(hud(), latestPowerWatts = null, bestWatts = null) + assertEquals("Latest lifting power —", ui.latestPowerLine) + assertEquals("Best: rep —", ui.bestLine) + + val filled = powerLossHudUi(hud(), latestPowerWatts = 252f, bestWatts = 300f) + assertEquals("Latest lifting power 252 W", filled.latestPowerLine) + assertEquals("Best: rep 2 · 300 W", filled.bestLine) + } + + @Test + fun `rep set with power inactive renders nothing`() { + val ui = powerLossHudUi(PowerLossHudState(powerActive = false)) + assertFalse(ui.visible) + } + + @Test + fun `locked note states the target is not editable from active-set UI`() { + val ui = powerLossHudUi(hud()) + assertEquals("Target locked for this set. Edit before the next set.", ui.lockedNote) + assertEquals("Target locked for this set.", PowerLossUiCopy.TARGET_LOCKED_SHORT) + } + + @Test + fun `E04 uncertain ROM reference shows the limited state and note`() { + val ui = powerLossHudUi(hud(attempt = 1, completed = 0, lastLoss = 0f), referenceRomUncertain = true) + assertEquals("Initial movement reference limited", ui.statusLine) + assertEquals( + "Range checks may be limited until a trustworthy reference is available.", + ui.referenceLimitedNote, + ) + } + + @Test + fun `trusted reference keeps the normal states without the limited note`() { + val ui = powerLossHudUi(hud(attempt = 3, completed = 3, lastLoss = 5f), referenceRomUncertain = false) + assertEquals("Below target", ui.statusLine) + assertNull(ui.referenceLimitedNote) + } + + @Test + fun `near-limit warning outranks the uncertain reference status`() { + val ui = powerLossHudUi(hud(attempt = 3, completed = 3, lastLoss = 16f), referenceRomUncertain = true) + assertEquals("Near power-loss target", ui.statusLine) + assertEquals( + "Range checks may be limited until a trustworthy reference is available.", + ui.referenceLimitedNote, + "The caveat note stays visible even when the status line carries the warning", + ) + } +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossSummaryUiStateTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossSummaryUiStateTest.kt new file mode 100644 index 000000000..b75aa74f9 --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossSummaryUiStateTest.kt @@ -0,0 +1,162 @@ +package com.devil.phoenixproject.presentation.powerloss + +import com.devil.phoenixproject.domain.powerloss.PowerCable +import com.devil.phoenixproject.domain.powerloss.PowerLossAttemptRecord +import com.devil.phoenixproject.domain.powerloss.PowerLossSetSummaryFacts +import com.devil.phoenixproject.domain.powerloss.PowerStopReason +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Issue #1392 P5 — summary reason variants and SD6 headline/clarification rules. + */ +class PowerLossSummaryUiStateTest { + + /** ui-spec §6 representative fixture (SIMULATED): 9 attempts, best rep 2, stop 21%. */ + private val fixtureAttempts = listOf( + PowerLossAttemptRecord(1, completed = true, mcpWatts = 285f, lossPercentAtDecision = 0f, referenceWorkingOrdinal = 1), + PowerLossAttemptRecord(2, completed = true, mcpWatts = 300f, lossPercentAtDecision = 0f, referenceWorkingOrdinal = 2), + PowerLossAttemptRecord(3, completed = true, mcpWatts = 294f, lossPercentAtDecision = 2f, referenceWorkingOrdinal = 2), + PowerLossAttemptRecord(7, completed = true, mcpWatts = 252f, lossPercentAtDecision = 16f, referenceWorkingOrdinal = 2), + PowerLossAttemptRecord(9, completed = false, mcpWatts = 237f, lossPercentAtDecision = 21f, referenceWorkingOrdinal = 2), + ) + + private fun facts( + winner: PowerStopReason? = PowerStopReason.POWER_LOSS, + stoppedAt: Int? = 9, + completed: Int = 8, + attempts: List = fixtureAttempts, + ) = PowerLossSetSummaryFacts( + winnerReason = winner, + thresholdPercent = 20, + maxWorkingReps = 20, + requireTwoConsecutive = false, + stoppedAtWorkingAttempt = stoppedAt, + completedRepCount = completed, + lossPercentAtStop = 21f, + bestWorkingOrdinal = 2, + shortRomObserved = false, + powerLossObserved = true, + attempts = attempts, + ) + + @Test + fun `power-loss headline renders only with the SD6 clarification`() { + val ui = powerLossSummaryUi(facts(), savedNominalReps = 12) + assertEquals("Stopped at rep 9 — 21% power loss (best: rep 2)", ui.headline) + assertEquals("8 completed reps · lifting attempt 9", ui.clarification) + assertNotNull(ui.headlineWithClarification) + assertTrue(ui.headlineWithClarification!!.contains("\n"), "Clarification renders adjacent to the headline") + assertTrue( + ui.headlineWithClarification!!.endsWith("8 completed reps · lifting attempt 9"), + "Completed count comes from actualReps — never promoted to match the headline", + ) + assertEquals("Target 20% · Max 20 working reps · Consecutive requirement off", ui.configLine) + assertEquals("Saved reps: 12", ui.savedRepsHeader) + assertEquals("Power-loss target active", ui.powerActiveBadge) + } + + @Test + fun `completed count is never promoted to the headline number`() { + val ui = powerLossSummaryUi(facts(completed = 8, stoppedAt = 9)) + assertTrue(ui.clarification!!.startsWith("8 completed")) + assertFalse(ui.clarification!!.startsWith("9 completed")) + } + + @Test + fun `short-rom variant keeps the trigger attempt and measured facts`() { + val trigger = PowerLossAttemptRecord( + workingConcentricOrdinal = 9, + completed = false, + romAMm = 410f, + romBMm = 500f, + romAPercentOfReference = 82f, + romBPercentOfReference = 100f, + romTrustworthy = true, + shortRom = true, + ) + val ui = powerLossSummaryUi(facts(winner = PowerStopReason.SHORT_ROM, attempts = listOf(trigger))) + assertEquals("Stopped at attempt 9 — short range of motion", ui.headline) + assertEquals("8 completed reps · lifting attempt 9", ui.clarification) + assertTrue(ui.secondaryLine!!.contains("Cable A: 82% of reference"), ui.secondaryLine) + // ROM deficit never becomes a measured loss. + assertEquals("—", ui.table.rows.single().mcpText) + assertEquals("—", ui.table.rows.single().lossAtDecisionText) + } + + @Test + fun `max-reps backstop never implies fatigue`() { + val ui = powerLossSummaryUi( + facts( + winner = PowerStopReason.MAX_REPS_BACKSTOP, + stoppedAt = 20, + completed = 20, + attempts = emptyList(), + ), + ) + assertEquals("Stopped at 20 working reps — max-reps limit", ui.headline) + assertFalse(ui.headline!!.contains("power loss"), "Cap stop must not imply a fatigue cause") + } + + @Test + fun `manual stop shows observations not a causal headline`() { + val ui = powerLossSummaryUi(facts(winner = null, stoppedAt = null), endedManually = true) + assertEquals("Set stopped manually", ui.headline) + assertNull(ui.clarification) + } + + @Test + fun `legacy set without evidence shows the unavailable line`() { + val ui = powerLossSummaryUi( + facts(winner = null, stoppedAt = null, attempts = emptyList()), + ) + assertNull(ui.headline) + assertEquals("Power-loss details unavailable for this set.", ui.unavailableLine) + assertNull(ui.powerActiveBadge) + } + + @Test + fun `first row zero loss is relative to its own decision-time reference`() { + val ui = powerLossSummaryUi(facts()) + val firstRow = ui.table.rows.first() + assertEquals("0%", firstRow.lossAtDecisionText) + assertEquals( + "1", + firstRow.referenceAtDecisionText, + "Row 1's reference-at-decision is its own ordinal, not the final best", + ) + val laterRow = ui.table.rows.first { it.attemptLabel == "7" } + assertEquals("2", laterRow.referenceAtDecisionText) + } + + @Test + fun `variants are mutually exclusive`() { + assertEquals(PowerLossSummaryVariant.POWER_LOSS, powerLossSummaryVariant(facts())) + assertEquals( + PowerLossSummaryVariant.SHORT_ROM, + powerLossSummaryVariant(facts(winner = PowerStopReason.SHORT_ROM)), + ) + assertEquals( + PowerLossSummaryVariant.MAX_REPS_BACKSTOP, + powerLossSummaryVariant(facts(winner = PowerStopReason.MAX_REPS_BACKSTOP)), + ) + assertEquals(PowerLossSummaryVariant.MANUAL, powerLossSummaryVariant(facts(winner = null))) + assertEquals( + PowerLossSummaryVariant.LEGACY_UNAVAILABLE, + powerLossSummaryVariant(facts(winner = null, attempts = emptyList())), + ) + } + + @Test + fun `summary disclosure keeps the local-data boundary`() { + val ui = powerLossSummaryUi(facts()) + assertEquals( + "Detailed power data is stored on this device, not synced to the portal.", + ui.disclosure, + ) + } +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossTargetReadbackAndExportFlowTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossTargetReadbackAndExportFlowTest.kt new file mode 100644 index 000000000..e36236c6f --- /dev/null +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/presentation/powerloss/PowerLossTargetReadbackAndExportFlowTest.kt @@ -0,0 +1,222 @@ +package com.devil.phoenixproject.presentation.powerloss + +import com.devil.phoenixproject.domain.model.ProgramMode +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.PowerLossProtocolFamily +import com.devil.phoenixproject.domain.powerloss.TargetMode +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +/** + * Issue #1392 P5 — Just Lift / set-ready target readback facts (ui-spec §2–§3) + * and the export-flow state machine (ui-spec §6): `Export power data` entry plus + * the legacy-export omission disclosure before any legacy run. + */ +class PowerLossTargetReadbackAndExportFlowTest { + + private val powerConfig = PowerLossConfig( + targetMode = TargetMode.POWER, + thresholdPercent = 20, + maxWorkingReps = 20, + requireTwoConsecutive = false, + savedNominalReps = 12, + ) + + // ── Readback facts (JustLiftScreen / SetReadyScreen) ─────────────────────── + + @Test + fun `readback shows SD6 saved facts and target lines for an active power target`() { + val readback = powerLossTargetReadback( + config = powerConfig, + supportedExecution = true, + savedNominalReps = 12, + ) + assertTrue(readback.visible) + assertEquals( + listOf( + "Power-loss target · 20%", + "Max 20 working reps", + "Saved reps: 12", + "Power-loss target active", + ), + readback.lines, + ) + assertEquals("Saved reps: 12", readback.savedRepsLine) + assertEquals("Power-loss target active", readback.powerActiveBadge) + assertNull(readback.dormantBanner) + assertFalse(readback.targetLocked) + } + + @Test + fun `during-set readback is locked - active-set UI never edits the target`() { + val readback = powerLossTargetReadback( + config = powerConfig, + supportedExecution = true, + savedNominalReps = 12, + locked = true, + ) + assertEquals("Target locked for this set.", readback.targetLockedLine) + assertTrue(readback.targetLocked) + assertEquals("Target locked for this set.", readback.lines.first()) + } + + @Test + fun `dormant power config shows the not-active banner and keeps the saved facts`() { + val readback = powerLossTargetReadback( + config = powerConfig, + supportedExecution = false, + savedNominalReps = 12, + ) + assertTrue(readback.visible) + assertEquals("Power-loss target is not active in this mode.", readback.dormantBanner) + assertEquals( + listOf( + "Power-loss target is not active in this mode.", + "Saved reps: 12", + ), + readback.lines, + ) + assertNull(readback.powerActiveBadge) + } + + @Test + fun `plain rep sets render no readback card - REP regression unchanged`() { + val readback = powerLossTargetReadback( + config = PowerLossConfig.DEFAULT, + supportedExecution = true, + savedNominalReps = 12, + ) + assertFalse(readback.visible) + assertEquals(emptyList(), readback.lines) + } + + @Test + fun `missing saved nominal reps shows no saved reps line - never fabricated`() { + val readback = powerLossTargetReadback( + config = powerConfig.copy(savedNominalReps = null), + supportedExecution = true, + savedNominalReps = null, + ) + assertTrue(readback.visible) + assertNull(readback.savedRepsLine) + assertFalse(readback.lines.any { it.startsWith("Saved reps:") }) + } + + // ── Execution support (inert on excluded paths) ─────────────────────────── + + @Test + fun `timed and bodyweight executions never support the power target`() { + assertFalse( + powerLossExecutionSupported( + config = powerConfig, + mode = ProgramMode.OldSchool, + isTimed = true, + ), + ) + assertFalse( + powerLossExecutionSupported( + config = powerConfig, + mode = ProgramMode.OldSchool, + isBodyweight = true, + ), + ) + } + + @Test + fun `just lift is a supported style for v1 modes only`() { + assertTrue( + powerLossExecutionSupported( + config = powerConfig, + mode = ProgramMode.OldSchool, + isJustLiftExecutionStyle = true, + ), + ) + // Excluded modes stay excluded even in Just Lift style (spec §1/§7). + assertFalse( + powerLossExecutionSupported( + config = powerConfig, + mode = ProgramMode.TUT, + isJustLiftExecutionStyle = true, + ), + ) + assertEquals( + PowerLossProtocolFamily.UNSUPPORTED, + PowerLossProtocolFamily.of(ProgramMode.TUT, isJustLiftExecutionStyle = true), + ) + assertEquals( + PowerLossProtocolFamily.JUST_LIFT, + PowerLossProtocolFamily.of(ProgramMode.Echo, isJustLiftExecutionStyle = true), + ) + } + + @Test + fun `timed and bodyweight paths resolve the execution config to inert rep target`() { + val inert = powerLossExecutionConfig(powerConfig, isTimed = true, isBodyweight = false) + assertEquals(TargetMode.REP_TARGET, inert.targetMode) + val inertBodyweight = powerLossExecutionConfig(powerConfig, isTimed = false, isBodyweight = true) + assertEquals(TargetMode.REP_TARGET, inertBodyweight.targetMode) + val carried = powerLossExecutionConfig(powerConfig, isTimed = false, isBodyweight = false) + assertEquals(TargetMode.POWER, carried.targetMode) + } + + // ── Export flow (ui-spec §6) ────────────────────────────────────────────── + + @Test + fun `legacy export always surfaces the omission disclosure first`() { + val flow = PowerLossExportFlowState.INITIAL + .reduce(PowerLossExportIntent.RequestLegacyExport) + assertTrue(flow.legacyConfirmationVisible) + assertFalse(flow.legacyExportApproved) + assertFalse(flow.powerExportRequested) + } + + @Test + fun `choose power-data export routes to the versioned power export`() { + val flow = PowerLossExportFlowState.INITIAL + .reduce(PowerLossExportIntent.RequestLegacyExport) + .reduce(PowerLossExportIntent.ChoosePowerDataExport) + assertFalse(flow.legacyConfirmationVisible) + assertFalse(flow.legacyExportApproved) + assertTrue(flow.powerExportRequested) + } + + @Test + fun `export without power details approves the disclosed legacy run`() { + val flow = PowerLossExportFlowState.INITIAL + .reduce(PowerLossExportIntent.RequestLegacyExport) + .reduce(PowerLossExportIntent.ExportWithoutPowerDetails) + assertFalse(flow.legacyConfirmationVisible) + assertTrue(flow.legacyExportApproved) + assertFalse(flow.powerExportRequested) + } + + @Test + fun `dismissing the disclosure runs nothing`() { + val flow = PowerLossExportFlowState.INITIAL + .reduce(PowerLossExportIntent.RequestLegacyExport) + .reduce(PowerLossExportIntent.DismissLegacyConfirmation) + assertFalse(flow.legacyConfirmationVisible) + assertFalse(flow.legacyExportApproved) + assertFalse(flow.powerExportRequested) + } + + @Test + fun `export entry and disclosure are the exact ui-spec strings`() { + val export = PowerLossExportUi() + assertEquals("Export power data", export.entryLabel) + assertEquals( + "This format does not include power-loss settings or per-attempt details. " + + "Use power-data export to keep them.", + export.legacyOmissionDisclosure, + ) + assertEquals("Choose power-data export", export.choosePowerDataExportAction) + assertEquals("Export without power details", export.exportWithoutPowerDetailsAction) + assertTrue( + export.localDataDisclosure.endsWith("they are not synced to the portal."), + "Local-data disclosure must end with the portal deferral", + ) + } +} diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/util/BackupSerializationTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/util/BackupSerializationTest.kt index 56559f245..e09ee6fff 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/util/BackupSerializationTest.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/util/BackupSerializationTest.kt @@ -562,4 +562,114 @@ class BackupSerializationTest { assertEquals("100,105,110", e.samplesUvCsv) assertEquals(1000000000L, e.sensorTimestampNs) } + + // ── Issue #1392: versioned optional power-loss sections (backup v7) ───── + + @Test + fun powerLossBackupSectionsRoundTripAndKeepNullsNotZeros() { + val setRow = PowerLossSetCompanionBackup( + sessionId = "session-1", + setId = "set-1", + metricVersion = 1, + targetMode = "POWER", + thresholdPercent = 25, + maxWorkingReps = 15, + requireTwoConsecutive = true, + savedNominalReps = 12, + activeCables = "A,B", + activeCableProvenance = "rep-metric-load-scan:first-working-attempt", + referenceWorkingOrdinal = 2, + referenceMcpWatts = 312.5f, + referenceRomAMm = null, + referenceRomBMm = null, + triggerWorkingOrdinal = 9, + winnerReason = "POWER_LOSS", + shortRomObserved = false, + powerLossObserved = true, + lossPercentAtDecision = 21.5f, + createdAt = 1_700_000_000_000L, + ) + val observationRow = PowerLossObservationCompanionBackup( + sessionId = "session-1", + setId = "set-1", + workingConcentricOrdinal = 9, + legacyRepIndex = null, + completed = false, + mcpWatts = null, + eccentricPowerWatts = null, + concentricDurationMs = null, + eccentricDurationMs = null, + lossPercentAtDecision = 21.5f, + referenceWorkingOrdinal = 2, + ) + val configRow = PowerLossExerciseConfigBackup( + routineExerciseId = "routine-1-re", + targetMode = "POWER", + thresholdPercent = 25, + maxWorkingReps = 15, + requireTwoConsecutive = true, + savedNominalReps = null, + updatedAt = 1_700_000_000_000L, + ) + val original = BackupData( + version = CURRENT_BACKUP_VERSION, + exportedAt = "2026-11-17T12:00:00Z", + appVersion = "test", + data = BackupContent( + powerLossSetCompanions = listOf(setRow), + powerLossObservationCompanions = listOf(observationRow), + powerLossExerciseConfigs = listOf(configRow), + ), + ) + + val deserialized = json.decodeFromString(json.encodeToString(original)) + + assertEquals(listOf(setRow), deserialized.data.powerLossSetCompanions) + assertEquals(listOf(observationRow), deserialized.data.powerLossObservationCompanions) + assertEquals(listOf(configRow), deserialized.data.powerLossExerciseConfigs) + // Absent fields stay null — never fabricated zeros. + assertNull(deserialized.data.powerLossSetCompanions[0].referenceRomAMm) + assertNull(deserialized.data.powerLossObservationCompanions[0].mcpWatts) + assertNull(deserialized.data.powerLossExerciseConfigs[0].savedNominalReps) + } + + @Test + fun legacyBackupWithoutPowerLossSectionsDecodesWithEmptySections() { + // An old backup (v7 before #1392) carries none of the power-loss sections. + // The new reader decodes it without crashing and the sections stay empty — + // restore treats an absent section as "nothing to add", never a wipe. + val legacy = json.decodeFromString( + """{"version":7,"exportedAt":"2026-01-01T00:00:00Z","appVersion":"old","data":{}}""", + ) + + assertTrue(legacy.data.powerLossSetCompanions.isEmpty()) + assertTrue(legacy.data.powerLossObservationCompanions.isEmpty()) + assertTrue(legacy.data.powerLossExerciseConfigs.isEmpty()) + } + + @Test + fun powerLossBackupRowsFailSafelyOnUnknownFormatVersions() { + assertFalse(isSupportedPowerLossBackupFormatVersion(POWER_LOSS_BACKUP_FORMAT_VERSION + 1)) + assertTrue(isSupportedPowerLossBackupFormatVersion(POWER_LOSS_BACKUP_FORMAT_VERSION)) + } + + @Test + fun powerLossBackupSectionsCarryNoSyncedOrBackedUpMarkers() { + // Restored rows are never marked synced or backed up: the wire types carry + // no such fields at all, so no restore path can claim one. + val descriptors = listOf( + PowerLossSetCompanionBackup.serializer().descriptor, + PowerLossObservationCompanionBackup.serializer().descriptor, + PowerLossExerciseConfigBackup.serializer().descriptor, + ) + for (descriptor in descriptors) { + for (index in 0 until descriptor.elementsCount) { + val name = descriptor.getElementName(index).lowercase() + assertFalse(name.contains("sync"), "${descriptor.serialName}.$name must not claim sync state") + assertFalse(name.contains("backup") && name.contains("up"), "${descriptor.serialName}.$name") + assertFalse(name.contains("upload"), "${descriptor.serialName}.$name") + assertFalse(name.contains("acknowledg"), "${descriptor.serialName}.$name") + } + } + } } diff --git a/shared/src/commonTest/kotlin/com/devil/phoenixproject/util/BlePacketFactoryTest.kt b/shared/src/commonTest/kotlin/com/devil/phoenixproject/util/BlePacketFactoryTest.kt index eb226df74..b4bb171f7 100644 --- a/shared/src/commonTest/kotlin/com/devil/phoenixproject/util/BlePacketFactoryTest.kt +++ b/shared/src/commonTest/kotlin/com/devil/phoenixproject/util/BlePacketFactoryTest.kt @@ -7,6 +7,10 @@ import com.devil.phoenixproject.domain.model.ProgramMode import com.devil.phoenixproject.domain.model.WorkoutMode import com.devil.phoenixproject.domain.model.WorkoutParameters import com.devil.phoenixproject.domain.model.toWorkoutMode +import com.devil.phoenixproject.domain.powerloss.ExecutionTargetPlan +import com.devil.phoenixproject.domain.powerloss.PowerLossConfig +import com.devil.phoenixproject.domain.powerloss.ProtocolRepBounds +import com.devil.phoenixproject.domain.powerloss.TargetMode import kotlin.test.Test import kotlin.test.assertContentEquals import kotlin.test.assertEquals @@ -1509,4 +1513,148 @@ class BlePacketFactoryTest { assertEquals(ProgramMode.TUTBeast, beastProgram, "TUTBeast -> ProgramMode.TUTBeast") assertEquals(WorkoutMode.TUTBeast, beastProgram.toWorkoutMode(), "ProgramMode.TUTBeast -> WorkoutMode.TUTBeast") } + + // ========== Issue #1392 (SD4): POWER effective-target plan encoding ========== + + private fun powerPlan( + cap: Int, + nominal: Int? = 12, + finiteIdentity: Boolean = true, + ): ExecutionTargetPlan = requireNotNull( + ExecutionTargetPlan.derive( + config = PowerLossConfig( + targetMode = TargetMode.POWER, + thresholdPercent = 20, + maxWorkingReps = cap, + savedNominalReps = nominal, + ), + bounds = ProtocolRepBounds( + maxRepresentableWorkingReps = 254, + protocolIdentityFinite = finiteIdentity, + ), + warmupSetCount = 3, + now = 0L, + ), + ) + + private fun repPlan(nominal: Int = 12): ExecutionTargetPlan = requireNotNull( + ExecutionTargetPlan.derive( + config = PowerLossConfig(targetMode = TargetMode.REP_TARGET, savedNominalReps = nominal), + bounds = ProtocolRepBounds(maxRepresentableWorkingReps = 254, protocolIdentityFinite = true), + warmupSetCount = 3, + now = 0L, + ), + ) + + private fun finiteParams(reps: Int = 12, warmupReps: Int = 3) = WorkoutParameters( + programMode = ProgramMode.OldSchool, + reps = reps, + warmupReps = warmupReps, + weightPerCableKg = 20f, + ) + + @Test + fun `power plan encodes the effective cap plus warmup in the program total rep byte`() { + val plan = powerPlan(cap = 20, nominal = 12) + val packet = BlePacketFactory.createProgramParams(finiteParams(), CommandLimits.TRAINER_PLUS_MAX_WEIGHT_PER_CABLE_KG, plan) + + assertEquals( + 23, + packet[0x04].toInt() and 0xFF, + "the frozen effective target (cap 20) plus warmup 3 — never the saved nominal 12", + ) + } + + @Test + fun `power plan encodes the effective cap in the echo control target byte`() { + val plan = powerPlan(cap = 20, nominal = 12) + val frame = BlePacketFactory.createEchoControl( + level = EchoLevel.HARD, + warmupReps = 3, + targetReps = 12, + eccentricPct = 100, + targetPlan = plan, + ) + + assertEquals(3, frame[0x04].toInt() and 0xFF, "warmup byte unchanged") + assertEquals(20, frame[0x05].toInt() and 0xFF, "echo working byte is the frozen effective target") + } + + @Test + fun `rep plan and null plan keep the legacy encoding byte identical`() { + val legacyProgram = BlePacketFactory.createProgramParams(finiteParams(), CommandLimits.TRAINER_PLUS_MAX_WEIGHT_PER_CABLE_KG) + val repProgram = BlePacketFactory.createProgramParams(finiteParams(), CommandLimits.TRAINER_PLUS_MAX_WEIGHT_PER_CABLE_KG, repPlan()) + assertContentEquals(legacyProgram, repProgram, "REP mode program bytes must stay byte-identical") + + val legacyEcho = BlePacketFactory.createEchoControl(EchoLevel.HARD, warmupReps = 3, targetReps = 12, eccentricPct = 100) + val repEcho = BlePacketFactory.createEchoControl(EchoLevel.HARD, warmupReps = 3, targetReps = 12, eccentricPct = 100, targetPlan = repPlan()) + assertContentEquals(legacyEcho, repEcho, "REP mode echo bytes must stay byte-identical") + } + + @Test + fun `unlimited identity keeps its sentinel under a power plan`() { + val plan = powerPlan(cap = 20, nominal = null, finiteIdentity = false) + val justLift = finiteParams().copy(isJustLift = true) + val packet = BlePacketFactory.createProgramParams(justLift, CommandLimits.TRAINER_PLUS_MAX_WEIGHT_PER_CABLE_KG, plan) + assertEquals(0xFF.toByte(), packet[0x04], "Just Lift hardware-unlimited identity preserved") + + val amrap = finiteParams().copy(isAMRAP = true, weightPerCableKg = 0f) + val amrapPacket = BlePacketFactory.createProgramParams(amrap, CommandLimits.TRAINER_PLUS_MAX_WEIGHT_PER_CABLE_KG, plan) + assertEquals(0xFF.toByte(), amrapPacket[0x04], "AMRAP hardware-unlimited identity preserved") + + val echo = BlePacketFactory.createEchoControl( + level = EchoLevel.HARD, + warmupReps = 3, + targetReps = 12, + isJustLift = true, + eccentricPct = 100, + targetPlan = plan, + ) + assertEquals(0xFF.toByte(), echo[0x05], "Echo unlimited identity preserved") + } + + @Test + fun `plan validation agrees with the encoded effective target`() { + // The validator checks what the frame will actually carry — the frozen cap + // plus warmup must fit the finite byte, even when each field alone would. + assertTrue( + WorkoutCommandValidator.validateProgramParams(finiteParams(), CommandLimits.TRAINER_PLUS_MAX_WEIGHT_PER_CABLE_KG, powerPlan(cap = 251)).isSuccess, + "cap 251 + warmup 3 = 254 fits the finite byte", + ) + assertTrue( + WorkoutCommandValidator.validateProgramParams(finiteParams(), CommandLimits.TRAINER_PLUS_MAX_WEIGHT_PER_CABLE_KG, powerPlan(cap = 252)).isFailure, + "cap 252 + warmup 3 = 255 collides with the unlimited sentinel", + ) + assertTrue( + WorkoutCommandValidator.validateEchoControl( + level = EchoLevel.HARD, + warmupReps = 3, + targetReps = 12, + isJustLift = false, + isAMRAP = false, + eccentricPct = 100, + targetPlan = powerPlan(cap = 254), + ).isSuccess, + "echo working byte is standalone so the validator bound applies", + ) + assertTrue( + WorkoutCommandValidator.validateEchoControl( + level = EchoLevel.HARD, + warmupReps = 3, + targetReps = 12, + isJustLift = false, + isAMRAP = false, + eccentricPct = 100, + targetPlan = ExecutionTargetPlan( + targetMode = TargetMode.POWER, + nominalReps = 12, + maxWorkingReps = 255, + warmupSetCount = 3, + protocolIdentityFinite = true, + planValidatedAt = 0L, + ), + ).isFailure, + "an unrepresentable frozen cap must not validate", + ) + } } diff --git a/shared/src/iosMain/kotlin/com/devil/phoenixproject/presentation/components/HapticFeedbackEffect.ios.kt b/shared/src/iosMain/kotlin/com/devil/phoenixproject/presentation/components/HapticFeedbackEffect.ios.kt index 7916c74e4..b0f57750b 100644 --- a/shared/src/iosMain/kotlin/com/devil/phoenixproject/presentation/components/HapticFeedbackEffect.ios.kt +++ b/shared/src/iosMain/kotlin/com/devil/phoenixproject/presentation/components/HapticFeedbackEffect.ios.kt @@ -368,6 +368,8 @@ private class IosSoundManager { HapticEvent.AUTO_START_READY to "auto_start_ready", // Issue #313: Velocity loss threshold alert (attention-getting) HapticEvent.VELOCITY_THRESHOLD_REACHED to "boopbeepbeep", + // Issue #1392: power-loss near-limit cue (reuses existing beepboop asset) + HapticEvent.POWER_NEAR_LIMIT to "beepboop", // ERROR, BADGE_EARNED, PERSONAL_RECORD, REP_COUNT_ANNOUNCED, COUNTDOWN_TICK handled separately ) @@ -799,6 +801,14 @@ private fun playHapticFeedback(event: HapticEvent) { notificationGenerator.notificationOccurred(UINotificationFeedbackType.UINotificationFeedbackTypeWarning) } + // Issue #1392: power-loss near-limit cue — medium impact, distinct from the + // velocity-threshold alert's heavy impact + warning notification. + is HapticEvent.POWER_NEAR_LIMIT -> { + val generator = UIImpactFeedbackGenerator(UIImpactFeedbackStyle.UIImpactFeedbackStyleMedium) + generator.prepare() + generator.impactOccurred() + } + // Issue #1356: Auto-start readiness — one firm impact, deliberately distinct // from WORKOUT_START's medium start impact. is HapticEvent.AUTO_START_READY -> { diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/components/ExerciseConfigModal.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/components/ExerciseConfigModal.kt index 42a562a12..a368b64cf 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/components/ExerciseConfigModal.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/components/ExerciseConfigModal.kt @@ -17,7 +17,13 @@ import androidx.compose.ui.window.Dialog import com.devil.phoenixproject.domain.model.EchoLevel import com.devil.phoenixproject.domain.model.ExerciseConfig import com.devil.phoenixproject.domain.model.ProgramMode +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.ui.text.input.KeyboardType import com.devil.phoenixproject.domain.model.percentLabel +import com.devil.phoenixproject.domain.powerloss.PowerLossProtocolFamily +import com.devil.phoenixproject.domain.powerloss.TargetMode +import com.devil.phoenixproject.presentation.powerloss.PowerLossConfigDraftState +import com.devil.phoenixproject.presentation.powerloss.PowerLossUiCopy import com.devil.phoenixproject.ui.theme.Spacing import org.jetbrains.compose.resources.stringResource import projectphoenix.shared.generated.resources.* @@ -52,9 +58,35 @@ fun ExerciseConfigModal( weightStepKg: Float = 2.5f, // Issue #266: Configurable weight step in kg // No default: a caller that forgot it would silently get the widest (Trainer+) ceiling. planningMaxWeightPerCableKg: Float, + // Issue #1392 SD4: dynamic Max-working-reps bound from the accepted execution plan + // (ProtocolRepBounds.maxRepresentableWorkingReps — PROGRAM: 254 minus warm-ups, + // Echo: its validator bound). This default is the un-warmed PROGRAM ceiling only; + // callers with a derived plan MUST pass the real bound — never assume 254 for Echo. + maxAllowedWorkingReps: Int = 254, ) { var config by remember { mutableStateOf(initialConfig) } + // Issue #1392 — Set target edits run through the pure draft state machine + // (validate-everything, atomic Apply; Cancel/discard restores the original). + var powerDraft by remember { + mutableStateOf( + PowerLossConfigDraftState.seededFrom( + config = initialConfig.powerLoss.copy( + savedNominalReps = initialConfig.powerLoss.savedNominalReps ?: templateReps, + ), + maxAllowedWorkingReps = maxAllowedWorkingReps, + protocolFamily = PowerLossProtocolFamily.of(initialConfig.mode, isJustLiftExecutionStyle = false), + ), + ) + } + // Program-mode switches move the capability gate (ui-spec §3). + val currentProtocolFamily = PowerLossProtocolFamily.of(config.mode, isJustLiftExecutionStyle = false) + LaunchedEffect(currentProtocolFamily) { + if (powerDraft.protocolFamily != currentProtocolFamily) { + powerDraft = powerDraft.copy(protocolFamily = currentProtocolFamily) + } + } + Dialog(onDismissRequest = onDismiss) { Surface( modifier = Modifier @@ -162,6 +194,14 @@ fun ExerciseConfigModal( HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + // Issue #1392 — Set target (power-loss) section, ui-spec §3. + PowerLossSetTargetSection( + draft = powerDraft, + onDraftChange = { powerDraft = it }, + ) + + HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant) + // Footer buttons Row( modifier = Modifier @@ -170,14 +210,25 @@ fun ExerciseConfigModal( horizontalArrangement = Arrangement.spacedBy(Spacing.small), ) { OutlinedButton( - onClick = onDismiss, + onClick = { + // Cancel: discard the unapplied draft (ui-spec §3). + powerDraft = powerDraft.cancel() + onDismiss() + }, modifier = Modifier.weight(1f), ) { Text(stringResource(Res.string.action_cancel)) } Button( - onClick = { onConfirm(config) }, + onClick = { + // Apply validates every effective field and commits + // atomically to ExerciseConfig.powerLoss. + val committed = powerDraft.apply() + powerDraft = committed + onConfirm(config.copy(powerLoss = committed.committed)) + }, + enabled = powerDraft.canApply, modifier = Modifier.weight(1f), ) { Text(stringResource(Res.string.action_apply)) diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/components/PowerLossSetTargetSection.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/components/PowerLossSetTargetSection.kt new file mode 100644 index 000000000..a268e8e15 --- /dev/null +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/components/PowerLossSetTargetSection.kt @@ -0,0 +1,350 @@ +package com.devil.phoenixproject.presentation.components + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.FilterChip +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardType +import com.devil.phoenixproject.domain.powerloss.PowerLossProtocolFamily +import com.devil.phoenixproject.domain.powerloss.TargetMode +import com.devil.phoenixproject.presentation.powerloss.PowerLossConfigDraftState +import com.devil.phoenixproject.presentation.powerloss.PowerLossTargetReadbackUi +import com.devil.phoenixproject.presentation.powerloss.PowerLossUiCopy +import com.devil.phoenixproject.ui.theme.Spacing + +// ==================== SET TARGET (issue #1392 power-loss) ==================== + +/** + * `Set target` section (ui-spec §3): Rep target | Power-loss target equal-width + * choices, the POWER expanded config on the pure [PowerLossConfigDraftState] + * machine, and the local-data disclosure. All copy comes from PowerLossUiCopy; + * edits stay in the draft until Apply commits atomically. + * + * Shared by `ExerciseConfigModal` (template configuration), `ExerciseEditBottomSheet` + * (routine/single-exercise editing) and any ad-hoc configuration surface — one + * implementation so the SD6 copy can never drift between surfaces. + */ +@Composable +internal fun PowerLossSetTargetSection( + draft: PowerLossConfigDraftState, + onDraftChange: (PowerLossConfigDraftState) -> Unit, +) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(Spacing.medium), + verticalArrangement = Arrangement.spacedBy(Spacing.medium), + ) { + Text( + text = PowerLossUiCopy.SECTION_HEADING, + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.primary, + ) + + // Two equal-width target choices (labels wrap, never truncate). + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(Spacing.small), + ) { + TargetModeButton( + label = PowerLossUiCopy.REP_TARGET_LABEL, + selected = draft.effectiveTargetMode == TargetMode.REP_TARGET, + onClick = { onDraftChange(draft.selectTargetMode(TargetMode.REP_TARGET)) }, + modifier = Modifier.weight(1f), + ) + TargetModeButton( + label = PowerLossUiCopy.POWER_TARGET_LABEL, + selected = draft.effectiveTargetMode == TargetMode.POWER, + onClick = { onDraftChange(draft.selectTargetMode(TargetMode.POWER)) }, + modifier = Modifier.weight(1f), + ) + } + + if (!draft.capabilityAvailable) { + SectionNote(PowerLossUiCopy.CAPABILITY_UNAVAILABLE) + SectionNote(PowerLossUiCopy.CAPABILITY_UNAVAILABLE_SECONDARY) + } + if (draft.dormantPowerConfig) { + SectionNote(PowerLossUiCopy.INCOMPATIBLE_SAVED_BANNER) + } + + if (!draft.powerSectionExpanded) { + SectionNote(PowerLossUiCopy.REP_HELPER) + draft.committed.savedNominalReps?.let { saved -> + SectionNote(PowerLossUiCopy.savedRepReadback(saved)) + } + } else { + Text( + text = PowerLossUiCopy.POWER_LEAD, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurface, + ) + SectionNote(PowerLossUiCopy.POWER_HELP) + + // Threshold presets — SD6 nonbreaking labels (`10%`, `Custom` never split). + Text( + text = PowerLossUiCopy.THRESHOLD_LABEL, + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(Spacing.small), + ) { + draft.presetChips.forEach { chip -> + FilterChip( + selected = chip.selected, + onClick = { onDraftChange(draft.selectPreset(chip.preset)) }, + label = { Text(chip.label) }, + modifier = Modifier.weight(1f), + ) + } + } + + if (draft.customSelected) { + OutlinedTextField( + value = draft.customThresholdInput, + onValueChange = { onDraftChange(draft.updateCustomThreshold(it)) }, + label = { Text(PowerLossUiCopy.CUSTOM_THRESHOLD_LABEL) }, + isError = draft.customThresholdError != null, + supportingText = { + Text(draft.customThresholdError ?: PowerLossUiCopy.CUSTOM_THRESHOLD_HELPER) + }, + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + modifier = Modifier.fillMaxWidth(), + ) + } + + if (draft.highThresholdCautionVisible) { + // Warning treatment only; never disables Apply (ui-spec §3.4). + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(Spacing.medium), + color = MaterialTheme.colorScheme.errorContainer, + ) { + Column(modifier = Modifier.padding(Spacing.medium)) { + Text( + text = PowerLossUiCopy.HIGH_THRESHOLD_TITLE, + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onErrorContainer, + ) + Spacer(modifier = Modifier.height(Spacing.extraSmall)) + Text( + text = PowerLossUiCopy.HIGH_THRESHOLD_BODY, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onErrorContainer, + ) + } + } + } + + OutlinedTextField( + value = draft.maxRepsInput, + onValueChange = { onDraftChange(draft.updateMaxReps(it)) }, + label = { Text(PowerLossUiCopy.MAX_WORKING_REPS_LABEL) }, + isError = draft.maxRepsError != null, + supportingText = { + // SD4: the error bound is dynamic (`Enter 2–{maxAllowed} working reps.`). + Text(draft.maxRepsError ?: PowerLossUiCopy.MAX_WORKING_REPS_HELPER) + }, + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + modifier = Modifier.fillMaxWidth(), + ) + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically, + ) { + Text( + text = PowerLossUiCopy.TWO_CONSECUTIVE_LABEL, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.weight(1f), + ) + Switch( + checked = draft.draft.requireTwoConsecutive, + onCheckedChange = { onDraftChange(draft.setRequireTwoConsecutive(it)) }, + ) + } + // SD1 helper copy; on/off text shown as well as the switch state. + SectionNote( + if (draft.draft.requireTwoConsecutive) { + PowerLossUiCopy.TWO_CONSECUTIVE_ON_HELPER + } else { + PowerLossUiCopy.TWO_CONSECUTIVE_OFF_HELPER + }, + ) + + // Non-toggleable safeguard — never an optional ROM switch (ui-spec §3.7). + SectionNote(PowerLossUiCopy.SHORT_ROM_SAFEGUARD) + SectionNote(PowerLossUiCopy.SHORT_ROM_SAFEGUARD_HELP) + + if (draft.protocolFamily == PowerLossProtocolFamily.ECHO) { + SectionNote(PowerLossUiCopy.ECHO_NOTE) + } + + Text( + text = draft.nearLimitCueReadback, + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + SectionNote(PowerLossUiCopy.NEAR_LIMIT_CUE_HELP) + } + + SectionNote(PowerLossUiCopy.LOCAL_DATA_DISCLOSURE) + } + + // Unsupported-mode confirmation (ui-spec §3); POWER settings stay dormant. + draft.pendingModeConfirmation?.let { confirmation -> + AlertDialog( + onDismissRequest = { onDraftChange(draft.dismissModeConfirmation()) }, + title = { Text(confirmation.title) }, + text = { Text(confirmation.body) }, + confirmButton = { + TextButton(onClick = { onDraftChange(draft.confirmUseRepTarget()) }) { + Text(confirmation.confirmAction) + } + }, + dismissButton = { + TextButton(onClick = { onDraftChange(draft.dismissModeConfirmation()) }) { + Text(confirmation.cancelAction) + } + }, + ) + } +} + +@Composable +private fun TargetModeButton( + label: String, + selected: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + OutlinedButton( + onClick = onClick, + modifier = modifier, + colors = ButtonDefaults.outlinedButtonColors( + containerColor = if (selected) { + MaterialTheme.colorScheme.primaryContainer + } else { + MaterialTheme.colorScheme.surfaceContainerLow + }, + contentColor = if (selected) { + MaterialTheme.colorScheme.onPrimaryContainer + } else { + MaterialTheme.colorScheme.onSurface + }, + ), + ) { + Text(text = label, style = MaterialTheme.typography.labelLarge) + } +} + +@Composable +private fun SectionNote(text: String) { + Text( + text = text, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) +} + +// ==================== TARGET READBACK (issue #1392 P5) ==================== + +/** + * SD6 saved-target facts: `Saved reps: 12` with the adjacent + * `Power-loss target active` badge. Renders nothing when there is nothing to say. + */ +@Composable +internal fun PowerLossSavedTargetFacts( + savedNominalReps: Int?, + powerActive: Boolean, +) { + if (savedNominalReps == null && !powerActive) return + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = Spacing.medium, vertical = Spacing.small), + horizontalArrangement = Arrangement.spacedBy(Spacing.small), + verticalAlignment = Alignment.CenterVertically, + ) { + savedNominalReps?.let { saved -> + Text( + text = PowerLossUiCopy.savedRepsHeader(saved), + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface, + ) + } + if (powerActive) { + Text( + text = PowerLossUiCopy.POWER_ACTIVE_BADGE, + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.primary, + ) + } + } +} + +/** + * Compact set-ready / Just Lift target readback (ui-spec §2): `Power-loss target + * · 20% · Max 20 working reps` plus the SD6 `Saved reps: 12` fact with the + * adjacent `Power-loss target active` badge. Renders nothing for plain REP sets. + * Active-set usage passes `locked` so the during-set copy reads + * `Target locked for this set.` — editing is only available before the next set. + */ +@Composable +internal fun PowerLossTargetReadbackCard(readback: PowerLossTargetReadbackUi) { + if (!readback.visible) return + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(Spacing.medium), + color = MaterialTheme.colorScheme.surfaceContainerHighest, + ) { + Column( + modifier = Modifier.padding(Spacing.medium), + verticalArrangement = Arrangement.spacedBy(Spacing.extraSmall), + ) { + readback.targetLockedLine?.let { lockedLine -> + Text( + text = lockedLine, + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.primary, + ) + } + readback.lines.forEach { line -> + Text( + text = line, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } +} diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/ActiveWorkoutScreen.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/ActiveWorkoutScreen.kt index 2158fd46f..6b86dda19 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/ActiveWorkoutScreen.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/ActiveWorkoutScreen.kt @@ -133,6 +133,8 @@ fun ActiveWorkoutScreen( val isCurrentExerciseBodyweight by viewModel.isCurrentExerciseBodyweight.collectAsState() val latestRepQuality by viewModel.latestRepQuality.collectAsState() val latestBiomechanicsResult by viewModel.latestBiomechanicsResult.collectAsState() + // Issue #1392: live power-loss HUD facts for the active HUD panel (ui-spec §4) + val powerLossHudState by viewModel.powerLossHud.collectAsState() // Issue #237: Motion-triggered set start val motionStartHoldProgress by viewModel.motionStartHoldProgress.collectAsState() // Issue #297, #228: Rest timer pause state @@ -447,6 +449,7 @@ fun ActiveWorkoutScreen( canGoBack, canSkipForward, timedExerciseRemainingSeconds, isCurrentExerciseBodyweight, latestRepQuality, latestBiomechanicsResult, + powerLossHudState, motionStartHoldProgress, isRestPaused, currentWarmupSetIndex, justLiftRestCountdown, isExerciseTimerPaused, @@ -485,6 +488,7 @@ fun ActiveWorkoutScreen( isCurrentExerciseBodyweight = isCurrentExerciseBodyweight, latestRepQualityScore = latestRepQuality?.composite, latestBiomechanicsResult = latestBiomechanicsResult, + powerLossHudState = powerLossHudState, motionStartHoldProgress = motionStartHoldProgress, isRestPaused = isRestPaused, currentWarmupSetIndex = currentWarmupSetIndex, diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/ExerciseEditBottomSheet.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/ExerciseEditBottomSheet.kt index a956a37e3..8365e5e6d 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/ExerciseEditBottomSheet.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/ExerciseEditBottomSheet.kt @@ -85,11 +85,14 @@ import com.devil.phoenixproject.domain.model.WarmupSet import com.devil.phoenixproject.domain.model.WeightUnit import com.devil.phoenixproject.domain.model.WorkoutMode import com.devil.phoenixproject.domain.model.WorkoutPhase +import com.devil.phoenixproject.domain.powerloss.TargetMode import com.devil.phoenixproject.domain.usecase.RoutineScalingBaselineSource import com.devil.phoenixproject.presentation.components.CompactNumberPicker import com.devil.phoenixproject.presentation.components.EquipmentRackSelectionCard import com.devil.phoenixproject.presentation.components.ExerciseDemoImage import com.devil.phoenixproject.presentation.components.ExpressiveSlider +import com.devil.phoenixproject.presentation.components.PowerLossSavedTargetFacts +import com.devil.phoenixproject.presentation.components.PowerLossSetTargetSection import com.devil.phoenixproject.presentation.components.ProgressionSlider import com.devil.phoenixproject.presentation.viewmodel.ExerciseConfigViewModel import com.devil.phoenixproject.presentation.viewmodel.ExerciseType @@ -507,6 +510,31 @@ fun ExerciseEditBottomSheet( onRepeatCountChange = viewModel::onRepeatCountChange, // Issue #667 ) + // Issue #1392 — Set target section beside the rep settings + // (ui-spec §2). Saved target facts (`Saved reps: 12` + + // `Power-loss target active`) render above the section; edits run + // through the pure draft state machine and commit atomically on + // Save. This sheet is configuration only — active-set UI never + // edits the target (`Target locked for this set.`). + val powerDraft by viewModel.powerLossDraft.collectAsState() + PowerLossSavedTargetFacts( + savedNominalReps = powerDraft.committed.savedNominalReps, + powerActive = powerDraft.committed.targetMode == TargetMode.POWER && + powerDraft.protocolFamily.supportsPowerLoss, + ) + Surface( + modifier = Modifier.fillMaxWidth(), + shape = MaterialTheme.shapes.small, + color = MaterialTheme.colorScheme.surface, + border = BorderStroke(1.dp, MaterialTheme.colorScheme.surfaceVariant), + shadowElevation = 2.dp, + ) { + PowerLossSetTargetSection( + draft = powerDraft, + onDraftChange = viewModel::onPowerLossDraftChange, + ) + } + // Per Set Rest Time toggle — immediately follows SetsConfiguration so rest // config lives in the same primary zone as the sets it applies to. Surface( diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/HistoryTab.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/HistoryTab.kt index 1d068614c..63826a8d9 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/HistoryTab.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/HistoryTab.kt @@ -53,6 +53,10 @@ import androidx.compose.ui.draw.shadow import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.devil.phoenixproject.data.ble.HrmBleManager +import com.devil.phoenixproject.domain.powerloss.PowerLossSetEvidence +import com.devil.phoenixproject.presentation.powerloss.PowerLossHistorySetUi +import com.devil.phoenixproject.presentation.powerloss.PowerLossUiCopy +import com.devil.phoenixproject.presentation.powerloss.powerLossHistorySet import com.devil.phoenixproject.data.repository.BiomechanicsRepository import com.devil.phoenixproject.data.repository.CompletedSetRepository import com.devil.phoenixproject.data.repository.ExerciseRepository @@ -781,6 +785,10 @@ private fun RepDetailsSection( weightUnit: WeightUnit, formatWeight: (Float, WeightUnit) -> String, repMetricRepository: RepMetricRepository, + // Issue #1392: per-set power-loss evidence (WorkoutExitSnapshot.powerLossEvidence). + // Threading from the history store lands with the parallel persistence packet; + // empty keeps the legacy section byte-for-byte. + powerLossEvidence: List = emptyList(), ) { var repMetrics by remember { mutableStateOf>(emptyList()) } @@ -794,6 +802,28 @@ private fun RepDetailsSection( } } + // Issue #1392 — compact power-loss rows (ui-spec §6) via PowerLossHistoryUi: + // one line per working attempt (`coreLine`), attempt-only and trigger-only rows + // stay visible, missing data shows `—` with a reason — never a fabricated zero. + if (powerLossEvidence.isNotEmpty()) { + Spacer(modifier = Modifier.height(Spacing.medium)) + + Text( + PowerLossUiCopy.DETAILS_EXPAND_LABEL, + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.primary, + ) + + Spacer(modifier = Modifier.height(Spacing.small)) + + Column(verticalArrangement = Arrangement.spacedBy(Spacing.small)) { + powerLossEvidence.forEach { evidence -> + PowerLossHistoryRows(ui = powerLossHistorySet(evidence)) + } + } + } + if (repMetrics.isNotEmpty()) { Spacer(modifier = Modifier.height(Spacing.medium)) @@ -818,6 +848,54 @@ private fun RepDetailsSection( } } +/** + * Issue #1392 — compact power-loss rows for history (ui-spec §6). + * + * One compact line per working attempt from [PowerLossHistorySetUi.coreRows]; + * the config header line and trigger-only row stay visible, and the local-data + * disclosure is always rendered. + */ +@Composable +private fun PowerLossHistoryRows(ui: PowerLossHistorySetUi) { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer), + shape = MaterialTheme.shapes.small, + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(Spacing.small), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Text( + text = ui.headerLine, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + ui.coreRows.forEach { row -> + Text( + text = row, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurface, + ) + } + ui.triggerOnlyRow?.let { + Text( + text = it, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Text( + text = ui.disclosure, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.8f), + ) + } + } +} + /** * Data class to hold grouped exercise information within a routine */ diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/IntegrationsScreen.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/IntegrationsScreen.kt index f2759c946..ac3c55f83 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/IntegrationsScreen.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/IntegrationsScreen.kt @@ -153,6 +153,33 @@ fun IntegrationsScreen( ) } + // ── Power-history file saver (issue #1392 `Export power data`) ──────────── + var triggerPowerSave by remember { mutableStateOf(false) } + + LaunchedEffect(uiState.powerExportResult) { + if (uiState.powerExportResult != null) { + triggerPowerSave = true + } + } + + if (triggerPowerSave && uiState.powerExportResult != null) { + val filePicker = rememberFilePicker() + val powerExport = uiState.powerExportResult!! + filePicker.LaunchFileSaver( + fileName = powerExport.displayName, + content = powerExport.content, + onSaved = { path -> + triggerPowerSave = false + viewModel.clearPowerExportContent() + if (path != null) { + scope.launch { + snackbarHostState.showSnackbar("Power data saved successfully") + } + } + }, + ) + } + // ── CSV file picker (import) ────────────────────────────────────────────── var triggerCsvImport by remember { mutableStateOf(false) } @@ -575,7 +602,10 @@ fun IntegrationsScreen( OutlinedButton( onClick = { csvExportWeightUnit = csvWeightUnit - viewModel.exportCsv(csvWeightUnit) + // Issue #1392 (ui-spec §6): a legacy export always surfaces + // the omission disclosure first — this format omits + // power-loss settings and per-attempt details. + viewModel.requestLegacyExport() }, enabled = !uiState.isExporting, shape = MaterialTheme.shapes.small, @@ -612,6 +642,61 @@ fun IntegrationsScreen( } } } + + // Issue #1392 — `Export power data` entry (ui-spec §6): the versioned + // power-history export preserves null/zero and attempt identity. + val powerLossExportUi = remember { com.devil.phoenixproject.presentation.powerloss.PowerLossExportUi() } + OutlinedButton( + onClick = { viewModel.exportPowerData() }, + enabled = !uiState.isPowerExporting && !uiState.isExporting, + shape = MaterialTheme.shapes.small, + modifier = Modifier.fillMaxWidth(), + ) { + if (uiState.isPowerExporting) { + LoadingIndicator(LoadingIndicatorSize.Small) + } else { + Icon( + Icons.Default.Upload, + contentDescription = null, + modifier = Modifier.size(16.dp), + ) + Spacer(Modifier.width(4.dp)) + Text( + powerLossExportUi.entryLabel, + style = MaterialTheme.typography.labelMedium, + ) + } + } + Text( + powerLossExportUi.localDataDisclosure, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + // Issue #1392 — legacy-export omission disclosure (ui-spec §6). The + // dialog is shown BEFORE any legacy export run; outside dismissal runs + // nothing. + uiState.legacyExportConfirmation?.let { confirmation -> + AlertDialog( + onDismissRequest = { viewModel.dismissLegacyExportConfirmation() }, + text = { Text(confirmation.disclosure) }, + confirmButton = { + TextButton(onClick = { viewModel.choosePowerDataExport() }) { + Text(confirmation.primaryAction) + } + }, + dismissButton = { + TextButton( + onClick = { + csvExportWeightUnit = csvWeightUnit + viewModel.exportWithoutPowerDetails(csvWeightUnit) + }, + ) { + Text(confirmation.secondaryAction) + } + }, + ) + } } } diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/JustLiftScreen.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/JustLiftScreen.kt index 60298a162..1d16fa8d4 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/JustLiftScreen.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/JustLiftScreen.kt @@ -99,10 +99,16 @@ import com.devil.phoenixproject.domain.model.WorkoutState import com.devil.phoenixproject.domain.model.eccentricLoadLabel import com.devil.phoenixproject.domain.model.echoLevelLabel import com.devil.phoenixproject.domain.model.toWorkoutMode +import com.devil.phoenixproject.domain.powerloss.PowerLossProtocolFamily import com.devil.phoenixproject.presentation.components.CompactNumberPicker +import com.devil.phoenixproject.presentation.components.PowerLossSetTargetSection +import com.devil.phoenixproject.presentation.components.PowerLossTargetReadbackCard import com.devil.phoenixproject.presentation.components.ProgressionSlider import com.devil.phoenixproject.presentation.components.RestTimePickerDialog import com.devil.phoenixproject.presentation.navigation.NavigationRoutes +import com.devil.phoenixproject.presentation.powerloss.PowerLossConfigDraftState +import com.devil.phoenixproject.presentation.powerloss.powerLossExecutionSupported +import com.devil.phoenixproject.presentation.powerloss.powerLossTargetReadback import com.devil.phoenixproject.presentation.util.DurationFormatter import com.devil.phoenixproject.presentation.util.WeightDisplayFormatter import com.devil.phoenixproject.presentation.util.isCompactAccessibilityLayout @@ -164,6 +170,22 @@ fun JustLiftScreen(navController: NavController, viewModel: MainViewModel) { var stallDetectionEnabled by rememberSaveable { mutableStateOf(true) } var restSeconds by rememberSaveable { mutableStateOf(60) } // Rest timer between sets (0 = off) var defaultsProfileId by remember { mutableStateOf(null) } + // Issue #1392 — Set target draft (ui-spec §2: controls below the mode/load + // controls, above Start). Ad-hoc choices apply to the next execution only; + // the active set is frozen (`Target locked for this set.`) and edits take + // effect next execution. No cross-profile reuse. + var powerDraft by remember { + mutableStateOf( + PowerLossConfigDraftState.seededFrom( + config = workoutParameters.powerLoss, + maxAllowedWorkingReps = 254, + protocolFamily = PowerLossProtocolFamily.of( + workoutParameters.programMode, + isJustLiftExecutionStyle = true, + ), + ), + ) + } // Profile-scoped workout defaults val profileRepository: UserProfileRepository = koinInject() val activeProfileContext by profileRepository.activeProfileContext.collectAsState() @@ -219,6 +241,14 @@ fun JustLiftScreen(navController: NavController, viewModel: MainViewModel) { } } + // Issue #1392: mode switches move the capability gate (ui-spec §3). + LaunchedEffect(selectedMode) { + val family = PowerLossProtocolFamily.of(selectedMode.toProgramMode(), isJustLiftExecutionStyle = true) + if (powerDraft.protocolFamily != family) { + powerDraft = powerDraft.copy(protocolFamily = family) + } + } + // Navigate to ActiveWorkout when workout becomes active LaunchedEffect(workoutState) { if (workoutState is WorkoutState.Active) { @@ -270,6 +300,7 @@ fun JustLiftScreen(navController: NavController, viewModel: MainViewModel) { restSeconds, weightUnit, defaultsLoaded, + powerDraft, ) { // Don't write params until saved defaults have been loaded. // Without this guard, the effect fires immediately with the hardcoded @@ -296,6 +327,10 @@ fun JustLiftScreen(navController: NavController, viewModel: MainViewModel) { repCountTiming = repCountTiming, selectedExerciseId = null, // Issue #97: Clear exercise ID for Just Lift sessions justLiftRestSeconds = restSeconds, // Issue #113: Configurable rest timer + // Issue #1392: the Set-target draft's committed config freezes into + // the parameters for the next execution (valid drafts commit + // atomically; an invalid draft keeps the last committed config). + powerLoss = powerDraft.apply().committed, ) Logger.d { "JustLift: Updating params - eccentricLoad=${eccentricLoad.percentage}%, echoLevel=${newEchoLevel.displayName}" } viewModel.updateWorkoutParameters(updatedParameters) @@ -762,6 +797,34 @@ fun JustLiftScreen(navController: NavController, viewModel: MainViewModel) { } } + // Issue #1392 — Set target (ui-spec §2: below the mode/load controls, + // above Start) plus the pre-set target readback facts. Ad-hoc choices + // apply to the next execution only; the active set is read-only. + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerHigh, + ), + shape = MaterialTheme.shapes.medium, + ) { + PowerLossSetTargetSection( + draft = powerDraft, + onDraftChange = { powerDraft = it }, + ) + } + PowerLossTargetReadbackCard( + powerLossTargetReadback( + config = powerDraft.committed, + supportedExecution = powerLossExecutionSupported( + config = powerDraft.committed, + mode = selectedMode.toProgramMode(), + isJustLiftExecutionStyle = true, + ), + savedNominalReps = powerDraft.committed.savedNominalReps, + locked = false, + ), + ) + // Active workout status (replaces mode cards when active) if (workoutState !is WorkoutState.Idle) { ActiveStatusCard( diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/SetReadyScreen.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/SetReadyScreen.kt index c282e81ae..d0a30211e 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/SetReadyScreen.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/SetReadyScreen.kt @@ -78,12 +78,15 @@ import com.devil.phoenixproject.presentation.components.EchoLevelPillSelector import com.devil.phoenixproject.presentation.components.EquipmentRackSelectionCard import com.devil.phoenixproject.presentation.components.ExerciseDemoImage import com.devil.phoenixproject.presentation.components.ExerciseQuickHistoryCard +import com.devil.phoenixproject.presentation.components.PowerLossTargetReadbackCard import com.devil.phoenixproject.presentation.components.SliderWithButtons import com.devil.phoenixproject.presentation.components.StartGateLabel import com.devil.phoenixproject.presentation.components.WeightChangePerRepControl import com.devil.phoenixproject.presentation.components.WeightRecommendationCard import com.devil.phoenixproject.presentation.components.WorkoutStartGateNotice import com.devil.phoenixproject.presentation.components.formatRackLoadContributionSummary +import com.devil.phoenixproject.presentation.powerloss.powerLossExecutionSupported +import com.devil.phoenixproject.presentation.powerloss.powerLossTargetReadback import com.devil.phoenixproject.presentation.components.toStartGatePresentation import com.devil.phoenixproject.presentation.navigation.NavigationRoutes import com.devil.phoenixproject.presentation.navigation.safePopOrNavigate @@ -491,6 +494,28 @@ fun SetReadyScreen(navController: NavController, viewModel: MainViewModel, exerc Spacer(Modifier.height(12.dp)) + // Issue #1392 — Set target readback before the set (ui-spec §2). The + // target is edited in the exercise configuration surfaces, never from + // here; during the set the HUD renders `Target locked for this set.` + PowerLossTargetReadbackCard( + powerLossTargetReadback( + config = currentExercise.powerLoss, + supportedExecution = powerLossExecutionSupported( + config = currentExercise.powerLoss, + mode = currentExercise.programMode, + isJustLiftExecutionStyle = false, + isTimed = currentExercise.duration != null, + isBodyweight = isBodyweight, + ), + savedNominalReps = if (currentExercise.isAmrapSet(setReadyState.setIndex)) { + null + } else { + setReadyState.adjustedReps + }, + locked = false, + ), + ) + // Issue #600: once-per-session Current bodyweight card for any routine // containing a bodyweight exercise, even if the current Set Ready exercise is cable. if (bodyweightPromptPending) { diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/SetSummaryCard.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/SetSummaryCard.kt index 3c63a5b8f..f3564cbed 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/SetSummaryCard.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/SetSummaryCard.kt @@ -39,6 +39,13 @@ import com.devil.phoenixproject.domain.model.SetQualitySummary import com.devil.phoenixproject.domain.model.StrengthProfile import com.devil.phoenixproject.domain.model.WeightUnit import com.devil.phoenixproject.domain.model.WorkoutState +import com.devil.phoenixproject.domain.powerloss.PowerLossSetSummaryFacts +import com.devil.phoenixproject.presentation.powerloss.PowerLossAttemptRowUi +import com.devil.phoenixproject.presentation.powerloss.PowerLossRepTableUi +import com.devil.phoenixproject.presentation.powerloss.PowerLossSummaryUi +import com.devil.phoenixproject.presentation.powerloss.PowerLossUiCopy +import com.devil.phoenixproject.presentation.powerloss.PowerLossUiFacts +import com.devil.phoenixproject.presentation.powerloss.powerLossSummaryUi import com.devil.phoenixproject.presentation.components.RpeIndicator import com.devil.phoenixproject.presentation.util.AchievedLoadPresentation import com.devil.phoenixproject.presentation.util.ContentAwareFit @@ -117,6 +124,10 @@ fun SetSummaryCard( isTerminalSummary: Boolean = false, hrmBleManager: HrmBleManager? = null, workoutRepository: WorkoutRepository? = null, + // Issue #1392: power-loss set-summary facts. `WorkoutState.SetSummary.powerLoss` + // arrives with the parallel packet; passed through PowerLossUiFacts until then. + // Null renders no power block (plain REP sets unchanged). + powerLossFacts: PowerLossSetSummaryFacts? = null, ) { // State for RPE tracking var loggedRpe by remember { mutableStateOf(null) } @@ -190,6 +201,14 @@ fun SetSummaryCard( val setWeightUnitText: String = primary.unitText val durationFormatted = DurationFormatter.formatDuration(summary.durationMs) + // Issue #1392 — power-loss summary projection (ui-spec §6). SD6: the headline + // renders ONLY with its adjacent `8 completed reps · lifting attempt 9` + // clarification; the completed count is never promoted to the headline. + // The engine freezes facts into `WorkoutState.SetSummary.powerLoss`; the + // explicit `powerLossFacts` param stays an override seam for callers/tests. + val powerLossSummary = PowerLossUiFacts.summaryFacts(powerLossFacts ?: summary.powerLoss) + ?.let { powerLossSummaryUi(it) } + // Peak/Avg forces - take max of both cables for display // Force values are per-cable measurements; primary display stays per-cable. val peakConcentric = WeightDisplayFormatter.toDisplayWeight(maxOf(summary.peakForceConcentricA, summary.peakForceConcentricB), weightUnit) @@ -274,6 +293,11 @@ fun SetSummaryCard( } } + // Issue #1392 — power-loss block (renders only for POWER sets). + powerLossSummary?.let { powerUi -> + PowerLossSummaryBlock(ui = powerUi) + } + // Stats Grid: one-column fallback when two cards can't fit their actual content // side by side (#1385). The decision measures rendered text at the current font // scale — values, labels and units — instead of a fixed width/fontScale ratio, @@ -2003,3 +2027,172 @@ private fun WeakestComponentTip(quality: SetQualitySummary) { } } } + +/** + * Issue #1392 — power-loss summary block (ui-spec §6, SD6 binding). + * + * The `Stopped at rep 9 — 21% power loss (best: rep 2)` headline renders ONLY + * adjacent to its `8 completed reps · lifting attempt 9` clarification; the + * completed count comes from actualReps and is never promoted to the headline. + */ +@Composable +private fun PowerLossSummaryBlock(ui: PowerLossSummaryUi) { + Card( + modifier = Modifier.fillMaxWidth(), + shape = MaterialTheme.shapes.medium, + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer), + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(12.dp), + verticalArrangement = Arrangement.spacedBy(4.dp), + ) { + ui.powerActiveBadge?.let { + Text( + text = it, + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.primary, + ) + } + ui.headline?.let { headline -> + Text( + text = headline, + style = MaterialTheme.typography.titleSmall, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurface, + ) + // SD6: the clarification must render adjacent to the headline. + ui.clarification?.let { + Text( + text = it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + ui.unavailableLine?.let { + Text( + text = it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + ui.secondaryLine?.let { + Text( + text = it, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Text( + text = ui.configLine, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + text = ui.helpLine, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.8f), + ) + // ui-spec F06 — per-attempt MCP table behind a `Power details` + // expandable. Rows carry text badges inline (coreLine) and expandable + // detail pairs (reference-at-decision, ROM A/B, con/ecc with quality). + PowerLossRepTable(ui = ui.table) + Text( + text = ui.savedRepsHeader, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + ui.savedRepReadback?.let { + Text( + text = it, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + Text( + text = ui.disclosure, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.8f), + ) + } + } +} + +/** + * Issue #1392 — summary per-attempt MCP table (ui-spec F06) behind a + * `Power details` expandable. One compact row per working attempt (`coreLine` + * carries the text badges); a row expands to its detail pairs (reference at + * decision, ROM A/B, con/ecc with quality). Missing metrics stay `—` with a + * reason — never a fabricated zero. + */ +@Composable +private fun PowerLossRepTable(ui: PowerLossRepTableUi) { + var expanded by remember { mutableStateOf(false) } + Column(modifier = Modifier.fillMaxWidth()) { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { expanded = !expanded } + .padding(vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text( + text = PowerLossUiCopy.DETAILS_EXPAND_LABEL, + style = MaterialTheme.typography.labelSmall, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.primary, + ) + Icon( + imageVector = if (expanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore, + contentDescription = if (expanded) { + "Hide ${PowerLossUiCopy.DETAILS_EXPAND_LABEL}" + } else { + "Show ${PowerLossUiCopy.DETAILS_EXPAND_LABEL}" + }, + modifier = Modifier.size(16.dp), + tint = MaterialTheme.colorScheme.primary, + ) + } + if (expanded) { + Text( + text = ui.caption, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + ui.rows.forEach { row -> + PowerLossAttemptRow(row = row) + } + } + } +} + +/** One expandable attempt row: compact `coreLine`, tap to reveal detail pairs. */ +@Composable +private fun PowerLossAttemptRow(row: PowerLossAttemptRowUi) { + var open by remember { mutableStateOf(false) } + Column(modifier = Modifier.fillMaxWidth()) { + Text( + text = row.coreLine, + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier + .fillMaxWidth() + .clickable { open = !open } + .padding(vertical = 2.dp), + ) + if (open) { + row.details.forEach { (label, value) -> + Text( + text = "$label: $value", + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(start = 8.dp, bottom = 2.dp), + ) + } + } + } +} diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutHud.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutHud.kt index fcf8fdf8b..5739906e4 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutHud.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutHud.kt @@ -27,6 +27,10 @@ import com.devil.phoenixproject.data.repository.ExerciseImageEntity import com.devil.phoenixproject.data.repository.ExerciseRepository import com.devil.phoenixproject.domain.model.* import com.devil.phoenixproject.domain.model.BiomechanicsRepResult +import com.devil.phoenixproject.domain.powerloss.PowerLossHudState +import com.devil.phoenixproject.presentation.powerloss.PowerLossHudUi +import com.devil.phoenixproject.presentation.powerloss.PowerLossUiFacts +import com.devil.phoenixproject.presentation.powerloss.powerLossHudUi import com.devil.phoenixproject.presentation.components.AnimatedRepCounter import com.devil.phoenixproject.presentation.components.CircularForceGauge import com.devil.phoenixproject.presentation.components.EnhancedCablePositionBar @@ -93,6 +97,10 @@ fun WorkoutHud( velocityLossThresholdPercent: Int = 20, rackLoadAdjustment: RackLoadAdjustment = RackLoadAdjustment(), currentWarmupSetIndex: Int = -1, // Issue #646: -1 = no warm-up phase + // Issue #1392: live power-loss HUD facts. The parallel engine packet adds the + // `powerLossHud` StateFlow; until it lands, callers pass null and the + // PowerLossUiFacts adapter supplies the inert state (never a fabricated readout). + powerLossHudState: PowerLossHudState? = null, modifier: Modifier = Modifier, ) { // Determine if we're in Echo mode @@ -101,6 +109,20 @@ fun WorkoutHud( val topBarModeLabel = if (isCurrentExerciseBodyweight) "Bodyweight" else workoutParameters.programMode.displayName val currentRoutineExercise = loadedRoutine?.exercises?.getOrNull(currentExerciseIndex) + // Issue #1392 — HUD projection (ui-spec §4): `Power-loss target · 20%` / + // `Max 20 working reps` readback plus the completed-vs-attempt identity line. + // Strictly from PowerLossHudUi facts; nothing renders for REP sets. + // SD6: warm-up identity comes from the separate warm-up rep counter; watts and + // the qualifying streak ride on the engine's PowerLossHudState (never invented here). + val powerLossHud = powerLossHudUi( + state = PowerLossUiFacts.hudFacts(powerLossHudState), + warmupActive = repCount.warmupReps > 0 && !repCount.isWarmupComplete, + referenceRomUncertain = powerLossHudState?.referenceRomUncertain == true, + latestPowerWatts = powerLossHudState?.lastMcpWatts, + bestWatts = powerLossHudState?.bestMcpWatts, + qualifyingCount = powerLossHudState?.qualifyingCount, + ) + // Determine gradient for background based on phase? // For now, keep it simple dark/light surface Scaffold( @@ -140,25 +162,30 @@ fun WorkoutHud( val exerciseName = currentRoutineExercise?.exercise?.name val totalSets = currentRoutineExercise?.setReps?.size ?: 0 - ExecutionPage( - metric = metric, - repCount = repCount, - weightUnit = weightUnit, - formatWeight = formatWeight, - workoutParameters = workoutParameters, - isEchoMode = isEchoMode, - echoForceKgMax = currentHeuristicKgMax, - exerciseName = exerciseName, - currentSetIndex = currentSetIndex, - totalSets = totalSets, - timedExerciseRemainingSeconds = timedExerciseRemainingSeconds, - isCurrentExerciseBodyweight = isCurrentExerciseBodyweight, - isExerciseTimerPaused = isExerciseTimerPaused, - onPauseExerciseTimer = onPauseExerciseTimer, - onResumeExerciseTimer = onResumeExerciseTimer, - onResetExerciseTimer = onResetExerciseTimer, - currentWarmupSetIndex = currentWarmupSetIndex, - ) + Column(modifier = Modifier.fillMaxSize()) { + if (powerLossHud.visible) { + PowerLossHudReadout(hud = powerLossHud) + } + ExecutionPage( + metric = metric, + repCount = repCount, + weightUnit = weightUnit, + formatWeight = formatWeight, + workoutParameters = workoutParameters, + isEchoMode = isEchoMode, + echoForceKgMax = currentHeuristicKgMax, + exerciseName = exerciseName, + currentSetIndex = currentSetIndex, + totalSets = totalSets, + timedExerciseRemainingSeconds = timedExerciseRemainingSeconds, + isCurrentExerciseBodyweight = isCurrentExerciseBodyweight, + isExerciseTimerPaused = isExerciseTimerPaused, + onPauseExerciseTimer = onPauseExerciseTimer, + onResumeExerciseTimer = onResumeExerciseTimer, + onResetExerciseTimer = onResetExerciseTimer, + currentWarmupSetIndex = currentWarmupSetIndex, + ) + } } 1 -> InstructionPage( @@ -1223,3 +1250,107 @@ private fun ExerciseTimerControls( } } } + +/** + * Issue #1392 — power-loss HUD readout (ui-spec §4). + * + * `Power-loss target · 20%` / `Max 20 working reps` (never a nominal `9 / 12` + * fraction) plus the completed-vs-attempt identity line, rendered strictly from + * [PowerLossHudUi] facts. Missing data shows `—` with a reason, never a zero. + */ +@Composable +private fun PowerLossHudReadout(hud: PowerLossHudUi) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { + Text( + text = hud.targetReadback, + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.primary, + ) + if (hud.capReadback.isNotEmpty()) { + Text( + text = hud.capReadback, + style = MaterialTheme.typography.labelMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + // Issue #1392 (P5 readback): the active set is read-only — the target is + // edited before the next set, never from active-set UI. + Text( + text = com.devil.phoenixproject.presentation.powerloss.PowerLossUiCopy.TARGET_LOCKED, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + text = hud.completedLine, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + // Issue #1392 (ui-spec §4 power panel): label + primary loss, latest + // lifting power, best-rep line, threshold line and the status text. + // Strictly the projection's facts — missing data renders `—` with a + // reason, never a fabricated zero (SD6). + Text( + text = "Power loss", + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.primary, + ) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text( + text = hud.lossDisplay, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurface, + ) + Text( + text = hud.statusLine, + style = MaterialTheme.typography.bodySmall, + color = if (hud.nearLimit) { + MaterialTheme.colorScheme.error + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, + ) + } + Text( + text = hud.latestPowerLine, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + text = hud.bestLine, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + text = hud.thresholdLine, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + // Conditional SD6 facts: invalid power + last-valid identity, trusted + // short-ROM detail, warm-up note, committed Ending set… state. + listOfNotNull( + hud.invalidPowerLine, + hud.lastValidLine, + hud.shortRomLine, + hud.referenceLimitedNote, + hud.warmupNote, + hud.endingLine, + hud.referenceResetLine, + ).forEach { line -> + Text( + text = line, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } +} diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutTab.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutTab.kt index 3c9a2c58a..ee1745ac9 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutTab.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutTab.kt @@ -197,6 +197,7 @@ fun WorkoutTab( val isCurrentExerciseBodyweight = state.isCurrentExerciseBodyweight val latestRepQualityScore = state.latestRepQualityScore val latestBiomechanicsResult = state.latestBiomechanicsResult + val powerLossHudState = state.powerLossHudState val onTagJustLiftSessionExercise = actions::onTagJustLiftSessionExercise val onClearJustLiftSessionExercise = actions::onClearJustLiftSessionExercise val motionStartHoldProgress = state.motionStartHoldProgress @@ -247,6 +248,7 @@ fun WorkoutTab( timedExerciseRemainingSeconds = timedExerciseRemainingSeconds, isCurrentExerciseBodyweight = isCurrentExerciseBodyweight, latestBiomechanicsResult = latestBiomechanicsResult, + powerLossHudState = powerLossHudState, isExerciseTimerPaused = isExerciseTimerPaused, onPauseExerciseTimer = onPauseExerciseTimer, onResumeExerciseTimer = onResumeExerciseTimer, diff --git a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutUiState.kt b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutUiState.kt index 7b122fba7..95b33bf7c 100644 --- a/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutUiState.kt +++ b/shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/WorkoutUiState.kt @@ -78,6 +78,8 @@ data class WorkoutUiState( val isCurrentExerciseBodyweight: Boolean = false, val latestRepQualityScore: Int? = null, val latestBiomechanicsResult: BiomechanicsRepResult? = null, + // Issue #1392: live power-loss HUD facts (ui-spec §4); null = inert panel (REP sets). + val powerLossHudState: com.devil.phoenixproject.domain.powerloss.PowerLossHudState? = null, // Issue #237: Motion-triggered set start hold progress (0.0-1.0, null = not active) val motionStartHoldProgress: Float? = null, // Issue #297, #228: Rest timer pause state for UI display