@trainheroic-unofficial/cli 1.1.1 → 1.3.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.
Files changed (2) hide show
  1. package/dist/cli.mjs +482 -51
  2. package/package.json +3 -3
package/dist/cli.mjs CHANGED
@@ -181,6 +181,26 @@ const logSetArgsSchema = z.object({
181
181
  */
182
182
  const coachLogSetArgsSchema = logSetArgsSchema.extend({ athleteId: idArgSchema });
183
183
  /**
184
+ * Args for the coach prescription-override write. Structurally the same as
185
+ * {@link coachLogSetArgsSchema} (athleteId + date + savedWorkoutSetId + per-exercise `sets`), but
186
+ * the values are prescribed targets (param1 = reps, param2 = weight) written to the athlete's
187
+ * plan without marking the set performed. It is a separate schema (not an alias) so a future
188
+ * prescribe-only constraint can be added here without changing the log args, and the write
189
+ * replaces the slot's prescribed values for this athlete only.
190
+ */
191
+ const coachPrescribeSetArgsSchema = logSetArgsSchema.extend({ athleteId: idArgSchema });
192
+ /**
193
+ * Args for the coach per-athlete exercise swap: replace the exercise prescribed in one of a
194
+ * roster athlete's saved-workout slots with a different exercise, the API equivalent of the
195
+ * app's per-athlete "swap exercise". `savedWorkoutSetExerciseId` is that athlete's own slot id
196
+ * (the same id `coachLogSetArgsSchema` uses, read off athlete_saved_workouts raw);
197
+ * `exerciseId` is the replacement exercise. The team/program prescription is left untouched.
198
+ */
199
+ const swapAthleteExerciseArgsSchema = z.object({
200
+ savedWorkoutSetExerciseId: idArgSchema,
201
+ exerciseId: idArgSchema
202
+ });
203
+ /**
184
204
  * Args for logging a whole session by exercise (rather than by saved-workout-set id). Each
185
205
  * exercise carries its entered sets and an optional 1-based `order`. The athlete path creates
186
206
  * or reuses a personal session for the date and logs against it; the coach path resolves each
@@ -455,6 +475,14 @@ function coerceInt(value) {
455
475
  }
456
476
  return null;
457
477
  }
478
+ function coerceNum(value) {
479
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
480
+ if (typeof value === "string" && value.trim() !== "") {
481
+ const n = Number(value);
482
+ return Number.isFinite(n) ? n : null;
483
+ }
484
+ return null;
485
+ }
458
486
  function unitLabel(paramType) {
459
487
  const t = coerceInt(paramType);
460
488
  if (t === null) return null;
@@ -1002,29 +1030,59 @@ function presentCoachAthleteTraining(raw, athleteId, year, month) {
1002
1030
  }
1003
1031
  const MAX_PARAM_SLOTS = 10;
1004
1032
  /**
1005
- * Build the body for `PUT /1.0/athlete/savedworkoutsetexercise/{id}`. The body uses
1006
- * snake_case keys matching the live API response shape. Each set slot (1-10) gets a
1007
- * `param_N_made` flag (1 if data is present, 0 otherwise) and `param_1_data_N` /
1008
- * `param_2_data_N` string values.
1033
+ * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
1034
+ * {@link SetResult}[]. The dto schemas validate ids as a number or a numeric string and leave
1035
+ * empty param slots optional; this narrows the id to a number and copies only the present per-set
1036
+ * values (so the per-set type stays free of `undefined` under exactOptionalPropertyTypes). Shared
1037
+ * by the MCP tools and the CLI so the mapping lives in one place rather than once per surface.
1038
+ */
1039
+ function toSetResults(results) {
1040
+ return results.map((r) => {
1041
+ const id = coerceInt(r.savedWorkoutSetExerciseId);
1042
+ if (id === null) throw new Error(`Invalid savedWorkoutSetExerciseId: ${String(r.savedWorkoutSetExerciseId)}`);
1043
+ return {
1044
+ savedWorkoutSetExerciseId: id,
1045
+ sets: r.sets.map((s) => {
1046
+ const slot = {};
1047
+ if (s.param1 !== void 0) slot.param1 = s.param1;
1048
+ if (s.param2 !== void 0) slot.param2 = s.param2;
1049
+ return slot;
1050
+ })
1051
+ };
1052
+ });
1053
+ }
1054
+ /**
1055
+ * Build the body for `PUT /1.0/{role}/savedworkoutsetexercise/{id}`. The body uses snake_case
1056
+ * keys matching the live API response shape. Each set slot (1-10) carries `param_1_data_N` /
1057
+ * `param_2_data_N` string values plus a `param_N_made` flag.
1058
+ *
1059
+ * `mode` selects which write this is — the same endpoint serves both:
1060
+ * - `"log"`: the values ARE a performed result, so `param_N_made` is 1 where the slot has data
1061
+ * and the exercise `completed` flag is 1 when any set has data.
1062
+ * - `"prescribe"`: the values are prescribed targets, written with every `param_N_made` and
1063
+ * `completed` left at 0 so the set is not marked done. This matches what the app sends when a
1064
+ * coach edits an athlete's prescribed reps/weight.
1009
1065
  *
1010
1066
  * Only `savedWorkoutSetExerciseId`, `savedWorkoutSetId`, and `workoutSetExerciseId` are
1011
1067
  * required from the live exercise record; everything else is derived from `results`.
1012
1068
  *
1013
- * Exported for unit testing — callers should use `logAthleteSet` instead.
1069
+ * Exported for unit testing — callers should use `logAthleteSet` / `prescribeForAthlete` instead.
1014
1070
  */
1015
- function buildExerciseLogPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results) {
1071
+ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results, mode) {
1016
1072
  if (results.length > MAX_PARAM_SLOTS) throw new Error(`At most ${MAX_PARAM_SLOTS} sets are supported per exercise; got ${results.length}.`);
1073
+ const performed = mode === "log";
1074
+ const hasData = results.some((s) => s.param1 !== void 0 || s.param2 !== void 0);
1017
1075
  const body = {
1018
1076
  id: savedWorkoutSetExerciseId,
1019
1077
  saved_workout_set_id: savedWorkoutSetId,
1020
1078
  workout_set_exercise_id: workoutSetExerciseId,
1021
- completed: results.some((s) => s.param1 !== void 0 || s.param2 !== void 0) ? 1 : 0
1079
+ completed: performed && hasData ? 1 : 0
1022
1080
  };
1023
1081
  for (let i = 1; i <= MAX_PARAM_SLOTS; i += 1) {
1024
1082
  const slot = results[i - 1];
1025
1083
  const p1 = slot?.param1 !== void 0 ? String(slot.param1) : "";
1026
1084
  const p2 = slot?.param2 !== void 0 ? String(slot.param2) : "";
1027
- body[`param_${i}_made`] = p1 !== "" || p2 !== "" ? 1 : 0;
1085
+ body[`param_${i}_made`] = performed && (p1 !== "" || p2 !== "") ? 1 : 0;
1028
1086
  body[`param_1_data_${i}`] = p1;
1029
1087
  body[`param_2_data_${i}`] = p2;
1030
1088
  }
@@ -1125,7 +1183,11 @@ function buildSetCompletePayload(rawSet, exerciseIds, complete) {
1125
1183
  * by the respective PUT bodies.
1126
1184
  */
1127
1185
  async function logAthleteSet(client, args) {
1128
- return writeSetResults(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId, args.results);
1186
+ const r = await writeSetResults(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId, args.results, "log");
1187
+ return {
1188
+ savedWorkoutSetId: r.savedWorkoutSetId,
1189
+ exercisesLogged: r.exercisesWritten
1190
+ };
1129
1191
  }
1130
1192
  /**
1131
1193
  * Coach "Log for Athlete": record set results for a roster athlete on their behalf, via the
@@ -1139,24 +1201,94 @@ async function logAthleteSet(client, args) {
1139
1201
  */
1140
1202
  async function logForAthlete(client, args) {
1141
1203
  const workouts = await fetchCoachAthleteWorkouts(client, args.athleteId, args.date, args.date);
1142
- return writeSetResults(client, {
1204
+ const r = await writeSetResults(client, {
1143
1205
  role: "coach",
1144
1206
  athleteId: args.athleteId
1145
- }, workouts, args.savedWorkoutSetId, args.results);
1207
+ }, workouts, args.savedWorkoutSetId, args.results, "log");
1208
+ return {
1209
+ savedWorkoutSetId: r.savedWorkoutSetId,
1210
+ exercisesLogged: r.exercisesWritten
1211
+ };
1146
1212
  }
1147
1213
  /**
1148
- * Shared two-step set-log write behind {@link logAthleteSet} and {@link logForAthlete}.
1149
- * `target` selects the surface: `athlete` writes `/1.0/athlete/...`; `coach` writes
1150
- * `/1.0/coach/...{athleteId}` and stamps `athleteId` into each body. Step 1 PUTs each
1151
- * exercise's entered data to its own endpoint (the only path that actually stores reps and
1152
- * weight). Step 2 marks the set completed; that body needs the app's camelCase in-memory
1153
- * shape and the full list of savedWorkoutSetExercise IDs in the set (not only the logged ones).
1214
+ * Coach prescription override: set the prescribed reps/weight for one of a roster athlete's saved
1215
+ * workout sets WITHOUT marking it performed — the API equivalent of the app's editing an athlete's
1216
+ * prescribed values. Writes each exercise's per-set targets via
1217
+ * `PUT /1.0/coach/savedworkoutsetexercise/{id}/{athleteId}` with `param_N_made = 0` /
1218
+ * `completed = 0`, and (unlike {@link logForAthlete}) skips the set-completion step, so the set
1219
+ * stays open for the athlete to log against.
1220
+ *
1221
+ * Overrides only this athlete's copy of the set; the team/program prescription is untouched, so
1222
+ * other athletes on the same program keep the original targets. The write REPLACES the slot's
1223
+ * prescribed values, so pass the full per-set prescription you want — `param1` is reps, `param2`
1224
+ * is weight, and an omitted param is written empty (clearing it), not left as-is.
1225
+ *
1226
+ * NOTE: TrainHeroic's seeded *demo* athletes are read-only and return 401/403; real (invited)
1227
+ * athletes accept it.
1154
1228
  */
1155
- async function writeSetResults(client, target, workouts, savedWorkoutSetId, results) {
1229
+ async function prescribeForAthlete(client, args) {
1230
+ const workouts = await fetchCoachAthleteWorkouts(client, args.athleteId, args.date, args.date);
1231
+ const r = await writeSetResults(client, {
1232
+ role: "coach",
1233
+ athleteId: args.athleteId
1234
+ }, workouts, args.savedWorkoutSetId, args.results, "prescribe");
1235
+ return {
1236
+ savedWorkoutSetId: r.savedWorkoutSetId,
1237
+ exercisesPrescribed: r.exercisesWritten
1238
+ };
1239
+ }
1240
+ /**
1241
+ * Swap the exercise prescribed in one of an athlete's saved-workout slots for a different
1242
+ * exercise — the API equivalent of the app's per-athlete "swap exercise":
1243
+ * `PUT /v5/savedWorkoutSetExercises/{savedWorkoutSetExerciseId}?exerciseId={exerciseId}` with an
1244
+ * empty body. The new exercise rides in the query string, not the body.
1245
+ *
1246
+ * This overrides only this athlete's copy of the slot; the underlying team/program prescription
1247
+ * (`workout_set_exercise.exercise_id`) is untouched, so other athletes on the same program keep
1248
+ * the original exercise. A coach's session token may write another user's row because the row
1249
+ * already carries its owner's `user_id`.
1250
+ *
1251
+ * `savedWorkoutSetExerciseId` is the same id {@link logForAthlete}/{@link logAthleteSet} use,
1252
+ * read off the athlete's saved workouts (the raw view). `exerciseId` is any exercise id the org
1253
+ * can use (resolve one via the exercise index).
1254
+ *
1255
+ * NOTE: as with logging, TrainHeroic's seeded *demo* athletes are read-only and return 401/403;
1256
+ * real (invited) athletes accept the swap.
1257
+ */
1258
+ async function swapAthleteExercise(client, args) {
1259
+ const res = await client.request("PUT", `/v5/savedWorkoutSetExercises/${args.savedWorkoutSetExerciseId}?exerciseId=${args.exerciseId}`);
1260
+ if (!res.ok) {
1261
+ const readOnly = res.status === 401 || res.status === 403 ? ` Athlete may be read-only for changes — TrainHeroic's seeded demo/sample athletes return ${res.status} here; swaps only persist for real (invited) athletes.` : "";
1262
+ throw new Error(`Swap failed (HTTP ${res.status}) for savedWorkoutSetExercise ${args.savedWorkoutSetExerciseId}.${readOnly}`);
1263
+ }
1264
+ const row = isRecord(res.data) ? res.data : {};
1265
+ const template = isRecord(row.workout_set_exercise) ? row.workout_set_exercise : {};
1266
+ const exercise = isRecord(row.exercise) ? row.exercise : {};
1267
+ return {
1268
+ savedWorkoutSetExerciseId: args.savedWorkoutSetExerciseId,
1269
+ athleteId: coerceInt(row.user_id),
1270
+ newExerciseId: coerceInt(row.exercise_id) ?? args.exerciseId,
1271
+ newExerciseTitle: str$1(exercise.title),
1272
+ originalTeamExerciseId: coerceInt(template.exercise_id)
1273
+ };
1274
+ }
1275
+ /**
1276
+ * Shared set-write behind {@link logAthleteSet}, {@link logForAthlete}, and
1277
+ * {@link prescribeForAthlete}. `target` selects the surface: `athlete` writes `/1.0/athlete/...`;
1278
+ * `coach` writes `/1.0/coach/...{athleteId}` and stamps `athleteId` into each body.
1279
+ *
1280
+ * Step 1 PUTs each exercise's per-set values to its own endpoint (the only path that actually
1281
+ * stores reps and weight). `mode` decides what those values mean: `"log"` records them as a
1282
+ * performed result and runs Step 2, which marks the set completed (that body needs the app's
1283
+ * camelCase in-memory shape and the full list of savedWorkoutSetExercise IDs in the set, not only
1284
+ * the written ones); `"prescribe"` writes them as a prescription and skips Step 2, leaving the set
1285
+ * open.
1286
+ */
1287
+ async function writeSetResults(client, target, workouts, savedWorkoutSetId, results, mode) {
1156
1288
  const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
1157
1289
  const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
1158
1290
  const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
1159
- let exercisesLogged = 0;
1291
+ let exercisesWritten = 0;
1160
1292
  for (const result of results) {
1161
1293
  const ex = exercises.find((e) => coerceInt(e.id) === result.savedWorkoutSetExerciseId);
1162
1294
  if (!ex) {
@@ -1170,25 +1302,27 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1170
1302
  const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
1171
1303
  if (!workoutSetExerciseId) throw new Error(`Could not resolve workout_set_exercise_id for exercise ${result.savedWorkoutSetExerciseId}.`);
1172
1304
  const body = {
1173
- ...buildExerciseLogPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets),
1305
+ ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode),
1174
1306
  ...extra
1175
1307
  };
1176
1308
  const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
1177
1309
  if (!res.ok) {
1178
- const readOnly = target.role === "coach" && (res.status === 401 || res.status === 403) ? ` Athlete ${target.athleteId} appears to be read-only for results — TrainHeroic's seeded demo/sample athletes return ${res.status} here; results only persist for real (invited) athletes.` : "";
1179
- throw new Error(`Failed to log exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).${readOnly}`);
1310
+ const readOnly = target.role === "coach" && (res.status === 401 || res.status === 403) ? ` Athlete ${target.athleteId} appears to be read-only for changes — TrainHeroic's seeded demo/sample athletes return ${res.status} here; writes only persist for real (invited) athletes.` : "";
1311
+ throw new Error(`Failed to write exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).${readOnly}`);
1180
1312
  }
1181
- exercisesLogged += 1;
1313
+ exercisesWritten += 1;
1314
+ }
1315
+ if (mode === "log") {
1316
+ const setBody = {
1317
+ ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
1318
+ ...extra
1319
+ };
1320
+ const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
1321
+ if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
1182
1322
  }
1183
- const setBody = {
1184
- ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
1185
- ...extra
1186
- };
1187
- const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
1188
- if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
1189
1323
  return {
1190
1324
  savedWorkoutSetId,
1191
- exercisesLogged
1325
+ exercisesWritten
1192
1326
  };
1193
1327
  }
1194
1328
  /**
@@ -1430,6 +1564,7 @@ function presentExerciseHistory(detail) {
1430
1564
  description: p.description ?? null,
1431
1565
  reps: p.reps ?? null,
1432
1566
  weight: p.weight ?? null,
1567
+ units: p.units ?? null,
1433
1568
  date: p.dateCompleted ?? null
1434
1569
  })),
1435
1570
  sessions: (detail.history ?? []).map((h) => ({
@@ -1447,6 +1582,37 @@ function presentExerciseHistory(detail) {
1447
1582
  function emailList(emails) {
1448
1583
  return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
1449
1584
  }
1585
+ /** The display name on a /v5/athletes row: `fullName` (e.g. "Cohen, A"), else first+last. */
1586
+ function rosterName(rec) {
1587
+ const full = typeof rec.fullName === "string" ? rec.fullName.trim() : "";
1588
+ if (full !== "") return full;
1589
+ const combined = `${typeof rec.firstName === "string" ? rec.firstName : ""} ${typeof rec.lastName === "string" ? rec.lastName : ""}`.trim();
1590
+ return combined !== "" ? combined : null;
1591
+ }
1592
+ /**
1593
+ * The coach's roster as id + display name, from /v5/athletes. One home for the id coercion and the
1594
+ * name-field choice (the API uses `fullName` / `firstName`+`lastName`), so the CLI, the MCP tools,
1595
+ * and the warehouse store map the roster identically. Includes the account owner and
1596
+ * demo/placeholder athletes (the raw roster does); pass `ids` to keep only a subset.
1597
+ */
1598
+ async function fetchCoachRoster(client, ids) {
1599
+ const res = await client.request("GET", "/v5/athletes");
1600
+ if (!res.ok || !Array.isArray(res.data)) throw new Error(`List athletes failed (HTTP ${res.status}).`);
1601
+ const keep = ids && ids.length > 0 ? new Set(ids) : null;
1602
+ const out = [];
1603
+ for (const row of res.data) {
1604
+ if (typeof row !== "object" || row === null) continue;
1605
+ const rec = row;
1606
+ const id = coerceInt(rec.id);
1607
+ if (id === null || id <= 0) continue;
1608
+ if (keep && !keep.has(id)) continue;
1609
+ out.push({
1610
+ id,
1611
+ name: rosterName(rec)
1612
+ });
1613
+ }
1614
+ return out;
1615
+ }
1450
1616
  /**
1451
1617
  * Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
1452
1618
  * addresses (`POST /v5/emails/validate`), then invite the validated ones
@@ -1726,6 +1892,213 @@ async function teamVolume(client, args) {
1726
1892
  };
1727
1893
  }
1728
1894
  //#endregion
1895
+ //#region ../js/src/main-lifts.ts
1896
+ /**
1897
+ * The "main lifts" — Big 4 plus the two Olympic lifts. ORDER MATTERS: a title is classified by the
1898
+ * first family that matches, so the more specific / easily-confused families come before the broad
1899
+ * overhead-press rule. That ordering is why "Bench Press" classifies as `bench` and never gets
1900
+ * swept up as an overhead press, and why "Clean & Jerk" is not mistaken for a clean-only movement.
1901
+ * This is the single place to edit the lift set.
1902
+ */
1903
+ const MAIN_LIFT_FAMILIES = [
1904
+ {
1905
+ key: "cleanjerk",
1906
+ label: "Clean & Jerk",
1907
+ matches: (t) => t.includes("jerk") || t.includes("clean") && !t.includes("clean pull")
1908
+ },
1909
+ {
1910
+ key: "snatch",
1911
+ label: "Snatch",
1912
+ matches: (t) => t.includes("snatch")
1913
+ },
1914
+ {
1915
+ key: "deadlift",
1916
+ label: "Deadlift",
1917
+ matches: (t) => t.includes("deadlift")
1918
+ },
1919
+ {
1920
+ key: "squat",
1921
+ label: "Squat",
1922
+ matches: (t) => t.includes("squat")
1923
+ },
1924
+ {
1925
+ key: "bench",
1926
+ label: "Bench Press",
1927
+ matches: (t) => t.includes("bench")
1928
+ },
1929
+ {
1930
+ key: "overhead",
1931
+ label: "Overhead Press",
1932
+ matches: (t) => t.includes("ohp") || (t.includes("overhead") || t.includes("shoulder") || t.includes("military") || t.includes("strict") || t.includes("push")) && t.includes("press")
1933
+ }
1934
+ ];
1935
+ /** The lift family a logged exercise title belongs to, or null if it is not a main lift. */
1936
+ function classifyMainLift(title) {
1937
+ const t = title.toLowerCase();
1938
+ for (const family of MAIN_LIFT_FAMILIES) if (family.matches(t)) return family.key;
1939
+ return null;
1940
+ }
1941
+ const DEFAULT_MONTHS = 12;
1942
+ function pad2(n) {
1943
+ return String(n).padStart(2, "0");
1944
+ }
1945
+ /** A local Date as a YYYY-MM-DD day string (the range endpoint's date format). */
1946
+ function isoDay(d) {
1947
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
1948
+ }
1949
+ /**
1950
+ * Discover a roster athlete's main lifts from what they actually logged. Reads the athlete's
1951
+ * logged workouts over the last `months` (default 12) — the program-workout range, the reliable
1952
+ * record of performed sets — buckets every performed exercise into a lift family, and for each
1953
+ * family picks the variant logged most often. Returns one entry per family the athlete has logged;
1954
+ * families they never trained are simply absent. (The monthly calendar summary is not used: it
1955
+ * comes back empty for some accounts that have logged sets in the range endpoint.)
1956
+ */
1957
+ async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
1958
+ const months = opts.months ?? DEFAULT_MONTHS;
1959
+ const now = opts.now ?? /* @__PURE__ */ new Date();
1960
+ const start = new Date(now.getFullYear(), now.getMonth() - (months - 1), 1);
1961
+ const tally = /* @__PURE__ */ new Map();
1962
+ let workouts = [];
1963
+ try {
1964
+ workouts = await fetchCoachAthleteWorkouts(client, athleteId, isoDay(start), isoDay(now));
1965
+ } catch {
1966
+ workouts = [];
1967
+ }
1968
+ for (const view of presentAthleteWorkouts(workouts)) for (const block of view.blocks) for (const ex of block.exercises) {
1969
+ if (ex.performed.length === 0 || ex.exerciseId === null) continue;
1970
+ const family = classifyMainLift(ex.title);
1971
+ if (family === null) continue;
1972
+ const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
1973
+ const prev = byId.get(ex.exerciseId);
1974
+ byId.set(ex.exerciseId, {
1975
+ count: (prev?.count ?? 0) + 1,
1976
+ title: prev?.title ?? ex.title
1977
+ });
1978
+ tally.set(family, byId);
1979
+ }
1980
+ const lifts = [];
1981
+ for (const family of MAIN_LIFT_FAMILIES) {
1982
+ const byId = tally.get(family.key);
1983
+ if (!byId || byId.size === 0) continue;
1984
+ let best = null;
1985
+ for (const [exerciseId, { count, title }] of byId) if (best === null || count > best.count || count === best.count && exerciseId < best.exerciseId) best = {
1986
+ exerciseId,
1987
+ count,
1988
+ title
1989
+ };
1990
+ if (best) lifts.push({
1991
+ family: family.key,
1992
+ label: family.label,
1993
+ exerciseId: best.exerciseId,
1994
+ title: best.title
1995
+ });
1996
+ }
1997
+ return {
1998
+ athleteId,
1999
+ athleteName: null,
2000
+ lifts
2001
+ };
2002
+ }
2003
+ const PR_CONCURRENCY = 5;
2004
+ /** The heaviest PR on an exercise's board (ties broken by more reps). */
2005
+ function bestPr(liftPRs) {
2006
+ let best = null;
2007
+ for (const pr of liftPRs) {
2008
+ const weight = coerceNum(pr.weight);
2009
+ if (weight === null) continue;
2010
+ const reps = coerceInt(pr.reps);
2011
+ if (best === null || weight > best.weight || weight === best.weight && (reps ?? 0) > (best.reps ?? 0)) best = {
2012
+ weight,
2013
+ reps,
2014
+ units: pr.units,
2015
+ date: pr.date
2016
+ };
2017
+ }
2018
+ return best;
2019
+ }
2020
+ /**
2021
+ * A roster athlete's best PR for each main lift. Discovers the lift variants they log
2022
+ * ({@link resolveAthleteMainLifts}), then pulls each variant's PR board and keeps the heaviest set.
2023
+ * The result always carries one entry per family in {@link MAIN_LIFT_FAMILIES} order; a family the
2024
+ * athlete has not logged comes back with null fields (the "no PR yet" case), so a dashboard can
2025
+ * render a stable row of columns.
2026
+ */
2027
+ async function fetchAthleteMainLiftPRs(client, athleteId, opts = {}) {
2028
+ const { athleteName, lifts } = await resolveAthleteMainLifts(client, athleteId, opts);
2029
+ const byFamily = new Map(lifts.map((l) => [l.family, l]));
2030
+ return {
2031
+ athleteId,
2032
+ athleteName,
2033
+ prs: await mapPool(MAIN_LIFT_FAMILIES, PR_CONCURRENCY, async (family) => {
2034
+ const lift = byFamily.get(family.key);
2035
+ const base = {
2036
+ family: family.key,
2037
+ label: family.label
2038
+ };
2039
+ const empty = {
2040
+ exerciseId: null,
2041
+ title: null,
2042
+ weight: null,
2043
+ reps: null,
2044
+ units: null,
2045
+ date: null
2046
+ };
2047
+ if (!lift) return {
2048
+ ...base,
2049
+ ...empty
2050
+ };
2051
+ const known = {
2052
+ exerciseId: lift.exerciseId,
2053
+ title: lift.title
2054
+ };
2055
+ try {
2056
+ const best = bestPr(presentExerciseHistory(await fetchExerciseHistoryDetail(client, lift.exerciseId, athleteId)).liftPRs);
2057
+ return {
2058
+ ...base,
2059
+ ...known,
2060
+ weight: best?.weight ?? null,
2061
+ reps: best?.reps ?? null,
2062
+ units: best?.units ?? null,
2063
+ date: best?.date ?? null
2064
+ };
2065
+ } catch {
2066
+ return {
2067
+ ...base,
2068
+ ...known,
2069
+ weight: null,
2070
+ reps: null,
2071
+ units: null,
2072
+ date: null
2073
+ };
2074
+ }
2075
+ })
2076
+ };
2077
+ }
2078
+ const ROSTER_CONCURRENCY = 4;
2079
+ /**
2080
+ * Every roster athlete's main-lift PRs in one call: list the roster ({@link fetchCoachRoster}) and
2081
+ * resolve each athlete's board ({@link fetchAthleteMainLiftPRs}), fanned out with a bounded pool.
2082
+ * `athleteIds` restricts to a subset (else the whole roster). Each entry's `athleteName` falls back
2083
+ * to the roster name when the per-athlete read can't supply one. This is the single roster-level
2084
+ * primitive the CLI, the MCP tool, and the warehouse store all build on.
2085
+ */
2086
+ async function fetchRosterMainLiftPRs(client, opts = {}) {
2087
+ const roster = await fetchCoachRoster(client, opts.athleteIds);
2088
+ const inner = {
2089
+ ...opts.months !== void 0 ? { months: opts.months } : {},
2090
+ ...opts.now !== void 0 ? { now: opts.now } : {}
2091
+ };
2092
+ return mapPool(roster, opts.concurrency ?? ROSTER_CONCURRENCY, async (athlete) => {
2093
+ const result = await fetchAthleteMainLiftPRs(client, athlete.id, inner);
2094
+ return {
2095
+ athleteId: athlete.id,
2096
+ athleteName: result.athleteName ?? athlete.name,
2097
+ prs: result.prs
2098
+ };
2099
+ });
2100
+ }
2101
+ //#endregion
1729
2102
  //#region ../js/src/util.ts
1730
2103
  /**
1731
2104
  * Drop the keys whose value is `undefined`, so the result can be passed to a function or
@@ -2388,16 +2761,30 @@ Coach — manage a roster (needs a coach account):
2388
2761
  coach athlete-workouts --athlete <id> --start Y-M-D --end Y-M-D [--logged-only] [--summary] [--raw|--log-ids] prescribed + logged work over a date range; --logged-only/--summary narrow it to what was actually logged; --log-ids prints just the savedWorkoutSetId + savedWorkoutSetExerciseId per set that log-set needs
2389
2762
  coach athlete-training --athlete <id> --year <YYYY> --month <1-12> sessions the athlete LOGGED in one month (empty = nothing logged that month, not an error)
2390
2763
  coach athlete-lift-history --athlete <id> --exercise <id> [--since Y-M-D] [--until Y-M-D] [--raw] one exercise's logged history + PRs
2764
+ coach main-lift-prs [--athlete <id>] [--athletes <id,id,...>] [--months <n>] best PRs for the main lifts (squat/bench/deadlift/overhead press/clean & jerk/snatch); auto-discovers the logged variant. With --athlete, one athlete; otherwise the whole roster (or --athletes subset)
2391
2765
 
2392
2766
  log for an athlete (record their reps/weights; real invited athletes only — demo/seeded ones 401):
2393
2767
  coach log-set --athlete <id> --date Y-M-D --set <savedWorkoutSetId> <resultsJson>|--file f --yes
2394
2768
  --date is the workout's SCHEDULED date (not necessarily today); get --set (savedWorkoutSetId)
2395
2769
  and each result's savedWorkoutSetExerciseId from 'coach athlete-workouts ... --log-ids'
2770
+ resultsJson: [{"savedWorkoutSetExerciseId":N,"sets":[{"param1":reps,"param2":weight}, ...]}, ...]
2396
2771
  coach log-session --athlete <id> --date Y-M-D <exercisesJson>|--file f --yes
2397
2772
  log by exercise instead of by set id: each exercise (exerciseId + sets) is matched to a set
2398
2773
  already on the athlete's calendar that day. The API can't put an off-plan session on an
2399
2774
  athlete's calendar, so an unprescribed exercise fails (it names what IS prescribed).
2400
2775
  JSON is the exercises array: [{"exerciseId":N,"sets":[{"param1":reps,"param2":weight}, ...]}, ...]
2776
+ coach swap-exercise --set-exercise <savedWorkoutSetExerciseId> --exercise <exerciseId> --yes
2777
+ swap one exercise in the athlete's scheduled workout for a different one, that athlete only
2778
+ (the team prescription stays put). Get --set-exercise from 'coach athlete-workouts ... --log-ids'
2779
+ and --exercise from 'coach exercise resolve/search'.
2780
+
2781
+ prescribe weights/reps for an athlete (set their targets WITHOUT marking the set done; that athlete only):
2782
+ coach prescribe-set --athlete <id> --date Y-M-D --set <savedWorkoutSetId> <resultsJson>|--file f --yes
2783
+ set the prescribed values on a scheduled set; the set stays open for the athlete to log against,
2784
+ and the team prescription is untouched. param1 is reps, param2 is weight; one sets[] entry per
2785
+ prescribed set, and the write REPLACES the slot's prescription (an omitted param clears it).
2786
+ resultsJson: [{"savedWorkoutSetExerciseId":N,"sets":[{"param1":reps,"param2":weight}, ...]}, ...]
2787
+ Same ids as log-set, from 'coach athlete-workouts ... --log-ids'. Use log-set to record a set as PERFORMED.
2401
2788
 
2402
2789
  roster management:
2403
2790
  coach athlete-invite --team <id> --emails a@x,b@y [--message "..."] --yes
@@ -2782,19 +3169,10 @@ async function cmdAthleteLogSet(client, a) {
2782
3169
  results: await jsonInput(positionals[0], values.file)
2783
3170
  }, "log-set args");
2784
3171
  if (values.yes !== true) fail(`logging to set ${savedWorkoutSetId} writes to your coach-visible log; add --yes.`);
2785
- const mapped = args.results.map((r) => ({
2786
- savedWorkoutSetExerciseId: toInt(String(r.savedWorkoutSetExerciseId), "savedWorkoutSetExerciseId"),
2787
- sets: r.sets.map((s) => {
2788
- const slot = {};
2789
- if (s.param1 !== void 0) slot.param1 = s.param1;
2790
- if (s.param2 !== void 0) slot.param2 = s.param2;
2791
- return slot;
2792
- })
2793
- }));
2794
3172
  return out(await logAthleteSet(client, {
2795
3173
  date: args.date,
2796
3174
  savedWorkoutSetId,
2797
- results: mapped
3175
+ results: toSetResults(args.results)
2798
3176
  }));
2799
3177
  }
2800
3178
  const LOG_SESSION_USAGE = "athlete log-session --date Y-M-D <exercisesJson>|--file f --yes";
@@ -2947,7 +3325,7 @@ async function cmdInstallSkill() {
2947
3325
  }
2948
3326
  out({ installed });
2949
3327
  }
2950
- const COACH_USAGE = "usage: trainheroic coach <head-coach|athletes|programs|teams|notifications|analytics|program <id>|team <id>|team-codes <id>|roster-activity|team-volume|athlete-training|athlete-lift-history|athlete-workouts|log-set|log-session|athlete-invite|athlete-archive|athlete-restore|team-create|team-update|team-delete|team-code-create|team-code-delete|session-copy|session-unpublish|session-save-template|analytics-query|exercise|workout|message>";
3328
+ const COACH_USAGE = "usage: trainheroic coach <head-coach|athletes|programs|teams|notifications|analytics|program <id>|team <id>|team-codes <id>|roster-activity|team-volume|athlete-training|athlete-lift-history|main-lift-prs|athlete-workouts|log-set|log-session|prescribe-set|swap-exercise|athlete-invite|athlete-archive|athlete-restore|team-create|team-update|team-delete|team-code-create|team-code-delete|session-copy|session-unpublish|session-save-template|analytics-query|exercise|workout|message>";
2951
3329
  const COACH_LOG_SET_USAGE = "coach log-set --athlete <id> --date Y-M-D --set <savedWorkoutSetId> <resultsJson> --yes";
2952
3330
  async function cmdCoachLogSet(client, a) {
2953
3331
  const { values, positionals } = parse(a, {
@@ -2967,20 +3345,37 @@ async function cmdCoachLogSet(client, a) {
2967
3345
  results: await jsonInput(positionals[0], values.file)
2968
3346
  }, "coach log-set args");
2969
3347
  if (values.yes !== true) fail(`logging to athlete ${athleteId}'s set ${savedWorkoutSetId} writes to their training log; add --yes.`);
2970
- const mapped = args.results.map((r) => ({
2971
- savedWorkoutSetExerciseId: toInt(String(r.savedWorkoutSetExerciseId), "savedWorkoutSetExerciseId"),
2972
- sets: r.sets.map((s) => {
2973
- const slot = {};
2974
- if (s.param1 !== void 0) slot.param1 = s.param1;
2975
- if (s.param2 !== void 0) slot.param2 = s.param2;
2976
- return slot;
2977
- })
2978
- }));
2979
3348
  return out(await logForAthlete(client, {
2980
3349
  athleteId,
2981
3350
  date: args.date,
2982
3351
  savedWorkoutSetId,
2983
- results: mapped
3352
+ results: toSetResults(args.results)
3353
+ }));
3354
+ }
3355
+ const COACH_PRESCRIBE_SET_USAGE = "coach prescribe-set --athlete <id> --date Y-M-D --set <savedWorkoutSetId> <resultsJson>|--file f --yes";
3356
+ async function cmdCoachPrescribeSet(client, a) {
3357
+ const { values, positionals } = parse(a, {
3358
+ athlete: { type: "string" },
3359
+ date: { type: "string" },
3360
+ set: { type: "string" },
3361
+ file: { type: "string" },
3362
+ yes: { type: "boolean" }
3363
+ });
3364
+ const athleteId = toInt(need(values.athlete, COACH_PRESCRIBE_SET_USAGE), "--athlete");
3365
+ const date = isoDate(need(values.date, COACH_PRESCRIBE_SET_USAGE), "--date");
3366
+ const savedWorkoutSetId = toInt(need(values.set, COACH_PRESCRIBE_SET_USAGE), "--set");
3367
+ const args = validate(coachPrescribeSetArgsSchema, {
3368
+ athleteId,
3369
+ date,
3370
+ savedWorkoutSetId,
3371
+ results: await jsonInput(positionals[0], values.file)
3372
+ }, "coach prescribe-set args");
3373
+ if (values.yes !== true) fail(`prescribing to athlete ${athleteId}'s set ${savedWorkoutSetId} changes their plan; add --yes.`);
3374
+ return out(await prescribeForAthlete(client, {
3375
+ athleteId,
3376
+ date: args.date,
3377
+ savedWorkoutSetId,
3378
+ results: toSetResults(args.results)
2984
3379
  }));
2985
3380
  }
2986
3381
  const COACH_LOG_SESSION_USAGE = "coach log-session --athlete <id> --date Y-M-D <exercisesJson>|--file f --yes";
@@ -3004,6 +3399,25 @@ async function cmdCoachLogSession(client, a) {
3004
3399
  exercises: toSessionExercises(args.exercises)
3005
3400
  }));
3006
3401
  }
3402
+ const COACH_SWAP_EXERCISE_USAGE = "coach swap-exercise --set-exercise <savedWorkoutSetExerciseId> --exercise <exerciseId> --yes";
3403
+ async function cmdCoachSwapExercise(client, a) {
3404
+ const { values } = parse(a, {
3405
+ "set-exercise": { type: "string" },
3406
+ exercise: { type: "string" },
3407
+ yes: { type: "boolean" }
3408
+ });
3409
+ const savedWorkoutSetExerciseId = toInt(need(values["set-exercise"], COACH_SWAP_EXERCISE_USAGE), "--set-exercise");
3410
+ const exerciseId = toInt(need(values.exercise, COACH_SWAP_EXERCISE_USAGE), "--exercise");
3411
+ validate(swapAthleteExerciseArgsSchema, {
3412
+ savedWorkoutSetExerciseId,
3413
+ exerciseId
3414
+ }, "coach swap-exercise args");
3415
+ if (values.yes !== true) fail(`swapping slot ${savedWorkoutSetExerciseId} changes what the athlete is prescribed; add --yes.`);
3416
+ return out(await swapAthleteExercise(client, {
3417
+ savedWorkoutSetExerciseId,
3418
+ exerciseId
3419
+ }));
3420
+ }
3007
3421
  async function cmdCoachTeamVolume(client, a) {
3008
3422
  const usage = "coach team-volume (--team <id> | --athletes <id,id,...>) --start Y-M-D --end Y-M-D";
3009
3423
  const { values } = parse(a, {
@@ -3227,6 +3641,20 @@ async function cmdCoachAthleteLiftHistory(client, a) {
3227
3641
  sessions
3228
3642
  });
3229
3643
  }
3644
+ async function cmdCoachMainLiftPrs(client, a) {
3645
+ const { values } = parse(a, {
3646
+ athlete: { type: "string" },
3647
+ athletes: { type: "string" },
3648
+ months: { type: "string" }
3649
+ });
3650
+ const opts = values.months !== void 0 ? { months: toInt(values.months, "--months") } : {};
3651
+ if (values.athlete !== void 0) return out(await fetchAthleteMainLiftPRs(client, toInt(values.athlete, "--athlete"), opts));
3652
+ const subset = values.athletes !== void 0 ? values.athletes.split(",").map((s) => s.trim()).filter((s) => s.length > 0).map((s) => toInt(s, "--athletes")) : void 0;
3653
+ return out(await fetchRosterMainLiftPRs(client, {
3654
+ ...opts,
3655
+ ...subset ? { athleteIds: subset } : {}
3656
+ }));
3657
+ }
3230
3658
  async function cmdCoach(client, rest) {
3231
3659
  const [sub, ...a] = rest;
3232
3660
  switch (sub) {
@@ -3243,9 +3671,12 @@ async function cmdCoach(client, rest) {
3243
3671
  case "team-volume": return cmdCoachTeamVolume(client, a);
3244
3672
  case "athlete-training": return cmdCoachAthleteTraining(client, a);
3245
3673
  case "athlete-lift-history": return cmdCoachAthleteLiftHistory(client, a);
3674
+ case "main-lift-prs": return cmdCoachMainLiftPrs(client, a);
3246
3675
  case "athlete-workouts": return cmdCoachAthleteWorkouts(client, a);
3247
3676
  case "log-set": return cmdCoachLogSet(client, a);
3248
3677
  case "log-session": return cmdCoachLogSession(client, a);
3678
+ case "prescribe-set": return cmdCoachPrescribeSet(client, a);
3679
+ case "swap-exercise": return cmdCoachSwapExercise(client, a);
3249
3680
  case "athlete-invite": return cmdCoachAthleteInvite(client, a);
3250
3681
  case "athlete-archive": return cmdCoachAthleteArchive(client, a);
3251
3682
  case "athlete-restore": return cmdCoachAthleteRestore(client, a);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/cli",
3
- "version": "1.1.1",
3
+ "version": "1.3.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,8 +21,8 @@
21
21
  ],
22
22
  "dependencies": {
23
23
  "zod": "^4.4.3",
24
- "@trainheroic-unofficial/dto": "1.1.1",
25
- "@trainheroic-unofficial/js": "1.1.1"
24
+ "@trainheroic-unofficial/dto": "1.3.0",
25
+ "@trainheroic-unofficial/js": "1.3.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.0.0",