Complete TASK-017 simplified EMOM and per-side entry
This commit is contained in:
@@ -3,3 +3,6 @@ dist/
|
|||||||
coverage/
|
coverage/
|
||||||
.vite/
|
.vite/
|
||||||
*.local
|
*.local
|
||||||
|
|
||||||
|
# Disposable Roborto task snapshots
|
||||||
|
.test-worktrees/
|
||||||
|
|||||||
Executable
+28
@@ -0,0 +1,28 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
case "${1:-}" in
|
||||||
|
validate)
|
||||||
|
command -v node >/dev/null
|
||||||
|
node -e 'const [a,b]=process.versions.node.split(".").map(Number); if(a<20 || (a===20 && b<19)) process.exit(1)'
|
||||||
|
command -v python3 >/dev/null
|
||||||
|
[[ -f "$ROBORTO_PROJECT_ROOT/node_modules/vite/bin/vite.js" ]]
|
||||||
|
;;
|
||||||
|
prepare)
|
||||||
|
python3 "$ROBORTO_PROJECT_ROOT/scripts/testtask_snapshot.py"
|
||||||
|
;;
|
||||||
|
start-backend)
|
||||||
|
# Frontend-only app; keep the runner's backend lifecycle slot alive.
|
||||||
|
exec tail -f /dev/null
|
||||||
|
;;
|
||||||
|
start-frontend)
|
||||||
|
cd "$ROBORTO_WORKTREE"
|
||||||
|
exec node node_modules/vite/bin/vite.js --host 127.0.0.1 --port 5187 --strictPort
|
||||||
|
;;
|
||||||
|
credentials)
|
||||||
|
echo 'Local app; no login. Snapshot storage is isolated by origin/profile. Use Tuesday or Saturday Morning to test EMOM.'
|
||||||
|
;;
|
||||||
|
cleanup)
|
||||||
|
# Runner owns its processes and disposable browser profile. Retain snapshot evidence.
|
||||||
|
;;
|
||||||
|
*) echo 'Unknown testtask hook operation' >&2; exit 2 ;;
|
||||||
|
esac
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
ROBORTO_PROJECT_SLUG="exercise-tracker"
|
||||||
|
ROBORTO_TASK_ID_PATTERN='^[0-9]{3}$'
|
||||||
|
ROBORTO_WORKTREE="${ROBORTO_PROJECT_ROOT}/.test-worktrees/task-${ROBORTO_TASK_ID}"
|
||||||
|
ROBORTO_HOOK="${ROBORTO_PROJECT_ROOT}/.roborto/testtask-hook"
|
||||||
|
ROBORTO_BROWSER_URL="http://127.0.0.1:5187/"
|
||||||
|
ROBORTO_READY_PORTS=(5187)
|
||||||
|
ROBORTO_READY_LABELS=(Web)
|
||||||
@@ -51,3 +51,10 @@ The project owner is Captain. Use a restrained chief-engineer/bridge voice while
|
|||||||
Update durable documents when work makes them stale. Refresh `HANDOFF.md` rather than appending chat history.
|
Update durable documents when work makes them stale. Refresh `HANDOFF.md` rather than appending chat history.
|
||||||
|
|
||||||
Do not commit, push, switch branches, merge, rebase, reset, deploy, or expose secrets without explicit user instruction. Do not perform destructive operations without authority. Captain retains merge and release authority unless an explicit repository rule delegates it.
|
Do not commit, push, switch branches, merge, rebase, reset, deploy, or expose secrets without explicit user instruction. Do not perform destructive operations without authority. Captain retains merge and release authority unless an explicit repository rule delegates it.
|
||||||
|
|
||||||
|
|
||||||
|
## Manual testing
|
||||||
|
|
||||||
|
**Captain runs `testtask`. Agents must not launch or restart it, open its browser windows, or stop Captain testing sessions unless explicitly instructed.** Agents run automated checks and provide the test command/handoff; wait for Captain to run the manual-test workflow. This explicit instruction supersedes any skill guidance to launch testtask automatically.
|
||||||
|
|
||||||
|
Use `PATH=/home/rob/.nvm/versions/node/v24.21.0/bin:$PATH scripts/testtask.sh 017` for TASK-017 (replace task ID for later tasks). Requires installed `roborto-testtask`, Python 3, Node >=20.19, installed node_modules, Firefox and a graphical display. The adapter copies an allowlisted, hash-verified source snapshot to `.test-worktrees/task-###`, including uncommitted/untracked task files and excluding secrets/local data. It shares node_modules and serves only loopback port 5187 with an isolated browser profile. Do not edit snapshots. Refresh refuses changed/unowned snapshots rather than overwriting their work. Ctrl-C stops only runner-owned processes and removes its disposable profile; snapshot evidence is retained.
|
||||||
|
|||||||
+15
-30
@@ -1,46 +1,31 @@
|
|||||||
# Exercise Tracker current state
|
# Exercise Tracker current state
|
||||||
|
|
||||||
- Last updated: 2026-11-04
|
- Last updated: 2026-11-07
|
||||||
- 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-017: Complete following Captain's explicit acceptance and commit/local codex merge authorization on 2026-11-07.
|
||||||
- TASK-015 integration base: `669bfc3`; Captain authorized committing the accepted task and fast-forward merging it to local `codex` on 2026-11-04.
|
- Source worktree: `/home/rob/projects/exercise-tracker`; task branch `task/017-emom-totals`, integration branch `codex`, base `9c0e820`. Use Git to verify resulting refs/HEAD after integration.
|
||||||
|
|
||||||
Code/configuration take precedence over this summary.
|
Code/configuration take precedence over this summary.
|
||||||
|
|
||||||
## Application status
|
## Application
|
||||||
|
|
||||||
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.
|
React/Vite/React-Bootstrap local workout app, seed v8 with 30 exercise definitions. Actual-date and Morning/Afternoon navigation, persistent wall clock, untimed recording, continuous daily-hang goal and attempts, equipment-specific load controls, partial drafts, explicit Save completion and compatible previous-session suggestions remain.
|
||||||
|
|
||||||
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.
|
TASK-017 replaces normal EMOM minute tables with exactly Weight (kg) and Total reps; no minute/set switch. New `emom-total` records retain one reps/vestKg/completion row and snapshots under a separate `:emom-total` key. Older aggregate/minute records remain untouched in collapsed Earlier records with original editors. Never sum coexisting representations; future history must use the current aggregate where present.
|
||||||
|
|
||||||
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.
|
Per-side exercises, including preacher curls and bird-dog holds, now use one Reps (each side) or Seconds (each side) input per set. Explicit edits write both stored side values together. Unequal/partial historical values remain intact on read and untouched Save, displayed as text until replaced. Equipment, prescribed side guidance and historical per-side calculation semantics remain compatible. Zero is explicit; blanks remain incomplete. No schema migration or programme change.
|
||||||
|
|
||||||
## Storage and compatibility
|
No timers/audio, dog walks, dark theme, full history/progress, routine editor, backup UI or offline-release work was added. TASK-015 remains Complete. TASK-016 is planning-only. TASK-005 and TASK-008 remain accepted future work; other task statuses are in TASKS.
|
||||||
|
|
||||||
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.
|
## Storage
|
||||||
|
|
||||||
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.
|
IndexedDB v3 retains routineOverrides, strengthEntries and performanceEntries. Detailed schemaVersion 1 records retain definition/prescription snapshots. JSON adapter exports envelope v3 and imports v1/v2/v3 atomically; old records are not silently converted. Old app builds do not support the new aggregate format. No Settings backup UI exists. User data was not cleared.
|
||||||
|
|
||||||
## Validation and limits
|
## Validation and workflow
|
||||||
|
|
||||||
- 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.
|
Final TASK-017 checks: 143 tests across 13 files, lint, production build, context validation (0 warnings) and whitespace checks pass on 2026-11-07. Coverage includes actual UI/IndexedDB save/reload/date isolation, aggregate/minute separation, historical edit isolation, shared side fields, old unequal/partial values, zero/blank/error paths, suggestions and JSON compatibility. Agent UI inventory was empty; no independent screenshot/mobile/desktop/keyboard visual pass is claimed. Captain explicitly accepted the task.
|
||||||
- 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.
|
|
||||||
|
|
||||||
## Workflow and next action
|
The testtask wrapper/config/hook and hash-verified allowlisted snapshot capability are provisioned. Only Captain runs testtask; agents must not launch/restart it, open browser windows or stop testing sessions without explicit instruction. Snapshot files are ignored by Git, tests and lint. No testtask/browser is launched for final integration.
|
||||||
|
|
||||||
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-017 implementation used the original worktree on a dedicated branch rather than a separate implementation worktree; this deviation was acknowledged. Manual-test snapshots are evidence environments, never implementation worktrees. Captain retains future commit/merge/release authority. No push or deployment is authorized.
|
||||||
|
|
||||||
## Floor-fly acceptance correction — 2026-11-04
|
Node minimum is 20.19; validation uses `/home/rob/.nvm/versions/node/v24.21.0/bin`. Baseline Vite/Vitest advisories were previously reported (1 high, 2 moderate); dependency versions are unchanged. No backend, authentication, remote or deployment target exists.
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
## All dumbbell-count inputs removed — 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.
|
|
||||||
|
|
||||||
## Completion checkboxes removed — 2026-11-04
|
|
||||||
|
|
||||||
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.
|
|
||||||
|
|||||||
@@ -339,3 +339,38 @@ TASK-015 refinement accepted by Captain (2026-11-04): floor flys always use two
|
|||||||
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 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.
|
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.
|
||||||
|
|
||||||
|
|
||||||
|
## ADR-020: EMOM entry requires only weight and total reps
|
||||||
|
|
||||||
|
- Status: Accepted; TASK-017 completed with Captain acceptance on 2026-11-07
|
||||||
|
- Date: 2026-11-07
|
||||||
|
|
||||||
|
### Decision
|
||||||
|
|
||||||
|
Normal EMOM entry has exactly one weight input and one total-reps input per exercise/session. Remove the minute table and minute/conventional-set switch. Retain protocol guidance, explicit Save and timer-free behavior.
|
||||||
|
|
||||||
|
### Context
|
||||||
|
|
||||||
|
Captain reiterated the earlier aggregate-entry instruction and rejected the table delivered in TASK-015. ADR-014 recorded the original intent. This decision supersedes ADR-017's per-minute EMOM clause and corresponding TASK-015/UI-brief requirements; other equipment and measurement decisions remain in force.
|
||||||
|
|
||||||
|
### Consequences
|
||||||
|
|
||||||
|
TASK-017 owns the correction. Preserve existing aggregate and minute records without silent conversion, data loss or fabricated uniform weights. Resolve compatible persistence and historical access during implementation while keeping normal entry to the two requested inputs. TASK-008 must support aggregates and preserved minute history without double-counting. Task creation does not start application implementation.
|
||||||
|
|
||||||
|
|
||||||
|
TASK-017 implementation contract (2026-11-07): new `emom-total` records retain schemaVersion 1 with one reps/vestKg row and immutable snapshots. A `:emom-total` key suffix preserves the original date/period/exercise detailed key. IndexedDB stays v3 with no rewriting migration. Earlier minute/aggregate records remain in a collapsed disclosure with explicit original-format editing; no empty minute editor is created for legacy-only history. Suggestions match new aggregates only. Coexisting representations must not be summed; the new aggregate is the current representation for future history. JSON exports use envelope v3, with v1/v2/v3 import compatibility.
|
||||||
|
|
||||||
|
|
||||||
|
## ADR-021: One measurement input for both sides
|
||||||
|
|
||||||
|
- Status: Accepted; TASK-017 correction accepted by Captain on 2026-11-07
|
||||||
|
- Date: 2026-11-07
|
||||||
|
|
||||||
|
### Decision
|
||||||
|
|
||||||
|
For exercises with per-side reps or durations, show one measurement input per set, applying that value to each side. Captain named Single-arm preacher curls over a chair as an example and requested removal of separate left/right inputs generally. This supersedes TASK-015's independent side-input UI requirement, while keeping programme side guidance and equipment behavior.
|
||||||
|
|
||||||
|
### Compatibility
|
||||||
|
|
||||||
|
Retain the current left/right storage fields and historical semantics. Explicit edits to the shared input set both values; browsing and untouched Save preserve unequal or partial historical values, displayed as read-only text rather than choosing one silently. No migration or fabricated historical values.
|
||||||
|
|||||||
+14
-46
@@ -2,59 +2,27 @@
|
|||||||
|
|
||||||
> Replaceable snapshot; repository code and maintained context take precedence.
|
> Replaceable snapshot; repository code and maintained context take precedence.
|
||||||
|
|
||||||
- Updated: 2026-11-04
|
- Updated: 2026-11-07
|
||||||
- Task: TASK-015 — Exercise equipment specifications and context-aware UI
|
- Task: TASK-017 — Simplify EMOM and per-side inputs.
|
||||||
- Status: Complete — Captain explicitly accepted on 2026-11-04 after the count-input and completion-checkbox corrections.
|
- Status: Complete — Captain explicitly said “task complete. commit all and merge to codex”.
|
||||||
- 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.
|
- Source: `/home/rob/projects/exercise-tracker`, task branch `task/017-emom-totals`, integration branch `codex`, base `9c0e820`. Captain authorized committing all pending task changes and merging locally; verify resulting refs/HEAD using Git. No push or deployment authorized.
|
||||||
- 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
|
## Delivered
|
||||||
|
|
||||||
- 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.
|
EMOM uses Weight (kg) and Total reps, explicit Save and compatible aggregate suggestions, without minute table or format switch. New emom-total records use a separate key, preserving historical minute/aggregate records and original editors. JSON envelope v3 supports v1/v2/v3 import; IndexedDB remains v3. Do not combine coexisting representations in future history.
|
||||||
- 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
|
Per-side sets use one Reps (each side) or Seconds (each side) input; explicit edits set both stored sides. Historical unequal/partial values are shown as text and preserved on browsing and untouched Save. Equipment, targets, hangs, navigation and clock remain compatible. No data was cleared or silently migrated.
|
||||||
|
|
||||||
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.
|
## Acceptance and validation
|
||||||
|
|
||||||
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.
|
Captain accepted all TASK-017 changes on 2026-11-07, including the per-side correction, and authorized commit/local codex merge. Final verification passes 143 tests across 13 files, lint, build, context validation (0 warnings) and whitespace checks. Review against base 9c0e820 covered tracked and untracked task files; no unresolved actionable correctness findings. No independent agent visual pass is claimed.
|
||||||
|
|
||||||
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.
|
Work used a dedicated branch in the original worktree, not a separate implementation worktree. This deviation was acknowledged to Captain; do not describe the test snapshot as an implementation worktree.
|
||||||
|
|
||||||
## Exact acceptance environment
|
## Manual-test ownership and next work
|
||||||
|
|
||||||
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.
|
Captain runs testtask. Agents must not launch/restart it, open its browser windows or stop Captain testing sessions unless explicitly instructed. Earlier agent launches were mistakes, not authority for future execution. Final integration does not invoke testtask or refresh its snapshot.
|
||||||
|
|
||||||
## Floor-fly acceptance correction — 2026-11-04
|
For future Captain testing: `PATH=/home/rob/.nvm/versions/node/v24.21.0/bin:$PATH scripts/testtask.sh 017`. The repository adapter prepares `.test-worktrees/task-017` from allowlisted source files with hash checks, shares node_modules and serves loopback port 5187 with an isolated Firefox profile. Snapshot is replaceable test evidence; do not edit it. It is historical after completion-context edits and should be refreshed by Captain if reused. No test session cleanup is inferred from the commit/merge request.
|
||||||
|
|
||||||
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.
|
TASK-016 remains planning-only; await Captain's next selected task. No implementation task is in progress after TASK-017 integration.
|
||||||
|
|
||||||
## 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,7 +6,7 @@ This is a newly initialized repository. The user calls the planned product "Work
|
|||||||
|
|
||||||
## Product
|
## Product
|
||||||
|
|
||||||
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.
|
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, durations and equipment-specific loads, with one shared measurement input for per-side work, supports completed rows, partial drafts and explicit previous-session suggestions, and records EMOM with one weight and one total-reps input. Earlier minute records remain separately accessible. 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.
|
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.
|
||||||
|
|
||||||
|
|||||||
+24
-12
@@ -16,8 +16,8 @@
|
|||||||
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.
|
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.
|
- 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.
|
- Reusable UI derives controls from repetitions, repetitions per side, duration, duration per side, distance when applicable, EMOM total reps 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 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.
|
- Log regular sets with independent load components and partial state. Explicit Save marks fully filled valid rows complete; no completion checkboxes are shown. Normal EMOM entry uses exactly one Weight (kg) input and one Total reps input (TASK-017 / ADR-020). Earlier aggregate/minute records remain separately accessible without conversion. 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.
|
- 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.
|
- 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. 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.
|
- 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.
|
||||||
@@ -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.
|
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.
|
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.
|
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 each EMOM minute independently and derive totals; log reps, per-side values, duration and equipment-specific loads per set as applicable.
|
4. Record one weight and total reps for each EMOM exercise; 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.
|
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.
|
6. Back up and restore their own data without cloud accounts, analytics or external services.
|
||||||
|
|
||||||
@@ -174,7 +174,7 @@ Target intensity (RPE): Monday **5–6**; Tuesday–Thursday **3–4**; Friday *
|
|||||||
### 4.9 Global strength-training rules
|
### 4.9 Global strength-training rules
|
||||||
|
|
||||||
- Usually **2 min** rest between sets, **2–3 min** for demanding compounds, **~3 min** between different exercises.
|
- 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 actual reps and load independently each minute; derive totals from recorded completed minutes.
|
- EMOM remains a prescribed ten-minute protocol with a new start each minute. Record one actual weight and one actual total-reps value for the exercise/session.
|
||||||
- Increase load or exercise difficulty after consistently reaching the top of a rep range with clean technique.
|
- 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.
|
- 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.
|
- Morning resistance training takes priority over optional higher-effort afternoon sessions.
|
||||||
@@ -195,7 +195,7 @@ 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.
|
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.
|
2. Allow navigating to any date/day, not just a repeating abstract weekday; records are tied to actual local dates.
|
||||||
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.
|
3. Expand Exercise details for available notes and honest content/image placeholders. Enter one weight and total reps for EMOM; regular sets retain metadata-selected measurements and load fields. Per-side exercises use one reps or seconds input per set, applying to each side (ADR-021). 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.
|
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.
|
5. Partial records remain saved, and future plan edits do not rewrite previously logged performance.
|
||||||
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.
|
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.
|
||||||
@@ -203,17 +203,17 @@ Each exercise has a stable `exerciseId` and human-readable name, category, equip
|
|||||||
|
|
||||||
### Suitcase-carry recording
|
### Suitcase-carry recording
|
||||||
|
|
||||||
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.
|
Suitcase carries retain their prescribed duration per side and accept one actual seconds-per-side input 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 recording
|
### Plank recording
|
||||||
|
|
||||||
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.
|
Front planks accept actual seconds and vest kilograms per set without repetitions. Side-plank hip raises accept one reps-per-side input 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
|
### 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.
|
- 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.
|
- Do not show workout, exercise, rest, or EMOM timers or audio cues.
|
||||||
- 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.
|
- Keep EMOM duration and rest guidance as prescriptions only. A new EMOM entry has one weight and one total-reps input with no minute table or mode switch; 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.
|
- Browsing dates does not create workout records. Saving a strength entry writes the selected date and exercise only.
|
||||||
|
|
||||||
## 7. Local data architecture
|
## 7. Local data architecture
|
||||||
@@ -246,7 +246,7 @@ The earlier `strengthEntries` store is kept verbatim, including aggregate EMOM,
|
|||||||
### 7.1 Tracking requirements (v1, agreed)
|
### 7.1 Tracking requirements (v1, agreed)
|
||||||
|
|
||||||
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.
|
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.
|
2. For EMOM pull-ups and chin-ups, save one total-reps value and one vest weight. Keep the ten-minute protocol visible without running a timer. The normal EMOM entry has no format switch.
|
||||||
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.
|
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.
|
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. Incomplete hold drafts may omit times; completion requires actual durations. Record sides independently where relevant.
|
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.
|
||||||
@@ -255,7 +255,7 @@ The earlier `strengthEntries` store is kept verbatim, including aggregate EMOM,
|
|||||||
8. Never rewrite completed history following routine edits, reseeding, changes to exercise definitions or app upgrades. Future routine edits only change future prescriptions.
|
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.
|
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.
|
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 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.
|
11. For a workout's **total external-load volume** (kg·reps), sum `actual reps × actual external kilograms moved` across completed regular sets and new aggregate EMOM entries; preserved historical minute entries retain their individual calculations. 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
|
### Data integrity and update rules
|
||||||
|
|
||||||
@@ -301,7 +301,7 @@ 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.
|
- [ ] 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.
|
- [ ] 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.
|
- [ ] 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 reps and vest weight are recorded independently each minute.
|
- [ ] Tuesday pull-ups and Saturday chin-ups retain the **10 × 60-second EMOM** prescription and 6 kg vest presets, while actual performance uses one total-reps and one weight input.
|
||||||
- [ ] Wednesday flys have **no floor-press drop set**; push-up plus precedes feet-elevated push-ups.
|
- [ ] 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**.
|
- [ ] 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**.
|
- [ ] Saturday includes hanging knee raises, 2–3 finger-hang sets, preacher curls and hammer curls; **no EZ curls or wrist curls**.
|
||||||
@@ -310,7 +310,7 @@ Do not implement all tasks as a single unreviewed change. Define task boundaries
|
|||||||
- [ ] 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.
|
- [ ] 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.
|
||||||
- [ ] Equipment capabilities contain no fixed weight. Historical 6/10 kg values remain prescription context only and do not determine inputs or prefill actuals.
|
- [ ] 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.
|
- [ ] 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 minute reps/load and regular-set measurements/weights survive reload by date, period and exercise; prescribed values are never saved as performed automatically.
|
- [ ] EMOM total reps/weight 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-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.
|
- [ ] 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.
|
- [ ] 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.
|
||||||
@@ -342,3 +342,15 @@ Do not implement all tasks as a single unreviewed change. Define task boundaries
|
|||||||
---
|
---
|
||||||
|
|
||||||
*This is a design specification, not medical guidance. Adjust any exercise causing pain and seek clinical assessment for new or progressive spinal prominence, unexplained weight loss or persistent pain.*
|
*This is a design specification, not medical guidance. Adjust any exercise causing pain and seek clinical assessment for new or progressive spinal prominence, unexplained weight loss or persistent pain.*
|
||||||
|
|
||||||
|
|
||||||
|
### TASK-017 EMOM compatibility contract
|
||||||
|
|
||||||
|
New EMOM totals use schemaVersion 1, format `emom-total`, one row of reps/vestKg/completion and saved definition/prescription snapshots. Their `performanceEntries` key adds `:emom-total` to date/period/exercise identity, leaving the original detailed record untouched. IndexedDB stays v3; no records migrate on read. Earlier records are accessible only through an initially collapsed disclosure; it never invents an empty minute record for editing. New suggestions match earlier aggregate-format records only. If aggregate and original representations coexist for one session, use the aggregate as the current representation and never sum them. Blank values persist as incomplete drafts; valid zero remains explicit.
|
||||||
|
|
||||||
|
Adapter exports now use JSON envelope v3 and continue importing v1/v2 as well as v3. Older applications cannot read the new aggregate record format; retain the new application for restoring v3 backups. No Settings backup UI is added.
|
||||||
|
|
||||||
|
|
||||||
|
### TASK-017 side-input correction
|
||||||
|
|
||||||
|
Every per-side exercise, including Single-arm preacher curls over a chair, uses one Reps (each side) or Seconds (each side) input per set. Entering or clearing the input changes both stored side values together. Equipment inputs and prescription guidance remain unchanged. Existing unequal/partial side values are shown as read-only text with a blank shared replacement input; browsing or untouched Save does not choose a side or rewrite either value. Storage shapes, snapshots and per-side volume semantics remain unchanged.
|
||||||
|
|||||||
+3
-1
@@ -1,5 +1,7 @@
|
|||||||
# TASK-015 UI and storage implementation brief
|
# TASK-015 UI and storage implementation brief
|
||||||
|
|
||||||
|
> Historical brief: TASK-017 / ADR-020 supersede every EMOM minute-table and format-switch requirement below. Current normal EMOM entry has only Weight (kg), Total reps and Save; existing minute history remains separately accessible.
|
||||||
|
|
||||||
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).
|
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
|
## Composition and interaction
|
||||||
@@ -8,7 +10,7 @@ Keep the app header, wall clock, date strip and exclusive period switch. Each ex
|
|||||||
|
|
||||||
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.
|
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.
|
TASK-017 / ADR-021 supersede separate side controls: rep-per-side and duration-per-side now use one shared input applying to each side. Historical unequal values remain read-only text until explicitly replaced. 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.
|
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.
|
||||||
|
|
||||||
|
|||||||
+29
-3
@@ -4,7 +4,7 @@ This file holds accepted, scoped implementation work. It is not a speculative ba
|
|||||||
|
|
||||||
## Proposed implementation sequence
|
## 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 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.
|
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; TASK-017 is Complete following Captain acceptance on 2026-11-07; 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
|
### TASK-001: Application foundation and responsive shell
|
||||||
|
|
||||||
@@ -87,8 +87,8 @@ Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001 through T
|
|||||||
|
|
||||||
- Status: Accepted
|
- Status: Accepted
|
||||||
- Objective: Browse actual dated performance and transparent basic trends without a time-based rate.
|
- 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 completed detailed minute/set rows and separately preserved legacy aggregates, longest continuous and cumulative hang separately, optional body-weight trend.
|
- Scope: Completed/partial session history, prior vs current performance, reps and load trends, total external-load volume from completed regular sets and aggregate EMOM entries, with historical minute/legacy records preserved separately, 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.
|
- Acceptance criteria: External-load volume is the sum, across completed regular sets and aggregate EMOM entries; historical minute entries retain their own load calculations, 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. Use the current aggregate when it coexists with older representations for one session; never sum both. 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.
|
- 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.
|
- 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.
|
- Non-goals: Coaching, calorie estimates, streaks.
|
||||||
@@ -250,3 +250,29 @@ Reconciled with `docs/SPEC.md` and `docs/WORKOUT_ROUTINE.md`. TASK-001 through T
|
|||||||
- 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.
|
- 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.
|
- 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.
|
- Recommended skills when engaged: Frontend UI Design → Webapp Feature → Frontend Visual QA. This record does not authorize implementation.
|
||||||
|
|
||||||
|
|
||||||
|
### TASK-017: Replace EMOM tables with one weight and one total-reps input
|
||||||
|
|
||||||
|
- Status: Complete — Captain explicitly accepted on 2026-11-07
|
||||||
|
- Engaged: 2026-11-07 on `task/017-emom-totals`, base `codex` / `9c0e820`.
|
||||||
|
- Requested: 2026-11-07. Captain reiterated that the EMOM minute table is unwanted and only one weight input and one total-reps input are needed.
|
||||||
|
- Objective: Restore simple aggregate EMOM entry under ADR-020, consistent with the original ADR-014 intent.
|
||||||
|
- Scope: Replace the normal EMOM input table with exactly one weight (kg) input and one total-reps input per exercise/session. Remove minute rows and the minute/conventional-set mode switch. Keep prescribed protocol guidance, explicit Save, validation and dated local persistence.
|
||||||
|
- Acceptance criteria: Every EMOM exercise has exactly these two performance inputs, with no minute table, repeated fields, add-set controls, completion checkboxes or mode switch. Values survive Save, reload and date/period navigation with correct isolation. Zero weight is valid; blanks remain missing rather than becoming zero or targets. Browsing writes nothing; invalid values and storage failures remain visible. Existing aggregate and detailed minute records retain original values and semantics without silent conversion, overwritten history, fabricated uniform weights or double-counting. Regular sets, non-EMOM equipment controls, hangs, navigation and the wall clock retain existing behavior; timers remain absent.
|
||||||
|
- Relevant areas: `src/PerformanceEditor.jsx`, `src/performanceModel.js`, performance/legacy storage adapters and tests, `docs/SPEC.md`, `docs/TASK-015_UI.md` and context documents.
|
||||||
|
- Required validation: UI assertions for exactly one weight and one total-reps input and no EMOM table/mode switch; IndexedDB save/reload/date-isolation tests; historical aggregate/minute compatibility and zero/blank/error regressions; full tests, lint, build, context validation and `git diff --check`. Verify keyboard use and 320px/desktop layout. Captain manual acceptance is required before Complete.
|
||||||
|
- Non-goals: Changes to the training programme or other exercise entry, advanced/per-minute entry, timers, history/progress screens and unrelated refactors.
|
||||||
|
- Dependencies or blockers: TASK-015 is integrated on local `codex` (inspected HEAD `9c0e820`). ADR-020 supersedes its minute-entry requirements and ADR-017's corresponding clause. During implementation define compatible persistence and historical access without silently collapsing varying historical loads. TASK-008 must support new aggregates alongside preserved minute history without double-counting. No additional input fields are authorized.
|
||||||
|
- Implementation evidence (2026-11-07): Two-input EMOM form, separate aggregate key/format, preserved original editors, aggregate-only suggestions and JSON v3 with v1/v2 import compatibility implemented. 139 tests across 12 files, lint and build pass; context/whitespace checks and refreshed testtask snapshot are recorded in HANDOFF. Reviewed against codex / 9c0e820. Browser UI automation inventory is empty; real 320px/desktop and keyboard visual checks remain for Captain. No commit/merge performed.
|
||||||
|
|
||||||
|
|
||||||
|
#### Accepted TASK-017 validation correction — one input for both sides (2026-11-07)
|
||||||
|
|
||||||
|
- Status: Complete — included in Captain acceptance on 2026-11-07.
|
||||||
|
- Scope: All exercises currently asking separate left/right reps or seconds, including Single-arm preacher curls over a chair, use one reps/seconds input per set labeled as applying to each side. Entering or clearing it updates both sides together. Keep equipment inputs and prescribed side guidance.
|
||||||
|
- Acceptance: No separate left/right input controls remain. Save/reload, multiple sets, zero/blank drafts and compatible suggestions work. Previously recorded unequal or partial left/right values remain intact on read and untouched Save, shown as read-only history; entering a replacement explicitly applies it to both sides. No schema migration or programme changes.
|
||||||
|
- Validation: All-exercise control matrix; preacher-curl and hold entry/reload; historical unequal/partial preservation; storage integration; full tests/lint/build/context/whitespace and refreshed TASK-017 test snapshot. Captain acceptance remains required.
|
||||||
|
|
||||||
|
|
||||||
|
- TASK-017 completion evidence (2026-11-07): Captain explicitly stated “task complete. commit all and merge to codex”, accepting EMOM totals and shared per-side inputs. Final automated verification: 143 tests across 13 files, lint, build, context validation and whitespace checks pass. No independent agent browser visual pass is claimed. Captain authorized committing all pending task changes and local codex integration; no push/deployment. Work was done on a dedicated task branch in the original worktree, not a separate implementation worktree; this workflow deviation is recorded, not retroactively corrected. Testtask execution belongs to Captain.
|
||||||
|
|||||||
+6
-1
@@ -39,10 +39,15 @@ The project owner is **Captain**. Reports may use a restrained Starfleet chief-e
|
|||||||
|
|
||||||
Record the status and evidence in `TASKS.md`; keep verified operational state in `CURRENT_STATE.md`; put durable decisions in `DECISIONS.md`; refresh `HANDOFF.md` with the testable state, exact validation, open risks, and next action. Tests passing alone do not promote a task past a required Captain review. Do not retroactively invent acceptance evidence.
|
Record the status and evidence in `TASKS.md`; keep verified operational state in `CURRENT_STATE.md`; put durable decisions in `DECISIONS.md`; refresh `HANDOFF.md` with the testable state, exact validation, open risks, and next action. Tests passing alone do not promote a task past a required Captain review. Do not retroactively invent acceptance evidence.
|
||||||
|
|
||||||
Before asking Captain for manual testing, identify an exact testable representation of the task. No `.roborto/testtask.conf`, `scripts/testtask.sh`, or other repository testtask adapter currently exists. Recheck for one before future test handoffs and use it if introduced. Manual-test snapshots are evidence environments, not implementation worktrees; refresh them after further changes. Record any test snapshot and its source state in `HANDOFF.md`.
|
Before asking Captain for manual testing, identify an exact testable representation of the task. The repository now has `.roborto/testtask.conf`, `scripts/testtask.sh` and a project hook. Captain runs this adapter; agents provide the handoff and command without launching it. Manual-test snapshots are evidence environments, not implementation worktrees; refresh them after further changes. Record any test snapshot and its source state in `HANDOFF.md`.
|
||||||
|
|
||||||
## Validation and design authority
|
## Validation and design authority
|
||||||
|
|
||||||
- Use each task's `Required validation` and acceptance criteria. Repository commands are `npm test`, `npm run lint`, and `npm run build` from the root; `package.json` requires Node.js 20.19 or newer. Run context validation and `git diff --check` when context changes. State any test that could not run and do not claim an unperformed visual or manual check.
|
- Use each task's `Required validation` and acceptance criteria. Repository commands are `npm test`, `npm run lint`, and `npm run build` from the root; `package.json` requires Node.js 20.19 or newer. Run context validation and `git diff --check` when context changes. State any test that could not run and do not claim an unperformed visual or manual check.
|
||||||
- For UI work, read `docs/SPEC.md`, relevant `docs/DECISIONS.md`, `src/styles.css`, and any later styling/design-system document or approved reference before designing or editing. Preserve the approved visual language unless the task changes it. No separate styling/design-system document is currently present.
|
- For UI work, read `docs/SPEC.md`, relevant `docs/DECISIONS.md`, `src/styles.css`, and any later styling/design-system document or approved reference before designing or editing. Preserve the approved visual language unless the task changes it. No separate styling/design-system document is currently present.
|
||||||
- Recommend the smallest useful specialist-skill sequence: Roborto New Project for a new template-based app; Frontend UI Design for unsettled UI; Webapp Feature for accepted functionality; Webapp Debug for faults; Frontend Visual QA for visible UI; Safe Refactor for behavior-preserving structure changes; Code Review for task diff; Production Readiness Review before launch; Deployment Check for an authorized release; Project Commercial Management for commercial scope; Roborto Contributor for contributor guidance. Recommend only applicable skills and do not claim one ran when it was merely suggested.
|
- Recommend the smallest useful specialist-skill sequence: Roborto New Project for a new template-based app; Frontend UI Design for unsettled UI; Webapp Feature for accepted functionality; Webapp Debug for faults; Frontend Visual QA for visible UI; Safe Refactor for behavior-preserving structure changes; Code Review for task diff; Production Readiness Review before launch; Deployment Check for an authorized release; Project Commercial Management for commercial scope; Roborto Contributor for contributor guidance. Recommend only applicable skills and do not claim one ran when it was merely suggested.
|
||||||
|
|
||||||
|
|
||||||
|
## Captain-owned testtask execution
|
||||||
|
|
||||||
|
Captain clarified on 2026-11-07 that `testtask` is for Captain to run. Agents must not automatically invoke/restart the runner, open its browser windows or stop Captain testing sessions. Provide the command and handoff after automated checks; run or control testtask only on explicit instruction. This overrides skill defaults to execute the manual-test runner.
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@ import globals from 'globals'
|
|||||||
import react from 'eslint-plugin-react'
|
import react from 'eslint-plugin-react'
|
||||||
|
|
||||||
export default [
|
export default [
|
||||||
{ ignores: ['dist/**', 'node_modules/**'] },
|
{ ignores: ['dist/**', 'node_modules/**', '.test-worktrees/**'] },
|
||||||
js.configs.recommended,
|
js.configs.recommended,
|
||||||
{
|
{
|
||||||
files: ['**/*.{js,jsx}'],
|
files: ['**/*.{js,jsx}'],
|
||||||
|
|||||||
Executable
+7
@@ -0,0 +1,7 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
if ! command -v roborto-testtask >/dev/null 2>&1; then
|
||||||
|
echo 'testtask: standalone roborto-testtask CLI is missing; install/configure it before running.' >&2
|
||||||
|
exit 127
|
||||||
|
fi
|
||||||
|
exec roborto-testtask "$@"
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
"""Refresh an owned source snapshot without commits or Git branch mutations."""
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
root = Path(os.environ['ROBORTO_PROJECT_ROOT']).resolve()
|
||||||
|
task = os.environ['ROBORTO_TASK_ID']
|
||||||
|
if len(task) != 3 or not task.isdecimal():
|
||||||
|
raise SystemExit('Invalid task ID')
|
||||||
|
snapshot = root / '.test-worktrees' / f'task-{task}'
|
||||||
|
if Path(os.environ['ROBORTO_WORKTREE']) != snapshot or snapshot.is_symlink():
|
||||||
|
raise SystemExit('Unexpected snapshot path')
|
||||||
|
marker = snapshot / '.snapshot.json'
|
||||||
|
if snapshot.exists():
|
||||||
|
if not marker.is_file() or json.loads(marker.read_text()).get('source') != str(root):
|
||||||
|
raise SystemExit('Refusing to replace an unowned snapshot')
|
||||||
|
# Detect manual edits before refreshing; snapshots are not implementation worktrees.
|
||||||
|
prior = json.loads(marker.read_text())['files']
|
||||||
|
for name, digest in prior.items():
|
||||||
|
target = snapshot / name
|
||||||
|
if not target.is_file() or hashlib.sha256(target.read_bytes()).hexdigest() != digest:
|
||||||
|
raise SystemExit(f'Snapshot changed; preserve/reconcile it before refresh: {name}')
|
||||||
|
expected = set(prior) | {'.snapshot.json'}
|
||||||
|
actual = {str(p.relative_to(snapshot)) for p in snapshot.rglob('*') if p.is_file() and 'node_modules' not in p.relative_to(snapshot).parts}
|
||||||
|
if actual - expected:
|
||||||
|
raise SystemExit('Snapshot has extra files; preserve/reconcile before refresh')
|
||||||
|
shutil.rmtree(snapshot)
|
||||||
|
names = subprocess.check_output(['git', 'ls-files', '-co', '--exclude-standard', '-z'], cwd=root).decode().split('\0')
|
||||||
|
# Explicit application/context allowlist: never copy local databases, env files or credentials.
|
||||||
|
root_files = {'AGENTS.md', '.gitignore', 'index.html', 'package.json', 'package-lock.json', 'vite.config.js', 'eslint.config.js', 'README.md'}
|
||||||
|
files = {}
|
||||||
|
for name in sorted(set(names) - {''}):
|
||||||
|
path = root / name
|
||||||
|
parts = Path(name).parts
|
||||||
|
if name not in root_files and parts[0] not in {'src', 'public', 'docs', 'scripts', '.roborto'}:
|
||||||
|
continue
|
||||||
|
if any(part.startswith('.env') or part in {'credentials', 'secrets'} for part in parts):
|
||||||
|
continue
|
||||||
|
if path.is_symlink():
|
||||||
|
raise SystemExit(f'Refusing source symlink: {name}')
|
||||||
|
if not path.is_file():
|
||||||
|
continue
|
||||||
|
target = snapshot / name
|
||||||
|
target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
shutil.copy2(path, target)
|
||||||
|
digest = hashlib.sha256(path.read_bytes()).hexdigest()
|
||||||
|
if hashlib.sha256(target.read_bytes()).hexdigest() != digest:
|
||||||
|
raise SystemExit(f'Snapshot mismatch: {name}')
|
||||||
|
files[name] = digest
|
||||||
|
(snapshot / 'node_modules').symlink_to(root / 'node_modules', target_is_directory=True)
|
||||||
|
marker.write_text(json.dumps({'source': str(root), 'task': task, 'files': files}, indent=2) + '\n')
|
||||||
|
print(f'Verified {len(files)} source files in {snapshot}; node_modules shared, browser data separate.')
|
||||||
@@ -16,20 +16,20 @@ it('runs detailed logging through the actual UI/storage boundary while preservin
|
|||||||
await writeStrengthEntry('2026-11-03', 'pull-up', legacy)
|
await writeStrengthEntry('2026-11-03', 'pull-up', legacy)
|
||||||
const view = render(<App />)
|
const view = render(<App />)
|
||||||
const card = screen.getByText('Pull-ups').closest('.exercise-card')
|
const card = screen.getByText('Pull-ups').closest('.exercise-card')
|
||||||
await waitFor(() => expect(within(card).getByLabelText('Minute 1 reps').disabled).toBe(false))
|
await waitFor(() => expect(within(card).getByLabelText('Total reps').disabled).toBe(false))
|
||||||
fireEvent.change(within(card).getByLabelText('Minute 1 reps'), { target: { value: '4' } })
|
fireEvent.change(within(card).getByLabelText('Total reps'), { target: { value: '4' } })
|
||||||
fireEvent.change(within(card).getByLabelText('Minute 1 vest (kg)'), { target: { value: '8' } })
|
fireEvent.change(within(card).getByLabelText('Weight (kg)'), { target: { value: '8' } })
|
||||||
fireEvent.click(within(card).getByRole('button', { name: 'Save performance' }))
|
fireEvent.click(within(card).getByRole('button', { name: 'Save performance' }))
|
||||||
await within(card).findByText('Saved')
|
await within(card).findByText('Saved')
|
||||||
expect(await readStrengthEntry('2026-11-03', 'pull-up')).toEqual(legacy)
|
expect(await readStrengthEntry('2026-11-03', 'pull-up')).toEqual(legacy)
|
||||||
const saved = await readPerformance('2026-11-03', 'morning', 'pull-up')
|
const saved = await readPerformance('2026-11-03', 'morning', 'pull-up', 'emom-total')
|
||||||
expect(saved.rows[0]).toEqual({ completed: true, values: { reps: 4 }, load: { vestKg: 8 } })
|
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 } })
|
expect(saved.rows).toHaveLength(1)
|
||||||
view.unmount(); render(<App />)
|
view.unmount(); render(<App />)
|
||||||
const restored = screen.getByText('Pull-ups').closest('.exercise-card')
|
const restored = screen.getByText('Pull-ups').closest('.exercise-card')
|
||||||
await waitFor(() => expect(within(restored).getByLabelText('Minute 1 vest (kg)').value).toBe('8'))
|
await waitFor(() => expect(within(restored).getByLabelText('Weight (kg)').value).toBe('8'))
|
||||||
fireEvent.click(screen.getByRole('button', { name: 'Next week' }))
|
fireEvent.click(screen.getByRole('button', { name: 'Next week' }))
|
||||||
expect(await readPerformance('2026-11-10', 'morning', 'pull-up')).toBeNull()
|
expect(await readPerformance('2026-11-10', 'morning', 'pull-up', 'emom-total')).toBeNull()
|
||||||
})
|
})
|
||||||
it('uses a persisted continuous hang target without losing unsaved attempts when editing it', async () => {
|
it('uses a persisted continuous hang target without losing unsaved attempts when editing it', async () => {
|
||||||
await writeDailyHangGoal(180)
|
await writeDailyHangGoal(180)
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
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 DetailedPerformanceEditor({ dateKey, period, definition, prescription, goalSeconds, historicalOnly = false }) {
|
||||||
|
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, sharedKeys) {
|
||||||
|
const value = raw === '' ? null : Number(raw)
|
||||||
|
change({ ...record, rows: record.rows.map((row, i) => i === index ? { ...row, completed: false, [group]: { ...row[group], ...Object.fromEntries((sharedKeys ?? [key]).map((field) => [field, 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 measurements = measurementColumns(record.definition)
|
||||||
|
const perSide = record.definition.measurement.endsWith('-per-side')
|
||||||
|
const inputMeasurements = perSide ? [{ ...measurements[0], label: record.definition.measurement === 'repetitions-per-side' ? 'Reps (each side)' : 'Seconds (each side)', sharedKeys: measurements.map(({ key }) => key) }] : measurements
|
||||||
|
const columns = [...inputMeasurements.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)
|
||||||
|
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>}
|
||||||
|
{historicalOnly && !hasSaved && loading && <p role="status">Loading earlier records…</p>}
|
||||||
|
{historicalOnly && !hasSaved && readFailed && <><p role="alert" className="strength-error">{error}</p><Button type="button" onClick={() => setRetry(retry + 1)}>Retry loading earlier records</Button></>}
|
||||||
|
{changedDefinition && <p role="status">This entry uses its saved exercise definition. Current targets above do not change its recorded equipment or measurements.</p>}
|
||||||
|
{(!historicalOnly || hasSaved) && <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>
|
||||||
|
</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, sharedKeys }) => <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={sharedKeys && !sharedKeys.every((field) => row[group][field] === row[group][key]) ? '' : row[group][key] ?? ''} disabled={disabled} onChange={(event) => update(index, group, key, event.target.value, sharedKeys)} /></label>)}
|
||||||
|
|
||||||
|
{perSide && row.values[measurements[0].key] !== row.values[measurements[1].key] && <p className="recorded-sides">Recorded: left {row.values[measurements[0].key] ?? 'blank'}, right {row.values[measurements[1].key] ?? 'blank'}. Enter a value above to replace both sides.</p>}
|
||||||
|
{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>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import { useEffect, useId, useState } from 'react'
|
||||||
|
import { Button } from 'react-bootstrap'
|
||||||
|
import { copy, newPerformance, performanceError, preparePerformanceForSave } from './performanceModel.js'
|
||||||
|
import { previousPerformance, readPerformance, writePerformance } from './performanceStorage.js'
|
||||||
|
import { readStrengthEntry } from './strengthStorage.js'
|
||||||
|
import DetailedPerformanceEditor from './DetailedPerformanceEditor.jsx'
|
||||||
|
|
||||||
|
export default function EmomTotalEditor({ dateKey, period, definition, prescription, ...rest }) {
|
||||||
|
const id = useId()
|
||||||
|
const [record, setRecord] = useState(null)
|
||||||
|
const [historyOpen, setHistoryOpen] = useState(false)
|
||||||
|
const [historical, setHistorical] = useState(false)
|
||||||
|
const [busy, setBusy] = useState(true)
|
||||||
|
const [failed, setFailed] = useState(false)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
const [notice, setNotice] = useState('')
|
||||||
|
const [retry, setRetry] = useState(0)
|
||||||
|
const [saved, setSaved] = useState(false)
|
||||||
|
useEffect(() => {
|
||||||
|
let active = true
|
||||||
|
setHistoryOpen(false); setBusy(true); setNotice(''); setError(''); setFailed(false); setRecord(null)
|
||||||
|
Promise.all([readPerformance(dateKey, period, definition.id, 'emom-total'), readPerformance(dateKey, period, definition.id), period === 'morning' ? readStrengthEntry(dateKey, definition.id) : null])
|
||||||
|
.then(([total, detailed, legacy]) => {
|
||||||
|
if (!active) return
|
||||||
|
setRecord(total ?? newPerformance(dateKey, period, definition, prescription, 'emom-total'))
|
||||||
|
setSaved(Boolean(total)); setHistorical(Boolean(detailed || legacy)); setBusy(false)
|
||||||
|
}).catch((failure) => { if (active) { setError(failure.message); setFailed(true); setBusy(false) } })
|
||||||
|
return () => { active = false }
|
||||||
|
}, [dateKey, period, definition, retry])
|
||||||
|
function update(group, key, raw) {
|
||||||
|
setRecord({ ...record, rows: [{ ...record.rows[0], completed: false, [group]: { ...record.rows[0][group], [key]: raw === '' ? null : Number(raw) } }] })
|
||||||
|
setNotice('Unsaved changes.'); setError('')
|
||||||
|
}
|
||||||
|
async function save(event) {
|
||||||
|
event.preventDefault()
|
||||||
|
const candidate = preparePerformanceForSave(saved ? record : { ...record, prescription: copy(prescription) })
|
||||||
|
const failure = performanceError(candidate)
|
||||||
|
if (failure) { setError(failure); return }
|
||||||
|
setBusy(true); setNotice(''); setError('')
|
||||||
|
try { await writePerformance(candidate); setRecord(candidate); setSaved(true); setNotice(candidate.rows[0].completed ? 'Saved' : 'Saved incomplete entry') }
|
||||||
|
catch (failure) { setError(failure.message) }
|
||||||
|
finally { setBusy(false) }
|
||||||
|
}
|
||||||
|
async function suggest() {
|
||||||
|
setBusy(true); setError('')
|
||||||
|
try {
|
||||||
|
if (record.rows[0].values.reps !== null || record.rows[0].load.vestKg !== null) { setNotice('Current entries kept.'); return }
|
||||||
|
const previous = await previousPerformance(dateKey, period, record.definition, 'emom-total')
|
||||||
|
if (!previous) { setNotice('No compatible previous session found.'); return }
|
||||||
|
setRecord({ ...record, rows: [{ ...copy(previous.rows[0]), completed: false }] })
|
||||||
|
setNotice(`Suggested from ${previous.date}. Review, then save.`)
|
||||||
|
} catch (failure) { setError(failure.message) }
|
||||||
|
finally { setBusy(false) }
|
||||||
|
}
|
||||||
|
return <div className="performance-entry">
|
||||||
|
<form onSubmit={save} aria-label={`${definition.name} actual performance`} aria-busy={busy} aria-describedby={error ? `${id}-error` : undefined}>
|
||||||
|
<div className="performance-toolbar"><strong>Actual performance</strong></div>
|
||||||
|
<div className="emom-total-fields">
|
||||||
|
<label>Weight (kg)<input aria-label="Weight (kg)" type="number" inputMode="decimal" min="0" step="any" value={record?.rows[0].load.vestKg ?? ''} disabled={busy || failed} onChange={(event) => update('load', 'vestKg', event.target.value)} /></label>
|
||||||
|
<label>Total reps<input aria-label="Total reps" type="number" inputMode="numeric" min="0" step="1" value={record?.rows[0].values.reps ?? ''} disabled={busy || failed} onChange={(event) => update('values', 'reps', event.target.value)} /></label>
|
||||||
|
</div>
|
||||||
|
<div className="performance-actions">
|
||||||
|
<Button type="button" variant="link" size="sm" disabled={busy || failed || !record} onClick={suggest}>Use previous session</Button>
|
||||||
|
<Button type="submit" size="sm" disabled={busy || failed || !record}>{busy ? 'Loading…' : 'Save performance'}</Button>
|
||||||
|
</div>
|
||||||
|
{failed && <Button type="button" onClick={() => setRetry(retry + 1)}>Retry loading</Button>}
|
||||||
|
<p role="status" className="performance-status">{notice}</p>
|
||||||
|
{error && <p role="alert" id={`${id}-error`} className="strength-error">{error}</p>}
|
||||||
|
</form>
|
||||||
|
{historical && <details className="legacy-entry" onToggle={(event) => setHistoryOpen(event.currentTarget.open)}><summary>Earlier records</summary>
|
||||||
|
<p>Original records are preserved separately. The total above is a separate entry for this session; do not add both representations together.</p>
|
||||||
|
{historyOpen && <DetailedPerformanceEditor historicalOnly dateKey={dateKey} period={period} definition={definition} prescription={prescription} {...rest} />}
|
||||||
|
</details>}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
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 PerformanceEditor from './PerformanceEditor.jsx'
|
||||||
|
import { exerciseDefinitions } from './data/index.js'
|
||||||
|
import { newPerformance } from './performanceModel.js'
|
||||||
|
import { readPerformance, writePerformance } from './performanceStorage.js'
|
||||||
|
import { exportBackup, importBackup } from './backupStorage.js'
|
||||||
|
const definition = exerciseDefinitions.find((d) => d.id === 'pull-up')
|
||||||
|
const props = { dateKey: '2026-11-03', period: 'morning', definition, prescription: { kind: 'emom', rounds: 10, intervalSec: 60 } }
|
||||||
|
const fill = (name, value) => fireEvent.change(screen.getByLabelText(name), { target: { value } })
|
||||||
|
const ready = () => waitFor(() => expect(screen.getByLabelText('Weight (kg)').disabled).toBe(false))
|
||||||
|
beforeEach(() => vi.stubGlobal('indexedDB', new IDBFactory()))
|
||||||
|
afterEach(() => { cleanup(); vi.unstubAllGlobals() })
|
||||||
|
it.each(['pull-up', 'chin-up'])('shows only weight and total reps for %s', async (id) => {
|
||||||
|
render(<PerformanceEditor {...props} definition={exerciseDefinitions.find((d) => d.id === id)} />); await ready()
|
||||||
|
expect(screen.getAllByRole('spinbutton')).toHaveLength(2)
|
||||||
|
expect(screen.queryByText(/Minute 1|Use conventional sets|Use EMOM minutes|Add set/)).toBeNull()
|
||||||
|
expect(screen.queryByRole('checkbox')).toBeNull()
|
||||||
|
})
|
||||||
|
it('saves zero weight and total reps, reloads and isolates dates and periods', async () => {
|
||||||
|
const view = render(<PerformanceEditor {...props} />); await ready()
|
||||||
|
fill('Weight (kg)', '0'); fill('Total reps', '37')
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||||
|
const record = await readPerformance(props.dateKey, 'morning', definition.id, 'emom-total')
|
||||||
|
expect(record.rows).toEqual([{ values: { reps: 37 }, load: { vestKg: 0 }, completed: true }])
|
||||||
|
view.unmount(); render(<PerformanceEditor {...props} />); await ready()
|
||||||
|
expect(screen.getByLabelText('Weight (kg)').value).toBe('0')
|
||||||
|
expect(screen.getByLabelText('Total reps').value).toBe('37')
|
||||||
|
expect(await readPerformance('2026-11-04', 'morning', definition.id, 'emom-total')).toBeNull()
|
||||||
|
expect(await readPerformance(props.dateKey, 'afternoon', definition.id, 'emom-total')).toBeNull()
|
||||||
|
const backup = await exportBackup(); vi.stubGlobal('indexedDB', new IDBFactory()); await importBackup(backup)
|
||||||
|
expect(await exportBackup()).toBe(backup)
|
||||||
|
})
|
||||||
|
it('keeps missing reps as an incomplete draft without inventing zero', async () => {
|
||||||
|
render(<PerformanceEditor {...props} />); await ready(); fill('Weight (kg)', '6')
|
||||||
|
expect(await readPerformance(props.dateKey, 'morning', definition.id, 'emom-total')).toBeNull()
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved incomplete entry')
|
||||||
|
expect((await readPerformance(props.dateKey, 'morning', definition.id, 'emom-total')).rows[0]).toMatchObject({ values: { reps: null }, completed: false })
|
||||||
|
})
|
||||||
|
it('preserves mixed historical minute loads when saving a new aggregate', async () => {
|
||||||
|
const old = newPerformance(props.dateKey, 'morning', definition, props.prescription)
|
||||||
|
old.rows[0] = { values: { reps: 4 }, load: { vestKg: 6 }, completed: true }
|
||||||
|
old.rows[1] = { values: { reps: 3 }, load: { vestKg: 10 }, completed: true }
|
||||||
|
await writePerformance(old)
|
||||||
|
render(<PerformanceEditor {...props} />); await ready()
|
||||||
|
expect(screen.getByLabelText('Weight (kg)').value).toBe('')
|
||||||
|
expect(screen.getByLabelText('Total reps').value).toBe('')
|
||||||
|
fill('Weight (kg)', '8'); fill('Total reps', '35')
|
||||||
|
const form = screen.getByRole('form', { name: 'Pull-ups actual performance' })
|
||||||
|
fireEvent.click(within(form).getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||||
|
expect(await readPerformance(props.dateKey, 'morning', definition.id)).toEqual(old)
|
||||||
|
const backup = await exportBackup(); vi.stubGlobal('indexedDB', new IDBFactory()); await importBackup(backup)
|
||||||
|
expect(await readPerformance(props.dateKey, 'morning', definition.id)).toEqual(old)
|
||||||
|
})
|
||||||
|
it('reports unavailable storage and offers retry without saving', async () => {
|
||||||
|
vi.stubGlobal('indexedDB', undefined)
|
||||||
|
render(<PerformanceEditor {...props} />)
|
||||||
|
await screen.findByRole('alert')
|
||||||
|
expect(screen.getByLabelText('Total reps').disabled).toBe(true)
|
||||||
|
vi.stubGlobal('indexedDB', new IDBFactory()); fireEvent.click(screen.getByRole('button', { name: 'Retry loading' })); await ready()
|
||||||
|
})
|
||||||
|
it('rejects invalid totals at storage boundary and retains drafts when a transaction fails', async () => {
|
||||||
|
render(<PerformanceEditor {...props} />); await ready()
|
||||||
|
fill('Weight (kg)', '6'); fill('Total reps', '36')
|
||||||
|
const original = indexedDB.open.bind(indexedDB)
|
||||||
|
vi.spyOn(indexedDB, 'open').mockImplementation(() => { throw new Error('Storage write failed') })
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Storage write failed')
|
||||||
|
expect(screen.getByLabelText('Total reps').value).toBe('36')
|
||||||
|
indexedDB.open.mockImplementation(original)
|
||||||
|
const invalid = newPerformance(props.dateKey, 'morning', definition, props.prescription, 'emom-total')
|
||||||
|
invalid.rows[0] = { values: { reps: 1.5 }, load: { vestKg: 6 }, completed: true }
|
||||||
|
await expect(writePerformance(invalid)).rejects.toThrow(/reps/)
|
||||||
|
invalid.rows[0] = { values: { reps: 36 }, load: { vestKg: -1 }, completed: true }
|
||||||
|
await expect(writePerformance(invalid)).rejects.toThrow(/vest/)
|
||||||
|
expect(await readPerformance(props.dateKey, 'morning', definition.id, 'emom-total')).toBeNull()
|
||||||
|
})
|
||||||
|
it('suggests only aggregate history without saving or overwriting current input', async () => {
|
||||||
|
const prior = newPerformance('2026-10-27', 'morning', definition, props.prescription, 'emom-total')
|
||||||
|
prior.rows[0] = { values: { reps: 34 }, load: { vestKg: 6 }, completed: true }
|
||||||
|
await writePerformance(prior)
|
||||||
|
render(<PerformanceEditor {...props} />); await ready()
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Use previous session' })); await screen.findByText(/Suggested from/)
|
||||||
|
expect(screen.getByLabelText('Total reps').value).toBe('34')
|
||||||
|
expect(await readPerformance(props.dateKey, 'morning', definition.id, 'emom-total')).toBeNull()
|
||||||
|
fill('Total reps', '35'); fireEvent.click(screen.getByRole('button', { name: 'Use previous session' })); await screen.findByText('Current entries kept.')
|
||||||
|
expect(screen.getByLabelText('Total reps').value).toBe('35')
|
||||||
|
})
|
||||||
|
it('opens original minute history for explicit edits without changing the aggregate', async () => {
|
||||||
|
const old = newPerformance(props.dateKey, 'morning', definition, props.prescription)
|
||||||
|
old.rows[0] = { values: { reps: 4 }, load: { vestKg: 6 }, completed: true }
|
||||||
|
await writePerformance(old)
|
||||||
|
render(<PerformanceEditor {...props} />); await ready()
|
||||||
|
expect(screen.queryByLabelText('Minute 1 reps')).toBeNull()
|
||||||
|
const details = screen.getByText('Earlier records').closest('details')
|
||||||
|
details.open = true; fireEvent(details, new Event('toggle'))
|
||||||
|
await waitFor(() => expect(screen.getByLabelText('Minute 1 reps').value).toBe('4'))
|
||||||
|
fill('Minute 1 reps', '3')
|
||||||
|
const historicalForm = screen.getByLabelText('Minute 1 reps').closest('form')
|
||||||
|
fireEvent.click(within(historicalForm).getByRole('button', { name: 'Save performance' })); await within(historicalForm).findByText('Saved')
|
||||||
|
expect((await readPerformance(props.dateKey, 'morning', definition.id)).rows[0].values.reps).toBe(3)
|
||||||
|
expect(await readPerformance(props.dateKey, 'morning', definition.id, 'emom-total')).toBeNull()
|
||||||
|
})
|
||||||
+4
-106
@@ -1,108 +1,6 @@
|
|||||||
import { useEffect, useId, useState } from 'react'
|
import EmomTotalEditor from './EmomTotalEditor.jsx'
|
||||||
import { Button } from 'react-bootstrap'
|
import DetailedPerformanceEditor from './DetailedPerformanceEditor.jsx'
|
||||||
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 }) {
|
export default function PerformanceEditor(props) {
|
||||||
const id = useId()
|
return props.prescription.kind === 'emom' ? <EmomTotalEditor {...props} /> : <DetailedPerformanceEditor {...props} />
|
||||||
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>
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ vi.mock('./performanceStorage.js', () => ({
|
|||||||
}))
|
}))
|
||||||
vi.mock('./strengthStorage.js', () => ({ readStrengthEntry: vi.fn(async () => memory.legacy), writeStrengthEntry: vi.fn(async () => {}) }))
|
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 () => {}) }))
|
vi.mock('./hangGoalStorage.js', () => ({ readDailyHangGoal: vi.fn(async () => null), writeDailyHangGoal: vi.fn(async () => {}) }))
|
||||||
import PerformanceEditor from './PerformanceEditor.jsx'
|
import PerformanceEditor from './DetailedPerformanceEditor.jsx'
|
||||||
import App from './App.jsx'
|
import App from './App.jsx'
|
||||||
import { exerciseDefinitions, initialRoutine } from './data/index.js'
|
import { exerciseDefinitions, initialRoutine } from './data/index.js'
|
||||||
import { loadColumns, measurementColumns, newPerformance } from './performanceModel.js'
|
import { loadColumns, measurementColumns, newPerformance } from './performanceModel.js'
|
||||||
@@ -23,8 +23,9 @@ it.each(exerciseDefinitions)('shows only applicable controls for $id', async (de
|
|||||||
render(<PerformanceEditor {...props(definition.id)} />)
|
render(<PerformanceEditor {...props(definition.id)} />)
|
||||||
await ready()
|
await ready()
|
||||||
const row = definition.protocols?.includes('attempts') ? 'Attempt' : rx(definition.id).kind === 'emom' ? 'Minute' : 'Set'
|
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())
|
const measurementLabels = definition.measurement.endsWith('-per-side') ? [{ label: definition.measurement === 'repetitions-per-side' ? 'Reps (each side)' : 'Seconds (each side)' }] : measurementColumns(definition)
|
||||||
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 expected = [...measurementLabels, ...loadColumns(definition).filter((column) => !column.hidden)].map((column) => column.label.toLowerCase())
|
||||||
|
for (const label of ['reps', 'reps (each side)', 'seconds (each side)', '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}`)
|
const input = screen.queryByLabelText(`${row} 1 ${label}`)
|
||||||
expect(Boolean(input), `${definition.id}: ${label}`).toBe(expected.includes(label))
|
expect(Boolean(input), `${definition.id}: ${label}`).toBe(expected.includes(label))
|
||||||
}
|
}
|
||||||
@@ -51,19 +52,19 @@ it('completes filled rows on save, keeps incomplete drafts, then restores by dat
|
|||||||
expect(screen.getByLabelText('Set 1 reps').value).toBe('')
|
expect(screen.getByLabelText('Set 1 reps').value).toBe('')
|
||||||
expect(memory.records.size).toBe(1)
|
expect(memory.records.size).toBe(1)
|
||||||
})
|
})
|
||||||
it('logs independent left/right durations without repetitions and validates completed rows', async () => {
|
it('logs one duration for each side without repetitions and preserves blank drafts', async () => {
|
||||||
render(<PerformanceEditor {...props('bird-dog-hold')} />); await ready()
|
render(<PerformanceEditor {...props('bird-dog-hold')} />); await ready()
|
||||||
fill('Set 1 left seconds', 20);
|
fill('Set 1 seconds (each side)', '');
|
||||||
fireEvent.click(screen.getByRole('button', { name: 'Save performance' }))
|
fireEvent.click(screen.getByRole('button', { name: 'Save performance' }))
|
||||||
await screen.findByText('Saved')
|
await screen.findByText('Saved')
|
||||||
expect(memory.records.values().next().value.rows[0]).toMatchObject({ completed: false, values: { leftSeconds: 20, rightSeconds: null } })
|
expect(memory.records.values().next().value.rows[0]).toMatchObject({ completed: false, values: { leftSeconds: null, rightSeconds: null } })
|
||||||
fill('Set 1 right seconds', 25)
|
fill('Set 1 seconds (each side)', 25)
|
||||||
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
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 })
|
expect(memory.records.values().next().value.rows[0].values).toEqual({ leftSeconds: 25, rightSeconds: 25 })
|
||||||
})
|
})
|
||||||
it('keeps independent vest and dumbbell loads for each mixed-equipment set', async () => {
|
it('keeps independent vest and dumbbell loads for each mixed-equipment set', async () => {
|
||||||
render(<PerformanceEditor {...props('bulgarian-split-squat')} />); await ready()
|
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)
|
fill('Set 1 reps (each side)', 10); fill('Set 1 vest (kg)', 5); fill('Set 1 dumbbell (kg each)', 12)
|
||||||
fireEvent.click(screen.getByRole('button', { name: 'Add set' }))
|
fireEvent.click(screen.getByRole('button', { name: 'Add set' }))
|
||||||
fill('Set 2 vest (kg)', 0); fill('Set 2 dumbbell (kg each)', 14)
|
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')
|
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||||
@@ -153,14 +154,6 @@ it('snapshots the current target on first save without changing a previously sav
|
|||||||
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||||
expect(memory.records.values().next().value.prescription.goalDurationSec).toBe(180)
|
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 () => {
|
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)
|
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 }
|
original.rows[0] = { values: { reps: 10 }, load: { dumbbellKgEach: 8, dumbbellCount: 1 }, completed: true }
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { IDBFactory } from 'fake-indexeddb'
|
||||||
|
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||||
|
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||||
|
import PerformanceEditor from './PerformanceEditor.jsx'
|
||||||
|
import { exerciseDefinitions } from './data/index.js'
|
||||||
|
import { newPerformance } from './performanceModel.js'
|
||||||
|
import { readPerformance, writePerformance } from './performanceStorage.js'
|
||||||
|
const props = (id) => ({ dateKey: '2026-11-07', period: 'morning', definition: exerciseDefinitions.find((d) => d.id === id), prescription: { kind: 'sets', sets: { min: 3, max: 4 } } })
|
||||||
|
const ready = () => waitFor(() => expect(screen.getByRole('button', { name: 'Save performance' }).disabled).toBe(false))
|
||||||
|
const fill = (label, value) => fireEvent.change(screen.getByLabelText(label), { target: { value: String(value) } })
|
||||||
|
beforeEach(() => vi.stubGlobal('indexedDB', new IDBFactory()))
|
||||||
|
afterEach(() => { cleanup(); vi.unstubAllGlobals() })
|
||||||
|
it('saves preacher curls with one reps input per set and restores both sides accurately', async () => {
|
||||||
|
const p = props('single-arm-preacher-curl')
|
||||||
|
const view = render(<PerformanceEditor {...p} />); await ready()
|
||||||
|
expect(screen.queryByLabelText(/left reps|right reps/i)).toBeNull()
|
||||||
|
expect(screen.getAllByRole('spinbutton')).toHaveLength(2)
|
||||||
|
fill('Set 1 reps (each side)', 12); fill('Set 1 dumbbell (kg each)', 8)
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Add set' }))
|
||||||
|
expect(screen.getByLabelText('Set 2 reps (each side)').value).toBe('')
|
||||||
|
expect(screen.getByLabelText('Set 2 dumbbell (kg each)').value).toBe('8')
|
||||||
|
fill('Set 2 reps (each side)', 0)
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||||
|
const record = await readPerformance(p.dateKey, p.period, p.definition.id)
|
||||||
|
expect(record.rows[0]).toMatchObject({ values: { leftReps: 12, rightReps: 12 }, completed: true })
|
||||||
|
expect(record.rows[1]).toMatchObject({ values: { leftReps: 0, rightReps: 0 }, completed: true })
|
||||||
|
view.unmount(); render(<PerformanceEditor {...p} />); await ready()
|
||||||
|
expect(screen.getByLabelText('Set 1 reps (each side)').value).toBe('12')
|
||||||
|
fill('Set 1 reps (each side)', '')
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||||
|
expect((await readPerformance(p.dateKey, p.period, p.definition.id)).rows[0]).toMatchObject({ values: { leftReps: null, rightReps: null }, completed: false })
|
||||||
|
})
|
||||||
|
it.each([[10, 8], [10, null]])('preserves historical side values %s/%s until explicitly replaced', async (left, right) => {
|
||||||
|
const p = props('single-arm-preacher-curl')
|
||||||
|
const original = newPerformance(p.dateKey, p.period, p.definition, p.prescription)
|
||||||
|
original.rows[0] = { values: { leftReps: left, rightReps: right }, load: { dumbbellKgEach: 8, dumbbellCount: 1 }, completed: right !== null }
|
||||||
|
await writePerformance(original)
|
||||||
|
render(<PerformanceEditor {...p} />); await ready()
|
||||||
|
expect(screen.getByText(/Recorded: left 10, right/)).toBeTruthy()
|
||||||
|
expect(screen.getByLabelText('Set 1 reps (each side)').value).toBe('')
|
||||||
|
expect(await readPerformance(p.dateKey, p.period, p.definition.id)).toEqual(original)
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||||
|
expect(await readPerformance(p.dateKey, p.period, p.definition.id)).toEqual(original)
|
||||||
|
fill('Set 1 reps (each side)', 9)
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||||
|
expect((await readPerformance(p.dateKey, p.period, p.definition.id)).rows[0].values).toEqual({ leftReps: 9, rightReps: 9 })
|
||||||
|
})
|
||||||
|
it('records a hold through one seconds input and suggests both sides as an unsaved draft', async () => {
|
||||||
|
const p = props('bird-dog-hold')
|
||||||
|
const prior = newPerformance('2026-11-06', p.period, p.definition, p.prescription)
|
||||||
|
prior.rows[0] = { values: { leftSeconds: 25, rightSeconds: 25 }, load: {}, completed: true }
|
||||||
|
await writePerformance(prior)
|
||||||
|
const view = render(<PerformanceEditor {...p} />); await ready()
|
||||||
|
expect(screen.getAllByRole('spinbutton')).toHaveLength(1)
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Use previous session' })); await screen.findByText(/Suggested from/)
|
||||||
|
expect(screen.getByLabelText('Set 1 seconds (each side)').value).toBe('25')
|
||||||
|
expect(await readPerformance(p.dateKey, p.period, p.definition.id)).toBeNull()
|
||||||
|
fireEvent.click(screen.getByRole('button', { name: 'Save performance' })); await screen.findByText('Saved')
|
||||||
|
view.unmount(); render(<PerformanceEditor {...p} />); await ready()
|
||||||
|
expect(screen.getByLabelText('Set 1 seconds (each side)').value).toBe('25')
|
||||||
|
})
|
||||||
@@ -15,7 +15,7 @@ export function parseBackup(input) {
|
|||||||
let backup
|
let backup
|
||||||
try { backup = typeof input === 'string' ? JSON.parse(input) : structuredClone(input) }
|
try { backup = typeof input === 'string' ? JSON.parse(input) : structuredClone(input) }
|
||||||
catch { throw new Error('Invalid backup JSON.') }
|
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 (backup?.format !== 'workout-tracker' || ![1, 2, 3].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.')
|
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.
|
// Version 1 is the legacy adapter envelope with the two original stores.
|
||||||
for (const store of stores) {
|
for (const store of stores) {
|
||||||
@@ -26,7 +26,7 @@ export function parseBackup(input) {
|
|||||||
if (!entry || typeof entry.key !== 'string' || keys.has(entry.key) || !validJSON(entry.value)) throw new Error('Invalid or duplicate backup entry.')
|
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)
|
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 === '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 === 'performanceEntries' && (performanceError(entry.value) || entry.key !== performanceKey(entry.value.date, entry.value.period, entry.value.exerciseId, entry.value.format))) 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.')
|
if (store === 'routineOverrides' && entry.key === 'dailyHangGoalSec' && (!Number.isSafeInteger(entry.value) || entry.value <= 0)) throw new Error('Invalid hanging goal.')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -43,7 +43,7 @@ export async function exportBackup() {
|
|||||||
if (cursor.result) { data[name].push({ key: cursor.result.key, value: cursor.result.value }); cursor.result.continue() }
|
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.oncomplete = () => { db.close(); resolve(JSON.stringify({ format: 'workout-tracker', version: 3, reference: { exerciseDefinitions, initialRoutine }, stores: data })) }
|
||||||
tx.onerror = tx.onabort = () => { db.close(); reject(new Error('Could not export local data.')) }
|
tx.onerror = tx.onabort = () => { db.close(); reject(new Error('Could not export local data.')) }
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-2
@@ -4,12 +4,14 @@
|
|||||||
|
|
||||||
`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.
|
`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.
|
||||||
|
|
||||||
`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.
|
`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. New EMOM totals use format emom-total with one reps/vestKg row and a separate :emom-total key; historical ten-minute rows remain unchanged; durations and hangs never require reps.
|
||||||
|
|
||||||
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.
|
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 v3 for all three stores and v1/v2 compatibility readers, validation and atomic non-overwriting or explicit-replacement import. TASK-009 owns backup UI; this task adds no Settings controls.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
|
Per-side UI uses one shared reps/seconds field per set. It writes both stored side values only on explicit input; unequal/partial history remains unchanged and displays read-only values until replaced (ADR-021).
|
||||||
|
|||||||
@@ -43,10 +43,11 @@ function validDefinition(definition) {
|
|||||||
}
|
}
|
||||||
export function performanceError(record) {
|
export function performanceError(record) {
|
||||||
if (!record || record.schemaVersion !== 1 || !validDate(record.date) || !['morning', 'afternoon'].includes(record.period)
|
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)
|
|| !validDefinition(record.definition) || record.exerciseId !== record.definition.id || !['sets', 'emom', 'emom-total', '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.'
|
|| !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.definition.protocols ?? ['sets']).includes(record.format === 'emom-total' ? 'emom' : 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 === 'emom' && (!record.definition.protocols?.includes('emom') || !Number.isSafeInteger(record.prescription.rounds) || record.rows.length !== record.prescription.rounds)) return 'Invalid EMOM minutes.'
|
||||||
|
if (record.format === 'emom-total' && (record.rows.length !== 1 || record.definition.measurement !== 'repetitions' || record.definition.equipment.length !== 1 || record.definition.equipment[0] !== 'weighted-vest')) return 'Invalid EMOM total.'
|
||||||
if (record.format === 'attempts' && !record.definition.protocols?.includes('attempts')) return 'Invalid attempts.'
|
if (record.format === 'attempts' && !record.definition.protocols?.includes('attempts')) return 'Invalid attempts.'
|
||||||
for (const [index, row] of record.rows.entries()) {
|
for (const [index, row] of record.rows.entries()) {
|
||||||
const error = rowError(row, index, record.definition)
|
const error = rowError(row, index, record.definition)
|
||||||
|
|||||||
@@ -99,3 +99,13 @@ it('derives completion on explicit save while retaining drafts and rejecting inv
|
|||||||
original.rows[0].load.vestKg = -1
|
original.rows[0].load.vestKg = -1
|
||||||
expect(performanceError(preparePerformanceForSave(original))).toMatch(/vest/)
|
expect(performanceError(preparePerformanceForSave(original))).toMatch(/vest/)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('validates aggregate EMOM independently of historical minute-row shape', () => {
|
||||||
|
const record = newPerformance('2026-11-03', 'morning', def('pull-up'), prescription('pull-up'), 'emom-total')
|
||||||
|
expect(record.rows).toHaveLength(1)
|
||||||
|
record.rows[0] = { values: { reps: 36 }, load: { vestKg: 6 }, completed: true }
|
||||||
|
expect(performanceError(record)).toBeNull()
|
||||||
|
expect(performanceTotals(record)).toMatchObject({ reps: 36, volume: 216 })
|
||||||
|
record.rows.push(structuredClone(record.rows[0]))
|
||||||
|
expect(performanceError(record)).toMatch(/Invalid EMOM total/)
|
||||||
|
})
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { openLocalDatabase } from './localDatabase.js'
|
import { openLocalDatabase } from './localDatabase.js'
|
||||||
import { performanceError, signature } from './performanceModel.js'
|
import { performanceError, signature } from './performanceModel.js'
|
||||||
|
|
||||||
export const performanceKey = (date, period, exerciseId) => `${date}:${period}:${exerciseId}`
|
export const performanceKey = (date, period, exerciseId, format) => `${date}:${period}:${exerciseId}${format === 'emom-total' ? ':emom-total' : ''}`
|
||||||
async function transaction(mode, action) {
|
async function transaction(mode, action) {
|
||||||
const db = await openLocalDatabase()
|
const db = await openLocalDatabase()
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
@@ -15,15 +15,15 @@ async function transaction(mode, action) {
|
|||||||
tx.onerror = tx.onabort = () => { db.close(); reject(new Error('Could not access detailed performance storage. Your changes were not saved.')) }
|
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) {
|
export async function readPerformance(date, period, exerciseId, format) {
|
||||||
const record = await transaction('readonly', (store) => store.get(performanceKey(date, period, exerciseId)))
|
const record = await transaction('readonly', (store) => store.get(performanceKey(date, period, exerciseId, format)))
|
||||||
if (record && performanceError(record)) throw new Error('The saved performance record is invalid or unsupported.')
|
if (record && performanceError(record)) throw new Error('The saved performance record is invalid or unsupported.')
|
||||||
return record
|
return record
|
||||||
}
|
}
|
||||||
export async function writePerformance(record) {
|
export async function writePerformance(record) {
|
||||||
const error = performanceError(record)
|
const error = performanceError(record)
|
||||||
if (error) throw new Error(error)
|
if (error) throw new Error(error)
|
||||||
await transaction('readwrite', (store) => store.put(record, performanceKey(record.date, record.period, record.exerciseId)))
|
await transaction('readwrite', (store) => store.put(record, performanceKey(record.date, record.period, record.exerciseId, record.format)))
|
||||||
}
|
}
|
||||||
export async function previousPerformance(date, period, definition, format) {
|
export async function previousPerformance(date, period, definition, format) {
|
||||||
const records = await transaction('readonly', (store) => store.index('exercisePeriodFormat').getAll([definition.id, period, format]))
|
const records = await transaction('readonly', (store) => store.index('exercisePeriodFormat').getAll([definition.id, period, format]))
|
||||||
|
|||||||
@@ -123,3 +123,9 @@ it('reports blocked v2 upgrade without overwriting existing data', async () => {
|
|||||||
expect(await readDailyHangGoal()).toBe(180)
|
expect(await readDailyHangGoal()).toBe(180)
|
||||||
expect(await readStrengthEntry('2026-10-27', 'pull-up')).toMatchObject({ totalReps: 36, externalKg: 6 })
|
expect(await readStrengthEntry('2026-10-27', 'pull-up')).toMatchObject({ totalReps: 36, externalKg: 6 })
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('still imports the previous v2 envelope without changing detailed records', async () => {
|
||||||
|
const record = completedEntry('2026-11-03')
|
||||||
|
await importBackup({ format: 'workout-tracker', version: 2, stores: { routineOverrides: [], strengthEntries: [], performanceEntries: [{ key: '2026-11-03:morning:front-plank', value: record }] } })
|
||||||
|
expect(await readPerformance(record.date, record.period, record.exerciseId)).toEqual(record)
|
||||||
|
})
|
||||||
|
|||||||
@@ -141,3 +141,10 @@ h1 { margin: .25rem 0 .55rem; font-size: clamp(2.2rem, 4vw, 3.25rem); line-heigh
|
|||||||
.performance-actions > button { min-height: 44px; }
|
.performance-actions > button { min-height: 44px; }
|
||||||
.performance-actions { align-items: stretch; }
|
.performance-actions { align-items: stretch; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.emom-total-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: .6rem; }
|
||||||
|
.emom-total-fields label { min-width: 0; font-size: .8rem; color: #52665a; }
|
||||||
|
.emom-total-fields input { display: block; width: 100%; min-width: 0; min-height: 40px; padding: .3rem .4rem; border: 1px solid #b6c7b8; border-radius: 6px; color: #254838; }
|
||||||
|
@media (max-width: 360px) { .emom-total-fields { grid-template-columns: minmax(0, 1fr); } }
|
||||||
|
|
||||||
|
.recorded-sides { grid-column: 1 / -1; margin: .2rem 0; font-size: .8rem; color: #52665a; }
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
import { defineConfig } from 'vite'
|
import { defineConfig } from 'vite'
|
||||||
import react from '@vitejs/plugin-react'
|
import react from '@vitejs/plugin-react'
|
||||||
|
import { configDefaults } from 'vitest/config'
|
||||||
|
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [react()],
|
plugins: [react()],
|
||||||
test: {
|
test: {
|
||||||
environment: 'jsdom',
|
environment: 'jsdom',
|
||||||
|
exclude: [...configDefaults.exclude, '.test-worktrees/**'],
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user