@trainheroic-unofficial/cli 0.1.0 → 1.1.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/dist/cli.mjs CHANGED
@@ -1,14 +1,204 @@
1
1
  #!/usr/bin/env node
2
- import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { cp, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { dirname, join } from "node:path";
3
5
  import process from "node:process";
4
6
  import { parseArgs } from "node:util";
5
7
  import { z } from "zod";
6
- import { homedir } from "node:os";
7
- import { dirname, join } from "node:path";
8
8
  //#region ../dto/src/common.ts
9
9
  /** An entity id as it arrives over the wire — a number or a numeric string. */
10
10
  const idSchema = z.union([z.string(), z.number()]);
11
- z.union([z.number().int(), z.string().regex(/^\d+$/u)]);
11
+ /**
12
+ * An id as a tool argument: a number, or a string of digits. Unlike idSchema (which
13
+ * tolerates whatever the API sends back), this rejects non-numeric strings up front so
14
+ * a bad argument fails validation instead of becoming NaN in a URL or a query.
15
+ */
16
+ const idArgSchema = z.union([z.number().int(), z.string().regex(/^\d+$/u)]);
17
+ //#endregion
18
+ //#region ../dto/src/athlete.ts
19
+ const intLike$1 = z.union([z.number(), z.string()]);
20
+ const intLikeOrNull$1 = z.union([
21
+ z.number(),
22
+ z.string(),
23
+ z.null()
24
+ ]);
25
+ const numLikeOrNull = z.union([
26
+ z.number(),
27
+ z.string(),
28
+ z.null()
29
+ ]);
30
+ z.looseObject({
31
+ id: intLike$1,
32
+ roles: z.array(z.string()).optional(),
33
+ org_id: intLikeOrNull$1.optional()
34
+ });
35
+ z.looseObject({
36
+ reps_sum: z.number().optional(),
37
+ volume_sum: z.number().optional(),
38
+ sessions_count: z.number().optional(),
39
+ first_logged_date: z.string().optional(),
40
+ last_logged_date: z.string().optional(),
41
+ duration_hours: z.number().optional()
42
+ });
43
+ z.looseObject({
44
+ id: intLike$1,
45
+ email: z.string().optional(),
46
+ name_first: z.string().optional(),
47
+ name_last: z.string().optional(),
48
+ username: z.string().optional(),
49
+ gender: z.string().optional(),
50
+ date_of_birth: z.string().optional(),
51
+ use_metric: z.boolean().optional()
52
+ });
53
+ z.looseObject({ id: intLike$1 });
54
+ /** One item of `/2.0/athlete/workingMax` — the athlete's working max for an exercise. */
55
+ const athleteWorkingMaxSchema = z.looseObject({
56
+ exercise_id: intLike$1,
57
+ title: z.string().optional(),
58
+ param_type: intLikeOrNull$1.optional(),
59
+ value: numLikeOrNull.optional(),
60
+ type_suffix: z.string().optional(),
61
+ working_max_id: intLikeOrNull$1.optional()
62
+ });
63
+ z.array(athleteWorkingMaxSchema);
64
+ /** One item of `/v5/users/exercises/history` — an exercise the athlete has logged. */
65
+ const exerciseHistoryListItemSchema = z.looseObject({
66
+ id: intLike$1,
67
+ title: z.string(),
68
+ isCircuit: z.boolean().optional(),
69
+ prescription: z.string().optional(),
70
+ param1Type: intLikeOrNull$1.optional(),
71
+ param2Type: intLikeOrNull$1.optional()
72
+ });
73
+ z.array(exerciseHistoryListItemSchema);
74
+ /** A single completed set inside a history entry (`/v5/exercises/{id}/history`). */
75
+ const historySetSchema = z.looseObject({
76
+ setNumber: z.number(),
77
+ formattedValue: z.string().optional(),
78
+ rawValue1: numLikeOrNull.optional(),
79
+ rawValue2: numLikeOrNull.optional(),
80
+ savedWorkoutSetExerciseId: intLike$1.optional()
81
+ });
82
+ /** A best rep-max derived for a history entry. */
83
+ const repMaxSchema = z.looseObject({
84
+ reps: z.number(),
85
+ weight: z.number()
86
+ });
87
+ /** One performed session of an exercise (`/v5/exercises/{id}/history` → `history[]`). */
88
+ const historyEntrySchema = z.looseObject({
89
+ dateCompleted: z.string(),
90
+ notes: z.string().nullable().optional(),
91
+ isLift: z.boolean().optional(),
92
+ param1Type: intLikeOrNull$1.optional(),
93
+ param2Type: intLikeOrNull$1.optional(),
94
+ savedWorkoutSetExerciseId: intLike$1.optional(),
95
+ teamId: intLikeOrNull$1.optional(),
96
+ programWorkoutId: intLikeOrNull$1.optional(),
97
+ abr: z.string().optional(),
98
+ bestEstimated1RM: z.number().optional(),
99
+ repMaxes: z.array(repMaxSchema).optional(),
100
+ sets: z.array(historySetSchema).optional()
101
+ });
102
+ /** A lifetime PR row from `/v5/exercises/{id}/history` → `liftPRs[]`. */
103
+ const liftPRSchema = z.looseObject({
104
+ weight: z.number().optional(),
105
+ savedWorkoutSetExerciseId: intLike$1.optional(),
106
+ setNumber: z.number().optional(),
107
+ dateCompleted: z.string().optional(),
108
+ reps: z.number().optional(),
109
+ units: z.string().optional(),
110
+ isMetric: z.boolean().optional(),
111
+ description: z.string().optional()
112
+ });
113
+ z.looseObject({
114
+ liftPRs: z.array(liftPRSchema).optional(),
115
+ singleParamPRs: z.array(z.unknown()).optional(),
116
+ history: z.array(historyEntrySchema).optional()
117
+ });
118
+ /** One item of `/v5/exercises/{id}/personalRecords` — a standards-filtered PR. */
119
+ const personalRecordSchema = z.looseObject({
120
+ id: intLike$1.optional(),
121
+ savedWorkoutSetExerciseId: intLike$1.optional(),
122
+ setNumber: z.number().optional(),
123
+ reps: z.number().optional(),
124
+ weight: z.number().optional(),
125
+ scaledWeight: z.number().optional(),
126
+ units: z.string().optional(),
127
+ isMetric: z.boolean().optional()
128
+ });
129
+ z.array(personalRecordSchema);
130
+ z.looseObject({
131
+ isLift: z.boolean().optional(),
132
+ lastPerformance: z.unknown().optional(),
133
+ personalRecord: z.unknown().optional()
134
+ });
135
+ /**
136
+ * One item of `/3.0/athlete/programworkout/range` — a scheduled/completed workout. The deep
137
+ * `summarizedSavedWorkout` tree is left loose: the presenter in `js` flattens it, so dto only
138
+ * pins the top-level fields the warehouse and presenter key off.
139
+ */
140
+ const programWorkoutSchema = z.looseObject({
141
+ id: intLike$1,
142
+ date: z.string().optional(),
143
+ workout_title: z.string().optional(),
144
+ program_id: intLikeOrNull$1.optional(),
145
+ program_title: z.string().optional(),
146
+ team_id: intLikeOrNull$1.optional(),
147
+ team_title: z.string().optional(),
148
+ summarizedSavedWorkout: z.unknown().optional()
149
+ });
150
+ z.array(programWorkoutSchema);
151
+ /** A `YYYY-MM-DD` date argument. The single definition reused across athlete tool inputs. */
152
+ const dateString = z.string().regex(/^\d{4}-\d{2}-\d{2}$/u, "expected YYYY-MM-DD");
153
+ z.object({
154
+ startDate: dateString,
155
+ endDate: dateString
156
+ });
157
+ /**
158
+ * One entered set: the value of each parameter slot (param 1 / param 2 — e.g. reps / weight).
159
+ * Shared by every logging write so the per-set shape is defined once.
160
+ */
161
+ const loggedSetSchema = z.object({
162
+ param1: z.union([z.number(), z.string()]).optional(),
163
+ param2: z.union([z.number(), z.string()]).optional()
164
+ });
165
+ /**
166
+ * Args for the set-logging write. `date` (the workout's day) locates the saved
167
+ * workout via the range endpoint; `savedWorkoutSetId` picks the set to complete; `results`
168
+ * gives, per exercise in it, the entered value of each set (param 1 / param 2 by entry slot).
169
+ */
170
+ const logSetArgsSchema = z.object({
171
+ date: dateString,
172
+ savedWorkoutSetId: idArgSchema,
173
+ results: z.array(z.object({
174
+ savedWorkoutSetExerciseId: idArgSchema,
175
+ sets: z.array(loggedSetSchema).min(1)
176
+ })).min(1)
177
+ });
178
+ /**
179
+ * Args for the coach "log for athlete" write — the same shape as logSetArgsSchema plus the
180
+ * roster `athleteId` whose set is being logged on their behalf.
181
+ */
182
+ const coachLogSetArgsSchema = logSetArgsSchema.extend({ athleteId: idArgSchema });
183
+ /**
184
+ * Args for logging a whole session by exercise (rather than by saved-workout-set id). Each
185
+ * exercise carries its entered sets and an optional 1-based `order`. The athlete path creates
186
+ * or reuses a personal session for the date and logs against it; the coach path resolves each
187
+ * exercise to a set already prescribed on that date and logs against that.
188
+ */
189
+ const logSessionArgsSchema = z.object({
190
+ date: dateString,
191
+ exercises: z.array(z.object({
192
+ exerciseId: idArgSchema,
193
+ order: z.number().int().positive().optional(),
194
+ sets: z.array(loggedSetSchema).min(1)
195
+ })).min(1)
196
+ });
197
+ /**
198
+ * Args for the coach variant of {@link logSessionArgsSchema}: the same shape plus the roster
199
+ * `athleteId` whose session is being logged on their behalf.
200
+ */
201
+ const coachLogSessionArgsSchema = logSessionArgsSchema.extend({ athleteId: idArgSchema });
12
202
  //#endregion
13
203
  //#region ../dto/src/exercise.ts
14
204
  /** Body for creating a custom exercise; extra fields the API accepts are preserved. */
@@ -270,12 +460,31 @@ function unitLabel(paramType) {
270
460
  if (t === null) return null;
271
461
  return PARAM_UNIT[t] ?? null;
272
462
  }
273
- /** Annotate a row with human-readable units for display. */
463
+ /**
464
+ * Fixed measurement units for an exercise, ordered by entry slot (param 1, then param 2).
465
+ * Positional, not semantic: some exercises reverse the slots, so the array is not labelled
466
+ * by role. A null entry is an unset slot.
467
+ */
468
+ function exerciseUnits(param1, param2) {
469
+ return [unitLabel(param1), unitLabel(param2)];
470
+ }
471
+ /** Present a row for display: drop the raw param-type codes, surface units positionally. */
274
472
  function withUnits(row) {
473
+ const { param_1_type, param_2_type, ...rest } = row;
275
474
  return {
276
- ...row,
277
- param_1_unit: unitLabel(row.param_1_type),
278
- param_2_unit: unitLabel(row.param_2_type)
475
+ ...rest,
476
+ units: exerciseUnits(param_1_type, param_2_type)
477
+ };
478
+ }
479
+ /**
480
+ * Present a full raw exercise object for display: drop the raw param-type codes and add the
481
+ * positional `units` array. Keeps every other field of the raw object intact.
482
+ */
483
+ function presentExercise$1(raw) {
484
+ const { param_1_type, param_2_type, ...rest } = raw;
485
+ return {
486
+ ...rest,
487
+ units: exerciseUnits(param_1_type, param_2_type)
279
488
  };
280
489
  }
281
490
  function buildSearchText(title) {
@@ -337,13 +546,1201 @@ function rankSearch(rows, query, limit) {
337
546
  if (title.startsWith(q)) score += 100;
338
547
  for (const tok of tokens) if (title.includes(tok)) score += 10;
339
548
  score -= title.length * .05;
340
- if (row.can_edit === 0) score += 1;
549
+ if ((row.can_edit ?? 0) === 0) score += 1;
341
550
  return {
342
551
  row,
343
552
  score
344
553
  };
345
554
  }).sort((a, b) => b.score - a.score).slice(0, limit).map((s) => s.row);
346
555
  }
556
+ /**
557
+ * Map over items with a bounded number of concurrent workers. Used to fan out upstream
558
+ * fetches (per-exercise history, the CLI export) without bursting the host all at once or,
559
+ * on workerd, blowing the subrequest budget.
560
+ */
561
+ async function mapPool(items, limit, fn) {
562
+ const out = Array.from({ length: items.length });
563
+ let next = 0;
564
+ const worker = async () => {
565
+ while (next < items.length) {
566
+ const i = next;
567
+ next += 1;
568
+ out[i] = await fn(items[i], i);
569
+ }
570
+ };
571
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
572
+ return out;
573
+ }
574
+ //#endregion
575
+ //#region ../js/src/athlete.ts
576
+ async function getJson(client, path, label) {
577
+ const res = await client.request("GET", path);
578
+ if (!res.ok) throw new Error(`${label} failed (HTTP ${res.status}).`);
579
+ return res.data;
580
+ }
581
+ async function getArray(client, path, label) {
582
+ const res = await client.request("GET", path);
583
+ if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
584
+ return res.data;
585
+ }
586
+ /**
587
+ * The logged-in account's numeric user id (the athlete warehouse's tenant key, and a required
588
+ * query arg for several athlete endpoints). Works from any session — coach or athlete — and
589
+ * even from a cached session that never went through login.
590
+ */
591
+ async function resolveAthleteUserId(client) {
592
+ const res = await client.request("GET", "/user/simple");
593
+ const id = isRecord(res.data) ? coerceInt(res.data.id) : null;
594
+ if (!res.ok || id === null || id <= 0) throw new Error("Could not resolve athlete user id from /user/simple.");
595
+ return id;
596
+ }
597
+ /** Lifetime training totals. `use_metric` is required by the API (omitting it 400s). */
598
+ function fetchAthleteProfileSummary(client, userId, useMetric = false) {
599
+ return getJson(client, `/v5/athleteProfile/summary?user_id=${userId}&use_metric=${useMetric ? 1 : 0}`, "athlete profile summary");
600
+ }
601
+ function fetchAthleteUser(client, userId) {
602
+ return getJson(client, `/v5/users/${userId}`, "athlete user");
603
+ }
604
+ /**
605
+ * Sort a roster-activity list most-recently-active first; never-logged rows (null date) last.
606
+ * Athletes tied on lastLoggedDate break by session count (more sessions first), so a tie is not
607
+ * left to arbitrary input order.
608
+ */
609
+ function sortRosterByRecency(rows) {
610
+ return [...rows].sort((a, b) => {
611
+ if (a.lastLoggedDate !== b.lastLoggedDate) {
612
+ if (a.lastLoggedDate === null) return 1;
613
+ if (b.lastLoggedDate === null) return -1;
614
+ return a.lastLoggedDate < b.lastLoggedDate ? 1 : -1;
615
+ }
616
+ return (b.sessionsCount ?? 0) - (a.sessionsCount ?? 0);
617
+ });
618
+ }
619
+ /**
620
+ * A coach's roster-activity ranking: each athlete's all-time training snapshot (session count,
621
+ * first/last logged date, total reps/volume), sorted most-recently-active first. There is no
622
+ * single roster-activity endpoint, so this fans out `/v5/athleteProfile/summary` per athlete with
623
+ * a small concurrency cap; pass the subset you care about for a large org. A failed or missing
624
+ * summary becomes a null-data row (sorted last), not an error.
625
+ */
626
+ async function fetchRosterActivity(client, athleteIds, useMetric = false) {
627
+ const rows = [];
628
+ const concurrency = 6;
629
+ for (let i = 0; i < athleteIds.length; i += concurrency) {
630
+ const chunk = athleteIds.slice(i, i + concurrency);
631
+ const settled = await Promise.all(chunk.map(async (id) => {
632
+ try {
633
+ return {
634
+ id,
635
+ summary: await fetchAthleteProfileSummary(client, id, useMetric)
636
+ };
637
+ } catch {
638
+ return {
639
+ id,
640
+ summary: null
641
+ };
642
+ }
643
+ }));
644
+ for (const { id, summary } of settled) {
645
+ const count = summary?.sessions_count ?? null;
646
+ const hasSessions = count !== null && count > 0;
647
+ const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
648
+ rows.push({
649
+ athleteId: id,
650
+ sessionsCount: count,
651
+ firstLoggedDate: normDate(summary?.first_logged_date),
652
+ lastLoggedDate: normDate(summary?.last_logged_date),
653
+ totalReps: summary?.reps_sum ?? null,
654
+ totalVolume: summary?.volume_sum ?? null
655
+ });
656
+ }
657
+ }
658
+ return sortRosterByRecency(rows);
659
+ }
660
+ function fetchAthletePrefs(client) {
661
+ return getJson(client, "/1.0/athlete/prefs", "athlete prefs");
662
+ }
663
+ function fetchWorkingMaxes(client) {
664
+ return getArray(client, "/2.0/athlete/workingMax", "athlete working maxes");
665
+ }
666
+ function fetchExerciseHistoryList(client) {
667
+ return getArray(client, "/v5/users/exercises/history", "athlete exercise history list");
668
+ }
669
+ /** Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). */
670
+ async function searchExerciseHistory(client, query, limit = 20) {
671
+ return rankSearch(await fetchExerciseHistoryList(client), query, limit);
672
+ }
673
+ function fetchExerciseHistoryDetail(client, exerciseId, userId) {
674
+ return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
675
+ }
676
+ function fetchPersonalRecords(client, exerciseId) {
677
+ return getArray(client, `/v5/exercises/${exerciseId}/personalRecords`, "athlete personal records");
678
+ }
679
+ /** Last performance + PR for an exercise. `date` (YYYY-MM-DD) is required by the API. */
680
+ function fetchExerciseStats(client, exerciseId, userId, date) {
681
+ return getJson(client, `/v5/exercises/${exerciseId}/stats?userId=${userId}&date=${date}`, "athlete exercise stats");
682
+ }
683
+ /** Scheduled + completed workouts in an inclusive YYYY-MM-DD window. */
684
+ function fetchAthleteWorkouts(client, startDate, endDate) {
685
+ return getArray(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
686
+ }
687
+ /**
688
+ * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
689
+ * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
690
+ * `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
691
+ * `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
692
+ */
693
+ function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
694
+ return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
695
+ }
696
+ /**
697
+ * A coach's month view of a roster athlete's logged sessions
698
+ * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
699
+ * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
700
+ * `userId` in each row is the roster athlete, not the calling coach.
701
+ */
702
+ function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
703
+ return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
704
+ }
705
+ function fetchLeaderboard(client, workoutId, opts = {}) {
706
+ const qs = new URLSearchParams();
707
+ if (opts.page !== void 0) qs.set("page", String(opts.page));
708
+ if (opts.pageSize !== void 0) qs.set("pageSize", String(opts.pageSize));
709
+ if (opts.gender !== void 0) qs.set("gender", String(opts.gender));
710
+ const query = qs.toString();
711
+ return getJson(client, `/3.0/athlete/leaderboard/${workoutId}${query ? `?${query}` : ""}`, "athlete leaderboard");
712
+ }
713
+ const SLOTS = 10;
714
+ function nonEmpty(value) {
715
+ return value !== void 0 && value !== null && String(value).trim() !== "";
716
+ }
717
+ /**
718
+ * Per-set prescriptions from the param_N_data slots, e.g. ["5 @ 225", "3 @ 245"] or ["AMRAP"].
719
+ * Values are kept raw (a non-numeric prescription like "AMRAP" or "8-12" must survive); the
720
+ * positional units come from the exercise's param types, mirroring the coach presenter.
721
+ */
722
+ function prescribedSets(ex) {
723
+ const out = [];
724
+ for (let i = 1; i <= SLOTS; i += 1) {
725
+ const p1 = ex[`param_1_data_${i}`];
726
+ const p2 = ex[`param_2_data_${i}`];
727
+ const has1 = nonEmpty(p1);
728
+ const has2 = nonEmpty(p2);
729
+ if (!has1 && !has2) continue;
730
+ if (has1 && has2) out.push(`${p1} @ ${p2}`);
731
+ else if (has1) out.push(String(p1));
732
+ else out.push(`@ ${p2}`);
733
+ }
734
+ return out;
735
+ }
736
+ /**
737
+ * The per-set values the athlete actually logged, read from a saved-copy exercise. A set
738
+ * counts as performed only when its `param_{i}_made` flag is 1: the saved copy pre-fills the
739
+ * `param_N_data` slots with the prescription, so the presence of data alone does not mean a
740
+ * set was done. `param_{i}_made` is the same per-set flag the logging write sets, and is the
741
+ * only reliable signal (the `completed` flags are often left at 0 on a logged session).
742
+ */
743
+ function performedSets(ex) {
744
+ const out = [];
745
+ for (let i = 1; i <= SLOTS; i += 1) {
746
+ if (coerceInt(ex[`param_${i}_made`]) !== 1) continue;
747
+ const p1 = ex[`param_1_data_${i}`];
748
+ const p2 = ex[`param_2_data_${i}`];
749
+ const has1 = nonEmpty(p1);
750
+ const has2 = nonEmpty(p2);
751
+ if (has1 && has2) out.push(`${p1} @ ${p2}`);
752
+ else if (has1) out.push(String(p1));
753
+ else if (has2) out.push(`@ ${p2}`);
754
+ }
755
+ return out;
756
+ }
757
+ function presentExercise(ex, performedById) {
758
+ const instruction = typeof ex.instruction === "string" && ex.instruction !== "" ? ex.instruction : null;
759
+ const id = coerceInt(ex.id);
760
+ return {
761
+ exerciseId: coerceInt(ex.exercise_id),
762
+ title: typeof ex.title === "string" ? ex.title : "",
763
+ instruction,
764
+ units: exerciseUnits(ex.param_1_type, ex.param_2_type),
765
+ prescribed: prescribedSets(ex),
766
+ performed: (id !== null ? performedById.get(id) : void 0) ?? []
767
+ };
768
+ }
769
+ function presentBlock(set, performedById) {
770
+ const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
771
+ return {
772
+ order: coerceInt(set.order) ?? 0,
773
+ title: typeof set.title === "string" && set.title !== "" ? set.title : null,
774
+ instruction: typeof set.instruction === "string" && set.instruction !== "" ? set.instruction : null,
775
+ isTest: coerceInt(set.is_test) === 1,
776
+ exercises: exercises.filter(isRecord).map((ex) => presentExercise(ex, performedById))
777
+ };
778
+ }
779
+ function str$1(v) {
780
+ return typeof v === "string" && v !== "" ? v : null;
781
+ }
782
+ /** Every logged set (programmed + athlete-added) in the saved copy, paired with its exercises. */
783
+ function savedSets(saved) {
784
+ const out = [];
785
+ for (const key of ["workoutSets", "addedWorkoutSets"]) {
786
+ const sets = Array.isArray(saved[key]) ? saved[key] : [];
787
+ for (const set of sets) {
788
+ if (!isRecord(set)) continue;
789
+ const exercises = (Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : []).filter(isRecord);
790
+ out.push({
791
+ set,
792
+ exercises
793
+ });
794
+ }
795
+ }
796
+ return out;
797
+ }
798
+ /**
799
+ * Map each prescription exercise id to the per-set values the athlete logged. In the saved
800
+ * copy, `workout_set_exercise_id` points back at the prescription exercise's `id`, and the
801
+ * entered values live in the same `param_N_data` slots as a prescription — so the
802
+ * prescription reader works on them unchanged.
803
+ */
804
+ function performedByExerciseId(sets) {
805
+ const map = /* @__PURE__ */ new Map();
806
+ for (const { exercises } of sets) for (const ex of exercises) {
807
+ const id = coerceInt(ex.workout_set_exercise_id);
808
+ if (id === null) continue;
809
+ const values = performedSets(ex);
810
+ if (values.length > 0) map.set(id, values);
811
+ }
812
+ return map;
813
+ }
814
+ /** Present a logged set straight from the saved copy (athlete-added or personal work). */
815
+ function presentSavedBlock(set, exercises) {
816
+ return {
817
+ order: coerceInt(set.order) ?? 0,
818
+ title: typeof set.title === "string" && set.title !== "" ? set.title : null,
819
+ instruction: typeof set.instruction === "string" && set.instruction !== "" ? set.instruction : null,
820
+ isTest: coerceInt(set.is_test) === 1,
821
+ exercises: exercises.map((ex) => ({
822
+ exerciseId: coerceInt(ex.exercise_id),
823
+ title: typeof ex.exercise_title === "string" ? ex.exercise_title : "",
824
+ instruction: typeof ex.instruction === "string" && ex.instruction !== "" ? ex.instruction : null,
825
+ units: exerciseUnits(ex.param_1_type, ex.param_2_type),
826
+ prescribed: [],
827
+ performed: performedSets(ex)
828
+ }))
829
+ };
830
+ }
831
+ /**
832
+ * Flatten one `/3.0/athlete/programworkout/range` item into a readable workout, merging the
833
+ * prescription (`summarizedSavedWorkout.workout`) with what the athlete logged
834
+ * (`summarizedSavedWorkout.saved_workout`). Each exercise carries both its `prescribed` and
835
+ * `performed` sets; athlete-added/personal work that has no prescription is appended as its
836
+ * own blocks. No `raw` is needed to see logged results.
837
+ */
838
+ function presentAthleteWorkout(raw) {
839
+ const rec = raw;
840
+ const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
841
+ const workout = isRecord(ssw.workout) ? ssw.workout : {};
842
+ const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : {};
843
+ const prescriptionSets = (Array.isArray(workout.workoutSets) ? workout.workoutSets : []).filter(isRecord);
844
+ const logged = savedSets(saved);
845
+ const performedById = performedByExerciseId(logged);
846
+ const blocks = prescriptionSets.map((s) => presentBlock(s, performedById)).sort((a, b) => a.order - b.order);
847
+ const prescribedIds = /* @__PURE__ */ new Set();
848
+ for (const s of prescriptionSets) {
849
+ const exs = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
850
+ for (const ex of exs) {
851
+ if (!isRecord(ex)) continue;
852
+ const id = coerceInt(ex.id);
853
+ if (id !== null) prescribedIds.add(id);
854
+ }
855
+ }
856
+ for (const { set, exercises } of logged) {
857
+ const extra = exercises.filter((ex) => {
858
+ if (performedSets(ex).length === 0) return false;
859
+ const id = coerceInt(ex.workout_set_exercise_id);
860
+ return id === null || !prescribedIds.has(id);
861
+ });
862
+ if (extra.length > 0) blocks.push(presentSavedBlock(set, extra));
863
+ }
864
+ return {
865
+ id: coerceInt(rec.id),
866
+ date: str$1(rec.date) ?? "",
867
+ title: str$1(rec.workout_title) ?? "",
868
+ program: str$1(rec.program_title),
869
+ team: str$1(rec.team_title),
870
+ instruction: str$1(workout.instruction),
871
+ logged: blocks.some((b) => b.exercises.some((e) => e.performed.length > 0)),
872
+ blocks
873
+ };
874
+ }
875
+ function presentAthleteWorkouts(list) {
876
+ return list.map(presentAthleteWorkout);
877
+ }
878
+ /**
879
+ * Project a workout range to just the ids a set-log write needs, read from the SAME saved-copy
880
+ * location {@link findSavedWorkoutSet} matches against (`summarizedSavedWorkout.saved_workout`).
881
+ * This is the self-service path for logging: instead of grepping the multi-KB `--raw` blob for
882
+ * which of several id fields maps to `--set`, callers read `savedWorkoutSetId` and each
883
+ * `savedWorkoutSetExerciseId` straight off these rows. One row per saved set, dropping any set
884
+ * with no resolvable id.
885
+ */
886
+ function presentLogTargets(list) {
887
+ const targets = [];
888
+ for (const pw of list) {
889
+ const rec = pw;
890
+ const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
891
+ const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
892
+ if (!saved) continue;
893
+ const date = str$1(rec.date) ?? "";
894
+ const workoutTitle = str$1(rec.workout_title) ?? "";
895
+ const sets = Array.isArray(saved.workoutSets) ? saved.workoutSets : [];
896
+ for (const s of sets) {
897
+ if (!isRecord(s)) continue;
898
+ const savedWorkoutSetId = coerceInt(s.id);
899
+ if (savedWorkoutSetId === null) continue;
900
+ const exercises = (Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : []).filter(isRecord).map((ex) => {
901
+ const id = coerceInt(ex.id);
902
+ if (id === null) return null;
903
+ return {
904
+ savedWorkoutSetExerciseId: id,
905
+ title: typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "",
906
+ units: exerciseUnits(ex.param_1_type, ex.param_2_type),
907
+ prescribed: prescribedSets(ex),
908
+ performed: performedSets(ex)
909
+ };
910
+ }).filter((e) => e !== null);
911
+ targets.push({
912
+ date,
913
+ workoutTitle,
914
+ savedWorkoutSetId,
915
+ setTitle: str$1(s.title),
916
+ exercises
917
+ });
918
+ }
919
+ }
920
+ return targets;
921
+ }
922
+ /**
923
+ * Narrow a presented workout list for the common "what did I actually do" reads. `loggedOnly`
924
+ * keeps only workouts the athlete logged a set on (the reliable signal, not the API's
925
+ * completion flag). `limit` keeps the most recent N by date (newest first). Both are pure
926
+ * post-filters over the presented view; the raw API path is left untouched.
927
+ */
928
+ function selectWorkouts(list, opts = {}) {
929
+ let out = opts.loggedOnly === true ? list.filter((w) => w.logged) : [...list];
930
+ if (opts.limit !== void 0) out = [...out].sort((a, b) => a.date < b.date ? 1 : a.date > b.date ? -1 : 0).slice(0, opts.limit);
931
+ return out;
932
+ }
933
+ /**
934
+ * Project presented workouts to compact headers (date/title/program + logged flag + exercise
935
+ * counts), dropping the per-set block detail. A dense multi-program week of full views can be
936
+ * tens of KB; this keeps an overview question to one small row per session, with a drill-in
937
+ * (narrow the date range) when the detail is actually needed.
938
+ */
939
+ function summarizeAthleteWorkouts(list) {
940
+ return list.map((w) => {
941
+ const exerciseCount = w.blocks.reduce((n, b) => n + b.exercises.length, 0);
942
+ const performedCount = w.blocks.reduce((n, b) => n + b.exercises.filter((e) => e.performed.length > 0).length, 0);
943
+ return {
944
+ id: w.id,
945
+ date: w.date,
946
+ title: w.title,
947
+ program: w.program,
948
+ team: w.team,
949
+ logged: w.logged,
950
+ exerciseCount,
951
+ performedCount
952
+ };
953
+ });
954
+ }
955
+ /**
956
+ * Flatten the coach athlete-calendar summary into compact per-session rows: title, the `logged`
957
+ * flag (the reliable did-they-train signal), rpe/duration/notes, and the exercises performed with
958
+ * the API's own set summary string (`abr`, e.g. "5 x 2 @ 205 lb"). The exercise titles here are
959
+ * the discovery handle a coach otherwise lacks: read what the athlete actually did, then pull the
960
+ * specific lift's PRs.
961
+ */
962
+ function presentCoachAthleteTraining(raw, athleteId, year, month) {
963
+ const sessions = [];
964
+ let athleteName = null;
965
+ for (const item of raw) {
966
+ if (!isRecord(item)) continue;
967
+ if (athleteName === null && typeof item.athleteName === "string") athleteName = item.athleteName;
968
+ const exercises = [];
969
+ const sets = Array.isArray(item.sets) ? item.sets : [];
970
+ for (const set of sets) {
971
+ if (!isRecord(set)) continue;
972
+ const exs = Array.isArray(set.exercises) ? set.exercises : [];
973
+ for (const ex of exs) {
974
+ if (!isRecord(ex)) continue;
975
+ exercises.push({
976
+ exerciseId: coerceInt(ex.exercise_id),
977
+ title: typeof ex.title === "string" ? ex.title : "",
978
+ summary: typeof ex.abr === "string" && ex.abr !== "" ? ex.abr : null,
979
+ completed: coerceInt(ex.completed) === 1
980
+ });
981
+ }
982
+ }
983
+ sessions.push({
984
+ workoutId: coerceInt(item.workout_id),
985
+ savedWorkoutId: coerceInt(item.saved_workout_id),
986
+ title: typeof item.workout_title === "string" ? item.workout_title : "",
987
+ logged: coerceInt(item.logged) === 1,
988
+ completed: coerceInt(item.completed) === 1,
989
+ rpe: coerceInt(item.rpe),
990
+ durationMin: coerceInt(item.session_duration),
991
+ notes: typeof item.notes === "string" && item.notes !== "" ? item.notes : null,
992
+ exercises
993
+ });
994
+ }
995
+ return {
996
+ athleteId,
997
+ athleteName,
998
+ year,
999
+ month,
1000
+ sessions
1001
+ };
1002
+ }
1003
+ const MAX_PARAM_SLOTS = 10;
1004
+ /**
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.
1009
+ *
1010
+ * Only `savedWorkoutSetExerciseId`, `savedWorkoutSetId`, and `workoutSetExerciseId` are
1011
+ * required from the live exercise record; everything else is derived from `results`.
1012
+ *
1013
+ * Exported for unit testing — callers should use `logAthleteSet` instead.
1014
+ */
1015
+ function buildExerciseLogPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results) {
1016
+ if (results.length > MAX_PARAM_SLOTS) throw new Error(`At most ${MAX_PARAM_SLOTS} sets are supported per exercise; got ${results.length}.`);
1017
+ const body = {
1018
+ id: savedWorkoutSetExerciseId,
1019
+ saved_workout_set_id: savedWorkoutSetId,
1020
+ workout_set_exercise_id: workoutSetExerciseId,
1021
+ completed: results.some((s) => s.param1 !== void 0 || s.param2 !== void 0) ? 1 : 0
1022
+ };
1023
+ for (let i = 1; i <= MAX_PARAM_SLOTS; i += 1) {
1024
+ const slot = results[i - 1];
1025
+ const p1 = slot?.param1 !== void 0 ? String(slot.param1) : "";
1026
+ const p2 = slot?.param2 !== void 0 ? String(slot.param2) : "";
1027
+ body[`param_${i}_made`] = p1 !== "" || p2 !== "" ? 1 : 0;
1028
+ body[`param_1_data_${i}`] = p1;
1029
+ body[`param_2_data_${i}`] = p2;
1030
+ }
1031
+ return body;
1032
+ }
1033
+ /**
1034
+ * Locate the target saved workout set across all program workouts on the given day.
1035
+ * Returns the `savedWorkoutId`, the matching set's `workoutSetExercises` array so callers
1036
+ * can look up `workout_set_exercise_id` by `savedWorkoutSetExerciseId`, and the raw set
1037
+ * record so callers can build the set-completion PUT body via `buildSetCompletePayload`.
1038
+ */
1039
+ function findSavedWorkoutSet(workouts, savedWorkoutSetId) {
1040
+ const available = [];
1041
+ for (const pw of workouts) {
1042
+ const rec = pw;
1043
+ const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
1044
+ const sw = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
1045
+ if (!sw) continue;
1046
+ const sets = Array.isArray(sw.workoutSets) ? sw.workoutSets : [];
1047
+ for (const s of sets) {
1048
+ if (!isRecord(s)) continue;
1049
+ const exercises = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises.filter(isRecord) : [];
1050
+ if (coerceInt(s.id) === savedWorkoutSetId) {
1051
+ const savedWorkoutId = coerceInt(sw.id);
1052
+ if (!savedWorkoutId) continue;
1053
+ return {
1054
+ savedWorkoutId,
1055
+ exercises,
1056
+ rawSet: s
1057
+ };
1058
+ }
1059
+ const setId = coerceInt(s.id);
1060
+ if (setId !== null) {
1061
+ const exLabels = exercises.map((ex) => {
1062
+ const exId = coerceInt(ex.id);
1063
+ const title = typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "exercise";
1064
+ return exId === null ? null : `${exId} (${title})`;
1065
+ }).filter((x) => x !== null);
1066
+ available.push(`set ${setId} → exercise ids: ${exLabels.join(", ") || "none"}`);
1067
+ }
1068
+ }
1069
+ }
1070
+ const hint = available.length > 0 ? ` Saved workout sets present on this date: ${available.join("; ")}. Pass a "set N" id to --set (the savedWorkoutSetId), and the matching "exercise id" as savedWorkoutSetExerciseId in the results.` : " No saved workout is scheduled on this date — log against a date that has a workout (find it via athlete-workouts / coach athlete-workouts).";
1071
+ throw new Error(`Saved workout set ${savedWorkoutSetId} not found on this date.${hint}`);
1072
+ }
1073
+ /**
1074
+ * Build the body for `PUT /1.0/athlete/savedworkoutset/{id}` that marks the set completed.
1075
+ *
1076
+ * The API requires the **app's camelCase in-memory model**, not the snake_case shape the
1077
+ * GET endpoints return. Key field mappings from the raw set record:
1078
+ * saved_workout_id → sessionId
1079
+ * workout_set_id → workoutSetId
1080
+ * is_super_set (0/1) → isSuperSet (boolean)
1081
+ * plain_text (0/1) → isPlainText (boolean)
1082
+ * unit ("lb"/"kg") → isMetric (boolean)
1083
+ * workoutSetExercises[].id → exercises (array of IDs)
1084
+ *
1085
+ * `exerciseIds` must be the savedWorkoutSetExercise IDs (not workout_set_exercise_ids).
1086
+ *
1087
+ * Exported for unit testing — callers should use `logAthleteSet` instead.
1088
+ */
1089
+ function buildSetCompletePayload(rawSet, exerciseIds, complete) {
1090
+ const id = coerceInt(rawSet.id);
1091
+ const sessionId = coerceInt(rawSet.saved_workout_id);
1092
+ const workoutSetId = coerceInt(rawSet.workout_set_id);
1093
+ if (!id || !sessionId || !workoutSetId) throw new Error("Raw set is missing required id / saved_workout_id / workout_set_id.");
1094
+ const unit = typeof rawSet.unit === "string" ? rawSet.unit : "";
1095
+ return {
1096
+ id,
1097
+ sessionId,
1098
+ workoutSetId,
1099
+ completed: complete ? "1" : "0",
1100
+ rx: coerceInt(rawSet.rx) ?? 0,
1101
+ version: coerceInt(rawSet.version) ?? 0,
1102
+ isMetric: unit.toLowerCase() === "kg",
1103
+ isSuperSet: rawSet.is_super_set === 1 || rawSet.is_super_set === true,
1104
+ isPlainText: rawSet.plain_text === 1 || rawSet.plain_text === true,
1105
+ title: typeof rawSet.title === "string" ? rawSet.title : "",
1106
+ instruction: typeof rawSet.instruction === "string" ? rawSet.instruction : "",
1107
+ notes: rawSet.notes ?? null,
1108
+ exercises: [...exerciseIds]
1109
+ };
1110
+ }
1111
+ /**
1112
+ * Record entered set results for one saved workout set.
1113
+ *
1114
+ * **Two-step write (both required for data to persist):**
1115
+ * 1. For each exercise in `results`:
1116
+ * `PUT /1.0/athlete/savedworkoutsetexercise/{savedWorkoutSetExerciseId}` with the
1117
+ * per-slot `param_N_data_M` values. This is the only path that actually stores reps
1118
+ * and weight — the `savedworkoutset` PUT accepts the same fields but silently discards
1119
+ * them.
1120
+ * 2. `PUT /1.0/athlete/savedworkoutset/{savedWorkoutSetId}` with `completed:"1"` to
1121
+ * mark the block done and make the entry visible as a logged set in history.
1122
+ *
1123
+ * The date is used to locate the saved workout (via the range endpoint) so we can resolve
1124
+ * `saved_workout_id` and `workout_set_exercise_id` for each exercise. Both are required
1125
+ * by the respective PUT bodies.
1126
+ */
1127
+ async function logAthleteSet(client, args) {
1128
+ return writeSetResults(client, { role: "athlete" }, await fetchAthleteWorkouts(client, args.date, args.date), args.savedWorkoutSetId, args.results);
1129
+ }
1130
+ /**
1131
+ * Coach "Log for Athlete": record set results for a roster athlete on their behalf, via the
1132
+ * coach surface — `PUT /1.0/coach/savedworkoutsetexercise/{id}/{athleteId}` (the data write)
1133
+ * then `PUT /1.0/coach/savedworkoutset/{id}/{athleteId}` (mark complete). Same two-step
1134
+ * contract as {@link logAthleteSet}; the bodies are identical except each is stamped with
1135
+ * `athleteId`. The day is located through the coach range endpoint for that athlete.
1136
+ *
1137
+ * NOTE: TrainHeroic's seeded *demo* athletes are read-only for results and return 401 on the
1138
+ * data-write step; real (invited) athletes accept it.
1139
+ */
1140
+ async function logForAthlete(client, args) {
1141
+ const workouts = await fetchCoachAthleteWorkouts(client, args.athleteId, args.date, args.date);
1142
+ return writeSetResults(client, {
1143
+ role: "coach",
1144
+ athleteId: args.athleteId
1145
+ }, workouts, args.savedWorkoutSetId, args.results);
1146
+ }
1147
+ /**
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).
1154
+ */
1155
+ async function writeSetResults(client, target, workouts, savedWorkoutSetId, results) {
1156
+ const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
1157
+ const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
1158
+ const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
1159
+ let exercisesLogged = 0;
1160
+ for (const result of results) {
1161
+ const ex = exercises.find((e) => coerceInt(e.id) === result.savedWorkoutSetExerciseId);
1162
+ if (!ex) {
1163
+ const valid = exercises.map((e) => {
1164
+ const id = coerceInt(e.id);
1165
+ const title = typeof e.exercise_title === "string" && e.exercise_title || typeof e.title === "string" && e.title || "exercise";
1166
+ return id === null ? null : `${id} (${title})`;
1167
+ }).filter((x) => x !== null);
1168
+ throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
1169
+ }
1170
+ const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
1171
+ if (!workoutSetExerciseId) throw new Error(`Could not resolve workout_set_exercise_id for exercise ${result.savedWorkoutSetExerciseId}.`);
1172
+ const body = {
1173
+ ...buildExerciseLogPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets),
1174
+ ...extra
1175
+ };
1176
+ const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
1177
+ 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}`);
1180
+ }
1181
+ exercisesLogged += 1;
1182
+ }
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
+ return {
1190
+ savedWorkoutSetId,
1191
+ exercisesLogged
1192
+ };
1193
+ }
1194
+ /**
1195
+ * POST /v5/programWorkouts/personal — create a personal workout session for a given date.
1196
+ * Returns the key ids: workoutId (needed for addExercisesToWorkout), programWorkoutId,
1197
+ * savedWorkoutId, and groupId.
1198
+ */
1199
+ async function createPersonalWorkout(client, date) {
1200
+ const res = await client.request("POST", "/v5/programWorkouts/personal", { body: { date } });
1201
+ if (!res.ok) throw new Error(`Create personal workout failed (HTTP ${res.status}).`);
1202
+ if (!isRecord(res.data)) throw new Error("Unexpected response from /v5/programWorkouts/personal.");
1203
+ const pw = isRecord(res.data.programWorkout) ? res.data.programWorkout : null;
1204
+ const sw = isRecord(res.data.savedWorkout) ? res.data.savedWorkout : null;
1205
+ if (!pw || !sw) throw new Error("Missing programWorkout or savedWorkout in response.");
1206
+ const programWorkoutId = coerceInt(pw.id);
1207
+ const workoutId = coerceInt(pw.workoutId);
1208
+ const savedWorkoutId = coerceInt(sw.id);
1209
+ const groupId = coerceInt(sw.group_id);
1210
+ if (!programWorkoutId || !workoutId || !savedWorkoutId || !groupId) throw new Error("Could not parse required ids from personal workout response.");
1211
+ return {
1212
+ programWorkoutId,
1213
+ workoutId,
1214
+ savedWorkoutId,
1215
+ groupId,
1216
+ date: typeof pw.date === "string" ? pw.date : date
1217
+ };
1218
+ }
1219
+ /**
1220
+ * PUT /v5/personalCalendar/workouts/{workoutId}/addExercises — add exercises to a personal
1221
+ * workout. Returns saved workout set objects: each top-level `id` is a savedWorkoutSetId
1222
+ * and `savedWorkoutSetExercises[].id` is a savedWorkoutSetExerciseId, both needed by
1223
+ * logAthleteSet.
1224
+ */
1225
+ async function addExercisesToWorkout(client, workoutId, exercises) {
1226
+ const res = await client.request("PUT", `/v5/personalCalendar/workouts/${workoutId}/addExercises`, { body: {
1227
+ exercises,
1228
+ circuits: []
1229
+ } });
1230
+ if (!res.ok) throw new Error(`Add exercises to workout failed (HTTP ${res.status}).`);
1231
+ return res.data;
1232
+ }
1233
+ /**
1234
+ * Find a personal-calendar session already on the given day. The range marks these with
1235
+ * `personal_cal === true`; the addable id is the program workout's `workout_id`. Returns the
1236
+ * first one's workoutId, or null when the day has no personal session.
1237
+ */
1238
+ function findPersonalSessionWorkoutId(workouts) {
1239
+ for (const pw of workouts) {
1240
+ const rec = pw;
1241
+ if (rec.personal_cal === true) {
1242
+ const workoutId = coerceInt(rec.workout_id);
1243
+ if (workoutId !== null) return workoutId;
1244
+ }
1245
+ }
1246
+ return null;
1247
+ }
1248
+ /**
1249
+ * Map the `addExercisesToWorkout` response (an array of saved sets) to per-exercise saved ids.
1250
+ * Each set's `id` is a savedWorkoutSetId; each `savedWorkoutSetExercises[].id` is a
1251
+ * savedWorkoutSetExerciseId and `.exerciseId` is the catalog exercise id that was added.
1252
+ */
1253
+ function indexAddedExercises(added) {
1254
+ const out = [];
1255
+ const sets = Array.isArray(added) ? added : [];
1256
+ for (const s of sets) {
1257
+ if (!isRecord(s)) continue;
1258
+ const savedWorkoutSetId = coerceInt(s.id);
1259
+ if (savedWorkoutSetId === null) continue;
1260
+ const exercises = Array.isArray(s.savedWorkoutSetExercises) ? s.savedWorkoutSetExercises : [];
1261
+ for (const ex of exercises) {
1262
+ if (!isRecord(ex)) continue;
1263
+ const savedWorkoutSetExerciseId = coerceInt(ex.id);
1264
+ const exerciseId = coerceInt(ex.exerciseId ?? ex.exercise_id);
1265
+ if (savedWorkoutSetExerciseId === null || exerciseId === null) continue;
1266
+ out.push({
1267
+ exerciseId,
1268
+ savedWorkoutSetId,
1269
+ savedWorkoutSetExerciseId
1270
+ });
1271
+ }
1272
+ }
1273
+ return out;
1274
+ }
1275
+ /** Flatten a day's prescribed saved sets into `{ savedWorkoutSetId, ex }` rows (both set keys). */
1276
+ function eachPrescribedExercise(workouts) {
1277
+ const rows = [];
1278
+ for (const pw of workouts) {
1279
+ const rec = pw;
1280
+ const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
1281
+ const sw = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
1282
+ if (!sw) continue;
1283
+ const sets = [...Array.isArray(sw.workoutSets) ? sw.workoutSets : [], ...Array.isArray(sw.addedWorkoutSets) ? sw.addedWorkoutSets : []];
1284
+ for (const s of sets) {
1285
+ if (!isRecord(s)) continue;
1286
+ const savedWorkoutSetId = coerceInt(s.id);
1287
+ if (savedWorkoutSetId === null) continue;
1288
+ const exercises = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
1289
+ for (const ex of exercises) if (isRecord(ex)) rows.push({
1290
+ savedWorkoutSetId,
1291
+ ex
1292
+ });
1293
+ }
1294
+ }
1295
+ return rows;
1296
+ }
1297
+ /**
1298
+ * Locate a single prescribed exercise on the given day's workouts, returning the saved set it
1299
+ * belongs to and its saved-set-exercise id. Used by the coach path, which can only log against
1300
+ * what is already on the athlete's calendar. Returns null when the exercise is not prescribed
1301
+ * that day.
1302
+ */
1303
+ function findPrescribedExercise(workouts, exerciseId, used) {
1304
+ for (const { savedWorkoutSetId, ex } of eachPrescribedExercise(workouts)) {
1305
+ const sweId = coerceInt(ex.id);
1306
+ if (sweId === null || used.has(sweId)) continue;
1307
+ if (coerceInt(ex.exercise_id) === exerciseId) return {
1308
+ savedWorkoutSetId,
1309
+ savedWorkoutSetExerciseId: sweId
1310
+ };
1311
+ }
1312
+ return null;
1313
+ }
1314
+ /** List the prescribed exercises on a day as `id (title)` labels, for not-found errors. */
1315
+ function prescribedExerciseLabels(workouts) {
1316
+ const labels = [];
1317
+ for (const { ex } of eachPrescribedExercise(workouts)) {
1318
+ const id = coerceInt(ex.exercise_id);
1319
+ if (id === null) continue;
1320
+ const title = typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || "exercise";
1321
+ labels.push(`${id} (${title})`);
1322
+ }
1323
+ return labels;
1324
+ }
1325
+ /** Group resolved exercises by saved set and write each set via the given log target. */
1326
+ async function logResolvedExercises(client, target, date, resolved) {
1327
+ const bySet = /* @__PURE__ */ new Map();
1328
+ for (const r of resolved) {
1329
+ const list = bySet.get(r.savedWorkoutSetId) ?? [];
1330
+ list.push({
1331
+ savedWorkoutSetExerciseId: r.savedWorkoutSetExerciseId,
1332
+ sets: [...r.sets]
1333
+ });
1334
+ bySet.set(r.savedWorkoutSetId, list);
1335
+ }
1336
+ const out = [];
1337
+ for (const [savedWorkoutSetId, results] of bySet) {
1338
+ const written = target.role === "coach" ? await logForAthlete(client, {
1339
+ athleteId: target.athleteId,
1340
+ date,
1341
+ savedWorkoutSetId,
1342
+ results
1343
+ }) : await logAthleteSet(client, {
1344
+ date,
1345
+ savedWorkoutSetId,
1346
+ results
1347
+ });
1348
+ out.push(written);
1349
+ }
1350
+ return out;
1351
+ }
1352
+ /**
1353
+ * Log a whole session for the logged-in athlete by exercise, with no pre-existing prescription
1354
+ * required. Reuses a personal session already on the date when one exists (the API marks these
1355
+ * `personal_cal`), otherwise creates one; then adds the exercises and logs their entered sets.
1356
+ * This is the "log whatever I just did" path — extra accessory work, a makeup lift, an off-plan
1357
+ * gym session.
1358
+ */
1359
+ async function logAdHocSession(client, args) {
1360
+ if (args.exercises.length === 0) throw new Error("Provide at least one exercise to log.");
1361
+ const existing = findPersonalSessionWorkoutId(await fetchAthleteWorkouts(client, args.date, args.date));
1362
+ const created = existing === null;
1363
+ const workoutId = existing ?? (await createPersonalWorkout(client, args.date)).workoutId;
1364
+ const withOrder = args.exercises.map((e, i) => ({
1365
+ ...e,
1366
+ order: e.order ?? i + 1
1367
+ }));
1368
+ const index = indexAddedExercises(await addExercisesToWorkout(client, workoutId, withOrder.map((e) => ({
1369
+ exerciseId: e.exerciseId,
1370
+ order: e.order
1371
+ }))));
1372
+ const consumed = /* @__PURE__ */ new Set();
1373
+ const resolved = withOrder.map((e) => {
1374
+ const hit = index.find((m) => m.exerciseId === e.exerciseId && !consumed.has(m.savedWorkoutSetExerciseId));
1375
+ if (!hit) throw new Error(`Could not place exercise ${e.exerciseId} into the session after adding it. The add-exercises response did not return a saved set for it.`);
1376
+ consumed.add(hit.savedWorkoutSetExerciseId);
1377
+ return {
1378
+ exerciseId: e.exerciseId,
1379
+ savedWorkoutSetId: hit.savedWorkoutSetId,
1380
+ savedWorkoutSetExerciseId: hit.savedWorkoutSetExerciseId,
1381
+ sets: e.sets
1382
+ };
1383
+ });
1384
+ const sets = await logResolvedExercises(client, { role: "athlete" }, args.date, resolved);
1385
+ return {
1386
+ date: args.date,
1387
+ created,
1388
+ sets
1389
+ };
1390
+ }
1391
+ /**
1392
+ * Coach "log a session for a roster athlete" by exercise. The API offers no way to put an
1393
+ * off-plan session on another user's calendar (the personal-calendar endpoints are self-scoped),
1394
+ * so this logs against the session the athlete already has on that date: each requested exercise
1395
+ * is resolved to a prescribed saved set and its results are written via the coach "Log for
1396
+ * Athlete" surface. Throws a readable error naming the prescribed exercises when one is missing.
1397
+ */
1398
+ async function logSessionForAthlete(client, args) {
1399
+ if (args.exercises.length === 0) throw new Error("Provide at least one exercise to log.");
1400
+ const day = await fetchCoachAthleteWorkouts(client, args.athleteId, args.date, args.date);
1401
+ const used = /* @__PURE__ */ new Set();
1402
+ const resolved = args.exercises.map((e) => {
1403
+ const hit = findPrescribedExercise(day, e.exerciseId, used);
1404
+ if (!hit) {
1405
+ const labels = prescribedExerciseLabels(day);
1406
+ const present = labels.length > 0 ? `Prescribed on ${args.date}: ${labels.join(", ")}.` : `Nothing is prescribed for athlete ${args.athleteId} on ${args.date}.`;
1407
+ throw new Error(`Exercise ${e.exerciseId} is not on athlete ${args.athleteId}'s calendar for ${args.date}, so there is no set to log it against. ${present} A coach can only log against an existing session; build/publish a session for the athlete first if it is missing.`);
1408
+ }
1409
+ used.add(hit.savedWorkoutSetExerciseId);
1410
+ return {
1411
+ exerciseId: e.exerciseId,
1412
+ ...hit,
1413
+ sets: e.sets
1414
+ };
1415
+ });
1416
+ const sets = await logResolvedExercises(client, {
1417
+ role: "coach",
1418
+ athleteId: args.athleteId
1419
+ }, args.date, resolved);
1420
+ return {
1421
+ date: args.date,
1422
+ created: false,
1423
+ sets
1424
+ };
1425
+ }
1426
+ /** Flatten `/v5/exercises/{id}/history` into PRs + a session time-series. */
1427
+ function presentExerciseHistory(detail) {
1428
+ return {
1429
+ liftPRs: (detail.liftPRs ?? []).map((p) => ({
1430
+ description: p.description ?? null,
1431
+ reps: p.reps ?? null,
1432
+ weight: p.weight ?? null,
1433
+ date: p.dateCompleted ?? null
1434
+ })),
1435
+ sessions: (detail.history ?? []).map((h) => ({
1436
+ date: h.dateCompleted,
1437
+ abr: h.abr ?? null,
1438
+ estimated1RM: h.bestEstimated1RM ?? null,
1439
+ sets: (h.sets ?? []).map((s) => ({
1440
+ setNumber: s.setNumber,
1441
+ value: s.formattedValue ?? null
1442
+ }))
1443
+ }))
1444
+ };
1445
+ }
1446
+ /** Normalize one-or-many emails into a deduped, trimmed list. */
1447
+ function emailList(emails) {
1448
+ return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
1449
+ }
1450
+ /**
1451
+ * Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
1452
+ * addresses (`POST /v5/emails/validate`), then invite the validated ones
1453
+ * (`POST /v5/athletes/inviteToTeam`). Throws with the API detail on failure.
1454
+ */
1455
+ async function inviteAthletes(client, args) {
1456
+ const list = emailList(args.emails);
1457
+ if (list.length === 0) throw new Error("Provide at least one email address to invite.");
1458
+ const validation = await client.request("POST", "/v5/emails/validate", { body: { emails: list.join(",") } });
1459
+ if (!validation.ok) {
1460
+ const detail = typeof validation.data === "string" ? validation.data : JSON.stringify(validation.data);
1461
+ throw new Error(`Email validation failed (HTTP ${validation.status}): ${detail}`);
1462
+ }
1463
+ const valid = Array.isArray(validation.data) ? validation.data : list;
1464
+ if (valid.length === 0) throw new Error(`No valid addresses among: ${list.join(", ")}. They may be malformed or already on the team.`);
1465
+ const invite = await client.request("POST", "/v5/athletes/inviteToTeam", { body: {
1466
+ teamType: 0,
1467
+ teamId: args.teamId,
1468
+ orgId: null,
1469
+ emails: valid,
1470
+ message: args.message ?? "Follow these steps and you'll be set up and ready to go!"
1471
+ } });
1472
+ if (!invite.ok) {
1473
+ const detail = typeof invite.data === "string" ? invite.data : JSON.stringify(invite.data);
1474
+ throw new Error(`Invite failed (HTTP ${invite.status}): ${detail}`);
1475
+ }
1476
+ return {
1477
+ teamId: args.teamId,
1478
+ invited: valid,
1479
+ result: invite.data
1480
+ };
1481
+ }
1482
+ /**
1483
+ * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
1484
+ * The API wants the target date as a structured object (with weekday and an isToday flag),
1485
+ * which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
1486
+ */
1487
+ async function copySession(client, args) {
1488
+ const [year, month, day] = parseWorkoutDate(args.toDate);
1489
+ const dayOfWeek = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
1490
+ const iso = `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
1491
+ const res = await client.request("POST", "/2.0/coach/calendar/copyProgramWorkout", { body: {
1492
+ toProgramId: args.toProgramId,
1493
+ pwId: args.pwId,
1494
+ toDate: {
1495
+ date: iso,
1496
+ day,
1497
+ month,
1498
+ year,
1499
+ dayOfWeek,
1500
+ isToday: false
1501
+ }
1502
+ } });
1503
+ if (!res.ok) throw new Error(`Copy session failed (HTTP ${res.status}).`);
1504
+ return res.data;
1505
+ }
1506
+ const ANALYTICS_METRIC_KEYS = [
1507
+ "readiness-team",
1508
+ "readiness-athlete",
1509
+ "lift-1rm-history",
1510
+ "training-summary-athlete",
1511
+ "compliance-team",
1512
+ "lift-progress-team",
1513
+ "working-max-history"
1514
+ ];
1515
+ const ANALYTICS_METRICS = {
1516
+ "readiness-team": {
1517
+ path: "/v5/analytics/readiness/teams",
1518
+ scope: "team",
1519
+ inputs: ["date"],
1520
+ requires: ["date"]
1521
+ },
1522
+ "readiness-athlete": {
1523
+ path: "/v5/analytics/readiness/users",
1524
+ scope: "user",
1525
+ inputs: ["dateStart", "dateEnd"],
1526
+ requires: ["dateStart", "dateEnd"]
1527
+ },
1528
+ "lift-1rm-history": {
1529
+ path: "/v5/analytics/lift-one-rep-max-history/users",
1530
+ scope: "user",
1531
+ inputs: [
1532
+ "dateStart",
1533
+ "dateEnd",
1534
+ "exerciseId",
1535
+ "useMetric"
1536
+ ],
1537
+ requires: [
1538
+ "dateStart",
1539
+ "dateEnd",
1540
+ "exerciseId"
1541
+ ]
1542
+ },
1543
+ "training-summary-athlete": {
1544
+ path: "/v5/analytics/training-summary/users",
1545
+ scope: "user",
1546
+ inputs: ["dateStart", "dateEnd"],
1547
+ requires: ["dateStart", "dateEnd"]
1548
+ },
1549
+ "compliance-team": {
1550
+ path: "/v5/analytics/compliance",
1551
+ scope: "team",
1552
+ inputs: ["dateStart", "dateEnd"],
1553
+ requires: ["dateStart", "dateEnd"]
1554
+ },
1555
+ "lift-progress-team": {
1556
+ path: "/v5/analytics/lift-progress/teams",
1557
+ scope: "team",
1558
+ inputs: [
1559
+ "exerciseId",
1560
+ "dateStart",
1561
+ "dateEnd"
1562
+ ],
1563
+ requires: [
1564
+ "exerciseId",
1565
+ "dateStart",
1566
+ "dateEnd"
1567
+ ]
1568
+ },
1569
+ "working-max-history": {
1570
+ path: "/v5/analytics/working-max-history/users",
1571
+ scope: "user",
1572
+ inputs: [
1573
+ "exerciseId",
1574
+ "dateStart",
1575
+ "dateEnd",
1576
+ "useMetric"
1577
+ ],
1578
+ requires: ["exerciseId"]
1579
+ }
1580
+ };
1581
+ /**
1582
+ * A serializable description of every analytics metric: its scope (does it need a `teamId` or
1583
+ * `userIds`) and which date/exercise inputs it requires vs. optionally accepts. The CLI/MCP
1584
+ * surface this so an agent picks a valid `metric` + params up front, instead of discovering the
1585
+ * shape by trial and error. These curated keys are deliberately NOT the raw category names from
1586
+ * `GET /v5/analytics`; this catalog is the source of truth for `analytics-query`.
1587
+ */
1588
+ function analyticsMetricCatalog() {
1589
+ return ANALYTICS_METRIC_KEYS.map((metric) => {
1590
+ const spec = ANALYTICS_METRICS[metric];
1591
+ return {
1592
+ metric,
1593
+ scope: spec.scope,
1594
+ scopeParam: spec.scope === "team" ? "teamId" : "userIds",
1595
+ requires: [...spec.requires],
1596
+ optional: spec.inputs.filter((i) => !spec.requires.includes(i))
1597
+ };
1598
+ });
1599
+ }
1600
+ const ANALYTICS_BODY_KEY = {
1601
+ date: "date",
1602
+ dateStart: "date_start",
1603
+ dateEnd: "date_end",
1604
+ exerciseId: "exercise_id",
1605
+ useMetric: "use_metric"
1606
+ };
1607
+ /**
1608
+ * Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
1609
+ * athlete metrics need one or more `userIds` (passed together — the report returns a row per
1610
+ * athlete). Throws a readable Error when a required input is missing or the call fails.
1611
+ */
1612
+ async function queryAnalytics(client, args) {
1613
+ const spec = ANALYTICS_METRICS[args.metric];
1614
+ const body = {};
1615
+ if (spec.scope === "team") {
1616
+ if (args.teamId === void 0) throw new Error(`${args.metric} needs teamId.`);
1617
+ body.teamId = args.teamId;
1618
+ } else {
1619
+ if (args.userIds === void 0 || args.userIds.length === 0) throw new Error(`${args.metric} needs userIds (one or more athlete ids).`);
1620
+ body.user_ids = args.userIds.map((u) => String(u));
1621
+ }
1622
+ const inputs = {
1623
+ date: args.date,
1624
+ dateStart: args.dateStart,
1625
+ dateEnd: args.dateEnd,
1626
+ exerciseId: args.exerciseId,
1627
+ useMetric: args.useMetric
1628
+ };
1629
+ const missing = spec.requires.filter((k) => inputs[k] === void 0);
1630
+ if (missing.length > 0) throw new Error(`${args.metric} also needs: ${missing.join(", ")}.`);
1631
+ for (const k of spec.inputs) {
1632
+ const v = inputs[k];
1633
+ if (v === void 0) continue;
1634
+ body[ANALYTICS_BODY_KEY[k]] = k === "exerciseId" ? String(v) : v;
1635
+ }
1636
+ const res = await client.request("POST", spec.path, { body });
1637
+ if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
1638
+ return res.data;
1639
+ }
1640
+ /**
1641
+ * Resolve a team's roster to athlete user ids. `/v5/athletes` is the org-wide roster and the only
1642
+ * place per-team membership lives (each row's `groups` holds the team/group ids it belongs to);
1643
+ * there is no per-team roster endpoint. Returns the ids of athletes whose `groups` include the
1644
+ * given id, matched as a string. Throws when the roster fetch fails.
1645
+ */
1646
+ async function fetchTeamAthleteIds(client, teamId) {
1647
+ const res = await client.request("GET", "/v5/athletes");
1648
+ if (!res.ok) throw new Error(`List athletes failed (HTTP ${res.status}).`);
1649
+ const rows = Array.isArray(res.data) ? res.data : [];
1650
+ const want = String(teamId);
1651
+ const ids = [];
1652
+ for (const row of rows) {
1653
+ if (row === null || typeof row !== "object") continue;
1654
+ const rec = row;
1655
+ if (!(Array.isArray(rec.groups) ? rec.groups.map((g) => String(g)) : []).includes(want)) continue;
1656
+ const id = typeof rec.id === "string" ? Number(rec.id) : rec.id;
1657
+ if (typeof id === "number" && Number.isFinite(id)) ids.push(id);
1658
+ }
1659
+ return ids;
1660
+ }
1661
+ function toNum(v) {
1662
+ const n = typeof v === "string" ? Number(v) : typeof v === "number" ? v : NaN;
1663
+ return Number.isFinite(n) ? n : 0;
1664
+ }
1665
+ /**
1666
+ * Team-wide training volume over an inclusive date window. The `training-summary-athlete`
1667
+ * analytics report already returns the team in one call — one row per logged session across all
1668
+ * `athleteIds` — so this fans nothing out: it queries once, groups rows by athlete (summing
1669
+ * volume/reps and counting sessions), and rolls the athletes up into a team total. Athletes who
1670
+ * logged nothing in range simply have no rows and are omitted. The windowed counterpart to the
1671
+ * all-time `fetchRosterActivity` snapshot, which has no date range.
1672
+ */
1673
+ async function teamVolume(client, args) {
1674
+ if (args.athleteIds.length === 0) throw new Error("teamVolume needs at least one athleteId.");
1675
+ const report = await queryAnalytics(client, {
1676
+ metric: "training-summary-athlete",
1677
+ userIds: args.athleteIds,
1678
+ dateStart: args.dateStart,
1679
+ dateEnd: args.dateEnd
1680
+ });
1681
+ const rows = report !== null && typeof report === "object" && Array.isArray(report.rows) ? report.rows : [];
1682
+ const byAthlete = /* @__PURE__ */ new Map();
1683
+ for (const row of rows) {
1684
+ const athleteId = toNum(row.user_id);
1685
+ if (athleteId === 0) continue;
1686
+ const date = typeof row.date_completed === "string" ? row.date_completed.slice(0, 10) : null;
1687
+ const name = [row.name_first, row.name_last].filter((s) => typeof s === "string" && s !== "").join(" ") || null;
1688
+ const existing = byAthlete.get(athleteId);
1689
+ if (existing) {
1690
+ existing.sessions += 1;
1691
+ existing.reps += toNum(row.reps);
1692
+ existing.volume += toNum(row.volume);
1693
+ if (date !== null) {
1694
+ if (existing.firstLoggedDate === null || date < existing.firstLoggedDate) existing.firstLoggedDate = date;
1695
+ if (existing.lastLoggedDate === null || date > existing.lastLoggedDate) existing.lastLoggedDate = date;
1696
+ }
1697
+ } else byAthlete.set(athleteId, {
1698
+ athleteId,
1699
+ name,
1700
+ sessions: 1,
1701
+ reps: toNum(row.reps),
1702
+ volume: toNum(row.volume),
1703
+ firstLoggedDate: date,
1704
+ lastLoggedDate: date
1705
+ });
1706
+ }
1707
+ const athletes = [...byAthlete.values()].sort((a, b) => b.volume - a.volume);
1708
+ const totals = athletes.reduce((acc, a) => ({
1709
+ athletes: acc.athletes + 1,
1710
+ sessions: acc.sessions + a.sessions,
1711
+ reps: acc.reps + a.reps,
1712
+ volume: acc.volume + a.volume
1713
+ }), {
1714
+ athletes: 0,
1715
+ sessions: 0,
1716
+ reps: 0,
1717
+ volume: 0
1718
+ });
1719
+ return {
1720
+ window: {
1721
+ start: args.dateStart,
1722
+ end: args.dateEnd
1723
+ },
1724
+ athletes,
1725
+ totals
1726
+ };
1727
+ }
1728
+ //#endregion
1729
+ //#region ../js/src/util.ts
1730
+ /**
1731
+ * Drop the keys whose value is `undefined`, so the result can be passed to a function or
1732
+ * spread into an object under `exactOptionalPropertyTypes` without the per-key
1733
+ * `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
1734
+ * optional ones lose `undefined` from their value type.
1735
+ *
1736
+ * Example:
1737
+ * definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
1738
+ */
1739
+ function definedProps(obj) {
1740
+ const result = {};
1741
+ for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
1742
+ return result;
1743
+ }
347
1744
  //#endregion
348
1745
  //#region ../js/src/workout-encode.ts
349
1746
  const LEADERBOARD_TYPE = {
@@ -831,10 +2228,7 @@ var ExerciseLibrary = class {
831
2228
  await this.ensureFresh();
832
2229
  const s = this.#byId.get(id);
833
2230
  if (!s) return null;
834
- const full = { ...s.raw };
835
- full.param_1_unit = unitLabel(full.param_1_type);
836
- full.param_2_unit = unitLabel(full.param_2_type);
837
- return full;
2231
+ return presentExercise$1(s.raw);
838
2232
  }
839
2233
  async defaults(id) {
840
2234
  const s = this.#byId.get(id);
@@ -970,33 +2364,98 @@ async function saveSession(sessionId) {
970
2364
  const HELP = `trainheroic — command-line tool for the TrainHeroic coaching API
971
2365
 
972
2366
  Credentials come from TRAINHEROIC_EMAIL and TRAINHEROIC_PASSWORD. Output is JSON.
2367
+ Coaching commands live under 'coach'; your own training lives under 'athlete'.
973
2368
 
974
- Reads:
975
- whoami | head-coach | athletes | programs | teams | notifications | analytics
976
- program <id> | team <id> | team-codes <id>
977
- request <METHOD> <path> [json] [--base coach|apis] [--file f] raw API call
2369
+ Start here (for AI agents):
2370
+ trainheroic skill full workflow guide + copy-paste examples (esp. workout specs)
2371
+ trainheroic skill --full also print the API + workout-creation reference docs
2372
+ trainheroic skill list list the available guides (coach, athlete)
978
2373
 
979
- Exercises (cached at ~/.trainheroic/library.json):
980
- exercise resolve <name>
981
- exercise search <query> [--limit N]
982
- exercise get <id>
983
- exercise sync [--force]
984
- exercise create <json>|--file f
985
- exercise forget <id> --yes
986
- exercise stats
2374
+ Setup:
2375
+ install-skill copy the Claude Code skills to ~/.claude/skills/
987
2376
 
988
- Workouts:
989
- workout build --program <id> (--date Y-M-D | --timeline-day <n>) [--publish --yes] <spec.json>|--file f
990
- workout read --program <id> --date Y-M-D --pw <id>
991
- workout publish --pw <id> --yes
992
- workout remove --program <id> --pw <id> --yes
2377
+ Shared:
2378
+ whoami the logged-in account
2379
+ request <METHOD> <path> [json] [--base coach|apis] [--file f] raw API call (--base defaults to coach)
993
2380
 
994
- Messaging:
995
- message list
996
- message read <streamId> [--limit N]
997
- message draft <streamId> <text> [--reply-to <id>]
998
- message send <streamId> <text> [--reply-to <id>] --yes
999
- message delete <streamId> <commentId> --yes
2381
+ Coach — manage a roster (needs a coach account):
2382
+ coach head-coach | athletes | programs | teams | notifications | analytics
2383
+ coach program <id> | team <id> | team-codes <id>
2384
+
2385
+ roster athlete reads (three lenses — pick by the question):
2386
+ coach roster-activity --athletes <id,id,...> [--metric] rank roster by recency; --metric adds session count + training volume. All-time snapshot, NO date range — for a windowed total use 'coach team-volume'. Get the full id list from 'coach athletes'.
2387
+ coach team-volume (--team <id> | --athletes <id,id,...>) --start Y-M-D --end Y-M-D team training volume scoped to a date window: per-athlete rows (only those who logged in range) + rolled-up totals (volume in lb). --team resolves the roster; --athletes passes ids directly.
2388
+ 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
+ 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
+ coach athlete-lift-history --athlete <id> --exercise <id> [--since Y-M-D] [--until Y-M-D] [--raw] one exercise's logged history + PRs
2391
+
2392
+ log for an athlete (record their reps/weights; real invited athletes only — demo/seeded ones 401):
2393
+ coach log-set --athlete <id> --date Y-M-D --set <savedWorkoutSetId> <resultsJson>|--file f --yes
2394
+ --date is the workout's SCHEDULED date (not necessarily today); get --set (savedWorkoutSetId)
2395
+ and each result's savedWorkoutSetExerciseId from 'coach athlete-workouts ... --log-ids'
2396
+ coach log-session --athlete <id> --date Y-M-D <exercisesJson>|--file f --yes
2397
+ log by exercise instead of by set id: each exercise (exerciseId + sets) is matched to a set
2398
+ already on the athlete's calendar that day. The API can't put an off-plan session on an
2399
+ athlete's calendar, so an unprescribed exercise fails (it names what IS prescribed).
2400
+ JSON is the exercises array: [{"exerciseId":N,"sets":[{"param1":reps,"param2":weight}, ...]}, ...]
2401
+
2402
+ roster management:
2403
+ coach athlete-invite --team <id> --emails a@x,b@y [--message "..."] --yes
2404
+ coach athlete-archive --athletes <id,id,...> --yes
2405
+ coach athlete-restore --athletes <id,id,...>
2406
+
2407
+ teams & join codes:
2408
+ coach team-create --title "..."
2409
+ coach team-update --team <id> --title "..."
2410
+ coach team-delete --team <id> --yes
2411
+ coach team-code-create --team <id> [--type N]
2412
+ coach team-code-delete --code <id> --yes (--code is the id from team-code-create, not the join-code number)
2413
+
2414
+ session lifecycle:
2415
+ coach session-copy --to-program <id> --pw <id> --to-date Y-M-D
2416
+ coach session-unpublish --pw <id> --yes
2417
+ coach session-save-template --workout <id>
2418
+
2419
+ analytics (curated metrics; for team training volume/recency use roster-activity --metric instead):
2420
+ coach analytics-query [--metric <key>] [--team <id>] [--users id,id] [--exercise <id>] [--date|--start|--end Y-M-D] [--use-metric]
2421
+ run with no --metric to list the valid keys + each one's scope and required params
2422
+ (these keys are curated and differ from the raw 'coach analytics' categories)
2423
+
2424
+ exercise library (cached at ~/.trainheroic/library.json):
2425
+ coach exercise resolve <name>
2426
+ coach exercise search <query> [--limit N]
2427
+ coach exercise get <id>
2428
+ coach exercise sync [--force]
2429
+ coach exercise create <json>|--file f
2430
+ coach exercise forget <id> --yes
2431
+ coach exercise stats
2432
+
2433
+ workouts (spec: {"blocks":[{"title","exercises":[{"id","sets"?,"reps"?,"weight"?,"rpe"?}]}],"instruction"?};
2434
+ reps/weight may be a scalar or per-set array; omit --publish to leave a draft):
2435
+ coach workout build --program <id> (--date Y-M-D | --timeline-day <n>) [--publish --yes] <spec.json>|--file f
2436
+ coach workout read --program <id> --date Y-M-D --pw <id>
2437
+ coach workout publish --pw <id> --yes
2438
+ coach workout remove --program <id> --pw <id> --yes
2439
+
2440
+ messaging:
2441
+ coach message list
2442
+ coach message read <streamId> [--limit N]
2443
+ coach message draft <streamId> <text> [--reply-to <id>]
2444
+ coach message send <streamId> <text> [--reply-to <id>] --yes
2445
+ coach message delete <streamId> <commentId> --yes
2446
+
2447
+ Athlete — the logged-in user's own training (a coach account works too):
2448
+ athlete whoami | profile [--metric] | prefs | working-maxes
2449
+ athlete workouts --start Y-M-D --end Y-M-D [--raw] [--log-ids] [--logged-only] [--limit N] [--summary] (--log-ids: the savedWorkoutSetId + savedWorkoutSetExerciseId log-set needs)
2450
+ athlete exercises [--q <text>] [--limit N]
2451
+ athlete history <exerciseId> [--raw]
2452
+ athlete prs <exerciseId>
2453
+ athlete stats <exerciseId> --date Y-M-D
2454
+ athlete leaderboard <workoutId> [--page N] [--page-size N] [--gender N]
2455
+ athlete export [--out dir] [--start Y-M-D] [--end Y-M-D] [--full]
2456
+ athlete log-set --date Y-M-D --set <savedWorkoutSetId> <resultsJson>|--file f --yes (logs to a PRESCRIBED workout on that date; ids from 'athlete workouts ... --log-ids')
2457
+ athlete log-session --date Y-M-D <exercisesJson>|--file f --yes (log OFF-PLAN work with no prescription — creates/reuses a personal session for the date, then logs it; exerciseIds from 'athlete exercises')
2458
+ JSON is the exercises array: [{"exerciseId":N,"sets":[{"param1":reps,"param2":weight}, ...]}, ...]
1000
2459
  `;
1001
2460
  function out(value) {
1002
2461
  process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
@@ -1015,9 +2474,9 @@ function toInt(value, label) {
1015
2474
  return n;
1016
2475
  }
1017
2476
  /** Validate input against a dto schema, failing with a readable message on mismatch. */
1018
- function validate(schema, value, label) {
2477
+ function validate(schema, value, label, hint) {
1019
2478
  const result = schema.safeParse(value);
1020
- if (!result.success) fail(`invalid ${label} — ${result.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ")}`);
2479
+ if (!result.success) fail(`invalid ${label} — ${result.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ")}${hint ? `\n${hint}` : ""}`);
1021
2480
  return result.data;
1022
2481
  }
1023
2482
  function parse(args, options) {
@@ -1057,6 +2516,16 @@ async function get(client, path, base) {
1057
2516
  if (!res.ok) fail(`GET ${path} failed (HTTP ${res.status}).`);
1058
2517
  return res.data;
1059
2518
  }
2519
+ /** A thin write request (POST/PUT/DELETE) that fails on a non-2xx and returns the body. */
2520
+ async function mutate(client, method, path, body) {
2521
+ const res = await client.request(method, path, body !== void 0 ? { body } : {});
2522
+ if (!res.ok) fail(`${method} ${path} failed (HTTP ${res.status}).`);
2523
+ return res.data;
2524
+ }
2525
+ /** Parse a comma-separated id list ("1,2,3") into numbers. */
2526
+ function idList(value, label) {
2527
+ return value.split(",").map((s) => toInt(s.trim(), label));
2528
+ }
1060
2529
  function library(client) {
1061
2530
  return new ExerciseLibrary(client, new JsonFileLibraryCache());
1062
2531
  }
@@ -1085,14 +2554,14 @@ async function cmdExercise(client, rest) {
1085
2554
  const [sub, ...a] = rest;
1086
2555
  const lib = library(client);
1087
2556
  switch (sub) {
1088
- case "resolve": return out(await lib.resolve(need(a.join(" ").trim() || void 0, "exercise resolve <name>")));
2557
+ case "resolve": return out(await lib.resolve(need(a.join(" ").trim() || void 0, "coach exercise resolve <name>")));
1089
2558
  case "search": {
1090
2559
  const { values, positionals } = parse(a, { limit: { type: "string" } });
1091
- const query = need(positionals.join(" ").trim() || void 0, "exercise search <query>");
2560
+ const query = need(positionals.join(" ").trim() || void 0, "coach exercise search <query>");
1092
2561
  const limit = values.limit !== void 0 ? toInt(values.limit, "--limit") : 20;
1093
2562
  return out(await lib.search(query, limit));
1094
2563
  }
1095
- case "get": return out(await lib.get(toInt(need(a[0], "exercise get <id>"), "id")));
2564
+ case "get": return out(await lib.get(toInt(need(a[0], "coach exercise get <id>"), "id")));
1096
2565
  case "sync": {
1097
2566
  const { values } = parse(a, { force: { type: "boolean" } });
1098
2567
  if (values.force === true) return out(await lib.refresh());
@@ -1106,13 +2575,13 @@ async function cmdExercise(client, rest) {
1106
2575
  }
1107
2576
  case "forget": {
1108
2577
  const { values, positionals } = parse(a, { yes: { type: "boolean" } });
1109
- const id = toInt(need(positionals[0], "exercise forget <id> --yes"), "id");
2578
+ const id = toInt(need(positionals[0], "coach exercise forget <id> --yes"), "id");
1110
2579
  if (values.yes !== true) fail(`add --yes to forget exercise ${id} from the local cache.`);
1111
2580
  await lib.recordDelete(id);
1112
2581
  return out({ forgotten: id });
1113
2582
  }
1114
2583
  case "stats": return out(await lib.stats());
1115
- default: return fail("usage: trainheroic exercise <resolve|search|get|sync|create|forget|stats>");
2584
+ default: return fail("usage: trainheroic coach exercise <resolve|search|get|sync|create|forget|stats>");
1116
2585
  }
1117
2586
  }
1118
2587
  async function cmdWorkout(client, rest) {
@@ -1127,10 +2596,10 @@ async function cmdWorkout(client, rest) {
1127
2596
  yes: { type: "boolean" },
1128
2597
  file: { type: "string" }
1129
2598
  });
1130
- const programId = toInt(need(values.program, "workout build --program <id> ..."), "--program");
2599
+ const programId = toInt(need(values.program, "coach workout build --program <id> ..."), "--program");
1131
2600
  if (values.date === void 0 && values["timeline-day"] === void 0) fail("provide --date YYYY-M-D or --timeline-day <n>.");
1132
2601
  const parsed = await jsonInput(positionals[0], values.file);
1133
- const spec = validate(workoutSpecSchema, Array.isArray(parsed) ? { blocks: parsed } : parsed, "workout spec");
2602
+ const spec = validate(workoutSpecSchema, Array.isArray(parsed) ? { blocks: parsed } : parsed, "workout spec", "run 'trainheroic skill' for the workout spec format and copy-paste examples.");
1134
2603
  const publish = values.publish === true;
1135
2604
  if (publish && values.yes !== true) fail("publishing is athlete-facing; add --yes to build and publish.");
1136
2605
  const opts = {
@@ -1157,14 +2626,14 @@ async function cmdWorkout(client, rest) {
1157
2626
  date: { type: "string" },
1158
2627
  pw: { type: "string" }
1159
2628
  });
1160
- return out(await readSession(client, toInt(need(values.program, "workout read --program <id> --date Y-M-D --pw <id>"), "--program"), parseWorkoutDate(need(values.date, "workout read --program <id> --date Y-M-D --pw <id>")), toInt(need(values.pw, "workout read --program <id> --date Y-M-D --pw <id>"), "--pw")));
2629
+ return out(await readSession(client, toInt(need(values.program, "coach workout read --program <id> --date Y-M-D --pw <id>"), "--program"), parseWorkoutDate(need(values.date, "coach workout read --program <id> --date Y-M-D --pw <id>")), toInt(need(values.pw, "coach workout read --program <id> --date Y-M-D --pw <id>"), "--pw")));
1161
2630
  }
1162
2631
  case "publish": {
1163
2632
  const { values } = parse(a, {
1164
2633
  pw: { type: "string" },
1165
2634
  yes: { type: "boolean" }
1166
2635
  });
1167
- const pw = toInt(need(values.pw, "workout publish --pw <id> --yes"), "--pw");
2636
+ const pw = toInt(need(values.pw, "coach workout publish --pw <id> --yes"), "--pw");
1168
2637
  if (values.yes !== true) fail(`publishing makes pw ${pw} athlete-visible; add --yes.`);
1169
2638
  await publishSession(client, pw);
1170
2639
  return out({ published: pw });
@@ -1175,13 +2644,13 @@ async function cmdWorkout(client, rest) {
1175
2644
  pw: { type: "string" },
1176
2645
  yes: { type: "boolean" }
1177
2646
  });
1178
- const programId = toInt(need(values.program, "workout remove --program <id> --pw <id> --yes"), "--program");
1179
- const pw = toInt(need(values.pw, "workout remove --program <id> --pw <id> --yes"), "--pw");
2647
+ const programId = toInt(need(values.program, "coach workout remove --program <id> --pw <id> --yes"), "--program");
2648
+ const pw = toInt(need(values.pw, "coach workout remove --program <id> --pw <id> --yes"), "--pw");
1180
2649
  if (values.yes !== true) fail(`removing pw ${pw} deletes the session; add --yes.`);
1181
2650
  await removeSession(client, programId, pw);
1182
2651
  return out({ removed: pw });
1183
2652
  }
1184
- default: return fail("usage: trainheroic workout <build|read|publish|remove>");
2653
+ default: return fail("usage: trainheroic coach workout <build|read|publish|remove>");
1185
2654
  }
1186
2655
  }
1187
2656
  async function cmdMessage(client, rest) {
@@ -1196,14 +2665,14 @@ async function cmdMessage(client, rest) {
1196
2665
  })));
1197
2666
  case "read": {
1198
2667
  const { values, positionals } = parse(a, { limit: { type: "string" } });
1199
- return out(await readLive(client, toInt(need(positionals[0], "message read <streamId> [--limit N]"), "streamId"), values.limit !== void 0 ? toInt(values.limit, "--limit") : 20));
2668
+ return out(await readLive(client, toInt(need(positionals[0], "coach message read <streamId> [--limit N]"), "streamId"), values.limit !== void 0 ? toInt(values.limit, "--limit") : 20));
1200
2669
  }
1201
2670
  case "draft": {
1202
2671
  const { values, positionals } = parse(a, { "reply-to": { type: "string" } });
1203
2672
  return out({
1204
2673
  draft: true,
1205
2674
  note: "NOT sent. Run 'message send' with --yes to deliver.",
1206
- payload: buildCommentPayload(toInt(need(positionals[0], "message draft <streamId> <text>"), "streamId"), need(positionals.slice(1).join(" ").trim() || void 0, "message draft <streamId> <text>"), values["reply-to"] !== void 0 ? toInt(values["reply-to"], "--reply-to") : null)
2675
+ payload: buildCommentPayload(toInt(need(positionals[0], "coach message draft <streamId> <text>"), "streamId"), need(positionals.slice(1).join(" ").trim() || void 0, "coach message draft <streamId> <text>"), values["reply-to"] !== void 0 ? toInt(values["reply-to"], "--reply-to") : null)
1207
2676
  });
1208
2677
  }
1209
2678
  case "send": {
@@ -1211,8 +2680,8 @@ async function cmdMessage(client, rest) {
1211
2680
  "reply-to": { type: "string" },
1212
2681
  yes: { type: "boolean" }
1213
2682
  });
1214
- const streamId = toInt(need(positionals[0], "message send <streamId> <text> --yes"), "streamId");
1215
- const text = need(positionals.slice(1).join(" ").trim() || void 0, "message send <streamId> <text> --yes");
2683
+ const streamId = toInt(need(positionals[0], "coach message send <streamId> <text> --yes"), "streamId");
2684
+ const text = need(positionals.slice(1).join(" ").trim() || void 0, "coach message send <streamId> <text> --yes");
1216
2685
  const replyTo = values["reply-to"] !== void 0 ? toInt(values["reply-to"], "--reply-to") : null;
1217
2686
  if (values.yes !== true) fail(`sending to stream ${streamId} is athlete-facing and immediate; add --yes.`);
1218
2687
  return out({
@@ -1222,33 +2691,585 @@ async function cmdMessage(client, rest) {
1222
2691
  }
1223
2692
  case "delete": {
1224
2693
  const { values, positionals } = parse(a, { yes: { type: "boolean" } });
1225
- const streamId = toInt(need(positionals[0], "message delete <streamId> <commentId> --yes"), "streamId");
1226
- const commentId = toInt(need(positionals[1], "message delete <streamId> <commentId> --yes"), "commentId");
2694
+ const streamId = toInt(need(positionals[0], "coach message delete <streamId> <commentId> --yes"), "streamId");
2695
+ const commentId = toInt(need(positionals[1], "coach message delete <streamId> <commentId> --yes"), "commentId");
1227
2696
  if (values.yes !== true) fail(`deleting comment ${commentId} acts on the live account; add --yes.`);
1228
2697
  return out({
1229
2698
  deleted: true,
1230
2699
  response: await deleteComment(client, streamId, commentId)
1231
2700
  });
1232
2701
  }
1233
- default: return fail("usage: trainheroic message <list|read|draft|send|delete>");
2702
+ default: return fail("usage: trainheroic coach message <list|read|draft|send|delete>");
1234
2703
  }
1235
2704
  }
1236
- async function dispatch(client, group, rest) {
1237
- switch (group) {
2705
+ function isoDate(value, label) {
2706
+ if (!/^\d{4}-\d{2}-\d{2}$/u.test(value)) fail(`${label} must be YYYY-MM-DD, got "${value}".`);
2707
+ return value;
2708
+ }
2709
+ function logErr(msg) {
2710
+ process.stderr.write(`${msg}\n`);
2711
+ }
2712
+ async function cmdAthleteExport(client, a) {
2713
+ const { values } = parse(a, {
2714
+ out: { type: "string" },
2715
+ start: { type: "string" },
2716
+ end: { type: "string" },
2717
+ full: { type: "boolean" }
2718
+ });
2719
+ const dir = values.out ?? join(homedir(), ".trainheroic", "athlete-export");
2720
+ const today = /* @__PURE__ */ new Date();
2721
+ const past = /* @__PURE__ */ new Date();
2722
+ past.setFullYear(past.getFullYear() - 2);
2723
+ const start = values.start !== void 0 ? isoDate(values.start, "--start") : past.toISOString().slice(0, 10);
2724
+ const end = values.end !== void 0 ? isoDate(values.end, "--end") : today.toISOString().slice(0, 10);
2725
+ await mkdir(dir, { recursive: true });
2726
+ const userId = await resolveAthleteUserId(client);
2727
+ logErr(`exporting to ${dir} (user ${userId})`);
2728
+ const [summary, user, prefs, workouts, exercises, workingMaxes] = await Promise.all([
2729
+ fetchAthleteProfileSummary(client, userId),
2730
+ fetchAthleteUser(client, userId),
2731
+ fetchAthletePrefs(client),
2732
+ fetchAthleteWorkouts(client, start, end),
2733
+ fetchExerciseHistoryList(client),
2734
+ fetchWorkingMaxes(client)
2735
+ ]);
2736
+ await writeFile(join(dir, "profile.json"), JSON.stringify({
2737
+ summary,
2738
+ user,
2739
+ prefs
2740
+ }, null, 2));
2741
+ await writeFile(join(dir, "workouts.json"), JSON.stringify(presentAthleteWorkouts(workouts), null, 2));
2742
+ await writeFile(join(dir, "exercises.json"), JSON.stringify(exercises, null, 2));
2743
+ await writeFile(join(dir, "working-maxes.json"), JSON.stringify(workingMaxes, null, 2));
2744
+ let histories = 0;
2745
+ if (values.full === true) {
2746
+ await mkdir(join(dir, "history"), { recursive: true });
2747
+ logErr(`fetching per-exercise history for ${exercises.length} exercises (--full)...`);
2748
+ await mapPool(exercises, 5, async (ex) => {
2749
+ const id = Number(ex.id);
2750
+ const detail = await fetchExerciseHistoryDetail(client, id, userId).catch(() => null);
2751
+ if (detail) {
2752
+ await writeFile(join(dir, "history", `${id}.json`), JSON.stringify(presentExerciseHistory(detail), null, 2));
2753
+ histories += 1;
2754
+ }
2755
+ });
2756
+ }
2757
+ out({
2758
+ exported: dir,
2759
+ range: {
2760
+ start,
2761
+ end
2762
+ },
2763
+ workouts: workouts.length,
2764
+ exercises: exercises.length,
2765
+ workingMaxes: workingMaxes.length,
2766
+ histories: values.full === true ? histories : "skipped (use --full)"
2767
+ });
2768
+ }
2769
+ const LOG_SET_USAGE = "athlete log-set --date Y-M-D --set <id> <resultsJson> --yes";
2770
+ async function cmdAthleteLogSet(client, a) {
2771
+ const { values, positionals } = parse(a, {
2772
+ date: { type: "string" },
2773
+ set: { type: "string" },
2774
+ file: { type: "string" },
2775
+ yes: { type: "boolean" }
2776
+ });
2777
+ const date = isoDate(need(values.date, LOG_SET_USAGE), "--date");
2778
+ const savedWorkoutSetId = toInt(need(values.set, LOG_SET_USAGE), "--set");
2779
+ const args = validate(logSetArgsSchema, {
2780
+ date,
2781
+ savedWorkoutSetId,
2782
+ results: await jsonInput(positionals[0], values.file)
2783
+ }, "log-set args");
2784
+ 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
+ return out(await logAthleteSet(client, {
2795
+ date: args.date,
2796
+ savedWorkoutSetId,
2797
+ results: mapped
2798
+ }));
2799
+ }
2800
+ const LOG_SESSION_USAGE = "athlete log-session --date Y-M-D <exercisesJson>|--file f --yes";
2801
+ /** Map validated logSession exercises to the SDK's SessionExercise[] (ids coerced, slots trimmed). */
2802
+ function toSessionExercises(exercises) {
2803
+ return exercises.map((e) => {
2804
+ const sets = e.sets.map((s) => {
2805
+ const slot = {};
2806
+ if (s.param1 !== void 0) slot.param1 = s.param1;
2807
+ if (s.param2 !== void 0) slot.param2 = s.param2;
2808
+ return slot;
2809
+ });
2810
+ const mapped = {
2811
+ exerciseId: toInt(String(e.exerciseId), "exerciseId"),
2812
+ sets
2813
+ };
2814
+ if (e.order !== void 0) mapped.order = e.order;
2815
+ return mapped;
2816
+ });
2817
+ }
2818
+ async function cmdAthleteLogSession(client, a) {
2819
+ const { values, positionals } = parse(a, {
2820
+ date: { type: "string" },
2821
+ file: { type: "string" },
2822
+ yes: { type: "boolean" }
2823
+ });
2824
+ const date = isoDate(need(values.date, LOG_SESSION_USAGE), "--date");
2825
+ const args = validate(logSessionArgsSchema, {
2826
+ date,
2827
+ exercises: await jsonInput(positionals[0], values.file)
2828
+ }, "log-session args");
2829
+ if (values.yes !== true) fail(`logging a session on ${date} writes to your coach-visible log; add --yes.`);
2830
+ return out(await logAdHocSession(client, {
2831
+ date: args.date,
2832
+ exercises: toSessionExercises(args.exercises)
2833
+ }));
2834
+ }
2835
+ async function cmdAthlete(client, rest) {
2836
+ const [sub, ...a] = rest;
2837
+ switch (sub) {
1238
2838
  case "whoami": return out(await get(client, "/user/simple"));
2839
+ case "profile": {
2840
+ const { values } = parse(a, { metric: { type: "boolean" } });
2841
+ const userId = await resolveAthleteUserId(client);
2842
+ const [summary, user] = await Promise.all([fetchAthleteProfileSummary(client, userId, values.metric === true), fetchAthleteUser(client, userId)]);
2843
+ return out({
2844
+ summary,
2845
+ user
2846
+ });
2847
+ }
2848
+ case "prefs": return out(await fetchAthletePrefs(client));
2849
+ case "workouts": {
2850
+ const { values } = parse(a, {
2851
+ start: { type: "string" },
2852
+ end: { type: "string" },
2853
+ raw: { type: "boolean" },
2854
+ "log-ids": { type: "boolean" },
2855
+ "logged-only": { type: "boolean" },
2856
+ limit: { type: "string" },
2857
+ summary: { type: "boolean" }
2858
+ });
2859
+ const workouts = await fetchAthleteWorkouts(client, isoDate(need(values.start, "athlete workouts --start Y-M-D --end Y-M-D"), "--start"), isoDate(need(values.end, "athlete workouts --start Y-M-D --end Y-M-D"), "--end"));
2860
+ if (values["log-ids"] === true) return out(presentLogTargets(workouts));
2861
+ if (values.raw === true) return out(workouts);
2862
+ const opts = {};
2863
+ if (values["logged-only"] === true) opts.loggedOnly = true;
2864
+ if (values.limit !== void 0) opts.limit = toInt(values.limit, "--limit");
2865
+ const selected = selectWorkouts(presentAthleteWorkouts(workouts), opts);
2866
+ return out(values.summary === true ? summarizeAthleteWorkouts(selected) : selected);
2867
+ }
2868
+ case "exercises": {
2869
+ const { values } = parse(a, {
2870
+ q: { type: "string" },
2871
+ limit: { type: "string" }
2872
+ });
2873
+ const limit = values.limit !== void 0 ? toInt(values.limit, "--limit") : 20;
2874
+ const q = values.q;
2875
+ return out(q !== void 0 ? await searchExerciseHistory(client, q, limit) : await fetchExerciseHistoryList(client));
2876
+ }
2877
+ case "history": {
2878
+ const { values, positionals } = parse(a, { raw: { type: "boolean" } });
2879
+ const detail = await fetchExerciseHistoryDetail(client, toInt(need(positionals[0], "athlete history <exerciseId>"), "exerciseId"), await resolveAthleteUserId(client));
2880
+ return out(values.raw === true ? detail : presentExerciseHistory(detail));
2881
+ }
2882
+ case "prs": return out(await fetchPersonalRecords(client, toInt(need(a[0], "athlete prs <exerciseId>"), "exerciseId")));
2883
+ case "stats": {
2884
+ const { values, positionals } = parse(a, { date: { type: "string" } });
2885
+ const id = toInt(need(positionals[0], "athlete stats <exerciseId> --date Y-M-D"), "exerciseId");
2886
+ const date = isoDate(need(values.date, "athlete stats <exerciseId> --date Y-M-D"), "--date");
2887
+ return out(await fetchExerciseStats(client, id, await resolveAthleteUserId(client), date));
2888
+ }
2889
+ case "working-maxes": return out(await fetchWorkingMaxes(client));
2890
+ case "leaderboard": {
2891
+ const { values, positionals } = parse(a, {
2892
+ page: { type: "string" },
2893
+ "page-size": { type: "string" },
2894
+ gender: { type: "string" }
2895
+ });
2896
+ const workoutId = toInt(need(positionals[0], "athlete leaderboard <workoutId>"), "workoutId");
2897
+ const opts = {};
2898
+ if (values.page !== void 0) opts.page = toInt(values.page, "--page");
2899
+ if (values["page-size"] !== void 0) opts.pageSize = toInt(values["page-size"], "--page-size");
2900
+ if (values.gender !== void 0) opts.gender = toInt(values.gender, "--gender");
2901
+ return out(await fetchLeaderboard(client, workoutId, opts));
2902
+ }
2903
+ case "export": return cmdAthleteExport(client, a);
2904
+ case "log-set": return cmdAthleteLogSet(client, a);
2905
+ case "log-session": return cmdAthleteLogSession(client, a);
2906
+ default: return fail("usage: trainheroic athlete <whoami|profile|prefs|workouts|exercises|history|prs|stats|working-maxes|leaderboard|export|log-set|log-session>");
2907
+ }
2908
+ }
2909
+ async function cmdSkill(rest) {
2910
+ const skillRoot = join(import.meta.dirname, "../skill");
2911
+ const positional = rest.find((r) => !r.startsWith("-"));
2912
+ if (positional === "list") return out((await readdir(skillRoot, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name));
2913
+ const name = positional ?? "trainheroic-unofficial";
2914
+ const dir = join(skillRoot, name);
2915
+ let text;
2916
+ try {
2917
+ text = await readFile(join(dir, "SKILL.md"), "utf8");
2918
+ } catch {
2919
+ return fail(`unknown skill "${name}". Run 'trainheroic skill list'.`);
2920
+ }
2921
+ process.stdout.write(text);
2922
+ if (rest.includes("--full")) try {
2923
+ const refDir = join(dir, "references");
2924
+ const refs = (await readdir(refDir)).filter((f) => f.endsWith(".md")).sort();
2925
+ for (const f of refs) {
2926
+ process.stdout.write(`\n\n===== references/${f} =====\n\n`);
2927
+ process.stdout.write(await readFile(join(refDir, f), "utf8"));
2928
+ }
2929
+ } catch {}
2930
+ }
2931
+ async function cmdInstallSkill() {
2932
+ const home = process.env.HOME ?? process.env.USERPROFILE;
2933
+ if (!home) fail("cannot determine home directory.");
2934
+ const skillRoot = join(import.meta.dirname, "../skill");
2935
+ const skillsDir = join(home, ".claude/skills");
2936
+ await mkdir(skillsDir, { recursive: true });
2937
+ const entries = await readdir(skillRoot, { withFileTypes: true });
2938
+ const installed = [];
2939
+ for (const entry of entries) {
2940
+ if (!entry.isDirectory()) continue;
2941
+ const dest = join(skillsDir, entry.name);
2942
+ await cp(join(skillRoot, entry.name), dest, {
2943
+ recursive: true,
2944
+ force: true
2945
+ });
2946
+ installed.push(dest);
2947
+ }
2948
+ out({ installed });
2949
+ }
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>";
2951
+ const COACH_LOG_SET_USAGE = "coach log-set --athlete <id> --date Y-M-D --set <savedWorkoutSetId> <resultsJson> --yes";
2952
+ async function cmdCoachLogSet(client, a) {
2953
+ const { values, positionals } = parse(a, {
2954
+ athlete: { type: "string" },
2955
+ date: { type: "string" },
2956
+ set: { type: "string" },
2957
+ file: { type: "string" },
2958
+ yes: { type: "boolean" }
2959
+ });
2960
+ const athleteId = toInt(need(values.athlete, COACH_LOG_SET_USAGE), "--athlete");
2961
+ const date = isoDate(need(values.date, COACH_LOG_SET_USAGE), "--date");
2962
+ const savedWorkoutSetId = toInt(need(values.set, COACH_LOG_SET_USAGE), "--set");
2963
+ const args = validate(coachLogSetArgsSchema, {
2964
+ athleteId,
2965
+ date,
2966
+ savedWorkoutSetId,
2967
+ results: await jsonInput(positionals[0], values.file)
2968
+ }, "coach log-set args");
2969
+ 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
+ return out(await logForAthlete(client, {
2980
+ athleteId,
2981
+ date: args.date,
2982
+ savedWorkoutSetId,
2983
+ results: mapped
2984
+ }));
2985
+ }
2986
+ const COACH_LOG_SESSION_USAGE = "coach log-session --athlete <id> --date Y-M-D <exercisesJson>|--file f --yes";
2987
+ async function cmdCoachLogSession(client, a) {
2988
+ const { values, positionals } = parse(a, {
2989
+ athlete: { type: "string" },
2990
+ date: { type: "string" },
2991
+ file: { type: "string" },
2992
+ yes: { type: "boolean" }
2993
+ });
2994
+ const athleteId = toInt(need(values.athlete, COACH_LOG_SESSION_USAGE), "--athlete");
2995
+ const args = validate(coachLogSessionArgsSchema, {
2996
+ athleteId,
2997
+ date: isoDate(need(values.date, COACH_LOG_SESSION_USAGE), "--date"),
2998
+ exercises: await jsonInput(positionals[0], values.file)
2999
+ }, "coach log-session args");
3000
+ if (values.yes !== true) fail(`logging a session for athlete ${athleteId} writes to their training log; add --yes.`);
3001
+ return out(await logSessionForAthlete(client, {
3002
+ athleteId,
3003
+ date: args.date,
3004
+ exercises: toSessionExercises(args.exercises)
3005
+ }));
3006
+ }
3007
+ async function cmdCoachTeamVolume(client, a) {
3008
+ const usage = "coach team-volume (--team <id> | --athletes <id,id,...>) --start Y-M-D --end Y-M-D";
3009
+ const { values } = parse(a, {
3010
+ team: { type: "string" },
3011
+ athletes: { type: "string" },
3012
+ start: { type: "string" },
3013
+ end: { type: "string" }
3014
+ });
3015
+ const dateStart = isoDate(need(values.start, usage), "--start");
3016
+ const dateEnd = isoDate(need(values.end, usage), "--end");
3017
+ const athleteIds = values.athletes !== void 0 ? idList(values.athletes, "--athletes") : await fetchTeamAthleteIds(client, toInt(need(values.team, usage), "--team"));
3018
+ if (athleteIds.length === 0) fail("no athletes resolved — pass --athletes <id,id,...> or a --team whose roster has athletes.");
3019
+ return out(await teamVolume(client, {
3020
+ athleteIds,
3021
+ dateStart,
3022
+ dateEnd
3023
+ }));
3024
+ }
3025
+ async function cmdCoachAthleteWorkouts(client, a) {
3026
+ const usage = "coach athlete-workouts --athlete <id> --start Y-M-D --end Y-M-D [--raw|--log-ids] [--logged-only] [--limit N] [--summary]";
3027
+ const { values } = parse(a, {
3028
+ athlete: { type: "string" },
3029
+ start: { type: "string" },
3030
+ end: { type: "string" },
3031
+ raw: { type: "boolean" },
3032
+ "log-ids": { type: "boolean" },
3033
+ "logged-only": { type: "boolean" },
3034
+ limit: { type: "string" },
3035
+ summary: { type: "boolean" }
3036
+ });
3037
+ const workouts = await fetchCoachAthleteWorkouts(client, toInt(need(values.athlete, usage), "--athlete"), isoDate(need(values.start, usage), "--start"), isoDate(need(values.end, usage), "--end"));
3038
+ if (values["log-ids"] === true) return out(presentLogTargets(workouts));
3039
+ if (values.raw === true) return out(workouts);
3040
+ const opts = {};
3041
+ if (values["logged-only"] === true) opts.loggedOnly = true;
3042
+ if (values.limit !== void 0) opts.limit = toInt(values.limit, "--limit");
3043
+ const selected = selectWorkouts(presentAthleteWorkouts(workouts), opts);
3044
+ return out(values.summary === true ? summarizeAthleteWorkouts(selected) : selected);
3045
+ }
3046
+ async function cmdCoachRosterActivity(client, a) {
3047
+ const usage = "coach roster-activity --athletes <id,id,...> [--metric]";
3048
+ const { values } = parse(a, {
3049
+ athletes: { type: "string" },
3050
+ metric: { type: "boolean" }
3051
+ });
3052
+ return out(await fetchRosterActivity(client, idList(need(values.athletes, usage), "--athletes"), values.metric === true));
3053
+ }
3054
+ async function cmdCoachAthleteInvite(client, a) {
3055
+ const usage = "coach athlete-invite --team <id> --emails a@x,b@y [--message \"...\"] --yes";
3056
+ const { values } = parse(a, {
3057
+ team: { type: "string" },
3058
+ emails: { type: "string" },
3059
+ message: { type: "string" },
3060
+ yes: { type: "boolean" }
3061
+ });
3062
+ const teamId = toInt(need(values.team, usage), "--team");
3063
+ const emails = need(values.emails, usage).split(",").map((e) => e.trim()).filter((e) => e.length > 0);
3064
+ if (values.yes !== true) fail(`inviting ${emails.join(", ")} emails them a real invitation; add --yes.`);
3065
+ return out(await inviteAthletes(client, definedProps({
3066
+ teamId,
3067
+ emails,
3068
+ message: values.message
3069
+ })));
3070
+ }
3071
+ async function cmdCoachAthleteArchive(client, a) {
3072
+ const usage = "coach athlete-archive --athletes <id,id,...> --yes";
3073
+ const { values } = parse(a, {
3074
+ athletes: { type: "string" },
3075
+ yes: { type: "boolean" }
3076
+ });
3077
+ const athleteIds = idList(need(values.athletes, usage), "--athletes");
3078
+ if (values.yes !== true) fail(`archiving athlete(s) ${athleteIds.join(", ")} removes them from the active roster; add --yes.`);
3079
+ return out(await mutate(client, "PUT", "/v5/athletes/archive", { athleteIds }));
3080
+ }
3081
+ async function cmdCoachAthleteRestore(client, a) {
3082
+ const usage = "coach athlete-restore --athletes <id,id,...>";
3083
+ const { values } = parse(a, { athletes: { type: "string" } });
3084
+ return out(await mutate(client, "PUT", "/v5/athletes/restore", { athleteIds: idList(need(values.athletes, usage), "--athletes") }));
3085
+ }
3086
+ async function cmdCoachTeamCreate(client, a) {
3087
+ const { values } = parse(a, { title: { type: "string" } });
3088
+ return out(await mutate(client, "POST", "/1.0/coach/team/createWithTitleAndCode", { title: need(values.title, "coach team-create --title \"...\"") }));
3089
+ }
3090
+ async function cmdCoachTeamUpdate(client, a) {
3091
+ const usage = "coach team-update --team <id> --title \"...\"";
3092
+ const { values } = parse(a, {
3093
+ team: { type: "string" },
3094
+ title: { type: "string" }
3095
+ });
3096
+ const teamId = toInt(need(values.team, usage), "--team");
3097
+ const title = need(values.title, usage);
3098
+ return out(await mutate(client, "PUT", `/v5/teams/${teamId}`, { title }));
3099
+ }
3100
+ async function cmdCoachTeamDelete(client, a) {
3101
+ const usage = "coach team-delete --team <id> --yes";
3102
+ const { values } = parse(a, {
3103
+ team: { type: "string" },
3104
+ yes: { type: "boolean" }
3105
+ });
3106
+ const teamId = toInt(need(values.team, usage), "--team");
3107
+ if (values.yes !== true) fail(`deleting team ${teamId} removes it and its calendar; add --yes.`);
3108
+ return out(await mutate(client, "DELETE", `/v5/teams/${teamId}`));
3109
+ }
3110
+ async function cmdCoachTeamCodeCreate(client, a) {
3111
+ const usage = "coach team-code-create --team <id> [--type N]";
3112
+ const { values } = parse(a, {
3113
+ team: { type: "string" },
3114
+ type: { type: "string" }
3115
+ });
3116
+ const teamId = toInt(need(values.team, usage), "--team");
3117
+ const type = values.type !== void 0 ? toInt(values.type, "--type") : 2;
3118
+ return out(await mutate(client, "POST", `/v5/teams/${teamId}/teamCodes`, { type }));
3119
+ }
3120
+ async function cmdCoachTeamCodeDelete(client, a) {
3121
+ const usage = "coach team-code-delete --code <id> --yes";
3122
+ const { values } = parse(a, {
3123
+ code: { type: "string" },
3124
+ yes: { type: "boolean" }
3125
+ });
3126
+ const codeId = toInt(need(values.code, usage), "--code");
3127
+ if (values.yes !== true) fail(`deleting team code ${codeId} stops athletes joining with it; add --yes.`);
3128
+ return out(await mutate(client, "DELETE", `/v5/teamCodes/${codeId}`));
3129
+ }
3130
+ async function cmdCoachSessionCopy(client, a) {
3131
+ const usage = "coach session-copy --to-program <id> --pw <id> --to-date Y-M-D";
3132
+ const { values } = parse(a, {
3133
+ "to-program": { type: "string" },
3134
+ pw: { type: "string" },
3135
+ "to-date": { type: "string" }
3136
+ });
3137
+ return out(await copySession(client, {
3138
+ toProgramId: toInt(need(values["to-program"], usage), "--to-program"),
3139
+ pwId: toInt(need(values.pw, usage), "--pw"),
3140
+ toDate: need(values["to-date"], usage)
3141
+ }));
3142
+ }
3143
+ async function cmdCoachSessionUnpublish(client, a) {
3144
+ const usage = "coach session-unpublish --pw <id> --yes";
3145
+ const { values } = parse(a, {
3146
+ pw: { type: "string" },
3147
+ yes: { type: "boolean" }
3148
+ });
3149
+ const pwId = toInt(need(values.pw, usage), "--pw");
3150
+ if (values.yes !== true) fail(`unpublishing session ${pwId} hides it from the athlete; add --yes.`);
3151
+ return out(await mutate(client, "POST", `/2.0/coach/calendar/programWorkout/unPublish/${pwId}`));
3152
+ }
3153
+ async function cmdCoachSessionSaveTemplate(client, a) {
3154
+ const usage = "coach session-save-template --workout <id>";
3155
+ const { values } = parse(a, { workout: { type: "string" } });
3156
+ return out(await mutate(client, "POST", `/2.0/coach/calendar/programWorkout/saveWorkoutAsTemplate/${toInt(need(values.workout, usage), "--workout")}`));
3157
+ }
3158
+ async function cmdCoachAnalyticsQuery(client, a) {
3159
+ const { values } = parse(a, {
3160
+ metric: { type: "string" },
3161
+ team: { type: "string" },
3162
+ users: { type: "string" },
3163
+ exercise: { type: "string" },
3164
+ date: { type: "string" },
3165
+ start: { type: "string" },
3166
+ end: { type: "string" },
3167
+ "use-metric": { type: "boolean" }
3168
+ });
3169
+ if (values.metric === void 0) return out({
3170
+ note: "Pick a --metric from this catalog (these keys differ from the raw 'coach analytics' categories). 'requires'/'optional' are the flags each metric takes.",
3171
+ metrics: analyticsMetricCatalog()
3172
+ });
3173
+ const metric = values.metric;
3174
+ if (!ANALYTICS_METRIC_KEYS.includes(metric)) fail(`--metric "${metric}" is not valid. Choose one of: ${ANALYTICS_METRIC_KEYS.join(", ")}. Run 'coach analytics-query' with no --metric for each one's scope and required params.`);
3175
+ return out(await queryAnalytics(client, definedProps({
3176
+ metric,
3177
+ teamId: values.team !== void 0 ? toInt(values.team, "--team") : void 0,
3178
+ userIds: values.users !== void 0 ? idList(values.users, "--users") : void 0,
3179
+ exerciseId: values.exercise !== void 0 ? toInt(values.exercise, "--exercise") : void 0,
3180
+ date: values.date !== void 0 ? isoDate(values.date, "--date") : void 0,
3181
+ dateStart: values.start !== void 0 ? isoDate(values.start, "--start") : void 0,
3182
+ dateEnd: values.end !== void 0 ? isoDate(values.end, "--end") : void 0,
3183
+ useMetric: values["use-metric"] === true ? true : void 0
3184
+ })));
3185
+ }
3186
+ async function cmdCoachAthleteTraining(client, a) {
3187
+ const usage = "coach athlete-training --athlete <id> --year <YYYY> --month <1-12>";
3188
+ const { values } = parse(a, {
3189
+ athlete: { type: "string" },
3190
+ year: { type: "string" },
3191
+ month: { type: "string" }
3192
+ });
3193
+ const athleteId = toInt(need(values.athlete, usage), "--athlete");
3194
+ const year = toInt(need(values.year, usage), "--year");
3195
+ const month = toInt(need(values.month, usage), "--month");
3196
+ const view = presentCoachAthleteTraining(await fetchCoachAthleteCalendarSummary(client, athleteId, year, month), athleteId, year, month);
3197
+ if (view.sessions.length === 0) return out({
3198
+ ...view,
3199
+ note: `No logged sessions for athlete ${athleteId} in ${year}-${String(month).padStart(2, "0")}. This is a per-month view of sessions the athlete actually logged (not prescribed work) — an empty list means nothing was logged that month, not an error. Try another month, or use 'coach athlete-workouts --athlete <id> --start <date> --end <date>' to see prescribed + logged work over a date range.`
3200
+ });
3201
+ return out(view);
3202
+ }
3203
+ async function cmdCoachAthleteLiftHistory(client, a) {
3204
+ const usage = "coach athlete-lift-history --athlete <id> --exercise <id> [--since Y-M-D] [--until Y-M-D] [--raw]";
3205
+ const { values } = parse(a, {
3206
+ athlete: { type: "string" },
3207
+ exercise: { type: "string" },
3208
+ since: { type: "string" },
3209
+ until: { type: "string" },
3210
+ raw: { type: "boolean" }
3211
+ });
3212
+ const athleteId = toInt(need(values.athlete, usage), "--athlete");
3213
+ const exerciseId = toInt(need(values.exercise, usage), "--exercise");
3214
+ const detail = await fetchExerciseHistoryDetail(client, exerciseId, athleteId);
3215
+ if (values.raw === true) return out(detail);
3216
+ const presented = presentExerciseHistory(detail);
3217
+ const since = values.since !== void 0 ? isoDate(values.since, "--since") : void 0;
3218
+ const until = values.until !== void 0 ? isoDate(values.until, "--until") : void 0;
3219
+ const sessions = presented.sessions.filter((s) => (since === void 0 || s.date >= since) && (until === void 0 || s.date <= until));
3220
+ if (sessions.length === 0 && presented.liftPRs.length === 0) return out({
3221
+ ...presented,
3222
+ sessions,
3223
+ note: `No logged history for exercise ${exerciseId} for athlete ${athleteId}${since !== void 0 || until !== void 0 ? " in this date window" : ""}. This view only shows sessions where the athlete logged this exact exercise — an empty result means none were logged, not an error. Confirm the exercise id (via 'coach exercise resolve <name>') and widen --since/--until.`
3224
+ });
3225
+ return out({
3226
+ ...presented,
3227
+ sessions
3228
+ });
3229
+ }
3230
+ async function cmdCoach(client, rest) {
3231
+ const [sub, ...a] = rest;
3232
+ switch (sub) {
1239
3233
  case "head-coach": return out(await get(client, "/v5/headCoach"));
1240
3234
  case "athletes": return out(await get(client, "/v5/athletes"));
1241
3235
  case "programs": return out(await get(client, "/1.0/coach/programs"));
1242
3236
  case "teams": return out(await get(client, "/1.0/coach/teams"));
1243
3237
  case "notifications": return out(await get(client, "/v5/notifications/counts"));
1244
3238
  case "analytics": return out(await get(client, "/v5/analytics"));
1245
- case "program": return out(await get(client, `/3.0/coach/program/${encodeURIComponent(need(rest[0], "program <id>"))}`));
1246
- case "team": return out(await get(client, `/v5/teams/${encodeURIComponent(need(rest[0], "team <id>"))}`));
1247
- case "team-codes": return out(await get(client, `/v5/teams/${encodeURIComponent(need(rest[0], "team-codes <id>"))}/teamCodes`));
3239
+ case "program": return out(await get(client, `/3.0/coach/program/${encodeURIComponent(need(a[0], "coach program <id>"))}`));
3240
+ case "team": return out(await get(client, `/v5/teams/${encodeURIComponent(need(a[0], "coach team <id>"))}`));
3241
+ case "team-codes": return out(await get(client, `/v5/teams/${encodeURIComponent(need(a[0], "coach team-codes <id>"))}/teamCodes`));
3242
+ case "roster-activity": return cmdCoachRosterActivity(client, a);
3243
+ case "team-volume": return cmdCoachTeamVolume(client, a);
3244
+ case "athlete-training": return cmdCoachAthleteTraining(client, a);
3245
+ case "athlete-lift-history": return cmdCoachAthleteLiftHistory(client, a);
3246
+ case "athlete-workouts": return cmdCoachAthleteWorkouts(client, a);
3247
+ case "log-set": return cmdCoachLogSet(client, a);
3248
+ case "log-session": return cmdCoachLogSession(client, a);
3249
+ case "athlete-invite": return cmdCoachAthleteInvite(client, a);
3250
+ case "athlete-archive": return cmdCoachAthleteArchive(client, a);
3251
+ case "athlete-restore": return cmdCoachAthleteRestore(client, a);
3252
+ case "team-create": return cmdCoachTeamCreate(client, a);
3253
+ case "team-update": return cmdCoachTeamUpdate(client, a);
3254
+ case "team-delete": return cmdCoachTeamDelete(client, a);
3255
+ case "team-code-create": return cmdCoachTeamCodeCreate(client, a);
3256
+ case "team-code-delete": return cmdCoachTeamCodeDelete(client, a);
3257
+ case "session-copy": return cmdCoachSessionCopy(client, a);
3258
+ case "session-unpublish": return cmdCoachSessionUnpublish(client, a);
3259
+ case "session-save-template": return cmdCoachSessionSaveTemplate(client, a);
3260
+ case "analytics-query": return cmdCoachAnalyticsQuery(client, a);
3261
+ case "exercise": return cmdExercise(client, a);
3262
+ case "workout": return cmdWorkout(client, a);
3263
+ case "message": return cmdMessage(client, a);
3264
+ default: return fail(COACH_USAGE);
3265
+ }
3266
+ }
3267
+ async function dispatch(client, group, rest) {
3268
+ switch (group) {
3269
+ case "whoami": return out(await get(client, "/user/simple"));
1248
3270
  case "request": return cmdRequest(client, rest);
1249
- case "exercise": return cmdExercise(client, rest);
1250
- case "workout": return cmdWorkout(client, rest);
1251
- case "message": return cmdMessage(client, rest);
3271
+ case "coach": return cmdCoach(client, rest);
3272
+ case "athlete": return cmdAthlete(client, rest);
1252
3273
  default: return fail(`unknown command "${group}". Run 'trainheroic help'.`);
1253
3274
  }
1254
3275
  }
@@ -1258,6 +3279,14 @@ async function main() {
1258
3279
  process.stdout.write(HELP);
1259
3280
  return;
1260
3281
  }
3282
+ if (group === "install-skill") {
3283
+ await cmdInstallSkill();
3284
+ return;
3285
+ }
3286
+ if (group === "skill") {
3287
+ await cmdSkill(rest);
3288
+ return;
3289
+ }
1261
3290
  const email = process.env.TRAINHEROIC_EMAIL;
1262
3291
  const password = process.env.TRAINHEROIC_PASSWORD;
1263
3292
  if (!email || !password) fail("set TRAINHEROIC_EMAIL and TRAINHEROIC_PASSWORD in the environment.");