Skip to content

feat(power-loss): power-loss autostop core — MCP V1 signal, pure policy, engine seam (#1392) - #1401

Open
9thLevelSoftware wants to merge 32 commits into
mainfrom
feature/1392-power-loss-autostop
Open

9thLevelSoftware wants to merge 32 commits into
mainfrom
feature/1392-power-loss-autostop

Conversation

@9thLevelSoftware

@9thLevelSoftware 9thLevelSoftware commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

Summary

Implementation of the signed-off power-loss autostop (VBT-style) enhancement (issue #1392, ticket 1569561696542920725), built as the bounded spec packets on feature/1392-power-loss-autostop. Current head 620dc71b contains packets P1 + P2 complete, P3 core, P4 tier-1 + export v1, P5 main UI surfaces — all behind an inert-by-default capability gate (feature cannot arm until the escalated merge gate enables it after P6–P8).

Fixes #1392 (closes on merge of the complete packet set — see Remaining packets below).

Packet map at this head

Packet Status Contents
P0 preflight ✅ done branch from main@4d4de558; overlap recheck recorded below
P1 acquisition + identity ✅ done PowerLossAcquisition.kt MCP V1 signal (commit 9d2f4142)
P2 pure policy + target plan ✅ done PowerLossPolicy.kt / PowerLossModels.kt, SD1–SD4 hard (commit 9d2f4142)
P3 engine integration ☑ core done one-winner evidence latch, WORKOUT_COMPLETE cap normalization, live HUD, POWER-only VBT suppression, once-only near-limit cue, non-blocking stop (SD5) — commits 3d6f1e45, 547dcb95, d6ca8dc0. Remaining: ExecutionSeed/BlePacketFactory/counter/freshness single-target propagation + production-path race tests (signoff §4.2)
P4 durable companions + codecs ☑ tier-1 done set/observation companions + migration 64 + SchemaManifest/MigrationStatements + atomic evidence commit (WorkoutExitSnapshot) + power-history export v1 (codec/exporter/Koin/roundtrip) — commits 11285534, b8a92be0, dd29acdb. Remaining: backup v7 versioned companion sections, versioned routine CSV / lossy-export block, runtime snapshot codec + restart/rebaseline, golden no-new-wire-keys test
P5 config + presentation ☑ main surfaces done PowerLossConfigDraft/Propagation/UiCopy/UiFacts, ExerciseConfigModal Set-target section (presets 10/20/30 + Custom 5–40 with 36–40 caution, max-reps bound, two-consecutive), WorkoutHud power-loss readout + attempt identity, SetSummaryCard headline block, HistoryTab compact rows — commits 120561d5, 26ac02d7, 53fb2952, f49c30c7, e194b713. Remaining: ExerciseEditBottomSheet/JustLiftScreen/set-ready readback, routine/template/ad-hoc propagation through RoutineFlowManager/DefaultWorkoutSessionManager, export entry + legacy-omission disclosure, remaining ui-spec states
P6 test hardening ⬜ open close every signoff §4.1–4.3 row not yet covered; REP regression sweep on exact head
P7 visual QA ⬜ open (merge gate) implementation-branch captures, Android + iOS, light/dark, 200% text, short viewport, screen readers
P8 trainer evidence ⬜ open (release gate) physical-hardware runs; feature stays off by default behind the capability gate until the escalated merge gate decides

What landed in detail

P1 — acquisition + identity (MCP V1 signal)

  • domain/powerloss/PowerLossAcquisition.kt: versioned validated pre-EMA paired control samples (per-cable kg + raw signed mm/s + positions + device ticks + monotonic ts + quality markers), MCP V1 = arithmetic sample mean of 9.81/1000 × (loadA×max(vA,0) + loadB×max(vB,0)) W — idle cable contributes 0, no cross-cable velocity substitution, signed lowering never counts.
  • Enumerable quality reasons: sample gap, stale data, rejected sample, buffer overflow, insufficient samples, phase unavailable.
  • OrderedSampleAccumulator (ordered submit/drain, duplicate/out-of-order rejection, gap/overflow counters) and ConcentricPhaseNormalizer (concentric start above 10 mm/s forward on an active cable; end on validated top-turnaround or two fresh at/below-threshold samples; seals exactly once on the next fresh ordered sample).
  • No midpoint/first-half fallback is ever used for control input (SD1): a rep whose concentric window cannot be sealed yields phase unavailable → null MCP.

P2 — pure policy + target plan

  • domain/powerloss/PowerLossPolicy.kt: side-effect-free reducer (PowerLossObservation + PowerLossPolicyState → PowerLossDecision + persisted PowerLossObservationRecord).
  • Signoff binding corrections carried as hard requirements:
    • SD1 — control only from MCP V1; trusted short-ROM qualification survives missing power; unavailable power alone never qualifies; streak resets only on an observation with neither qualifying reason.
    • SD2 — SHORT_ROM wins over POWER_LOSS in the same sealed observation; both qualification facts (and measured loss when valid) persist; same-cycle precedence safety > manual > cap > fatigue.
    • SD3 — reference-at-decision facts frozen before any reference update; unknown/untrusted ROM never promotes the reference; missing candidate ROM is neither fabricated full-ROM nor a short-ROM stop; short reps never replace the reference; earliest-tie retention.
    • SD4 — cap enforcement independent of telemetry/streak; saved nominal reps are display-only in POWER (never stop early); finite/unlimited protocol identity preserved; protocol byte bounds supplied by the validator (never hardcoded — impossible plans are rejected).
    • Threshold semantics: unrounded 100 × (1 − MCP/bestMCP) ≥ thresholdPercent in double precision (equality qualifies; display rounding never triggers); display clamp 0–100; ≥2 working reps before any fatigue trigger.
  • PowerLossConfig / TargetMode / ExecutionTargetPlan / PowerLossProtocolFamily / PowerLossCapability (V1 effective modes: Old School, Pump, Echo, Just Lift execution style; TUT/TUT Beast/Eccentric-Only/timed/bodyweight inert; unknown target enum never arms POWER).

P3 — engine integration (core)

  • SetEndReason + MAX_REPS_BACKSTOP, POWER_LOSS, SHORT_ROM (persisted names; fromPersisted still maps unknown → UNKNOWN).
  • Per-set PowerLossSetController wired into ActiveSessionEngine's completed-rep path; observations from validated paired samples through the pure phase normalizer.
  • One-winner evidence latch (PowerLossEvidence.kt + WorkoutExitSnapshot): immutable winning reason + metrics latched before claim/teardown; raw WORKOUT_COMPLETE on a finite POWER plan normalizes to MAX_REPS_BACKSTOP (never TARGET_REPS_REACHED, never inferred fatigue).
  • POWER-only suppression of the global velocity AUTO-END and velocity-threshold voice/defer at evaluateLatestVbtResult (velocity analysis/display preserved; REP/legacy unchanged).
  • Once-per-set near-limit cue at max(0, threshold − 5) loss (HapticEvent.POWER_NEAR_LIMIT, beepsEnabled-gated, terminal supersedes, safety supersedes both); the stop path never waits for audio/animation/persistence (SD5).

P4 — durable companions + codecs (tier-1)

  • Additive SQLDelight set + observation companions (PowerLossCompanionStore.kt), migration 64 (additive .sqm; API-26-safe), SchemaManifest.kt + MigrationStatements.kt updated together (validateSchemaManifest green: 812 columns across 68 tables, all covered, order validated).
  • Atomic evidence commit into commitCompletedSet via WorkoutExitSnapshot (deep-frozen companions; attempt-only trigger rows survive).
  • Power-history export v1 (PowerHistoryExportCodec/PowerHistoryExporterImpl + Koin wiring): separately identified version, stable IDs, attempt/completed identity, frozen config, metric version, reference/trigger/winner, nullable metrics/quality, units, explicit null-vs-zero semantics + import/roundtrip validation.

P5 — config + presentation (main surfaces)

  • ExerciseConfigModal Set-target section: Rep target | Power-loss target, presets 10% 20% 30% Custom (nonbreaking labels), custom 5–40 integer validation, persistent 36–40 caution copy, Max working reps dynamic bound, two-consecutive switch (SD1-corrected helper), non-toggleable short-ROM safeguard, Echo concentric-only note.
  • WorkoutHud: Power-loss target · 20% / Max 20 working reps readout (never 9 / 12), 8 completed reps · attempt 9 not confirmed complete attempt identity, near-limit once-only state, trusted short-ROM Cable A 82% of reference, invalid-power Last valid · attempt N labeling, Ending set….
  • SetSummaryCard: Stopped at rep 9 — 21% power loss (best: rep 2) headline with the adjacent completed/attempt clarification + per-rep table layer.
  • HistoryTab: compact power-loss rows (grouped + single-session; attempt-only rows render; missing data shows —, never fabricated zeros).
  • SD6 corrections applied throughout (native layout, preset wrapping, HUD attempt/count, Ending set… vs completed, history rows, headline clarification).

Tests (all green at head 620dc71b)

New suites (123 tests, 0 failures, executed 2026-11-17 via ./gradlew -Pskip.supabase.check=true :shared:iosSimulatorArm64Test --tests … — BUILD SUCCESSFUL):

  • PowerLossPolicyTest (32) — signoff §4.1 fixture matrix: warmup exclusion, ≥2-attempt gate, positive baseline, first-row zero loss vs own reference, later-best + frozen decision facts, earliest-tie retention, no short-rep reference replacement, unrounded threshold equality (binary-exact 64→48 = 25%), sub-threshold no-trigger where display rounding would, display clamp, SHORT_ROM/POWER_LOSS tie-break with both facts, one-short-arm, 85%-equality not short (double-precision bound), trusted short ROM with null MCP, unavailable power resets streak, unknown-ROM non-promotion + non-stop, active-cable mask provenance, two-consecutive modes (either prior reason, terminal tie-break, adjacency breaks), cap without telemetry, cap > fatigue, nominal-below-cap, near-limit once-only + zero-baseline silence + terminal supersession, termination latch, config validation, unknown target enum.
  • PowerLossAcquisitionTest (14) — asymmetric/single-cable units, signed velocity, MCP sample-mean math, all six quality reasons, accumulator ordering/gap/overflow/drain semantics, phase-normalizer start/end/seal-exactly-once/top-turnaround/stale rejection.
  • ExecutionTargetPlanTest (10) — POWER finite cap derivation, impossible-plan rejection against supplied byte bounds, REP finite/unlimited identity (Just Lift/AMRAP), nominal-below-cap, capability gating (V1 mode map).
  • PowerLossSetEvidenceLatchTest (8) — one-winner latch immutability across late callbacks, WORKOUT_COMPLETE cap normalization, evidence facts frozen at decision time.
  • PowerLossConfigDraftTest (17) — config draft/commit/cancel semantics, preset/custom validation, caution band, max-reps bound, two-consecutive SD1 helper, mode-confirmation.
  • PowerLossHudUiStateTest (12) / PowerLossSummaryUiStateTest (9) / PowerLossHistoryUiStateTest (9) / PowerLossExportAndCopyGuardTest (7) — HUD attempt identity + once-only cue states, summary reason variants + headline clarification, history grouping + attempt-only rows, export copy guards + no physiological/RPE claim copy.
  • PowerHistoryExportRoundtripTest (androidHostTest) — export v1 roundtrip preserving null/zero/identity.
  • Updated: SetEndReasonTest (5) — durable-schema guard pins the ten persisted reasons.

Verification (exact head 620dc71b)

  • Targeted power-loss + end-reason suites: 123 tests / 0 failures (:shared:iosSimulatorArm64Test, BUILD SUCCESSFUL in 9m 25s; validateSchemaManifest green).
  • androidHostTest data-layer suites (export roundtrip, SchemaParityTest, Android109UpgradeTest, IntervalsMigrationTest) — result recorded in the PR evidence comment below.
  • Zero regressions proven by A/B against baseline main@4d4de558 in the same harness (phase-1 head 3d6f1e45): baseline :shared:iosSimulatorArm64Test (presentation-manager + packet-factory + end-reason suites) = 1105 tests, 14 failed; branch = the identical 1105 tests, the identical 14 failures, name-for-name. The 14 failures are pre-existing on main in this test harness and untouched by this PR:
    • 4 source-structure tests (VbtUiWiringTest ×2, WorkoutMachineTeardownTest, Issue673DropSetProductFlowTest) fail in the test-runner's readProjectFile source-location walk — same on baseline.
    • 10 set-lifecycle tests (DWSMWorkoutLifecycleTest ×7, Issue687WorkoutExecutionIsolationTest ×2, ActiveSessionEngineStopInvariantTest ×1) expect WorkoutState.SetSummary and observe WorkoutState.Completed — same assertion outcome on baseline.
  • No wire/portal changes exist in this diff by construction (buildRepSummaries / avgPowerWatts / powerWatts untouched).

Remaining packets (on this branch before merge gate)

  • P3 remainder: ExecutionSeed/BlePacketFactory/counter/freshness propagation of the one effective target; production-path race tests (signoff §4.2 — pure tests alone do not satisfy).
  • P4 remainder: backup v7 versioned companion/config sections (full + streaming + session/routine paths); explicitly versioned routine CSV or blocked lossy export; runtime snapshot codec versioning + restart/rebaseline; golden no-new-wire-keys test (signoff §4.3).
  • P5 remainder: ExerciseEditBottomSheet/JustLiftScreen/set-ready readback, routine/template/ad-hoc propagation, export entry + legacy-omission disclosure, remaining ui-spec state rows (E01–E12).
  • P6: full cross-cutting test hardening + schema parity (incl. production-consumed view registration + query-plan assertions if any view is added).
  • P7: mandatory implementation-branch visual QA (Android+iOS, light/dark, 200% text, short viewport 320 dp, keyboard, TalkBack/VoiceOver; core frames F01–F06 + E01–E12; one full-set flow video per platform) — merge gate.
  • P8: physical trainer evidence + capability-gated rollout — release gate; feature stays off by default behind the capability gate until the escalated merge gate decides.

Signoff corrections SD1–SD8 mapping

All eight carried as hard requirements; SD5 (no stop delay), SD7 (no capture-only accommodations — this branch adds none; the Phantom capture binding is disposable-source-set only per ruling t_62c3867a), and SD8 (gates, not follow-ups) enforced in code/structure. SD6 (native UI corrections) applied in the P5 surfaces landed here.

Overlap recheck (P0)

Checked immediately before coding: #1369 (audio ready cue), #1375 (JustLift exit), #1386 (archival exit-snapshot trimming), #1388 (finalization/export) are all merged into main@4d4de558. No unmerged sibling PR touches domain/powerloss/ (new package), PowerLossSetController.kt (new file), or the engine seams edited here. #1386's archival trimming never trims the live control accumulator (new OrderedSampleAccumulator is per-execution, not archival).

Visual evidence

Not yet captured — P7 is an open merge gate. No capture-only accommodations exist on this branch. Mandatory implementation-branch captures (Android + iOS) accompany the remaining packets; the merge gate holds until they exist and are referenced here.

User-instructions / release-note summary

Full user guide + release-note draft: user-instructions.md (artifact companion). Release-note draft carried in this PR:

Power-loss set termination (VBT-style) — opt-in. New per-exercise Set target: Power-loss target alternative to rep targets for Old School, Pump, Just Lift, and Echo — Phoenix computes each rep's Mean Concentric Power from paired per-cable force and velocity and ends the set when a rep drops below your threshold versus your best working rep. Threshold presets 10/20/30% and custom 5–40% (caution above 35%), a mandatory max-working-reps backstop, optional two-consecutive qualification, and a short-rep guard. Live power/loss readout in the HUD with a one-time near-limit cue at threshold − 5%; set summary headline like "Stopped at rep 9 — 21% power loss (best: rep 2)"; per-rep power history + versioned Export power data (on-device only — not synced to the portal). Rep-target behavior unchanged; feature off by default, capability-gated, pending hardware validation. Training guidance only; no efficacy or RPE-equivalence claims.

Merge policy

No merge authorized by this PR. Final merge is the escalated merge gate (phoenix-rca) after exact-head CI and fresh review of the complete packet set.

Devil added 2 commits November 14, 2026 14:05
…cy, engine seam (#1392)

Phase 1 of the signed-off power-loss autostop enhancement (issue #1392):

- domain/powerloss: validated pre-EMA paired control samples, MCP V1 signal
  (9.81/1000 x sum(load x max(v,0)) sample mean, idle cable zero, no
  cross-cable substitution), quality reasons, ordered accumulator, and a
  finite-state concentric phase normalizer (P1)
- pure PowerLossPolicy reducer with the signoff SD1-SD4 semantics: frozen
  reference-at-decision facts, unrounded threshold equality, trusted short-ROM
  qualification surviving missing power, SHORT_ROM-over-POWER_LOSS tie-break
  with both facts persisted, unknown-ROM no reference promotion, earliest-tie
  reference retention, ordinal-adjacency streak breaks, cap independence
  (P2)
- ExecutionTargetPlan + protocol byte-bound validator + capability gate;
  REP identity preserved (nominal never stops POWER early; unlimited stays
  unlimited) (P2/SD4)
- SetEndReason + MAX_REPS_BACKSTOP / POWER_LOSS / SHORT_ROM (P3, persisted
  names; unknown still maps to UNKNOWN)
- engine seam: per-set PowerLossSetController, POWER-only VBT auto-end and
  voice/defer suppression, once-per-set near-limit cue, non-blocking stop
  path (P3/SD5). Inert by default (REP_TARGET) behind the capability gate.

Tests: PowerLossPolicyTest (signoff 4.1 fixture matrix), PowerLossAcquisitionTest,
ExecutionTargetPlanTest, SetEndReasonTest updated for the new persisted reasons.
…OM bound (#1392)

- Add POWER_NEAR_LIMIT arms to the iOS and Android haptic/audio routers
  (exhaustive-when requirement); reuse existing beepboop asset, distinct
  medium-pulse haptic patterns per platform.
- SHORT_ROM_FRACTION as Double so the 85%-of-reference-ROM bound compares
  in double precision (Float 0.85f x 200 misclassifies an exact-equality
  170mm ROM as short).
- Test names: Kotlin/Native forbids commas/parens in backtick names.

Verified: :shared:iosSimulatorArm64Test --tests powerloss.* + SetEndReasonTest
= 61 tests, 0 failures (SetEndReasonTest 5, ExecutionTargetPlanTest 10,
PowerLossAcquisitionTest 14, PowerLossPolicyTest 32).
Copilot AI balanced review requested due to automatic review settings November 15, 2026 17:11

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

Devil added 13 commits November 17, 2026 09:13
PowerLossSetEvidence/PowerLossAttemptRecord/PowerLossHudState/
PowerLossSetSummaryFacts + WorkoutExitSnapshot.powerLossEvidence +
evidence-aware commitCompletedSet overloads + ExerciseConfig.powerLoss.
Pure contract only: no behavior change, legacy paths unchanged.
…y view layer (#1392)

PowerLossUiCopy (SD6 copy incl. headline clarification + nonbreaking presets),
PowerLossConfigDraft (5-40 validation, caution 36-40, max-reps bound,
two-consecutive SD1 helper), PowerLossHudUi/PowerLossSummaryUi/PowerLossHistoryUi
state renderers, PowerLossExportUi entry, PowerLossConfigPropagation,
PowerLossUiFacts adapter. Tests: config draft, HUD/summary/history state,
export + copy guards.
…ce commit (#1392)

Set/observation companion tables (migration 64, additive, API-26 safe),
PowerLossCompanionStore codec (null-vs-zero preserved), evidence-aware
commitCompletedSet(WithCompletion) overrides committing companions in the
same transaction, powerLossEvidenceForSession reads. Schema parity +
migration + upgrade tests green.
Rep target | Power-loss target toggle on PowerLossConfigDraftState; presets
10/20/30/Custom with SD6 nonbreaking labels; custom 5-40 validation and 36-40
caution; Max working reps with dynamic SD4 bound; two-consecutive switch with
SD1 helper copy; Echo concentric-only note; near-limit cue readback; local-data
disclosure. Apply commits atomically to ExerciseConfig.powerLoss; Cancel
discards the draft.
…1392 P5)

Renders 'Power-loss target · 20%' / 'Max 20 working reps' readback and the
completed-vs-attempt identity line from PowerLossHudUi on the Execution page.
The parallel engine 'powerLossHud' StateFlow is not in this tree, so facts come
through the PowerLossUiFacts adapter (inert until wired).
PowerLossSummaryUi projection: 'Stopped at rep 9 — 21% power loss (best: rep 2)'
renders ONLY with the adjacent SD6 clarification '8 completed reps · lifting
attempt 9'; config line, help, saved-reps readbacks and local-data disclosure.
Facts come via PowerLossUiFacts.summaryFacts (WorkoutState.SetSummary.powerLoss
added by the parallel packet); null renders no block for REP sets.
RepDetailsSection renders PowerLossHistoryUi compact core rows per set (header
line, per-attempt coreLine rows, trigger-only row, local-data disclosure) from
PowerLossSetEvidence via powerLossHistorySet. Optional powerLossEvidence param
keeps the legacy section byte-for-byte until the persistence packet threads
evidence from the history store.
…normalization, live HUD (#1392)

PowerLossSetController: ordered attempt records, immutable winner latch
(SD2 both-facts), buildEvidence/buildSummaryFacts/hudState; engine: finite
POWER WORKOUT_COMPLETE -> MAX_REPS_BACKSTOP (SD4), pre-teardown
WorkoutExitSnapshot.powerLossEvidence + SetSummary.powerLoss capture,
live powerLossHud StateFlow with committed Ending set... state (SD6);
no stop-path waits (SD5 unchanged). Latch tests green (8 fixtures).
@9thLevelSoftware

Copy link
Copy Markdown
Owner Author

Test evidence — head 620dc71b (2026-11-17)

Targeted power-loss + end-reason suites — :shared:iosSimulatorArm64Test — BUILD SUCCESSFUL (9m 25s)

Suite Tests Failures
PowerLossPolicyTest 32 0
PowerLossConfigDraftTest 17 0
PowerLossAcquisitionTest 14 0
PowerLossHudUiStateTest 12 0
ExecutionTargetPlanTest 10 0
PowerLossHistoryUiStateTest 9 0
PowerLossSummaryUiStateTest 9 0
PowerLossSetEvidenceLatchTest 8 0
PowerLossExportAndCopyGuardTest 7 0
SetEndReasonTest 5 0
Total 123 0

P4 data-layer suites — :shared:testAndroidHostTest — BUILD SUCCESSFUL (3m 21s)

Suite Tests Failures
SchemaParityTest (fresh/upgrade/fallback parity incl. migration 64) 35 0
IntervalsMigrationTest 8 0
PowerHistoryExportRoundtripTest (export v1 null-vs-zero roundtrip) 1 0
Android109UpgradeTest 1 0
Total 45 0

validateSchemaManifest green at this head: 812 columns across 68 tables, all covered; column order matches SchemaManifest.

Regression status

Phase-1 A/B at 3d6f1e45 (recorded in PR body) proved zero regressions vs baseline main@4d4de558 (identical 1105 tests / identical 14 pre-existing failures, name-for-name). The 13 commits added since (547dcb95…620dc71b, P3/P4/P5) extend the evidence with the suites above; a full-suite sweep at the merged head is run before the merge gate and its result will be appended here.

Remaining before merge gate: P3 remainder (single-target propagation + production race tests), P4 remainder (backup v7 sections, versioned routine CSV / lossy-export block, runtime snapshot codec, golden no-new-wire-keys test), P5 remainder (bottom-sheet/JustLift/set-ready surfaces + propagation), P6 hardening, P7 implementation-branch visual QA (merge gate), P8 trainer evidence (release gate; feature stays off by default).

…1392)

Pins the exact serialized wire path set of sessions + rep telemetry (55 paths,
pre-feature contract captured on this branch whose data/sync chain is
byte-identical to main@4d4de558), asserts no power-loss identifiers reach the
wire, and guards the legacy powerWatts = avgPowerWatts mapping. Covers signoff
acceptance gate 4 'golden push payload contains no new wire keys'.
@9thLevelSoftware

Copy link
Copy Markdown
Owner Author

Full-suite A/B at merged head 5a6ff36b (appended per the evidence comment above): same harness :shared:iosSimulatorArm64Test run on baseline main@4d4de558 and the branch — baseline 4230 tests / 252 failed; branch 4348 tests / 229 failed. Zero failures unique to the branch: all 229 branch failures are pre-existing on main (name-for-name), 23 baseline-only failures are flaky sync-suite tests that pass on the branch, and the +118 test delta is the new power-loss suites. Also new since that comment: PowerLossNoNewWireKeysTest (3/3 green) — the golden no-new-wire-keys guard pinning the 55-path mobile-sync-push wire surface (sessions + rep telemetry), asserting no power-loss identifier reaches the wire and the legacy powerWatts = avgPowerWatts mapping is unchanged. 2>&1 | true

Devil added 2 commits November 17, 2026 12:45
…ss-autostop

# Conflicts:
#	shared/src/commonMain/kotlin/com/devil/phoenixproject/di/DataModule.kt
#	shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/HistoryTab.kt
#	shared/src/phoneMain/kotlin/com/devil/phoenixproject/presentation/screen/SetSummaryCard.kt
…65 (#1392)

migration 64 added by this branch raises the schema head to 65; the
persisted-file upgrade harness default and both QA guides must name the
current head (PersistedFileUpgradeHarnessContractTest).
@9thLevelSoftware

Copy link
Copy Markdown
Owner Author

PR follow-up (CI/comments hardening) — head 20e839d4

Not merge-ready yet: the signed-off packet set is still open — P3 remainder (single-target propagation + production race tests), P4 remainder (backup v7, versioned routine CSV / lossy-export block, runtime snapshot codec), P5 remainder (bottom-sheet/JustLift/set-ready + routine propagation + export UX), P6 hardening, P7 implementation-branch visual QA (merge gate — captures must come from the completed implementation branch), P8 trainer evidence (release gate). Implementation continues on this same branch/PR; the escalated merge gate still owns the merge decision.

Devil added 2 commits November 18, 2026 00:47
…ss-autostop

# Conflicts:
#	shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/Android109UpgradeTest.kt
#	shared/src/androidHostTest/kotlin/com/devil/phoenixproject/data/local/IntervalsMigrationTest.kt
#	shared/src/commonMain/kotlin/com/devil/phoenixproject/data/local/MigrationStatements.kt
#	shared/src/commonMain/kotlin/com/devil/phoenixproject/presentation/manager/WorkoutExitSnapshot.kt
#	shared/src/commonMain/sqldelight/com/devil/phoenixproject/database/migrations/64.sqm
#	shared/src/commonMain/sqldelight/com/devil/phoenixproject/database/migrations/65.sqm
@9thLevelSoftware

Copy link
Copy Markdown
Owner Author

Implementation continuation — P3/P4/P5 remainders landed; CI green at 6cc4688b

Since the last progress note (5a6ff36b), the three remaining implementation packets were completed and integrated with origin/main (ca2fefe1):

Landed in this push (head 6cc4688b)

  • P3 remainder — one ExecutionTargetPlan is derived exactly once at set start and frozen through ExecutionSeed/ExecutionLease, so the packet bytes (BlePacketFactory PROGRAM 0x04 / Echo 0x05), WorkoutCommandValidator, RepNotificationFreshnessGate, the counter config, the power policy and the HUD all read one identical effective target (POWER = cap incl. warmup accounting; REP bytes byte-identical to before; JustLift/AMRAP 0xFF sentinel identity preserved with the cap enforced in-app). Production-path race tests added (PowerLossExecutionTargetPropagationTest: same-cycle stall/manual/cap/fatigue races, winner immutability, stale-lease rejection, no manufactured windows on counter jumps, nominal-below-cap, cap with invalid telemetry, impossible-plan fail-safe).
  • P4 remainder — backup v7 versioned power-loss sections (set/observation companions + per-exercise config) across full/streaming/session/routine paths with privacy filters (aggregates retained with raw telemetry opt-in off; absent sections never wipe local data; nulls never fabricated zeros; no false synced/backed-up claims); routine CSV v3 config-preserving format (a POWER routine is never quietly exported as REP; invalid config is blocked with explicit copy); runtime snapshot codec versioning with restart/rebaseline (armed policy never resumes from incomplete samples; restore issues no machine commands).
  • P5 remainder — PowerLossSetTargetSection shared component wired into ExerciseEditBottomSheet (config-only; active-set UI stays read-only), JustLiftScreen and set-ready readback facts; routine/template/ad-hoc propagation through RoutineFlowManager/DefaultWorkoutSessionManager/ExerciseConfigViewModel/MainViewModel (unknown/excluded modes resolve to inert REP_TARGET); Export power data entry + legacy-export omission disclosure.
  • origin/main merge — resolved [Bug]: Velocity is 10x too low (stored as cm/s, labelled mm/s); set MCV and velocity loss include calibration and ramp reps #1400 metric-unit work coexistence: our migrations renumbered to 66 (companions) / 67 (per-exercise config) above main's 64/65 (schema head user_version 68); SchemaManifest/MigrationStatements/PhoenixDatabase.sq carry all four migrations; schema-version pins, QA doc markers and the noMigrationTouchesExerciseImage ratchet updated in the same pass. Note for review: our P1 acquisition constants (e.g. the 10 mm/s phase threshold) follow the spec's true mm/s units, which match the post-[Bug]: Velocity is 10x too low (stored as cm/s, labelled mm/s); set MCV and velocity loss include calibration and ramp reps #1400 ingestion scale.

Verification (exact head 6cc4688b)

  • Local: full :shared:testAndroidHostTest 6,064 tests green (includes SchemaParity fresh/upgrade/fallback/iOS-heal, BackupSerialization, DataBackupCompleteness, RoutineCsvCodec v3, PowerHistoryExportRoundtrip, PowerLossPolicy 32, PowerLossAcquisition, PowerLossExecutionTargetPropagation 10, golden PowerLossNoNewWireKeysTest 3/3 unmodified), :androidApp:testDebugUnitTest green, :shared:compileTestKotlinIosArm64 green.
  • CI: all required checks pass — Unit Tests, Build Android, iOS Test Target Compile, Android App Unit Test Results, Shared Module Test Results, Lint Check, Security Hygiene, iOS Schema Sync Check (GitGuardian informational only).

P6 — signoff §4.1–4.3 fixture → test map

§4.1 pure signal/policy: asymmetric/single-cable units + signed velocity + warmup exclusion + phase validity + ordered/gap/overflow rejection → PowerLossAcquisitionTest, PowerLossPolicyTest; baseline/new-best/earliest-tie retention → PowerLossPolicyTest; unrounded threshold equality → PowerLossPolicyTest; 85% equality-not-short boundary → PowerLossPolicyTest; trusted-ROM/null-MCP qualification (SD1) → PowerLossPolicyTest; unknown-ROM no reference promotion (SD3) → PowerLossPolicyTest; SHORT_ROM tie-break (SD2) + skipped ordinals → PowerLossPolicyTest; cap without telemetry → PowerLossPolicyTest + PowerLossExecutionTargetPropagationTest ("cap stop fires with telemetry invalid or unavailable").
§4.2 production engine integration: single plan through packet/lease/counter/HUD → PowerLossExecutionTargetPropagationTest ("power plan freezes one effective target across packet lease counter and HUD") + BlePacketFactoryTest (frame/plan agreement, REP byte-identity); nominal below cap → PowerLossExecutionTargetPropagationTest; JustLift finite/unlimited + warmup fallback → PowerLossExecutionTargetPropagationTest ("unlimited identity keeps its sentinel and caps in app") + ExecutionTargetPlanTest; modern/legacy identity → Issue673SetEndReasonLifecycleTest; no manufactured windows → PowerLossExecutionTargetPropagationTest; stale execution rejection + one completion/snapshot/navigation under races → PowerLossExecutionTargetPropagationTest + PowerLossSetEvidenceLatchTest + ActiveSessionEngineStopInvariantTest; no audio delay (SD5) → PowerLossSetEvidenceLatchTest / stop-path tests; POWER-only velocity-stop suppression → VbtEnabledRuntimeTest.
§4.3 durability/compatibility: immutable snapshot before teardown + atomic companion commit incl. attempt-only rows + retry/idempotency → WorkoutExitPersistenceTest, RepMetricPersistenceTest, PowerLossSetEvidenceLatchTest; additive migration + fresh/upgrade parity → SchemaParityTest, Android109UpgradeTest, IntervalsMigrationTest; backup full/streaming + session/routine paths + privacy filter + old-backup preservation → BackupSerializationTest, DataBackupCompletenessTest, BackupJsonNavigatorTest, BackupRestoreSyncTest; both versioned CSV contracts + lossy-export block → RoutineCsvCodecTest (v3 roundtrip + never-as-v2 + invalid block), RoutineCsvImportPlannerTest, RoutineCsvImportRepositoryTest, PhoenixCsvCodecTest, PowerHistoryExportRoundtripTest; restore/rebaseline without automatic commands → RestoredRuntimeDuplicateResumeAuthorityTest, SqlDelightActiveWorkoutRuntimeRepositoryTest; absent-field preservation on legacy pull → PortalPullAdapterTest + backup suite; unchanged legacy average power/payload + no new wire keys → PowerLossNoNewWireKeysTest (golden, pins the exact 55-path mobile-sync-push surface), HrmBackupWireKeysRegressionTest; no false synced/backed-up claim → BackupSerializationTest (no-sync-markers).

P7 visual QA — partial evidence captured from the implementation branch (merge gate still open)

Android emulator (phoenix_phantom_api36 AVD, API 36, debug build of the implementation branch, normal startup — no capture-only accommodations) config-surface frames, stored in <artifact_dir>/final-visuals/, uploaded to release tag v1.1.0 and attached to the Kanban card:

Still open for the merge gate: extended matrix (F01–F06/E01–E12 incl. HUD/summary/history states — those need the Phantom BLE machine simulation to reach an active set), Android light/dark + 200% text + 320dp + keyboard + TalkBack shots, full iOS captures (the PhoenixApp Xcode target is currently device-only — iosArm64 framework link + SDK_NAME=iphoneos guard — so the iOS Simulator route needs a dual-SDK build adaptation first), and the per-platform full-set flow videos. P8 trainer evidence remains a release gate (feature stays off-by-default behind the capability gate; simulator evidence per owner evidence policy 2026-11-17).

No merge authorized by this worker — final merge stays with the escalated merge gate.

@9thLevelSoftware

Copy link
Copy Markdown
Owner Author

P7 visual QA progress — implementation branch head 6cc4688b (iteration 3)

Android config matrix (real implementation UI, emulator, release tag v1.1.0 assets):
android-config-rep-target, android-config-power-full, android-config-power-lead, android-config-power-presets, android-config-custom-invalid, android-config-custom-36-caution, android-config-keyboard-open, android-config-disclosure, android-config-unsupported-dormant, android-config-unsupported-mode-confirm, android-dark-config-set-target, android-dark-config-power, android-200pct-config-set-target, android-200pct-config-power, android-320dp-config-set-target, android-320dp-config-power, android-320dp-config-threshold (prior iteration) plus this iteration: android-config-set-target-rep-active, android-config-powerloss-default-justlift, android-config-custom-35-no-caution, android-config-maxreps-bound-invalid (dynamic bound Enter 2–254 working reps. + short-ROM safeguard copy), android-config-two-consecutive-on, android-config-no-baseline-scaling (capability-unavailable scaling state).

iOS simulator route is now UNBLOCKED and producing evidence from the implementation branch (first iOS captures ever for this feature): ios-home, ios-single-exercise-picker, ios-single-exercise-search, ios-config-sheet-3-4-situp (real Configure Exercise sheet), ios-launch-splash. Built from a scratch checkout of head 6cc4688b with two capture-only adaptations that are not on the PR branch: (1) the pbxproj SDK guard + framework search path widened to the iosSimulatorArm64 debug framework (dual-SDK build adaptation), (2) PlatformModule.ios.kt SecureSettingsQualifier routed to the NSUserDefaults legacy store — simulator Keychain SecItemAdd fails -34018 and the app fails startup closed (STARTUP_INITIALIZATION_FAILED); logged as CAPTURE-ONLY NSUserDefaults fallback active. EULA acceptance seeded as labeled test-fixture state (eula_accepted_version=1), not a person accepting the agreement. UI driven headlessly by a semantic XCUITest driver + simctl screenshots (the sanctioned substitute for Simulator.app/computer_use).

Remaining P7 matrix (next implementation iteration):

  • iOS Set-target / power-loss config states: the exercise row tap opens Configure Exercise, but a bodyweight exercise shows Sets & Duration (no Set target card) — use a cable exercise in Reps mode; sheet scrolls must start inside the sheet content (edge swipes dismiss the sheet).
  • Extended states E01–E12 (live HUD/summary/history incl. near-limit cue, short-ROM, consecutive 1-of-2) on both platforms — require Phantom BLE machine simulation (PhantomBleRepository exists only in iosSimulatorArm64Main and is unbound at this head; wiring is scratch-checkout work per the phantom harness recipe).
  • Android TalkBack / iOS VoiceOver focus shots (TalkBack is not installed on the emulator AVD).
  • Per-platform full-set flow videos.
  • iOS light/dark + 200% text + 320dp variants of the config matrix.

P8 physical-trainer evidence remains the RELEASE GATE (owner evidence policy 2026-11-17: simulator/emulator evidence suffices for stages and gates; hardware facts derived from code/protocol definitions; feature stays off-by-default behind the capability gate).

All 28 frames are stored under the artifact directory final-visuals/; the 10 new frames are attached to rolling release v1.1.0 as assets named above. CI at 6cc4688b remains fully green and MERGEABLE; the merge gate stays held on the P7 remainder list above.

@9thLevelSoftware

Copy link
Copy Markdown
Owner Author

P7 visual QA — iteration 4 (iOS power-loss config matrix). Progress only; the merge gate stays held.

New implementation-branch captures (head 6cc4688, real UI via headless XCUITest + simulator screenshots, no hardware), uploaded to release tag v1.1.0:

  • ios-config-cable-sheet.png — real Configure Exercise sheet for a cable exercise (Cable Chest Press, Reps mode) — the enabled power-loss capability path
  • ios-config-set-target.png — Set target section, Rep target default selected (helper + saved readback + local-data disclosure)
  • ios-config-powerloss-default.png — Power-loss target selected: lead copy, MCP explainer, threshold presets 10/20/30/Custom (20% default), Max working reps field, Require 2 consecutive reps toggle
  • ios-config-threshold-presets.png / ios-config-custom-field.png — preset row and the Custom threshold (%) field
  • ios-config-custom-36.png — custom threshold 36 typed and verified (Custom chip selected)
  • ios-config-custom-200-invalid.png — value 200 with red "Enter a whole number from 5 to 40."
  • ios-config-custom-20.png — valid custom 20 with helper
  • ios-config-maxreps-bound-invalid.png — Max working reps 1 with red "Enter 2–254 working reps."
  • ios-config-maxreps-12.png — valid 12 with helper
  • ios-config-two-consecutive-off-helper.png — two-consecutive row + OFF helper + short-ROM safeguard + safeguard help + near-limit cue + local-data disclosure (copy block evidence)
  • ios-config-short-rom-safeguard.png / ios-config-disclosure.png — short-ROM safeguard copy and local-data disclosure
  • ios-config-dormant-unavailable.png — bodyweight dormant state: "Power-loss target unavailable for this trainer." + "Use Rep target to continue."
  • ios-config-unsupported-mode-confirm.png — unsupported-mode confirmation dialog ("Use Rep target for this mode?" / "Power-loss target is not available for this mode…")
  • ios-dark-set-target.png / ios-dark-powerloss.png — dark-mode variants of the two hero states

Remaining P7 matrix: the high-threshold caution visual state (the >35 caution block; its label is present in the accessibility tree but did not render in any captured frame — likely below the pinned footer at capture time), the 2-consecutive ON state (switch tap did not toggle in the driver), extended E01–E12 live HUD/summary/history states (Phantom BLE machine simulation), accessibility focus shots, per-platform full-set flow videos, and iOS 200% text / small-viewport variants. P8 physical-trainer evidence remains the release gate (owner evidence policy 2026-11-17: simulator/emulator evidence suffices; the feature stays off-by-default behind the capability gate).

CI at head 6cc4688 remains fully green and the PR is MERGEABLE. 45 implementation-branch frames are now in final-visuals/.

@9thLevelSoftware

Copy link
Copy Markdown
Owner Author

P7 visual QA — iteration 5 (caution state, 2-consecutive ON, 200% text + narrow viewport). Progress only; the merge gate stays held.

New implementation-branch captures (head 6cc4688, real UI via headless XCUITest + simulator screenshots, no hardware), uploaded to release tag v1.1.0:

  • ios-config-custom-36-typed.png — Custom threshold 36 typed and verified (Custom chip selected, keyboard up)
  • ios-config-custom-36-caution.png — the >35 caution block rendered: "High power-loss threshold" + "Above 35% allows a larger drop before the set ends. Consider a lower threshold." (errorContainer surface) — iteration 4 could not render this state; the fix was positioning the typed field high and using one measured plain-text drag instead of scroll loops (blind scroll loops run away once AX culls the off-viewport field with the keyboard up)
  • ios-config-two-consecutive-on.png / ios-config-two-consecutive-on-helper.png — Require 2 consecutive reps = ON (switch filled, knob right) with the SD1 ON helper copy ("Two adjacent qualifying attempts are required…"), verified by helper-copy state, not just a tap
  • ios-200pct-config-*.png — config matrix at system text size UICTContentSizeCategoryAccessibilityXL (≈2.35x, ≥200%), set via the simulator's com.apple.UIKit UIPreferredContentSizeCategoryName default (the app ignores -UIPreferredContentSizeCategoryName launch arguments — verified; Compose picks the system category up at launch). Includes the 2-consecutive ON state at large text.
  • ios-320dp-config-*.png — config matrix on a narrow device (iPhone 13 mini, 360pt — the narrowest device type creatable on the iOS 27 runtime; the 320pt iPhone SE 1st-gen type cannot be created there — recorded honestly as 360pt-class evidence for the 320dp requirement)

Driver fixes this iteration (capture-only, scratch checkout; excluded from the PR branch): multi-strategy switch toggling with helper-copy verification (element tap worked where coordinate taps no-op'd), measured single drags for below-keyboard content, and first-launch EULA pre-seeding via simctl spawn defaults write <bundle> eula_accepted_version 1 for fresh simulator installs.

Remaining P7 matrix: extended E01–E12 live HUD/summary/history states (Phantom BLE machine simulation — PhantomBleRepository exists in iosSimulatorArm64Main at this head but is unbound in the simulator DI; scratch-checkout wiring + scripted rep stream is the next bounded step), Android TalkBack (not installed on the AVD) / iOS VoiceOver focus shots, and per-platform full-set flow videos. P8 physical-trainer evidence remains the release gate (owner evidence policy 2026-11-17: simulator/emulator evidence suffices; hardware facts derive from code/protocol definitions; the feature stays off-by-default behind the capability gate).

CI at head 6cc4688 remains fully green and the PR is MERGEABLE.

phoenixworker added 2 commits November 18, 2026 08:08
#1392)

The engine published PowerLossHudState per scored rep but no caller passed it
to WorkoutHud, so the signed-off ui-spec §4 power panel never rendered during a
real set. Thread the state through MainViewModel -> WorkoutUiState -> WorkoutTab
-> WorkoutHud and extend PowerLossHudState with the projection facts the
signed-off copy requires: latest/best MCP watts, the two-consecutive qualifying
streak, and the initial-ROM uncertainty flag (SD6). Warm-up identity comes from
the separate warm-up rep counter. Adds PowerLossHudWattsAndStreakWiringTest.
…adout (#1392)

PowerLossHudReadout rendered only the target/cap/locked/completed lines; the
signed-off §4 panel layout was missing its power facts: the Power loss label,
the primary loss percentage with status text, Latest lifting power, Best: rep N
and the Target/cue threshold line, plus the conditional invalid-power, last-
valid, short-ROM, warm-up and Ending set lines. All values come from the tested
PowerLossHudUi projection — missing data stays '—' with a reason (SD6).
@9thLevelSoftware

Copy link
Copy Markdown
Owner Author

P7 visual QA — iteration 6 (live-set states + two P5 gap fixes on the branch). Progress only; the merge gate stays held.

Two implementation gaps found by the live-set QA, fixed on this branch

Driving a real set through the simulator exposed that the signed-off ui-spec §4/§6 live states could not render at all — not a capture problem but two P5 wiring gaps:

  1. 24ab81f7 — HUD facts wiring. The engine published PowerLossHudState per scored rep but no caller passed it to WorkoutHud, so the power panel was inert (PowerLossUiFacts placeholder) in every real set. The state now threads MainViewModel → WorkoutUiState → WorkoutTab → WorkoutHud, and PowerLossHudState carries the projection facts the signed-off copy requires: latest/best MCP watts, the two-consecutive qualifying streak, and the initial-ROM uncertainty flag (SD6). New PowerLossHudWattsAndStreakWiringTest (3 tests).
  2. 1cab0000 — full §4 power panel render. PowerLossHudReadout rendered only the target/cap/locked/completed lines; it now renders the signed-off panel: Power loss label, primary loss % with status text (near-limit in error color), Latest lifting power … W, Best: rep N · … W, Target 20% · cue from 15%, and the conditional invalid-power / Last valid · attempt N / short-ROM / warm-up / Ending set… lines. All values come from the tested PowerLossHudUi projection; missing data stays — with a reason.

Both fixes are minimal production changes in scope of the signoff-approved spec; full *PowerLoss* host tests (99) and the Kotlin/Native test-compile gate are green locally, and all required CI checks are green at 1cab0000.

Live-set captures (13 new frames in final-visuals/, ios-live-*)

From the real implementation UI at head 1cab0000, with the scripted Phantom rep stream (capture-only seam, see disclosure below): config sheet → Set target → POWER section → set start → live HUD → trigger stop → clean closeout.

The engine's computed values match the ui-spec §6 representative fixture exactly:

  • Best: rep 2 · 300 W (fixture best rep 2, 300 W)
  • Latest lifting power 245 W / 18% at working attempt 8 with the red Near power-loss target status (fixture rep 8: 246 W, 18%; cue from 15% at T20)
  • 21% Ending set… at working attempt 9, Last valid · attempt 9 (fixture rep 9: 237 W, 21% POWER_LOSS trigger)
  • Working attempt N · lifting phase complete attempt identity, Target locked for this set. Edit before the next set., Power-loss target · 20% / Max 20 working reps readback (SD6: never a nominal 9 / 12 fraction)

Key frames uploaded to release tag v1.1.0 (ios-live-14-below-target.png, ios-live-15-near-limit.png, ios-live-20-ending.png, ios-live-21-summary.png, ios-live-03b-power-section.png).

Capture-only seam disclosure (excluded from this branch, per SD7)

The live states run through the entire real production pipeline — rep freshness gate, rep counter, per-rep metric segmentation, ConcentricPhaseNormalizer, MeanConcentricPower, PowerLossPolicy, HUD/summary — driven from a scratch-checkout-only scripted rep stream over the Phantom BLE machine simulation (ScriptedPowerScenarioRepository + IosRuntimeBindings DI seam in the simulator build only). The seam emits the same RepNotification/WorkoutMetric shapes as PhantomBleRepository's own phone rep stream; raw-packet parse fidelity remains covered by PhantomBleRepositoryTest. None of this is on the PR branch.

Remaining P7 matrix (next iteration)

  • Discrete quality states as separate scenario runs: no-baseline/first-attempt copy, invalid-power + Last valid, trusted short-ROM/null power, 2-consecutive 1-of-2 → reset → 2-of-2, cap-only MAX_REPS_BACKSTOP summary, restart/rebaseline.
  • Summary-screen headline capture (Stopped at rep 9 — 21% power loss (best: rep 2)) and the per-attempt MCP table expansion — the trigger sequence itself is captured but the routine auto-advanced to the rest screen before the static summary frame.
  • Android TalkBack (not installed on the AVD) / iOS VoiceOver focus shots; per-platform full-set flow videos.

P8 physical-trainer evidence remains the release gate (owner evidence policy 2026-11-17: simulator/emulator evidence suffices; hardware facts derive from code/protocol definitions; the feature stays off-by-default behind the capability gate).

…ble (#1392)

The set-summary power-loss block never rendered in a real set: the engine
freezes `PowerLossSetSummaryFacts` into `WorkoutState.SetSummary.powerLoss`
(P3), but `SetSummaryCard` only read its `powerLossFacts` param, which every
call site left null. The P7 live-set video confirmed the signed-off
`Stopped at rep 9 — 21% power loss (best: rep 2)` headline and the per-attempt
`Power details` table were absent from the summary.

- Feed the block from `WorkoutState.SetSummary.powerLoss` when no explicit
  `powerLossFacts` override is passed (the param stays a test seam).
- Render the per-attempt MCP table (F06) behind a `Power details` expandable:
  one compact `coreLine` row per working attempt with text badges, each row
  expanding to its reference-at-decision / ROM / con-ecc detail pairs.
- Carry `savedNominalReps` on the frozen facts so the SD6 `Saved reps: 12`
  readback derives from the set-time config (null renders `—`, never fabricated).

New `PowerLossSummaryFactsWiringTest` pins the controller→facts→summary-UI
chain (headline + adjacent SD6 clarification + table rows) so the block can
never render empty while facts are present.
@9thLevelSoftware

Copy link
Copy Markdown
Owner Author

P7 visual QA — iteration 7 (summary block gap found + fixed on the branch). Progress only; the merge gate stays held.

A third P5 gap found by the live-set video, fixed on this branch

Recording the full-set flow revealed the signed-off set-summary power-loss block never rendered — the same class of wiring gap as iteration 6's HUD fixes. The engine freezes PowerLossSetSummaryFacts into WorkoutState.SetSummary.powerLoss (P3), but SetSummaryCard only read its powerLossFacts parameter, which every call site left null. The Stopped at rep 9 — 21% power loss (best: rep 2) headline and the per-attempt Power details table were computed but never displayed.

  1. b05f9288 — summary block wiring + per-attempt table. SetSummaryCard now feeds the block from WorkoutState.SetSummary.powerLoss when no explicit override is passed (the powerLossFacts param stays a test seam), and renders the F06 per-attempt MCP table behind a Power details expandable — one compact coreLine row per working attempt with text badges (Best / Near-limit / Trigger), each row expanding to its reference-at-decision / ROM A/B / con-ecc detail pairs. savedNominalReps now rides the frozen facts so the SD6 Saved reps: 12 readback derives from the set-time config. New PowerLossSummaryFactsWiringTest pins the controller→facts→summary-UI chain so the block can never render empty while facts are present.

Summary capture (from the real implementation UI at head b05f9288)

The signed-off summary now renders end-to-end in the iOS Simulator against the real pipeline:

  • Stopped at rep 9 — 21% power loss (best: rep 2) headline + 9 completed reps · lifting attempt 9 clarification (SD6: the completed count comes from actualReps, never promoted to the headline).
  • Power-loss target active badge, Target 20% · Max 20 working reps · Consecutive requirement off config line, the SD6 help line, and the Saved reps readback.
  • The expanded per-attempt Power details table: 9 rows (attempts 1–9) with MCP watts (267→300→236 W), loss at decision (0→21%), and text badges — Best on rep 2 (300 W), Near-limit on reps 7–8, Trigger on rep 9.

The computed values match the ui-spec §6 representative fixture exactly (best rep 2 @300 W, trigger rep 9 @236 W / 21%). Frames ios-live-21-summary-headline, ios-live-22-details, ios-live-23-details-scrolled uploaded to release tag v1.1.0.

CI + verification

All required checks GREEN at b05f9288 — Build Android, iOS Test Target Compile, Unit Tests, Lint Check, Security Hygiene, iOS Schema Sync Check (native-tv + native-tv-device now pass too). MERGEABLE vs main. Local: :shared:testAndroidHostTest '*PowerLoss*' 145 tests green (incl. the 2 new wiring tests), :shared:compileTestKotlinIosArm64 green (Kotlin/Native test-name gate).

Remaining P7 matrix

  • Discrete E03–E08 quality/consecutive/cap scenario captures: the power-stop live states + summary/table are captured; the consecutive/cap-only/rom-uncertain scenario runs are in progress and their trigger timings are flaky in the scripted harness (the 2-consecutive streak and the transient summary auto-advance are easy to miss on a 1.5 s poll).
  • Android TalkBack (not installed on the AVD) / iOS VoiceOver focus shots; per-platform full-set flow videos.

P8 physical-trainer evidence remains the release gate (owner evidence policy 2026-11-17: simulator/emulator evidence suffices; hardware facts derive from code/protocol definitions; the feature stays off-by-default behind the capability gate).

The ui-spec section-4 'Initial ROM/mask uncertain' state never rendered:
powerLossHudUi accepted referenceRomUncertain but dropped it, so
'Initial movement reference limited' and its range-checks caveat could
not appear even though the controller computes the fact and WorkoutHud
passes it. Slot the caveat into the status priority (below near-limit
warnings, above the generic first-attempt/below-target states), render
the persistent note line in the HUD readout, and pin the state and its
precedence in PowerLossHudUiStateTest.
@9thLevelSoftware

Copy link
Copy Markdown
Owner Author

P7 visual QA — iteration 8 (a fourth P5 gap found + fixed; the three open scenario fixtures captured). Progress only; the merge gate stays held.

Why the scenario captures kept coming up empty (harness, not product)

The "flaky scripted triggers" of iterations 6–7 were a harness defect: the config-sheet arming helper's button geometry heuristic matched 0 buttons whenever the sheet's scroll position left the Set target heading outside its narrow y-band, so Power-loss target was never tapped and the sets ran in plain rep-target mode (no trigger, no summary, in every run). The driver now anchors on the button's own label with verified scrolling and retries until Power-loss threshold proves the section expanded. A second harness bug — the Require 2 consecutive reps switch filter matched on value == "off", but Compose switch values are empty, so the streak switch was never toggled; it now taps by row adjacency and verifies. Captures were re-taken with the fixed driver.

A fourth P5 gap found on the branch: the E04 uncertain-reference state never rendered

powerLossHudUi accepted referenceRomUncertain — computed by PowerLossSetController and passed by WorkoutHud — and then dropped it: the ui-spec §4 Initial ROM/mask uncertain state (Initial movement reference limited + Range checks may be limited until a trustworthy reference is available.) could never appear, and HUD_ROM_REFERENCE_LIMITED(_NOTE) were referenced by nothing. Fixed in d0237669: the caveat slots into the status priority (below near-limit warnings, above the generic first-attempt/below-target states), the persistent note renders in the HUD readout, and PowerLossHudUiStateTest pins the state, its precedence, and the trusted-reference counter-case. Same class of dead-wiring gap as the iteration 6 HUD and iteration 7 summary-block fixes.

Scenario fixtures captured (real implementation UI, scripted Phantom machine stream)

  • SD1 two-consecutive (E05 mixed reasons): Qualifying attempts: 1 of 2 (21% loss, Best: rep 2 · 300 W — the reference now computes exactly) → invalid-power reset (Power unavailable, Qualifying count reset) → trusted short-ROM/null-power qualifier (Short range of motion · Cable A 82% of reference) → 2-of-2 stop: summary Stopped at rep 6 — 21% power loss (best: rep 2) with Target 20% · Max 20 working reps · Consecutive requirement on, 6 completed reps · lifting attempt 6, Saved reps: 10, and the expanded per-attempt Power details table.
  • E04 uncertain ROM/mask (new fix): 0% Initial movement reference limited + Range checks may be limited until a trustworthy reference is available. at the initial masked-ROM reference; unknown-ROM attempts never promote the reference (best stays rep 1), and the invalid-power window shows Power unavailable.
  • Cap-only (max-reps backstop): the backstop commits at exactly attempt 20 (Working attempt 20 · lifting phase complete + 3% Ending set…). The earlier runs stalled in Ending set… because the scripted capture seam echoed repsSetTotal = 0, so the rep counter's workingReps >= workingTarget derivation never emitted the machine-side WORKOUT_COMPLETE event that the SD4 backstop completion consumes (RepType.WORKOUT_COMPLETE → handleSetCompletion(MAX_REPS_BACKSTOP)) — a seam fidelity gap in the never-merged capture harness, not a product defect. The seam now echoes the commanded target (20); re-run result below.
  • power-stop fixture (unchanged since iteration 7's verification) re-captured head-to-toe: below-target → near-limit → Stopped at rep 9 — 21% power loss (best: rep 2) + expanded table.

Screen readers / platform evidence

  • Android TalkBack focus shots (final-head build d0237669 on the phoenix_phantom_api36 AVD): focus walk over Rep target → Power-loss target → 10% / 20% / 30% presets → Max working reps → Require 2 consecutive reps switch → Per Set Rest Time. TalkBack ships on this AVD but disabled; it was enabled for the capture and disabled again after. Fresh final-head Android config frames replace the iteration-3 captures.
  • Android full-set flow video cannot be produced in-emulator: the Phantom BLE machine simulation exists only in iosSimulatorArm64Main (+ the tvOS fixture) — there is no Android machine-sim seam in the repo — so Android live-set/summary rendering routes to the P8 trainer runs (release gate), while the HUD/summary composables the iOS captures exercise are the shared phoneMain code Android renders. iOS VoiceOver focus shots remain open (next iteration).
  • Full-set flow videos (config → start → warm-up → reps → near-limit/qualifier → stop → summary → details) recorded per scenario on iOS Simulator and stored under final-visuals/ (ios-flow-*.mp4), uploaded to release tag v1.1.0 alongside the frames.

CI + verification

All required checks GREEN at d0237669 (Unit Tests, Build Android, iOS Test Target Compile, Lint, Security Hygiene, iOS Schema Sync, native-tv + native-tv-device; iOS Simulator Tests skipped non-blocking). MERGEABLE vs main. Local: :shared:testAndroidHostTest '*PowerLoss*' 155 tests green (incl. 3 new E04 HUD tests), :shared:compileTestKotlinIosArm64 green (Kotlin/Native test-name gate).

Remaining P7 matrix

  • Cap-only fixture closed (with one capture miss): the backstop commits at exactly attempt 20 (Working attempt 20 · lifting phase complete + 3% Ending set…) and the set completes end-to-end — the evidence frames show the post-set REST screen (UP NEXT — Set 2, rest timer counting down) and the next-set configuration card, and the flow video carries the whole transition. The Stopped at 20 working reps — max-reps limit summary card itself rendered only briefly between two poll ticks and is not in a discrete frame (a capture-timing miss, not a rendering gap — the same summary path is proven by the SD1/power-stop headline frames). Two seam/harness notes from the trace: (1) the scripted machine's repsSetTotal=0 echo suppressed the counter's WORKOUT_COMPLETE derivation (workingReps >= workingTarget) that the SD4 backstop completion consumes — the seam now echoes the commanded target (both were capture-only changes, never merged); (2) observation for follow-up: after set 1's completion, set 2's HUD briefly showed set 1's frozen power panel (Working attempt 20 … Ending set…) alongside Set 2/Calibration Reps headers — the power-loss HUD state appears not to reset at the set boundary; flagged for the merge gate to triage as a possible state-reset bug.
  • iOS VoiceOver focus shots of config/HUD.
  • P8 physical-trainer evidence remains the release gate (owner evidence policy 2026-11-17: simulator/emulator evidence suffices; hardware facts derive from code/protocol definitions; the feature stays off-by-default behind the capability gate).

Devil added 2 commits November 18, 2026 16:13
Field QA on the implementation branch saw set 1's frozen power panel
(Working attempt 20 / Ending set...) render under the next set's headers
after a max-reps backstop completion: WorkoutCoordinator._powerLossHud
was written per rep but never cleared at the set boundary.

- installBiomechanicsContext: a new set's context install starts its HUD
  clean (SD6 set-boundary rule), covering every start path.
- resetBiomechanicsContext: the frozen panel ends with the set's teardown
  (completion/manual-stop paths), identity-guarded so a late teardown can
  never wipe a newer set's live HUD.

PowerLossHudSetBoundaryResetTest pins the production-path reset at
teardown and at the next set's install, plus the SD6 non-regression that
the committed Ending set... state stays visible through the stop-to-
completed window.
…nce (#1392)

P7 field QA caught the max-reps summary card silently degrading to the
MANUAL variant: when the machine-counter completion (SD4
WORKOUT_COMPLETE -> handleSetCompletion(MAX_REPS_BACKSTOP)) claims the
one-winner latch before the final rep's metric evaluation can latch the
policy winner, buildSummaryFacts saw winnerReason=null and dropped the
signed-off 'Stopped at 20 working reps - max-reps limit' headline and
its SD6 clarification.

- buildSummaryFacts/buildEvidence accept the committed completion reason
  as a fallback winner (with the cap attempt as trigger of record) ONLY
  when the SD2 policy latch is empty; the latched winner is never
  overwritten and non-power end reasons never forge a power winner.
- SetEndReason.toPowerStopReasonOrNull maps only the power vocabulary.

PowerLossSummaryWinnerFallbackTest pins the headline/clarification, the
SD2 latch precedence, the manual/safety null-headline regression, and
evidence parity; PowerLossHudSetBoundaryResetTest pins the engine->SetSummary
wiring on the production cap path.
@9thLevelSoftware

Copy link
Copy Markdown
Owner Author

P7 visual QA — iteration 9 (two more P5-class gaps found + fixed: set-boundary HUD reset + cap-summary committed winner; the missing cap summary fixture captured).

Gap 5 (fixed in 4484dd5d): the frozen power panel leaked across the set boundary

Iteration 8's follow-up observation root-caused to a real defect: WorkoutCoordinator._powerLossHud is written per rep but was never cleared at the set boundary, so after a max-reps backstop completion set 2's HUD rendered set 1's frozen Working attempt 20 … Ending set… panel under Set 2 / Calibration Reps headers.

  • installBiomechanicsContext now starts every new set's HUD clean (covers every start path), and resetBiomechanicsContext clears the frozen panel at set teardown (completion/manual-stop paths), identity-guarded so a late teardown can never wipe a newer set's live HUD. The SD6 distinction is preserved: the committed Ending set… state stays visible through the stop-to-completed window and ends with the completed transition.
  • PowerLossHudSetBoundaryResetTest (3 tests, production DWSM/engine path) pins the reset at teardown, the clean install even after a seeded stale panel, and the endingSet SD6 non-regression.
  • Visual + textual proof from the real implementation UI: ios-sc-caponly-25-next-set-hud.png / 25b-next-set-hud-settled.png show set 2's calibration HUD with no frozen panel, and the accessibility-tree dumps (ios-sc-caponly-26-next-set-hud-labels.txt, 26b-…-settled-labels.txt) contain Set 2 + Calibration Reps with zero occurrences of Ending set, Working attempt 19/20 or any stale panel text.

Gap 6 (fixed in 1590b3cb): the max-reps summary card dropped its committed-winner headline

Iteration 8's "capture-timing miss" was not a capture problem — the frame was missing because the product rendered the card wrong. When the machine-counter completion (SD4 WORKOUT_COMPLETE → handleSetCompletion(MAX_REPS_BACKSTOP)) claims the one-winner latch before the final rep's metric evaluation can latch the policy winner, buildSummaryFacts saw winnerReason=null and the summary silently degraded to the MANUAL variant: no Stopped at 20 working reps — max-reps limit headline and no SD6 clarification, even though the committed completion reason was unambiguous.

  • The committed completion reason is now the winner of record when the SD2 latch is empty — never overwriting a latched policy winner, and non-power end reasons (manual/stall/safety/timer) never forge a power winner. Applied to both buildSummaryFacts and the P4 buildEvidence (same winner + trigger of record in history/export).
  • PowerLossSummaryWinnerFallbackTest (4 tests) pins the exact headline + SD6 clarification, SD2 latch precedence over the fallback, the manual/safety null-headline regression, and evidence parity. PowerLossHudSetBoundaryResetTest additionally pins the engine→SetSummary wiring on the production cap path.
  • Before (gap evidence, extracted from the flow video of the pre-fix head): iter9-gap5-cap-summary-missing-headline*.png — the card sat on screen ~10 s with the config line and Power details table but no headline/clarification.
  • After (final head, discrete capture): ios-sc-caponly-21-summary-headline.png — Stopped at 20 working reps — max-reps limit + 20 completed reps · lifting attempt 20 + Target 20% · Max 20 working reps · Consecutive requirement off + the expanded per-attempt Power details table (22-details, 23-details-scrolled).

Remaining P7 matrix

  • iOS VoiceOver focus shots: still open after three bounded attempts this iteration. The headless driver now reaches the simulator's Settings → Accessibility → VoiceOver toggle reliably (v2 scroll/matching fix), but the switch will not flip from XCUITest taps in either focus/activate mode (PHX_VO_SWITCH_STUCK), so the focus-ring walk cannot arm. Config-screen accessibility labels are captured in ios-vo-00-config-labels-vo-off.txt (the walk's label-dump preflight); the screen-reader matrix stands on the Android TalkBack series from iteration 8. Next-step note for whoever picks this up: try arming VO via xcrun simctl spawn <udid> defaults write com.apple.Accessibility VoiceOverTouchEnabled -bool YES + killall -u mobile accessibilityd instead of the in-app toggle, then reuse LiveSet.testVoiceOverFocus's walk.
  • Android full-set video cannot be produced in-emulator (no Android machine-sim seam in the repo) — routes to the P8 trainer runs, while the shared phoneMain HUD/summary composables are exercised by the iOS captures.
  • P8 physical-trainer evidence remains the RELEASE GATE (owner evidence policy 2026-11-17: simulator/emulator evidence suffices; hardware facts derive from code/protocol definitions; the feature stays off-by-default behind the capability gate).

CI + verification

Head 1590b3cb (set-boundary reset 4484dd5d + cap-summary winner 1590b3cb): full :shared:testAndroidHostTest 6,257 tests green (7 new regression tests), :shared:compileTestKotlinIosArm64 green (Kotlin/Native test-name gate). PR #1401 required CI green at both pushed heads (Unit Tests, Build Android, iOS Test Target Compile, Lint, Security Hygiene, iOS Schema Sync, native-tv + native-tv-device). MERGEABLE vs main. P0-P6 packets remain complete and verified; implementation continuation routes to the SAME branch/PR #1401.

@9thLevelSoftware

Copy link
Copy Markdown
Owner Author

P7 visual QA — iteration 10: the iOS VoiceOver focus-shot matrix is captured (iter9's PHX_VO_SWITCH_STUCK blocker root-caused and solved).

The blocker: the iter9 next-step needed one more discovery

The documented follow-up (simctl spawn defaults write com.apple.Accessibility VoiceOverTouchEnabled + killall accessibilityd) is on the right track but does not work as written on this host:

  • The iOS 27.0 simulator runtime ships no sh, killall, or pkill — simctl spawn of any of them fails with LaunchdSimError 111 / No such file or directory (only defaults and launchctl resolve).
  • defaults write alone flips the pref (the Settings toggle reads back ON) but does not engage the VO engine — com.apple.VoiceOverTouch stays not running, so no focus cursor appears.

The working arming path (verified on Phoenix-1392-impl, iOS 27.0):

xcrun simctl spawn <udid> defaults write /var/mobile/Library/Preferences/com.apple.Accessibility VoiceOverTouchEnabled -bool YES
xcrun simctl spawn <udid> defaults write com.apple.Accessibility VoiceOverTouchEnabled -bool YES
xcrun simctl spawn <udid> launchctl kickstart system/com.apple.VoiceOverTouch

Disarm: same defaults write … -bool NO + launchctl kill SIGTERM system/com.apple.VoiceOverTouch. VO's first enable raises a system "VoiceOver Gestures" dialog (dismissed VO-aware); it does not reappear on later enables. The headless driver arms VO mid-walk through this host-side path (navigation runs with VO off — under VO, drags are explore gestures and cannot scroll), confirmed by defaults read == 1 + the running com.apple.VoiceOverTouch service.

Focus-ring evidence (real implementation UI, head 1590b3cb)

Three bounded walk runs cover every config control; each shot shows the black VO focus cursor on the exact target element, and every screenshot shows zero state drift (20% chip stays selected, Power-loss target stays active, toggles stay off) — which is itself proof the taps were genuine VO focus moves, not activations.

Upper rows (voiceover walk):

  • ios-vo-focus-00-probe-powerloss-button.png / 01-Power-loss-target.png — cursor on Power-loss target (probe tap is a mode no-op):
    vo-powerloss
  • ios-vo-focus-02-10pct.png — cursor on the 10% preset:
    vo-10
  • ios-vo-focus-03-20pct.png / 04-30pct.png — cursors on 20% and 30%
  • ios-vo-focus-05-Max-working-reps.png — cursor on the Max working reps field (no keyboard opened):
    vo-maxreps
  • ios-vo-focus-06-Require-2-consecutive-reps.png — cursor on Require 2 consecutive reps (toggle untouched):
    vo-consecutive
  • ios-vo-focus-07-Set-target.png — cursor on the Set target section label (walked last by design; its activation would switch modes and was unsafe to walk before VO was verified on)

Lower rows (voiceover-b, pre-scrolled before arming since VO cannot scroll with one finger):

  • ios-vo-b-focus-04-Per-Set-Rest-Time.png — cursor on Per Set Rest Time (the row that is below the fold at the initial scroll position):
    vo-rest
  • ios-vo-b-focus-02-Max-working-reps.png / 03-Require-2-consecutive-reps.png — re-shot at the lower scroll position with the full supporting copy in frame (near-limit cue + local-only data note)

Custom chip (voiceover-c):

  • ios-vo-c-focus-01-Custom-chip.png — cursor on the Custom preset (its label embeds a U+2060 word joiner that defeats literal queries; matched via inner substring):
    vo-custom

Textual proof: ios-vo-focus-labels.txt, ios-vo-b-focus-labels.txt, ios-vo-c-focus-labels.txt (accessibility-tree dumps at the walk positions) and ios-vo-00-config-labels-vo-off.txt (pre-arm preflight). All 22 artifacts are on release tag v1.1.0 and stored under the ticket's final-visuals/.

Remaining P7 matrix

  • iOS VoiceOver focus shots — complete (this iteration; screen-reader matrix now stands on both the Android TalkBack series (iter8) and this iOS VO series).
  • Android full-set video cannot be produced in-emulator (no Android machine-sim seam in the repo) — routes to the P8 trainer runs, while the shared phoneMain HUD/summary composables are exercised by the iOS captures.
  • P8 physical-trainer evidence remains the RELEASE GATE (owner evidence policy 2026-11-17: simulator/emulator evidence suffices; hardware facts derive from code/protocol definitions; the feature stays off-by-default behind the capability gate).

CI + verification

No product code changed this iteration (capture-only driver work in the scratch checkout). Head remains 1590b3cb: full :shared:testAndroidHostTest 6,257 tests green, :shared:compileTestKotlinIosArm64 green, PR #1401 required CI green and MERGEABLE vs main. P0-P6 packets complete and verified; implementation continuation routes to the SAME branch/PR #1401.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: Power-loss autostop (VBT-style) — auto-end set on configurable power-loss threshold

2 participants