chore(project): initialize scaffolding and baseline domain documentation

This commit is contained in:
kiskaadee committed 2026-09-24 01:34:37 -05:00
1 parent 809601ebb3
commit 65f72ad2a4
13 files changed
+2676 -1

No files matched your search

+1
View File
@@ -0,0 +1 @@
source .venv/bin/activate
+1
View File
@@ -0,0 +1 @@
3.13
+78
View File
@@ -0,0 +1,78 @@
# Praxis — Agent Guidelines & Architecture Rules
This repository contains **Praxis**, a self-hosted workout tracking and habit execution platform.
All AI coding assistants and contributors working on this codebase must adhere strictly to the architectural constraints, domain invariants, and coding conventions defined below.
---
## 1. Architectural Philosophy: Clean / Hexagonal Architecture
The codebase follows Ports & Adapters (Hexagonal Architecture) with explicit dependency direction:
```text
Interfaces (FastAPI, CLI)
↓
Application Layer (Use Cases, DTOs, Policies)
↓
Domain Layer (Aggregates, Entities, Value Objects)
↑
Infrastructure Layer (SQLAlchemy/SQLModel Repositories, Authelia Auth Adapter)
```
### Dependency Rules:
1. **Domain Purity**: The domain layer (`src/praxis/domain/`) must **never** import or depend on web frameworks (FastAPI, Starlette), ORMs (SQLModel, SQLAlchemy, Tortoise), or infrastructure libraries. Use standard library `dataclasses`, `enum`, `typing`, and pure Python logic.
2. **Ports Define Boundaries**: All external dependencies (database repositories, external identity adapters, time providers) must be declared as abstract interfaces/protocols in `src/praxis/application/ports/`.
3. **Adapters Implement Ports**: Specific technologies (PostgreSQL, SQLite, Authelia header extraction) live strictly in `src/praxis/infrastructure/adapters/`.
---
## 2. Core Domain Invariants (Non-Negotiable)
When authoring or modifying code, ensure these core domain invariants are never violated:
1. **Three-Layer Temporal Separation**:
- **Prescription** (*What was planned*): `Routine`, `WorkoutDay`, `ExercisePrescription`, `SessionActivity`, `Phase`.
- **Performance** (*What happened*): `WorkoutSession`, `SessionPrescriptionSnapshot`, `ExercisePerformance`, `SetPerformance`, `ActivityPerformance`.
- **Analysis** (*What can be derived*): Workload, adherence, and exercise histories derived purely from historical sessions.
2. **Snapshot Immutability**:
- When a `WorkoutSession` is initiated, `SessionPrescriptionSnapshot` freezes the planned work.
- Modifying a `Routine` template must **never** alter past or currently in-progress `WorkoutSession` records.
3. **Session Lifecycle Mutability**:
- While `status == In_Progress`, a `WorkoutSession`'s execution state is mutable (logging sets, adding movements, substituting exercises).
- Once marked `Completed`, `Partially_Completed`, or `Skipped`, the session is finalized and locked against further mutation.
4. **Substituted History Isolation**:
- If exercise $A$ is substituted with exercise $B$, the logged sets contribute strictly to the history of exercise $B$ (`performed_exercise_id`).
- The prescription snapshot retains $A$ (`planned_exercise_id`) for auditability, but analysis queries for $A$ must not include sets performed for $B$.
5. **Single-Active-Routine Enforcement**:
- `Routine` does not enforce single-active-routine itself (it cannot inspect other routines).
- This invariant is strictly orchestrated at the application level by `ActivateRoutineUseCase`.
6. **Metric Type Validation**:
- `SetPerformance` must validate its fields against the exercise's `MetricType` (reps required for `RepsWeight`, duration required for `Duration`).
---
## 3. Specification Documents as Source of Truth
Before proposing domain changes or implementing new features, consult the baseline documentation in `docs/`:
- [`docs/praxis-srs-v1.0.2.md`](docs/praxis-srs-v1.0.2.md): Canonical Software Requirements Specification.
- [`docs/praxis-domain-model-v1.0.1.md`](docs/praxis-domain-model-v1.0.1.md): Canonical Domain Model, Entities, Value Objects, Behavioral Contracts, and Use Cases.
If a requirement or design decision changes during development, update these specifications synchronously.
---
## 4. Testing Conventions
- **Domain Tests (`tests/unit/domain/`)**: Test aggregates, value objects, and domain policies in complete isolation without mocks or database fixtures.
- **Use Case Tests (`tests/unit/application/`)**: Test interactors using simple in-memory repository fakes (`InMemoryRoutineRepository`, etc.).
- **Integration Tests (`tests/integration/`)**: Test database adapters against SQLite (in-memory or file) or PostgreSQL test containers.
---
## 5. Rules of Engagement
- **Do not commit directly without explicit user instruction.**
- Keep PRs and changes focused: prefer atomic, well-tested domain increments.
- Follow PEP 8, enforce strict type annotations (`mypy` / `pyright`), and keep docstrings informative.
View File
Whitespace-only changes.
+92 -1
View File
@@ -1 +1,92 @@
# praxis
# Praxis
> *Praxis* (from Greek/Latin for *"the practical application of a plan"*) is a self-hosted workout execution and habit-tracking platform designed for homelab deployment.
Unlike conventional fitness apps that conflate planned routines with actual performance or impose punitive streak mechanics, Praxis is built around a strict **Three-Layer Temporal Model** and a clean hexagonal architecture.
---
## Architecture: The Three-Layer Temporal Model
```mermaid
flowchart TD
subgraph Layer1["1. Prescription (What was planned)"]
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
```
1. **Prescription**: Reusable `Routine` templates defining weekly schedules (`Monday`–`Sunday`), target exercises, reps/ranges, weights, durations, activities (warm-ups, cardio), and calendar-week **Progression Phases**.
2. **Performance**: Concrete `WorkoutSession` instances created upon initiation. Each session freezes an immutable `SessionPrescriptionSnapshot` while providing total runtime autonomy to log sets, adjust weights/reps, swap exercises, or add unscheduled movements without corrupting the routine template.
3. **Analysis**: Factual, deterministic observations (adherence rates, workload volumes, progression curves) derived purely from historical session logs rather than mutable counters.
---
## Core Domain Invariants
- **Snapshot Immutability**: When a session is initiated, its prescribed targets are frozen. Future modifications to routines never alter past or in-progress workouts.
- **Session Autonomy**: The routine is a guide, not a tyrant. Users can adjust sets/reps on the fly, substitute movements, or record ad-hoc workouts.
- **Substituted History Isolation**: Substituted exercises contribute strictly to the history of the *performed* movement, leaving the originally planned exercise clean while preserving the substitution audit trail.
- **Factual Adherence**: Consistency is measured via distribution rates (`Completed`, `Partially_Completed`, `Skipped`, and `Set Adherence Rate`) rather than fragile binary streaks.
- **Decoupled Identity**: Business logic depends only on internal `UserId`. External authentication (Authelia forward-auth headers, LLDAP) is isolated behind an `AuthProvider` port.
---
## Project Specifications
Detailed requirements and design documents are maintained in `docs/`:
| Document | Version | Description |
| :--- | :--- | :--- |
| [`docs/praxis-srs-v1.0.2.md`](docs/praxis-srs-v1.0.2.md) | `1.0.2-draft` | Software Requirements Specification baseline. |
| [`docs/praxis-domain-model-v1.0.1.md`](docs/praxis-domain-model-v1.0.1.md) | `1.0.1` | Domain aggregates, entities, value objects, behavioral contracts, and use cases. |
| [`docs/praxis-srs.md`](docs/praxis-srs.md) | `1.0.0` | Initial SRS draft (archived for comparison). |
| [`docs/praxis-domain-model.md`](docs/praxis-domain-model.md) | `1.0.0` | Initial domain model draft (archived for comparison). |
---
## Implementation Roadmap
- **Milestone 1 (MVP Foundation)**:
- Domain aggregates (`Routine`, `WorkoutSession`, `Exercise`) with zero external dependencies.
- Multi-modal set logging (reps/weight, timed duration) and session activities.
- Session snapshot engine (`SessionSnapshotFactory`) with phase set adjustments.
- Set-intent completion policy and factual adherence metrics.
- Hexagonal ports: `AuthProvider` (Authelia forward-auth), SQL repositories (SQLite/PostgreSQL).
- FastAPI / REST API endpoints and Dockerized homelab deployment.
- **Milestone 2 (Evolution)**:
- Estimated 1RM (Epley formula) and personal record (PR) calculations.
- Interactive progression and workload trend charts.
- Automated phase transition alerts.
- Mobile-first Progressive Web App (PWA).
- **Milestone 3 (Advanced)**:
- Rest interval timers and rest-pause tagging.
- Equipment availability substitution suggestions.
- Webhook event notifications.
---
## License
See [LICENSE](LICENSE) for details.
+25
View File
@@ -0,0 +1,25 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org/>
+474
View File
@@ -0,0 +1,474 @@
---
type: inbox
created: 2026-09-24
project: praxis
tags: [praxis, domain-model, oop, ddd, clean-architecture, homelab]
---
# Praxis — Domain Model & OOP Design Specification
**Document Version:** 1.0.1
**Date:** 2026-09-24
**Status:** Approved Domain Design Baseline
**Previous Version:** [praxis-domain-model.md](../inbox/praxis-domain-model.md)
**SRS Baseline:** [praxis-srs-v1.0.2.md](../inbox/praxis-srs-v1.0.2.md)
---
> [!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
```
+499
View File
@@ -0,0 +1,499 @@
---
type: inbox
created: 2026-09-24
project: praxis
tags: [praxis, domain-model, oop, ddd, clean-architecture, homelab]
---
# Praxis — Domain Model & OOP Design Specification
**Document Version:** 1.0.0
**Date:** 2026-09-24
**Status:** Approved Domain Design Baseline
**Prerequisite:** [praxis-srs.md](../inbox/praxis-srs.md)
---
## 1. Domain Topology & Conceptual Overview
Praxis translates user intent into physical performance and derived analytical insight. The architecture strictly enforces boundaries across three temporal layers:
```mermaid
classDiagram
direction TB
class User {
+UserId id
+ExternalIdentityId external_id
+UserProfile profile
+DateTime created_at
}
class Routine {
<<Aggregate Root>>
+RoutineId id
+UserId owner_id
+String name
+Boolean is_active
+DateTime activated_at
+List~Phase~ phases
+Map~Weekday, WorkoutDay~ schedule
+activate(now: DateTime)
+deactivate()
+get_current_phase(for_date: Date) Phase
}
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
+TargetSets target_sets
+RepRange rep_range
+TargetDuration target_duration
+Weight target_weight
+Boolean is_unilateral
+Int order_index
+String notes
}
class Exercise {
<<Entity / Reference>>
+ExerciseId id
+UserId author_id
+String name
+MuscleGroup category
+Equipment equipment
+MetricType default_metric
+String instructions
}
class WorkoutSession {
<<Aggregate Root>>
+SessionId id
+UserId user_id
+RoutineId routine_id
+Date session_date
+SessionStatus status
+DateTime started_at
+DateTime finished_at
+List~ExercisePerformance~ exercises
+List~ActivityPerformance~ activities
+String notes
+record_set(exercise_id, set_perf)
+substitute_exercise(original_id, new_id, reason)
+finish(policy: CompletionPolicy)
+skip(reason: String)
}
class ExercisePerformance {
<<Entity>>
+ExercisePerformanceId id
+ExerciseId prescribed_exercise_id
+ExerciseId actual_exercise_id
+PrescriptionSnapshot prescription_snapshot
+List~SetPerformance~ sets
+SubstitutionContext substitution
+String notes
}
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
}
User "1" --> "*" Routine : owns
Routine "1" *-- "7" WorkoutDay : contains
WorkoutDay "1" *-- "*" ExercisePrescription : prescribes
ExercisePrescription "1" --> "1" Exercise : targets
User "1" --> "*" WorkoutSession : performs
WorkoutSession "1" *-- "*" ExercisePerformance : tracks
ExercisePerformance "1" *-- "*" SetPerformance : logs
ExercisePerformance "1" --> "1" Exercise : references
```
---
## 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. |
### 2.2. Entities
- **`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.
---
## 3. Aggregate Boundaries & Encapsulation
```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]
end
subgraph Aggregate_WorkoutSession["Aggregate Root: WorkoutSession"]
WS_Root[WorkoutSession] --> EPF1[ExercisePerformance]
WS_Root --> EPF2[ExercisePerformance]
EPF1 --> SP1[SetPerformance 1]
EPF1 --> SP2[SetPerformance 2]
end
Aggregate_Routine -.->|Snapshot Factory creates| Aggregate_WorkoutSession
```
### 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.
### 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.
---
## 4. Detailed Specification of Key Objects
### 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**:
```mermaid
flowchart LR
subgraph Services["Domain Services & Policies"]
SSF[SessionSnapshotFactory]
CP[CompletionPolicy]
WLC[WorkloadCalculator]
AHC[AdherenceCalculator]
PRC[PersonalRecordCalculator]
end
R[Routine] --> SSF
WD[WorkoutDay] --> SSF
SSF --> WS[WorkoutSession]
WS --> CP
WS --> WLC
Hist[(WorkoutSession History)] --> AHC
Hist --> PRC
```
### 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.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.
---
### 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:
```mermaid
sequenceDiagram
autonumber
actor User
participant UC as InitiateWorkoutUseCase
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)
```
### 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.
---
## 7. Ports & Adapters Architecture (Hexagonal)
```mermaid
graph TD
subgraph DrivingAdapters["Driving / Primary Adapters (Incoming)"]
API[FastAPI / REST Controllers]
CLI[Admin / Seed CLI]
end
subgraph ApplicationCore["Application Core (Use Cases / Domain)"]
UC[Use Cases / Interactors]
DM[Domain Model & Policies]
end
subgraph DrivenPorts["Driven / Secondary Ports (Interfaces)"]
IPort_Auth[AuthProvider Port]
IPort_Routine[RoutineRepository Port]
IPort_Session[SessionRepository Port]
IPort_Exercise[ExerciseRepository Port]
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
```
### 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)`.
+199
View File
@@ -0,0 +1,199 @@
---
type: inbox
created: 2026-09-24
project: praxis
tags: [praxis, srs, homelab, workout-tracker, architecture]
---
# Software Requirements Specification (SRS)
## Project: Praxis — Personal Workout & Habit Tracking Platform
**Version:** 1.0.2-draft
**Date:** 2026-09-24
**Status:** Draft Baseline (Refined)
**Previous Version:** [praxis-srs.md](../inbox/praxis-srs.md)
---
> [!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
```
+174
View File
@@ -0,0 +1,174 @@
---
type: inbox
created: 2026-09-24
project: praxis
tags: [praxis, srs, homelab, workout-tracker, architecture]
---
# Software Requirements Specification (SRS)
## Project: Praxis — Personal Workout & Habit Tracking Platform
**Version:** 1.0.0-draft
**Date:** 2026-09-24
**Status:** Draft Baseline
---
## 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 --> ACT[Session Activity / Note]
R -.-> PH[Progression Phases]
end
subgraph Layer2["2. Performance (What actually happened)"]
SW[Scheduled Workout Projection] -->|Initiate| WS[Workout Session Snapshot]
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]
VOL[Metric-Dependent Workload]
PR[Personal Records & 1RM]
TRN[Longitudinal Progression]
end
Layer1 -->|Project into calendar| SW
Layer2 -->|Pure deterministic derivation| Layer3
```
---
## 2. Core Domain Glossary
| Term | Definition |
| :--- | :--- |
| **User** | Internal domain actor owning routines, exercise customizations, and workout history. |
| **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. |
| **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. |
| **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. **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.
---
## 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 exercises 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*)
- `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-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:
- **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"*).
- **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-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...)
- 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)
- Set-level notes
- **FR-LOG-3 (Runtime Session Flexibility)**:
- Users can append ad-hoc sets or remove prescribed sets.
- 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 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"*).
### 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)**: Rather than an arbitrary weighted score, 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-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).
---
## 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-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.
+22
View File
@@ -0,0 +1,22 @@
[project]
name = "praxis"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
authors = [
{ name = "kiskaadee", email = "fcortesbio@gmail.com" }
]
requires-python = ">=3.13"
dependencies = [
"fastapi[standard]>=0.141.1",
"pydantic-settings>=2.15.0",
"sqlalchemy[asyncio]>=2.0.54",
"sqlmodel>=0.0.47",
]
[project.scripts]
praxis = "praxis:main"
[build-system]
requires = ["uv_build>=0.12.16,<0.13.0"]
build-backend = "uv_build"
+2
View File
@@ -0,0 +1,2 @@
def main() -> None:
print("Hello from praxis!")
Generated
+1109
View File
File diff suppressed because it is too large. Load diff