Compare commits
3
Commits
d6f9103906
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6272a93d8a | ||
|
|
12fdf41516 | ||
|
|
c0a3a1faa7 |
No files matched your search
@@ -1,484 +0,0 @@
|
||||
---
|
||||
title: Domain Model & OOP Architecture Specification
|
||||
description: Canonical domain model, aggregates, entities, value objects, behavioral contracts, and use cases for Praxis.
|
||||
version: 1.0.1
|
||||
status: Approved Domain Baseline
|
||||
date: 2026-09-24
|
||||
tags:
|
||||
- domain-model
|
||||
- ddd
|
||||
- clean-architecture
|
||||
- oop
|
||||
---
|
||||
|
||||
# Domain Model & OOP Architecture Specification
|
||||
|
||||
> Canonical Domain Model, Object-Oriented Design, and Clean Architecture Specification for **Praxis**.
|
||||
|
||||
| Document Attribute | Specification |
|
||||
| :--- | :--- |
|
||||
| **Document Version** | `1.0.1` |
|
||||
| **Status** | Approved Domain Baseline |
|
||||
| **Last Updated** | 2026-09-24 |
|
||||
| **SRS Baseline** | [`praxis-srs-v1.0.2.md`](praxis-srs-v1.0.2.md) |
|
||||
| **Previous Revision** | [`praxis-domain-model.md`](praxis-domain-model.md) (`v1.0.0`) |
|
||||
|
||||
---
|
||||
|
||||
> [!NOTE]
|
||||
> ### Summary of Changes from v1.0.0
|
||||
> 1. **Snapshot vs. Execution Mutability**: Clarified that `WorkoutSession` contains an immutable `SessionPrescriptionSnapshot` frozen upon initiation, while its execution performance state remains mutable until explicitly finalized (`Completed`, `Partially_Completed`, `Skipped`), at which point the entire session locks.
|
||||
> 2. **Unified Prescription Snapshot**: Grouped frozen prescriptions and activities under a single session-level `SessionPrescriptionSnapshot` value object rather than scattering snapshot copies across individual performances.
|
||||
> 3. **`Exercise` Promoted to Aggregate Root**: Recognized `Exercise` as an independent Aggregate Root with its own lifecycle, referenced by ID from prescriptions and performances.
|
||||
> 4. **`User` Clarified as Ownership Entity**: Modeled `User` as an identity and profile entity, avoiding an oversized aggregate that contains all routines and sessions.
|
||||
> 5. **`SessionActivity` & `ActivityPerformance` Entities**: Formally modeled non-set activities (warm-ups, cardio) across both the prescription layer (`SessionActivity`) and execution layer (`ActivityPerformance`).
|
||||
> 6. **`DayKind` Cleanup**: Removed `Active Recovery` from `DayKind` (`Workout`, `Rest`, `Unscheduled`). Active recovery is represented as an activity or ad-hoc session.
|
||||
> 7. **Phase Progression Model**: Broadened `Phase` from a narrow integer set modifier to a declarative specification supporting prescription overrides over defined week windows.
|
||||
> 8. **Single-Active-Routine Invariant Placement**: Transferred the single-active-routine rule from `Routine` aggregate invariant to an Application Policy orchestrated by `ActivateRoutineUseCase`.
|
||||
> 9. **Naming & Substitution Clarification**: Renamed to `planned_exercise_id` and `performed_exercise_id`. Established invariant: performance of substituted exercises contributes strictly to the `performed_exercise_id`'s historical log.
|
||||
> 10. **Targeted Method Encapsulation**: Refactored `session.record_set(performance_id, set_data)` and `session.remove_set(performance_id, set_id)` to target performances and sets by ID.
|
||||
> 11. **Metric Validation on `SetPerformance`**: Added metric type validation enforcing required fields (e.g., reps for weightlifting, duration for timed planks) to prevent nonsensical data combinations.
|
||||
> 12. **Effort Scoping**: Scoped effort tracking strictly to optional `RIR` for MVP; deferred RPE.
|
||||
> 13. **Milestone Scoping (1RM Deferred)**: Moved 1RM/PR estimation out of the core MVP calculation layer into Milestone 2, keeping MVP focused on factual history, metric-dependent workload, and adherence.
|
||||
> 14. **Domain Behavioral Contracts**: Added explicit pre/post-conditions and state transition matrices for each aggregate.
|
||||
|
||||
---
|
||||
|
||||
## 1. Domain Topology & Class Diagram
|
||||
|
||||
Praxis enforces strict separation across the three temporal layers (**Prescription**, **Performance**, **Analysis**) while maintaining decoupled aggregate boundaries:
|
||||
|
||||
```mermaid
|
||||
classDiagram
|
||||
direction TB
|
||||
|
||||
class User {
|
||||
<<Entity / Identity>>
|
||||
+UserId id
|
||||
+ExternalIdentityId external_id
|
||||
+UserProfile profile
|
||||
+DateTime created_at
|
||||
}
|
||||
|
||||
class Exercise {
|
||||
<<Aggregate Root>>
|
||||
+ExerciseId id
|
||||
+UserId author_id
|
||||
+String name
|
||||
+MuscleGroup category
|
||||
+Equipment equipment
|
||||
+MetricType default_metric
|
||||
+String instructions
|
||||
+update_metadata(name, category, equipment, default_metric, instructions)
|
||||
}
|
||||
|
||||
class Routine {
|
||||
<<Aggregate Root>>
|
||||
+RoutineId id
|
||||
+UserId owner_id
|
||||
+String name
|
||||
+Boolean is_active
|
||||
+DateTime activated_at
|
||||
+List~Phase~ phases
|
||||
+Map~Weekday, WorkoutDay~ schedule
|
||||
+mark_active(now: DateTime)
|
||||
+mark_inactive()
|
||||
+get_current_phase(for_date: Date) Phase
|
||||
+configure_workout_day(weekday, label, kind)
|
||||
+add_prescription(weekday, prescription)
|
||||
+remove_prescription(weekday, prescription_id)
|
||||
+reorder_prescriptions(weekday, ordered_ids)
|
||||
}
|
||||
|
||||
class WorkoutDay {
|
||||
<<Entity>>
|
||||
+WorkoutDayId id
|
||||
+Weekday weekday
|
||||
+DayKind kind
|
||||
+String label
|
||||
+List~ExercisePrescription~ prescriptions
|
||||
+List~SessionActivity~ activities
|
||||
}
|
||||
|
||||
class ExercisePrescription {
|
||||
<<Entity>>
|
||||
+PrescriptionId id
|
||||
+ExerciseId exercise_id
|
||||
+Int target_sets
|
||||
+RepRange rep_range
|
||||
+Duration target_duration
|
||||
+Weight target_weight
|
||||
+Boolean is_unilateral
|
||||
+Int order_index
|
||||
+String notes
|
||||
}
|
||||
|
||||
class SessionActivity {
|
||||
<<Entity>>
|
||||
+ActivityId id
|
||||
+String name
|
||||
+String description
|
||||
+Duration target_duration
|
||||
+Int order_index
|
||||
}
|
||||
|
||||
class WorkoutSession {
|
||||
<<Aggregate Root>>
|
||||
+SessionId id
|
||||
+UserId user_id
|
||||
+RoutineId routine_id
|
||||
+Date session_date
|
||||
+SessionStatus status
|
||||
+DateTime started_at
|
||||
+DateTime finished_at
|
||||
+SessionPrescriptionSnapshot prescription_snapshot
|
||||
+List~ExercisePerformance~ exercises
|
||||
+List~ActivityPerformance~ activities
|
||||
+String notes
|
||||
+record_set(performance_id, set_data) SetPerformance
|
||||
+remove_set(performance_id, set_id)
|
||||
+substitute_exercise(performance_id, new_exercise_id, reason)
|
||||
+add_ad_hoc_exercise(exercise_id) ExercisePerformance
|
||||
+record_activity(activity_perf_id, actual_duration, actual_dist, notes)
|
||||
+finish(policy: CompletionPolicy) CompletionResult
|
||||
+skip(reason: String)
|
||||
}
|
||||
|
||||
class SessionPrescriptionSnapshot {
|
||||
<<Value Object>>
|
||||
+RoutineId routine_id
|
||||
+String routine_name
|
||||
+String phase_name
|
||||
+List~PrescriptionSnapshotItem~ exercise_prescriptions
|
||||
+List~ActivitySnapshotItem~ activities
|
||||
}
|
||||
|
||||
class ExercisePerformance {
|
||||
<<Entity>>
|
||||
+ExercisePerformanceId id
|
||||
+ExerciseId planned_exercise_id
|
||||
+ExerciseId performed_exercise_id
|
||||
+PrescriptionId prescription_item_id
|
||||
+List~SetPerformance~ sets
|
||||
+SubstitutionContext substitution
|
||||
+String notes
|
||||
+append_set(set_data) SetPerformance
|
||||
+remove_set(set_id)
|
||||
+calculate_workload(metric_type) Workload
|
||||
}
|
||||
|
||||
class SetPerformance {
|
||||
<<Entity>>
|
||||
+SetPerformanceId id
|
||||
+Int actual_reps
|
||||
+Weight actual_weight
|
||||
+Duration actual_duration
|
||||
+RIR reps_in_reserve
|
||||
+String notes
|
||||
}
|
||||
|
||||
class ActivityPerformance {
|
||||
<<Entity>>
|
||||
+ActivityPerformanceId id
|
||||
+ActivityId planned_activity_id
|
||||
+String name
|
||||
+Duration actual_duration
|
||||
+Distance actual_distance
|
||||
+Boolean is_completed
|
||||
+String notes
|
||||
}
|
||||
|
||||
User "1" --> "*" Routine : owns
|
||||
User "1" --> "*" WorkoutSession : performs
|
||||
User "1" --> "*" Exercise : authors
|
||||
|
||||
Routine "1" *-- "7" WorkoutDay : contains
|
||||
WorkoutDay "1" *-- "*" ExercisePrescription : prescribes
|
||||
WorkoutDay "1" *-- "*" SessionActivity : prescribes
|
||||
ExercisePrescription "1" --> "1" Exercise : references
|
||||
|
||||
WorkoutSession "1" *-- "1" SessionPrescriptionSnapshot : freezes
|
||||
WorkoutSession "1" *-- "*" ExercisePerformance : tracks
|
||||
WorkoutSession "1" *-- "*" ActivityPerformance : tracks
|
||||
ExercisePerformance "1" *-- "*" SetPerformance : logs
|
||||
ExercisePerformance "1" --> "1" Exercise : performed_as
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Classification: Entities vs. Value Objects
|
||||
|
||||
### 2.1. Value Objects
|
||||
|
||||
| Value Object | Structural Fields | Invariants & Validation Rules |
|
||||
| :--- | :--- | :--- |
|
||||
| `UserId` | `UUID / String` | Immutable non-empty opaque string. |
|
||||
| `ExerciseId` | `UUID / String` | Unique identifier for canonical exercise movements. |
|
||||
| `RoutineId` | `UUID / String` | Unique identifier for routine templates. |
|
||||
| `SessionId` | `UUID / String` | Unique identifier for workout sessions. |
|
||||
| `Weekday` | `Enum: Monday .. Sunday` | ISO-8601 integer representation (1–7). |
|
||||
| `DayKind` | `Enum: Workout, Rest, Unscheduled` | Primary calendar classification. |
|
||||
| `MetricType` | `Enum: RepsWeight, Duration, DistanceDuration` | Governs measurement and validation rules. |
|
||||
| `RepRange` | `min_reps: Int, max_reps: Int` | `1 <= min_reps <= max_reps <= 200`. For fixed reps, `min_reps == max_reps`. |
|
||||
| `Weight` | `value: Decimal, unit: Unit (KG, LBS)` | `value >= 0.0`. Implements lossless `.to_kg()` conversion. |
|
||||
| `Duration` | `seconds: Int` | `seconds >= 0`. Whole-second granularity. |
|
||||
| `Distance` | `meters: Decimal` | `meters >= 0.0`. |
|
||||
| `RIR` | `value: Int` | `0 <= value <= 5` (Reps In Reserve). |
|
||||
| `Phase` | `name: String, start_week: Int, end_week: Optional[Int], target_sets_override: Optional[Int]` | `start_week >= 1`. If `end_week` present, `start_week <= end_week`. |
|
||||
| `SessionPrescriptionSnapshot` | Frozen copy of prescriptions, activities, and phase metadata | Fully immutable value object materialised at session initiation. |
|
||||
| `PrescriptionSnapshotItem` | `prescription_id, exercise_id, exercise_name, target_sets, rep_range, target_duration, target_weight, order_index` | Immutable representation of a single prescribed movement. |
|
||||
| `ActivitySnapshotItem` | `activity_id, name, description, target_duration, order_index` | Immutable representation of a prescribed session activity. |
|
||||
| `SubstitutionContext` | `original_exercise_id: ExerciseId, reason: String, substituted_at: DateTime` | Immutable audit trail of an on-the-fly exercise change. |
|
||||
|
||||
### 2.2. Entities & Aggregate Roots
|
||||
|
||||
1. **`Exercise` (Aggregate Root)**: Canonical movement definition with name, muscle group, equipment, default metric hint, and instructional cues.
|
||||
2. **`Routine` (Aggregate Root)**: Reusable schedule template containing 7 `WorkoutDay` entities and progression `Phase` definitions.
|
||||
3. **`WorkoutSession` (Aggregate Root)**: Historical training occurrence containing a frozen prescription snapshot and executing child entities (`ExercisePerformance`, `ActivityPerformance`, `SetPerformance`).
|
||||
4. **`User` (Identity Entity)**: System boundary actor owning user preferences and domain references.
|
||||
|
||||
---
|
||||
|
||||
## 3. Aggregate Boundaries & Encapsulation Rules
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
subgraph Aggregate_Routine["Aggregate Root: Routine"]
|
||||
R[Routine] --> WD[WorkoutDay]
|
||||
WD --> EP[ExercisePrescription]
|
||||
WD --> SA[SessionActivity]
|
||||
end
|
||||
|
||||
subgraph Aggregate_Exercise["Aggregate Root: Exercise"]
|
||||
EX[Exercise]
|
||||
end
|
||||
|
||||
subgraph Aggregate_WorkoutSession["Aggregate Root: WorkoutSession"]
|
||||
WS[WorkoutSession] --> SPS[SessionPrescriptionSnapshot]
|
||||
WS --> EPF[ExercisePerformance]
|
||||
WS --> APF[ActivityPerformance]
|
||||
EPF --> SP[SetPerformance]
|
||||
end
|
||||
|
||||
Aggregate_Routine -.->|SnapshotFactory materializes| Aggregate_WorkoutSession
|
||||
Aggregate_WorkoutSession -.->|References by ExerciseId| Aggregate_Exercise
|
||||
Aggregate_Routine -.->|References by ExerciseId| Aggregate_Exercise
|
||||
```
|
||||
|
||||
### Boundary Rule 1: `Routine` Aggregate
|
||||
- Encapsulates `WorkoutDay`, `ExercisePrescription`, `SessionActivity`, and `Phase`.
|
||||
- Prescriptions cannot be modified from outside without passing through `Routine` methods.
|
||||
- Has **zero knowledge** of past or active `WorkoutSession` instances.
|
||||
- Does not enforce global uniqueness of the active routine; activation state is modified via `mark_active()` and orchestrated by `ActivateRoutineUseCase`.
|
||||
|
||||
### Boundary Rule 2: `WorkoutSession` Aggregate
|
||||
- Encapsulates `SessionPrescriptionSnapshot`, `ExercisePerformance`, `SetPerformance`, and `ActivityPerformance`.
|
||||
- All modifications to performance state (recording sets, removing sets, swapping exercises, checking off activities) must be executed through methods on `WorkoutSession`.
|
||||
- **Targeted Operations**: Sets are recorded against a specific `ExercisePerformanceId`, preventing ambiguity between planned and substituted exercises.
|
||||
- **Set Identity Invariant**: Sets possess a unique `SetPerformanceId`. Removing a set operates on `set_id`; display order numbers are derived dynamically from sequence position.
|
||||
|
||||
### Boundary Rule 3: `Exercise` Aggregate
|
||||
- Independent aggregate root. Modifying an exercise's instructions or category never mutates existing prescriptions or historical performances (which store snapshot names and IDs).
|
||||
|
||||
---
|
||||
|
||||
## 4. Metric Validation on `SetPerformance`
|
||||
|
||||
To prevent data corruption (e.g. logging 70kg on a timed Plank), `SetPerformance` creation is governed by a **Metric Validation Policy**:
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
M[MetricType of Exercise]
|
||||
M -->|RepsWeight| V1{actual_reps != null?}
|
||||
V1 -->|Yes| OK1[Valid Reps/Weight Set]
|
||||
V1 -->|No| ERR1[Error: Repetitions required]
|
||||
|
||||
M -->|Duration| V2{actual_duration != null?}
|
||||
V2 -->|Yes| OK2[Valid Timed Set]
|
||||
V2 -->|No| ERR2[Error: Duration required]
|
||||
|
||||
M -->|DistanceDuration| V3{duration or distance != null?}
|
||||
V3 -->|Yes| OK3[Valid Distance/Duration Set]
|
||||
V3 -->|No| ERR3[Error: Duration or distance required]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Domain Behavioral Contracts & State Machines
|
||||
|
||||
### 5.1. `WorkoutSession` Lifecycle State Machine
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> In_Progress: SessionSnapshotFactory / InitiateWorkout
|
||||
|
||||
In_Progress --> In_Progress: record_set()
|
||||
In_Progress --> In_Progress: remove_set()
|
||||
In_Progress --> In_Progress: substitute_exercise()
|
||||
In_Progress --> In_Progress: add_ad_hoc_exercise()
|
||||
In_Progress --> In_Progress: record_activity()
|
||||
|
||||
In_Progress --> Completed: finish() [100% set-intent achieved]
|
||||
In_Progress --> Partially_Completed: finish() [>0% sets logged, some omitted]
|
||||
In_Progress --> Skipped: skip(reason)
|
||||
|
||||
Completed --> [*]: Locked (Immutable)
|
||||
Partially_Completed --> [*]: Locked (Immutable)
|
||||
Skipped --> [*]: Locked (Immutable)
|
||||
```
|
||||
|
||||
### 5.2. Behavioral Contracts
|
||||
|
||||
#### `WorkoutSession.record_set`
|
||||
- **Signature**: `record_set(performance_id: ExercisePerformanceId, set_data: SetData) -> SetPerformance`
|
||||
- **Preconditions**:
|
||||
- `self.status == SessionStatus.In_Progress` (error if finalized).
|
||||
- `performance_id` exists within `self.exercises`.
|
||||
- `set_data` satisfies `MetricValidationPolicy` for the exercise's `MetricType`.
|
||||
- **Postconditions**:
|
||||
- New `SetPerformance` instance appended to matching `ExercisePerformance.sets`.
|
||||
- Returns created `SetPerformance`.
|
||||
|
||||
#### `WorkoutSession.remove_set`
|
||||
- **Signature**: `remove_set(performance_id: ExercisePerformanceId, set_id: SetPerformanceId) -> None`
|
||||
- **Preconditions**:
|
||||
- `self.status == SessionStatus.In_Progress`.
|
||||
- `set_id` exists in `performance_id`.
|
||||
- **Postconditions**:
|
||||
- `SetPerformance` matching `set_id` is removed.
|
||||
|
||||
#### `WorkoutSession.substitute_exercise`
|
||||
- **Signature**: `substitute_exercise(performance_id: ExercisePerformanceId, new_exercise_id: ExerciseId, reason: String) -> None`
|
||||
- **Preconditions**:
|
||||
- `self.status == SessionStatus.In_Progress`.
|
||||
- `performance_id.sets` is empty (substitution must occur before logging sets on that performance).
|
||||
- **Postconditions**:
|
||||
- `performance.performed_exercise_id = new_exercise_id`.
|
||||
- `performance.substitution = SubstitutionContext(original_exercise_id, reason, now)`.
|
||||
|
||||
#### `WorkoutSession.finish`
|
||||
- **Signature**: `finish(completion_policy: CompletionPolicy, override_status: Optional[SessionStatus] = None) -> CompletionResult`
|
||||
- **Preconditions**:
|
||||
- `self.status == SessionStatus.In_Progress`.
|
||||
- **Postconditions**:
|
||||
- If `override_status` is provided: `self.status = override_status`.
|
||||
- Else: `self.status = completion_policy.evaluate(self).suggested_status`.
|
||||
- `self.finished_at = now`.
|
||||
- Session becomes locked against further mutation.
|
||||
|
||||
#### `WorkoutSession.skip`
|
||||
- **Signature**: `skip(reason: String) -> None`
|
||||
- **Preconditions**:
|
||||
- `self.status == SessionStatus.In_Progress` and no sets have been logged.
|
||||
- **Postconditions**:
|
||||
- `self.status = SessionStatus.Skipped`.
|
||||
- `self.finished_at = now`.
|
||||
- `self.notes = reason`.
|
||||
|
||||
---
|
||||
|
||||
## 6. Domain Policies & Derivations
|
||||
|
||||
### 6.1. `SessionSnapshotFactory`
|
||||
Materializes a `WorkoutSession` from a scheduled `WorkoutDay`:
|
||||
1. Determines elapsed weeks since routine activation:
|
||||
$$\text{week\_index} = \left\lfloor \frac{\text{session\_date} - \text{routine.activated\_at.date}}{7} \right\rfloor + 1$$
|
||||
2. Queries `routine.get_current_phase(session_date)` to resolve active phase and target set overrides (e.g. 3 sets vs 4 sets).
|
||||
3. Freezes `SessionPrescriptionSnapshot` containing all prescribed exercises and activities.
|
||||
4. Generates an initial `ExercisePerformance` entity for each prescribed exercise, setting both `planned_exercise_id` and `performed_exercise_id` to the prescribed exercise ID.
|
||||
5. Generates an initial `ActivityPerformance` for each prescribed activity.
|
||||
6. Returns `WorkoutSession` in `In_Progress` status.
|
||||
|
||||
### 6.2. `CompletionPolicy` (Set-Intent Evaluation)
|
||||
Evaluates whether a session achieved full or partial completion:
|
||||
- **Exercise Complete**: Evaluated as complete if $\text{count}(\text{valid sets logged}) \ge \text{target sets from snapshot}$.
|
||||
- **Suggested Status**:
|
||||
- If $100\%$ of prescribed exercises are complete $\rightarrow$ `Completed`.
|
||||
- If $>0$ sets logged but $<100\%$ prescribed exercises complete $\rightarrow$ `Partially_Completed`.
|
||||
|
||||
### 6.3. `WorkloadCalculator`
|
||||
Calculates metric-dependent physical workload:
|
||||
- **Weighted Volume**: $\sum_{i} (\text{actual\_reps}_i \times \text{actual\_weight}_i\text{.to\_kg()})$
|
||||
- **Duration Workload**: $\sum_{i} \text{actual\_duration}_i\text{.seconds}$
|
||||
- **Distance Workload**: $\sum_{i} \text{actual\_distance}_i\text{.meters}$
|
||||
|
||||
### 6.4. `AdherenceCalculator`
|
||||
Calculates objective habit consistency over a window $[T_{\text{start}}, T_{\text{end}}]$:
|
||||
$$\text{Scheduled Count} = N_{\text{scheduled}}$$
|
||||
$$\text{Completion Rate} = \frac{N_{\text{completed}}}{N_{\text{scheduled}}}$$
|
||||
$$\text{Partial Rate} = \frac{N_{\text{partially\_completed}}}{N_{\text{scheduled}}}$$
|
||||
$$\text{Skip Rate} = \frac{N_{\text{skipped}}}{N_{\text{scheduled}}}$$
|
||||
$$\text{Set Adherence Rate} = \frac{\sum \text{Sets Performed}}{\sum \text{Sets Prescribed}}$$
|
||||
|
||||
---
|
||||
|
||||
## 7. Application Use Cases (Interactors)
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
autonumber
|
||||
actor User
|
||||
participant UC as ActivateRoutineUseCase
|
||||
participant RRepo as RoutineRepository
|
||||
|
||||
User->>UC: execute(target_routine_id)
|
||||
UC->>RRepo: get_active(user_id)
|
||||
opt Active routine exists
|
||||
RRepo-->>UC: current_active_routine
|
||||
UC->>current_active_routine: mark_inactive()
|
||||
UC->>RRepo: save(current_active_routine)
|
||||
end
|
||||
UC->>RRepo: get_by_id(target_routine_id)
|
||||
RRepo-->>UC: target_routine
|
||||
UC->>target_routine: mark_active(now)
|
||||
UC->>RRepo: save(target_routine)
|
||||
UC-->>User: Success (target_routine activated)
|
||||
```
|
||||
|
||||
### Complete Use Case Inventory
|
||||
|
||||
1. **`CreateRoutineUseCase(user_id, name, schedule_spec, phases)`**: Creates new `Routine` aggregate.
|
||||
2. **`ActivateRoutineUseCase(user_id, routine_id)`**: Enforces the single-active-routine policy by deactivating the current active routine before activating the target routine.
|
||||
3. **`InitiateWorkoutUseCase(user_id, date)`**: Calls `SessionSnapshotFactory` and saves new `WorkoutSession`.
|
||||
4. **`RecordSetUseCase(user_id, session_id, performance_id, set_data)`**: Appends validated set to performance.
|
||||
5. **`RemoveSetUseCase(user_id, session_id, performance_id, set_id)`**: Removes set by identity.
|
||||
6. **`SubstituteExerciseUseCase(user_id, session_id, performance_id, new_exercise_id, reason)`**: Records substitution.
|
||||
7. **`AddAdHocExerciseUseCase(user_id, session_id, exercise_id)`**: Appends unscheduled exercise to active session.
|
||||
8. **`RecordActivityUseCase(user_id, session_id, activity_perf_id, actual_duration, actual_dist, notes)`**: Logs activity completion.
|
||||
9. **`FinishWorkoutUseCase(user_id, session_id, override_status=None)`**: Evaluates completion via `CompletionPolicy` and finalizes session.
|
||||
10. **`SkipWorkoutUseCase(user_id, date, reason)`**: Records skipped session.
|
||||
11. **`QueryWeeklyCalendarUseCase(user_id, start_date, end_date)`**: Returns projected `ScheduledWorkout` items alongside recorded `WorkoutSession` instances.
|
||||
12. **`QueryExerciseHistoryUseCase(user_id, exercise_id)`**: Returns historical performances where `performed_exercise_id == exercise_id`.
|
||||
13. **`CalculateAdherenceUseCase(user_id, start_date, end_date)`**: Generates factual adherence metrics.
|
||||
|
||||
---
|
||||
|
||||
## 8. Clean Architecture Dependency Graph
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
subgraph Infrastructure["Infrastructure Layer"]
|
||||
FastAPI[FastAPI Controllers / REST API]
|
||||
AuthAdapter[Authelia Reverse-Proxy Header Adapter]
|
||||
SQLRepo[PostgreSQL / SQLite Repositories]
|
||||
end
|
||||
|
||||
subgraph Application["Application Layer (Use Cases)"]
|
||||
UC[Application Use Cases]
|
||||
DTO[Data Transfer Objects / Schemas]
|
||||
end
|
||||
|
||||
subgraph Domain["Domain Layer (Pure Business Rules)"]
|
||||
Agg_Routine[Routine Aggregate]
|
||||
Agg_Session[WorkoutSession Aggregate]
|
||||
Agg_Exercise[Exercise Aggregate]
|
||||
DomainServices[Domain Policies & Calculators]
|
||||
Ports[Repository & Auth Ports]
|
||||
end
|
||||
|
||||
FastAPI --> UC
|
||||
UC --> Domain
|
||||
UC --> Ports
|
||||
AuthAdapter --> Ports
|
||||
SQLRepo --> Ports
|
||||
```
|
||||
+315
-341
@@ -1,45 +1,77 @@
|
||||
---
|
||||
title: Domain Model & OOP Architecture Specification — v1.0.0 Draft (Archived)
|
||||
description: Initial domain model specification draft for Praxis, preserved for historical and comparative reference.
|
||||
version: 1.0.0
|
||||
status: Superseded / Archive
|
||||
title: Domain Model & OOP Architecture Specification
|
||||
description: Canonical domain model, aggregates, entities, value objects, behavioral contracts, and use cases for Praxis.
|
||||
version: 1.0.1
|
||||
status: Approved Domain Baseline
|
||||
date: 2026-09-24
|
||||
tags:
|
||||
- domain-model
|
||||
- ddd
|
||||
- archive
|
||||
- clean-architecture
|
||||
- oop
|
||||
---
|
||||
|
||||
# Domain Model & OOP Architecture Specification — v1.0.0 Draft (Archived)
|
||||
# Domain Model & OOP Architecture Specification
|
||||
|
||||
> [!WARNING]
|
||||
> **Superseded Specification**: This document is an initial draft preserved for historical reference and auditability. The canonical, active specification is maintained in [`praxis-domain-model-v1.0.1.md`](praxis-domain-model-v1.0.1.md).
|
||||
> Canonical Domain Model, Object-Oriented Design, and Clean Architecture Specification for **Praxis**.
|
||||
|
||||
| Document Attribute | Specification |
|
||||
| :--- | :--- |
|
||||
| **Document Version** | `1.0.0` |
|
||||
| **Status** | Superseded / Historical Archive |
|
||||
| **Date** | 2026-09-24 |
|
||||
| **Canonical Baseline** | [`praxis-domain-model-v1.0.1.md`](praxis-domain-model-v1.0.1.md) |
|
||||
| **Prerequisite SRS** | [`praxis-srs.md`](praxis-srs.md) |
|
||||
| **Document Version** | `1.0.1` |
|
||||
| **Status** | Approved Domain Baseline |
|
||||
| **Last Updated** | 2026-09-24 |
|
||||
| **SRS Baseline** | [`praxis-srs-v1.0.2.md`](praxis-srs-v1.0.2.md) |
|
||||
| **Previous Revision** | [`praxis-domain-model.md`](praxis-domain-model.md) (`v1.0.0`) |
|
||||
|
||||
---
|
||||
|
||||
## 1. Domain Topology & Conceptual Overview
|
||||
> [!NOTE]
|
||||
> ### Summary of Changes from v1.0.0
|
||||
> 1. **Snapshot vs. Execution Mutability**: Clarified that `WorkoutSession` contains an immutable `SessionPrescriptionSnapshot` frozen upon initiation, while its execution performance state remains mutable until explicitly finalized (`Completed`, `Partially_Completed`, `Skipped`), at which point the entire session locks.
|
||||
> 2. **Unified Prescription Snapshot**: Grouped frozen prescriptions and activities under a single session-level `SessionPrescriptionSnapshot` value object rather than scattering snapshot copies across individual performances.
|
||||
> 3. **`Exercise` Promoted to Aggregate Root**: Recognized `Exercise` as an independent Aggregate Root with its own lifecycle, referenced by ID from prescriptions and performances.
|
||||
> 4. **`User` Clarified as Ownership Entity**: Modeled `User` as an identity and profile entity, avoiding an oversized aggregate that contains all routines and sessions.
|
||||
> 5. **`SessionActivity` & `ActivityPerformance` Entities**: Formally modeled non-set activities (warm-ups, cardio) across both the prescription layer (`SessionActivity`) and execution layer (`ActivityPerformance`).
|
||||
> 6. **`DayKind` Cleanup**: Removed `Active Recovery` from `DayKind` (`Workout`, `Rest`, `Unscheduled`). Active recovery is represented as an activity or ad-hoc session.
|
||||
> 7. **Phase Progression Model**: Broadened `Phase` from a narrow integer set modifier to a declarative specification supporting prescription overrides over defined week windows.
|
||||
> 8. **Single-Active-Routine Invariant Placement**: Transferred the single-active-routine rule from `Routine` aggregate invariant to an Application Policy orchestrated by `ActivateRoutineUseCase`.
|
||||
> 9. **Naming & Substitution Clarification**: Renamed to `planned_exercise_id` and `performed_exercise_id`. Established invariant: performance of substituted exercises contributes strictly to the `performed_exercise_id`'s historical log.
|
||||
> 10. **Targeted Method Encapsulation**: Refactored `session.record_set(performance_id, set_data)` and `session.remove_set(performance_id, set_id)` to target performances and sets by ID.
|
||||
> 11. **Metric Validation on `SetPerformance`**: Added metric type validation enforcing required fields (e.g., reps for weightlifting, duration for timed planks) to prevent nonsensical data combinations.
|
||||
> 12. **Effort Scoping**: Scoped effort tracking strictly to optional `RIR` for MVP; deferred RPE.
|
||||
> 13. **Milestone Scoping (1RM Deferred)**: Moved 1RM/PR estimation out of the core MVP calculation layer into Milestone 2, keeping MVP focused on factual history, metric-dependent workload, and adherence.
|
||||
> 14. **Domain Behavioral Contracts**: Added explicit pre/post-conditions and state transition matrices for each aggregate.
|
||||
|
||||
Praxis translates user intent into physical performance and derived analytical insight. The architecture strictly enforces boundaries across three temporal layers:
|
||||
---
|
||||
|
||||
## 1. Domain Topology & Class Diagram
|
||||
|
||||
Praxis enforces strict separation across the three temporal layers (**Prescription**, **Performance**, **Analysis**) while maintaining decoupled aggregate boundaries:
|
||||
|
||||
```mermaid
|
||||
classDiagram
|
||||
direction TB
|
||||
|
||||
class User {
|
||||
<<Entity / Identity>>
|
||||
+UserId id
|
||||
+ExternalIdentityId external_id
|
||||
+UserProfile profile
|
||||
+DateTime created_at
|
||||
}
|
||||
|
||||
class Exercise {
|
||||
<<Aggregate Root>>
|
||||
+ExerciseId id
|
||||
+UserId author_id
|
||||
+String name
|
||||
+MuscleGroup category
|
||||
+Equipment equipment
|
||||
+MetricType default_metric
|
||||
+String instructions
|
||||
+update_metadata(name, category, equipment, default_metric, instructions)
|
||||
}
|
||||
|
||||
class Routine {
|
||||
<<Aggregate Root>>
|
||||
+RoutineId id
|
||||
@@ -49,9 +81,13 @@ classDiagram
|
||||
+DateTime activated_at
|
||||
+List~Phase~ phases
|
||||
+Map~Weekday, WorkoutDay~ schedule
|
||||
+activate(now: DateTime)
|
||||
+deactivate()
|
||||
+mark_active(now: DateTime)
|
||||
+mark_inactive()
|
||||
+get_current_phase(for_date: Date) Phase
|
||||
+configure_workout_day(weekday, label, kind)
|
||||
+add_prescription(weekday, prescription)
|
||||
+remove_prescription(weekday, prescription_id)
|
||||
+reorder_prescriptions(weekday, ordered_ids)
|
||||
}
|
||||
|
||||
class WorkoutDay {
|
||||
@@ -68,24 +104,22 @@ classDiagram
|
||||
<<Entity>>
|
||||
+PrescriptionId id
|
||||
+ExerciseId exercise_id
|
||||
+TargetSets target_sets
|
||||
+Int target_sets
|
||||
+RepRange rep_range
|
||||
+TargetDuration target_duration
|
||||
+Duration target_duration
|
||||
+Weight target_weight
|
||||
+Boolean is_unilateral
|
||||
+Int order_index
|
||||
+String notes
|
||||
}
|
||||
|
||||
class Exercise {
|
||||
<<Entity / Reference>>
|
||||
+ExerciseId id
|
||||
+UserId author_id
|
||||
class SessionActivity {
|
||||
<<Entity>>
|
||||
+ActivityId id
|
||||
+String name
|
||||
+MuscleGroup category
|
||||
+Equipment equipment
|
||||
+MetricType default_metric
|
||||
+String instructions
|
||||
+String description
|
||||
+Duration target_duration
|
||||
+Int order_index
|
||||
}
|
||||
|
||||
class WorkoutSession {
|
||||
@@ -97,414 +131,354 @@ classDiagram
|
||||
+SessionStatus status
|
||||
+DateTime started_at
|
||||
+DateTime finished_at
|
||||
+SessionPrescriptionSnapshot prescription_snapshot
|
||||
+List~ExercisePerformance~ exercises
|
||||
+List~ActivityPerformance~ activities
|
||||
+String notes
|
||||
+record_set(exercise_id, set_perf)
|
||||
+substitute_exercise(original_id, new_id, reason)
|
||||
+finish(policy: CompletionPolicy)
|
||||
+record_set(performance_id, set_data) SetPerformance
|
||||
+remove_set(performance_id, set_id)
|
||||
+substitute_exercise(performance_id, new_exercise_id, reason)
|
||||
+add_ad_hoc_exercise(exercise_id) ExercisePerformance
|
||||
+record_activity(activity_perf_id, actual_duration, actual_dist, notes)
|
||||
+finish(policy: CompletionPolicy) CompletionResult
|
||||
+skip(reason: String)
|
||||
}
|
||||
|
||||
class SessionPrescriptionSnapshot {
|
||||
<<Value Object>>
|
||||
+RoutineId routine_id
|
||||
+String routine_name
|
||||
+String phase_name
|
||||
+List~PrescriptionSnapshotItem~ exercise_prescriptions
|
||||
+List~ActivitySnapshotItem~ activities
|
||||
}
|
||||
|
||||
class ExercisePerformance {
|
||||
<<Entity>>
|
||||
+ExercisePerformanceId id
|
||||
+ExerciseId prescribed_exercise_id
|
||||
+ExerciseId actual_exercise_id
|
||||
+PrescriptionSnapshot prescription_snapshot
|
||||
+ExerciseId planned_exercise_id
|
||||
+ExerciseId performed_exercise_id
|
||||
+PrescriptionId prescription_item_id
|
||||
+List~SetPerformance~ sets
|
||||
+SubstitutionContext substitution
|
||||
+String notes
|
||||
+append_set(set_data) SetPerformance
|
||||
+remove_set(set_id)
|
||||
+calculate_workload(metric_type) Workload
|
||||
}
|
||||
|
||||
class SetPerformance {
|
||||
<<Entity>>
|
||||
+SetPerformanceId id
|
||||
+Int set_number
|
||||
+Int actual_reps
|
||||
+Weight actual_weight
|
||||
+Duration actual_duration
|
||||
+RIR reps_in_reserve
|
||||
+RPE perceived_exertion
|
||||
+String notes
|
||||
}
|
||||
|
||||
class ActivityPerformance {
|
||||
<<Entity>>
|
||||
+ActivityPerformanceId id
|
||||
+ActivityId planned_activity_id
|
||||
+String name
|
||||
+Duration actual_duration
|
||||
+Distance actual_distance
|
||||
+Boolean is_completed
|
||||
+String notes
|
||||
}
|
||||
|
||||
User "1" --> "*" Routine : owns
|
||||
User "1" --> "*" WorkoutSession : performs
|
||||
User "1" --> "*" Exercise : authors
|
||||
|
||||
Routine "1" *-- "7" WorkoutDay : contains
|
||||
WorkoutDay "1" *-- "*" ExercisePrescription : prescribes
|
||||
ExercisePrescription "1" --> "1" Exercise : targets
|
||||
WorkoutDay "1" *-- "*" SessionActivity : prescribes
|
||||
ExercisePrescription "1" --> "1" Exercise : references
|
||||
|
||||
User "1" --> "*" WorkoutSession : performs
|
||||
WorkoutSession "1" *-- "1" SessionPrescriptionSnapshot : freezes
|
||||
WorkoutSession "1" *-- "*" ExercisePerformance : tracks
|
||||
WorkoutSession "1" *-- "*" ActivityPerformance : tracks
|
||||
ExercisePerformance "1" *-- "*" SetPerformance : logs
|
||||
ExercisePerformance "1" --> "1" Exercise : references
|
||||
ExercisePerformance "1" --> "1" Exercise : performed_as
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Classification: Entities vs. Value Objects
|
||||
|
||||
To eliminate mutable identity bugs and enforce domain integrity, elements are strictly separated into **Entities** (having unique identity, lifecycle, and mutable state governed by methods) and **Value Objects** (immutable descriptors compared purely by value, with structural validation).
|
||||
|
||||
### 2.1. Value Objects
|
||||
|
||||
| Value Object | Structural Fields | Invariants & Validation Rules |
|
||||
| :--- | :--- | :--- |
|
||||
| `UserId` | `UUID / String` | Non-empty, opaque string representing domain user identity. |
|
||||
| `Weekday` | `Enum: Monday .. Sunday` | ISO-8601 weekday integer representation (1–7). |
|
||||
| `DayKind` | `Enum: Workout, Rest, Unscheduled` | Categorizes scheduling nature of the calendar day. |
|
||||
| `RepRange` | `min_reps: Int, max_reps: Int` | `1 <= min_reps <= max_reps <= 200`. If fixed reps (e.g. 12), `min_reps == max_reps`. |
|
||||
| `Weight` | `value: Decimal, unit: Unit (KG, LBS)` | `value >= 0.0`. Provides explicit conversions between KG and LBS. |
|
||||
| `Duration` | `seconds: Int` | `seconds >= 0`. Expressed in whole seconds. |
|
||||
| `RIR` | `value: Int` | `0 <= value <= 10` (Reps In Reserve). |
|
||||
| `RPE` | `value: Decimal` | `1.0 <= value <= 10.0` (Rating of Perceived Exertion). |
|
||||
| `Phase` | `name: String, start_week: Int, end_week: Optional[Int], set_modifier: Int` | `start_week >= 1`. If `end_week` is present, `start_week <= end_week`. Governs prescribed set counts. |
|
||||
| `PrescriptionSnapshot` | Frozen copy of prescribed sets, reps, weight, duration, cues | Completely immutable value object frozen upon session creation. |
|
||||
| `SubstitutionContext` | `original_exercise_id: ExerciseId, reason: String` | Records why an exercise was swapped during live execution. |
|
||||
| `UserId` | `UUID / String` | Immutable non-empty opaque string. |
|
||||
| `ExerciseId` | `UUID / String` | Unique identifier for canonical exercise movements. |
|
||||
| `RoutineId` | `UUID / String` | Unique identifier for routine templates. |
|
||||
| `SessionId` | `UUID / String` | Unique identifier for workout sessions. |
|
||||
| `Weekday` | `Enum: Monday .. Sunday` | ISO-8601 integer representation (1–7). |
|
||||
| `DayKind` | `Enum: Workout, Rest, Unscheduled` | Primary calendar classification. |
|
||||
| `MetricType` | `Enum: RepsWeight, Duration, DistanceDuration` | Governs measurement and validation rules. |
|
||||
| `RepRange` | `min_reps: Int, max_reps: Int` | `1 <= min_reps <= max_reps <= 200`. For fixed reps, `min_reps == max_reps`. |
|
||||
| `Weight` | `value: Decimal, unit: Unit (KG, LBS)` | `value >= 0.0`. Implements lossless `.to_kg()` conversion. |
|
||||
| `Duration` | `seconds: Int` | `seconds >= 0`. Whole-second granularity. |
|
||||
| `Distance` | `meters: Decimal` | `meters >= 0.0`. |
|
||||
| `RIR` | `value: Int` | `0 <= value <= 5` (Reps In Reserve). |
|
||||
| `Phase` | `name: String, start_week: Int, end_week: Optional[Int], target_sets_override: Optional[Int]` | `start_week >= 1`. If `end_week` present, `start_week <= end_week`. |
|
||||
| `SessionPrescriptionSnapshot` | Frozen copy of prescriptions, activities, and phase metadata | Fully immutable value object materialised at session initiation. |
|
||||
| `PrescriptionSnapshotItem` | `prescription_id, exercise_id, exercise_name, target_sets, rep_range, target_duration, target_weight, order_index` | Immutable representation of a single prescribed movement. |
|
||||
| `ActivitySnapshotItem` | `activity_id, name, description, target_duration, order_index` | Immutable representation of a prescribed session activity. |
|
||||
| `SubstitutionContext` | `original_exercise_id: ExerciseId, reason: String, substituted_at: DateTime` | Immutable audit trail of an on-the-fly exercise change. |
|
||||
|
||||
### 2.2. Entities
|
||||
### 2.2. Entities & Aggregate Roots
|
||||
|
||||
- **`User`**: Root user entity owning preferences and data references.
|
||||
- **`Exercise`**: Canonical catalog entry for a physical movement.
|
||||
- **`Routine`**: Root aggregate managing weekly schedules and phase definitions.
|
||||
- **`WorkoutDay`**: Child entity of `Routine` defining prescriptions for a given weekday.
|
||||
- **`ExercisePrescription`**: Child entity of `WorkoutDay` prescribing targets for an exercise.
|
||||
- **`WorkoutSession`**: Root aggregate representing a concrete training event.
|
||||
- **`ExercisePerformance`**: Child entity of `WorkoutSession` capturing logged work for one exercise.
|
||||
- **`SetPerformance`**: Child entity of `ExercisePerformance` capturing an individual set's execution metrics.
|
||||
1. **`Exercise` (Aggregate Root)**: Canonical movement definition with name, muscle group, equipment, default metric hint, and instructional cues.
|
||||
2. **`Routine` (Aggregate Root)**: Reusable schedule template containing 7 `WorkoutDay` entities and progression `Phase` definitions.
|
||||
3. **`WorkoutSession` (Aggregate Root)**: Historical training occurrence containing a frozen prescription snapshot and executing child entities (`ExercisePerformance`, `ActivityPerformance`, `SetPerformance`).
|
||||
4. **`User` (Identity Entity)**: System boundary actor owning user preferences and domain references.
|
||||
|
||||
---
|
||||
|
||||
## 3. Aggregate Boundaries & Encapsulation
|
||||
## 3. Aggregate Boundaries & Encapsulation Rules
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
subgraph Aggregate_Routine["Aggregate Root: Routine"]
|
||||
R_Root[Routine] --> WD1[WorkoutDay: Mon]
|
||||
R_Root --> WD2[WorkoutDay: Tue]
|
||||
WD1 --> EP1[ExercisePrescription]
|
||||
WD1 --> EP2[ExercisePrescription]
|
||||
R[Routine] --> WD[WorkoutDay]
|
||||
WD --> EP[ExercisePrescription]
|
||||
WD --> SA[SessionActivity]
|
||||
end
|
||||
|
||||
subgraph Aggregate_Exercise["Aggregate Root: Exercise"]
|
||||
EX[Exercise]
|
||||
end
|
||||
|
||||
subgraph Aggregate_WorkoutSession["Aggregate Root: WorkoutSession"]
|
||||
WS_Root[WorkoutSession] --> EPF1[ExercisePerformance]
|
||||
WS_Root --> EPF2[ExercisePerformance]
|
||||
EPF1 --> SP1[SetPerformance 1]
|
||||
EPF1 --> SP2[SetPerformance 2]
|
||||
WS[WorkoutSession] --> SPS[SessionPrescriptionSnapshot]
|
||||
WS --> EPF[ExercisePerformance]
|
||||
WS --> APF[ActivityPerformance]
|
||||
EPF --> SP[SetPerformance]
|
||||
end
|
||||
|
||||
Aggregate_Routine -.->|Snapshot Factory creates| Aggregate_WorkoutSession
|
||||
Aggregate_Routine -.->|SnapshotFactory materializes| Aggregate_WorkoutSession
|
||||
Aggregate_WorkoutSession -.->|References by ExerciseId| Aggregate_Exercise
|
||||
Aggregate_Routine -.->|References by ExerciseId| Aggregate_Exercise
|
||||
```
|
||||
|
||||
### Boundary Rule 1: `Routine` Aggregate
|
||||
- **Root**: `Routine`.
|
||||
- **Enclosed**: `WorkoutDay`, `ExercisePrescription`, `SessionActivity`, `Phase`.
|
||||
- **Encapsulation Rules**:
|
||||
- External code cannot mutate `ExercisePrescription` directly; it calls methods on `Routine` (e.g., `routine.add_prescription(weekday, prescription)`).
|
||||
- `Routine` has **zero references** to `WorkoutSession` or historical performance data.
|
||||
- Modifying a `Routine` never triggers side-effects in past or in-progress `WorkoutSession` instances.
|
||||
- Encapsulates `WorkoutDay`, `ExercisePrescription`, `SessionActivity`, and `Phase`.
|
||||
- Prescriptions cannot be modified from outside without passing through `Routine` methods.
|
||||
- Has **zero knowledge** of past or active `WorkoutSession` instances.
|
||||
- Does not enforce global uniqueness of the active routine; activation state is modified via `mark_active()` and orchestrated by `ActivateRoutineUseCase`.
|
||||
|
||||
### Boundary Rule 2: `WorkoutSession` Aggregate
|
||||
- **Root**: `WorkoutSession`.
|
||||
- **Enclosed**: `ExercisePerformance`, `SetPerformance`, `ActivityPerformance`.
|
||||
- **Encapsulation Rules**:
|
||||
- `WorkoutSession` is the sole boundary through which sets and exercise substitutions are recorded:
|
||||
- `session.record_set(exercise_id, set_data)`
|
||||
- `session.substitute_exercise(original_exercise_id, new_exercise_id, reason)`
|
||||
- `session.add_ad_hoc_exercise(exercise_id)`
|
||||
- `session.finish(completion_policy)`
|
||||
- Direct manipulation of inner `SetPerformance` instances outside the aggregate boundary is prohibited.
|
||||
- Encapsulates `SessionPrescriptionSnapshot`, `ExercisePerformance`, `SetPerformance`, and `ActivityPerformance`.
|
||||
- All modifications to performance state (recording sets, removing sets, swapping exercises, checking off activities) must be executed through methods on `WorkoutSession`.
|
||||
- **Targeted Operations**: Sets are recorded against a specific `ExercisePerformanceId`, preventing ambiguity between planned and substituted exercises.
|
||||
- **Set Identity Invariant**: Sets possess a unique `SetPerformanceId`. Removing a set operates on `set_id`; display order numbers are derived dynamically from sequence position.
|
||||
|
||||
### Boundary Rule 3: `Exercise` Aggregate
|
||||
- Independent aggregate root. Modifying an exercise's instructions or category never mutates existing prescriptions or historical performances (which store snapshot names and IDs).
|
||||
|
||||
---
|
||||
|
||||
## 4. Detailed Specification of Key Objects
|
||||
## 4. Metric Validation on `SetPerformance`
|
||||
|
||||
### 4.1. `Routine` (Aggregate Root)
|
||||
1. **Identity**: `RoutineId` (UUID).
|
||||
2. **State**:
|
||||
- `owner_id`: `UserId`
|
||||
- `name`: string
|
||||
- `is_active`: bool
|
||||
- `activated_at`: optional `DateTime`
|
||||
- `schedule`: dictionary mapping each `Weekday` (1..7) to a `WorkoutDay`
|
||||
- `phases`: ordered list of `Phase` value objects
|
||||
3. **Invariants**:
|
||||
- A routine must contain entries for all 7 weekdays.
|
||||
- `activated_at` must be populated if and only if `is_active == True`.
|
||||
- Phases must not have overlapping week intervals.
|
||||
4. **Behavior**:
|
||||
- `activate(now: DateTime)`: Sets `is_active = True`, records `activated_at = now`.
|
||||
- `deactivate()`: Sets `is_active = False`, clears `activated_at`.
|
||||
- `resolve_phase(for_date: Date) -> Phase`: Calculates elapsed weeks:
|
||||
$$\text{weeks\_elapsed} = \left\lfloor \frac{\text{for\_date} - \text{activated\_at.date}}{7} \right\rfloor + 1$$
|
||||
Returns the matching `Phase`.
|
||||
- `configure_workout_day(weekday, label, kind)`: Reconfigures a day (e.g. converting Sunday to Rest).
|
||||
5. **Relationships**: Owns 7 `WorkoutDay` entities; references `UserId`.
|
||||
6. **Lifecycle**: Created $\rightarrow$ Draft $\rightarrow$ Active $\leftrightarrow$ Inactive $\rightarrow$ Archived.
|
||||
7. **Allowed to Mutate**: Its own schedule, days, prescriptions, and phases.
|
||||
8. **Forbidden Knowledge**: Has no knowledge of `WorkoutSession`, calendar logs, or historical set recordings.
|
||||
|
||||
---
|
||||
|
||||
### 4.2. `WorkoutDay` (Entity within Routine)
|
||||
1. **Identity**: `WorkoutDayId` (UUID).
|
||||
2. **State**:
|
||||
- `weekday`: `Weekday`
|
||||
- `kind`: `DayKind` (`Workout`, `Rest`, `Unscheduled`)
|
||||
- `label`: string (e.g. *"Cuádriceps / Glúteo"*, *"Descanso"*)
|
||||
- `prescriptions`: list of `ExercisePrescription`
|
||||
- `activities`: list of `SessionActivity`
|
||||
3. **Invariants**:
|
||||
- If `kind == Rest` or `Unscheduled`, `prescriptions` must be empty.
|
||||
- Prescription ordering indices must be unique and sequential without gaps.
|
||||
4. **Behavior**:
|
||||
- `add_prescription(exercise_id, target_sets, rep_range, ...)`
|
||||
- `remove_prescription(prescription_id)`
|
||||
- `reorder_prescriptions(ordered_ids: List[PrescriptionId])`
|
||||
- `add_activity(description, duration)`
|
||||
5. **Relationships**: Child of `Routine`. References `ExerciseId`.
|
||||
6. **Lifecycle**: Co-terminous with parent `Routine`.
|
||||
|
||||
---
|
||||
|
||||
### 4.3. `Exercise` (Entity / Reference Data)
|
||||
1. **Identity**: `ExerciseId` (UUID).
|
||||
2. **State**:
|
||||
- `author_id`: optional `UserId` (null if system-seeded)
|
||||
- `name`: string (e.g. *"Sentadilla búlgara en Smith"*)
|
||||
- `category`: `MuscleGroup`
|
||||
- `equipment`: `Equipment`
|
||||
- `default_metric`: `MetricType` (`RepsWeight`, `Duration`, `DistanceDuration`)
|
||||
- `instructions`: string
|
||||
3. **Invariants**:
|
||||
- `name` cannot be blank.
|
||||
- System exercises (`author_id == null`) are immutable by regular users.
|
||||
4. **Behavior**:
|
||||
- `update_metadata(name, category, equipment, default_metric, instructions)` (only permitted if user is author).
|
||||
5. **Forbidden Knowledge**: Has no awareness of prescriptions, workouts, or performance history.
|
||||
|
||||
---
|
||||
|
||||
### 4.4. `WorkoutSession` (Aggregate Root)
|
||||
1. **Identity**: `SessionId` (UUID).
|
||||
2. **State**:
|
||||
- `user_id`: `UserId`
|
||||
- `routine_id`: optional `RoutineId` (null if spontaneous/ad-hoc)
|
||||
- `session_date`: `Date`
|
||||
- `status`: `SessionStatus` (`In_Progress`, `Completed`, `Partially_Completed`, `Skipped`)
|
||||
- `started_at`: `DateTime`
|
||||
- `finished_at`: optional `DateTime`
|
||||
- `exercises`: ordered list of `ExercisePerformance`
|
||||
- `activities`: list of `ActivityPerformance`
|
||||
- `notes`: string
|
||||
3. **Invariants**:
|
||||
- If `status == In_Progress`, `finished_at` must be null.
|
||||
- If `status in (Completed, Partially_Completed)`, `finished_at` must be $\ge$ `started_at`.
|
||||
- Once marked `Completed`, `Partially_Completed`, or `Skipped`, the session is locked against further set modifications.
|
||||
4. **Behavior**:
|
||||
- `record_set(exercise_id, set_number, reps, weight, duration, rir, notes) -> SetPerformance`
|
||||
- `substitute_exercise(original_exercise_id, new_exercise_id, reason)`
|
||||
- `add_ad_hoc_exercise(exercise_id)`
|
||||
- `finish(completion_policy: CompletionPolicy) -> CompletionResult`: Evaluates completion, transitions status, and sets `finished_at = now`.
|
||||
- `skip(reason: String)`: Transitions status to `Skipped` and records reason.
|
||||
5. **Allowed to Mutate**: Child `ExercisePerformance` and `SetPerformance` entities.
|
||||
6. **Forbidden Knowledge**: Knows nothing about future routines, upcoming calendar days, or external authentication providers.
|
||||
|
||||
---
|
||||
|
||||
### 4.5. `ExercisePerformance` (Entity within WorkoutSession)
|
||||
1. **Identity**: `ExercisePerformanceId` (UUID).
|
||||
2. **State**:
|
||||
- `prescribed_exercise_id`: optional `ExerciseId` (null if ad-hoc addition)
|
||||
- `actual_exercise_id`: `ExerciseId`
|
||||
- `prescription_snapshot`: optional `PrescriptionSnapshot`
|
||||
- `sets`: list of `SetPerformance`
|
||||
- `substitution`: optional `SubstitutionContext`
|
||||
- `notes`: string
|
||||
3. **Invariants**:
|
||||
- If substituted, `substitution` must be present and `actual_exercise_id != prescribed_exercise_id`.
|
||||
- Set numbers must be strictly sequential starting from 1.
|
||||
4. **Behavior**:
|
||||
- `append_set(reps, weight, duration, rir, notes)`
|
||||
- `remove_set(set_number)`
|
||||
- `calculate_workload() -> Workload`
|
||||
|
||||
---
|
||||
|
||||
## 5. Domain Policies and Domain Services
|
||||
|
||||
Domain rules that coordinate across entities or encapsulate algorithmic derivations are extracted into **Domain Services & Policies**:
|
||||
To prevent data corruption (e.g. logging 70kg on a timed Plank), `SetPerformance` creation is governed by a **Metric Validation Policy**:
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph Services["Domain Services & Policies"]
|
||||
SSF[SessionSnapshotFactory]
|
||||
CP[CompletionPolicy]
|
||||
WLC[WorkloadCalculator]
|
||||
AHC[AdherenceCalculator]
|
||||
PRC[PersonalRecordCalculator]
|
||||
end
|
||||
flowchart TD
|
||||
M[MetricType of Exercise]
|
||||
M -->|RepsWeight| V1{actual_reps != null?}
|
||||
V1 -->|Yes| OK1[Valid Reps/Weight Set]
|
||||
V1 -->|No| ERR1[Error: Repetitions required]
|
||||
|
||||
R[Routine] --> SSF
|
||||
WD[WorkoutDay] --> SSF
|
||||
SSF --> WS[WorkoutSession]
|
||||
WS --> CP
|
||||
WS --> WLC
|
||||
Hist[(WorkoutSession History)] --> AHC
|
||||
Hist --> PRC
|
||||
M -->|Duration| V2{actual_duration != null?}
|
||||
V2 -->|Yes| OK2[Valid Timed Set]
|
||||
V2 -->|No| ERR2[Error: Duration required]
|
||||
|
||||
M -->|DistanceDuration| V3{duration or distance != null?}
|
||||
V3 -->|Yes| OK3[Valid Distance/Duration Set]
|
||||
V3 -->|No| ERR3[Error: Duration or distance required]
|
||||
```
|
||||
|
||||
### 5.1. `SessionSnapshotFactory`
|
||||
- **Role**: Factory domain service responsible for materializing a `WorkoutSession` from a `Routine`'s scheduled `WorkoutDay`.
|
||||
- **Contract**:
|
||||
```python
|
||||
def create_session(
|
||||
routine: Routine,
|
||||
for_date: Date,
|
||||
user_id: UserId,
|
||||
now: DateTime
|
||||
) -> WorkoutSession
|
||||
```
|
||||
- **Rules**:
|
||||
1. Identifies the weekday for `for_date`.
|
||||
2. Queries `routine.get_current_phase(for_date)` to determine current phase modifiers (e.g. 3 sets vs 4 sets).
|
||||
3. Deep-copies prescriptions and activities into frozen `PrescriptionSnapshot` value objects inside `ExercisePerformance` entities.
|
||||
4. Returns a fresh `WorkoutSession` in `In_Progress` state.
|
||||
---
|
||||
|
||||
## 5. Domain Behavioral Contracts & State Machines
|
||||
|
||||
### 5.1. `WorkoutSession` Lifecycle State Machine
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> In_Progress: SessionSnapshotFactory / InitiateWorkout
|
||||
|
||||
In_Progress --> In_Progress: record_set()
|
||||
In_Progress --> In_Progress: remove_set()
|
||||
In_Progress --> In_Progress: substitute_exercise()
|
||||
In_Progress --> In_Progress: add_ad_hoc_exercise()
|
||||
In_Progress --> In_Progress: record_activity()
|
||||
|
||||
In_Progress --> Completed: finish() [100% set-intent achieved]
|
||||
In_Progress --> Partially_Completed: finish() [>0% sets logged, some omitted]
|
||||
In_Progress --> Skipped: skip(reason)
|
||||
|
||||
Completed --> [*]: Locked (Immutable)
|
||||
Partially_Completed --> [*]: Locked (Immutable)
|
||||
Skipped --> [*]: Locked (Immutable)
|
||||
```
|
||||
|
||||
### 5.2. Behavioral Contracts
|
||||
|
||||
#### `WorkoutSession.record_set`
|
||||
- **Signature**: `record_set(performance_id: ExercisePerformanceId, set_data: SetData) -> SetPerformance`
|
||||
- **Preconditions**:
|
||||
- `self.status == SessionStatus.In_Progress` (error if finalized).
|
||||
- `performance_id` exists within `self.exercises`.
|
||||
- `set_data` satisfies `MetricValidationPolicy` for the exercise's `MetricType`.
|
||||
- **Postconditions**:
|
||||
- New `SetPerformance` instance appended to matching `ExercisePerformance.sets`.
|
||||
- Returns created `SetPerformance`.
|
||||
|
||||
#### `WorkoutSession.remove_set`
|
||||
- **Signature**: `remove_set(performance_id: ExercisePerformanceId, set_id: SetPerformanceId) -> None`
|
||||
- **Preconditions**:
|
||||
- `self.status == SessionStatus.In_Progress`.
|
||||
- `set_id` exists in `performance_id`.
|
||||
- **Postconditions**:
|
||||
- `SetPerformance` matching `set_id` is removed.
|
||||
|
||||
#### `WorkoutSession.substitute_exercise`
|
||||
- **Signature**: `substitute_exercise(performance_id: ExercisePerformanceId, new_exercise_id: ExerciseId, reason: String) -> None`
|
||||
- **Preconditions**:
|
||||
- `self.status == SessionStatus.In_Progress`.
|
||||
- `performance_id.sets` is empty (substitution must occur before logging sets on that performance).
|
||||
- **Postconditions**:
|
||||
- `performance.performed_exercise_id = new_exercise_id`.
|
||||
- `performance.substitution = SubstitutionContext(original_exercise_id, reason, now)`.
|
||||
|
||||
#### `WorkoutSession.finish`
|
||||
- **Signature**: `finish(completion_policy: CompletionPolicy, override_status: Optional[SessionStatus] = None) -> CompletionResult`
|
||||
- **Preconditions**:
|
||||
- `self.status == SessionStatus.In_Progress`.
|
||||
- **Postconditions**:
|
||||
- If `override_status` is provided: `self.status = override_status`.
|
||||
- Else: `self.status = completion_policy.evaluate(self).suggested_status`.
|
||||
- `self.finished_at = now`.
|
||||
- Session becomes locked against further mutation.
|
||||
|
||||
#### `WorkoutSession.skip`
|
||||
- **Signature**: `skip(reason: String) -> None`
|
||||
- **Preconditions**:
|
||||
- `self.status == SessionStatus.In_Progress` and no sets have been logged.
|
||||
- **Postconditions**:
|
||||
- `self.status = SessionStatus.Skipped`.
|
||||
- `self.finished_at = now`.
|
||||
- `self.notes = reason`.
|
||||
|
||||
---
|
||||
|
||||
### 5.2. `CompletionPolicy`
|
||||
- **Role**: Implements the set-intent evaluation policy to evaluate completion status.
|
||||
- **Contract**:
|
||||
```python
|
||||
def evaluate(session: WorkoutSession) -> CompletionEvaluation:
|
||||
# Returns:
|
||||
# - suggested_status: Completed | Partially_Completed
|
||||
# - total_prescribed_sets: Int
|
||||
# - total_logged_sets: Int
|
||||
# - completed_exercise_count: Int
|
||||
# - total_prescribed_exercises: Int
|
||||
```
|
||||
- **Rules**:
|
||||
1. An exercise is complete if count of logged sets $\ge$ prescribed sets (adjusted by active phase) and sets represent attempted work.
|
||||
2. The session is `Completed` if all prescribed exercises are complete.
|
||||
3. The session is `Partially_Completed` if $>0$ sets were logged but some prescribed exercises/sets were omitted.
|
||||
## 6. Domain Policies & Derivations
|
||||
|
||||
### 6.1. `SessionSnapshotFactory`
|
||||
Materializes a `WorkoutSession` from a scheduled `WorkoutDay`:
|
||||
1. Determines elapsed weeks since routine activation:
|
||||
$$\text{week\_index} = \left\lfloor \frac{\text{session\_date} - \text{routine.activated\_at.date}}{7} \right\rfloor + 1$$
|
||||
2. Queries `routine.get_current_phase(session_date)` to resolve active phase and target set overrides (e.g. 3 sets vs 4 sets).
|
||||
3. Freezes `SessionPrescriptionSnapshot` containing all prescribed exercises and activities.
|
||||
4. Generates an initial `ExercisePerformance` entity for each prescribed exercise, setting both `planned_exercise_id` and `performed_exercise_id` to the prescribed exercise ID.
|
||||
5. Generates an initial `ActivityPerformance` for each prescribed activity.
|
||||
6. Returns `WorkoutSession` in `In_Progress` status.
|
||||
|
||||
### 6.2. `CompletionPolicy` (Set-Intent Evaluation)
|
||||
Evaluates whether a session achieved full or partial completion:
|
||||
- **Exercise Complete**: Evaluated as complete if $\text{count}(\text{valid sets logged}) \ge \text{target sets from snapshot}$.
|
||||
- **Suggested Status**:
|
||||
- If $100\%$ of prescribed exercises are complete $\rightarrow$ `Completed`.
|
||||
- If $>0$ sets logged but $<100\%$ prescribed exercises complete $\rightarrow$ `Partially_Completed`.
|
||||
|
||||
### 6.3. `WorkloadCalculator`
|
||||
Calculates metric-dependent physical workload:
|
||||
- **Weighted Volume**: $\sum_{i} (\text{actual\_reps}_i \times \text{actual\_weight}_i\text{.to\_kg()})$
|
||||
- **Duration Workload**: $\sum_{i} \text{actual\_duration}_i\text{.seconds}$
|
||||
- **Distance Workload**: $\sum_{i} \text{actual\_distance}_i\text{.meters}$
|
||||
|
||||
### 6.4. `AdherenceCalculator`
|
||||
Calculates objective habit consistency over a window $[T_{\text{start}}, T_{\text{end}}]$:
|
||||
$$\text{Scheduled Count} = N_{\text{scheduled}}$$
|
||||
$$\text{Completion Rate} = \frac{N_{\text{completed}}}{N_{\text{scheduled}}}$$
|
||||
$$\text{Partial Rate} = \frac{N_{\text{partially\_completed}}}{N_{\text{scheduled}}}$$
|
||||
$$\text{Skip Rate} = \frac{N_{\text{skipped}}}{N_{\text{scheduled}}}$$
|
||||
$$\text{Set Adherence Rate} = \frac{\sum \text{Sets Performed}}{\sum \text{Sets Prescribed}}$$
|
||||
|
||||
---
|
||||
|
||||
### 5.3. `WorkloadCalculator`
|
||||
- **Role**: Computes metric-dependent physical workload for performances and sessions without conflating units.
|
||||
- **Contract**:
|
||||
```python
|
||||
def calculate_set_workload(set_perf: SetPerformance) -> Workload
|
||||
def calculate_session_workload(session: WorkoutSession) -> SessionWorkload
|
||||
```
|
||||
- **Calculations**:
|
||||
- **Weighted Volume (Tonnage)**: $\sum (\text{actual\_reps} \times \text{actual\_weight.to\_kg()})$
|
||||
- **Cumulative Duration**: $\sum \text{actual\_duration.seconds}$
|
||||
- **Distance**: $\sum \text{actual\_distance}$
|
||||
|
||||
---
|
||||
|
||||
### 5.4. `AdherenceCalculator`
|
||||
- **Role**: Pure derivation service calculating factual consistency rates over an evaluation window.
|
||||
- **Contract**:
|
||||
```python
|
||||
def calculate_adherence(
|
||||
scheduled_count: int,
|
||||
sessions: List[WorkoutSession]
|
||||
) -> AdherenceReport
|
||||
```
|
||||
- **Formulas**:
|
||||
- `completed_rate = count(Completed) / scheduled_count`
|
||||
- `partial_rate = count(Partially_Completed) / scheduled_count`
|
||||
- `skip_rate = count(Skipped) / scheduled_count`
|
||||
- `set_adherence = total_sets_performed / total_sets_prescribed`
|
||||
|
||||
---
|
||||
|
||||
### 5.5. `PersonalRecordCalculator`
|
||||
- **Role**: Scans historical `WorkoutSession` instances to derive personal bests for a specific `ExerciseId`.
|
||||
- **Derivations**:
|
||||
- **Peak Weight Lifted**: $\max(\text{actual\_weight})$ across all sets.
|
||||
- **Peak Volume in Single Set**: $\max(\text{reps} \times \text{weight})$.
|
||||
- **Estimated 1RM (Epley)**: $\max\left(\text{weight} \times \left(1 + \frac{\text{reps}}{30}\right)\right)$ for sets where $1 \le \text{reps} \le 10$.
|
||||
|
||||
---
|
||||
|
||||
## 6. Core Application Use Cases (Interactors)
|
||||
|
||||
Below are the primary transactional boundaries orchestrating domain entities and repositories:
|
||||
## 7. Application Use Cases (Interactors)
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
autonumber
|
||||
actor User
|
||||
participant UC as InitiateWorkoutUseCase
|
||||
participant UC as ActivateRoutineUseCase
|
||||
participant RRepo as RoutineRepository
|
||||
participant SRepo as SessionRepository
|
||||
participant SSF as SessionSnapshotFactory
|
||||
|
||||
User->>UC: execute(date)
|
||||
UC->>RRepo: get_active_routine(user_id)
|
||||
RRepo-->>UC: routine
|
||||
UC->>SSF: create_session(routine, date, user_id, now)
|
||||
SSF-->>UC: workout_session
|
||||
UC->>SRepo: save(workout_session)
|
||||
SRepo-->>UC: saved_session
|
||||
UC-->>User: WorkoutSessionDTO (In_Progress)
|
||||
User->>UC: execute(target_routine_id)
|
||||
UC->>RRepo: get_active(user_id)
|
||||
opt Active routine exists
|
||||
RRepo-->>UC: current_active_routine
|
||||
UC->>current_active_routine: mark_inactive()
|
||||
UC->>RRepo: save(current_active_routine)
|
||||
end
|
||||
UC->>RRepo: get_by_id(target_routine_id)
|
||||
RRepo-->>UC: target_routine
|
||||
UC->>target_routine: mark_active(now)
|
||||
UC->>RRepo: save(target_routine)
|
||||
UC-->>User: Success (target_routine activated)
|
||||
```
|
||||
|
||||
### Use Case Inventory
|
||||
### Complete Use Case Inventory
|
||||
|
||||
1. **`CreateRoutine(user_id, name, schedule_spec, phases)`**: Instantiates and persists a new `Routine`.
|
||||
2. **`ActivateRoutine(user_id, routine_id)`**: Deactivates any currently active routine for the user and activates the specified routine.
|
||||
3. **`InitiateWorkout(user_id, date)`**: Finds active routine, invokes `SessionSnapshotFactory`, and persists the new in-progress `WorkoutSession`.
|
||||
4. **`RecordSet(user_id, session_id, exercise_id, set_data)`**: Loads `WorkoutSession`, appends set via `session.record_set(...)`, and saves.
|
||||
5. **`SubstituteExercise(user_id, session_id, original_id, new_id, reason)`**: Records substitution on the active session without altering `Routine`.
|
||||
6. **`FinishWorkout(user_id, session_id, override_status=None)`**: Evaluates completion via `CompletionPolicy`, marks session finished, and persists.
|
||||
7. **`SkipWorkout(user_id, date, reason)`**: Creates or marks a session as `Skipped`.
|
||||
8. **`QueryWeeklyCalendar(user_id, start_date, end_date)`**: Merges active routine's projected `ScheduledWorkout` items with recorded `WorkoutSession` instances for the calendar grid.
|
||||
9. **`QueryExerciseProgression(user_id, exercise_id)`**: Loads history for `exercise_id`, computes workload and PR trends via domain services, and returns time-series data.
|
||||
10. **`CalculateAdherenceReport(user_id, window_start, window_end)`**: Runs `AdherenceCalculator` over the specified historical date range.
|
||||
1. **`CreateRoutineUseCase(user_id, name, schedule_spec, phases)`**: Creates new `Routine` aggregate.
|
||||
2. **`ActivateRoutineUseCase(user_id, routine_id)`**: Enforces the single-active-routine policy by deactivating the current active routine before activating the target routine.
|
||||
3. **`InitiateWorkoutUseCase(user_id, date)`**: Calls `SessionSnapshotFactory` and saves new `WorkoutSession`.
|
||||
4. **`RecordSetUseCase(user_id, session_id, performance_id, set_data)`**: Appends validated set to performance.
|
||||
5. **`RemoveSetUseCase(user_id, session_id, performance_id, set_id)`**: Removes set by identity.
|
||||
6. **`SubstituteExerciseUseCase(user_id, session_id, performance_id, new_exercise_id, reason)`**: Records substitution.
|
||||
7. **`AddAdHocExerciseUseCase(user_id, session_id, exercise_id)`**: Appends unscheduled exercise to active session.
|
||||
8. **`RecordActivityUseCase(user_id, session_id, activity_perf_id, actual_duration, actual_dist, notes)`**: Logs activity completion.
|
||||
9. **`FinishWorkoutUseCase(user_id, session_id, override_status=None)`**: Evaluates completion via `CompletionPolicy` and finalizes session.
|
||||
10. **`SkipWorkoutUseCase(user_id, date, reason)`**: Records skipped session.
|
||||
11. **`QueryWeeklyCalendarUseCase(user_id, start_date, end_date)`**: Returns projected `ScheduledWorkout` items alongside recorded `WorkoutSession` instances.
|
||||
12. **`QueryExerciseHistoryUseCase(user_id, exercise_id)`**: Returns historical performances where `performed_exercise_id == exercise_id`.
|
||||
13. **`CalculateAdherenceUseCase(user_id, start_date, end_date)`**: Generates factual adherence metrics.
|
||||
|
||||
---
|
||||
|
||||
## 7. Ports & Adapters Architecture (Hexagonal)
|
||||
## 8. Clean Architecture Dependency Graph
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
subgraph DrivingAdapters["Driving / Primary Adapters (Incoming)"]
|
||||
API[FastAPI / REST Controllers]
|
||||
CLI[Admin / Seed CLI]
|
||||
subgraph Infrastructure["Infrastructure Layer"]
|
||||
FastAPI[FastAPI Controllers / REST API]
|
||||
AuthAdapter[Authelia Reverse-Proxy Header Adapter]
|
||||
SQLRepo[PostgreSQL / SQLite Repositories]
|
||||
end
|
||||
|
||||
subgraph ApplicationCore["Application Core (Use Cases / Domain)"]
|
||||
UC[Use Cases / Interactors]
|
||||
DM[Domain Model & Policies]
|
||||
subgraph Application["Application Layer (Use Cases)"]
|
||||
UC[Application Use Cases]
|
||||
DTO[Data Transfer Objects / Schemas]
|
||||
end
|
||||
|
||||
subgraph DrivenPorts["Driven / Secondary Ports (Interfaces)"]
|
||||
IPort_Auth[AuthProvider Port]
|
||||
IPort_Routine[RoutineRepository Port]
|
||||
IPort_Session[SessionRepository Port]
|
||||
IPort_Exercise[ExerciseRepository Port]
|
||||
subgraph Domain["Domain Layer (Pure Business Rules)"]
|
||||
Agg_Routine[Routine Aggregate]
|
||||
Agg_Session[WorkoutSession Aggregate]
|
||||
Agg_Exercise[Exercise Aggregate]
|
||||
DomainServices[Domain Policies & Calculators]
|
||||
Ports[Repository & Auth Ports]
|
||||
end
|
||||
|
||||
subgraph DrivenAdapters["Driven / Secondary Adapters (Infrastructure)"]
|
||||
AuthHeader[Authelia Forward-Auth Header Adapter]
|
||||
SQLRepo[PostgreSQL / SQLite SQLModel/SQLAlchemy Adapter]
|
||||
end
|
||||
|
||||
API --> UC
|
||||
CLI --> UC
|
||||
UC --> DM
|
||||
UC --> DrivenPorts
|
||||
DrivenPorts --> DrivenAdapters
|
||||
FastAPI --> UC
|
||||
UC --> Domain
|
||||
UC --> Ports
|
||||
AuthAdapter --> Ports
|
||||
SQLRepo --> Ports
|
||||
```
|
||||
|
||||
### Port Definitions:
|
||||
- `AuthProvider`: Resolves external identity headers (`Remote-User`, `Remote-Email`) into a domain `UserId`.
|
||||
- `RoutineRepository`: `save(routine)`, `get_by_id(id)`, `get_active(user_id)`.
|
||||
- `WorkoutSessionRepository`: `save(session)`, `get_by_id(id)`, `find_by_user_and_date(user_id, date)`, `find_history_by_exercise(user_id, exercise_id)`.
|
||||
- `ExerciseRepository`: `save(exercise)`, `get_by_id(id)`, `list_catalog(user_id)`.
|
||||
@@ -1,8 +1,8 @@
|
||||
---
|
||||
title: Implementation Blueprint
|
||||
description: Translates the approved SRS (v1.0.2) and Domain Model (v1.0.1) into concrete Python implementation decisions. Records all design choices made during the Phase 0 implementation-readiness pass.
|
||||
version: 0.1.0
|
||||
status: Active
|
||||
version: 0.2.0
|
||||
status: Phase 0 Complete
|
||||
date: 2026-09-24
|
||||
tags:
|
||||
- implementation
|
||||
@@ -19,8 +19,8 @@ tags:
|
||||
|
||||
| Document Attribute | Specification |
|
||||
| :--- | :--- |
|
||||
| **Document Version** | `0.1.0` |
|
||||
| **Status** | Active |
|
||||
| **Document Version** | `0.2.0` |
|
||||
| **Status** | Phase 0 Complete |
|
||||
| **Last Updated** | 2026-09-24 |
|
||||
| **SRS Baseline** | [`praxis-srs-v1.0.2.md`](praxis-srs-v1.0.2.md) |
|
||||
| **Domain Model Baseline** | [`praxis-domain-model-v1.0.1.md`](praxis-domain-model-v1.0.1.md) |
|
||||
@@ -48,6 +48,7 @@ src/praxis/
|
||||
│ │ ├── identifiers.py # UserId, ExerciseId, RoutineId, SessionId, PrescriptionId, …
|
||||
│ │ ├── measurement.py # Weight, Duration, Distance, RIR, RepRange
|
||||
│ │ ├── enums.py # Weekday, DayKind, MetricType, SessionStatus, MuscleGroup, Equipment, Unit
|
||||
│ │ ├── set_data.py # SetData (input value object for MetricValidationPolicy and record_set)
|
||||
│ │ └── snapshot.py # SessionPrescriptionSnapshot, PrescriptionSnapshotItem, ActivitySnapshotItem, SubstitutionContext
|
||||
│ ├── policies/
|
||||
│ │ ├── __init__.py
|
||||
@@ -116,15 +117,43 @@ tests/
|
||||
|
||||
## 2. Dependency Direction
|
||||
|
||||
```text
|
||||
┌──────────────────┐
|
||||
│ interfaces/ │ (Phase 4 — FastAPI)
|
||||
└────────┬─────────┘
|
||||
│ imports
|
||||
▼
|
||||
┌──────────────────┐
|
||||
│ application/ │ use_cases/ + dtos/ + ports/
|
||||
└────────┬─────────┘
|
||||
│ imports
|
||||
┌──────────┴──────────┐
|
||||
▼ ▼
|
||||
┌──────────────┐ ┌──────────────────┐
|
||||
│ domain/ │ │ application/ │
|
||||
│ (pure Python│ │ ports/ │
|
||||
│ stdlib) │ │ (Protocol stubs)│
|
||||
└──────────────┘ └────────┬─────────┘
|
||||
▲ implements (structurally)
|
||||
│
|
||||
┌────────┴─────────┐
|
||||
│ infrastructure/ │
|
||||
│ adapters/ │
|
||||
└──────────────────┘
|
||||
```
|
||||
tests/unit/domain/ → domain/ only (no mocks, no fakes)
|
||||
tests/unit/application/ → application/ + domain/ (in-memory fakes for ports)
|
||||
tests/integration/ → infrastructure/ (real DB)
|
||||
|
||||
interfaces/fastapi/ → application/use_cases/ (Phase 4)
|
||||
The critical relationship: **both** `application/` and `infrastructure/` depend on `application/ports/`. `infrastructure/` never depends on `application/use_cases/`, and `application/` never depends on `infrastructure/`. The protocol is satisfied structurally — no base class import required.
|
||||
|
||||
**In import terms:**
|
||||
|
||||
```text
|
||||
interfaces/fastapi/ → application/use_cases/
|
||||
application/use_cases/ → domain/ + application/ports/
|
||||
domain/ → stdlib only (dataclasses, enum, uuid, datetime, decimal)
|
||||
infrastructure/adapters/ → application/ports/ (implements them)
|
||||
infrastructure/adapters/ → application/ports/ (satisfies Protocol structurally)
|
||||
tests/unit/domain/ → domain/ only (no mocks, no fakes)
|
||||
tests/unit/application/ → application/ + domain/ (in-memory port fakes)
|
||||
tests/integration/ → infrastructure/ (real DB — Phase 3)
|
||||
```
|
||||
|
||||
**Absolute prohibition**: `domain/` must not import from `application/`, `infrastructure/`, or any third-party library.
|
||||
@@ -219,7 +248,7 @@ class ExerciseId:
|
||||
|
||||
**Rationale**: Strong typing prevents passing a `RoutineId` where an `ExerciseId` is expected. Wrapping `uuid.UUID` (not raw `str`) gives canonical comparison semantics and clean serialisation.
|
||||
|
||||
All IDs are defined in `domain/value_objects/identifiers.py`.
|
||||
All IDs are defined in `praxis/domain/value_objects/identifiers.py`.
|
||||
|
||||
---
|
||||
|
||||
@@ -246,7 +275,7 @@ class SessionStatus(str, Enum):
|
||||
|
||||
## 6. Exception Strategy
|
||||
|
||||
Domain exceptions live in `domain/exceptions.py`. No third-party libraries.
|
||||
Domain exceptions live in `praxis/domain/exceptions.py`. No third-party libraries.
|
||||
|
||||
```python
|
||||
class PraxisDomainError(Exception):
|
||||
@@ -289,7 +318,9 @@ Domain factories and aggregate methods that need the current time receive `now:
|
||||
|
||||
## 8. Aggregate Construction
|
||||
|
||||
Aggregate roots are constructed via **factory classmethods**, not bare `__init__` calls, to make intent explicit and enforce invariants at construction:
|
||||
The **public construction API** for aggregate roots is a `create()` classmethod. It carries the invariant checks and ID generation that must happen at construction time. The underlying dataclass `__init__` remains available as the implementation mechanism — `create()` calls it via `cls(...)`.
|
||||
|
||||
This distinction matters: do not fight Python's generated `__init__` or mark it private. It is used internally by `create()` and will also be needed by infrastructure adapters when rehydrating persisted aggregates from storage (where invariants were already satisfied on the way in).
|
||||
|
||||
```python
|
||||
@classmethod
|
||||
@@ -302,6 +333,8 @@ def create(
|
||||
) -> "Routine":
|
||||
if not name.strip():
|
||||
raise ValueError("Routine name must not be blank")
|
||||
if not phases:
|
||||
raise ValueError("Routine must have at least one Phase")
|
||||
return cls(
|
||||
id=RoutineId.generate(),
|
||||
owner_id=owner_id,
|
||||
@@ -321,25 +354,62 @@ def create(
|
||||
|
||||
### 9.1. `SetPerformance` — Metric Field Requirements (Decision)
|
||||
|
||||
The domain model lists `actual_reps`, `actual_weight`, `actual_duration`, and the SRS workload rules reference `actual_distance`. The `DistanceDuration` metric type is handled via `ActivityPerformance.actual_distance`, **not** `SetPerformance`.
|
||||
The domain model lists `actual_reps`, `actual_weight`, and `actual_duration` on `SetPerformance`. The SRS workload rules (FR-ANL-2) also reference distance. `DistanceDuration` exercises cover two distinct activity patterns that require different representations:
|
||||
|
||||
**Decision**:
|
||||
```text
|
||||
DistanceDuration
|
||||
├── Continuous activity (e.g. 20-min stationary bike)
|
||||
│ → ActivityPerformance.actual_distance / actual_duration
|
||||
└── Discrete interval set (e.g. 400m sprint as one logged set)
|
||||
→ SetPerformance.actual_distance / actual_duration
|
||||
```
|
||||
|
||||
**Decision**: `actual_distance: Distance | None` is added to `SetPerformance` to cover the discrete-interval case. `ActivityPerformance.actual_distance` covers the continuous-activity case. Both fields are optional; `MetricValidationPolicy` requires at least one to be non-null when the metric type is `DistanceDuration`.
|
||||
|
||||
| Metric Type | Required on `SetPerformance` | Optional on `SetPerformance` |
|
||||
| :--- | :--- | :--- |
|
||||
| `RepsWeight` | `actual_reps` (int ≥ 0) | `actual_weight` (may be bodyweight = null) |
|
||||
| `RepsWeight` | `actual_reps` (int ≥ 0) | `actual_weight` (null = bodyweight) |
|
||||
| `Duration` | `actual_duration` (Duration) | — |
|
||||
| `DistanceDuration` | at least one of `actual_duration` or `actual_distance` | the other |
|
||||
|
||||
`actual_distance` is added as `Distance | None` to `SetPerformance` to handle interval-style distance sets (e.g., 400m sprints logged as a set). `ActivityPerformance.actual_distance` handles continuous cardio.
|
||||
**Rationale**: Treating sprint intervals as sets is consistent with how strength training is logged — a 400m sprint is a discrete effort with a start and end, not a continuous session activity. The two-case split keeps `ActivityPerformance` for unstructured/continuous cardio and `SetPerformance` for structured intervals.
|
||||
|
||||
**Rationale**: The SRS FR-ANL-2 workload formula references distance. The domain model diagram shows `Distance actual_distance` on `ActivityPerformance`. Sprint-style distance sets are discrete efforts that fit `SetPerformance`. Both are supported.
|
||||
|
||||
The `MetricValidationPolicy` enforces these rules in `domain/policies/metric_validation.py`.
|
||||
`MetricValidationPolicy` enforces these rules in `praxis/domain/policies/metric_validation.py`.
|
||||
|
||||
---
|
||||
|
||||
### 9.2. Completion Semantics — `CompletionPolicy` vs. SRS "Honest Effort" (Decision)
|
||||
### 9.2. `SetData` — Input Value Object (Decision)
|
||||
|
||||
`MetricValidationPolicy.validate()` and `WorkoutSession.record_set()` both need a typed input value. Rather than accepting loose keyword arguments, they receive a `SetData` value object.
|
||||
|
||||
**Decision**: `SetData` is a frozen dataclass defined in `praxis/domain/value_objects/set_data.py`.
|
||||
|
||||
```python
|
||||
# praxis/domain/value_objects/set_data.py
|
||||
from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
from praxis.domain.value_objects.measurement import Weight, Duration, Distance, RIR
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SetData:
|
||||
"""Carries the raw input for one logged set before it becomes a SetPerformance.
|
||||
|
||||
All measurement fields are optional at construction; MetricValidationPolicy
|
||||
determines which combination is valid for a given MetricType.
|
||||
"""
|
||||
actual_reps: int | None = None
|
||||
actual_weight: Weight | None = None
|
||||
actual_duration: Duration | None = None
|
||||
actual_distance: Distance | None = None
|
||||
reps_in_reserve: RIR | None = None
|
||||
notes: str = ""
|
||||
```
|
||||
|
||||
`SetData` lives in the domain layer so that `MetricValidationPolicy` (also domain) can reference it without any application or infrastructure imports.
|
||||
|
||||
---
|
||||
|
||||
### 9.3. Completion Semantics — `CompletionPolicy` vs. SRS "Honest Effort" (Decision)
|
||||
|
||||
SRS FR-STAT-2 says: *"An exercise is evaluated as complete when all prescribed sets have been attempted with honest effort (logging reps within target range or completing full sets short of failure with RIR/notes)."*
|
||||
|
||||
@@ -369,7 +439,7 @@ class CompletionPolicy:
|
||||
|
||||
---
|
||||
|
||||
### 9.3. `WorkoutSession.finish()` — Legal Override States (Decision)
|
||||
### 9.4. `WorkoutSession.finish()` — Legal Override States (Decision)
|
||||
|
||||
The domain model permits an `Optional[override_status]` parameter. The question is which states are valid overrides.
|
||||
|
||||
@@ -390,7 +460,7 @@ This is enforced inside `WorkoutSession.finish()` before any state transition oc
|
||||
|
||||
---
|
||||
|
||||
### 9.4. Metric Snapshotting — What Gets Frozen (Decision)
|
||||
### 9.5. Metric Snapshotting — What Gets Frozen (Decision)
|
||||
|
||||
The snapshot must make each session historically stable even if the live `Exercise` aggregate is later updated (e.g., name changed, category corrected).
|
||||
|
||||
@@ -416,7 +486,7 @@ class PrescriptionSnapshotItem:
|
||||
|
||||
---
|
||||
|
||||
### 9.5. `ScheduledWorkout` — Aggregate vs. Read Model (Decision)
|
||||
### 9.6. `ScheduledWorkout` — Aggregate vs. Read Model (Decision)
|
||||
|
||||
SRS FR-CAL-1/CAL-2 references `ScheduledWorkout` as a projection. Domain Model §7 use case #11 (`QueryWeeklyCalendarUseCase`) returns projected items.
|
||||
|
||||
@@ -448,12 +518,15 @@ class ScheduledWorkoutProjection:
|
||||
|
||||
## 10. Repository Port Shapes
|
||||
|
||||
Ports are declared as `Protocol` classes in `application/ports/repositories.py`. No base classes, no generics superclass — each port is explicit and minimal.
|
||||
> [!NOTE]
|
||||
> The method signatures below are **provisional** — derived from the approved use case inventory in Domain Model §7. They will be refined in Phase 2 as each use case is implemented. The existence and structure of ports (as `Protocol` classes in `application/ports/`) is architectural and frozen; the exact query methods are not.
|
||||
|
||||
Ports are declared as `Protocol` classes in `praxis/application/ports/repositories.py`. No base classes, no generics superclass — each port is explicit and minimal.
|
||||
|
||||
```python
|
||||
from typing import Protocol
|
||||
from domain.aggregates.routine import Routine
|
||||
from domain.value_objects.identifiers import UserId, RoutineId
|
||||
from praxis.domain.aggregates.routine import Routine
|
||||
from praxis.domain.value_objects.identifiers import UserId, RoutineId
|
||||
|
||||
class RoutineRepository(Protocol):
|
||||
def save(self, routine: Routine) -> None: ...
|
||||
@@ -556,26 +629,33 @@ This means `SetPerformance` has no `to_dict()`. The persistence adapter is respo
|
||||
|
||||
| Phase | Scope | Entry Criterion | Done When |
|
||||
| :--- | :--- | :--- | :--- |
|
||||
| **Phase 0** | Implementation Readiness | Specs baselined | All ambiguities in §9 resolved (this document) |
|
||||
| **Phase 1** | Pure Domain Foundation | Phase 0 complete | All domain tests green, ≥90% coverage, mypy clean |
|
||||
| **Phase 0** | Implementation Readiness | Specs baselined | All Phase-1-blocking ambiguities resolved; implementation conventions frozen; remaining questions explicitly deferred |
|
||||
| **Phase 1** | Pure Domain Foundation | Phase 0 complete | All domain tests green; `ruff` and `pyright strict` clean |
|
||||
| **Phase 2** | Application Layer | Phase 1 complete | All use case tests green with in-memory fakes |
|
||||
| **Phase 3** | Infrastructure | Phase 2 complete | Integration tests pass with SQLite |
|
||||
| **Phase 4** | FastAPI Interface | Phase 3 complete | OpenAPI spec generated, integration round-trips pass |
|
||||
| **Phase 5** | Containerisation | Phase 4 complete | Docker Compose stack runs, Authelia header adapter wired |
|
||||
|
||||
> [!NOTE]
|
||||
> **Coverage and linting are project quality policy, not domain architecture.** The 90% coverage gate and `pyright strict` requirement are enforced by the pre-push hook and `pyproject.toml` configuration (see `AGENTS.md §5`). They apply across all phases, but they are toolchain constraints — they do not determine whether a concept belongs in the domain layer.
|
||||
|
||||
---
|
||||
|
||||
## 15. Open Questions (Not Blocking Phase 1)
|
||||
## 15. Open Questions
|
||||
|
||||
These are deferred — they do not affect the domain layer and will be resolved in later phases.
|
||||
Questions are classified by when they become blocking.
|
||||
|
||||
### Resolved
|
||||
|
||||
| # | Question | Resolution |
|
||||
| :--- | :--- | :--- |
|
||||
| **OQ-2** | `Phase.end_week = None` means open-ended. What should `get_current_phase()` return when no phase matches the current week? | **Resolved**: Return the phase with the highest `start_week` (the last-defined phase). This implements "Week 3+" semantics from the reference training program. An empty `phases` list raises `ValueError` at construction. |
|
||||
|
||||
### Deferred (not blocking Phase 1)
|
||||
|
||||
| # | Question | Blocking |
|
||||
| :--- | :--- | :--- |
|
||||
| OQ-1 | `WorkoutSession.routine_id` is nullable for ad-hoc sessions (no routine). Should `session_date` uniqueness be enforced at application or DB level? | Phase 2 |
|
||||
| OQ-2 | `Phase.end_week = None` means "open-ended". What happens when `get_current_phase` finds no matching phase? Return last phase or raise? | Phase 1 (`Routine`) |
|
||||
| OQ-1 | `WorkoutSession.routine_id` is nullable for ad-hoc sessions. Should `session_date` uniqueness be enforced at application or DB level? | Phase 2 |
|
||||
| OQ-3 | Weight unit preference — stored on `User.profile` or derived per-request? | Phase 2 |
|
||||
| OQ-4 | `ExercisePrescription.target_weight = None` is valid (bodyweight). How is this communicated in the snapshot / UI suggestion? | Phase 4 |
|
||||
| OQ-4 | `ExercisePrescription.target_weight = None` is valid (bodyweight). How is this communicated to the snapshot consumer / UI? | Phase 4 |
|
||||
| OQ-5 | Exercise catalog seeding (FR-EX-1) — migration fixture or Python data file? | Phase 3 |
|
||||
|
||||
> [!NOTE]
|
||||
> OQ-2 must be resolved before implementing `Routine.get_current_phase()` in Phase 1. **Proposed resolution**: return the last defined phase (highest `start_week`) when the current week exceeds all `end_week` values. This matches the reference program's "Week 3+" semantics.
|
||||
@@ -1,208 +0,0 @@
|
||||
---
|
||||
title: Software Requirements Specification (SRS)
|
||||
description: Canonical Software Requirements Specification for the Praxis workout tracking and habit execution platform.
|
||||
version: 1.0.2-draft
|
||||
status: Canonical Baseline
|
||||
date: 2026-09-24
|
||||
tags:
|
||||
- requirements
|
||||
- srs
|
||||
- specification
|
||||
- architecture
|
||||
---
|
||||
|
||||
# Software Requirements Specification (SRS)
|
||||
|
||||
> Canonical Software Requirements Specification for the **Praxis** workout tracking and habit execution platform.
|
||||
|
||||
| Document Attribute | Specification |
|
||||
| :--- | :--- |
|
||||
| **Document Version** | `1.0.2-draft` |
|
||||
| **Status** | Canonical Requirements Baseline (Refined) |
|
||||
| **Last Updated** | 2026-09-24 |
|
||||
| **Previous Revision** | [`praxis-srs.md`](praxis-srs.md) (`v1.0.0-draft`) |
|
||||
|
||||
---
|
||||
|
||||
> [!NOTE]
|
||||
> ### Summary of Changes from v1.0.0
|
||||
> - **FR-LOG-1 (Snapshot Clarification)**: Clarified that the *prescription snapshot* is immutable upon initiation, while the session's execution state remains mutable until explicitly finalized (`Completed`, `Partially_Completed`, `Skipped`). Once finalized, the entire session locks against further edits.
|
||||
> - **FR-CAL-2 & FR-RT-3 (DayKind vs. Active Recovery)**: Confirmed `DayKind` strictly contains `Workout`, `Rest`, and `Unscheduled`. *Active Recovery* is modeled as an activity/session (e.g. Saturday cycling activity or Sunday ad-hoc session on a Rest day), not as a separate day kind.
|
||||
> - **FR-RT-4 & FR-LOG-2 (SessionActivity Formalization)**: Promoted non-set movements (warm-up instructions, cardio) into a formal prescription and performance entity pair: `SessionActivity` $\rightarrow$ `ActivityPerformance`.
|
||||
> - **FR-LOG-2 (Effort Scoping)**: Focused effort tracking strictly on optional **RIR (Reps in Reserve)** for MVP, aligning with reference training program instructions (*"dejando 1–2 repeticiones antes del fallo"*). RPE is deferred.
|
||||
> - **FR-ANL-3 & Milestone Scope (1RM Deferral)**: Formally deferred estimated 1RM and automated PR calculation to Milestone 2 to avoid premature algorithmic complexity. MVP focuses strictly on factual exercise history (sets, reps, weight, duration), metric-dependent workload, and adherence rates.
|
||||
> - **FR-ANL-1 (Substitution Analytics Invariant)**: Invariant established: performance of a substituted exercise contributes exclusively to the history of the *performed* exercise, never to the *planned* exercise.
|
||||
|
||||
---
|
||||
|
||||
## 1. Executive Summary & Domain Philosophy
|
||||
|
||||
**Praxis** (from the Greek/Latin for *"the practical application of a plan"*) is a self-hosted workout execution and habit tracking system designed to run in a homelab environment.
|
||||
|
||||
Unlike typical fitness trackers that conflate what was planned with what was performed, Praxis is architected around a strict **Three-Layer Temporal Model**:
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph Layer1["1. Prescription (What should happen)"]
|
||||
R[Routine Template] --> WD[Workout Day]
|
||||
WD --> EP[Exercise Prescription]
|
||||
WD --> SA[Session Activity]
|
||||
R -.-> PH[Progression Phases]
|
||||
end
|
||||
|
||||
subgraph Layer2["2. Performance (What actually happened)"]
|
||||
SW[Scheduled Workout Projection] -->|Initiate| WS[Workout Session]
|
||||
WS --> SPS[SessionPrescriptionSnapshot]
|
||||
WS --> EPF[Exercise Performance]
|
||||
EPF --> SPF[Set Performance]
|
||||
WS --> APF[Activity Performance]
|
||||
WS --> ST[Status: In_Progress / Completed / Partially_Completed / Skipped]
|
||||
end
|
||||
|
||||
subgraph Layer3["3. Analysis (What can be derived)"]
|
||||
ADH[Adherence & Consistency Rates]
|
||||
WKL[Metric-Dependent Workload]
|
||||
HST[Factual Exercise History]
|
||||
TRN[Longitudinal Progression]
|
||||
end
|
||||
|
||||
Layer1 -->|Project into calendar| SW
|
||||
Layer2 -->|Pure deterministic derivation| Layer3
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Core Domain Glossary
|
||||
|
||||
| Term | Definition |
|
||||
| :--- | :--- |
|
||||
| **User** | Internal domain entity representing identity, ownership, and preferences. |
|
||||
| **Routine** | Reusable weekly schedule template specifying which weekdays have workouts, rest, or unscheduled days. |
|
||||
| **Phase** | Temporal cycle within a routine (e.g., Weeks 1–2 vs. Week 3+) that governs progression rules such as prescribed set volumes based on elapsed calendar weeks since routine activation. |
|
||||
| **Exercise** | Canonical movement definition with category, target muscle group, equipment, and default measurement type hint. |
|
||||
| **Exercise Prescription** | Plan for an exercise on a workout day: target sets, target reps/duration, target weight/effort, order, and notes. |
|
||||
| **Session Activity** | Non-set prescribed instruction or movement (e.g., articular warm-up, post-workout cardio, mobility). |
|
||||
| **Scheduled Workout** | Projection of a routine's workout day onto a specific calendar date before physical initiation. |
|
||||
| **Workout Session** | Concrete historical occurrence of physical training on a calendar date. Contains a frozen prescription snapshot and mutable execution state until finalized. |
|
||||
| **Exercise Performance** | Concrete execution of an exercise within a session, containing one or more logged sets and optional substitution context. |
|
||||
| **Set Performance** | Concrete logged set recording actual repetitions, actual weight, duration, optional RIR, and set notes. |
|
||||
| **Activity Performance** | Concrete execution of a session activity (e.g., 20 min cycling completed, warm-up performed). |
|
||||
| **Adherence** | Set of factual metrics tracking scheduled sessions vs completed, partial, and skipped sessions over an evaluation window. |
|
||||
| **Workload** | Metric-dependent measure of physical work performed (weighted volume $\sum \text{reps} \times \text{weight}$, cumulative duration in seconds, or distance). |
|
||||
|
||||
---
|
||||
|
||||
## 3. Fundamental Domain Invariants
|
||||
|
||||
1. **Prescription Snapshot Immutability**: When a `WorkoutSession` is initiated, a complete snapshot of prescribed exercises and activities is frozen. Editing a `Routine` never alters past or in-progress sessions.
|
||||
2. **Session Lifecycle & Mutability**: While `In_Progress`, a `WorkoutSession` execution state is mutable (logging sets, adding exercises, recording deviations). Once transitioned to `Completed`, `Partially_Completed`, or `Skipped`, the entire session becomes immutable.
|
||||
3. **Session Autonomy**: During an active session, a user has total autonomy to deviate from prescribed sets, reps, and weights, swap exercises, add unscheduled exercises, or omit exercises without mutating the parent `Routine`.
|
||||
4. **Decoupled Identity**: The core domain depends only on an internal `UserId`. External identity provider specifics (LLDAP, Authelia, OAuth2) are isolated behind an `AuthProvider` port.
|
||||
5. **Single Active Routine Policy**: An application-level invariant: a user may curate an arbitrary library of routines, but at any given date, at most one routine is marked `Active` to generate scheduled workout projections on the calendar.
|
||||
6. **Substituted History Isolation**: When exercise $A$ is substituted by exercise $B$, the logged sets contribute strictly to the historical record of exercise $B$, preserving an audit trail of the original intent without corrupting exercise $A$'s progress.
|
||||
7. **Derived Analysis Invariant**: Progress metrics (workload, adherence, factual history) are never stored as mutable counters; they are purely derived functions of immutable historical `WorkoutSession` records.
|
||||
|
||||
---
|
||||
|
||||
## 4. Detailed Functional Requirements
|
||||
|
||||
### 4.1. Identity & External Authentication (Ports & Adapters)
|
||||
- **FR-AUTH-1**: The backend shall decouple authentication from core business logic via an `IdentityAdapter` / `AuthProvider` interface.
|
||||
- **FR-AUTH-2**: The system shall ship with a reverse-proxy header adapter (consuming headers such as `Remote-User`, `Remote-Email`, `Remote-Name` passed by Authelia/Nginx/Traefik).
|
||||
- **FR-AUTH-3**: The system shall automatically provision or sync an internal `User` profile upon receiving a valid authenticated request from an external identity.
|
||||
- **FR-AUTH-4**: The domain model shall be agnostic to credential storage; no passwords, hashes, or SSO credentials shall be persisted in the Praxis domain database.
|
||||
|
||||
### 4.2. Exercise Catalog Management
|
||||
- **FR-EX-1**: The system shall ship with a pre-seeded catalog of standard exercises, covering all movements from the reference training program.
|
||||
- **FR-EX-2**: Users shall be able to create custom exercises and edit their own custom definitions.
|
||||
- **FR-EX-3**: Each exercise shall specify:
|
||||
- `name`: string
|
||||
- `category` / `muscle_group`: (e.g., *Cuádriceps, Glúteo, Espalda, Hombro, Isquiotibiales, Pecho, Brazos, Core, Cardio*)
|
||||
- `equipment`: (e.g., *Smith machine, Dumbbell, Barbell, Cable/Machine, Band, Bodyweight*)
|
||||
- `default_metric`: default hint (*Reps-Weight*, *Duration*, *Distance-Duration*)
|
||||
- `instructions` / `cues`: optional text
|
||||
|
||||
### 4.3. Routine & Phase Management
|
||||
- **FR-RT-1**: Users can create, clone, rename, archive, and delete multiple routines.
|
||||
- **FR-RT-2 (Application Policy)**: The application ensures at most one routine is set as `Active` per user at any given time.
|
||||
- **FR-RT-3**: A routine defines a 7-day weekly schedule (`Monday` through `Sunday`). Each weekday can be assigned as:
|
||||
- `Workout Day`
|
||||
- `Rest Day`
|
||||
- `Unscheduled Day`
|
||||
- **FR-RT-4**: A Workout Day within a routine contains:
|
||||
- **Exercise Prescriptions**: Target sets, target repetitions (or rep ranges, e.g. 10–12), optional target weight, optional unilateral indicator (`each leg / cada pie`), order index, and prescription notes.
|
||||
- **Session Activities**: Non-set activities (e.g., *"Articular warm-up before session"* or *"15–20 min stationary bike or elliptical at moderate pace"*).
|
||||
- **FR-RT-5 (Progression Phases)**: Routines support declarative phases (e.g., Phase 1: Weeks 1–2 prescribing 3 sets; Phase 2: Week 3+ prescribing 4 sets). The active phase is determined deterministically by elapsed calendar weeks from the routine's activation date:
|
||||
$$\text{Week Index} = \left\lfloor \frac{\text{Date} - \text{ActivationDate}}{7} \right\rfloor + 1$$
|
||||
|
||||
### 4.4. Calendar & Scheduling
|
||||
- **FR-CAL-1**: The system shall provide an API for a weekly calendar view displaying projected `ScheduledWorkout` items alongside actual `WorkoutSession` instances across Monday–Sunday.
|
||||
- **FR-CAL-2**: The calendar displays days as `Scheduled Workout Day`, `Rest Day`, or `Unscheduled Day`. Physical activity logged on a Rest day (e.g. Sunday cycling) is displayed as an ad-hoc session or active recovery activity.
|
||||
- **FR-CAL-3**: The calendar shall display historical weeks with immutable records of past performance.
|
||||
|
||||
### 4.5. Workout Execution & Runtime Logging
|
||||
- **FR-LOG-1 (Snapshot on Initiation)**: When a user initiates a workout for a calendar day, Praxis generates a `WorkoutSession` containing a frozen `SessionPrescriptionSnapshot` of the prescribed exercises, sets, target values, and activities.
|
||||
- **FR-LOG-2 (Set-Level Performance)**: For each exercise performance, the user can log:
|
||||
- Actual repetitions completed
|
||||
- Actual weight used (in user's preferred unit: kg or lbs)
|
||||
- Actual duration in seconds (for timed sets like Planks)
|
||||
- Optional RIR (Reps in Reserve, 0–5)
|
||||
- Set-level notes
|
||||
- **FR-LOG-3 (Runtime Session Flexibility)**:
|
||||
- Users can append ad-hoc sets or remove logged sets (by set identity).
|
||||
- Users can reorder exercises during execution.
|
||||
- Users can substitute an exercise on the fly with another exercise from the catalog, preserving the substitution event for auditing.
|
||||
- Users can add completely unscheduled exercises to the active session.
|
||||
- **FR-LOG-4 (Activity Logging)**: Users can record the execution of session activities (e.g., check off warm-up, record actual duration of cardio).
|
||||
- **FR-LOG-5 (Ad-Hoc / Rest Day Logging)**: Users can initiate and log an ad-hoc session or active recovery (e.g., Sunday cycling) on any day without a prior scheduled prescription.
|
||||
- **FR-LOG-6 (Session Notes & Deviations)**: Users can record session-level notes (e.g. *"Gym was crowded, had to swap Smith machine for dumbbells"* or *"Fatigued, stopped 1 set early"*).
|
||||
|
||||
### 4.6. Session Completion Semantics & Habit Adherence
|
||||
- **FR-STAT-1**: A `WorkoutSession` transitions through lifecycle states:
|
||||
- `In_Progress` (user has initiated session and/or logged sets)
|
||||
- `Completed` (all prescribed exercises logged with full set intent)
|
||||
- `Partially_Completed` (session finished with at least one set logged, but some prescribed exercises/sets omitted)
|
||||
- `Skipped` (explicitly marked skipped by user or flagged when scheduled date has passed without initiation)
|
||||
- **FR-STAT-2 (Set-Intent Completion Evaluation)**: An exercise is evaluated as complete when all prescribed sets have been attempted with honest effort (logging reps within target range or completing full sets short of failure with RIR/notes).
|
||||
- **FR-STAT-3 (Smart Completion Suggestion)**: When the user calls "Finish Workout", the system evaluates logged work:
|
||||
- If 100% of prescribed sets/exercises completed $\rightarrow$ suggests `Completed`.
|
||||
- If $>0\%$ completed $\rightarrow$ suggests `Partially_Completed` with summary of completed vs omitted work.
|
||||
- User can confirm or override the final state.
|
||||
- **FR-STAT-4 (Factual Adherence Metrics)**: Adherence is reported as factual distribution rates over a selected evaluation window:
|
||||
- `Completed Sessions Rate`: $N_{\text{completed}} / N_{\text{scheduled}}$
|
||||
- `Partial Sessions Rate`: $N_{\text{partial}} / N_{\text{scheduled}}$
|
||||
- `Skipped Sessions Rate`: $N_{\text{skipped}} / N_{\text{scheduled}}$
|
||||
- `Set Adherence Rate`: Total Sets Performed / Total Sets Prescribed
|
||||
|
||||
### 4.7. Progression & Performance Analytics
|
||||
- **FR-ANL-1 (Factual Exercise History)**: For any exercise, the user can query past performances (chronological history of weights, reps, sets, and workload). Substitutions contribute strictly to the performed exercise.
|
||||
- **FR-ANL-2 (Metric-Dependent Workload)**: For each session and per exercise, compute appropriate workload:
|
||||
- Weighted Repetitions: $\text{Volume} = \sum (\text{reps} \times \text{weight})$
|
||||
- Timed Exercises: $\text{Duration} = \sum \text{seconds}$
|
||||
- Distance: $\text{Distance} = \sum \text{kilometers/meters}$
|
||||
- **FR-ANL-3 (Trend Analytics)**: The system provides query endpoints for time-series trend analysis (weekly workload by muscle group, adherence rates by month, progression curves for core lifts).
|
||||
|
||||
---
|
||||
|
||||
## 5. Non-Functional & Architectural Requirements
|
||||
|
||||
- **NFR-ARCH-1 (API-First & Decoupled Frontend)**: The backend shall expose a clean, comprehensive REST/OpenAPI specification. The frontend is decoupled.
|
||||
- **NFR-ARCH-2 (Clean / Hexagonal Architecture)**: Domain aggregates (`Routine`, `WorkoutSession`, `Exercise`) contain pure business rules with zero dependencies on database ORMs or web frameworks.
|
||||
- **NFR-ARCH-3 (Self-Hosted / Containerized)**: Deployable as a single Docker container or Docker Compose service with minimal resource footprint (< 256MB RAM idle) suited for homelab micro-servers.
|
||||
- **NFR-ARCH-4 (Zero External Cloud Reliance)**: Runs entirely on local infrastructure with SQLite or PostgreSQL; no third-party telemetry, proprietary clouds, or external API dependencies.
|
||||
- **NFR-ARCH-5 (Data Portability)**: Users can export their entire history, routines, and exercises as JSON / CSV at any time.
|
||||
|
||||
---
|
||||
|
||||
## 6. Implementation Scope Milestones
|
||||
|
||||
```mermaid
|
||||
timeline
|
||||
title Praxis Implementation Roadmap (Updated)
|
||||
section MVP (Foundation)
|
||||
Decoupled Auth (Header Adapter) : Domain Aggregates (Routine, WorkoutSession, Exercise) : SessionPrescriptionSnapshot Engine : Multi-Modal Set Logging & Activities : Smart Completion Suggestion : Factual Adherence & Metric Workload Analytics
|
||||
section Milestone 2 (Evolution)
|
||||
Estimated 1RM (Epley/Brzycki) & PR Tracking : Interactive Progression Visualizations : Automated Phase Transition Alerts : Workout Templates Import/Export (JSON/YAML) : Mobile-First PWA Client
|
||||
section Milestone 3 (Advanced)
|
||||
Rest Interval Timers : RPE & Effort Conversions : Equipment Availability Substitution Suggestions : Webhook Event Notifications
|
||||
```
|
||||
+72
-48
@@ -1,26 +1,37 @@
|
||||
---
|
||||
title: Software Requirements Specification (SRS) — v1.0.0 Draft (Archived)
|
||||
description: Initial Software Requirements Specification draft for Praxis, preserved for historical and comparative reference.
|
||||
version: 1.0.0-draft
|
||||
status: Superseded / Archive
|
||||
title: Software Requirements Specification (SRS)
|
||||
description: Canonical Software Requirements Specification for the Praxis workout tracking and habit execution platform.
|
||||
version: 1.0.2-draft
|
||||
status: Canonical Baseline
|
||||
date: 2026-09-24
|
||||
tags:
|
||||
- requirements
|
||||
- srs
|
||||
- archive
|
||||
- specification
|
||||
- architecture
|
||||
---
|
||||
|
||||
# Software Requirements Specification (SRS) — v1.0.0 Draft (Archived)
|
||||
# Software Requirements Specification (SRS)
|
||||
|
||||
> [!WARNING]
|
||||
> **Superseded Specification**: This document is an initial draft preserved for historical reference and auditability. The canonical, active specification is maintained in [`praxis-srs-v1.0.2.md`](praxis-srs-v1.0.2.md).
|
||||
> Canonical Software Requirements Specification for the **Praxis** workout tracking and habit execution platform.
|
||||
|
||||
| Document Attribute | Specification |
|
||||
| :--- | :--- |
|
||||
| **Document Version** | `1.0.0-draft` |
|
||||
| **Status** | Superseded / Historical Archive |
|
||||
| **Date** | 2026-09-24 |
|
||||
| **Canonical Baseline** | [`praxis-srs-v1.0.2.md`](praxis-srs-v1.0.2.md) |
|
||||
| **Document Version** | `1.0.2-draft` |
|
||||
| **Status** | Canonical Requirements Baseline (Refined) |
|
||||
| **Last Updated** | 2026-09-24 |
|
||||
| **Previous Revision** | [`praxis-srs.md`](praxis-srs.md) (`v1.0.0-draft`) |
|
||||
|
||||
---
|
||||
|
||||
> [!NOTE]
|
||||
> ### Summary of Changes from v1.0.0
|
||||
> - **FR-LOG-1 (Snapshot Clarification)**: Clarified that the *prescription snapshot* is immutable upon initiation, while the session's execution state remains mutable until explicitly finalized (`Completed`, `Partially_Completed`, `Skipped`). Once finalized, the entire session locks against further edits.
|
||||
> - **FR-CAL-2 & FR-RT-3 (DayKind vs. Active Recovery)**: Confirmed `DayKind` strictly contains `Workout`, `Rest`, and `Unscheduled`. *Active Recovery* is modeled as an activity/session (e.g. Saturday cycling activity or Sunday ad-hoc session on a Rest day), not as a separate day kind.
|
||||
> - **FR-RT-4 & FR-LOG-2 (SessionActivity Formalization)**: Promoted non-set movements (warm-up instructions, cardio) into a formal prescription and performance entity pair: `SessionActivity` $\rightarrow$ `ActivityPerformance`.
|
||||
> - **FR-LOG-2 (Effort Scoping)**: Focused effort tracking strictly on optional **RIR (Reps in Reserve)** for MVP, aligning with reference training program instructions (*"dejando 1–2 repeticiones antes del fallo"*). RPE is deferred.
|
||||
> - **FR-ANL-3 & Milestone Scope (1RM Deferral)**: Formally deferred estimated 1RM and automated PR calculation to Milestone 2 to avoid premature algorithmic complexity. MVP focuses strictly on factual exercise history (sets, reps, weight, duration), metric-dependent workload, and adherence rates.
|
||||
> - **FR-ANL-1 (Substitution Analytics Invariant)**: Invariant established: performance of a substituted exercise contributes exclusively to the history of the *performed* exercise, never to the *planned* exercise.
|
||||
|
||||
---
|
||||
|
||||
@@ -35,12 +46,13 @@ flowchart TD
|
||||
subgraph Layer1["1. Prescription (What should happen)"]
|
||||
R[Routine Template] --> WD[Workout Day]
|
||||
WD --> EP[Exercise Prescription]
|
||||
WD --> ACT[Session Activity / Note]
|
||||
WD --> SA[Session Activity]
|
||||
R -.-> PH[Progression Phases]
|
||||
end
|
||||
|
||||
subgraph Layer2["2. Performance (What actually happened)"]
|
||||
SW[Scheduled Workout Projection] -->|Initiate| WS[Workout Session Snapshot]
|
||||
SW[Scheduled Workout Projection] -->|Initiate| WS[Workout Session]
|
||||
WS --> SPS[SessionPrescriptionSnapshot]
|
||||
WS --> EPF[Exercise Performance]
|
||||
EPF --> SPF[Set Performance]
|
||||
WS --> APF[Activity Performance]
|
||||
@@ -49,8 +61,8 @@ flowchart TD
|
||||
|
||||
subgraph Layer3["3. Analysis (What can be derived)"]
|
||||
ADH[Adherence & Consistency Rates]
|
||||
VOL[Metric-Dependent Workload]
|
||||
PR[Personal Records & 1RM]
|
||||
WKL[Metric-Dependent Workload]
|
||||
HST[Factual Exercise History]
|
||||
TRN[Longitudinal Progression]
|
||||
end
|
||||
|
||||
@@ -64,16 +76,17 @@ flowchart TD
|
||||
|
||||
| Term | Definition |
|
||||
| :--- | :--- |
|
||||
| **User** | Internal domain actor owning routines, exercise customizations, and workout history. |
|
||||
| **User** | Internal domain entity representing identity, ownership, and preferences. |
|
||||
| **Routine** | Reusable weekly schedule template specifying which weekdays have workouts, rest, or unscheduled days. |
|
||||
| **Phase** | Temporal cycle within a routine (e.g., Weeks 1–2 vs. Week 3+) that governs progression rules such as prescribed set volumes based on elapsed calendar weeks since routine activation. |
|
||||
| **Exercise** | Canonical movement definition with category, target muscle group, equipment, and default measurement type hint. |
|
||||
| **Exercise Prescription** | Plan for an exercise on a workout day: target sets, target reps/duration, target weight/effort, order, and notes. |
|
||||
| **Session Activity** | Non-set prescribed instruction or movement (e.g., articular warm-up, post-workout cardio, mobility). |
|
||||
| **Scheduled Workout** | Projection of a routine's workout day onto a specific calendar date before physical initiation. |
|
||||
| **Workout Session** | Concrete historical occurrence of physical training on a calendar date. Created upon initiation as an immutable snapshot of the prescribed work. |
|
||||
| **Workout Session** | Concrete historical occurrence of physical training on a calendar date. Contains a frozen prescription snapshot and mutable execution state until finalized. |
|
||||
| **Exercise Performance** | Concrete execution of an exercise within a session, containing one or more logged sets and optional substitution context. |
|
||||
| **Set Performance** | Concrete logged set recording actual repetitions, actual weight, duration, RIR/effort, and set notes. |
|
||||
| **Set Performance** | Concrete logged set recording actual repetitions, actual weight, duration, optional RIR, and set notes. |
|
||||
| **Activity Performance** | Concrete execution of a session activity (e.g., 20 min cycling completed, warm-up performed). |
|
||||
| **Adherence** | Set of factual metrics tracking scheduled sessions vs completed, partial, and skipped sessions over an evaluation window. |
|
||||
| **Workload** | Metric-dependent measure of physical work performed (weighted volume $\sum \text{reps} \times \text{weight}$, cumulative duration in seconds, or distance). |
|
||||
|
||||
@@ -81,12 +94,13 @@ flowchart TD
|
||||
|
||||
## 3. Fundamental Domain Invariants
|
||||
|
||||
1. **Snapshot Immutability**: Historical `WorkoutSession` records and their contained performances are immutable with respect to future changes in `Routine` templates. Editing a routine never alters past or in-progress sessions.
|
||||
2. **Session Autonomy**: During an active workout session, a user has total autonomy to deviate from prescribed sets, reps, and weights, swap exercises, add unscheduled exercises, or omit exercises without mutating the parent `Routine`.
|
||||
3. **Decoupled Identity**: The core domain depends only on an internal `User` identifier and profile. External identity provider specifics (LLDAP, Authelia, OAuth2) are isolated behind an `AuthProvider` port.
|
||||
4. **Single Active Routine Driving Schedule**: A user may curate an arbitrary library of routines, but at any given date, at most one routine is marked `Active` to generate scheduled workout projections on the calendar.
|
||||
5. **Derived Analysis Invariant**: Progress metrics (workload, adherence, estimated 1RM, personal records) are never stored as mutable counters; they are purely derived functions of immutable historical `WorkoutSession` records.
|
||||
6. **Separation of Schedule and Session**: A `ScheduledWorkout` is a projected calendar event. A `WorkoutSession` comes into existence only upon explicit initiation or ad-hoc workout creation.
|
||||
1. **Prescription Snapshot Immutability**: When a `WorkoutSession` is initiated, a complete snapshot of prescribed exercises and activities is frozen. Editing a `Routine` never alters past or in-progress sessions.
|
||||
2. **Session Lifecycle & Mutability**: While `In_Progress`, a `WorkoutSession` execution state is mutable (logging sets, adding exercises, recording deviations). Once transitioned to `Completed`, `Partially_Completed`, or `Skipped`, the entire session becomes immutable.
|
||||
3. **Session Autonomy**: During an active session, a user has total autonomy to deviate from prescribed sets, reps, and weights, swap exercises, add unscheduled exercises, or omit exercises without mutating the parent `Routine`.
|
||||
4. **Decoupled Identity**: The core domain depends only on an internal `UserId`. External identity provider specifics (LLDAP, Authelia, OAuth2) are isolated behind an `AuthProvider` port.
|
||||
5. **Single Active Routine Policy**: An application-level invariant: a user may curate an arbitrary library of routines, but at any given date, at most one routine is marked `Active` to generate scheduled workout projections on the calendar.
|
||||
6. **Substituted History Isolation**: When exercise $A$ is substituted by exercise $B$, the logged sets contribute strictly to the historical record of exercise $B$, preserving an audit trail of the original intent without corrupting exercise $A$'s progress.
|
||||
7. **Derived Analysis Invariant**: Progress metrics (workload, adherence, factual history) are never stored as mutable counters; they are purely derived functions of immutable historical `WorkoutSession` records.
|
||||
|
||||
---
|
||||
|
||||
@@ -99,49 +113,49 @@ flowchart TD
|
||||
- **FR-AUTH-4**: The domain model shall be agnostic to credential storage; no passwords, hashes, or SSO credentials shall be persisted in the Praxis domain database.
|
||||
|
||||
### 4.2. Exercise Catalog Management
|
||||
- **FR-EX-1**: The system shall ship with a pre-seeded catalog of standard exercises, covering all exercises from the reference training program.
|
||||
- **FR-EX-1**: The system shall ship with a pre-seeded catalog of standard exercises, covering all movements from the reference training program.
|
||||
- **FR-EX-2**: Users shall be able to create custom exercises and edit their own custom definitions.
|
||||
- **FR-EX-3**: Each exercise shall specify:
|
||||
- `name`: string
|
||||
- `category` / `muscle_group`: (e.g., *Cuádriceps, Glúteo, Espalda, Hombro, Isquiotibiales, Pecho, Brazos, Core, Cardio*)
|
||||
- `equipment`: (e.g., *Smith machine, Dumbbell, Barbell, Cable/Machine, Band, Bodyweight*)
|
||||
- `default_metric_type`: default hint (*Reps-Weight*, *Duration*, *Distance-Duration*)
|
||||
- `default_metric`: default hint (*Reps-Weight*, *Duration*, *Distance-Duration*)
|
||||
- `instructions` / `cues`: optional text
|
||||
|
||||
### 4.3. Routine & Phase Management
|
||||
- **FR-RT-1**: Users can create, clone, rename, archive, and delete multiple routines.
|
||||
- **FR-RT-2**: Exactly one routine can be set as `Active` per user at any given time.
|
||||
- **FR-RT-2 (Application Policy)**: The application ensures at most one routine is set as `Active` per user at any given time.
|
||||
- **FR-RT-3**: A routine defines a 7-day weekly schedule (`Monday` through `Sunday`). Each weekday can be assigned as:
|
||||
- `Workout Day`
|
||||
- `Rest Day`
|
||||
- `Unscheduled Day`
|
||||
- **FR-RT-4**: A Workout Day within a routine contains an ordered list of:
|
||||
- **FR-RT-4**: A Workout Day within a routine contains:
|
||||
- **Exercise Prescriptions**: Target sets, target repetitions (or rep ranges, e.g. 10–12), optional target weight, optional unilateral indicator (`each leg / cada pie`), order index, and prescription notes.
|
||||
- **Session Activities / Instructions**: General instructions (e.g., *"Articular warm-up before session"* or *"15–20 min stationary bike or elliptical at moderate pace"*).
|
||||
- **Session Activities**: Non-set activities (e.g., *"Articular warm-up before session"* or *"15–20 min stationary bike or elliptical at moderate pace"*).
|
||||
- **FR-RT-5 (Progression Phases)**: Routines support declarative phases (e.g., Phase 1: Weeks 1–2 prescribing 3 sets; Phase 2: Week 3+ prescribing 4 sets). The active phase is determined deterministically by elapsed calendar weeks from the routine's activation date:
|
||||
$$\text{Week Index} = \left\lfloor \frac{\text{Date} - \text{ActivationDate}}{7} \right\rfloor + 1$$
|
||||
|
||||
### 4.4. Calendar & Scheduling
|
||||
- **FR-CAL-1**: The system shall provide an API for a weekly calendar view displaying projected `ScheduledWorkout` items alongside actual `WorkoutSession` instances across Monday–Sunday.
|
||||
- **FR-CAL-2**: The calendar shall distinguish between `Scheduled Workout Day`, `Rest Day`, `Active Recovery`, and `Unscheduled Day`.
|
||||
- **FR-CAL-2**: The calendar displays days as `Scheduled Workout Day`, `Rest Day`, or `Unscheduled Day`. Physical activity logged on a Rest day (e.g. Sunday cycling) is displayed as an ad-hoc session or active recovery activity.
|
||||
- **FR-CAL-3**: The calendar shall display historical weeks with immutable records of past performance.
|
||||
|
||||
### 4.5. Workout Execution & Runtime Logging
|
||||
- **FR-LOG-1 (Snapshot on Initiation)**: When a user initiates a workout for a calendar day, Praxis generates a `WorkoutSession` snapshot copying the prescribed exercises, sets, target values, and activities.
|
||||
- **FR-LOG-2 (Set-Level Performance)**: For each exercise, the user can log:
|
||||
- Set sequence number (1, 2, 3...)
|
||||
- **FR-LOG-1 (Snapshot on Initiation)**: When a user initiates a workout for a calendar day, Praxis generates a `WorkoutSession` containing a frozen `SessionPrescriptionSnapshot` of the prescribed exercises, sets, target values, and activities.
|
||||
- **FR-LOG-2 (Set-Level Performance)**: For each exercise performance, the user can log:
|
||||
- Actual repetitions completed
|
||||
- Actual weight used (in user's preferred unit: kg or lbs)
|
||||
- Actual duration in seconds (for timed sets like Planks)
|
||||
- RIR (Reps in Reserve) or RPE (optional)
|
||||
- Optional RIR (Reps in Reserve, 0–5)
|
||||
- Set-level notes
|
||||
- **FR-LOG-3 (Runtime Session Flexibility)**:
|
||||
- Users can append ad-hoc sets or remove prescribed sets.
|
||||
- Users can append ad-hoc sets or remove logged sets (by set identity).
|
||||
- Users can reorder exercises during execution.
|
||||
- Users can substitute an exercise on the fly with another exercise from the library, preserving the substitution event for auditing.
|
||||
- Users can substitute an exercise on the fly with another exercise from the catalog, preserving the substitution event for auditing.
|
||||
- Users can add completely unscheduled exercises to the active session.
|
||||
- **FR-LOG-4 (Ad-Hoc / Rest Day Logging)**: Users can initiate and log an ad-hoc session or active recovery (e.g., Sunday cycling) on any day without a prior scheduled prescription.
|
||||
- **FR-LOG-5 (Session Notes & Deviations)**: Users can record session-level notes (e.g. *"Gym was crowded, had to swap Smith machine for dumbbells"* or *"Fatigued, stopped 1 set early"*).
|
||||
- **FR-LOG-4 (Activity Logging)**: Users can record the execution of session activities (e.g., check off warm-up, record actual duration of cardio).
|
||||
- **FR-LOG-5 (Ad-Hoc / Rest Day Logging)**: Users can initiate and log an ad-hoc session or active recovery (e.g., Sunday cycling) on any day without a prior scheduled prescription.
|
||||
- **FR-LOG-6 (Session Notes & Deviations)**: Users can record session-level notes (e.g. *"Gym was crowded, had to swap Smith machine for dumbbells"* or *"Fatigued, stopped 1 set early"*).
|
||||
|
||||
### 4.6. Session Completion Semantics & Habit Adherence
|
||||
- **FR-STAT-1**: A `WorkoutSession` transitions through lifecycle states:
|
||||
@@ -154,31 +168,41 @@ flowchart TD
|
||||
- If 100% of prescribed sets/exercises completed $\rightarrow$ suggests `Completed`.
|
||||
- If $>0\%$ completed $\rightarrow$ suggests `Partially_Completed` with summary of completed vs omitted work.
|
||||
- User can confirm or override the final state.
|
||||
- **FR-STAT-4 (Factual Adherence Metrics)**: Rather than an arbitrary weighted score, adherence is reported as factual distribution rates over a selected evaluation window:
|
||||
- **FR-STAT-4 (Factual Adherence Metrics)**: Adherence is reported as factual distribution rates over a selected evaluation window:
|
||||
- `Completed Sessions Rate`: $N_{\text{completed}} / N_{\text{scheduled}}$
|
||||
- `Partial Sessions Rate`: $N_{\text{partial}} / N_{\text{scheduled}}$
|
||||
- `Skipped Sessions Rate`: $N_{\text{skipped}} / N_{\text{scheduled}}$
|
||||
- `Set Adherence Rate`: Total Sets Performed / Total Sets Prescribed
|
||||
|
||||
### 4.7. Progression & Performance Analytics
|
||||
- **FR-ANL-1 (Exercise History)**: For any exercise, the user can query past performances (chronological history of weights, reps, sets, and workload).
|
||||
- **FR-ANL-1 (Factual Exercise History)**: For any exercise, the user can query past performances (chronological history of weights, reps, sets, and workload). Substitutions contribute strictly to the performed exercise.
|
||||
- **FR-ANL-2 (Metric-Dependent Workload)**: For each session and per exercise, compute appropriate workload:
|
||||
- Weighted Repetitions: $\text{Volume} = \sum (\text{reps} \times \text{weight})$
|
||||
- Timed Exercises: $\text{Duration} = \sum \text{seconds}$
|
||||
- Distance: $\text{Distance} = \sum \text{kilometers/meters}$
|
||||
- **FR-ANL-3 (Personal Records & Estimated 1RM)**: The system shall calculate personal bests per exercise:
|
||||
- Max Weight Lifted
|
||||
- Max Volume in a Single Session
|
||||
- Estimated 1RM using Brzycki or Epley formula:
|
||||
$$\text{1RM}_{\text{Epley}} = w \times \left(1 + \frac{r}{30}\right)$$
|
||||
- **FR-ANL-4 (Trend Analytics)**: The system provides query endpoints for time-series trend analysis (weekly workload by muscle group, adherence rates by month, progression curves for core lifts).
|
||||
- **FR-ANL-3 (Trend Analytics)**: The system provides query endpoints for time-series trend analysis (weekly workload by muscle group, adherence rates by month, progression curves for core lifts).
|
||||
|
||||
---
|
||||
|
||||
## 5. Non-Functional & Architectural Requirements
|
||||
|
||||
- **NFR-ARCH-1 (API-First & Decoupled Frontend)**: The backend shall expose a clean, comprehensive REST/OpenAPI specification. The frontend is decoupled.
|
||||
- **NFR-ARCH-2 (Clean / Hexagonal Architecture)**: Domain entities (`User`, `Routine`, `WorkoutSession`, `Exercise`) contain pure business rules with zero dependencies on database ORMs or web frameworks.
|
||||
- **NFR-ARCH-2 (Clean / Hexagonal Architecture)**: Domain aggregates (`Routine`, `WorkoutSession`, `Exercise`) contain pure business rules with zero dependencies on database ORMs or web frameworks.
|
||||
- **NFR-ARCH-3 (Self-Hosted / Containerized)**: Deployable as a single Docker container or Docker Compose service with minimal resource footprint (< 256MB RAM idle) suited for homelab micro-servers.
|
||||
- **NFR-ARCH-4 (Zero External Cloud Reliance)**: Runs entirely on local infrastructure with SQLite or PostgreSQL; no third-party telemetry, proprietary clouds, or external API dependencies.
|
||||
- **NFR-ARCH-5 (Data Portability)**: Users can export their entire history, routines, and exercises as JSON / CSV at any time.
|
||||
|
||||
---
|
||||
|
||||
## 6. Implementation Scope Milestones
|
||||
|
||||
```mermaid
|
||||
timeline
|
||||
title Praxis Implementation Roadmap (Updated)
|
||||
section MVP (Foundation)
|
||||
Decoupled Auth (Header Adapter) : Domain Aggregates (Routine, WorkoutSession, Exercise) : SessionPrescriptionSnapshot Engine : Multi-Modal Set Logging & Activities : Smart Completion Suggestion : Factual Adherence & Metric Workload Analytics
|
||||
section Milestone 2 (Evolution)
|
||||
Estimated 1RM (Epley/Brzycki) & PR Tracking : Interactive Progression Visualizations : Automated Phase Transition Alerts : Workout Templates Import/Export (JSON/YAML) : Mobile-First PWA Client
|
||||
section Milestone 3 (Advanced)
|
||||
Rest Interval Timers : RPE & Effort Conversions : Equipment Availability Substitution Suggestions : Webhook Event Notifications
|
||||
```
|
||||
@@ -1,5 +1,5 @@
|
||||
version = 1
|
||||
revision = 3
|
||||
revision = 5
|
||||
requires-python = ">=3.13"
|
||||
resolution-markers = [
|
||||
"python_full_version >= '3.15'",
|
||||
@@ -113,11 +113,11 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "certifi"
|
||||
version = "2026.7.22"
|
||||
version = "2026.10.23"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
Reference in new issue
Block a user