@trainheroic-unofficial/cli 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/cli",
3
- "version": "0.1.0",
3
+ "version": "1.0.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
7
- "url": "https://github.com/alandotcom/trainheroic-skill.git",
7
+ "url": "https://github.com/alandotcom/trainheroic-unofficial.git",
8
8
  "directory": "packages/cli"
9
9
  },
10
10
  "description": "Command-line tool for the TrainHeroic coaching API.",
@@ -16,12 +16,13 @@
16
16
  "access": "public"
17
17
  },
18
18
  "files": [
19
- "dist"
19
+ "dist",
20
+ "skill"
20
21
  ],
21
22
  "dependencies": {
22
23
  "zod": "^4.4.3",
23
- "@trainheroic-unofficial/dto": "0.1.0",
24
- "@trainheroic-unofficial/js": "0.1.0"
24
+ "@trainheroic-unofficial/dto": "1.0.0",
25
+ "@trainheroic-unofficial/js": "1.0.0"
25
26
  },
26
27
  "devDependencies": {
27
28
  "@types/node": "^26.0.0",
@@ -0,0 +1,148 @@
1
+ ---
2
+ name: trainheroic-athlete
3
+ description: Read and analyze your own TrainHeroic training — scheduled and completed workouts, per-exercise history, PRs, working maxes, and lifetime totals — and optionally log completed sets. Use when the user wants to review their training history, track progress on a lift over time, look up PRs or working maxes, see what's programmed, export their training data, or log a workout result. Works for an athlete account or a coach account (a coach also has athlete-scoped training).
4
+ metadata:
5
+ author: alandotcom
6
+ version: "1.0.0"
7
+ ---
8
+
9
+ # TrainHeroic Athlete API
10
+
11
+ Authenticated access to the logged-in user's **own** training through the `trainheroic`
12
+ command-line tool (`@trainheroic-unofficial/cli`), which wraps the
13
+ `@trainheroic-unofficial/js` SDK. This is the athlete surface: history, scheduled workouts,
14
+ PRs, working maxes. For coaching (rosters, teams, programming, messaging) use the
15
+ `trainheroic-unofficial` skill instead.
16
+
17
+ - Base URL: `https://api.trainheroic.com`
18
+ - Login endpoint: `https://apis.trainheroic.com/auth`
19
+
20
+ A coach account works here too: a coach login also carries athlete scope, so these commands
21
+ return the coach's own training data.
22
+
23
+ ## Setup
24
+
25
+ ### CLI
26
+
27
+ Verify the CLI is available, then install if missing (no credentials required):
28
+
29
+ ```bash
30
+ which trainheroic || npm install -g @trainheroic-unofficial/cli
31
+ trainheroic install-skill # refreshes skill files in ~/.claude/skills/
32
+ ```
33
+
34
+ Set `TH` for the commands below:
35
+
36
+ ```bash
37
+ TH="trainheroic"
38
+ ```
39
+
40
+ ### Credentials
41
+
42
+ Credentials come from the environment (if unset, ask the user — do not guess):
43
+
44
+ ```bash
45
+ export TRAINHEROIC_EMAIL="athlete@example.com"
46
+ export TRAINHEROIC_PASSWORD="..."
47
+ ```
48
+
49
+ The CLI logs in, caches the session at `~/.trainheroic/session.json`, and re-authenticates
50
+ on a 401/403. Start with `$TH athlete whoami` to confirm auth and get your `id`. Run
51
+ `$TH help` for the full command list.
52
+
53
+ ## What you can do
54
+
55
+ | Goal | Command |
56
+ | ------------------------------------- | -------------------------------------------------------------------- |
57
+ | Lifetime totals + profile | `$TH athlete profile [--metric]` |
58
+ | Scheduled / completed workouts | `$TH athlete workouts --start Y-M-D --end Y-M-D [--raw] [--summary]` |
59
+ | Find an exercise you've logged | `$TH athlete exercises [--q <text>] [--limit N]` |
60
+ | One lift's PRs + history over time | `$TH athlete history <exerciseId> [--raw]` |
61
+ | Personal records for a lift | `$TH athlete prs <exerciseId>` |
62
+ | Last performance + PR as of a date | `$TH athlete stats <exerciseId> --date Y-M-D` |
63
+ | Working maxes (drive % prescriptions) | `$TH athlete working-maxes` |
64
+ | Benchmark leaderboard | `$TH athlete leaderboard <workoutId>` |
65
+ | Download all historicals to JSON | `$TH athlete export [--out dir] [--full]` |
66
+ | Log completed set results (gated) | `$TH athlete log-set --date Y-M-D --set <id> ... --yes` |
67
+
68
+ ## Reading training
69
+
70
+ Most analysis starts by finding the exercise id, then pulling its history:
71
+
72
+ ```bash
73
+ $TH athlete exercises --q "back squat" # -> id + title + positional units
74
+ $TH athlete history 1659830 # PRs + dated session time-series
75
+ $TH athlete stats 1659830 --date 2026-06-01
76
+ ```
77
+
78
+ `history` returns a presented view (PRs plus each session's date, summary `abr`, estimated
79
+ 1RM, and sets). Add `--raw` for the untouched API object.
80
+
81
+ `workouts` flattens each day into blocks and exercises with per-set prescriptions and
82
+ positional units:
83
+
84
+ ```bash
85
+ $TH athlete workouts --start 2026-06-01 --end 2026-06-14
86
+ ```
87
+
88
+ Add `--summary` for one compact row per session (date, title, logged flag, exercise/performed
89
+ counts) instead of every set — use it to scan a multi-week window, then re-query a single day
90
+ without it to see that day's sets. `--logged-only` keeps only sessions with logged sets;
91
+ `--limit N` returns the most recent N.
92
+
93
+ `profile` returns lifetime totals (reps, volume, sessions, first/last logged, hours) plus
94
+ the profile. Pass `--metric` for kg/metric totals.
95
+
96
+ ## Exporting your history
97
+
98
+ `$TH athlete export` writes your historicals to JSON files (default
99
+ `~/.trainheroic/athlete-export`): `profile.json`, `workouts.json` (a 2-year window by
100
+ default; override with `--start`/`--end`), `exercises.json` (the catalog), and
101
+ `working-maxes.json`. Add `--full` to also fetch each exercise's history into
102
+ `history/<id>.json` — that is one request per exercise (hundreds), so it is slower.
103
+
104
+ ```bash
105
+ $TH athlete export --out ./my-training # fast: workouts, catalog, maxes, profile
106
+ $TH athlete export --out ./my-training --full # also per-exercise history (slow)
107
+ ```
108
+
109
+ ## Logging a set
110
+
111
+ `$TH athlete log-set` writes completed results back to a workout (reps/weight per set),
112
+ marks the set completed, and the result shows up in your exercise history. **It is
113
+ athlete-facing**: it mutates your training log, which your coach can see, so confirm before
114
+ running and re-read the workout to check the result landed.
115
+
116
+ Get the `savedWorkoutSetId` and each `savedWorkoutSetExerciseId` from the raw workout
117
+ (`$TH athlete workouts --start <day> --end <day> --raw`, under
118
+ `summarizedSavedWorkout.saved_workout.workoutSets`). Then:
119
+
120
+ ```bash
121
+ $TH athlete log-set --date 2026-06-01 --set 1593305783 --yes \
122
+ '[{"savedWorkoutSetExerciseId": 2712369448, "sets": [{"param1": 3, "param2": 225}]}]'
123
+ ```
124
+
125
+ `--yes` is required. Confirm with the user before running it, and re-read the workout to
126
+ check the result landed as intended. `param1`/`param2` are the entered values by entry slot
127
+ (check the exercise's positional units first).
128
+
129
+ ## Gotchas
130
+
131
+ - `profile` must send `use_metric` and `stats` must send `date`, or the API returns 400.
132
+ The CLI fills `use_metric` (toggle with `--metric`); pass `--date` to `stats`.
133
+ - Units are **fixed per exercise** and surfaced positionally as `[param 1, param 2]` (e.g.
134
+ `["reps", "lb"]`). They are not labelled by role: some exercises reverse the slots.
135
+ - `log-set` writes to your coach-visible log. Gate it behind explicit user confirmation,
136
+ never run it autonomously, and verify the result. Its request shape was reverse-engineered
137
+ from the mobile app (a two-step write: log the exercise data, then mark the set completed).
138
+ - This API is undocumented and can change. `references/athlete-api.md` lists the endpoints
139
+ and shapes.
140
+
141
+ ## Beyond the CLI
142
+
143
+ The same SDK powers the local `@trainheroic-unofficial/athlete-mcp` stdio server (the same
144
+ tools as MCP tools) and the hosted Cloudflare worker. The hosted worker adds a **training
145
+ warehouse** (D1): `athlete_workouts_sync` / `athlete_training_sync` download your
146
+ historicals, and `athlete_workouts_stored` / `athlete_training_stored` query them — so you
147
+ can research your training over time without re-hitting the API. See
148
+ `references/athlete-api.md` for the warehouse tools.
@@ -0,0 +1,111 @@
1
+ # Athlete API reference
2
+
3
+ The athlete endpoints operate on the **logged-in user** (no athlete id in the path — the
4
+ session identifies you). Several need the numeric user id as a query arg; get it from
5
+ `GET /user/simple` (`.id`). All are on the default host `https://api.trainheroic.com` and
6
+ authenticate with the `session-token` header. Response schemas are loose (the API drifts);
7
+ only the fields below are relied on.
8
+
9
+ ## Identity & profile
10
+
11
+ | Endpoint | Notes |
12
+ | --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
13
+ | `GET /user/simple` | `id`, `roles`, `org_id`, name. The id is the tenant key for everything else. |
14
+ | `GET /v5/athleteProfile/summary?user_id={id}&use_metric={0\|1}` | Lifetime totals: `reps_sum`, `volume_sum`, `sessions_count`, `first_logged_date`, `last_logged_date`, `duration_hours`. **`use_metric` is required** — omitting it returns `400 Invalid data`. |
15
+ | `GET /v5/users/{id}` | Detailed profile: dob, gender, height/weight, `use_metric`, trial status. |
16
+ | `GET /1.0/athlete/prefs` | Notification + display preference flags. |
17
+
18
+ ## Workouts
19
+
20
+ `GET /3.0/athlete/programworkout/range?startDate={Y-M-D}&endDate={Y-M-D}` — scheduled and
21
+ completed workouts in an inclusive window. Each item:
22
+
23
+ - Top level: `id` (the programWorkout id), `date`, `workout_title`, `program_id`,
24
+ `program_title`, `team_id`, `team_title`.
25
+ - `summarizedSavedWorkout.workout`: `title`, `instruction` (coach note), `workoutSets[]`.
26
+ - Each set: `title`, `order`, `instruction`, `is_test`, `workoutSetExercises[]`.
27
+ - Each exercise: `exercise_id`, `title`, `instruction`, `param_1_type`, `param_2_type`,
28
+ and the prescription in `param_1_data_1..10` / `param_2_data_1..10` (one slot per set;
29
+ empty string for unused). Non-numeric prescriptions (`AMRAP`, `8-12`) appear as-is.
30
+ - `summarizedSavedWorkout.saved_workout`: the athlete's logged copy, with `workoutSets[]`
31
+ (plus `addedWorkoutSets[]` for work the athlete added) whose `id` is the
32
+ **savedWorkoutSetId** and whose `workoutSetExercises[].id` is the **savedWorkoutSetExerciseId**
33
+ — the ids the logging write targets. Each saved exercise's `workout_set_exercise_id` points
34
+ back at the prescription exercise's `id`.
35
+ - The athlete's entered values live in the same `param_1_data_1..10` / `param_2_data_1..10`
36
+ slots, but the saved copy **pre-fills those with the prescription**, so data presence does
37
+ not mean a set was logged. The reliable per-set "performed" signal is `param_{i}_made == 1`
38
+ (the same flag the logging write sets). The set/workout-level `completed` and
39
+ `percent_completed` are unreliable — a session routinely holds logged sets with those left
40
+ at 0.
41
+
42
+ The SDK's `presentAthleteWorkout` merges the two copies into `{ id, date, title, program, team,
43
+ instruction, logged, blocks: [{ order, title, instruction, isTest, exercises: [{ exerciseId,
44
+ title, instruction, units, prescribed, performed }] }] }`. `performed` holds the per-set values
45
+ the athlete logged (made-gated; empty when nothing was recorded), `logged` is true when any
46
+ exercise has `performed` values, and athlete-added/personal work with no prescription is
47
+ appended as its own blocks. No `--raw` is needed to read logged results.
48
+
49
+ ## Exercises, history, PRs
50
+
51
+ | Endpoint | Notes |
52
+ | ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
53
+ | `GET /v5/users/exercises/history` | The exercises you've logged: `id`, `title`, `param1Type`, `param2Type`, `prescription`, `isCircuit`. Use it to find an exercise id. |
54
+ | `GET /v5/exercises/{id}/history?userId={id}` | `liftPRs[]` (rep-max PRs), `history[]` (per-session: `dateCompleted`, `abr`, `bestEstimated1RM`, `savedWorkoutSetExerciseId`, `programWorkoutId`, `sets[]`, `repMaxes[]`). |
55
+ | `GET /v5/exercises/{id}/personalRecords` | PR rows with strength-standard `filters`. |
56
+ | `GET /v5/exercises/{id}/stats?userId={id}&date={Y-M-D}` | `isLift`, `lastPerformance`, `personalRecord`. **`date` is required** — omitting it returns `400 Invalid date parameter`. |
57
+ | `GET /v5/exercises/{id}` | Exercise detail: description, `param1Type`/`param2Type`, `units`, video. |
58
+ | `GET /2.0/athlete/workingMax` | Working max per exercise: `exercise_id`, `title`, `param_type`, `value`, `type_suffix`. |
59
+ | `GET /3.0/athlete/leaderboard/{workoutId}` | Leaderboard for a benchmark/test workout (`tests`, `results`, `testStats`). |
60
+
61
+ ## Logging a set (write)
62
+
63
+ Logging is a **two-step** write, reverse-engineered from the mobile app (verified against
64
+ captured traffic). The SDK's `logAthleteSet` performs both; it fetches the day's range to
65
+ resolve the ids from `summarizedSavedWorkout.saved_workout`.
66
+
67
+ 1. **Persist the entered data** — `PUT /1.0/athlete/savedworkoutsetexercise/{savedWorkoutSetExerciseId}`
68
+ with `{ id, saved_workout_set_id, workout_set_exercise_id, completed:1, param_N_made,
69
+ param_1_data_N, param_2_data_N (10 slots) }`. This is the only path that actually stores
70
+ reps/weight (and it alone surfaces the result in exercise history). The
71
+ `savedworkoutset`/`savedworkout` PUTs accept the same fields but **silently discard** the
72
+ `param_N_data` values.
73
+ 2. **Mark the set completed** — `PUT /1.0/athlete/savedworkoutset/{savedWorkoutSetId}` with
74
+ the camelCase in-memory model (`sessionId` ← `saved_workout.id`, `workoutSetId` ←
75
+ `workout_set_id`, `isSuperSet`, `exercises: [savedWorkoutSetExerciseId, …]`, `completed`).
76
+ A minimal `{id, sessionId, completed}` body returns 500 — the full mapped body is required.
77
+
78
+ There is no GET for a single saved workout set; read it from the workout range's
79
+ `saved_workout.workoutSets[]` (`id` = savedWorkoutSetId, `workoutSetExercises[].id` =
80
+ savedWorkoutSetExerciseId, `workoutSetExercises[].workout_set_exercise_id` = the template id).
81
+
82
+ ## MCP tools
83
+
84
+ The local `@trainheroic-unofficial/athlete-mcp` server and the hosted worker (for any
85
+ account) expose:
86
+
87
+ - Live reads: `athlete_whoami`, `athlete_profile`, `athlete_prefs`, `athlete_workouts`,
88
+ `athlete_exercises`, `athlete_exercise_history`, `athlete_personal_records`,
89
+ `athlete_exercise_stats`, `athlete_working_maxes`, `athlete_leaderboard`.
90
+ - Gated write: `athlete_log_set` (elicitation or `confirm:true`).
91
+
92
+ ## Warehouse tools (hosted worker only, D1-backed)
93
+
94
+ Download historicals into D1 so they can be queried over time without re-hitting the API.
95
+ One sync verb populates each zone; one query tool reads it.
96
+
97
+ - `athlete_workouts_sync { startDate, endDate }` → `athlete_workouts_stored { workoutId? |
98
+ startDate?/endDate? }`.
99
+ - `athlete_training_sync { exerciseId? | batchSize?, full? }` → `athlete_training_stored
100
+ { q? | exerciseId? (+prs?) | workingMaxes? }`. Omitting `exerciseId` syncs the catalog +
101
+ working maxes and drains a **batch** of un-synced exercises (repeat until `remaining` is 0
102
+ — bounded per call to respect Worker subrequest limits). `full:true` re-pulls every
103
+ exercise.
104
+
105
+ ## Still unexplored
106
+
107
+ - `PUT /1.0/athlete/savedworkout/{id}` (whole-workout sync; not needed for per-set logging,
108
+ which uses the two-step path above).
109
+ - `GET /v5/users/circuits/{recent,history}` (circuit history; shapes mirror the exercise
110
+ history list).
111
+ - `GET /1.0/athlete/programming/programs` (subscribed programs; empty for the test account).
@@ -0,0 +1,275 @@
1
+ ---
2
+ name: trainheroic-unofficial
3
+ description: Call the TrainHeroic coach/athlete REST API to manage athletes, teams, programs, sessions, exercises, and analytics. Use when the user wants to authenticate against TrainHeroic, automate coaching tasks, build workouts or session templates, create teams/athletes/custom exercises, resolve exercise IDs, or pull training, readiness, and analytics data.
4
+ metadata:
5
+ author: alandotcom
6
+ version: "2.0.0"
7
+ ---
8
+
9
+ # TrainHeroic API
10
+
11
+ Authenticated access to the TrainHeroic coaching API through the `trainheroic`
12
+ command-line tool (`@trainheroic-unofficial/cli`), which wraps the `@trainheroic-unofficial/js`
13
+ SDK: a spec-driven workout builder, an on-disk exercise cache, and gated messaging.
14
+
15
+ - Coach base URL: `https://api.trainheroic.com`
16
+ - Login endpoint: `https://apis.trainheroic.com/auth`
17
+
18
+ ## Setup
19
+
20
+ ### CLI
21
+
22
+ Before making API calls, verify the CLI is available:
23
+
24
+ ```bash
25
+ which trainheroic
26
+ ```
27
+
28
+ If not found, install it (no credentials required):
29
+
30
+ ```bash
31
+ npm install -g @trainheroic-unofficial/cli
32
+ trainheroic install-skill # also refreshes skill files in ~/.claude/skills/
33
+ ```
34
+
35
+ To update to the latest version:
36
+
37
+ ```bash
38
+ npm update -g @trainheroic-unofficial/cli
39
+ trainheroic install-skill # pick up any updated skill files
40
+ ```
41
+
42
+ Set `TH` to the binary name for the commands below:
43
+
44
+ ```bash
45
+ TH="trainheroic"
46
+ ```
47
+
48
+ ### Credentials
49
+
50
+ Credentials come from the environment (if unset, ask the user — do not guess):
51
+
52
+ ```bash
53
+ export TRAINHEROIC_EMAIL="coach@example.com"
54
+ export TRAINHEROIC_PASSWORD="..."
55
+ ```
56
+
57
+ The CLI logs in, caches the session at `~/.trainheroic/session.json` (mode 0600),
58
+ reuses it across invocations, and re-authenticates automatically on a 401/403. The
59
+ exercise library is cached at `~/.trainheroic/library.json`.
60
+
61
+ Start a session with `$TH whoami`: it confirms auth and returns the coach's `id`,
62
+ `org_id`, and roles that later calls reference. Run `$TH help` for the full command list.
63
+
64
+ ## Making requests
65
+
66
+ `$TH request <METHOD> <path> [json-body]` — path is everything after the base URL. It
67
+ prints `{status, ok, data}` and exits non-zero on failure. Bodies can be an inline JSON
68
+ argument, `--file <path>`, or piped on stdin.
69
+
70
+ ```bash
71
+ $TH request GET /v5/athletes
72
+ $TH request POST /v5/teams/4677619/teamCodes '{"type": 2}'
73
+ $TH request PUT /v5/athletes/archive '{"athleteIds": [123]}'
74
+ $TH request DELETE /v5/teamCodes/874586
75
+ cat block.json | $TH request POST /2.0/coach/calendar/saveProgramWorkoutSets
76
+ ```
77
+
78
+ A few endpoints live on the login host (`apis.trainheroic.com`); reach them with
79
+ `--base apis` (the default base is the coach host). `whoami` and `request` are top-level;
80
+ the coach reads live under the `coach` group: `coach head-coach`, `coach athletes`,
81
+ `coach programs`, `coach teams`, `coach notifications`, `coach analytics`,
82
+ `coach program <id>`, `coach team <id>`, `coach team-codes <id>`.
83
+
84
+ Load `references/api-reference.md` when you need an endpoint's exact request or
85
+ response shape, or an area not covered here.
86
+
87
+ ## What you can do
88
+
89
+ | Area | How |
90
+ | ------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
91
+ | Athletes | `$TH coach athletes`; `coach athlete-invite\|athlete-archive\|athlete-restore` |
92
+ | Teams / join codes | `$TH coach teams\|team <id>\|team-codes <id>`; `coach team-create\|team-update\|team-delete\|team-code-create\|team-code-delete` |
93
+ | Programs | `$TH coach programs`, `$TH coach program <id>` |
94
+ | Exercises | `$TH coach exercise resolve\|search\|get\|sync\|create\|forget\|stats` (below) |
95
+ | Sessions / workouts | `$TH coach workout build\|read\|publish\|remove`; `coach session-copy\|session-unpublish\|session-save-template` |
96
+ | Roster training | `$TH coach roster-activity\|athlete-training\|athlete-lift-history\|athlete-workouts` (read another athlete's training) |
97
+ | Log for an athlete | `$TH coach log-set` — record a roster athlete's reps/weights (real athletes only; see below) |
98
+ | Messaging | `$TH coach message list\|read\|draft\|send\|delete` (below) |
99
+ | Analytics | `$TH coach analytics` (category list); `$TH coach analytics-query --metric <key> ...` (the report) |
100
+
101
+ ## Resolving exercises
102
+
103
+ Do **not** dump `GET /v5/exerciseLibrary/all` (~2,400 rows) to find an ID. Use the
104
+ cache, which mirrors the library into `~/.trainheroic/library.json` and serves lookups
105
+ locally:
106
+
107
+ ```bash
108
+ $TH coach exercise resolve "Back Squat" # exact/best match -> id (+ unit labels)
109
+ $TH coach exercise search "incline press" # ranked candidates
110
+ $TH coach exercise sync --force # refresh the mirror (7-day TTL otherwise)
111
+ ```
112
+
113
+ `resolve` returns `match: null` plus a candidate list when a name is ambiguous; pick the
114
+ right ID from there. The mirror auto-refreshes on a 7-day TTL and on a miss.
115
+
116
+ After creating a custom exercise, go through the cache so the mirror stays current; after
117
+ deleting one via the API, drop it from the mirror:
118
+
119
+ ```bash
120
+ $TH coach exercise create '{"title":"Sandbag Clean","param_1_type":3,"param_2_type":1}'
121
+ $TH coach exercise forget 7721170 --yes # cache-only, run after an API delete
122
+ ```
123
+
124
+ `$TH coach exercise stats` shows the cached row count.
125
+
126
+ ## Building a workout
127
+
128
+ **Confirm the program before you build, and confirm before you publish.** Writing a
129
+ session to a real coaching calendar is athlete-facing and hard to undo. When the request
130
+ is at all ambiguous — which team/program/calendar, which date, the exact exercises,
131
+ sets/reps/load, distance units, or how a scheme should be structured — **ask clarifying
132
+ follow-up questions first; do not guess.** Restate the program you intend to build and get
133
+ explicit confirmation before publishing. Build a draft (the default), show the read-back
134
+ for review, and only publish once the user confirms.
135
+
136
+ `$TH coach workout build` runs the whole sequence (program → session → blocks → exercises),
137
+ fills every field that otherwise makes the exercise step return HTTP 500, encodes
138
+ prescriptions correctly, and prints unit advisories plus a read-back. Feed it a JSON spec
139
+ (inline, `--file`, or stdin):
140
+
141
+ ```bash
142
+ cat > day.json <<'JSON'
143
+ { "blocks": [
144
+ { "title": "Primary Press", "exercises": [
145
+ { "id": 1162, "title": "Bench Press", "reps": [10,10,8,8], "rpe": 8 } ] },
146
+ { "title": "Accessory", "instruction": "Superset", "exercises": [
147
+ { "id": 903, "title": "Dips", "sets": 3, "reps": 12, "rpe": 8 },
148
+ { "id": 6535, "title": "Tricep Pushdown", "reps": [15,15,15], "rpe": 8 } ] }
149
+ ] }
150
+ JSON
151
+
152
+ $TH coach workout build --program 4980851 --date 2026-6-22 --file day.json # draft
153
+ $TH coach workout publish --pw <id> --yes # publish after review
154
+ ```
155
+
156
+ The build defaults to a **draft** (unpublished). Add `--publish --yes` to publish in one
157
+ step, or publish later with `$TH coach workout publish --pw <id> --yes`. Read a built session
158
+ back with `$TH coach workout read --program <id> --date Y-M-D --pw <id>`. There is no in-place
159
+ replace: to rebuild a date, remove the old session first with
160
+ `$TH coach workout remove --program <id> --pw <id> --yes`.
161
+
162
+ Two exercises in one block become a superset. Add `"leaderboard": "rounds"` (or
163
+ `reps`/`time`/`calories`/`meters`/… or `{"unit":"time","lowest_wins":true}`) to a block to
164
+ make it a scored Red Zone leaderboard (trophy + "FOR <UNIT>"). A top-level `"instruction"`
165
+ in the spec sets the session's Coach Instructions (the day-note above the blocks;
166
+ `PUT /3.0/coach/workout/{id}`, applied after the blocks save and without publishing — a
167
+ draft stays a draft). The read-back shows it under "Coach Instructions". For an **AMRAP**,
168
+ score by `rounds`/`reps` and program multiple sets (one per expected round); for **"for
169
+ time"**, score by `time`. Ask the coach when the scheme or score is ambiguous rather than
170
+ guessing.
171
+
172
+ Load `references/workout-creation.md` before building manually or for something the builder
173
+ does not cover (drop sets, pyramids, %-of-max, the raw field list, or the parameter-type
174
+ table).
175
+
176
+ ## Logging for an athlete ("Log for Athlete")
177
+
178
+ A coach can record an athlete's actual reps/weights on their behalf — the API equivalent of
179
+ the mobile app's "Log for Athlete". It is a two-step write the SDK handles in one call: the
180
+ per-exercise data PUT (`/1.0/coach/savedworkoutsetexercise/{id}/{athleteId}`, the only call
181
+ that stores reps/weight) then the block-completion PUT. **Athlete-facing — gate behind
182
+ `--yes`.**
183
+
184
+ ```bash
185
+ # 1) find the set + exercise ids for the athlete's day (raw exposes the ids):
186
+ $TH coach athlete-workouts --athlete 200004 --start 2026-06-22 --end 2026-06-22 --raw
187
+ # 2) log it (results JSON = one entry per exercise; each set is param1=reps, param2=weight):
188
+ $TH coach log-set --athlete 200004 --date 2026-06-22 --set 1594558978 --yes \
189
+ '[{"savedWorkoutSetExerciseId":2714543789,"sets":[{"param1":"10","param2":"225"},{"param1":"10","param2":"225"}]}]'
190
+ ```
191
+
192
+ **Only works for real (invited) athletes.** TrainHeroic's seeded _demo_ athletes are
193
+ read-only for results: the data-write returns `401` and the change never persists (the app
194
+ shows it optimistically but it is not saved). The official app hits the same 401 on demo
195
+ athletes. Read another athlete's training with `coach roster-activity`, `coach
196
+ athlete-training` (a logged month), `coach athlete-lift-history`, or `coach athlete-workouts`.
197
+
198
+ ## Messaging
199
+
200
+ A **stream** is a conversation (a team, or a 1:1 with an athlete); a **comment** is a
201
+ message. Sending is athlete-facing and immediate — TrainHeroic chat has no server-side
202
+ draft state, so a POST is delivered at once. The CLI therefore separates drafting from
203
+ sending and requires `--yes` to actually send or delete.
204
+
205
+ ```bash
206
+ $TH coach message list # conversations (id, kind, title)
207
+ $TH coach message read 37730920 # recent messages
208
+ $TH coach message draft 37730920 "Great session today!" # PREVIEW only — never sends
209
+ $TH coach message send 37730920 "Great session today!" --yes # delivers (gate behind user OK)
210
+ $TH coach message send 37730920 "Nice PR!" --reply-to 125652586 --yes # threaded reply
211
+ $TH coach message delete 37730920 <commentId> --yes # soft delete (destructive)
212
+ ```
213
+
214
+ Default to `draft`: it prints the exact payload and target without touching the account.
215
+ Run `send` only after the user confirms the wording and recipient. Check
216
+ `$TH coach notifications` (`countMessagingNotViewed`) first as a cheap "anything new?" gate.
217
+
218
+ ## Gotchas
219
+
220
+ Environment-specific facts that defy reasonable assumptions:
221
+
222
+ - **Sending a chat message needs `feed_id` in the body** — the stream id from the path,
223
+ repeated. `{"content": "..."}` returns `400 Invalid parameters`; so does trimming any
224
+ field. The CLI sends the full body. There is **no draft state**: a POST is delivered
225
+ immediately, so gate sends behind explicit user confirmation (`--yes`).
226
+ - **Units are fixed per exercise — you can't set them at prescribe time.** On save the API
227
+ discards the `param_1_type`/`param_2_type` you send and restores the exercise's library
228
+ defaults (the _values_ are kept). So the stock `Run` (miles) can't be made metric; a
229
+ "200 m run" on it shows as 200 _miles_. And `param_2_type` `2` (% of max) and `14` (RPE)
230
+ coerce to weight on a weight lift, rendering as pounds — put % or RPE in the
231
+ `instruction` (the builder does this from `rpe`). You _can_ add weight (`1`) to a
232
+ no-secondary-param lift (weighted Pull-Ups). Check units with `$TH coach exercise resolve`
233
+ (the `units` array, ordered by entry slot `[param 1, param 2]`); the builder prints a
234
+ warning when a sent type will be overridden. "Max"/"AMRAP" reps work as free text in the
235
+ rep slots.
236
+ - **`saveWorkoutSetExercises` returns HTTP 500** unless every field is present: all ten
237
+ `param_1_data_N`/`param_2_data_N` slots (empty string for unused), `set_num`, `key`,
238
+ `setKey`, `eType`, `tags`, `use_count`. The builder fills these — prefer it over raw calls.
239
+ - **`GET /1.0/coach/programs/edit/{cal}/{y}/{m}/{d}` returns every session in that date's
240
+ _month_** — not just the day, and not the whole calendar. Match yours by the `id`
241
+ returned at create time, not `programWorkouts[0]`; to read a whole program, walk month by
242
+ month.
243
+ - **A created session exposes two IDs**: `workout_id` (for adding blocks) and `id` (the
244
+ programWorkout id, used to publish and to delete; the CLI calls it `pw`).
245
+ - **The API ignores the exercise `title` you send** and uses the real title for
246
+ `exercise_id`; it also overrides both `param_1_type` and `param_2_type` to the exercise
247
+ default (see the units gotcha above).
248
+ - **Response envelopes vary.** `2.0/coach/*` tag/exercise endpoints wrap data as
249
+ `{"success": 1, "data": {...}}`; most others return bare objects/arrays.
250
+ - **This API is undocumented and can change.** `references/api-reference.md` has a "Still
251
+ Unexplored" section listing known gaps.
252
+ - **Destructive actions always require explicit user action.** For any call that deletes,
253
+ archives, or removes live data — archive/restore athlete, delete team, delete custom
254
+ exercise, remove or unpublish a session, delete team code, delete a message — and for
255
+ **sending a chat message** (athlete-facing, instant, no draft state) — you must:
256
+ 1. **never run it autonomously** (no destructive call without the user's explicit
257
+ go-ahead in the moment — prior approval does not carry over to a new action);
258
+ 2. **print a clear WARNING** stating exactly what will be affected, that it acts on the
259
+ live account, and that it is hard or impossible to undo;
260
+ 3. **offer the user the option to do it themselves** — hand them the exact command (e.g.
261
+ `$TH request DELETE /v5/teamCodes/874586`) or the UI steps.
262
+
263
+ The CLI enforces a `--yes` flag on `coach message send`/`coach message delete`,
264
+ `coach workout publish`, `coach workout remove`, `coach exercise forget`, `coach
265
+ athlete-invite`, `coach athlete-archive`, `coach team-delete`, `coach team-code-delete`,
266
+ `coach session-unpublish`, and `coach log-set`, but the gate above still applies: confirm
267
+ in the moment before adding `--yes`.
268
+
269
+ ## Beyond the CLI
270
+
271
+ The same SDK powers two MCP servers (see `README.md`):
272
+ `@trainheroic-unofficial/coach-mcp` (local, single-user, stdio) and
273
+ `@trainheroic-unofficial/cloudflare` (hosted, multi-tenant). The hosted server adds a
274
+ programming/messaging history warehouse (D1); `references/data-warehouse.md` documents
275
+ those zones and the sync rules.