Implement TASK-015 metadata-driven exercise logging

This commit is contained in:
rob
2026-11-04 22:22:26 +00:00
parent 669bfc3910
commit 9c0e82037f
31 changed files with 1537 additions and 416 deletions
+26 -36
View File
@@ -1,56 +1,46 @@
# Exercise Tracker current state
- Last updated: 2026-11-04
- Current branch: `task/001-foundation`
- Worktree: `/home/rob/projects/exercise-tracker`; accepted TASK-015 source branch `task/015-equipment-ui`, authorized integration target `codex`. Verify current branch/HEAD from Git.
- TASK-015 integration base: `669bfc3`; Captain authorized committing the accepted task and fast-forward merging it to local `codex` on 2026-11-04.
Code and configuration take precedence over this summary.
Code/configuration take precedence over this summary.
## Application status
The React/Vite app shows a version 7 seven-day routine with 30 exercise definitions, actual-date navigation, exclusive Morning/Afternoon views, title-only Monday/Friday full body stretch routines, and no dog walks. A large local time-of-day clock stays in the header. Afternoon isometric holds have no prescribed time. The daily hanging goal starts at two minutes, can be edited, and persists in IndexedDB without vest details.
TASK-014 is Complete following Captain's explicit acceptance, including suitcase-carry dumbbell weights and front/side-plank vest inputs. Completed TASK-015 now uses seed v8 with 30 versioned exercise definitions. Equipment capabilities and measurement types drive reusable controls; definitions have no fixed resistance. New logging supports independent set/minute loads, dumbbell kg each/count, left/right reps or seconds, duration-only work, completion derived on explicit successful Save, partial drafts and compatible previous-session suggestions. Deep-push-up dumbbells remain handles rather than lifted resistance.
TASK-014 removes the workout, exercise, rest, and EMOM timers and all timer audio. Morning EMOM cards accept one total-reps entry and exercise-specific actual load. Regular repetition exercises accept separate reps and load for each entered set. The next set copies the preceding set's load fields but leaves reps blank. Vest, dumbbell, and EZ-bar inputs follow the routine seed; exercises using both vest and dumbbells show separate fields. A paired-dumbbell field records kilograms per dumbbell, with two dumbbells reflected in the saved total external kilograms. Bodyweight-only work records zero added weight. Earlier single-total entries remain readable and editable as legacy totals rather than being reinterpreted as components. Entries are keyed by local date and exercise in IndexedDB; browsing alone does not save a record. The database remains version 2 and preserves the hanging-goal override store. Prescribed EMOM timing and rest guidance remain visible as targets, with no app timer or volume-per-minute feature.
New EMOM work has ten minute rows and derived completed totals; conventional sets can be selected for an empty entry. Daily hang is bodyweight-only, with separate attempts, longest continuous/cumulative results and an editable initially 120-second continuous target. No workout, exercise, rest or EMOM timers/audio return. The persistent local clock, actual-date navigation, Morning/Afternoon switching, optional exercise order/ranges and Monday/Friday empty stretch headings remain. Dog walks remain excluded; their bodyweight-only assignment is documentation context.
Broader recording, a full history view, routine editing, backup, and offline reload are still planned work. The latest commit is `e86a2e7` (`Initialize Workout Tracker app shell`); the later task work is uncommitted.
Exercise details reveal available routine notes and explicit missing-content/image placeholders. Reviewed muscle/technique copy and illustrations remain TASK-004/TASK-011. Full history/progress, routine editor, backup UI, offline release and dark theme remain separate tasks. TASK-005 retains notes/body weight and recording extensions outside TASK-015.
## Storage and compatibility
IndexedDB v3 adds performanceEntries plus a compound exercise/period/format index. Original routineOverrides and strengthEntries are unchanged. Detailed schemaVersion 1 records retain definition/prescription snapshots and actual values/load/completion rows; incomplete values are null and explicit zero stays zero. Legacy aggregate EMOM, rep sets, component/total-only and weight-only records remain separately available in their original editor; no minute/side/duration values are inferred and detailed saves do not overwrite them.
The JSON adapter (no Settings UI) exports all three stores as v2 and accepts a v1 envelope containing the two legacy stores. It validates before writes and imports atomically; duplicates abort without changing existing data unless replacement is explicitly requested. No earlier shipping backup format existed. Future TASK-009 owns preview, confirmations and user-facing conflict policy. UI period preference remains in localStorage; full settings backup is future TASK-009 work.
## Validation and limits
- On 2026-11-04, TASK-014 lock-on verification passed all 27 tests across 7 files, lint and production build in the current worktree. No application changes or browser/manual checks were made; Captain validation remains pending.
- TASK-015 final verification: 129 tests across 11 files, lint, production build, Context System validation (0 warnings) and whitespace checks pass on 2026-11-04. Manual checklist is in HANDOFF. Tests cover every exercise's applicable/absent controls, variable/zero loads, counts, sides, durations, completion/drafts, suggestions, minute EMOM, continuous hang, actual App→IndexedDB integration, v1/v2 upgrades, indexed lookups, rollback and JSON round trips.
- Reviewed tracked and new task files against `codex` / `669bfc3`. Test-only fake-indexeddb 6.2.7 added; no runtime dependency change. Review corrections include target snapshot timing, preserving entered counts during suggestions and excluding invalid completed drafts from totals.
- Browser inventory is empty; in-app browser unavailable as previously checked. No visual screenshots, browser-console/network audit, real mobile/desktop overflow check or formal accessibility audit is claimed. Semantic labels/focus/disclosures are tested/static-reviewed. Captain accepted TASK-015 on 2026-11-04; no separate agent browser pass is claimed.
- The loopback-only Vite server at `http://127.0.0.1:5174/` was verified serving the current TASK-015 App module. Other ports/origins have independent browser storage; no real data was cleared. This is not an offline-release or deployment check.
- npm audit during dev-dependency installation reports existing Vite 8.0.3 / Vitest 4.1.11 toolchain advisories (1 high, 2 moderate package findings). Those baseline versions are unchanged; no advisory is attributed to fake-indexeddb. No automatic dependency upgrade was made.
- Node 24.21.0 is available at `/home/rob/.nvm/versions/node/v24.21.0/bin`; repository minimum is 20.19. No backend, authentication, cloud, remote or deployment target exists.
- On 2026-10-27, all 23 tests across 7 files passed, including strength-entry UI, date isolation, validation, IndexedDB v1-to-v2 upgrade, and hanging-goal preservation. Lint and production build passed.
- On 2026-10-28, the revised strength-entry flow passed 27 tests across 7 files, lint, production build, context validation, and `git diff --check`. Tests cover flys, mixed vest/dumbbell entries, next-set weight defaults, legacy totals, and storage consistency. The browser inventory remained empty, so visual/manual verification is still pending.
- The available computer-use inventory had no browser, so phone/desktop visual checks could not be run here. The owner previously confirmed TASK-003's UI check; the current TASK-014 layout has not been independently checked in a browser.
- Node 24.21.0 is installed outside the default shell PATH at `/home/rob/.nvm/versions/node/v24.21.0/bin`.
- Exercise illustrations and detailed technique copy are not supplied; TASK-004 can use placeholders, while TASK-011 requires reviewed assets/content. Deployment location is not selected.
## Workflow and next action
## Current work and priorities
TASK-015 is Complete following Captain’s explicit acceptance on 2026-11-04 after the count-input and checkbox corrections. TASK-016 remains planning-only. Captain has now authorized committing TASK-015 and merging it to local codex. No push/deployment is authorized. Verify the resulting refs and clean worktree after integration. No repository testtask adapter exists. See HANDOFF for the exact source/test endpoint and completed-task checklist and handoff.
TASK-014 is Complete following Captain's explicit acceptance on 2026-11-04, including suitcase-carry dumbbell inputs and front/side-plank vest inputs. Final automated checks passed 32 tests, lint and build; agent browser QA remained unavailable. TASK-006's timer scope is superseded. TASK-005 remains accepted for additional recording, including hang attempts, hold checkoffs, notes, and other previously accepted records. TASK-008 remains accepted for history and total external-load volume from recorded reps and external weight, without a time denominator.
## Floor-fly acceptance correction — 2026-11-04
## Workflow state
Floor flys now fix the dumbbell count at two and omit the redundant count input. Kg-per-dumbbell entry and saved count/volume remain accurate. Definition v2 and shared metadata-driven visibility preserve existing paired snapshots without rewriting records; other exercise count behavior is unchanged. Captain accepted this correction with TASK-015 completion on 2026-11-04.
Roborto Workflow 2.0 operating guidance is in `AGENTS.md` and `docs/WORKFLOW.md`; Context System remains 1.0. This is the sole worktree on `task/001-foundation`. It contains uncommitted work spanning multiple tasks. No integration branch, remote, merge policy, worktree directory convention, release branch, or repository testtask adapter is defined. Proposed defaults are documented for Captain review, not yet adopted.
## All dumbbell-count inputs removed — 2026-11-04
## TASK-015 planning status — 2026-11-04
Captain extended the correction to every exercise. The shared editor hides all count controls; kg-per-dumbbell entry remains. Counts stay in stored records/calculations, with definition defaults for new rows and existing historical counts preserved. Older incomplete null counts are filled from their saved definition on explicit Save only, so they can be completed without a hidden-field validation failure. Browsing never rewrites data. Captain accepted this correction with TASK-015 completion on 2026-11-04.
The matching TASK-015 record was expanded after inspection, not duplicated. This session changed documentation only; the running application/database remain unchanged. TASK-015 awaits implementation approval, the exact timer scope, and a safe agreed Git base/worktree arrangement. The latest request clarifies per-minute EMOM logging, actual per-side hold durations, continuous daily-hang target and bodyweight-only walk classification; see ADR-017 and the explicit planning overlays in SPEC/WORKOUT_ROUTINE. Existing TASK-014 Captain validation remains pending. No app tests or browser QA were rerun for this planning-only update.
## Completion checkboxes removed — 2026-11-04
## TASK-014 engaged validation — 2026-11-04
No app changes were needed based on source review; automated checks passed earlier in this session. Browser inventory is empty and in-app browser unavailable, so real-browser QA remains unverified. A loopback-only Vite acceptance endpoint is running at `http://127.0.0.1:5174/` from this worktree; it uses a distinct browser-storage origin from port 5173. Captain validation remains the completion gate; see HANDOFF for the checklist and environment.
## Suitcase-carry weight correction — 2026-11-04
TASK-014 now shows a single-dumbbell kilogram input per suitcase-carry set without requiring repetitions. Different loads (including zero) save/reload by date; a new set copies the preceding load. Existing 30–60-second-per-side targets remain separate and no actual duration is invented. Storage adds `load-sets` records in the existing v2 store without rewriting prior data. All 29 tests across 7 files, lint and build pass. Browser QA remains unavailable and Captain validation is pending.
## Plank vest correction — 2026-11-04
TASK-014 now exposes vest kilograms per set for front planks (weight-only, no reps) and side-plank hip raises (reps plus vest). Seed v7 adds unspecified vest load for these two exercises; no prescribed targets or historical records are rewritten. Old bodyweight-only rows remain readable as prior totals and require explicit conversion to component entry. All 32 tests across 7 files, lint and build pass. Browser QA remains unavailable; Captain validation is pending.
## TASK-014 acceptance — 2026-11-04
Captain explicitly confirmed “task complete” after reviewing the implemented corrections. TASK-014 is Complete. Earlier pending-validation entries above record the sequence before acceptance, not an outstanding gate. No further task was engaged, and no commit, merge or deployment was performed. TASK-015 and TASK-016 remain awaiting implementation authority.
## Authorized baseline integration — 2026-11-04
Captain selected timer-free TASK-015 and authorized committing all current pending work and merging it into local codex before implementation. Branch inspection found only task/001-foundation and no remote; codex will be created from the original foundation commit. ADR-018 and WORKFLOW establish codex as TASK-015's integration base and sequential task/015-equipment-ui branch in this worktree. No TASK-015 merge/push/deployment is authorized. Earlier unresolved timer/Git notes are superseded by this explicit instruction.
Captain requested removing redundant completion checkboxes. Explicit Save now completes fully filled valid rows; incomplete rows remain drafts and invalid entered values remain errors. Suggestions and failed saves do not create achieved totals. Editing a saved row resets only its unsaved draft state until a successful Save. Existing persisted completion flags/history stay unchanged on read, and the database schema is unchanged. Captain accepted this correction with TASK-015 completion on 2026-11-04.
+19
View File
@@ -320,3 +320,22 @@ Captain authorized committing the existing uncommitted work and merging it into
### Consequences
This resolves TASK-015's timer and dirty-baseline gates. Existing TASK-014 acceptance and completed prerequisites travel in the baseline commit. Further merges remain Captain-controlled unless explicitly authorized. The present merge instruction covers the pre-existing work, not the future TASK-015 implementation.
## ADR-019: Additive detailed performance with saved metadata
- Status: Accepted implementation; TASK-015 accepted by Captain on 2026-11-04
- Date: 2026-11-04
### Decision
Derive applicable controls from the versioned exercise definition's equipment and measurement metadata. Record new actuals as schemaVersion 1 detailed entries with date/period/exercise identity, format, definition/prescription snapshots and independent values/load/completion rows. Per-side actuals are left/right; dumbbells record kg each and one/two count. Missing draft values are null; zero is an explicit actual. New sets copy only load/count. Previous-session suggestions use compatible earlier completed detailed records and fill only empty drafts without completion or automatic save.
IndexedDB v3 adds performanceEntries with an exercise/period/format index. Keep existing strengthEntries and routineOverrides verbatim, exposing original-format records separately through their existing explicit editor. Do not decompose legacy totals, infer duration/side breakdowns or overwrite them when saving detailed entries. Do not combine both representations in volume/history. Definition changes never re-interpret saved snapshots.
Adapter JSON v2 covers all three stores; a v1 envelope supports the two legacy stores. No prior export/import implementation existed. Validate before mutation and use one atomic transaction, rejecting duplicate keys unless replacement is explicitly requested. TASK-009 still owns user-facing confirmations, import policy and backup UI. Timer-free behavior stays authoritative (ADR-018), and dark theming remains TASK-016.
TASK-015 refinement accepted by Captain (2026-11-04): floor flys always use two dumbbells. Definition v2 fixes the count at two and suppresses the redundant input, retaining kg-per-dumbbell entry and the count in stored actuals/calculations. Existing history is not rewritten; older paired snapshots hide the redundant field too. Other exercise counts are unchanged.
Subsequent TASK-015 refinement accepted by Captain (2026-11-04): remove “Dumbbells used” from every exercise. Keep count as internal load metadata with definition defaults for new rows, preserving already-recorded values. An unrecorded null count in an older draft may be filled from its saved definition only when the user explicitly saves. Kg-per-dumbbell entry and accurate total-load calculations remain.
Subsequent TASK-015 completion refinement accepted by Captain (2026-11-04): remove the per-row completion checkboxes. Successful explicit Save marks fully filled valid rows complete, leaving incomplete rows as drafts. Invalid entered values remain errors; zero is valid where applicable. Suggestions and browsing never mark achieved performance. Editing a saved row makes it an unsaved draft until Save; existing stored records are not rewritten merely by reading. Stored completion booleans remain compatible, so no database migration is required.
+56 -8
View File
@@ -1,12 +1,60 @@
# Exercise Tracker handoff
> This is a replaceable snapshot. Repository code and maintained current context take precedence.
> Replaceable snapshot; repository code and maintained context take precedence.
- Updated: 2026-11-04
- Baseline source: task/001-foundation at e86a2e7 plus reviewed pending work.
- Captain accepted TASK-014 including suitcase-carry and plank-load corrections. Final baseline checks: 32 tests across 7 files, lint and build pass. Browser QA unavailable; Captain explicitly accepted completion.
- Captain authorized committing existing uncommitted source/context and merging it into local codex before TASK-015 implementation. No codex branch or remote existed at inspection; create codex from the foundation commit and fast-forward the reviewed baseline. ADR-018 and WORKFLOW record the operation and sequential task-branch convention.
- TASK-015 timer gate resolved: retain timer-free behavior, wall clock and rest/EMOM guidance. No audio/timers return. Task branch after clean merge: task/015-equipment-ui based on codex. The future TASK-015 merge is not authorized by the baseline merge instruction.
- Current seed is v7 with 30 exercises. IndexedDB is v2, storing routineOverrides and strengthEntries. Strength entries include sets, aggregate emom and weight-only load-sets. Legacy bodyweight/total records must survive TASK-015.
- No remote, deployment or repository testtask adapter exists. Browser inventory was empty; in-app browser unavailable. Loopback Vite test server was started at http://127.0.0.1:5174/; verify runtime state before relying on it. Different ports have separate browser storage.
- TASK-015 scoped implementation follows baseline integration, focused UI design, metadata/storage/schema adapters, reusable controls, tests and Captain acceptance. Dark theme remains TASK-016; history, routine editor and backup interface remain separate tasks. Do not fabricate technique content/assets.
- Task: TASK-015 — Exercise equipment specifications and context-aware UI
- Status: Complete — Captain explicitly accepted on 2026-11-04 after the count-input and completion-checkbox corrections.
- Accepted source: TASK-015 files in `/home/rob/projects/exercise-tracker`, task branch `task/015-equipment-ui`, based on `codex` / `669bfc3`. Integration target is local `codex`; use Git HEAD/log to identify the resulting commit.
- Captain explicitly authorized committing TASK-015 and merging it into local `codex` on 2026-11-04. The merge is a fast-forward from the unchanged integration baseline. No push or deployment is authorized.
## Delivered candidate
- Definition metadata covers all 30 exercises, supported equipment, applicable measurements, side semantics, dumbbell defaults and support-handle distinction. Seed v8 aligns all assignments and daily-hang continuous target. No numeric resistance is embedded in capabilities; old plan presets do not prefill actuals.
- PerformanceEditor replaces exercise-ID control exceptions with reusable rows for reps, left/right reps, seconds, left/right seconds, equipment load/count, completion, partial saves and explicit previous-session suggestions. EMOM has ten minute rows with separate vest loads and derived completed totals; empty entries can use conventional sets. Set additions copy only load/count.
- Bodyweight-only work has no external-load inputs; vest-only work has no dumbbell/bar inputs. Daily hang attempts show longest continuous and total duration separately; only valid completed attempts can achieve the current continuous target. Changing the editable goal retains unsaved attempts; first save captures the current target while later goal edits do not rewrite saved target context.
- Cards preserve date/period navigation, wall clock and rest guidance, with shared headings on desktop and labeled stacked fields on narrow screens. Expandable details show available routine notes and honest reviewed-content/image placeholders. No timers/audio, dark theme, history interface, routine editor or backup UI added.
- IndexedDB v3 adds performanceEntries and an exercise/period/format index. The upgrade preserves old records, but older v2 application binaries cannot reopen a v3 database; downgrade is not a supported rollback path. Original routineOverrides and strengthEntries remain intact. Detailed schemaVersion 1 snapshots retain historical equipment/measurement/prescription meaning. Original records have a separate disclosure/editor; legacy totals are not spread into minutes/sides or combined with detailed records.
- JSON adapter v2 exports the three stores, accepts v1 legacy-store envelopes, validates before mutation and imports atomically. Duplicate keys roll back unless replacement is explicit. No previous shipping backup implementation existed. TASK-009 still owns Settings UI, previews, confirmations and full settings/plan-edit backup policy.
## Validation and review
Final verification on 2026-11-04: `npm test` passed **129 tests across 11 files**; `npm run lint`, `npm run build`, Context System validation (0 warnings) and `git diff --check` passed with Node 24.21.0. Tests exercise all assigned controls and absences, zero/mixed/per-set loads, dumbbell counts, sides, actual duration, minute EMOM, drafts/completion, compatible previous sessions, continuous/cumulative hang distinction, legacy read/edit paths, actual App→IndexedDB save/reload, v1/v2 upgrades, indexed queries, unsupported records, blocked upgrade, JSON round trips and whole-import rollback.
Applied Frontend UI Design, Webapp Feature, Frontend Visual QA availability check and Code Review. Reviewed tracked/untracked changes against codex and the task requirements. Review fixes preserve current target on first save, user-selected count during suggestions, snapshot-based historical controls, and valid-only achieved totals. The test-only fake-indexeddb 6.2.7 dependency permits transactional upgrade/rollback tests; runtime dependencies are unchanged.
Browser inventory returned no apps/browsers. Therefore no actual viewport screenshots, browser-console/network inspection, real keyboard journey or mobile/desktop visual pass is claimed. Existing automated navigation/clock/hang-goal tests remain green. npm audit reports baseline Vite/Vitest advisories (1 high, 2 moderate package findings); their versions are unchanged and no automatic unrelated update was applied.
## Exact acceptance environment
The existing loopback Vite server at **http://127.0.0.1:5174/** was checked serving the current App module containing PerformanceEditor. It reads the authoritative task worktree directly. No repository testtask/snapshot adapter exists. Refresh before testing; other ports and hostnames are different browser-storage origins. The loopback address is reachable on this machine; use browser responsive mode for phone widths. No existing user records were cleared.
## Floor-fly acceptance correction — 2026-11-04
Captain reported the floor-fly count input is redundant because two dumbbells are always used. Definition v2 now sets fixedDumbbellCount=2; the shared editor hides that field and retains kg each with the correct two-dumbbell resistance/volume calculation. Existing paired snapshots also hide the field without data rewrites; historical differing counts retain their original semantics. Superseded by the following all-exercise correction. Regression tests cover absent input, saved count=2, preserved snapshots and volume calculation. All 129 tests across 11 files, lint and build pass. Context and whitespace checks pass; browser verification remains unavailable.
## All dumbbell-count inputs removed — 2026-11-04
Captain requested removal across every exercise. Shared column metadata now hides all “Dumbbells used” controls. Existing kg-each inputs remain. Counts remain internal with definition defaults for new rows; historical non-null counts are preserved exactly. A null count from an old partial draft is filled from its saved definition only at explicit Save, avoiding an impossible-to-complete hidden field. The 30-exercise UI matrix verifies the count input is absent everywhere; regressions cover old recorded counts, old null-count drafts and paired resistance calculations. Browser QA remains unavailable.
## Completion checkboxes removed — 2026-11-04
Captain accepted the recommendation to remove all completion checkboxes. Explicit successful Save now derives completion: fully filled valid rows complete; missing values stay drafts; invalid entered values fail validation. Unsaved edits and suggestions do not count as achieved. Failed saves retain draft state and do not inflate totals. Existing completion booleans remain intact on read; an edited record changes only on explicit Save. No IndexedDB/schema migration. The all-exercise control matrix asserts checkbox absence; regressions exercise partial save/reload, derived EMOM/hang totals, edited rows, valid zero and failed-save behavior.
## Captain checklist
1. Tuesday Morning: enter different pull-up reps/vest loads for two EMOM minutes, save to complete the filled minutes. Reload and revisit the date. Existing aggregate history, if present, stays in its original disclosure without invented minutes.
2. Wednesday: flys show dumbbell kg each without count or vest. Deep push-ups show vest only; details explain the dumbbell handles. Push-up plus now supports vest, including zero.
3. Thursday: split squats/RDLs/calf raises have left/right reps and independent vest/dumbbell loads. Front plank asks seconds/vest without reps. Add a set and verify only load/count copies.
4. Saturday: hanging knee raises have no weights; finger hangs ask seconds/vest with no invented duration target. Sunday hip raises ask left/right reps and vest.
5. Afternoon: bird-dog asks left/right seconds with no reps or weights. Daily hang has optional attempts and an editable continuous target. Complete attempts of 60 and 75 seconds: total 135, longest 75, no 120-second continuous achievement. Change the goal while drafting and verify entered seconds remain.
6. Save an incomplete row, reload and verify null/blank values remain incomplete. Saving an incomplete row keeps it a draft; invalid entered values should show validation feedback. There are no completion checkboxes. Suggestions for a later matching session fill only empty drafts and never mark complete/save automatically.
7. Check 320px, tablet and desktop widths, field wrapping, expanded details, legacy records, errors and focus visibility without horizontal scrolling. Verify Today/Week, Morning/Afternoon, wall clock, empty Monday/Friday mornings and timer absence.
Captain explicitly confirmed “task complete” after the final corrections; TASK-015 is Complete. Final checks passed 129 tests, lint, build, context and whitespace checks. Agent browser QA remained unavailable; no separate visual pass is claimed.
## Integration handoff and next action
Captain authorized TASK-015 commit and merge to local `codex`. Run the repository checks, commit the accepted source/tests/context, then switch to codex and fast-forward task/015-equipment-ui. Verify both refs point at the accepted commit and the worktree is clean before reporting success. No remote or deployment is involved. This instruction is task-specific and does not authorize future merges.
TASK-016 (dark theme) remains planning-only; await Captain selection before new implementation. No task is in progress after TASK-015 integration.
+6 -4
View File
@@ -6,13 +6,15 @@ This is a newly initialized repository. The user calls the planned product "Work
## Product
Planned: a personal, offline-first workout tracker with seven-day date navigation; exclusive Morning and Afternoon views; strength sets, repetitions, and weight components; untimed daily isometrics and daily hanging practice with an editable time goal; Monday/Friday “Full body stretch routine” headings with no exercise entries until the owner provides them; exercise details and local illustrations; a prominent persistent local time clock; no workout timers; EMOM total reps/weight and regular per-set reps/weight recorded by date; workout history and progress including total external-load volume; editable routines; JSON backup and restoration; and responsive mobile and desktop layouts. The owner removed the previously listed stretch exercises. The authoritative initial programme is bundled as data and has a Today/Week routine view. The large local time-of-day clock remains, while workout, exercise, rest and EMOM timers have been removed. Strength rep/weight entry is implemented locally with exercise-specific vest, dumbbell, and EZ-bar fields; the daily hang shows no vest load yet. Other recording behavior remains future work. `docs/SPEC.md` defines application behavior and `docs/WORKOUT_ROUTINE.md` defines the authoritative initial programme.
Workout Tracker is a personal local workout app with actual-date navigation, exclusive Morning/Afternoon views, a persistent local-time clock and no workout timers. Seed v8 contains 30 versioned exercise definitions with equipment/measurement metadata. Reusable logging shows only relevant reps, side values, durations and equipment-specific loads, supports completed rows, partial drafts and explicit previous-session suggestions, and records EMOM minute-by-minute. Daily hangs have an editable continuous target, independent attempts, longest continuous and cumulative totals. Monday/Friday stretch routines have headings but no invented exercises. Dog walks remain excluded; their latest classification is bodyweight-only reference context.
Exercise definition, workout prescription and dated performance are independent. New performance retains definition/prescription snapshots, while original aggregate, rep-set and weight-only history stays readable separately. Exercise details expose available notes and placeholders; reviewed technique/muscle content and local illustrations remain future work. History/progress screens, routine editing, backup interface, offline reload and dark theming remain separate tasks. SPEC defines behavior and WORKOUT_ROUTINE the authoritative initial programme.
## Technology and architecture
The application foundation now uses React, Vite, and React-Bootstrap. IndexedDB stores the user-edited daily hanging goal and dated strength entries; TASK-005 will extend local storage for additional workout records while preserving those values. The application has no backend, authentication, or cloud dependency.
The application foundation now uses React, Vite, and React-Bootstrap. IndexedDB v3 stores the hanging-goal override, legacy strength records and new detailed performance in separate stores behind adapters. JSON backup/import is implemented at adapter level with version validation and atomic transactions; TASK-009 owns its UI. Native IndexedDB is used at runtime; fake-indexeddb is a test-only dependency. The application has no backend, authentication, or cloud dependency.
The planned design keeps routine templates, exercise definitions, historical workout records, and UI state separate. The initial routine is bundled as versioned seed data; subsequent user edits are local data and must not be overwritten by updates. A storage adapter separates React components from IndexedDB. A service worker and locally bundled assets are required for offline reload in the release scope.
The design keeps routine templates, exercise definitions, historical workout records, and UI state separate. The initial routine is bundled as versioned seed data; subsequent user edits are local data and must not be overwritten by updates. A storage adapter separates React components from IndexedDB. A service worker and locally bundled assets are required for offline reload in the release scope.
## Repository structure
@@ -21,7 +23,7 @@ The planned design keeps routine templates, exercise definitions, historical wor
- `docs/SPEC.md` — application requirements and behavior.
- `docs/WORKOUT_ROUTINE.md` — authoritative initial training programme.
- `docs/WORKFLOW.md` — repository operating workflow and open Git conventions.
- `src/` — React shell, local styling, routine view, dated strength-entry storage/UI, a daily hang-goal storage adapter, tests, and versioned initial routine data; broader workout storage remains future work.
- `src/` — React shell, local styling, routine view, metadata-driven performance and legacy entry UI, IndexedDB/JSON adapters, tests and versioned initial routine data.
- `package.json` — development, test, lint, and build commands.
## Development environment
+33 -29
View File
@@ -11,16 +11,16 @@
**Primary devices:** Debian laptop/desktop browser; responsive mobile browser
**Maintainer workflow:** Codex CLI + `roborto-project-context`, Git, isolated per-task branches/worktrees
## TASK-015 planning overlay — 2026-11-04
## TASK-015 accepted implementation — 2026-11-04
TASK-015 is scoped in `docs/TASKS.md`; implementation awaits Captain approval. The current app and the earlier sections below describe the timer-free, aggregate-EMOM baseline. This overlay records the latest requested changes without claiming they are implemented.
TASK-015 implements metadata-driven equipment/measurement entry and was accepted by Captain on 2026-11-04 after the count-input and completion-checkbox refinements. Its UI brief is `docs/TASK-015_UI.md`. Legacy aggregate EMOM, repetition sets and weight-only sets remain preserved separately; new logging uses detailed versioned records. The app stays timer-free.
- Exercise definitions describe supported equipment and applicable measurements, independent of prescription targets and performed values. Use the complete assignment matrix in `WORKOUT_ROUTINE.md` section 8. No fixed vest weight belongs in definitions. Dumbbells used as push-up handles do not contribute lifted resistance.
- Reusable UI derives controls from repetitions, repetitions per side, duration, duration per side, distance when applicable, EMOM reps per minute and equipment-specific loads. Bodyweight-only work has no external-weight fields; supported external resistance accepts explicit zero. Dumbbells are entered per dumbbell; bars include the bar's weight.
- Log each set/minute with independent load components, explicit completion and partial state. New EMOM records support per-minute reps/load and derived totals; old aggregate records must never be split into invented minutes. Keep previous-session suggestions distinct from actuals and preserve next-set weight defaults.
- Log each set/minute with independent load components and partial state. Explicit Save marks fully filled valid rows complete; no completion checkboxes are shown. New EMOM records support per-minute reps/load and derived totals; old aggregate records must never be split into invented minutes. Keep previous-session suggestions distinct from actuals and preserve next-set weight defaults.
- Show compact name/target/equipment/rest information and applicable logging, with expandable available instructions, muscles, technique and local media/placeholders. Reduce repeated visible labels while retaining accessible names; stack at mobile width without horizontal scrolling. Preserve date navigation, Morning/Afternoon switching and the wall clock.
- Afternoon holds may record actual seconds (per side where applicable) without repetitions, weights or prescribed hold times. Daily hang is bodyweight-only with an editable initial two-minute **continuous** target, optional attempts and independent longest/cumulative totals. Do not treat cumulative duration as continuous success.
- Preserve historical records and local edits independently of metadata changes. Version new record schemas and JSON serialization; review IndexedDB v2 for an additive migration only where needed. Test old total-only/component records, existing goal overrides and old/new JSON round trips. TASK-009 still owns backup UI and import conflict policy; none exists in the current app.
- Preserve historical records and local edits independently of metadata changes. IndexedDB v3 adds performanceEntries and its matching-session index without rewriting the two older stores. New records use schemaVersion 1; JSON adapter backups use version 2 with a legacy version 1 envelope reader. Test old total-only/component records, existing goal overrides and old/new JSON round trips. TASK-009 still owns backup UI and user-facing import policy; the current adapter supports non-overwriting imports or explicit transactional replacement, with no Settings interface.
- Dog-walk classification is bodyweight-only; restoring walks to the UI/seed/logs is outside this task. No straight-bar exercise is added merely to support the equipment vocabulary.
- Captain resolved the timer question on 2026-11-04: keep the app timer-free. Preserve the local wall clock and prescribed rest/EMOM guidance; no timers or audio are added (ADR-018).
@@ -34,7 +34,7 @@ A successful first version enables the user to:
1. See the complete seven-day plan and today's prescribed sessions using a weekday strip and exclusive Morning/Afternoon switch.
2. Open each exercise's instructions, muscles involved, equipment, and image(s), with offline availability.
3. Complete and log morning strength sessions and afternoon isometric holds. Monday and Friday mornings are labeled Full body stretch routine; specific stretches will be provided later.
4. Record one total repetition count and actual exercise-specific load for each EMOM exercise, and reps and exercise-specific load for each regular set.
4. Record each EMOM minute independently and derive totals; log reps, per-side values, duration and equipment-specific loads per set as applicable.
5. Edit routine parameters through the UI; retain dated performance history and progress views, including total external-load volume without a time-based rate.
6. Back up and restore their own data without cloud accounts, analytics or external services.
@@ -166,7 +166,7 @@ Target intensity (RPE): Monday **5–6**; Tuesday–Thursday **3–4**; Friday *
- Hang from the pull-up bar **every day**, during the afternoon isometric session.
- Goal starts at **120 seconds** and can be changed in the app; it is a target, not an assumed current ability or default completed duration.
- Current successful continuous duration, number of attempts, and whether the initial two-minute goal is presently cumulative **are not specified**; do not invent these. Vest use may be added later but is not shown in the current daily-hang UI.
- Current successful duration and number of attempts are not specified. The goal is explicitly continuous; daily hangs are bodyweight-only. Never default performed duration to the goal.
- Allow logging multiple attempts separately, in seconds, with **longest continuous hang** and **total cumulative hang time** computed independently. A 120-second cumulative total is not equivalent to one continuous 120-second hang.
- Keep Saturday finger hangs as distinct morning exercises, independent of the daily afternoon hang.
- Watch for accumulated grip, finger, elbow and shoulder fatigue; exercise logging must not force completion.
@@ -174,7 +174,7 @@ Target intensity (RPE): Monday **5–6**; Tuesday–Thursday **3–4**; Friday *
### 4.9 Global strength-training rules
- Usually **2 min** rest between sets, **2–3 min** for demanding compounds, **~3 min** between different exercises.
- EMOM remains a prescribed ten-minute protocol with a new start each minute. Record total performed reps and actual external weight for the exercise.
- EMOM remains a prescribed ten-minute protocol with a new start each minute. Record actual reps and load independently each minute; derive totals from recorded completed minutes.
- Increase load or exercise difficulty after consistently reaching the top of a rep range with clean technique.
- Allow recording actual load, reps and time even when they differ from the plan.
- Morning resistance training takes priority over optional higher-effort afternoon sessions.
@@ -195,25 +195,25 @@ Each exercise has a stable `exerciseId` and human-readable name, category, equip
1. Default to **Today**, selecting its actual date and the last-used Morning/Afternoon period; show only that period.
2. Allow navigating to any date/day, not just a repeating abstract weekday; records are tied to actual local dates.
3. Tap an exercise to open details. For EMOM exercises, enter the **total** actual reps and relevant load. For regular strength exercises, enter actual reps and relevant load separately for each set. Show vest, dumbbell, and EZ-bar fields only where the exercise calls for them; mixed vest/dumbbell work needs both. Adding a set copies the previous set's entered weights but not its reps. Never mark prescribed values as performed automatically.
3. Expand Exercise details for available notes and honest content/image placeholders. Enter each EMOM minute or regular set with only metadata-selected measurements and load fields. Per-side exercises have independent left/right values. Adding a set copies loads/count but leaves measurements blank. Save performance marks fully filled valid rows complete; incomplete rows remain saved drafts. Never mark targets or suggestions as performed automatically.
4. End the session with a compact summary (recorded sets, deviations and free-text notes) when session summaries are implemented.
5. Partial records remain saved, and future plan edits do not rewrite previously logged performance.
6. Check off isometric exercises without requiring times; log daily hang attempts in seconds and surface personal best and progress toward the current editable hang goal when extended recording is implemented.
6. Save isometric duration drafts without requiring completion; completed holds have actual seconds (per side where applicable). Daily hang attempts in seconds produce separate longest-continuous and cumulative totals and continuous-goal status. Long-term personal best history remains TASK-008.
7. Show previous performance and basic progress views without confusing prescribed and achieved values; retain previous records after routine edits.
### Suitcase-carry load recording — TASK-014 correction
### Suitcase-carry recording
Suitcase carries retain their prescribed duration per side and accept actual dumbbell kilograms per set, without requiring repetitions or inventing performed duration. Record one dumbbell's weight, with independent set values and next-set load copying. Save dated weight-only rows as `kind: load-sets`; no repetitions or rep-load volume are implied. Broader duration/per-side performance remains TASK-015.
Suitcase carries retain their prescribed duration per side and accept actual left/right seconds plus dumbbell kilograms per dumbbell and count per set, without requiring repetitions. Existing TASK-014 weight-only rows (`load-sets`) remain separately available; no achieved duration is inferred from them. Timed work contributes no rep-load volume.
### Plank vest recording — TASK-014 correction
### Plank recording
Front planks and side-plank hip raises accept vest kilograms per set with no dumbbell/bar inputs or assumed vest weight. Front planks use the existing weight-only set shape without repetition entry; side-plank hip raises retain reps-per-side guidance and reps/load set recording. Different sets may use different loads or zero. Existing bodyweight-only records stay readable as prior totals; changing them to component weights requires an explicit action. Broader actual-duration logging remains separate work.
Front planks accept actual seconds and vest kilograms per set without repetitions. Side-plank hip raises accept independent left/right reps and vest kilograms. Neither has dumbbell/bar fields or assumed load. Different sets may use zero or different loads. Older bodyweight-only or weight-only records stay in their original representation and are never converted automatically.
### Clock and recording behavior
- Show the current local time in the persistent app header across all views. It is a time-of-day display and does not record workout duration.
- Do not show workout, exercise, rest, or EMOM timers or audio cues.
- Keep EMOM duration and rest guidance as prescriptions only. One saved EMOM entry has total actual reps and the applicable load components; regular strength work has one saved rep/load row per performed set. A paired-dumbbell field means kilograms per dumbbell. Preserve older single-total entries without interpreting them as components.
- Keep EMOM duration and rest guidance as prescriptions only. A detailed EMOM entry has ten minute rows of actual reps and load; regular entries have applicable measurements, load/count and completion per set. Dumbbell fields mean kilograms per dumbbell. No exercise shows a dumbbell-count input; its defined count supplies new rows and remains stored for load calculations. Existing recorded counts are preserved. Preserve older single-total entries without interpreting them as components.
- Browsing dates does not create workout records. Saving a strength entry writes the selected date and exercise only.
## 7. Local data architecture
@@ -228,31 +228,34 @@ IndexedDB is **per browser profile and origin**, not a server database; a laptop
| Entity | Essential fields |
|---|---|
| `ExerciseDefinition` | `id`, `name`, `category`, `equipment`, `muscles`, `instructions`, `cues`, `warnings`, `imageAssets`, `version` |
| `ExerciseDefinition` | `id`, `name`, `category`, `version`, `equipment`, `measurement`, optional `dumbbellCount`, `protocols`, support-role notes; future `muscles`, `instructions`, `cues`, `warnings`, `imageAssets` |
| `Routine` | `id`, `name`, `version`, `effectiveDate`, `weeklySchedule` |
| `RoutineExercise` | `exerciseId`, `day`, `sessionType`, `order`, `sets`, `repMin`, `repMax`, `targetDurationSec`, `perSide`, `restSec`, `loadKg`, `optional`, `notes` |
| `RoutineOverride` | `dailyHangGoalSec` stored separately from the bundled seed |
| `StrengthEntry` | `date`, `exerciseId`, `kind` (`emom` or `sets`), EMOM `totalReps` and applicable `load` or regular `sets` with each set's `reps` and `load`; new records also retain derived `externalKg`, while older records may have only `externalKg` |
| `CompletedSet` | `exerciseId`, `sequence`, `reps`, `side`, `notes`, and load components (`vestKg`, `dumbbellKgEach` / `dumbbellKg`, `ezBarTotalKg`, `bodyweightOnly` when relevant); later work may support variable dumbbell counts |
| `LegacyStrengthEntry` | Original aggregate `emom`, repetition `sets` or weight-only `load-sets`, including component or unclassified `externalKg` values |
| `PerformanceEntry` | `schemaVersion`, `date`, `period`, `exerciseId`, `format`, saved `definition`, saved `prescription`, and actual `rows` |
| `LegacyCompletedSet` | `exerciseId`, `sequence`, `reps`, `side`, `notes`, and load components (`vestKg`, `dumbbellKgEach` / `dumbbellKg`, `ezBarTotalKg`, `bodyweightOnly` when relevant); later work may support variable dumbbell counts |
| `HangAttempt` | `date`, `sessionId`, `exerciseId`, `attemptNumber`, `durationSec`, `completedAt`, `notes` (daily hangs distinct from Saturday finger hangs) |
| `BodyWeightLog` | `date`, `weightKg`, `notes` (optional entry) |
| `Settings` | `preferredUnit`, `dataSchemaVersion` |
The implementation may normalize or refine this model. **Do not treat the suggested shape as frozen API contracts.** TASK-014 now stores actual load components for the seeded strength exercises and derives total external kilograms; existing entries with only a total remain valid and unclassified. `dumbbellKgEach` represents each of two dumbbells; `dumbbellKg` represents one. TASK-005 may later support variable counts and additional recording. The 6 kg and 10 kg programme values are prescriptions, not assumed actuals.
New detailed entries live in `performanceEntries`, keyed by local date, period and exercise. The compound exercise/period/format index supports compatible previous-session queries. Each record has `schemaVersion: 1`, identity, format, a definition snapshot, a prescription snapshot and rows `{values, load, completed}`. Measurement keys are reps/leftReps/rightReps/seconds/leftSeconds/rightSeconds/metres as applicable; load keys are vestKg/dumbbellKgEach/dumbbellCount/ezBarTotalKg/straightBarTotalKg. Missing draft values are null, never assumed zero. Completion is derived only on explicit successful Save: fully filled valid rows are complete and incomplete rows remain drafts. Only valid completed rows contribute achieved totals. Historical snapshots are independent of current metadata.
The earlier `strengthEntries` store is kept verbatim, including aggregate EMOM, component sets, total-only sets and weight-only rows. It is exposed in an original-record disclosure with the existing explicit editor; new detailed entries do not overwrite or double-count it. There were no shipping backup files before TASK-015: adapter JSON v1 represents the two legacy stores and v2 all three. Import validates the complete file before opening one transaction, rejects unsupported versions/duplicate keys, and rolls back failed imports. Replacement is an explicit adapter option; TASK-009 owns confirmation and UI. The backup includes bundled reference data and saved snapshots; it does not overwrite the running seed or create a routine editor.
### 7.1 Tracking requirements (v1, agreed)
1. Save regular strength sets independently with actual reps and external weight, including 0 kg for bodyweight-only work. Preserve partial records and separate them from prescription values.
2. For EMOM pull-ups and chin-ups, save **total actual repetitions and vest weight** for the exercise. Keep the ten-minute, one-minute-round prescription visible without timing or per-round logging. Support conventional-set sessions when the user switches training format.
3. For weighted push-ups, track vest load (initial prescription 10 kg); for applicable leg exercises record actual vest and dumbbell load separately. Dumbbell flys record kilograms per dumbbell, without a vest field. No made-up actual weights.
1. Save regular strength sets independently with actual reps and external weight, without external-weight controls for bodyweight-only work. Explicit zero is valid where external resistance is supported. Preserve partial records and separate them from prescription values.
2. For EMOM pull-ups and chin-ups, save actual reps and vest weight per minute, with derived completed-rep totals. Keep the ten-minute protocol visible without running a timer. Support conventional-set sessions when the user switches training format.
3. For weighted push-ups, track vest load (initial prescription 10 kg); for applicable leg exercises record actual vest and dumbbell load separately. Dumbbell floor flys record kilograms per dumbbell with a fixed count of two, without vest or count fields. No made-up actual weights.
4. For daily hangs, track each timed attempt, longest single attempt, accumulated time across attempts, and progression toward the current editable goal (initially two minutes). Record Saturday finger-hang work separately.
5. For other timed workout activities (planks and carries), log **actual** duration rather than treating the prescribed value as achieved. Isometric holds do not require times. Per-side timing should remain distinguishable where relevant.
6. Later, suggest starting weights/reps from the previous matching exercise/session, but require user action before recording completion.
5. For other timed workout activities (planks and carries), log **actual** duration rather than treating the prescribed value as achieved. Incomplete hold drafts may omit times; completion requires actual durations. Record sides independently where relevant.
6. Offer Use previous session for compatible earlier detailed records. Fill only an empty current draft, reset completion, and never save automatically or reinterpret legacy totals.
7. Show dated exercise history, previous vs current performance and straightforward progress charts/personal bests (particularly vest load, reps, hang duration, optional body weight). Do not fabricate missing data or equate different loading modes in comparisons.
8. Never rewrite completed history following routine edits, reseeding, changes to exercise definitions or app upgrades. Future routine edits only change future prescriptions.
9. Export all workouts, hang attempts, plan edits, and optional body-weight records to a **versioned JSON backup**; validate on import and ask before overwriting/merging existing records.
10. Avoid external analytics and automatic calorie estimates; training data remains local and private.
11. For a workout's **total external-load volume** (kg·reps), sum `actual reps × actual external kilograms moved` across recorded regular sets and EMOM totals. External load includes recorded vest mass, actual dumbbell mass times count, and EZ-bar total as applicable; it excludes body weight. Do not invent missing load components. Show the formula and raw total, and mark partial or incomplete data. Timed holds and hangs do not contribute rep-load volume. Do not calculate volume per minute.
11. For a workout's **total external-load volume** (kg·reps), sum `actual reps × actual external kilograms moved` across completed detailed regular sets and each EMOM minute. Retain original aggregate calculations separately when displaying legacy history; do not count both representations together. External load includes recorded vest mass, actual dumbbell mass times count, and EZ/straight-bar total as applicable; it excludes body weight. Do not invent missing load components. Show the formula and raw total, and mark partial or incomplete data. Timed holds and hangs do not contribute rep-load volume. Do not calculate volume per minute.
### Data integrity and update rules
@@ -267,7 +270,7 @@ The implementation may normalize or refine this model. **Do not treat the sugges
- Calm, minimal, readable, keyboard-usable layout; neutral/dark styling with clear completion emphasis. Respect light/dark preference if feasible without a large theme system.
- The weekday strip and **Morning/Afternoon toggle** should be immediately visible. Display **only one selected session period** on screen, never both together.
- Exercise cards show: name, prescription, prescribed rest, load/vest preset, rep/weight entry for applicable strength work, and an expandable description/image view when details are implemented.
- Exercise cards show: name, prescription, relevant equipment, prescribed rest, only applicable actual logging controls, and an expandable detail view with available notes and missing-content/media placeholders.
- The persistent local time clock remains legible at phone and desktop widths.
- Avoid busy gamification, badges/streaks and unnecessary dashboards.
- Responsive at mobile widths; no horizontal scrolling for primary interaction.
@@ -285,7 +288,8 @@ Use separate Codex tasks and isolated branches/worktrees in the repository conte
| T004 | Exercise-detail screen and local media placeholders; accessibility | T002–T003 |
| T005 | Extend TASK-014 records with hangs, holds, other performance details and history-safe migrations | T014 |
| T006 | Superseded timer task; the local time clock and hang-goal editor remain | T003 |
| T014 | Remove timers; save EMOM total reps/weight and regular per-set reps/weight by date | T002–T003 |
| T014 | Completed timer-free original-format recording baseline | T002–T003 |
| T015 | Metadata-driven detailed sets/minutes/attempts; compatible storage and JSON adapter | T014 |
| T007 | Routine editor: reorder, adjust prescription, optional exercises, persistence | T005 |
| T008 | History and progress views (hang PB, loads, reps, total external-load volume), responsive/accessibility polish, offline/PWA build, test pass and documentation | T004–T007, T014 |
| T009 (content) | Produce and review licensed/local exercise illustrations for the actual variants | T004; may run separately |
@@ -297,16 +301,16 @@ Do not implement all tasks as a single unreviewed change. Define task boundaries
- [ ] Today defaults to current local calendar date; seven-day strip works across weeks; exclusive Morning/Afternoon toggle remembers its state and does not show both periods at once.
- [ ] Monday and Friday mornings show “Full body stretch routine” with no invented exercise entries; afternoon holds and hangs remain.
- [ ] The local time clock remains prominent and readable at phone and desktop widths while navigating the app.
- [ ] Tuesday pull-ups and Saturday chin-ups retain the **10 × 60-second EMOM** prescription and 6 kg vest presets, while actual total reps and external weight are recorded once for each exercise.
- [ ] Tuesday pull-ups and Saturday chin-ups retain the **10 × 60-second EMOM** prescription and 6 kg vest presets, while actual reps and vest weight are recorded independently each minute.
- [ ] Wednesday flys have **no floor-press drop set**; push-up plus precedes feet-elevated push-ups.
- [ ] Thursday includes single-leg RDLs and front planks, **not weighted floor crunches**.
- [ ] Saturday includes hanging knee raises, 2–3 finger-hang sets, preacher curls and hammer curls; **no EZ curls or wrist curls**.
- [ ] Sunday includes optional single-arm triceps extensions and side-plank hip raises.
- [ ] Afternoon isometric holds show no time targets; day-specific effort guidance remains.
- [ ] Daily afternoon hangs appear all seven days with an initially **2:00 goal** that can be changed and survives reload, but no invented achieved value or vest detail; multiple attempts produce longest-continuous and cumulative totals independently. Saturday finger hangs remain separate.
- [ ] Weight presets on pull-ups/chin-ups (6 kg) and weighted push-ups/vested leg work (10 kg) display correctly; dumbbell loads are **not invented**.
- [ ] Equipment capabilities contain no fixed weight. Historical 6/10 kg values remain prescription context only and do not determine inputs or prefill actuals.
- [ ] Users can enter vest and dumbbell loads separately, total EZ-bar load, per-side values, recorded reps, hold/carry durations, and optional body-weight entries.
- [ ] EMOM total reps and actual external weight, plus separate regular-set reps and weights, survive reload by date and exercise; prescribed values are never saved as performed automatically.
- [ ] EMOM minute reps/load and regular-set measurements/weights survive reload by date, period and exercise; prescribed values are never saved as performed automatically.
- [ ] Exercise-specific load components, hang attempts and untimed hold checkoffs can be extended without replacing existing strength records; old total-only entries remain available.
- [ ] Exercise history and simple progress charts display actual saved values; editing a future prescription leaves existing entries unchanged.
- [ ] Total external-load volume uses recorded reps and actual external weight without a time denominator; the display shows raw totals and flags partial or missing data.
+27
View File
@@ -0,0 +1,27 @@
# TASK-015 UI and storage implementation brief
Design mode: extend the existing React-Bootstrap layout and green/light visual language. TASK-016 owns dark theming. Captain engaged implementation on 2026-11-04; timer-free behavior is authoritative (ADR-018).
## Composition and interaction
Keep the app header, wall clock, date strip and exclusive period switch. Each exercise card presents name, optional state, a clearly labeled target, supported equipment and rest guidance. Below it, show actual logging rows derived from definition metadata. Desktop rows share column headings; at <=575px labels appear on stacked fields. Units and accessible names include row/side. No horizontal table scrolling.
Use a reusable performance editor for sets, EMOM minutes and hang attempts. New rows start blank except for copied preceding loads/count. EMOM starts with ten blank minute rows; conventional-set format remains available. There are no completion checkboxes. Explicit Save marks fully filled valid rows complete and retains incomplete rows as drafts; invalid entered values fail validation. Never auto-save on navigation or count suggested values as performed.
Rep-per-side and duration-per-side use independent left/right fields. Dumbbells use kg each with count supplied internally from the definition; no exercise shows a count field. Floor flys always use two, vest/bar loads have separate fields. Bodyweight-only work has no external-load inputs. The existing prescription remains separate from actual values; seed load presets never initialize actuals.
Use one Save performance action, Add set/attempt where relevant, optional Use previous session action with date and compatibility check, and clear saved/unsaved/error feedback. Suggestions require action and completion is reset. Initial loading disables logging; failure preserves drafts with retry. Save failures leave values intact. Validation errors identify the row and field; completed data and incomplete drafts are distinguished by saved summary counts and unsaved/saved feedback.
Daily hang shows editable continuous target, attempt seconds, longest continuous and cumulative duration separately. Only completed attempts contribute to achieved summaries. Finger hangs remain separate. Details use a keyboard-operable disclosure with existing notes, support-equipment distinction and explicit unavailable-content placeholders; no invented muscle/technique copy or unreviewed image.
Historical aggregate EMOM, rep sets and weight-only records remain in their original store and appear in a separate disclosure, with the existing editor available for explicit edits. They are not allocated to minute/side rows or counted together with new detailed entries. New logging is saved separately and captures definition/prescription snapshots. A clear label explains the two representations; a new detailed record never overwrites the old one.
## Responsive and state coverage
Desktop keeps compact headings and aligned fields; tablet wraps within the card; mobile stacks row fields with visible labels and full-width actions as needed. Labels/errors wrap and controls have min-width:0. Existing focus style extends to all new controls; use native semantic form controls and text status. Loading, empty, partial, saved/unsaved, storage-read failure, save failure, invalid completed row, legacy-only and changed-definition history are explicit states. No modal or new navigation is needed.
## Data contract
IndexedDB v3 adds performanceEntries and a compound exercise/period/format index. Existing strengthEntries and routineOverrides are retained verbatim. Each new record is schemaVersion 1 with date, period, exercise ID, format, immutable definition/prescription snapshots, and rows of measurement values/load/completion. Legacy readers remain intact. Partial values use null, not inferred zero. New JSON adapter exports all three stores with versioned validation and transactional import; no Settings backup interface is added (TASK-009).
Validation: all equipment/measurement assignments, units/count/side semantics, applicable and absent controls, variable/zero loads, completion and partial reload, suggestions, legacy isolation, v1/v2 upgrades, failed transactions, JSON old/new round trips, full tests/lint/build, diff review against codex, and browser mobile/desktop QA if a browser becomes available. Captain acceptance is required before Complete.
+25 -18
View File
@@ -4,7 +4,7 @@ This file holds accepted, scoped implementation work. It is not a speculative ba
## Proposed implementation sequence
Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001 through TASK-003 and TASK-012–TASK-013 are complete; TASK-014 is complete following Captain acceptance on 2026-11-04; TASK-006 is superseded; TASK-005 and TASK-008 are accepted; TASK-015 is scoped and awaiting implementation approval; TASK-016 is accepted for planning only; the remaining tasks are proposed. Implement one task per isolated branch/worktree under `docs/WORKFLOW.md`. Preserve the documented initial programme, including optional/ranged prescriptions and distinct session types. TASK-013 supersedes the dog-walk reference added by TASK-012; TASK-014 supersedes timer work.
Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001 through TASK-003 and TASK-012–TASK-013 are complete; TASK-014 is complete following Captain acceptance on 2026-11-04; TASK-006 is superseded; TASK-005 and TASK-008 are accepted; TASK-015 is Complete following Captain acceptance on 2026-11-04; TASK-016 is accepted for planning only; the remaining tasks are proposed. Implement one task per isolated branch/worktree under `docs/WORKFLOW.md`. Preserve the documented initial programme, including optional/ranged prescriptions and distinct session types. TASK-013 supersedes the dog-walk reference added by TASK-012; TASK-014 supersedes timer work.
### TASK-001: Application foundation and responsive shell
@@ -47,7 +47,7 @@ Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001 through T
- Acceptance criteria: Every seeded exercise opens a useful detail view; missing images have accessible placeholders; no hotlinked images or invented technique guidance.
- Relevant areas: Exercise library, detail UI, tests.
- Required validation: Detail and accessibility tests, offline asset check, responsive visual check.
- Non-goals: Producing final illustrations or logging notes.
- Non-goals: Producing final illustrations or logging notes. TASK-015 supplies the expandable detail shell and missing-content placeholders; this task owns reviewed content/detail extensions.
- Dependencies or blockers: TASK-002 and TASK-003; detailed technique text requires reviewed source/content.
### TASK-005: Extended workout recording
@@ -59,7 +59,7 @@ Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001 through T
- Relevant areas: IndexedDB adapter, domain model, recording UI, tests.
- Required validation: IndexedDB integration tests, migration/error cases, load-component and hang reload checks, partial-session checks, build.
- Non-goals: Progress charts, routine editor, backup UI.
- Dependencies or blockers: TASK-002, TASK-003, and TASK-014. The owner narrowed logging to EMOM totals and per-set reps/weight on 2026-10-27; further load and hang details remain accepted from earlier requests.
- Dependencies or blockers: TASK-014 and TASK-015. TASK-015 now owns metadata-driven load/count/side/duration/hang recording, completion and previous-session suggestions. TASK-005 retains notes, optional body weight and other extended recording without duplicating TASK-015.
### TASK-006: Timers during and between exercises
@@ -87,8 +87,8 @@ Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001 through T
- Status: Accepted
- Objective: Browse actual dated performance and transparent basic trends without a time-based rate.
- Scope: Completed/partial session history, prior vs current performance, reps and load trends, total external-load volume from recorded EMOM totals and regular sets, longest continuous and cumulative hang separately, optional body-weight trend.
- Acceptance criteria: External-load volume is the sum, across recorded regular sets and EMOM totals, of actual reps multiplied by recorded external kilograms moved (vest, dumbbell total based on count, and/or EZ-bar total; body weight excluded). Show the formula and raw totals; label partial workouts and incomplete load data. Timed-only work contributes no rep-load volume; routine edits leave history intact. Do not show volume per minute.
- Scope: Completed/partial session history, prior vs current performance, reps and load trends, total external-load volume from completed detailed minute/set rows and separately preserved legacy aggregates, longest continuous and cumulative hang separately, optional body-weight trend.
- Acceptance criteria: External-load volume is the sum, across completed detailed regular sets and each EMOM minute, of actual reps multiplied by recorded external kilograms moved (vest, dumbbell total based on count, and/or EZ-bar total; body weight excluded). Do not combine detailed and legacy representations for the same performance. Show the formula and raw totals; label partial workouts and incomplete load data. Timed-only work contributes no rep-load volume; routine edits leave history intact. Do not show volume per minute.
- Relevant areas: Queries/aggregations, history/progress UI, tests.
- Required validation: Calculation and view tests with mixed loading modes, missing weights, partial workouts, and timed-only exercises; responsive check.
- Non-goals: Coaching, calorie estimates, streaks.
@@ -103,7 +103,7 @@ Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001 through T
- Relevant areas: Backup format, storage transaction, settings UI, tests.
- Required validation: Full round trip in a fresh profile, invalid/old-version tests, transaction rollback test.
- Non-goals: Cloud synchronization or CSV export.
- Dependencies or blockers: TASK-005 and TASK-007; decide precise merge conflict behavior before implementing merge.
- Dependencies or blockers: TASK-015 supplies the tested JSON v2/v1 adapter; TASK-005/TASK-007 extend future stored content. User-facing preview/confirmation/conflict policy remains this task, with no automatic merge acceptance.
### TASK-010: Offline release and full UX verification
@@ -172,18 +172,19 @@ Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001 through T
### TASK-015: Exercise equipment specifications and context-aware UI
- Status: Accepted for scoping; awaiting Captain approval before implementation
- Lock-on: Captain selected TASK-015 for briefing on 2026-11-04 after accepting TASK-014. Implementation has not begun; timer scope and Git arrangement remain unresolved.
- Brief refreshed: 2026-11-04. This is the existing matching task, expanded rather than duplicated. No application implementation is authorized by this planning turn.
- Status: Complete
- Engaged: 2026-11-04 on `task/015-equipment-ui` from clean `codex` commit `669bfc3`. Timer-free. Focused UI brief: `docs/TASK-015_UI.md`.
- Lock-on: Captain selected TASK-015 for briefing on 2026-11-04 after accepting TASK-014. This was a briefing only; the subsequent ADR-018/engage instruction resolved timer/Git gates.
- Brief refreshed: 2026-11-04. This is the existing matching task, expanded rather than duplicated. Initial planning was documentation-only; subsequent engagement authorized implementation.
- Objective: Separate exercise capabilities, workout prescriptions, and actual performance, and use equipment/measurement metadata to drive a compact exercise interface.
#### Scope and boundaries
1. Add versioned equipment and measurement metadata to all 30 current exercise definitions, following the assignment matrix in `WORKOUT_ROUTINE.md`'s TASK-015 planning addendum. Supported equipment vocabulary: bodyweight, weighted vest, dumbbell(s), EZ curl bar, straight bar. No exercise is assigned a straight bar by this request; support the type without adding exercises. Multiple equipment types may be used simultaneously. Deep-push-up dumbbells are support handles, excluded from lifted load.
1. Add versioned equipment and measurement metadata to all 30 current exercise definitions, following the assignment matrix in `WORKOUT_ROUTINE.md`'s equipment assignment matrix. Supported equipment vocabulary: bodyweight, weighted vest, dumbbell(s), EZ curl bar, straight bar. No exercise is assigned a straight bar by this request; support the type without adding exercises. Multiple equipment types may be used simultaneously. Deep-push-up dumbbells are support handles, excluded from lifted load.
2. Remove fixed resistance from exercise capabilities. Retain prescription targets separately, and record actual equipment-specific resistance independently for each set/minute. Dumbbell entry is kilograms per dumbbell with count represented explicitly; EZ/straight-bar entry is total kilograms including the bar. Zero is valid where additional resistance is supported; blank is not an inferred zero.
3. Define repetitions, repetitions per side, duration, duration per side, distance where appropriate, and EMOM repetitions per minute. Preserve existing rep/set ranges, order, optional exercises, and unspecified targets. Carries currently prescribe duration per side; do not invent a distance target. Bird-dog and other unilateral holds allow actual seconds per side without inventing prescribed times.
4. Replace prescription-load-key-driven fields with reusable metadata-driven controls. Support independent set completion, partial drafts, per-set loads, EMOM minute rows, duration attempts, previous matching session suggestions, and existing next-set load defaults. Suggestions are editable drafts, never automatically performed/completed records. Match by exercise, period, format, measurement/side semantics, and compatible equipment; do not suggest future sessions, reinterpret legacy totals, or overwrite current-date work.
5. Compact cards show name, target sets/reps/duration, relevant equipment and rest guidance; actual entry is distinct. Use shared field headings on desktop with accessible row labels, stacked controls on mobile, and expandable details for available instructions, muscles, technique notes and local images/placeholders. Review this proposal through Frontend UI Design before code. Keep Today/Week navigation, exclusive Morning/Afternoon switching, local clock and editable hang goal. Timer behavior requires the decision below.
5. Compact cards show name, target sets/reps/duration, relevant equipment and rest guidance; actual entry is distinct. Use shared field headings on desktop with accessible row labels, stacked controls on mobile, and expandable details for available instructions, muscles, technique notes and local images/placeholders. Review this proposal through Frontend UI Design before code. Keep Today/Week navigation, exclusive Morning/Afternoon switching, local clock and editable hang goal. Timer-free behavior follows ADR-018.
6. Daily hang is bodyweight-only with an initial editable 120-second continuous target, actual seconds per attempt, optional additional attempts, longest continuous and total duration separately. Never infer success from cumulative duration or prefill 120 as achieved. Keep Saturday weighted finger hangs distinct.
7. Preserve old records, load interpretation, hang-goal overrides and any local plan edits through versioned storage/record upgrades. Define and test versioned JSON serialization and legacy import compatibility at the adapter boundary; the Settings backup interface and merge policy remain TASK-009.
8. Update SPEC, WORKOUT_ROUTINE, relevant decisions, data README, tasks/current state and handoff with approved requirements, schema rules, validation and Captain acceptance evidence.
@@ -195,7 +196,7 @@ Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001 through T
- Bulgarian split squats and all four specified mixed leg exercises support separate vest and dumbbell values. Different sets and EMOM minutes retain different loads after save/reload/date navigation, including explicit zero. Dumbbell counts and bar-inclusive totals produce correct saved external load.
- Rep exercises show reps or reps per side as appropriate; timed exercises show seconds or seconds per side without requiring reps. Carry distance is supported only when relevant metadata selects it. Finger-hang duration remains unspecified as a target.
- EMOM supports ten minute-by-minute rep/load entries, partial rounds and derived totals. Legacy aggregate EMOM records remain aggregate, available without invented minute allocations. No default targets become actuals; mixed-load volume, if calculated, uses the sum of each minute's reps times its own load, never total reps times one assumed weight.
- Completion is an explicit action independent of entering/suggesting values. Partial records survive reload; previous-session prefills and next-set defaults do not mark work complete or write records on browsing.
- Completion follows successful explicit Save, not a separate checkbox: fully filled valid rows complete, incomplete rows stay drafts. Partial records survive reload; previous-session prefills and next-set defaults do not mark work complete or write records on browsing.
- Daily hang attempts preserve actual seconds independently, compute longest and cumulative totals, and compare the continuous target to the longest attempt. Editable goal persists independently; unilateral isometric logging requires neither reps nor invented duration targets.
- Metadata/prescription changes, reseeding and upgrades leave existing actuals and historical load semantics unchanged. Test old total-only and component sets/EMOM, v1 hang-goal-only database and v2 database, unknown historical equipment, blocked/unavailable storage and failed transaction rollback. No legacy total is decomposed or per-minute load fabricated.
- Versioned JSON round trips restore both old and new records and relevant definition/prescription context; old versions are accepted through explicit adapters and invalid/unsupported input leaves data unchanged. No claim that old app binaries can read new records is required.
@@ -205,9 +206,9 @@ Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001 through T
#### Inspected implementation and likely affected files
- `src/data/exerciseDefinitions.json`: currently only IDs/names/categories; add equipment, measurement, support-role and version metadata.
- `src/data/initialRoutine.json`, `src/data/index.js`, `src/data/README.md`, `src/data/initialRoutine.test.js`: versioned prescription seed (currently v7), target/load separation and assignment invariants.
- `src/data/initialRoutine.json`, `src/data/index.js`, `src/data/README.md`, `src/data/initialRoutine.test.js`: versioned prescription seed (now v8), target/load separation and assignment invariants.
- `src/App.jsx`, `src/StrengthEntryEditor.jsx`, `src/HangGoalEditor.jsx`, `src/routineView.js`, `src/strengthLoad.js`, `src/styles.css`: exercise cards, metadata selectors, reusable set/minute/attempt fields, details and responsive layout; add focused domain/components as needed rather than hardcoding exercise IDs.
- `src/localDatabase.js`, `src/strengthStorage.js`, `src/hangGoalStorage.js` and their tests: versioned reads/writes, new performance shapes, compatible prior-session queries, historical context and overrides. Current strength validation accepts repetition sets, weight-only `load-sets`, and aggregate EMOM. The editor derives fields from prescription `load` keys; it cannot store actual duration/side/attempt/completion/minute data yet. TASK-014 already supplies suitcase-carry weight-only sets and vest inputs for front planks/side-plank hip raises; preserve those behaviors while replacing the exercise-ID exceptions with metadata.
- `src/localDatabase.js`, `src/strengthStorage.js`, `src/hangGoalStorage.js` and their tests: versioned reads/writes, new performance shapes, compatible prior-session queries, historical context and overrides. Legacy strength validation retains repetition sets, weight-only `load-sets` and aggregate EMOM. New PerformanceEditor/model/storage support actual duration/side/attempt/completion/minute data from metadata. The old editor remains available only for explicitly editing original-format records.
- `src/App.test.jsx`, `src/StrengthEntryEditor.test.jsx`, `src/routineView.test.js` and new focused metadata/storage/serialization tests.
- Documentation listed above; future TASK-009 consumes the serialization contract. No export/import implementation exists today.
@@ -215,19 +216,25 @@ Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001 through T
1. Approve unresolved timer/Git decisions and UI brief; reconcile task ownership below. Establish a safe dedicated task worktree from the agreed base without losing current uncommitted prerequisites.
2. Define separate versioned exercise capabilities, prescriptions and performance records. New records retain actual units, side, equipment/count and sufficient definition/prescription context for historical interpretation. Review whether old preset weights remain optional prescription information; never use them to generate actual loads or capabilities.
3. Add metadata and audited seed updates, then a versioned performance reader/writer with legacy adapters. IndexedDB is currently version 2 with `routineOverrides` and `strengthEntries`, keyed by date/exercise. Record schema versioning is needed; an IndexedDB version bump is required only if stores/indexes change. Prefer additive storage and preserving legacy records verbatim; decide exact stores/indexes after schema review. Test before integrating UI.
3. Add metadata and audited seed updates, then a versioned performance reader/writer with legacy adapters. The initial baseline was IndexedDB v2. The implemented v3 adds performanceEntries and its compound index while retaining routineOverrides and strengthEntries verbatim. New detailed records use schemaVersion 1 and saved definition/prescription snapshots. Test before integrating UI.
4. Build reusable card/measurement/load/row/detail components; add minute and duration flows plus compatible prior-session lookup. Apply the focused layout proposal, preserving the existing visual language.
5. Add JSON codec/version compatibility fixtures, regression tests and browser QA; update context and hand off an exact testable representation. No repository testtask adapter currently exists; recheck at handoff.
#### Dependencies, decisions and implementation gate
- TASK-014 is Complete following Captain acceptance on 2026-11-04; its uncommitted dated-load implementation is the technical baseline. No separate application work starts in this turn.
- TASK-014 is Complete following Captain acceptance on 2026-11-04; its committed dated-load implementation in codex 669bfc3 is the technical baseline.
- TASK-015 owns metadata, applicable per-side/duration/hang logging, completion and previous-session suggestions requested here, replacing the overlapping portions of TASK-005 when engaged. TASK-005 retains notes, optional body weight and other unrelated extended recording. TASK-004 supplies reviewed detail content; TASK-015 can provide the expandable shell and honest missing-content placeholders without waiting for TASK-011's final illustrations. TASK-008 consumes the new performance shapes; TASK-009 owns backup UI/import policy. Do not duplicate those features.
- **Timer decision resolved (2026-11-04):** Captain selected timer-free behavior. Keep only the wall clock and prescribed rest/EMOM guidance; no timers/audio return (ADR-018).
- **Git decision resolved (2026-11-04):** Captain authorized committing existing work and merging it into local `codex` before implementation. Create TASK-015 branch from that clean integration baseline per ADR-018 and WORKFLOW. Do not merge TASK-015 without further authority.
- The current explicit request resolves earlier planning questions: minute-by-minute EMOM is required (derived totals supplement it; existing aggregate history stays aggregate); isometric duration means actual logging, not prescribed hold targets; daily hang goal means continuous; dog walks are bodyweight-only classification context without authorized restoration of removed app screens/records. No fixed vest values enter definitions. These do not require repeated approval.
- Non-goals: unrelated redesign, new exercises, fabricated technique content/assets, dog-walk UI/logging, calorie calculations, routine editor, full history/backup UI, volume per minute, merge or deployment.
- Recommended skills when approved: Frontend UI Design → Webapp Feature → Frontend Visual QA → Code Review. No implementation or visual QA has run for TASK-015.
- Skills applied: Frontend UI Design, Webapp Feature, Frontend Visual QA availability check and Code Review of tracked/untracked task changes against codex. Browser inventory remained empty; no visual pass is claimed.
- Captain correction (2026-11-04): Remove all completion checkboxes; successful Save completes fully filled valid rows and retains incomplete drafts. Suggestions, browsing and failed saves do not create achieved performance.
- Captain correction (2026-11-04): Remove the count input from all exercises; retain definition defaults for new rows and preserve recorded historical counts internally for load calculations.
- Earlier Captain correction (2026-11-04): Floor flys always use two dumbbells. Hide their count control, retain kilograms per dumbbell and a fixed count of two in new records/calculations. Preserve original snapshot counts in existing records.
- Implementation evidence (2026-11-04): Metadata and seed v8, reusable detailed editor, left/right actuals, minute EMOM/conventional sets, load/count and completion, hang totals, compatible previous-session lookup, expandable details, additive IndexedDB v3 and JSON adapter v2/v1 are implemented. Original stores/records remain intact. Reviewed against codex 669bfc3; no unrelated theme/history/backup UI changes. All 129 tests across 11 files, lint, build, context validation (0 warnings) and whitespace checks pass on 2026-11-04. Exact Captain checklist is in HANDOFF. Captain subsequently authorized task commit/merge to local codex on 2026-11-04; no push/deployment authorized.
- Completion evidence (2026-11-04): Captain explicitly confirmed “task complete” after removal of all dumbbell-count inputs and completion checkboxes. Final checks passed 129 tests across 11 files, lint, build, context validation and whitespace checks. Agent browser QA was unavailable; Captain acceptance is recorded without claiming a separate agent visual pass. Captain subsequently explicitly authorized committing and merging this accepted task into local codex on 2026-11-04. No push or deployment is authorized.
### TASK-016: Apply a consistent dark theme
@@ -239,7 +246,7 @@ Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001 through T
- Relevant areas: `src/styles.css`, `src/main.jsx`, `src/App.jsx`, shared React-Bootstrap configuration, strength/hang editors where required, existing interaction tests and `docs/SPEC.md`. No workout data or IndexedDB migration is expected.
- Proposed approach: Inspect current UI and approve a restrained dark palette; centralize semantic colors for surfaces/text/borders/accent/status/focus; apply the supported Bootstrap dark theme plus local tokens; inspect all controls and states in the browser and correct contrast or native-control mismatches. Preserve existing green identity where contrast permits.
- Required validation: Mobile (including 320px) and desktop browser review across all sections and both workout periods; keyboard/focus and measured contrast checks; input, disabled, saved and error-state review; existing test suite, lint, build, context validation and `git diff --check`; Captain visual acceptance before Complete. Avoid tests that merely duplicate CSS declarations.
- Dependencies or blockers: Resolve the existing dirty-checkout/base/worktree arrangement under WORKFLOW before implementation. Coordinate styling with TASK-015 if it proceeds first; neither task requires implementing the other's behavior. No new app behavior is authorized here.
- Dependencies or blockers: Use the approved codex base and a clean dedicated task branch under WORKFLOW; TASK-015 currently occupies the sole worktree. Coordinate styling with TASK-015; neither task requires implementing the other's behavior. No new app behavior is authorized here.
- Non-goals: New layouts, unrelated UX redesign, light-mode variants, a theme picker, OS-theme switching, new settings or persistent preferences, and changes to workout definitions/storage/timers.
- Decisions required before implementation: Review the exact palette through the UI brief; default scope is a single dark theme. A light/dark switch would require separately approved scope.
- Recommended skills when engaged: Frontend UI Design → Webapp Feature → Frontend Visual QA. This record does not authorize implementation.
+1 -1
View File
@@ -23,7 +23,7 @@ The project owner is **Captain**. Reports may use a restrained Starfleet chief-e
- Default target: one accepted numbered implementation task per dedicated task branch/worktree. Concurrent tasks use separate worktrees. Keep the code, tests, task-specific decisions, and context updates for a task together; never use another task's manual-test snapshot as an editing worktree.
- Captain authorized baseline reconciliation on 2026-11-04: commit reviewed pending work on `task/001-foundation`, create local `codex` from the original foundation commit, and merge that baseline into `codex` before TASK-015 implementation. No remote exists. See ADR-018.
- `codex` is the approved TASK-015 integration/base branch. Sequential task work may use the sole `/home/rob/projects/exercise-tracker` worktree after a clean switch to its dedicated numbered branch; TASK-015 uses `task/015-equipment-ui`. Concurrent tasks still require separate worktrees. Do not switch a dirty or separately occupied worktree.
- Worktree directory convention, general merge strategy and release/deployment convention remain unspecified. Future merges, commits/pushes and deployments require the applicable Captain authority; baseline reconciliation does not authorize merging TASK-015.
- Worktree directory convention, general merge strategy and release/deployment convention remain unspecified. Future merges, commits/pushes and deployments require the applicable Captain authority; baseline reconciliation did not authorize merging TASK-015; Captain separately authorized its commit and local codex merge on 2026-11-04 after accepting the task. This does not authorize later task merges.
- Review each meaningful task diff against its confirmed integration base and acceptance criteria. Do not treat the current task branch as the base merely because it is checked out. Leave merge/release authority with Captain.
## Task status and handoff
+17 -9
View File
@@ -2,7 +2,7 @@
**Status:** Current agreed baseline
**Last revised:** 2026-10-26
**Last revised:** 2026-11-04
**Purpose:** Authoritative description of the user's present training programme for the workout application.
**Proposed repository location:** `docs/WORKOUT_ROUTINE.md`
@@ -112,8 +112,8 @@ Target effort (RPE): Monday **5–6**; Tuesday–Thursday **3–4**; Friday **6
| Timing | **Afternoon**, alongside isometric holds, separate from morning strength training |
| Goal | Start at **2 minutes**; the owner can change the goal in the app |
| Current duration | **Not specified** — 2 minutes is the target, not a confirmed current ability |
| Sets / breaks | **Not specified** — do not assume 2 minutes continuous or cumulative |
| Weight | Vest use may be added later; it is not shown for daily hangs in the current app |
| Sets / breaks | Optional multiple attempts; initial target is one continuous 2-minute hang, never a cumulative total |
| Weight | Bodyweight only; no external-weight inputs |
The daily hang is **additional to the existing programme**. Saturday also currently lists 2–3 sets of finger hangs in the morning; retain those for now rather than silently replacing them. Track the daily hang and Saturday finger hangs separately. Since pull-ups, chin-ups, hanging knee raises and finger hangs already load the hands and elbows, ease off if grip, finger, elbow or shoulder discomfort develops.
@@ -133,11 +133,11 @@ The daily hang is **additional to the existing programme**. Saturday also curren
## 6. Implementation notes for the workout app
- Preserve **exercise order**, **prescription ranges**, **optional status**, and **vest load** in structured data; do not flatten a range (e.g. `3–4 sets`) to a mandatory count without representing the difference.
- Preserve **exercise order**, **prescription ranges**, **optional status**, and separate prescription context in structured data; do not flatten a range (e.g. `3–4 sets`) to a mandatory count without representing the difference.
- Separate the routine template from workout logs. Logged sets, weights, repetitions, timings and notes are **historical user data**.
- The EMOM remains a 10-minute protocol. Record actual total reps and external weight for the exercise; the app does not run an EMOM timer or require per-round entries.
- The EMOM remains a 10-minute protocol. Record actual reps and load per minute and derive completed totals; no EMOM timer runs. Existing aggregate totals remain historical aggregates without invented minute entries.
- Afternoon isometrics and **daily hanging practice** are separate from morning strength workouts. Monday and Friday mornings show the full body stretch routine heading without exercise entries until the owner supplies them.
- Record daily hang duration and whether the 2-minute goal was achieved; do not default duration to 120 seconds or assume it is one continuous attempt. Keep Saturday finger hangs independently logged.
- Record daily hang duration and whether the 2-minute goal was achieved; do not default performed duration to 120 seconds. Only an actual continuous attempt meets the continuous target; cumulative hanging is a separate measure. Keep Saturday finger hangs independently logged.
- Include exercise instructions/images as independent exercise-library data; this source document records the *agreed programme*, not an exhaustive technique manual.
- Any exercise weight omitted above is **not specified**. Do not infer a dumbbell or EZ-bar load.
- No fixed finger-hang duration is agreed.
@@ -156,9 +156,9 @@ The daily hang is **additional to the existing programme**. Saturday also curren
| 2026-10-18 | Added daily afternoon hangs alongside isometric holds, with a goal of 2 minutes; current duration and continuous/cumulative format remain unspecified. |
| 2026-10-18 | Consolidated the then-current strength routine, seven-day isometrics, walking volume and known vest loads into one document. |
## 8. TASK-015 equipment and measurement planning addendum — 2026-11-04
## 8. Authoritative equipment and measurement assignments — 2026-11-04
These are the Captain's latest requested assignments for TASK-015, awaiting implementation approval. They take precedence over older equipment wording above for this task; the running seed is unchanged. Numeric vest references above are historical prescription context, never exercise capabilities or assumed actuals. Exercise definition, workout prescription and actual performance must remain separate.
These are the Captain's assignments implemented in the TASK-015 candidate, seed v8. They take precedence over older equipment wording above. Numeric vest references above are historical prescription context, never exercise capabilities or assumed actuals. Exercise definition, workout prescription and actual performance must remain separate.
| Session | Exercise | Supported resistance equipment | Performance measurement |
|---|---|---|---|
@@ -197,8 +197,16 @@ These are the Captain's latest requested assignments for TASK-015, awaiting impl
- Straight bar is a supported equipment type with total load including the bar, but no current exercise is assigned it. EZ curl bar uses the same total-weight convention. Dumbbell weights are per dumbbell; preserve the number used separately.
- Actual vest/dumbbell/bar load may vary per set or EMOM minute, including explicit zero where applicable. Do not prescribe particular weights through exercise definitions.
- Daily hanging supports multiple optional attempts. Longest continuous and cumulative duration are different results; only a continuous attempt meets the continuous target. This clarifies the earlier unspecified continuous/cumulative goal without inventing current ability.
- Minute-by-minute EMOM supersedes aggregate-only logging for new performance once TASK-015 is approved and implemented. Existing aggregate history stays intact. Existing prescription ranges/order/rest/optional flags remain unless explicitly changed here.
- Minute-by-minute EMOM supersedes aggregate-only logging for new detailed performance under TASK-015. Existing aggregate history stays intact. Existing prescription ranges/order/rest/optional flags remain unless explicitly changed here.
### Implemented equipment correction — 2026-11-04
At Captain's explicit request, seed v7 now assigns weighted vest support with unspecified load to front planks and side-plank hip raises. Both accept actual vest kilograms per set, including zero. Front planks remain duration-prescribed and require no reps; hip raises retain repetitions per side. This implements only these two assignments from the planning matrix, not the rest of TASK-015. Existing bodyweight-only performances remain historical data.
### TASK-015 candidate — 2026-11-04
All 30 definitions now describe equipment and measurement semantics without numeric resistance. Seed v8 aligns push-up plus, single-leg RDLs and finger hangs with the matrix and makes the daily-hang goal continuous. Unilateral actuals use separate left/right values. New actual dumbbell entries use kg per dumbbell and count; bars include the bar. Old prescription vest values above remain plan context, not capabilities or automatically achieved values. Details retain available source notes with honest content/image placeholders. No timers return. Captain accepted TASK-015 on 2026-11-04, including the later count-input and completion-checkbox refinements.
Floor-fly clarification (2026-11-04): always use two dumbbells. Enter kilograms per dumbbell; no dumbbell-count input is required. New records retain the fixed count of two for accurate resistance/volume calculations without changing historical records.
Further UI clarification (2026-11-04): no exercise needs a “Dumbbells used” input. New rows use the exercise definition's one-/two-dumbbell count internally. Kg-per-dumbbell inputs remain, and historical actual counts are preserved rather than recalculated from the current definition.
+11
View File
@@ -19,6 +19,7 @@
"@vitejs/plugin-react": "6.0.1",
"eslint": "9.39.3",
"eslint-plugin-react": "7.37.2",
"fake-indexeddb": "6.2.7",
"globals": "16.4.0",
"jsdom": "29.1.1",
"vite": "8.0.3",
@@ -2397,6 +2398,16 @@
"node": ">=12.0.0"
}
},
"node_modules/fake-indexeddb": {
"version": "6.2.7",
"resolved": "https://registry.npmjs.org/fake-indexeddb/-/fake-indexeddb-6.2.7.tgz",
"integrity": "sha512-g0ghQ+BmU3CSZaHup5FigEAAtCmtNyxkrmID7OAeK2qONHghw1aQ2l2T1RxmfhP1H1tEXVRWArUTGVCk5832ww==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">=18"
}
},
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
+1
View File
@@ -23,6 +23,7 @@
"@vitejs/plugin-react": "6.0.1",
"eslint": "9.39.3",
"eslint-plugin-react": "7.37.2",
"fake-indexeddb": "6.2.7",
"globals": "16.4.0",
"jsdom": "29.1.1",
"vite": "8.0.3",
+24 -21
View File
@@ -1,9 +1,10 @@
import { useEffect, useState } from 'react'
import { Button, Container, Nav, Navbar } from 'react-bootstrap'
import { exerciseDefinitions, initialRoutine } from './data/index.js'
import { addCalendarDays, loadLabel, localCalendarDate, localDateKey, prescriptionLabel, restLabel, routineForDate, startOfWeek } from './routineView.js'
import { addCalendarDays, localCalendarDate, localDateKey, prescriptionLabel, restLabel, routineForDate, startOfWeek } from './routineView.js'
import HangGoalEditor from './HangGoalEditor.jsx'
import StrengthEntryEditor from './StrengthEntryEditor.jsx'
import PerformanceEditor from './PerformanceEditor.jsx'
import { equipmentLabels } from './performanceModel.js'
import { readDailyHangGoal, writeDailyHangGoal } from './hangGoalStorage.js'
const sections = [
@@ -13,7 +14,7 @@ const sections = [
{ id: 'plan', label: 'Plan', title: 'Your training plan', description: 'Routine editing will become available in a later task.' },
{ id: 'settings', label: 'Settings', title: 'Your data and preferences', description: 'Local backup and app settings will become available in a later task.' },
]
const exerciseNames = new Map(exerciseDefinitions.map(({ id, name }) => [id, name]))
const exerciseLibrary = new Map(exerciseDefinitions.map((definition) => [definition.id, definition]))
const initialHangGoalSeconds = initialRoutine.days.monday.afternoon.exercises.find(({ exerciseId }) => exerciseId === 'daily-hang').prescription.goalDurationSec
const dateFormatter = new Intl.DateTimeFormat('en-IE', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' })
const weekdayFormatter = new Intl.DateTimeFormat('en-IE', { weekday: 'short' })
@@ -46,26 +47,28 @@ function savedPeriod() {
}
}
function ExerciseList({ exercises, dateKey, hangGoalSeconds, hangGoalLoading, hangGoalError, onSaveHangGoal }) {
return (
<ol className="exercise-list">
{exercises.map(({ order, exerciseId, prescription, optional, rest, load }) => (
<li className="exercise-card" key={`${order}-${exerciseId}`}>
function ExerciseList({ exercises, dateKey, period, hangGoalSeconds, hangGoalLoading, hangGoalError, onSaveHangGoal }) {
return <ol className="exercise-list">{exercises.map(({ order, exerciseId, prescription, optional, rest, notes }) => {
const definition = exerciseLibrary.get(exerciseId)
const isHang = definition.protocols?.includes('attempts')
const target = isHang ? { ...prescription, goalDurationSec: hangGoalSeconds } : prescription
return <li className="exercise-card" key={`${order}-${exerciseId}`}>
<span className="exercise-number" aria-hidden="true">{order}</span>
<div className="exercise-copy">
<div className="exercise-title-row">
<h3>{exerciseNames.get(exerciseId)}</h3>
{optional && <span className="optional-tag">Optional</span>}
</div>
<p className="prescription">{prescriptionLabel(exerciseId === 'daily-hang' ? { ...prescription, goalDurationSec: hangGoalSeconds } : prescription)}</p>
{(rest || load) && <p className="exercise-meta">{[restLabel(rest), loadLabel(load)].filter(Boolean).join(' · ')}</p>}
{(['emom', 'repetitions'].includes(prescription.kind) || ['suitcase-carry', 'front-plank'].includes(exerciseId)) && <StrengthEntryEditor key={`${dateKey}-${exerciseId}`} dateKey={dateKey} exerciseId={exerciseId} kind={prescription.kind === 'emom' ? 'emom' : ['suitcase-carry', 'front-plank'].includes(exerciseId) ? 'load-sets' : 'sets'} load={load} />}
{exerciseId === 'daily-hang' && <HangGoalEditor goalSeconds={hangGoalSeconds} loading={hangGoalLoading} storageError={hangGoalError} onSave={onSaveHangGoal} />}
<div className="exercise-title-row"><h3>{definition.name}</h3>{optional && <span className="optional-tag">Optional</span>}</div>
<p className="prescription">Target: {prescriptionLabel(target).replace(/^Goal: /, '')}{isHang ? ' continuous' : ''}</p>
<p className="exercise-meta">{definition.equipment.map((equipment) => equipmentLabels[equipment]).join(' + ')}{rest ? ` · ${restLabel(rest)}` : ''}</p>
<PerformanceEditor key={`${dateKey}-${period}-${exerciseId}`} dateKey={dateKey} period={period} definition={definition} prescription={target} goalSeconds={hangGoalSeconds} />
{isHang && <HangGoalEditor goalSeconds={hangGoalSeconds} loading={hangGoalLoading} storageError={hangGoalError} onSave={onSaveHangGoal} />}
<details className="exercise-details"><summary>Exercise details</summary>
{notes && <p>{notes}</p>}
{definition.supports?.map((text) => <p key={text}>{text}</p>)}
<p>Instructions and muscles worked: reviewed content is not yet available.</p>
<p role="img" aria-label="Exercise illustration not yet available">Illustration not yet available.</p>
</details>
</div>
</li>
))}
</ol>
)
})}</ol>
}
function RoutineView({ selectedDate, setSelectedDate, period, setPeriod, setActiveId, hangGoalSeconds, hangGoalLoading, hangGoalError, onSaveHangGoal }) {
@@ -134,10 +137,10 @@ function RoutineView({ selectedDate, setSelectedDate, period, setPeriod, setActi
{session.exercises.length > 0 && <span className="session-count">{session.exercises.length} exercises</span>}
</div>
{session.targetEffortRpe && <p className="session-guidance">Target effort: RPE {session.targetEffortRpe.min}–{session.targetEffortRpe.max} · One round to start; a second round only if recovery remains good.</p>}
{session.exercises.length > 0 && <ExerciseList exercises={session.exercises} dateKey={localDateKey(selectedDate)} hangGoalSeconds={hangGoalSeconds} hangGoalLoading={hangGoalLoading} hangGoalError={hangGoalError} onSaveHangGoal={onSaveHangGoal} />}
{session.exercises.length > 0 && <ExerciseList exercises={session.exercises} period={period} dateKey={localDateKey(selectedDate)} hangGoalSeconds={hangGoalSeconds} hangGoalLoading={hangGoalLoading} hangGoalError={hangGoalError} onSaveHangGoal={onSaveHangGoal} />}
</section>
<p className="shell-note">Enter actual reps and the relevant weights for strength work. Other recording will be added later.</p>
<p className="shell-note">Targets describe the plan. Save actual performance to complete filled rows. Incomplete rows stay drafts; browsing never saves an entry.</p>
</div>
)
}
+52
View File
@@ -0,0 +1,52 @@
import { IDBFactory } from 'fake-indexeddb'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import App from './App.jsx'
import { readPerformance } from './performanceStorage.js'
import { readStrengthEntry, writeStrengthEntry } from './strengthStorage.js'
import { writeDailyHangGoal } from './hangGoalStorage.js'
beforeEach(() => {
vi.stubGlobal('indexedDB', new IDBFactory())
vi.useFakeTimers({ toFake: ['Date'] }); vi.setSystemTime(new Date(2026, 10, 3, 12))
window.localStorage.clear()
})
afterEach(() => { cleanup(); vi.useRealTimers(); vi.unstubAllGlobals() })
it('runs detailed logging through the actual UI/storage boundary while preserving original EMOM totals', async () => {
const legacy = { kind: 'emom', totalReps: 36, externalKg: 6 }
await writeStrengthEntry('2026-11-03', 'pull-up', legacy)
const view = render(<App />)
const card = screen.getByText('Pull-ups').closest('.exercise-card')
await waitFor(() => expect(within(card).getByLabelText('Minute 1 reps').disabled).toBe(false))
fireEvent.change(within(card).getByLabelText('Minute 1 reps'), { target: { value: '4' } })
fireEvent.change(within(card).getByLabelText('Minute 1 vest (kg)'), { target: { value: '8' } })
fireEvent.click(within(card).getByRole('button', { name: 'Save performance' }))
await within(card).findByText('Saved')
expect(await readStrengthEntry('2026-11-03', 'pull-up')).toEqual(legacy)
const saved = await readPerformance('2026-11-03', 'morning', 'pull-up')
expect(saved.rows[0]).toEqual({ completed: true, values: { reps: 4 }, load: { vestKg: 8 } })
expect(saved.rows[1]).toEqual({ completed: false, values: { reps: null }, load: { vestKg: null } })
view.unmount(); render(<App />)
const restored = screen.getByText('Pull-ups').closest('.exercise-card')
await waitFor(() => expect(within(restored).getByLabelText('Minute 1 vest (kg)').value).toBe('8'))
fireEvent.click(screen.getByRole('button', { name: 'Next week' }))
expect(await readPerformance('2026-11-10', 'morning', 'pull-up')).toBeNull()
})
it('uses a persisted continuous hang target without losing unsaved attempts when editing it', async () => {
await writeDailyHangGoal(180)
render(<App />)
fireEvent.click(screen.getByRole('button', { name: 'Afternoon' }))
const hang = screen.getByText('Daily hanging practice').closest('.exercise-card')
await within(hang).findByText('Target: 3 min continuous')
await waitFor(() => expect(within(hang).getByLabelText('Attempt 1 seconds').disabled).toBe(false))
fireEvent.change(within(hang).getByLabelText('Attempt 1 seconds'), { target: { value: '90' } })
fireEvent.change(screen.getByLabelText('Hang goal (seconds)'), { target: { value: '150' } })
fireEvent.click(screen.getByRole('button', { name: 'Save goal' }))
await within(hang).findByText('Target: 150 sec continuous')
expect(within(hang).getByLabelText('Attempt 1 seconds').value).toBe('90')
fireEvent.click(within(hang).getByRole('button', { name: 'Save performance' }))
await within(hang).findByText('Saved')
const saved = await readPerformance('2026-11-03', 'afternoon', 'daily-hang')
expect(saved.prescription.goalDurationSec).toBe(150)
expect(saved.rows[0].values.seconds).toBe(90)
expect(saved.rows[0].completed).toBe(true)
})
+9 -7
View File
@@ -10,36 +10,38 @@ vi.mock('./hangGoalStorage.js', () => ({
}),
}))
import { IDBFactory } from 'fake-indexeddb'
import App from './App.jsx'
beforeEach(() => {
vi.stubGlobal('indexedDB', new IDBFactory())
saved.goal = null
saved.fail = false
window.localStorage.clear()
})
afterEach(() => cleanup())
afterEach(() => { cleanup(); vi.unstubAllGlobals() })
describe('daily hanging goal', () => {
it('changes the goal across days and reloads without hold times or vest details', async () => {
const view = render(<App />)
fireEvent.click(screen.getByRole('button', { name: 'Afternoon' }))
await waitFor(() => expect(screen.getByLabelText('Hang goal (seconds)').disabled).toBe(false))
expect(screen.getByText('Goal: 2 min')).toBeTruthy()
expect(screen.getByText('Deep squat hold').closest('.exercise-card').querySelector('.prescription').textContent).toBe('Hold')
expect(screen.getByText('Target: 2 min continuous')).toBeTruthy()
expect(screen.getByText('Deep squat hold').closest('.exercise-card').querySelector('.prescription').textContent).toBe('Target: Hold')
expect(screen.queryByText(/Vest load not specified/)).toBeNull()
fireEvent.change(screen.getByLabelText('Hang goal (seconds)'), { target: { value: '180' } })
fireEvent.click(screen.getByRole('button', { name: 'Save goal' }))
await screen.findByText('Goal: 3 min')
await screen.findByText('Target: 3 min continuous')
fireEvent.click(screen.getByRole('button', { name: 'Next week' }))
expect(screen.getByText('Goal: 3 min')).toBeTruthy()
expect(screen.getByText('Target: 3 min continuous')).toBeTruthy()
view.unmount()
render(<App />)
fireEvent.click(screen.getByRole('button', { name: 'Afternoon' }))
await screen.findByText('Goal: 3 min')
await screen.findByText('Target: 3 min continuous')
})
it('shows a save failure without changing the displayed goal', async () => {
@@ -50,6 +52,6 @@ describe('daily hanging goal', () => {
fireEvent.change(screen.getByLabelText('Hang goal (seconds)'), { target: { value: '240' } })
fireEvent.click(screen.getByRole('button', { name: 'Save goal' }))
expect((await screen.findByRole('alert')).textContent).toMatch(/Could not save/)
expect(screen.getByText('Goal: 2 min')).toBeTruthy()
expect(screen.getByText('Target: 2 min continuous')).toBeTruthy()
})
})
+108
View File
@@ -0,0 +1,108 @@
import { useEffect, useId, useState } from 'react'
import { Button } from 'react-bootstrap'
import { blankRow, copy, loadColumns, measurementColumns, newPerformance, performanceError, performanceTotals, preparePerformanceForSave, signature } from './performanceModel.js'
import { previousPerformance, readPerformance, writePerformance } from './performanceStorage.js'
import { readStrengthEntry } from './strengthStorage.js'
import StrengthEntryEditor from './StrengthEntryEditor.jsx'
export default function PerformanceEditor({ dateKey, period, definition, prescription, goalSeconds }) {
const id = useId()
const [record, setRecord] = useState(() => newPerformance(dateKey, period, definition, prescription))
const [legacy, setLegacy] = useState(null)
const [hasSaved, setHasSaved] = useState(false)
const [loading, setLoading] = useState(true)
const [readFailed, setReadFailed] = useState(false)
const [retry, setRetry] = useState(0)
const [saving, setSaving] = useState(false)
const [error, setError] = useState('')
const [notice, setNotice] = useState('')
const [dirty, setDirty] = useState(false)
useEffect(() => {
let active = true
setLoading(true)
Promise.all([readPerformance(dateKey, period, definition.id), period === 'morning' ? readStrengthEntry(dateKey, definition.id) : Promise.resolve(null)])
.then(([saved, old]) => {
if (!active) return
setRecord(saved ?? newPerformance(dateKey, period, definition, prescription))
setLegacy(old)
setHasSaved(Boolean(saved))
setReadFailed(false)
setError('')
setDirty(false)
setLoading(false)
}).catch((failure) => { if (active) { setReadFailed(true); setError(failure.message); setLoading(false) } })
return () => { active = false }
}, [dateKey, period, definition, retry])
function change(next) { setRecord(next); setDirty(true); setNotice(''); setError('') }
function update(index, group, key, raw) {
const value = raw === '' ? null : Number(raw)
change({ ...record, rows: record.rows.map((row, i) => i === index ? { ...row, completed: false, [group]: { ...row[group], [key]: value } } : row) })
}
async function save(event) {
event.preventDefault()
const candidate = preparePerformanceForSave(hasSaved ? record : { ...record, prescription: copy(prescription) })
const failure = performanceError(candidate)
if (failure) { setError(failure); return }
setSaving(true); setError(''); setNotice('')
try { await writePerformance(candidate); setRecord(candidate); setHasSaved(true); setDirty(false); setNotice('Saved') }
catch (failure) { setError(failure.message) }
finally { setSaving(false) }
}
async function suggest() {
setSaving(true); setError('')
try {
const previous = await previousPerformance(dateKey, period, record.definition, record.format)
if (!previous) { setNotice('No compatible previous session found.'); return }
// Only fill a blank current record. Do not overwrite existing values or completed work.
if (record.rows.some((row) => row.completed || Object.values(row.values).some((value) => value !== null) || Object.entries(row.load).some(([key, value]) => key === 'dumbbellCount' ? value !== record.definition.dumbbellCount : value !== null))) {
setNotice('Current entries kept. Previous-session suggestions are available for an empty entry.'); return
}
const priorRows = previous.rows.filter((row) => row.completed)
const rows = record.format === 'emom' ? record.rows.map((row, index) => previous.rows[index]?.completed ? { ...copy(previous.rows[index]), completed: false } : row) : priorRows.map((row) => ({ ...copy(row), completed: false }))
change({ ...record, rows }); setNotice(`Suggested from ${previous.date}. Review the suggestions, then save to record completed rows.`)
} catch (failure) { setError(failure.message) }
finally { setSaving(false) }
}
const columns = [...measurementColumns(record.definition).map((column) => ({ ...column, group: 'values' })), ...loadColumns(record.definition).filter((column) => !column.hidden).map((column) => ({ ...column, group: 'load' }))]
const disabled = loading || readFailed || saving
const totals = performanceTotals(record)
const rowName = record.format === 'emom' ? 'Minute' : record.format === 'attempts' ? 'Attempt' : 'Set'
const oldLoad = legacy?.load ?? legacy?.sets?.[0]?.load
const changedDefinition = signature(definition, record.format) !== signature(record.definition, record.format)
const canSwitch = definition.protocols?.includes('emom') && record.rows.every((row) => !row.completed && Object.values(row.values).every((v) => v === null) && Object.entries(row.load).every(([key, value]) => key === 'dumbbellCount' || value === null))
return (
<div className="performance-entry">
{legacy && <details className="legacy-entry"><summary>Earlier record · original {legacy.kind === 'emom' ? 'EMOM total' : legacy.kind === 'load-sets' ? 'weights only' : 'sets'}</summary>
<p>Preserved separately. No minute, side or duration values have been inferred. Detailed entries below do not replace this record.</p>
<StrengthEntryEditor dateKey={dateKey} exerciseId={definition.id} kind={legacy.kind} load={oldLoad} />
</details>}
{changedDefinition && <p role="status">This entry uses its saved exercise definition. Current targets above do not change its recorded equipment or measurements.</p>}
<form onSubmit={save} aria-label={`${definition.name} actual performance`} aria-busy={loading || saving} aria-describedby={error ? `${id}-error` : undefined}>
<div className="performance-toolbar"><strong>Actual performance{record.format === 'emom' ? ' · per minute' : ''}</strong>
{canSwitch && <Button type="button" variant="link" size="sm" disabled={disabled} onClick={() => change(newPerformance(dateKey, period, definition, prescription, record.format === 'emom' ? 'sets' : 'emom'))}>{record.format === 'emom' ? 'Use conventional sets' : 'Use EMOM minutes'}</Button>}
</div>
{loading && <p role="status">Loading saved performance…</p>}
<div className="performance-head" aria-hidden="true" style={{ '--fields': columns.length }}><span>{rowName}</span>{columns.map(({ key, label }) => <span key={key}>{label}</span>)}</div>
<div className="performance-rows">
{record.rows.map((row, index) => <div key={index} className={`performance-row${row.completed ? ' is-complete' : ''}`} style={{ '--fields': columns.length }}>
<strong className="row-number">{rowName} {index + 1}</strong>
{columns.map(({ key, label, group, whole, min = 0, max }) => <label key={key}><span className="field-label">{label}</span><input type="number" inputMode={whole ? 'numeric' : 'decimal'} min={min} max={max} step={whole ? 1 : 'any'} aria-label={`${rowName} ${index + 1} ${label.toLowerCase()}`} value={row[group][key] ?? ''} disabled={disabled} onChange={(event) => update(index, group, key, event.target.value)} /></label>)}
{record.format !== 'emom' && record.rows.length > 1 && <Button type="button" className="remove-row" variant="link" size="sm" disabled={disabled} aria-label={`Remove ${rowName.toLowerCase()} ${index + 1}`} onClick={() => change({ ...record, rows: record.rows.filter((_, i) => i !== index) })}>Remove</Button>}
</div>)}
</div>
<div className="performance-actions">
{record.format !== 'emom' && <Button type="button" variant="outline-secondary" size="sm" disabled={disabled || record.rows.length >= 1000} onClick={() => change({ ...record, rows: [...record.rows, blankRow(record.definition, record.rows.at(-1))] })}>Add {record.format === 'attempts' ? 'attempt' : 'set'}</Button>}
<Button type="button" variant="link" size="sm" disabled={disabled} onClick={suggest}>Use previous session</Button>
<Button type="submit" size="sm" disabled={disabled}>{saving ? 'Saving…' : 'Save performance'}</Button>
</div>
{readFailed && <Button type="button" variant="outline-secondary" onClick={() => setRetry(retry + 1)}>Retry loading</Button>}
<p className="performance-status" role="status">{dirty ? 'Unsaved changes. ' : ''}{notice}</p>
{error && <p id={`${id}-error`} className="strength-error" role="alert">{error}</p>}
{record.format === 'attempts' ? <p className="performance-summary">Longest continuous: {totals.longest} sec · Total hanging: {totals.seconds} sec · {totals.longest >= goalSeconds ? 'Continuous target achieved' : `Continuous target: ${goalSeconds} sec`}</p>
: <p className="performance-summary">{totals.completed}/{record.rows.length} {record.format === 'emom' ? 'minutes' : 'sets'} complete{record.format === 'emom' ? ` · ${totals.reps} total reps` : ''} · Partial entries can be saved.</p>}
</form>
</div>
)
}
+239
View File
@@ -0,0 +1,239 @@
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
const memory = vi.hoisted(() => ({ records: new Map(), legacy: null, fail: false, readFail: false, previous: null }))
vi.mock('./performanceStorage.js', () => ({
readPerformance: vi.fn(async (date, period, id) => { if (memory.readFail) throw new Error('Storage read failed'); return memory.records.get(`${date}:${period}:${id}`) ?? null }),
writePerformance: vi.fn(async (record) => { if (memory.fail) throw new Error('Storage write failed'); memory.records.set(`${record.date}:${record.period}:${record.exerciseId}`, structuredClone(record)) }),
previousPerformance: vi.fn(async () => memory.previous),
}))
vi.mock('./strengthStorage.js', () => ({ readStrengthEntry: vi.fn(async () => memory.legacy), writeStrengthEntry: vi.fn(async () => {}) }))
vi.mock('./hangGoalStorage.js', () => ({ readDailyHangGoal: vi.fn(async () => null), writeDailyHangGoal: vi.fn(async () => {}) }))
import PerformanceEditor from './PerformanceEditor.jsx'
import App from './App.jsx'
import { exerciseDefinitions, initialRoutine } from './data/index.js'
import { loadColumns, measurementColumns, newPerformance } from './performanceModel.js'
const def = (id) => exerciseDefinitions.find((item) => item.id === id)
const rx = (id) => Object.values(initialRoutine.days).flatMap((day) => [...day.morning.exercises, ...day.afternoon.exercises]).find((item) => item.exerciseId === id).prescription
const props = (id) => ({ dateKey: '2026-11-03', period: 'morning', definition: def(id), prescription: rx(id), goalSeconds: 120 })
async function ready() { await waitFor(() => expect(screen.getByRole('button', { name: 'Save performance' }).disabled).toBe(false)) }
const fill = (name, value) => fireEvent.change(screen.getByLabelText(name), { target: { value: String(value) } })
beforeEach(() => { memory.records.clear(); memory.legacy = null; memory.fail = false; memory.readFail = false; memory.previous = null })
afterEach(() => { cleanup(); vi.useRealTimers() })
it.each(exerciseDefinitions)('shows only applicable controls for $id', async (definition) => {
render(<PerformanceEditor {...props(definition.id)} />)
await ready()
const row = definition.protocols?.includes('attempts') ? 'Attempt' : rx(definition.id).kind === 'emom' ? 'Minute' : 'Set'
const expected = [...measurementColumns(definition), ...loadColumns(definition).filter((column) => !column.hidden)].map((column) => column.label.toLowerCase())
for (const label of ['reps', 'left reps', 'right reps', 'seconds', 'left seconds', 'right seconds', 'vest (kg)', 'dumbbell (kg each)', 'dumbbells used', 'ez bar total (kg)', 'straight bar total (kg)']) {
const input = screen.queryByLabelText(`${row} 1 ${label}`)
expect(Boolean(input), `${definition.id}: ${label}`).toBe(expected.includes(label))
}
expect(screen.queryByRole('button', { name: /Start.*timer|Sound|Start EMOM/ })).toBeNull()
expect(screen.queryByRole('checkbox')).toBeNull()
})
it('completes filled rows on save, keeps incomplete drafts, then restores by date', async () => {
const p = props('dumbbell-floor-fly')
const view = render(<PerformanceEditor {...p} />); await ready()
fill('Set 1 reps', 12); fill('Set 1 dumbbell (kg each)', 8)
fireEvent.click(screen.getByRole('button', { name: 'Add set' }))
expect(screen.getByLabelText('Set 2 dumbbell (kg each)').value).toBe('8')
expect(screen.getByLabelText('Set 2 reps').value).toBe('')
fill('Set 2 dumbbell (kg each)', 0)
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
const saved = memory.records.get('2026-11-03:morning:dumbbell-floor-fly')
expect(saved.rows[0]).toMatchObject({ completed: true, values: { reps: 12 }, load: { dumbbellKgEach: 8, dumbbellCount: 2 } })
expect(saved.rows[1]).toMatchObject({ completed: false, values: { reps: null }, load: { dumbbellKgEach: 0 } })
view.unmount(); render(<PerformanceEditor {...p} />); await ready()
expect(screen.queryByRole('checkbox')).toBeNull()
expect(screen.getByLabelText('Set 2 dumbbell (kg each)').value).toBe('0')
cleanup(); render(<PerformanceEditor {...p} dateKey="2026-11-10" />); await ready()
expect(screen.getByLabelText('Set 1 reps').value).toBe('')
expect(memory.records.size).toBe(1)
})
it('logs independent left/right durations without repetitions and validates completed rows', async () => {
render(<PerformanceEditor {...props('bird-dog-hold')} />); await ready()
fill('Set 1 left seconds', 20);
fireEvent.click(screen.getByRole('button', { name: 'Save performance' }))
await screen.findByText('Saved')
expect(memory.records.values().next().value.rows[0]).toMatchObject({ completed: false, values: { leftSeconds: 20, rightSeconds: null } })
fill('Set 1 right seconds', 25)
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
expect(memory.records.values().next().value.rows[0].values).toEqual({ leftSeconds: 20, rightSeconds: 25 })
})
it('keeps independent vest and dumbbell loads for each mixed-equipment set', async () => {
render(<PerformanceEditor {...props('bulgarian-split-squat')} />); await ready()
fill('Set 1 left reps', 10); fill('Set 1 right reps', 9); fill('Set 1 vest (kg)', 5); fill('Set 1 dumbbell (kg each)', 12)
fireEvent.click(screen.getByRole('button', { name: 'Add set' }))
fill('Set 2 vest (kg)', 0); fill('Set 2 dumbbell (kg each)', 14)
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
const rows = memory.records.values().next().value.rows
expect(rows[0].load).toEqual({ vestKg: 5, dumbbellKgEach: 12, dumbbellCount: 2 })
expect(rows[1].load).toEqual({ vestKg: 0, dumbbellKgEach: 14, dumbbellCount: 2 })
})
it('tracks minute-by-minute EMOM with separate resistance and completed-rep total', async () => {
render(<PerformanceEditor {...props('pull-up')} />); await ready()
expect(screen.getAllByLabelText(/^Minute \d+ reps$/)).toHaveLength(10)
expect(screen.queryByRole('checkbox')).toBeNull()
fill('Minute 1 reps', 4); fill('Minute 1 vest (kg)', 6);
fill('Minute 2 reps', 3); fill('Minute 2 vest (kg)', 10);
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
expect(screen.getByText(/2\/10 minutes complete · 7 total reps/)).toBeTruthy()
expect(memory.records.values().next().value.rows.slice(0, 2).map((row) => row.load.vestKg)).toEqual([6, 10])
})
it('reports cumulative hang duration without claiming continuous success', async () => {
render(<PerformanceEditor {...props('daily-hang')} />); await ready()
fill('Attempt 1 seconds', 60);
fireEvent.click(screen.getByRole('button', { name: 'Add attempt' }))
fill('Attempt 2 seconds', 75);
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
expect(screen.getByText(/Longest continuous: 75 sec · Total hanging: 135 sec · Continuous target: 120 sec/)).toBeTruthy()
expect(screen.queryByText(/target achieved/)).toBeNull()
})
it('applies previous-session suggestions only to empty drafts and never marks complete', async () => {
const p = props('front-plank'); memory.previous = newPerformance('2026-10-29', p.period, p.definition, p.prescription)
memory.previous.rows[0] = { values: { seconds: 45 }, load: { vestKg: 8 }, completed: true }
render(<PerformanceEditor {...p} />); await ready()
fireEvent.click(screen.getByRole('button', { name: 'Use previous session' }))
await screen.findByText(/Suggested from 2026-10-29/)
expect(screen.getByLabelText('Set 1 seconds').value).toBe('45')
expect(screen.getByText(/0\/1 sets complete/)).toBeTruthy()
expect(memory.records.size).toBe(0)
fill('Set 1 vest (kg)', 9)
fireEvent.click(screen.getByRole('button', { name: 'Use previous session' }))
await screen.findByText(/Current entries kept/)
expect(screen.getByLabelText('Set 1 vest (kg)').value).toBe('9')
})
it('keeps legacy aggregate values separate and never fabricates minutes', async () => {
memory.legacy = { kind: 'emom', totalReps: 36, externalKg: 6 }
render(<PerformanceEditor {...props('pull-up')} />); await ready()
await waitFor(() => expect(screen.getByLabelText('Total reps').value).toBe('36'))
expect(screen.getByLabelText('Minute 1 reps').value).toBe('')
expect(memory.legacy).toEqual({ kind: 'emom', totalReps: 36, externalKg: 6 })
})
it('recovers from storage read failure and retains entered values after write failure', async () => {
memory.readFail = true
render(<PerformanceEditor {...props('front-plank')} />)
await screen.findByText('Storage read failed')
expect(screen.getByRole('button', { name: 'Save performance' }).disabled).toBe(true)
memory.readFail = false; fireEvent.click(screen.getByRole('button', { name: 'Retry loading' })); await ready()
fill('Set 1 seconds', 35); memory.fail = true
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Storage write failed')
expect(screen.getByLabelText('Set 1 seconds').value).toBe('35')
expect(screen.queryByText('Saved')).toBeNull()
})
it('preserves in-progress daily-hang attempts when the editable goal changes', async () => {
const p = props('daily-hang'); const view = render(<PerformanceEditor {...p} />); await ready()
fill('Attempt 1 seconds', 90)
view.rerender(<PerformanceEditor {...p} prescription={{ ...p.prescription, goalDurationSec: 150 }} goalSeconds={150} />)
expect(screen.getByLabelText('Attempt 1 seconds').value).toBe('90')
expect(screen.getByText(/Continuous target: 150 sec/)).toBeTruthy()
})
it('integrates details and applicable logging with the existing navigation', async () => {
vi.useFakeTimers({ toFake: ['Date'] }); vi.setSystemTime(new Date(2026, 10, 4, 12)); window.localStorage.clear()
render(<App />)
const flys = screen.getByText('Dumbbell floor flys').closest('.exercise-card')
await waitFor(() => expect(within(flys).getByLabelText('Set 1 dumbbell (kg each)').disabled).toBe(false))
fireEvent.click(within(flys).getByText('Exercise details'))
expect(within(flys).getByText(/reviewed content is not yet available/)).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Afternoon' }))
expect(screen.getByText('Bird-dog hold')).toBeTruthy()
expect(screen.getByText('Daily hanging practice')).toBeTruthy()
expect(screen.queryByText('Dumbbell floor flys')).toBeNull()
expect(screen.getByLabelText('Current local time')).toBeTruthy()
expect(memory.records.size).toBe(0)
})
it('snapshots the current target on first save without changing a previously saved target', async () => {
const p = props('daily-hang'); const view = render(<PerformanceEditor {...p} />); await ready()
view.rerender(<PerformanceEditor {...p} prescription={{ ...p.prescription, goalDurationSec: 180 }} goalSeconds={180} />)
fill('Attempt 1 seconds', 80)
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
expect(memory.records.values().next().value.prescription.goalDurationSec).toBe(180)
view.rerender(<PerformanceEditor {...p} prescription={{ ...p.prescription, goalDurationSec: 240 }} goalSeconds={240} />)
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
expect(memory.records.values().next().value.prescription.goalDurationSec).toBe(180)
})
it('allows switching an empty EMOM entry to conventional sets and back', async () => {
render(<PerformanceEditor {...props('pull-up')} />); await ready()
fireEvent.click(screen.getByRole('button', { name: 'Use conventional sets' }))
expect(screen.getByLabelText('Set 1 reps')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Use EMOM minutes' }))
expect(screen.getAllByLabelText(/^Minute \d+ reps$/)).toHaveLength(10)
expect(screen.queryByRole('checkbox')).toBeNull()
})
it('keeps a recorded historical dumbbell count without displaying a count input', async () => {
const p = props('hammer-curl'); const original = newPerformance(p.dateKey, p.period, p.definition, p.prescription)
original.rows[0] = { values: { reps: 10 }, load: { dumbbellKgEach: 8, dumbbellCount: 1 }, completed: true }
memory.records.set('2026-11-03:morning:hammer-curl', structuredClone(original))
render(<PerformanceEditor {...p} />); await ready()
expect(screen.queryByLabelText('Set 1 dumbbells used')).toBeNull()
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
expect(memory.records.values().next().value).toEqual(original)
})
it('renders straight-bar and distance controls from metadata without a seeded exercise', async () => {
const definition = { ...def('ez-bar-bent-over-row'), equipment: ['straight-bar'], measurement: 'distance' }
render(<PerformanceEditor {...props(definition.id)} definition={definition} />); await ready()
expect(screen.getByLabelText('Set 1 metres')).toBeTruthy()
expect(screen.getByLabelText('Set 1 straight bar total (kg)')).toBeTruthy()
expect(screen.queryByLabelText('Set 1 reps')).toBeNull()
expect(screen.queryByLabelText('Set 1 ez bar total (kg)')).toBeNull()
})
it('renders saved historical controls after the current exercise equipment changes', async () => {
const p = props('front-plank')
const prior = newPerformance(p.dateKey, p.period, p.definition, p.prescription)
prior.rows[0] = { values: { seconds: 45 }, load: { vestKg: 8 }, completed: true }
memory.records.set('2026-11-03:morning:front-plank', prior)
render(<PerformanceEditor {...p} definition={{ ...p.definition, version: 2, equipment: ['bodyweight'] }} />); await ready()
expect(screen.getByLabelText('Set 1 vest (kg)').value).toBe('8')
expect(screen.getByText(/uses its saved exercise definition/)).toBeTruthy()
expect(memory.records.get('2026-11-03:morning:front-plank')).toEqual(prior)
})
it('hides the fixed floor-fly dumbbell count while saving two dumbbells', async () => {
render(<PerformanceEditor {...props('dumbbell-floor-fly')} />); await ready()
expect(screen.queryByLabelText('Set 1 dumbbells used')).toBeNull()
fill('Set 1 reps', 12); fill('Set 1 dumbbell (kg each)', 8)
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
expect(memory.records.values().next().value.rows[0].load).toEqual({ dumbbellKgEach: 8, dumbbellCount: 2 })
})
it('also hides the count on earlier paired floor-fly entries without rewriting their snapshot', async () => {
const p = props('dumbbell-floor-fly'); const record = newPerformance(p.dateKey, p.period, p.definition, p.prescription)
delete record.definition.fixedDumbbellCount; record.definition.version = 1
record.rows[0] = { values: { reps: 12 }, load: { dumbbellKgEach: 8, dumbbellCount: 2 }, completed: true }
memory.records.set('2026-11-03:morning:dumbbell-floor-fly', structuredClone(record))
render(<PerformanceEditor {...p} />); await ready()
expect(screen.queryByLabelText('Set 1 dumbbells used')).toBeNull()
expect(memory.records.values().next().value).toEqual(record)
})
it('fills only an unrecorded legacy draft count from the saved definition on explicit save', async () => {
const p = props('hammer-curl'); const original = newPerformance(p.dateKey, p.period, p.definition, p.prescription)
original.rows[0] = { values: { reps: 10 }, load: { dumbbellKgEach: 8, dumbbellCount: null }, completed: false }
memory.records.set('2026-11-03:morning:hammer-curl', structuredClone(original))
render(<PerformanceEditor {...p} />); await ready()
expect(memory.records.values().next().value.rows[0].load.dumbbellCount).toBeNull()
expect(screen.queryByLabelText('Set 1 dumbbells used')).toBeNull()
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
expect(memory.records.values().next().value.rows[0].load.dumbbellCount).toBe(2)
})
it('turns an edited saved row back into a draft only when explicitly saved', async () => {
const p = props('front-plank'); const original = newPerformance(p.dateKey, p.period, p.definition, p.prescription)
original.rows[0] = { values: { seconds: 45 }, load: { vestKg: 8 }, completed: true }
memory.records.set('2026-11-03:morning:front-plank', structuredClone(original))
render(<PerformanceEditor {...p} />); await ready()
fill('Set 1 seconds', '')
expect(memory.records.values().next().value.rows[0].completed).toBe(true)
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
expect(memory.records.values().next().value.rows[0]).toMatchObject({ values: { seconds: null }, completed: false })
expect(screen.getByText(/0\/1 sets complete/)).toBeTruthy()
})
it('does not count a filled row as achieved when saving fails', async () => {
memory.fail = true
render(<PerformanceEditor {...props('front-plank')} />); await ready()
fill('Set 1 seconds', 45); fill('Set 1 vest (kg)', 0)
expect(screen.getByText(/0\/1 sets complete/)).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Storage write failed')
expect(screen.getByText(/0\/1 sets complete/)).toBeTruthy()
expect(memory.records.size).toBe(0)
})
+58 -221
View File
@@ -1,229 +1,66 @@
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const saved = vi.hoisted(() => ({ entries: new Map(), fail: false }))
// Legacy editor remains available for explicitly editing original-format history.
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
const saved = vi.hoisted(() => ({ entry: null, fail: false }))
vi.mock('./strengthStorage.js', () => ({
readStrengthEntry: vi.fn(async (dateKey, exerciseId) => saved.entries.get(`${dateKey}:${exerciseId}`) ?? null),
writeStrengthEntry: vi.fn(async (dateKey, exerciseId, entry) => {
if (saved.fail) throw new Error('Could not save the strength entry.')
saved.entries.set(`${dateKey}:${exerciseId}`, entry)
}),
readStrengthEntry: vi.fn(async () => saved.entry),
writeStrengthEntry: vi.fn(async (_date, _id, entry) => { if (saved.fail) throw new Error('Could not save the strength entry.'); saved.entry = entry }),
}))
vi.mock('./hangGoalStorage.js', () => ({ readDailyHangGoal: vi.fn(async () => null), writeDailyHangGoal: vi.fn(async () => {}) }))
import App from './App.jsx'
beforeEach(() => {
saved.entries.clear()
saved.fail = false
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(new Date(2026, 9, 27, 12))
window.localStorage.clear()
import StrengthEntryEditor from './StrengthEntryEditor.jsx'
beforeEach(() => { saved.entry = null; saved.fail = false })
afterEach(cleanup)
const editor = (kind = 'sets', load = { dumbbellKgEach: null }) => render(<StrengthEntryEditor dateKey="2026-11-03" exerciseId="legacy-exercise" kind={kind} load={load} />)
it('retains original EMOM totals without allocating them to minutes', async () => {
saved.entry = { kind: 'emom', totalReps: 36, externalKg: 6 }
editor('emom', { vestKg: null })
await waitFor(() => expect(screen.getByLabelText('Total reps').value).toBe('36'))
expect(screen.getByLabelText('previously recorded total external weight (kg)').value).toBe('6')
fireEvent.click(screen.getByRole('button', { name: 'Save reps and weight' }))
await screen.findByText('Saved')
expect(saved.entry).toEqual({ kind: 'emom', totalReps: 36, externalKg: 6 })
})
afterEach(() => {
cleanup()
vi.useRealTimers()
it('copies loads into subsequent legacy sets without copying reps', async () => {
editor()
await waitFor(() => expect(screen.getByLabelText('Set 1 reps').disabled).toBe(false))
fireEvent.change(screen.getByLabelText('Set 1 reps'), { target: { value: '10' } })
fireEvent.change(screen.getByLabelText('Set 1 dumbbell weight (kg each)'), { target: { value: '8' } })
fireEvent.click(screen.getByRole('button', { name: 'Add set' }))
expect(screen.getByLabelText('Set 2 reps').value).toBe('')
expect(screen.getByLabelText('Set 2 dumbbell weight (kg each)').value).toBe('8')
fireEvent.change(screen.getByLabelText('Set 2 reps'), { target: { value: '9' } })
fireEvent.click(screen.getByRole('button', { name: 'Save reps and weight' }))
await screen.findByText('Saved')
expect(saved.entry.sets).toEqual([{ reps: 10, externalKg: 16, load: { dumbbellKgEach: 8 } }, { reps: 9, externalKg: 16, load: { dumbbellKgEach: 8 } }])
})
describe('strength recording without timers', () => {
it('saves one EMOM total and actual external weight by date', async () => {
const view = render(<App />)
const pullUps = screen.getByText('Pull-ups').closest('.exercise-card')
await waitFor(() => expect(within(pullUps).getByLabelText('Total reps').disabled).toBe(false))
expect(within(pullUps).getByText('10 min EMOM · 3–4 reps each minute')).toBeTruthy()
expect(screen.queryByRole('region', { name: 'Workout timers' })).toBeNull()
expect(screen.queryByRole('button', { name: /Start EMOM|Start workout clock|Sound on|Sound off/ })).toBeNull()
fireEvent.change(within(pullUps).getByLabelText('Total reps'), { target: { value: '36' } })
fireEvent.change(within(pullUps).getByLabelText('vest weight (kg)'), { target: { value: '6' } })
fireEvent.click(within(pullUps).getByRole('button', { name: 'Save reps and weight' }))
await within(pullUps).findByText('Saved')
expect(saved.entries.get('2026-10-27:pull-up')).toEqual({ kind: 'emom', totalReps: 36, externalKg: 6, load: { vestKg: 6 } })
view.unmount()
render(<App />)
const again = screen.getByText('Pull-ups').closest('.exercise-card')
await waitFor(() => expect(within(again).getByLabelText('Total reps').value).toBe('36'))
expect(within(again).getByLabelText('vest weight (kg)').value).toBe('6')
it('preserves legacy bodyweight totals until explicit component conversion', async () => {
saved.entry = { kind: 'sets', sets: [{ reps: 12, externalKg: 0, load: { bodyweightOnly: true } }] }
editor('sets', { vestKg: null })
await waitFor(() => expect(screen.getByLabelText('Set 1 previously recorded total external weight (kg)').value).toBe('0'))
expect(saved.entry.sets[0].load).toEqual({ bodyweightOnly: true })
fireEvent.click(screen.getByRole('button', { name: 'Enter specific weights' }))
fireEvent.change(screen.getByLabelText('Set 1 vest weight (kg)'), { target: { value: '5' } })
fireEvent.click(screen.getByRole('button', { name: 'Save reps and weight' }))
await screen.findByText('Saved')
expect(saved.entry.sets[0]).toEqual({ reps: 12, externalKg: 5, load: { vestKg: 5 } })
})
it('saves separate regular sets and keeps dates separate', async () => {
render(<App />)
fireEvent.click(screen.getByRole('button', { name: 'Previous week' }))
fireEvent.click(screen.getByRole('button', { name: /Sunday.*25 October 2026/ }))
const press = screen.getByText('Standing single-arm dumbbell shoulder press').closest('.exercise-card')
await waitFor(() => expect(within(press).getByLabelText('Set 1 reps').disabled).toBe(false))
fireEvent.change(within(press).getByLabelText('Set 1 reps'), { target: { value: '10' } })
fireEvent.change(within(press).getByLabelText('Set 1 dumbbell weight (kg)'), { target: { value: '12' } })
fireEvent.click(within(press).getByRole('button', { name: 'Add set' }))
expect(within(press).getByLabelText('Set 2 dumbbell weight (kg)').value).toBe('12')
expect(within(press).getByLabelText('Set 2 reps').value).toBe('')
fireEvent.change(within(press).getByLabelText('Set 2 reps'), { target: { value: '8' } })
fireEvent.change(within(press).getByLabelText('Set 2 dumbbell weight (kg)'), { target: { value: '14' } })
fireEvent.click(within(press).getByRole('button', { name: 'Add set' }))
expect(within(press).getByLabelText('Set 3 dumbbell weight (kg)').value).toBe('14')
fireEvent.change(within(press).getByLabelText('Set 3 reps'), { target: { value: '7' } })
fireEvent.click(within(press).getByRole('button', { name: 'Save reps and weight' }))
await within(press).findByText('Saved')
expect(saved.entries.get('2026-10-25:single-arm-shoulder-press')).toEqual({ kind: 'sets', sets: [{ reps: 10, externalKg: 12, load: { dumbbellKg: 12 } }, { reps: 8, externalKg: 14, load: { dumbbellKg: 14 } }, { reps: 7, externalKg: 14, load: { dumbbellKg: 14 } }] })
fireEvent.click(screen.getByRole('button', { name: 'Next week' }))
fireEvent.click(screen.getByRole('button', { name: /Sunday.*1 November 2026/ }))
const future = screen.getByText('Standing single-arm dumbbell shoulder press').closest('.exercise-card')
await waitFor(() => expect(within(future).getByLabelText('Set 1 reps').disabled).toBe(false))
expect(within(future).getByLabelText('Set 1 reps').value).toBe('')
expect(saved.entries.size).toBe(1)
it('retains weight-only sets without inventing reps or durations', async () => {
saved.entry = { kind: 'load-sets', sets: [{ externalKg: 20, load: { dumbbellKg: 20 } }] }
editor('load-sets', { dumbbellKg: null })
await waitFor(() => expect(screen.getByLabelText('Set 1 dumbbell weight (kg)').value).toBe('20'))
expect(screen.queryByLabelText(/reps/i)).toBeNull()
fireEvent.click(screen.getByRole('button', { name: 'Save weight' }))
await screen.findByText('Saved')
expect(saved.entry.sets[0]).not.toHaveProperty('reps')
})
it('records flys as dumbbell weight per dumbbell, without a vest field', async () => {
render(<App />)
fireEvent.click(screen.getByRole('button', { name: /Wednesday.*28 October 2026/ }))
const flys = screen.getByText('Dumbbell floor flys').closest('.exercise-card')
await waitFor(() => expect(within(flys).getByLabelText('Set 1 dumbbell weight (kg each)').disabled).toBe(false))
expect(within(flys).queryByLabelText(/vest weight/i)).toBeNull()
fireEvent.change(within(flys).getByLabelText('Set 1 reps'), { target: { value: '12' } })
fireEvent.change(within(flys).getByLabelText('Set 1 dumbbell weight (kg each)'), { target: { value: '8' } })
fireEvent.click(within(flys).getByRole('button', { name: 'Add set' }))
expect(within(flys).getByLabelText('Set 2 dumbbell weight (kg each)').value).toBe('8')
fireEvent.change(within(flys).getByLabelText('Set 2 reps'), { target: { value: '10' } })
fireEvent.click(within(flys).getByRole('button', { name: 'Save reps and weight' }))
await within(flys).findByText('Saved')
expect(saved.entries.get('2026-10-28:dumbbell-floor-fly')).toEqual({ kind: 'sets', sets: [
{ reps: 12, externalKg: 16, load: { dumbbellKgEach: 8 } },
{ reps: 10, externalKg: 16, load: { dumbbellKgEach: 8 } },
] })
})
it('keeps vest and dumbbell weights separate for mixed-load sets', async () => {
render(<App />)
fireEvent.click(screen.getByRole('button', { name: /Thursday.*29 October 2026/ }))
const squats = screen.getByText('Squats').closest('.exercise-card')
await waitFor(() => expect(within(squats).getByLabelText('Set 1 vest weight (kg)').disabled).toBe(false))
fireEvent.change(within(squats).getByLabelText('Set 1 reps'), { target: { value: '10' } })
fireEvent.change(within(squats).getByLabelText('Set 1 vest weight (kg)'), { target: { value: '10' } })
fireEvent.change(within(squats).getByLabelText('Set 1 dumbbell weight (kg each)'), { target: { value: '12' } })
fireEvent.click(within(squats).getByRole('button', { name: 'Add set' }))
expect(within(squats).getByLabelText('Set 2 vest weight (kg)').value).toBe('10')
expect(within(squats).getByLabelText('Set 2 dumbbell weight (kg each)').value).toBe('12')
fireEvent.change(within(squats).getByLabelText('Set 2 reps'), { target: { value: '8' } })
fireEvent.click(within(squats).getByRole('button', { name: 'Save reps and weight' }))
await within(squats).findByText('Saved')
expect(saved.entries.get('2026-10-29:squat')).toEqual({ kind: 'sets', sets: [
{ reps: 10, externalKg: 34, load: { vestKg: 10, dumbbellKgEach: 12 } },
{ reps: 8, externalKg: 34, load: { vestKg: 10, dumbbellKgEach: 12 } },
] })
})
it('keeps older total-weight entries as totals rather than reinterpreting them', async () => {
saved.entries.set('2026-10-27:ez-bar-bent-over-row', { kind: 'sets', sets: [{ reps: 10, externalKg: 25 }] })
render(<App />)
const rows = screen.getByText('EZ-bar bent-over rows').closest('.exercise-card')
await waitFor(() => expect(within(rows).getByLabelText('Set 1 previously recorded total external weight (kg)').value).toBe('25'))
fireEvent.click(within(rows).getByRole('button', { name: 'Add set' }))
expect(within(rows).getByLabelText('Set 2 previously recorded total external weight (kg)').value).toBe('25')
fireEvent.change(within(rows).getByLabelText('Set 2 reps'), { target: { value: '8' } })
fireEvent.click(within(rows).getByRole('button', { name: 'Save reps and weight' }))
await within(rows).findByText('Saved')
expect(saved.entries.get('2026-10-27:ez-bar-bent-over-row')).toEqual({ kind: 'sets', sets: [{ reps: 10, externalKg: 25 }, { reps: 8, externalKg: 25 }] })
fireEvent.click(within(rows).getAllByRole('button', { name: 'Enter specific weights' })[0])
expect(within(rows).getByLabelText('Set 1 ez-bar total weight (kg)').value).toBe('')
fireEvent.change(within(rows).getByLabelText('Set 1 ez-bar total weight (kg)'), { target: { value: '25' } })
fireEvent.click(within(rows).getByRole('button', { name: 'Save reps and weight' }))
await within(rows).findByText('Saved')
expect(saved.entries.get('2026-10-27:ez-bar-bent-over-row')).toEqual({ kind: 'sets', sets: [{ reps: 10, externalKg: 25, load: { ezBarTotalKg: 25 } }, { reps: 8, externalKg: 25 }] })
})
it('records suitcase-carry weights per set without requiring reps and restores them', async () => {
const view = render(<App />)
const carry = screen.getByText('Suitcase carries').closest('.exercise-card')
await waitFor(() => expect(within(carry).getByLabelText('Set 1 dumbbell weight (kg)').disabled).toBe(false))
expect(within(carry).queryByLabelText(/reps/i)).toBeNull()
expect(within(carry).queryByLabelText(/vest/i)).toBeNull()
fireEvent.click(within(carry).getByRole('button', { name: 'Save weight' }))
expect(within(carry).getByRole('alert').textContent).toMatch(/each shown weight/)
fireEvent.change(within(carry).getByLabelText('Set 1 dumbbell weight (kg)'), { target: { value: '20' } })
fireEvent.click(within(carry).getByRole('button', { name: 'Add set' }))
expect(within(carry).getByLabelText('Set 2 dumbbell weight (kg)').value).toBe('20')
fireEvent.change(within(carry).getByLabelText('Set 2 dumbbell weight (kg)'), { target: { value: '0' } })
fireEvent.click(within(carry).getByRole('button', { name: 'Save weight' }))
await within(carry).findByText('Saved')
expect(saved.entries.get('2026-10-27:suitcase-carry')).toEqual({ kind: 'load-sets', sets: [
{ externalKg: 20, load: { dumbbellKg: 20 } },
{ externalKg: 0, load: { dumbbellKg: 0 } },
] })
view.unmount()
render(<App />)
const restored = screen.getByText('Suitcase carries').closest('.exercise-card')
await waitFor(() => expect(within(restored).getByLabelText('Set 1 dumbbell weight (kg)').value).toBe('20'))
expect(within(restored).getByLabelText('Set 2 dumbbell weight (kg)').value).toBe('0')
fireEvent.click(screen.getByRole('button', { name: 'Next week' }))
const nextWeek = screen.getByText('Suitcase carries').closest('.exercise-card')
await waitFor(() => expect(within(nextWeek).getByLabelText('Set 1 dumbbell weight (kg)').disabled).toBe(false))
expect(within(nextWeek).getByLabelText('Set 1 dumbbell weight (kg)').value).toBe('')
expect(saved.entries.size).toBe(1)
})
it.each([
['Thursday', '29 October 2026', 'Front plank', 'front-plank', '2026-10-29', 'load-sets'],
['Sunday', '1 November 2026', 'Side-plank hip raises', 'side-plank-hip-raise', '2026-11-01', 'sets'],
])('records vest weights for %s plank work without irrelevant load fields', async (day, date, name, id, dateKey, kind) => {
const view = render(<App />)
fireEvent.click(screen.getByRole('button', { name: new RegExp(`${day}.*${date}`) }))
const card = screen.getByText(name).closest('.exercise-card')
await waitFor(() => expect(within(card).getByLabelText('Set 1 vest weight (kg)').disabled).toBe(false))
expect(within(card).queryByLabelText(/dumbbell|bar total/i)).toBeNull()
expect(within(card).getByLabelText('Set 1 vest weight (kg)').value).toBe('')
if (kind === 'load-sets') expect(within(card).queryByLabelText(/reps/i)).toBeNull()
else fireEvent.change(within(card).getByLabelText('Set 1 reps'), { target: { value: '12' } })
fireEvent.change(within(card).getByLabelText('Set 1 vest weight (kg)'), { target: { value: '6' } })
fireEvent.click(within(card).getByRole('button', { name: 'Add set' }))
expect(within(card).getByLabelText('Set 2 vest weight (kg)').value).toBe('6')
fireEvent.change(within(card).getByLabelText('Set 2 vest weight (kg)'), { target: { value: '0' } })
if (kind === 'sets') fireEvent.change(within(card).getByLabelText('Set 2 reps'), { target: { value: '10' } })
fireEvent.click(within(card).getByRole('button', { name: kind === 'sets' ? 'Save reps and weight' : 'Save weight' }))
await within(card).findByText('Saved')
expect(saved.entries.get(`${dateKey}:${id}`)).toEqual({ kind, sets: [
{ ...(kind === 'sets' ? { reps: 12 } : {}), externalKg: 6, load: { vestKg: 6 } },
{ ...(kind === 'sets' ? { reps: 10 } : {}), externalKg: 0, load: { vestKg: 0 } },
] })
view.unmount()
render(<App />)
fireEvent.click(screen.getByRole('button', { name: new RegExp(`${day}.*${date}`) }))
const restored = screen.getByText(name).closest('.exercise-card')
await waitFor(() => expect(within(restored).getByLabelText('Set 1 vest weight (kg)').value).toBe('6'))
expect(within(restored).getByLabelText('Set 2 vest weight (kg)').value).toBe('0')
})
it('keeps historical bodyweight-only hip raises until explicitly entering vest weights', async () => {
const old = { kind: 'sets', sets: [{ reps: 12, externalKg: 0, load: { bodyweightOnly: true } }] }
saved.entries.set('2026-11-01:side-plank-hip-raise', old)
render(<App />)
fireEvent.click(screen.getByRole('button', { name: /Sunday.*1 November 2026/ }))
const card = screen.getByText('Side-plank hip raises').closest('.exercise-card')
await waitFor(() => expect(within(card).getByLabelText('Set 1 previously recorded total external weight (kg)').value).toBe('0'))
expect(saved.entries.get('2026-11-01:side-plank-hip-raise')).toEqual(old)
fireEvent.click(within(card).getByRole('button', { name: 'Enter specific weights' }))
expect(within(card).getByLabelText('Set 1 vest weight (kg)').value).toBe('')
fireEvent.change(within(card).getByLabelText('Set 1 vest weight (kg)'), { target: { value: '5' } })
fireEvent.click(within(card).getByRole('button', { name: 'Save reps and weight' }))
await within(card).findByText('Saved')
expect(saved.entries.get('2026-11-01:side-plank-hip-raise')).toEqual({ kind: 'sets', sets: [{ reps: 12, externalKg: 5, load: { vestKg: 5 } }] })
})
it('rejects incomplete rows and shows storage failures', async () => {
it('reports incomplete entry and storage failure without showing success', async () => {
saved.fail = true
render(<App />)
const pullUps = screen.getByText('Pull-ups').closest('.exercise-card')
await waitFor(() => expect(within(pullUps).getByLabelText('Total reps').disabled).toBe(false))
fireEvent.click(within(pullUps).getByRole('button', { name: 'Save reps and weight' }))
expect(within(pullUps).getByRole('alert').textContent).toMatch(/whole-number reps/)
expect(saved.entries.size).toBe(0)
fireEvent.change(within(pullUps).getByLabelText('Total reps'), { target: { value: '0' } })
fireEvent.change(within(pullUps).getByLabelText('vest weight (kg)'), { target: { value: '0' } })
fireEvent.click(within(pullUps).getByRole('button', { name: 'Save reps and weight' }))
await waitFor(() => expect(within(pullUps).getByRole('alert').textContent).toMatch(/Could not save/))
})
editor('sets', { vestKg: null })
await waitFor(() => expect(screen.getByLabelText('Set 1 reps').disabled).toBe(false))
fireEvent.click(screen.getByRole('button', { name: 'Save reps and weight' }))
expect(screen.getByRole('alert').textContent).toMatch(/whole-number reps/)
fireEvent.change(screen.getByLabelText('Set 1 reps'), { target: { value: '0' } })
fireEvent.change(screen.getByLabelText('Set 1 vest weight (kg)'), { target: { value: '0' } })
fireEvent.click(screen.getByRole('button', { name: 'Save reps and weight' }))
await waitFor(() => expect(screen.getByRole('alert').textContent).toMatch(/Could not save/))
expect(screen.queryByText('Saved')).toBeNull()
})
+65
View File
@@ -0,0 +1,65 @@
// Versioned adapter only; TASK-009 owns the user-facing import/export workflow.
import { initialRoutine, exerciseDefinitions } from './data/index.js'
import { openLocalDatabase } from './localDatabase.js'
import { performanceError } from './performanceModel.js'
import { performanceKey } from './performanceStorage.js'
import { validEntry } from './strengthStorage.js'
const stores = ['routineOverrides', 'strengthEntries', 'performanceEntries']
function validJSON(value) {
if (value === null || typeof value === 'string' || typeof value === 'boolean') return true
if (typeof value === 'number') return Number.isFinite(value)
return typeof value === 'object' && Object.values(value).every(validJSON)
}
export function parseBackup(input) {
let backup
try { backup = typeof input === 'string' ? JSON.parse(input) : structuredClone(input) }
catch { throw new Error('Invalid backup JSON.') }
if (backup?.format !== 'workout-tracker' || ![1, 2].includes(backup.version) || !backup.stores || typeof backup.stores !== 'object' || Array.isArray(backup.stores)) throw new Error('Unsupported backup schema.')
if (Object.keys(backup.stores).some((store) => !stores.includes(store))) throw new Error('Unsupported backup store.')
// Version 1 is the legacy adapter envelope with the two original stores.
for (const store of stores) {
if (backup.version === 1 && store === 'performanceEntries' && backup.stores[store] == null) backup.stores[store] = []
if (!Array.isArray(backup.stores[store])) throw new Error(`Missing backup store: ${store}.`)
const keys = new Set()
for (const entry of backup.stores[store]) {
if (!entry || typeof entry.key !== 'string' || keys.has(entry.key) || !validJSON(entry.value)) throw new Error('Invalid or duplicate backup entry.')
keys.add(entry.key)
if (store === 'strengthEntries' && (!/^\d{4}-\d{2}-\d{2}:.+/.test(entry.key) || !validEntry(entry.value))) throw new Error('Invalid legacy strength entry.')
if (store === 'performanceEntries' && (performanceError(entry.value) || entry.key !== performanceKey(entry.value.date, entry.value.period, entry.value.exerciseId))) throw new Error('Invalid detailed performance entry.')
if (store === 'routineOverrides' && entry.key === 'dailyHangGoalSec' && (!Number.isSafeInteger(entry.value) || entry.value <= 0)) throw new Error('Invalid hanging goal.')
}
}
return backup
}
export async function exportBackup() {
const db = await openLocalDatabase()
return new Promise((resolve, reject) => {
const tx = db.transaction(stores, 'readonly')
const data = Object.fromEntries(stores.map((store) => [store, []]))
for (const name of stores) {
const cursor = tx.objectStore(name).openCursor()
cursor.onsuccess = () => {
if (cursor.result) { data[name].push({ key: cursor.result.key, value: cursor.result.value }); cursor.result.continue() }
}
}
tx.oncomplete = () => { db.close(); resolve(JSON.stringify({ format: 'workout-tracker', version: 2, reference: { exerciseDefinitions, initialRoutine }, stores: data })) }
tx.onerror = tx.onabort = () => { db.close(); reject(new Error('Could not export local data.')) }
})
}
export async function importBackup(input, { replace = false } = {}) {
const backup = parseBackup(input) // Validate everything before opening a write transaction.
const db = await openLocalDatabase()
return new Promise((resolve, reject) => {
const tx = db.transaction(stores, 'readwrite')
try {
for (const name of stores) {
const store = tx.objectStore(name)
if (replace) store.clear()
for (const { key, value } of backup.stores[name]) store.add(value, key)
}
} catch { tx.abort() }
tx.oncomplete = () => { db.close(); resolve() }
tx.onerror = tx.onabort = () => { db.close(); reject(new Error('Import failed; existing data was left unchanged. Duplicate keys require an explicit replacement.')) }
})
}
+8 -8
View File
@@ -1,15 +1,15 @@
# Initial routine data
# Exercise and routine data
`exerciseDefinitions.json` holds stable IDs, names, and categories. `initialRoutine.json` holds the versioned seven-day prescription and refers to definitions by ID. Neither file contains completed workout records or user edits.
`exerciseDefinitions.json` contains stable IDs/names/categories, definition version, equipment capabilities, measurement type and optional default dumbbell count/protocols/support notes. It contains no numeric resistance. Equipment vocabulary is bodyweight, weighted-vest, dumbbells, ez-curl-bar and straight-bar. No current exercise is assigned straight-bar. Dumbbells used as push-up handles are support equipment, not lifted load.
Each day has separate `morning` and `afternoon` sessions. An exercise's `order` is one-based within its session. A `{ "min", "max" }` pair preserves a documented range; equal bounds represent a single target. Durations use seconds unless the field says `Min`. `null` means the source does not specify a value, especially for current hanging ability, finger-hang duration, and unknown loads. A `goalDurationSec` is a goal, not an achieved duration.
`initialRoutine.json` is seed v8 with separate Morning/Afternoon prescriptions, order, ranges, optional flags, rest and historical prescription load context. All assignments follow WORKOUT_ROUTINE section 8. It preserves unknown values as null, untimed afternoon targets, Monday/Friday empty stretch headings, no walks, and the editable initial 120-second continuous daily-hang goal. Do not infer performance or overwrite local overrides from seed updates.
Loads keep vest, dumbbell, and EZ-bar components separate. The 6 kg and 10 kg values are prescribed vest settings only. The source is [`docs/WORKOUT_ROUTINE.md`](../../docs/WORKOUT_ROUTINE.md); any approved change to the initial programme must update that document and this seed together. A future broader storage adapter must copy this seed only when creating a new local routine, then preserve user edits and history.
`performanceModel.js` maps definition metadata to actual measurement/load fields. New detailed records use schemaVersion 1 and definition/prescription snapshots, independent left/right measurements and per-row completion/load. Dumbbells are kg each with actual count (1/2); vest and bars are separate, with bar totals including the bar. Draft nulls differ from explicit zero. Adding rows copies loads/count, never measurements/completion. EMOM stores ten minute rows; durations and hangs never require reps.
Strength entry fields follow each exercise's `load` keys. `dumbbellKgEach` means the mass of each of two dumbbells; `dumbbellKg` means one dumbbell. Mixed `vestKg` and dumbbell keys produce separate inputs. Actual entries do not assume the seed's prescribed weights. New records retain components and a derived total external weight; older entries with only `externalKg` remain legacy totals.
IndexedDB v3 adds performanceEntries and a compound matching-session index while retaining routineOverrides and strengthEntries unchanged. Original sets, EMOM totals, total-only/component and load-sets history remain in their original store and editor. No old totals are reclassified or distributed into detailed rows. `backupStorage.js` provides adapter JSON v2 for all three stores and a v1 legacy-envelope reader, validation and atomic non-overwriting or explicit-replacement import. TASK-009 owns backup UI; this task adds no Settings controls.
Afternoon isometric holds have no prescribed duration. The daily hang starts with a two-minute goal but no vest field. A user-changed hanging goal is stored separately in IndexedDB by `hangGoalStorage.js`; seed updates must not overwrite it.
Floor-fly definition v2 has `fixedDumbbellCount: 2`: count stays in saved load data and calculations but is hidden in the new UI. Older paired floor-fly snapshots also omit the redundant count control without being rewritten. The subsequent Captain correction hides the count input for all exercises; new rows use the defined count internally. Historical differing counts retain their original snapshot semantics.
Suitcase carries also expose their single-dumbbell load as dated weight-only set entries (`kind: load-sets`). These contain actual load and derived external kilograms, without fabricated repetitions or performed duration. The carry duration-per-side prescription remains separate. Existing repetition sets and EMOM totals are unchanged; no IndexedDB store upgrade is needed.
All dumbbell-count controls are now hidden. Counts remain in stored loads and calculations; existing non-null historical counts are preserved. If an older partial draft has a null count, an explicit Save fills only that unrecorded value from its saved definition. Reading alone never rewrites it.
Seed v7 adds vest-only support (`vestKg: null`) to front planks and side-plank hip raises without prescribing a numeric load. Front planks reuse weight-only `load-sets`; hip raises retain repetition sets. Historical bodyweight-only entries remain prior totals until the user explicitly chooses component entry. No database migration is required.
Completion has no checkbox. `preparePerformanceForSave` derives row completion from applicable values/load only when Save is requested; fully filled valid rows become complete, incomplete rows remain drafts and invalid actuals are rejected. The UI adopts derived completion only after a successful write, preserving failed-save/draft semantics and existing records on read. No schema migration is required.
+333 -30
View File
@@ -1,32 +1,335 @@
[
{"id":"pull-up","name":"Pull-ups","category":"strength"},
{"id":"ez-bar-bent-over-row","name":"EZ-bar bent-over rows","category":"strength"},
{"id":"single-arm-dumbbell-row","name":"Single-arm dumbbell rows","category":"strength"},
{"id":"suitcase-carry","name":"Suitcase carries","category":"strength"},
{"id":"weighted-deep-push-up","name":"Weighted deep push-ups using dumbbells as handles","category":"strength"},
{"id":"dumbbell-floor-fly","name":"Dumbbell floor flys","category":"strength"},
{"id":"push-up-plus","name":"Push-up plus","category":"strength"},
{"id":"feet-elevated-weighted-push-up","name":"Feet-elevated weighted push-ups","category":"strength"},
{"id":"bulgarian-split-squat","name":"Bulgarian split squats","category":"strength"},
{"id":"single-leg-romanian-deadlift","name":"Single-leg Romanian deadlifts","category":"strength"},
{"id":"squat","name":"Squats","category":"strength"},
{"id":"single-leg-calf-raise","name":"Single-leg calf raises","category":"strength"},
{"id":"front-plank","name":"Front plank","category":"strength"},
{"id":"chin-up","name":"Chin-ups","category":"strength"},
{"id":"hanging-knee-raise","name":"Hanging knee raises","category":"strength"},
{"id":"finger-hang","name":"Finger hangs","category":"strength"},
{"id":"single-arm-preacher-curl","name":"Single-arm preacher curls over a chair","category":"strength"},
{"id":"hammer-curl","name":"Hammer curls","category":"strength"},
{"id":"single-arm-shoulder-press","name":"Standing single-arm dumbbell shoulder press","category":"strength"},
{"id":"leaning-single-arm-lateral-raise","name":"Leaning single-arm lateral raises","category":"strength"},
{"id":"bent-over-rear-delt-fly","name":"Bent-over rear-delt flys","category":"strength"},
{"id":"lying-dumbbell-triceps-extension","name":"Lying dumbbell triceps extensions","category":"strength"},
{"id":"single-arm-triceps-extension","name":"Single-arm triceps extensions","category":"strength"},
{"id":"side-plank-hip-raise","name":"Side-plank hip raises","category":"strength"},
{"id":"deep-squat-hold","name":"Deep squat hold","category":"isometric"},
{"id":"ninety-ninety-hip-hold","name":"90/90 hip hold","category":"isometric"},
{"id":"bird-dog-hold","name":"Bird-dog hold","category":"isometric"},
{"id":"single-leg-balance","name":"Single-leg balance","category":"isometric"},
{"id":"prone-swimmer-iso","name":"Prone swimmer iso","category":"isometric"},
{"id":"daily-hang","name":"Daily hanging practice","category":"hang"}
{
"id": "pull-up",
"name": "Pull-ups",
"category": "strength",
"version": 1,
"equipment": [
"weighted-vest"
],
"measurement": "repetitions",
"protocols": [
"sets",
"emom"
]
},
{
"id": "ez-bar-bent-over-row",
"name": "EZ-bar bent-over rows",
"category": "strength",
"version": 1,
"equipment": [
"ez-curl-bar"
],
"measurement": "repetitions"
},
{
"id": "single-arm-dumbbell-row",
"name": "Single-arm dumbbell rows",
"category": "strength",
"version": 1,
"equipment": [
"dumbbells"
],
"measurement": "repetitions-per-side",
"dumbbellCount": 1
},
{
"id": "suitcase-carry",
"name": "Suitcase carries",
"category": "strength",
"version": 1,
"equipment": [
"dumbbells"
],
"measurement": "duration-per-side",
"dumbbellCount": 1
},
{
"id": "weighted-deep-push-up",
"name": "Weighted deep push-ups using dumbbells as handles",
"category": "strength",
"version": 1,
"equipment": [
"weighted-vest"
],
"measurement": "repetitions",
"supports": [
"Stable dumbbells used as handles; their weight is not lifted resistance."
]
},
{
"id": "dumbbell-floor-fly",
"name": "Dumbbell floor flys",
"category": "strength",
"version": 2,
"equipment": [
"dumbbells"
],
"measurement": "repetitions",
"dumbbellCount": 2,
"fixedDumbbellCount": 2
},
{
"id": "push-up-plus",
"name": "Push-up plus",
"category": "strength",
"version": 1,
"equipment": [
"weighted-vest"
],
"measurement": "repetitions"
},
{
"id": "feet-elevated-weighted-push-up",
"name": "Feet-elevated weighted push-ups",
"category": "strength",
"version": 1,
"equipment": [
"weighted-vest"
],
"measurement": "repetitions"
},
{
"id": "bulgarian-split-squat",
"name": "Bulgarian split squats",
"category": "strength",
"version": 1,
"equipment": [
"weighted-vest",
"dumbbells"
],
"measurement": "repetitions-per-side",
"dumbbellCount": 2
},
{
"id": "single-leg-romanian-deadlift",
"name": "Single-leg Romanian deadlifts",
"category": "strength",
"version": 1,
"equipment": [
"weighted-vest",
"dumbbells"
],
"measurement": "repetitions-per-side",
"dumbbellCount": 2
},
{
"id": "squat",
"name": "Squats",
"category": "strength",
"version": 1,
"equipment": [
"weighted-vest",
"dumbbells"
],
"measurement": "repetitions",
"dumbbellCount": 2
},
{
"id": "single-leg-calf-raise",
"name": "Single-leg calf raises",
"category": "strength",
"version": 1,
"equipment": [
"weighted-vest",
"dumbbells"
],
"measurement": "repetitions-per-side",
"dumbbellCount": 1
},
{
"id": "front-plank",
"name": "Front plank",
"category": "strength",
"version": 1,
"equipment": [
"weighted-vest"
],
"measurement": "duration"
},
{
"id": "chin-up",
"name": "Chin-ups",
"category": "strength",
"version": 1,
"equipment": [
"weighted-vest"
],
"measurement": "repetitions",
"protocols": [
"sets",
"emom"
]
},
{
"id": "hanging-knee-raise",
"name": "Hanging knee raises",
"category": "strength",
"version": 1,
"equipment": [
"bodyweight"
],
"measurement": "repetitions"
},
{
"id": "finger-hang",
"name": "Finger hangs",
"category": "strength",
"version": 1,
"equipment": [
"weighted-vest"
],
"measurement": "duration"
},
{
"id": "single-arm-preacher-curl",
"name": "Single-arm preacher curls over a chair",
"category": "strength",
"version": 1,
"equipment": [
"dumbbells"
],
"measurement": "repetitions-per-side",
"dumbbellCount": 1
},
{
"id": "hammer-curl",
"name": "Hammer curls",
"category": "strength",
"version": 1,
"equipment": [
"dumbbells"
],
"measurement": "repetitions",
"dumbbellCount": 2
},
{
"id": "single-arm-shoulder-press",
"name": "Standing single-arm dumbbell shoulder press",
"category": "strength",
"version": 1,
"equipment": [
"dumbbells"
],
"measurement": "repetitions-per-side",
"dumbbellCount": 1
},
{
"id": "leaning-single-arm-lateral-raise",
"name": "Leaning single-arm lateral raises",
"category": "strength",
"version": 1,
"equipment": [
"dumbbells"
],
"measurement": "repetitions-per-side",
"dumbbellCount": 1
},
{
"id": "bent-over-rear-delt-fly",
"name": "Bent-over rear-delt flys",
"category": "strength",
"version": 1,
"equipment": [
"dumbbells"
],
"measurement": "repetitions",
"dumbbellCount": 2
},
{
"id": "lying-dumbbell-triceps-extension",
"name": "Lying dumbbell triceps extensions",
"category": "strength",
"version": 1,
"equipment": [
"dumbbells"
],
"measurement": "repetitions",
"dumbbellCount": 2
},
{
"id": "single-arm-triceps-extension",
"name": "Single-arm triceps extensions",
"category": "strength",
"version": 1,
"equipment": [
"dumbbells"
],
"measurement": "repetitions-per-side",
"dumbbellCount": 1
},
{
"id": "side-plank-hip-raise",
"name": "Side-plank hip raises",
"category": "strength",
"version": 1,
"equipment": [
"weighted-vest"
],
"measurement": "repetitions-per-side"
},
{
"id": "deep-squat-hold",
"name": "Deep squat hold",
"category": "isometric",
"version": 1,
"equipment": [
"bodyweight"
],
"measurement": "duration"
},
{
"id": "ninety-ninety-hip-hold",
"name": "90/90 hip hold",
"category": "isometric",
"version": 1,
"equipment": [
"bodyweight"
],
"measurement": "duration-per-side"
},
{
"id": "bird-dog-hold",
"name": "Bird-dog hold",
"category": "isometric",
"version": 1,
"equipment": [
"bodyweight"
],
"measurement": "duration-per-side"
},
{
"id": "single-leg-balance",
"name": "Single-leg balance",
"category": "isometric",
"version": 1,
"equipment": [
"bodyweight"
],
"measurement": "duration-per-side"
},
{
"id": "prone-swimmer-iso",
"name": "Prone swimmer iso",
"category": "isometric",
"version": 1,
"equipment": [
"bodyweight"
],
"measurement": "duration"
},
{
"id": "daily-hang",
"name": "Daily hanging practice",
"category": "hang",
"version": 1,
"equipment": [
"bodyweight"
],
"measurement": "duration",
"protocols": [
"attempts"
]
}
]
+14 -10
View File
@@ -1,6 +1,6 @@
{
"id": "documented-baseline",
"version": 7,
"version": 8,
"source": "docs/WORKOUT_ROUTINE.md",
"days": {
"monday": {
@@ -63,7 +63,7 @@
"kind": "hanging-practice",
"goalDurationSec": 120,
"currentDurationSec": null,
"goalFormat": null,
"goalFormat": "continuous",
"attemptCount": null,
"breaks": null
},
@@ -250,7 +250,7 @@
"kind": "hanging-practice",
"goalDurationSec": 120,
"currentDurationSec": null,
"goalFormat": null,
"goalFormat": "continuous",
"attemptCount": null,
"breaks": null
},
@@ -348,7 +348,7 @@
}
},
"load": {
"bodyweightOnly": true
"vestKg": null
},
"notes": "Initially unweighted; focus on shoulder-blade protraction."
},
@@ -439,7 +439,7 @@
"kind": "hanging-practice",
"goalDurationSec": 120,
"currentDurationSec": null,
"goalFormat": null,
"goalFormat": "continuous",
"attemptCount": null,
"breaks": null
},
@@ -515,6 +515,7 @@
}
},
"load": {
"vestKg": null,
"dumbbellKgEach": null
},
"notes": "Use suitable dumbbell loading and controlled balance."
@@ -659,7 +660,7 @@
"kind": "hanging-practice",
"goalDurationSec": 120,
"currentDurationSec": null,
"goalFormat": null,
"goalFormat": "continuous",
"attemptCount": null,
"breaks": null
},
@@ -738,7 +739,7 @@
"kind": "hanging-practice",
"goalDurationSec": 120,
"currentDurationSec": null,
"goalFormat": null,
"goalFormat": "continuous",
"attemptCount": null,
"breaks": null
},
@@ -827,7 +828,10 @@
"max": 120
}
},
"notes": "Duration not specified; distinct from the daily afternoon hang."
"notes": "Duration not specified; distinct from the daily afternoon hang.",
"load": {
"vestKg": null
}
},
{
"order": 4,
@@ -938,7 +942,7 @@
"kind": "hanging-practice",
"goalDurationSec": 120,
"currentDurationSec": null,
"goalFormat": null,
"goalFormat": "continuous",
"attemptCount": null,
"breaks": null
},
@@ -1174,7 +1178,7 @@
"kind": "hanging-practice",
"goalDurationSec": 120,
"currentDurationSec": null,
"goalFormat": null,
"goalFormat": "continuous",
"attemptCount": null,
"breaks": null
},
+2 -2
View File
@@ -18,7 +18,7 @@ const range = (min, max = min) => ({ min, max })
describe('documented initial routine', () => {
it('is versioned, has one stable definition per used exercise, and retains every day and exercise order', () => {
expect(initialRoutine.version).toBe(7)
expect(initialRoutine.version).toBe(8)
expect(initialRoutine.source).toBe('docs/WORKOUT_ROUTINE.md')
expect(Object.keys(initialRoutine.days)).toEqual(weekdays)
@@ -91,7 +91,7 @@ describe('documented initial routine', () => {
expect(afternoon).not.toHaveProperty('restBetweenHoldsSec')
expect(afternoon.targetsAreMandatory).toBe(false)
expect(exercise(day, 'afternoon', 'daily-hang')).toMatchObject({
prescription: { goalDurationSec: 120, currentDurationSec: null, attemptCount: null, breaks: null, goalFormat: null },
prescription: { goalDurationSec: 120, currentDurationSec: null, attemptCount: null, breaks: null, goalFormat: 'continuous' },
})
expect(exercise(day, 'afternoon', 'daily-hang')).not.toHaveProperty('load')
}
+1 -1
View File
@@ -6,7 +6,7 @@ function memoryIndexedDB() {
const stores = new Set()
const db = {
objectStoreNames: { contains: (name) => stores.has(name) },
createObjectStore: (name) => stores.add(name),
createObjectStore: (name) => { stores.add(name); return { createIndex() {} } },
close() {},
transaction() {
const transaction = {
+9 -2
View File
@@ -1,5 +1,5 @@
const DATABASE_NAME = 'workout-tracker'
const DATABASE_VERSION = 2
const DATABASE_VERSION = 3
export function openLocalDatabase() {
return new Promise((resolve, reject) => {
@@ -11,13 +11,20 @@ export function openLocalDatabase() {
const request = globalThis.indexedDB.open(DATABASE_NAME, DATABASE_VERSION)
let blocked = false
request.onupgradeneeded = () => {
if (!request.result.objectStoreNames.contains('performanceEntries')) {
const store = request.result.createObjectStore('performanceEntries')
store.createIndex('exercisePeriodFormat', ['exerciseId', 'period', 'format'])
}
for (const store of ['routineOverrides', 'strengthEntries']) {
if (!request.result.objectStoreNames.contains(store)) request.result.createObjectStore(store)
}
}
request.onsuccess = () => {
if (blocked) request.result.close()
else resolve(request.result)
else {
request.result.onversionchange = () => request.result.close()
resolve(request.result)
}
}
request.onerror = () => reject(new Error('Could not open local workout storage.'))
request.onblocked = () => { blocked = true; reject(new Error('Local workout storage is blocked by another tab.')) }
+91
View File
@@ -0,0 +1,91 @@
export const equipmentLabels = { bodyweight: 'Bodyweight only', 'weighted-vest': 'Weighted vest', dumbbells: 'Dumbbell(s)', 'ez-curl-bar': 'EZ curl bar', 'straight-bar': 'Straight bar' }
export const measurements = {
repetitions: [{ key: 'reps', label: 'Reps', whole: true }],
'repetitions-per-side': [{ key: 'leftReps', label: 'Left reps', whole: true }, { key: 'rightReps', label: 'Right reps', whole: true }],
duration: [{ key: 'seconds', label: 'Seconds' }],
'duration-per-side': [{ key: 'leftSeconds', label: 'Left seconds' }, { key: 'rightSeconds', label: 'Right seconds' }],
distance: [{ key: 'metres', label: 'Metres' }],
}
const loadDefinitions = {
'weighted-vest': { key: 'vestKg', label: 'Vest (kg)' },
dumbbells: { key: 'dumbbellKgEach', label: 'Dumbbell (kg each)' },
'ez-curl-bar': { key: 'ezBarTotalKg', label: 'EZ bar total (kg)' },
'straight-bar': { key: 'straightBarTotalKg', label: 'Straight bar total (kg)' },
}
export function validDate(value) {
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false
const date = new Date(`${value}T12:00:00Z`)
return Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value
}
export const copy = (value) => JSON.parse(JSON.stringify(value))
export const loadColumns = (definition) => definition.equipment.filter((equipment) => loadDefinitions[equipment]).flatMap((equipment) => equipment === 'dumbbells'
? [loadDefinitions[equipment], { key: 'dumbbellCount', label: 'Dumbbells used', whole: true, min: definition.fixedDumbbellCount ?? 1, max: definition.fixedDumbbellCount ?? 2, hidden: true }]
: [loadDefinitions[equipment]])
export const measurementColumns = (definition) => measurements[definition.measurement] ?? []
export const formatFor = (definition, prescription) => definition.protocols?.includes('attempts') ? 'attempts' : prescription.kind === 'emom' ? 'emom' : 'sets'
export function signature(definition, format) {
return JSON.stringify([definition.id, definition.measurement, [...definition.equipment].sort(), definition.fixedDumbbellCount ?? null, format])
}
export function blankRow(definition, prior) {
return { values: Object.fromEntries(measurementColumns(definition).map(({ key }) => [key, null])), load: Object.fromEntries(loadColumns(definition).map(({ key }) => [key, key === 'dumbbellCount' ? definition.fixedDumbbellCount ?? prior?.load[key] ?? definition.dumbbellCount : prior?.load[key] ?? null])), completed: false }
}
export function newPerformance(date, period, definition, prescription, format = formatFor(definition, prescription)) {
return { schemaVersion: 1, date, period, exerciseId: definition.id, format, definition: copy(definition), prescription: copy(prescription), rows: Array.from({ length: format === 'emom' ? prescription.rounds : 1 }, () => blankRow(definition)) }
}
function validDefinition(definition) {
return definition && typeof definition.id === 'string' && typeof definition.name === 'string' && Number.isSafeInteger(definition.version) && definition.version > 0
&& Object.hasOwn(measurements, definition.measurement) && Array.isArray(definition.equipment) && definition.equipment.length > 0
&& new Set(definition.equipment).size === definition.equipment.length && definition.equipment.every((item) => Object.hasOwn(equipmentLabels, item))
&& (!definition.equipment.includes('bodyweight') || definition.equipment.length === 1)
&& (!definition.equipment.includes('dumbbells') || [1, 2].includes(definition.dumbbellCount))
&& (definition.fixedDumbbellCount == null || (definition.equipment.includes('dumbbells') && [1, 2].includes(definition.fixedDumbbellCount) && definition.fixedDumbbellCount === definition.dumbbellCount))
&& (definition.protocols == null || (Array.isArray(definition.protocols) && definition.protocols.length > 0 && definition.protocols.every((format) => ['sets', 'emom', 'attempts'].includes(format))))
}
export function performanceError(record) {
if (!record || record.schemaVersion !== 1 || !validDate(record.date) || !['morning', 'afternoon'].includes(record.period)
|| !validDefinition(record.definition) || record.exerciseId !== record.definition.id || !['sets', 'emom', 'attempts'].includes(record.format)
|| !record.prescription || typeof record.prescription.kind !== 'string' || !Array.isArray(record.rows) || record.rows.length === 0 || record.rows.length > 1000) return 'Invalid performance record.'
if (!(record.definition.protocols ?? ['sets']).includes(record.format)) return 'Unsupported exercise format.'
if (record.format === 'emom' && (!record.definition.protocols?.includes('emom') || !Number.isSafeInteger(record.prescription.rounds) || record.rows.length !== record.prescription.rounds)) return 'Invalid EMOM minutes.'
if (record.format === 'attempts' && !record.definition.protocols?.includes('attempts')) return 'Invalid attempts.'
for (const [index, row] of record.rows.entries()) {
const error = rowError(row, index, record.definition)
if (error) return error
}
return null
}
function rowError(row, index, definition) {
if (!row || typeof row.completed !== 'boolean') return `Row ${index + 1}: invalid completion.`
const groups = [['values', measurementColumns(definition)], ['load', loadColumns(definition)]]
for (const [group, columns] of groups) {
if (!row[group] || typeof row[group] !== 'object' || Array.isArray(row[group]) || Object.keys(row[group]).length !== columns.length || Object.keys(row[group]).some((key) => !columns.some((column) => column.key === key))) return `Row ${index + 1}: invalid fields.`
for (const { key, label, whole, min = 0, max = Number.MAX_VALUE } of columns) {
const value = row[group][key]
if (value === null && !row.completed) continue
if (typeof value !== 'number' || !Number.isFinite(value) || value < min || value > max || (whole && !Number.isSafeInteger(value))) return `Row ${index + 1}: enter ${label.toLowerCase()}${row.completed ? ' before marking complete' : ' as a valid number'}.`
}
}
return null
}
export function preparePerformanceForSave(record) {
return { ...record, rows: record.rows.map((row, index) => {
const load = { ...row.load }
if (Object.hasOwn(load, 'dumbbellCount') && load.dumbbellCount == null) load.dumbbellCount = record.definition.fixedDumbbellCount ?? record.definition.dumbbellCount
const candidate = { ...row, load, completed: true }
// Missing values remain draft; invalid entered values still fail performanceError.
return { ...candidate, completed: !rowError(candidate, index, record.definition) }
}) }
}
export function externalKg(row) {
const l = row.load
const weights = Object.entries(l).filter(([key]) => key !== 'dumbbellCount')
if (weights.some(([, value]) => value == null) || ('dumbbellKgEach' in l && l.dumbbellCount == null)) return null
return weights.reduce((sum, [key, value]) => sum + value * (key === 'dumbbellKgEach' ? l.dumbbellCount : 1), 0)
}
export function performanceTotals(record) {
const completed = record.rows.filter((row) => row.completed && !rowError(row, 0, record.definition))
const durations = completed.flatMap(({ values }) => Object.entries(values).filter(([key]) => /seconds/i.test(key)).map(([, value]) => value))
return { completed: completed.length, reps: completed.reduce((sum, { values }) => sum + Object.entries(values).filter(([key]) => /reps/i.test(key)).reduce((total, [, value]) => total + value, 0), 0), longest: Math.max(0, ...durations), seconds: durations.reduce((sum, value) => sum + value, 0), volume: completed.reduce((sum, row) => sum + Object.entries(row.values).filter(([key]) => /reps/i.test(key)).reduce((total, [, value]) => total + value, 0) * (externalKg(row) ?? 0), 0) }
}
+101
View File
@@ -0,0 +1,101 @@
import { describe, expect, it } from 'vitest'
import { exerciseDefinitions, initialRoutine } from './data/index.js'
import { blankRow, equipmentLabels, externalKg, loadColumns, measurementColumns, newPerformance, performanceError, performanceTotals, preparePerformanceForSave } from './performanceModel.js'
const def = (id) => exerciseDefinitions.find((d) => d.id === id)
const prescription = (id) => Object.values(initialRoutine.days).flatMap((day) => [...day.morning.exercises, ...day.afternoon.exercises]).find((e) => e.exerciseId === id).prescription
const make = (id) => newPerformance('2026-11-03', 'morning', def(id), prescription(id))
const expectedEquipment = {
'pull-up': ['weighted-vest'], 'ez-bar-bent-over-row': ['ez-curl-bar'], 'single-arm-dumbbell-row': ['dumbbells'], 'suitcase-carry': ['dumbbells'],
'weighted-deep-push-up': ['weighted-vest'], 'dumbbell-floor-fly': ['dumbbells'], 'push-up-plus': ['weighted-vest'], 'feet-elevated-weighted-push-up': ['weighted-vest'],
'bulgarian-split-squat': ['weighted-vest', 'dumbbells'], 'single-leg-romanian-deadlift': ['weighted-vest', 'dumbbells'], squat: ['weighted-vest', 'dumbbells'], 'single-leg-calf-raise': ['weighted-vest', 'dumbbells'], 'front-plank': ['weighted-vest'],
'chin-up': ['weighted-vest'], 'hanging-knee-raise': ['bodyweight'], 'finger-hang': ['weighted-vest'], 'single-arm-preacher-curl': ['dumbbells'], 'hammer-curl': ['dumbbells'],
'single-arm-shoulder-press': ['dumbbells'], 'leaning-single-arm-lateral-raise': ['dumbbells'], 'bent-over-rear-delt-fly': ['dumbbells'], 'lying-dumbbell-triceps-extension': ['dumbbells'], 'single-arm-triceps-extension': ['dumbbells'], 'side-plank-hip-raise': ['weighted-vest'],
'deep-squat-hold': ['bodyweight'], 'ninety-ninety-hip-hold': ['bodyweight'], 'bird-dog-hold': ['bodyweight'], 'single-leg-balance': ['bodyweight'], 'prone-swimmer-iso': ['bodyweight'], 'daily-hang': ['bodyweight'],
}
describe('metadata and actual performance', () => {
it.each(exerciseDefinitions)('audits equipment for $id without a numeric load in definitions', (d) => {
expect(d.equipment).toEqual(expectedEquipment[d.id])
expect(d.equipment.every((e) => e in equipmentLabels)).toBe(true)
expect(measurementColumns(d).length).toBeGreaterThan(0)
expect(d).not.toHaveProperty('load')
expect(performanceError(make(d.id))).toBeNull()
if (d.equipment[0] === 'bodyweight') expect(loadColumns(d)).toEqual([])
})
it('supports straight-bar totals and distance without adding seed exercises', () => {
const d = { ...def('ez-bar-bent-over-row'), equipment: ['straight-bar'], measurement: 'distance' }
expect(loadColumns(d).map((c) => c.key)).toEqual(['straightBarTotalKg'])
expect(measurementColumns(d).map((c) => c.key)).toEqual(['metres'])
expect(externalKg({ load: { straightBarTotalKg: 25 } })).toBe(25)
})
it('requires measurements/load for completion, permits drafts, and rejects invalid fields', () => {
const entry = make('front-plank')
entry.rows[0].completed = true
expect(performanceError(entry)).toMatch(/seconds/)
entry.rows[0].values.seconds = 45
expect(performanceError(entry)).toMatch(/vest/)
entry.rows[0].load.vestKg = 0
expect(performanceError(entry)).toBeNull()
entry.rows[0].values.reps = 2
expect(performanceError(entry)).toMatch(/invalid fields/)
})
it('sums variable per-minute resistance and keeps target and actuals independent', () => {
const entry = make('pull-up')
expect(entry.rows).toHaveLength(10)
expect(entry.rows[0].load.vestKg).toBeNull()
entry.rows[0] = { values: { reps: 4 }, load: { vestKg: 6 }, completed: true }
entry.rows[1] = { values: { reps: 3 }, load: { vestKg: 10 }, completed: true }
expect(performanceTotals(entry)).toMatchObject({ reps: 7, completed: 2, volume: 54 })
})
it('records independent side values and dumbbell count without counting handles', () => {
const entry = make('bulgarian-split-squat')
entry.rows[0] = { values: { leftReps: 10, rightReps: 8 }, load: { vestKg: 5, dumbbellKgEach: 12, dumbbellCount: 2 }, completed: true }
expect(externalKg(entry.rows[0])).toBe(29)
expect(performanceTotals(entry).volume).toBe(522)
expect(loadColumns(def('weighted-deep-push-up')).map((c) => c.key)).toEqual(['vestKg'])
const next = blankRow(entry.definition, entry.rows[0])
expect(next.values).toEqual({ leftReps: null, rightReps: null })
expect(next.load).toEqual(entry.rows[0].load)
expect(next.completed).toBe(false)
})
it('separates cumulative hanging time from continuous success and incomplete drafts', () => {
const entry = make('daily-hang')
entry.rows = [60, 75, 150].map((seconds, i) => ({ values: { seconds }, load: {}, completed: i < 2 }))
expect(performanceTotals(entry)).toMatchObject({ longest: 75, seconds: 135, completed: 2 })
})
})
it('rejects impossible dates and excludes invalid completed drafts from achieved totals', () => {
const record = make('daily-hang')
record.rows[0].completed = true
expect(performanceTotals(record)).toMatchObject({ completed: 0, longest: 0, seconds: 0 })
record.date = '2026-02-30'
expect(performanceError(record)).toMatch(/Invalid performance/)
})
it('rejects unsupported exercise formats and malformed protocol metadata', () => {
const record = make('daily-hang')
record.format = 'sets'
expect(performanceError(record)).toMatch(/Unsupported exercise format/)
record.definition.protocols = 'attempts'
expect(performanceError(record)).toMatch(/Invalid performance/)
})
it('fixes floor-fly count at two and calculates paired resistance from kg each', () => {
const record = make('dumbbell-floor-fly')
record.rows[0] = { values: { reps: 12 }, load: { dumbbellKgEach: 8, dumbbellCount: 2 }, completed: true }
expect(performanceError(record)).toBeNull()
expect(performanceTotals(record).volume).toBe(192)
record.rows[0].load.dumbbellCount = 1
expect(performanceError(record)).toMatch(/dumbbells used/)
})
it('derives completion on explicit save while retaining drafts and rejecting invalid actuals', () => {
const original = make('front-plank')
original.rows[0] = { values: { seconds: 0 }, load: { vestKg: 0 }, completed: false }
let prepared = preparePerformanceForSave(original)
expect(prepared.rows[0].completed).toBe(true)
expect(original.rows[0].completed).toBe(false)
original.rows[0].values.seconds = null
prepared = preparePerformanceForSave(original)
expect(prepared.rows[0].completed).toBe(false)
expect(performanceError(prepared)).toBeNull()
original.rows[0].load.vestKg = -1
expect(performanceError(preparePerformanceForSave(original))).toMatch(/vest/)
})
+32
View File
@@ -0,0 +1,32 @@
import { openLocalDatabase } from './localDatabase.js'
import { performanceError, signature } from './performanceModel.js'
export const performanceKey = (date, period, exerciseId) => `${date}:${period}:${exerciseId}`
async function transaction(mode, action) {
const db = await openLocalDatabase()
return new Promise((resolve, reject) => {
const tx = db.transaction('performanceEntries', mode)
let value
try {
const request = action(tx.objectStore('performanceEntries'))
if (request) request.onsuccess = () => { value = request.result }
} catch { tx.abort() }
tx.oncomplete = () => { db.close(); resolve(value ?? null) }
tx.onerror = tx.onabort = () => { db.close(); reject(new Error('Could not access detailed performance storage. Your changes were not saved.')) }
})
}
export async function readPerformance(date, period, exerciseId) {
const record = await transaction('readonly', (store) => store.get(performanceKey(date, period, exerciseId)))
if (record && performanceError(record)) throw new Error('The saved performance record is invalid or unsupported.')
return record
}
export async function writePerformance(record) {
const error = performanceError(record)
if (error) throw new Error(error)
await transaction('readwrite', (store) => store.put(record, performanceKey(record.date, record.period, record.exerciseId)))
}
export async function previousPerformance(date, period, definition, format) {
const records = await transaction('readonly', (store) => store.index('exercisePeriodFormat').getAll([definition.id, period, format]))
return (records ?? []).filter((record) => record.date < date && !performanceError(record) && signature(record.definition, record.format) === signature(definition, format) && record.rows.some((row) => row.completed))
.sort((a, b) => b.date.localeCompare(a.date))[0] ?? null
}
+125
View File
@@ -0,0 +1,125 @@
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { IDBFactory } from 'fake-indexeddb'
import { readPerformance, writePerformance, previousPerformance } from './performanceStorage.js'
import { exportBackup, importBackup, parseBackup } from './backupStorage.js'
import { newPerformance } from './performanceModel.js'
import { exerciseDefinitions } from './data/index.js'
import { readStrengthEntry, writeStrengthEntry } from './strengthStorage.js'
import { readDailyHangGoal, writeDailyHangGoal } from './hangGoalStorage.js'
import { openLocalDatabase } from './localDatabase.js'
const definition = exerciseDefinitions.find((d) => d.id === 'front-plank')
const prescription = { kind: 'timed-sets', sets: { min: 3, max: 3 }, durationSec: { min: 30, max: 60 } }
const entry = (date = '2026-11-03') => newPerformance(date, 'morning', definition, prescription)
const completedEntry = (date) => {
const record = entry(date)
record.rows[0] = { values: { seconds: 45 }, load: { vestKg: 8 }, completed: true }
return record
}
beforeEach(() => vi.stubGlobal('indexedDB', new IDBFactory()))
afterEach(() => vi.unstubAllGlobals())
function seedDatabase(version) {
return new Promise((resolve, reject) => {
const request = indexedDB.open('workout-tracker', version)
request.onupgradeneeded = () => {
request.result.createObjectStore('routineOverrides').put(180, 'dailyHangGoalSec')
if (version === 2) request.result.createObjectStore('strengthEntries').put({ kind: 'emom', totalReps: 36, externalKg: 6 }, '2026-10-27:pull-up')
}
request.onsuccess = () => { request.result.close(); resolve() }
request.onerror = () => reject(request.error)
})
}
it.each([1, 2])('upgrades v%i additively and preserves existing data verbatim', async (version) => {
await seedDatabase(version)
const db = await openLocalDatabase()
expect(db.version).toBe(3)
expect([...db.objectStoreNames]).toEqual(['performanceEntries', 'routineOverrides', 'strengthEntries'])
expect(db.transaction('performanceEntries').objectStore('performanceEntries').indexNames.contains('exercisePeriodFormat')).toBe(true)
db.close()
expect(await readDailyHangGoal()).toBe(180)
if (version === 2) expect(await readStrengthEntry('2026-10-27', 'pull-up')).toEqual({ kind: 'emom', totalReps: 36, externalKg: 6 })
await writePerformance(entry())
expect(await readPerformance('2026-11-03', 'morning', 'front-plank')).toEqual(entry())
expect(await readPerformance('2026-11-04', 'morning', 'front-plank')).toBeNull()
expect(await readPerformance('2026-11-03', 'afternoon', 'front-plank')).toBeNull()
})
it('keeps saved context and actuals after source definitions/prescriptions change', async () => {
const record = completedEntry('2026-11-03')
const original = structuredClone(record)
await writePerformance(record)
record.definition.equipment = ['bodyweight']; record.prescription.durationSec.min = 999; record.rows[0].load.vestKg = 99
expect(await readPerformance(original.date, original.period, original.exerciseId)).toEqual(original)
})
it('suggests only an earlier completed session with matching exercise, period, format and equipment', async () => {
await writePerformance(completedEntry('2026-10-29'))
await writePerformance(entry('2026-11-02')) // incomplete draft cannot become a suggestion
await writePerformance(completedEntry('2026-11-10')) // future excluded
const changed = completedEntry('2026-11-01'); changed.definition.equipment = ['bodyweight']; changed.rows[0].load = {}
await writePerformance(changed)
const prior = await previousPerformance('2026-11-03', 'morning', definition, 'sets')
expect(prior.date).toBe('2026-10-29')
expect(await previousPerformance('2026-11-03', 'afternoon', definition, 'sets')).toBeNull()
})
it('round trips detailed drafts, legacy total/component/weight-only records and goal overrides', async () => {
await writeDailyHangGoal(180)
await writeStrengthEntry('2026-10-27', 'pull-up', { kind: 'emom', totalReps: 36, externalKg: 6 })
await writeStrengthEntry('2026-10-29', 'squat', { kind: 'sets', sets: [{ reps: 10, externalKg: 34, load: { vestKg: 10, dumbbellKgEach: 12 } }] })
await writeStrengthEntry('2026-11-03', 'suitcase-carry', { kind: 'load-sets', sets: [{ externalKg: 20, load: { dumbbellKg: 20 } }] })
await writePerformance(completedEntry('2026-11-03'))
const backup = await exportBackup()
vi.stubGlobal('indexedDB', new IDBFactory())
await importBackup(backup)
expect(await exportBackup()).toBe(backup)
expect(await readDailyHangGoal()).toBe(180)
expect(await readPerformance('2026-11-03', 'morning', 'front-plank')).toEqual(completedEntry('2026-11-03'))
})
it('imports a legacy v1 adapter envelope without inventing detailed rows', async () => {
await importBackup({ format: 'workout-tracker', version: 1, stores: { routineOverrides: [{ key: 'dailyHangGoalSec', value: 150 }], strengthEntries: [{ key: '2026-10-27:pull-up', value: { kind: 'emom', totalReps: 36, externalKg: 6 } }] } })
expect(await readDailyHangGoal()).toBe(150)
expect(await readPerformance('2026-10-27', 'morning', 'pull-up')).toBeNull()
expect(await readStrengthEntry('2026-10-27', 'pull-up')).toMatchObject({ totalReps: 36 })
})
it('rolls back the whole import on a duplicate, and rejects invalid data before mutation', async () => {
await writeDailyHangGoal(180)
const before = await exportBackup()
const incoming = parseBackup(before)
// First add succeeds; the following duplicate must roll it back in the same transaction.
incoming.stores.routineOverrides.unshift({ key: 'futurePlanEdit', value: { preserved: true } })
await expect(importBackup(incoming)).rejects.toThrow(/unchanged/)
expect(await exportBackup()).toBe(before)
incoming.version = 999
await expect(importBackup(incoming, { replace: true })).rejects.toThrow(/Unsupported/)
expect(await exportBackup()).toBe(before)
const invalid = parseBackup(before); invalid.stores.performanceEntries.push({ key: 'bad', value: { schemaVersion: 1 } })
await expect(importBackup(invalid, { replace: true })).rejects.toThrow(/Invalid detailed/)
expect(await exportBackup()).toBe(before)
})
it('supports explicit replacement atomically and preserves unknown legacy exercise IDs', async () => {
await writeStrengthEntry('2026-11-02', 'retired-exercise', { kind: 'sets', sets: [{ reps: 8, externalKg: 12 }] })
const backup = await exportBackup()
await writeDailyHangGoal(300)
await importBackup(backup, { replace: true })
expect(await readDailyHangGoal()).toBeNull()
expect(await readStrengthEntry('2026-11-02', 'retired-exercise')).toEqual({ kind: 'sets', sets: [{ reps: 8, externalKg: 12 }] })
})
it('rejects unsupported or malformed files without silently accepting incomplete backups', () => {
expect(() => parseBackup('no json')).toThrow(/Invalid backup JSON/)
expect(() => parseBackup({ format: 'workout-tracker', version: 2, stores: {} })).toThrow(/Missing/)
})
it('rejects failed detailed writes without modifying a saved record', async () => {
const original = completedEntry('2026-11-03')
await writePerformance(original)
const invalid = structuredClone(original); invalid.rows[0].load.vestKg = -5
await expect(writePerformance(invalid)).rejects.toThrow(/vest/)
expect(await readPerformance(original.date, original.period, original.exerciseId)).toEqual(original)
})
it('reports blocked v2 upgrade without overwriting existing data', async () => {
await seedDatabase(2)
const old = await new Promise((resolve) => { const request = indexedDB.open('workout-tracker', 2); request.onsuccess = () => resolve(request.result) })
const pending = openLocalDatabase()
await expect(pending).rejects.toThrow(/blocked/)
old.close()
// Let the pending upgrade finish and close its connection after the blocker exits.
const db = await openLocalDatabase(); db.close()
expect(await readDailyHangGoal()).toBe(180)
expect(await readStrengthEntry('2026-10-27', 'pull-up')).toMatchObject({ totalReps: 36, externalKg: 6 })
})
+1 -1
View File
@@ -23,7 +23,7 @@ function validRecordedWeight(record) {
return total != null && Math.abs(total - record.externalKg) < 1e-9
}
function validEntry(entry) {
export function validEntry(entry) {
if (entry?.kind === 'emom') return validReps(entry.totalReps) && validRecordedWeight(entry)
if (entry?.kind === 'load-sets') return Array.isArray(entry.sets) && entry.sets.length > 0 && entry.sets.every((row) => row && validRecordedWeight(row))
if (entry?.kind === 'sets') return Array.isArray(entry.sets) && entry.sets.length > 0 && entry.sets.every((row) => row && validReps(row.reps) && validRecordedWeight(row))
+1 -1
View File
@@ -7,7 +7,7 @@ function existingV1Database() {
let version = 1
const db = {
objectStoreNames: { contains: (name) => stores.has(name) },
createObjectStore(name) { stores.set(name, new Map()) },
createObjectStore(name) { stores.set(name, new Map()); return { createIndex() {} } },
close() {},
transaction(name) {
const transaction = {
+35
View File
@@ -106,3 +106,38 @@ h1 { margin: .25rem 0 .55rem; font-size: clamp(2.2rem, 4vw, 3.25rem); line-heigh
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { scroll-behavior: auto !important; animation-duration: .01ms !important; transition-duration: .01ms !important; }
}
/* TASK-015: scoped logging layout; existing visual language retained. */
.performance-entry { margin-top: .8rem; padding-top: .65rem; border-top: 1px solid #e2e8e0; }
.performance-toolbar, .performance-actions { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; }
.performance-toolbar { margin-bottom: .5rem; }
.performance-toolbar strong { color: #315847; font-size: .88rem; }
.performance-rows { display: grid; gap: .45rem; }
.performance-row, .performance-head { display: grid; grid-template-columns: 4.8rem repeat(var(--fields), minmax(0, 1fr)); align-items: end; gap: .5rem; }
.performance-head { color: #52665a; font-size: .76rem; font-weight: 650; margin-bottom: .25rem; }
.performance-row { padding: .45rem; border: 1px solid #e2e8e0; border-radius: 8px; }
.performance-row.is-complete { border-color: #6c946c; background: #f0f5ec; }
.performance-row label { min-width: 0; font-size: .8rem; color: #52665a; }
.performance-row input[type=number] { width: 100%; min-width: 0; min-height: 40px; padding: .3rem .4rem; border: 1px solid #b6c7b8; border-radius: 6px; color: #254838; }
.performance-row .field-label { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
.row-number { align-self: center; font-size: .8rem; color: #52665a; }
.performance-row .remove-row { grid-column: 1 / -1; justify-self: end; padding-block: .15rem; }
.performance-actions { margin-top: .6rem; }
.performance-status, .performance-summary { margin: .4rem 0 0; color: #52665a; font-size: .82rem; }
.exercise-details, .legacy-entry { margin-top: .6rem; font-size: .85rem; overflow-wrap: anywhere; }
.exercise-details p, .legacy-entry p { margin: .5rem 0; }
.exercise-details summary, .legacy-entry summary { cursor: pointer; color: #315847; padding-block: .4rem; }
.performance-entry button:focus-visible, .performance-entry input:focus-visible, .exercise-details summary:focus-visible, .legacy-entry summary:focus-visible { outline: 3px solid #9fc45c; outline-offset: 2px; }
@media (max-width: 991px) {
.performance-head { display: none; }
.performance-row { grid-template-columns: repeat(2, minmax(0, 1fr)); align-items: end; }
.performance-row .field-label { position: static; width: auto; height: auto; clip-path: none; display: block; }
.row-number { grid-column: 1 / -1; }
}
@media (max-width: 575px) {
.exercise-card { gap: .5rem; padding: .75rem .6rem; }
.exercise-number { flex-basis: 24px; height: 24px; }
.performance-row { grid-template-columns: minmax(0, 1fr); }
.performance-actions > button { min-height: 44px; }
.performance-actions { align-items: stretch; }
}